answer
stringlengths
17
10.2M
package org.valuereporter.observation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; /** * @author <a href="bard.lind@gmail.com">Bard Lind</a> */ public class JdbcReporter { private static final Logger log = LoggerFactory.getLogger(JdbcReporter.class); private JdbcTemplate jdbcTemplate; public JdbcReporter(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } private void report(long timestamp, String prefix, String methodName, Object... values) { try { log.trace("Update for prefix [{}], methodName [{}]", prefix, methodName); int rowsUpdated = insertObservedInterval(prefix, methodName,timestamp, values); if (rowsUpdated < 1) { String updateKeysql = "insert ignore into ObservedKeys (prefix, methodName) values ('" + prefix+ "','" + methodName +"')"; jdbcTemplate.update(updateKeysql); rowsUpdated = insertObservedInterval(prefix, methodName, timestamp, values); } log.trace("Updated {} rows", rowsUpdated); } catch (Exception e) { log.error("error", e.getMessage(), e); } } private int insertObservedInterval(String prefix, String methodName, long timestamp, Object[] values) { String sql = JdbcHelper.insertObservedInterval(prefix, methodName, timestamp, values); return jdbcTemplate.update(sql); } }
package reciter.algorithm.cluster; 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.Map.Entry; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reciter.algorithm.cluster.model.ReCiterCluster; import reciter.model.article.ReCiterArticle; import reciter.model.author.ReCiterAuthor; import reciter.model.author.TargetAuthor; import reciter.model.boardcertifications.ReadBoardCertifications; import reciter.utils.reader.YearDiscrepacyReader; import database.dao.IdentityDao; import database.dao.MatchingDepartmentsJournalsDao; import database.model.Identity; public class ReCiterClusterer implements Clusterer { private static final Logger slf4jLogger = LoggerFactory.getLogger(ReCiterClusterer.class); private Map<Integer, ReCiterCluster> finalCluster = new HashMap<Integer, ReCiterCluster>(); private boolean selectingTarget = false; private double similarityThreshold = 0.3; private double targetAuthorSimilarityThreshold = 0.001; public ReCiterClusterer() { ReCiterCluster.getClusterIDCounter().set(0); // reset counter on cluster id. } public Map<Integer, ReCiterCluster> getFinalCluster() { return finalCluster; } public int assignTargetToCluster(ReCiterArticle article) { selectingTarget = true; return selectCandidateCluster(article); } /** * * @param articleList * @param targetAuthor */ @Override public void cluster(List<ReCiterArticle> reciterArticleList) { slf4jLogger.info("Number of articles to be clustered: " + reciterArticleList.size()); ReCiterArticle first = null; if (reciterArticleList != null && reciterArticleList.size() > 0) { first = reciterArticleList.get(0); } else { return; } first.setClusterOriginator(true); // first article is the cluster starter. ReCiterCluster firstCluster = new ReCiterCluster(); firstCluster.add(first); finalCluster.put(firstCluster.getClusterID(), firstCluster); for (int i = 1; i < reciterArticleList.size(); i++) { ReCiterArticle article = reciterArticleList.get(i); // slf4jLogger.info("Assigning " + i + ": " + article.getArticleID()); int selection = selectCandidateCluster(article); if (selection == -1) { article.setClusterOriginator(true); // create its own cluster. ReCiterCluster newCluster = new ReCiterCluster(); newCluster.add(article); finalCluster.put(newCluster.getClusterID(), newCluster); } else { finalCluster.get(selection).add(article); } } } /** * Select the candidate cluster. * @param currentArticle * @param targetAuthor * @return */ public int selectCandidateCluster(ReCiterArticle currentArticle) { // Get cluster ids with max number of coauthor matches. Set<Integer> clusterIdSet = getKeysWithMaxVal(computeCoauthorMatch(currentArticle)); // slf4jLogger.info("PMID: " + currentArticle.getArticleID() + " " + clusterIdSet); // If groups have matching co-authors, the program selects the group that has the most matching names. if (clusterIdSet.size() == 1) { for (int id : clusterIdSet) { return id; } } // If two or more of these have the same number of coauthors, the one with the highest matching score is selected. if (clusterIdSet.size() > 1) { return getIdWithMostContentSimilarity(clusterIdSet, currentArticle); } // If groups have no matching co-authors, the group with the highest // matching (cosine) score is selected, provided that the score // exceeds a given threshold. Set<Integer> allClusterIdSet = new HashSet<Integer>(); for (ReCiterCluster c : finalCluster.values()) { allClusterIdSet.add(c.getClusterID()); } return getIdWithMostContentSimilarity(allClusterIdSet, currentArticle); } /** * * @param clusterIdList * @param currentArticle * @return */ private int getIdWithMostContentSimilarity(Set<Integer> clusterIdList, ReCiterArticle currentArticle) { double currentMax = -1; int currentMaxId = -1; for (int id : clusterIdList) { double sim = finalCluster.get(id).contentSimilarity(currentArticle); // cosine similarity score. // We have two sources for knowing whether someone lived or worked outside of the United States: // rc_identity_citizenship and rc_identity_education (foreign countries are in parentheses there). if (selectingTarget) { /* IdentityCizenshipDao identityCitizenshipDao = new IdentityCitizenshipDao(); IdentityEducationDao identityEducationDao = new IdentityEducationDao(); for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { for (ReCiterAuthor coauthor : article.getArticleCoAuthors().getCoAuthors()) { // please skip the coauthor which is the targetAuthor by comparing the first name, // middle name, and last name. if (coauthor.getAffiliation().equals(citizenship) || coauthor.getAffiliation().equals(education)) { // increase sim score. } } } */ } // Leverage departmental affiliation string matching for phase two matching. if (selectingTarget) { // Grab columns "primary_department" and "other_departments" from table "rc_identity". /* * Please be sure to translate "and" into different ways it's represented. "Pathology and Laboratory Medicine" should become: 1. Pathology and Laboratory Medicine 2. Pathology/Laboratory Medicine 3. Pathology & Laboratory Medicine */ /* for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { // compare the above departments information with the article's affiliation information. // increase the sim score if departments match. } */ } // For individuals with no/few papers, use default departmental-journal similarity score. if (selectingTarget) { for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { MatchingDepartmentsJournalsDao matchingDepartmentsJournalsDao = new MatchingDepartmentsJournalsDao(); double score = matchingDepartmentsJournalsDao.getScoreByJournalAndDepartment( article.getJournal().getIsoAbbreviation(), TargetAuthor.getInstance().getDepartment()); sim *= (1 + score); } } // Leverage data on board certifications to improve phase two matching. if (selectingTarget) { String cwid = TargetAuthor.getInstance().getCwid(); ReadBoardCertifications efr=new ReadBoardCertifications(); List<String> boardCertificationList = efr.getBoardCertifications(cwid); StringBuilder certificationData = new StringBuilder(); for(String data:boardCertificationList)certificationData.append(data).append(" "); // for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { // // TODO if TargetAuthor.getInstance()'s board certification matches the `article` object. Increase `sim`. } // // Leverage known co-investigators on grants to improve phase two matching. if (selectingTarget) { IdentityDao identityDao = new IdentityDao(); List<Identity> identityList = identityDao.getAssosiatedGrantIdentityList(TargetAuthor.getInstance().getCwid()); for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { for (ReCiterAuthor author : article.getArticleCoAuthors().getCoAuthors()) { for(Identity identity: identityList){ for (ReCiterAuthor currentArticleCoAuthor : currentArticle.getArticleCoAuthors().getCoAuthors()) { if (currentArticleCoAuthor.getAuthorName().firstInitialLastNameMatch(TargetAuthor.getInstance().getAuthorName())) { // First Name if (author.getAuthorName().getFirstName().equalsIgnoreCase(identity.getFirstName()) && currentArticleCoAuthor.getAuthorName().getFirstName().equalsIgnoreCase(identity.getFirstName())){ sim = sim + 1; } // Last Name if (author.getAuthorName().getLastName().equalsIgnoreCase(identity.getLastName()) && currentArticleCoAuthor.getAuthorName().getLastName().equalsIgnoreCase(identity.getLastName()) ){ sim = sim + 1; } } } } } } } // // If a candidate article is published in a journal and the cluster contains that journal, increase the score for a match. if (!selectingTarget) { for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { if(article.getJournal().getJournalTitle().equalsIgnoreCase(currentArticle.getJournal().getJournalTitle())){ sim = sim + 1; } // // TODO If `article`'s journal title matches (by direct string matching or journal similarity) `currentArticle`'s // // journal tit//le, increase `sim` score. } } // Grab CWID from rc_identity table. Combine with "@med.cornell.edu" and match against candidate records. // When email is found in affiliation string, during phase two clustering, automatically assign the matching identity. if (selectingTarget) { for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { if (article.getAffiliationConcatenated() != null) { if (article.getAffiliationConcatenated().contains(TargetAuthor.getInstance().getCwid() + "@med.cornell.edu")) { // sim *= 1.3; // a matching email should dramatically increase the score of some results but not decrease the score of others return id; } } } } // Increase similarity if the affiliation information "Weill Cornell Medical College" appears in affiliation. if (!selectingTarget) { for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { if (StringUtils.contains(StringUtils.lowerCase(article.getAffiliationConcatenated()), "weill cornell") && StringUtils.contains(StringUtils.lowerCase(currentArticle.getAffiliationConcatenated()), "weill cornell")) { sim *= 3; } } } // Adjust cosine similarity score with year discrepancy. if (!selectingTarget) { // Update the similarity score with year discrepancy. int yearDiff = Integer.MAX_VALUE; // Compute difference in year between candidate article and closest year in article cluster. for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { int currentYearDiff = Math.abs(currentArticle.getJournal().getJournalIssuePubDateYear() - article.getJournal().getJournalIssuePubDateYear()); if (currentYearDiff < yearDiff) { yearDiff = currentYearDiff; } } if (yearDiff > 40) { sim *= 0.001526; } else { sim = sim * YearDiscrepacyReader.getYearDiscrepancyMap().get(yearDiff); } } // Context: first name is a valuable indication if a person is author for an article. // It is always tracked in the rc_identity table. And it is sometimes, though not always available in the // article. First names tend to change especially in cases where it becomes Westernized. // middle initial is a valuable indication if a person has the identity of author for an article. // It is, sometimes, though not always, tracked in the rc_identity table. // And it is sometimes, though not always available in the article. if (!selectingTarget) { for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { String targetAuthorMiddleInitial = TargetAuthor.getInstance().getAuthorName().getMiddleInitial(); String firstName = TargetAuthor.getInstance().getAuthorName().getFirstName(); // First Name from rc_identity. if (firstName != null) { // For cases where first name is present in rc_identity. for (ReCiterAuthor author : article.getArticleCoAuthors().getCoAuthors()) { if (author.getAuthorName().firstInitialLastNameMatch(TargetAuthor.getInstance().getAuthorName())) { if (firstName.equalsIgnoreCase((author.getAuthorName().getFirstName()))) { for (ReCiterAuthor currentArticleAuthor : currentArticle.getArticleCoAuthors().getCoAuthors()) { if (currentArticleAuthor.getAuthorName().firstInitialLastNameMatch(TargetAuthor.getInstance().getAuthorName())) { if (firstName.equalsIgnoreCase(currentArticleAuthor.getAuthorName().getFirstName())) { sim *= 1.3; // (rc_idenity = YES, present in cluster = YES, match = YES. } else { sim *= 0.4; // (rc_idenity = YES, present in cluster = YES, match = NO. } } } } } } } // Middle initial from rc_identity. if (targetAuthorMiddleInitial != null) { // For cases where middle initial is present in rc_identity. for (ReCiterAuthor author : article.getArticleCoAuthors().getCoAuthors()) { if (author.getAuthorName().firstInitialLastNameMatch(TargetAuthor.getInstance().getAuthorName())) { if (targetAuthorMiddleInitial.equalsIgnoreCase((author.getAuthorName().getMiddleInitial()))) { for (ReCiterAuthor currentArticleAuthor : currentArticle.getArticleCoAuthors().getCoAuthors()) { if (currentArticleAuthor.getAuthorName().firstInitialLastNameMatch(TargetAuthor.getInstance().getAuthorName())) { if (targetAuthorMiddleInitial.equalsIgnoreCase(currentArticleAuthor.getAuthorName().getMiddleInitial())) { sim *= 1.3; } else { sim *= 0.3; // the likelihood that someone wrote an article should plummet when this is the case } } } } } } } else { // For cases where middle initial is not present in rc_identity. for (ReCiterAuthor author : article.getArticleCoAuthors().getCoAuthors()) { if (author.getAuthorName().firstInitialLastNameMatch(TargetAuthor.getInstance().getAuthorName())) { for (ReCiterAuthor currentArticleAuthor : currentArticle.getArticleCoAuthors().getCoAuthors()) { if (currentArticleAuthor.getAuthorName().firstInitialLastNameMatch(TargetAuthor.getInstance().getAuthorName())) { if (currentArticleAuthor.getAuthorName().getMiddleInitial() == null && author.getAuthorName().getMiddleInitial() != null) { // it's rare but not completely improbable that an author would share their // middle initial on a paper but won't supply it on an official CV, or so I would argue sim *= 0.7; } } } } } } } } // if (!selectingTarget) { // JournalDao journalDao = new JournalDao(); // for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { // // Use the cluster starter to compare journal similarity. // if (article.isClusterStarter()) { // if (article.getJournal() != null && currentArticle.getJournal() != null) { // double journalSimScore = journalDao.getJournalSimilarity( // article.getJournal().getIsoAbbreviation(), // currentArticle.getJournal().getIsoAbbreviation()); // // Check similarity both ways. // if (journalSimScore == -1.0) { // journalSimScore = journalDao.getJournalSimilarity( // currentArticle.getJournal().getIsoAbbreviation(), // article.getJournal().getIsoAbbreviation()); // if (journalSimScore != -1.0) { // if (journalSimScore > 0.8) { // sim *= (1 + journalSimScore); // Journal similarity on a sliding scale. if (selectingTarget) { // Update the similarity score with year discrepancy. int yearDiff = Integer.MAX_VALUE; // Compute difference in year between candidate article and closest year in article cluster. for (ReCiterArticle article : finalCluster.get(id).getArticleCluster()) { int currentYearDiff = article.getJournal().getJournalIssuePubDateYear() - TargetAuthor.getInstance().getTerminalDegreeYear(); if (currentYearDiff < yearDiff) { yearDiff = currentYearDiff; } } // 7 years before terminal degree >> 0.3 if (yearDiff < -7) { sim *= 0.3; // 0 - 7 years before terminal degree >> 0.75 } else if (yearDiff <= 0 && yearDiff >= -7) { sim *= 0.75; } // after terminal degree >> 1.0 (don't change sim score). } else if (sim > similarityThreshold && sim > currentMax) { currentArticle.setInfo("Max Id: + " + currentMaxId + " sim: " + sim); currentMaxId = id; currentMax = sim; // TODO: what happens if cosine similarity is tied? } } return currentMaxId; // found a cluster. } /** * * @param currentArticle * @param targetAuthor * @return */ // computes coauthor matches of this article with all current clusters. private Map<Integer, Integer> computeCoauthorMatch(ReCiterArticle currentArticle) { Map<Integer, Integer> coauthorsCount = new HashMap<Integer, Integer>(); // ClusterId to number of coauthors. for (ReCiterCluster reCiterCluster : finalCluster.values()) { int matchingCoauthors = reCiterCluster.getMatchingCoauthorCount(currentArticle); coauthorsCount.put(reCiterCluster.getClusterID(), matchingCoauthors); } return coauthorsCount; } /** * * @param map * @return */ // helper function to find keys in map data structure with max values. private Set<Integer> getKeysWithMaxVal(Map<Integer, Integer> map) { Set<Integer> keyList = new HashSet<Integer>(); int maxValueInMap=(Collections.max(map.values())); // This will return max value in the Hashmap // System.out.println("Max value: " + maxValueInMap); for (Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() == maxValueInMap && maxValueInMap != 0) { keyList.add(entry.getKey()); } } return keyList; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Number of clusters formed: " + getFinalCluster().size() + "\n"); for (ReCiterCluster r : finalCluster.values()) { sb.append("{"); sb.append(r.getClusterID()); sb.append(" (size of cluster="); sb.append(r.getArticleCluster().size()); sb.append("): "); for (ReCiterArticle a : r.getArticleCluster()) { sb.append(a.getArticleID()); sb.append(", "); } sb.append("}\n"); } return sb.toString(); } @Override public double getArticleToArticleSimilarityThresholdValue() { // TODO Auto-generated method stub return 0; } }
/** * @author Sibo Wang * @author Raul (edits) * */ package inputoutput.conn; import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import inputoutput.Attribute; import inputoutput.Record; import inputoutput.TableInfo; public class DBConnector extends Connector { private static final Logger log = Logger.getLogger(DBConnector.class.getName()); private DBType db;// db system name e.g., mysq/oracle etc. private String username;// db conn user name; private String password; // db conn password; private String connIP;// for database private String port;// db connection port private Connection conn = null; private TableInfo tbInfo; private long currentOffset = 0; public DBConnector() { this.tbInfo = new TableInfo(); } public DBConnector(DBType dbType, String connIP, String port, String connectPath, String filename, String username, String password) throws IOException{ this.db = dbType; this.connIP = connIP; this.port = port; this.connectPath = connectPath; this.sourceName = filename; this.username =username; this.password = password; this.tbInfo = new TableInfo(); this.initConnector(); } @Override public void initConnector() throws IOException { try { if(db == DBType.MYSQL) { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql: connIP + ":" + port + "/" + connectPath, username, password); } else if(db == DBType.POSTGRESQL) { Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection("jdbc:postgresql: connIP + ":" + port + "/" + connectPath, username, password); } else if(db == DBType.ORACLE) { Class.forName ("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection( "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)" + "(HOST="+connIP+")(PORT="+port+")))" + "(CONNECT_DATA=(SID="+connectPath+")))", username, password); } List<Attribute> attrs = this.getAttributes(); this.tbInfo.setTableAttributes(attrs); } catch (ClassNotFoundException e) { log.log(Level.SEVERE, "DB connection driver not found"); e.printStackTrace(); } catch (SQLException e) { log.log(Level.SEVERE, "Cannot connect to the database"); e.printStackTrace(); } } @Override public boolean readRows(int num, List<Record> rec_list) throws IOException, SQLException { String sql = null; // TODO: add mysql here if(this.db == DBType.POSTGRESQL) { sql = "SELECT * FROM "+sourceName+ " LIMIT "+ num + " OFFSET " + currentOffset; } else if(this.db == DBType.ORACLE) { long newLimit = num + currentOffset; sql = " SELECT * FROM ( SELECT * FROM "+sourceName+") WHERE ROWNUM BETWEEN "+currentOffset+" AND " + newLimit + " "; } ResultSet rs = null; try { Statement stat = conn.createStatement(); stat.closeOnCompletion(); // close it with the resultSet.close() rs = stat.executeQuery(sql); } catch(SQLException sqle) { System.out.println("ERROR: " + sqle.getLocalizedMessage()); return false; } boolean new_row = false; while(rs.next()) { new_row = true; Record rec = new Record(); for(int i = 0; i < this.tbInfo.getTableAttributes().size(); i++) { Object obj = rs.getObject(i+1); if(obj != null) { String v1 = obj.toString(); rec.getTuples().add(v1); } else { rec.getTuples().add(""); } } rec_list.add(rec); } currentOffset += rec_list.size(); rs.close(); return new_row; } @Override void destroyConnector() { try { conn.close(); } catch (SQLException e) { log.log(Level.SEVERE, "Cannot close the connection to the database"); e.printStackTrace(); } } @Override public List<Attribute> getAttributes() throws SQLException { if(tbInfo.getTableAttributes() != null) return tbInfo.getTableAttributes(); DatabaseMetaData metadata = conn.getMetaData(); ResultSet resultSet = metadata.getColumns(null, null, sourceName, null); Vector<Attribute> attrs = new Vector<Attribute>(); while (resultSet.next()) { String name = resultSet.getString("COLUMN_NAME"); String type = resultSet.getString("TYPE_NAME"); int size = resultSet.getInt("COLUMN_SIZE"); Attribute attr = new Attribute(name, type, size); attrs.addElement(attr); } tbInfo.setTableAttributes(attrs); return attrs; } /* * setters and getters. This is a boring part, and could be ignored. */ public String getConnectPath(){ return this.connectPath; } public void setConnectPath(String connectPath){ this.connectPath = connectPath; } public String getFilename(){ return this.sourceName; } public void setFilename(String filename){ this.sourceName = filename; } public DBType getDBType() { return db; } public void setDB(DBType db) { this.db = db; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConnIP() { return connIP; } public void setConnIP(String connIP) { this.connIP = connIP; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } @Override public String getSourceName() { return this.conn.toString(); } public void close() { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package nl.mpi.kinnate.data; import java.net.URI; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Vector; import javax.swing.ImageIcon; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.data.ContainerNode; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.IndexerParameters; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.svg.SymbolGraphic; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; public class KinTreeNode extends ArbilNode implements Comparable { private UniqueIdentifier uniqueIdentifier; protected EntityData entityData = null; protected IndexerParameters indexerParameters; protected ArbilNode[] childNodes = null; static private SymbolGraphic symbolGraphic = null; protected EntityCollection entityCollection; protected MessageDialogHandler dialogHandler; protected ArbilDataNodeLoader dataNodeLoader; private String derivedLabelString = null; public KinTreeNode(UniqueIdentifier uniqueIdentifier, EntityData entityData, IndexerParameters indexerParameters, MessageDialogHandler dialogHandler, EntityCollection entityCollection, ArbilDataNodeLoader dataNodeLoader) { // todo: create new constructor that takes a unique identifer and loads from the database. super(); this.uniqueIdentifier = uniqueIdentifier; this.indexerParameters = indexerParameters; this.entityData = entityData; this.entityCollection = entityCollection; this.dialogHandler = dialogHandler; this.dataNodeLoader = dataNodeLoader; if (symbolGraphic == null) { symbolGraphic = new SymbolGraphic(dialogHandler); } } // public void setEntityData(EntityData entityData) { // // todo: this does not cause the tree to update so it is redundent // this.entityData = entityData; // derivedLabelString = null; // symbolGraphic = null; // // todo: clear or set the child entity data // //childNodes public EntityData getEntityData() { return entityData; } public UniqueIdentifier getUniqueIdentifier() { return uniqueIdentifier; } @Override public String toString() { if (derivedLabelString == null) { if (entityData == null) { return "(entity not loaded)"; } else { StringBuilder labelBuilder = new StringBuilder(); final String[] labelArray = entityData.getLabel(); if (labelArray != null && labelArray.length > 0) { for (String labelString : labelArray) { labelBuilder.append(labelString); labelBuilder.append(" "); } } else { labelBuilder.append(" "); } derivedLabelString = labelBuilder.toString(); } } return derivedLabelString; } @Override public ArbilDataNode[] getAllChildren() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void getAllChildren(Vector<ArbilDataNode> allChildren) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ArbilNode[] getChildArray() { if (childNodes == null) { // add the related entities grouped into metanodes by relation type and within each group the subsequent nodes are filtered by the type of relation. HashMap<DataTypes.RelationType, HashSet<KinTreeFilteredNode>> metaNodeMap = new HashMap<DataTypes.RelationType, HashSet<KinTreeFilteredNode>>(); for (EntityRelation entityRelation : entityData.getAllRelations()) { if (!metaNodeMap.containsKey(entityRelation.getRelationType())) { metaNodeMap.put(entityRelation.getRelationType(), new HashSet<KinTreeFilteredNode>()); } metaNodeMap.get(entityRelation.getRelationType()).add(new KinTreeFilteredNode(entityRelation, indexerParameters, dialogHandler, entityCollection, dataNodeLoader)); } HashSet<ArbilNode> kinTreeMetaNodes = new HashSet<ArbilNode>(); for (Map.Entry<DataTypes.RelationType, HashSet<KinTreeFilteredNode>> filteredNodeEntry : metaNodeMap.entrySet()) {//values().toArray(new KinTreeFilteredNode[]{}) kinTreeMetaNodes.add(new FilteredNodeContainer(filteredNodeEntry.getKey().name(), null, filteredNodeEntry.getValue().toArray(new KinTreeFilteredNode[]{}))); } getLinksMetaNode(kinTreeMetaNodes); childNodes = kinTreeMetaNodes.toArray(new ArbilNode[]{}); } return childNodes; } protected void getLinksMetaNode(HashSet<ArbilNode> kinTreeMetaNodes) { if (entityData.archiveLinkArray != null) { HashSet<ArbilDataNode> relationList = new HashSet<ArbilDataNode>(); for (URI archiveLink : entityData.archiveLinkArray) { ArbilDataNode linkedArbilDataNode = dataNodeLoader.getArbilDataNode(null, archiveLink); relationList.add(linkedArbilDataNode); } kinTreeMetaNodes.add(new ContainerNode("External Links", null, relationList.toArray(new ArbilDataNode[]{}))); } } @Override public int getChildCount() { throw new UnsupportedOperationException("Not supported yet."); } @Override public ImageIcon getIcon() { if (entityData != null) { return symbolGraphic.getSymbolGraphic(entityData.getSymbolNames(), entityData.isEgo); } return null; } @Override public boolean hasCatalogue() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasHistory() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasLocalResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isArchivableFile() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCatalogue() { return false; } @Override public boolean isChildNode() { return false; } @Override public boolean isCmdiMetaDataNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCorpus() { return false; } @Override public boolean isDataLoaded() { return true; } @Override public boolean isDirectory() { return false; } @Override public boolean isEditable() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isEmptyMetaNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isFavorite() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLoading() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isDataPartiallyLoaded() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLocal() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isMetaDataNode() { return false; } @Override public boolean isResourceSet() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isSession() { return false; } public int compareTo(Object o) { if (o instanceof KinTreeNode) { int compResult = this.toString().compareTo(o.toString()); if (compResult == 0) { // todo: compare by age if the labels match // compResult = entityData } return compResult; } else { // put kin nodes in front of other nodes return 1; } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KinTreeNode other = (KinTreeNode) obj; // we compare the entity data instance because this is the only way to update the arbil tree // todo: this does not break the graph selection process but check for other places where equals might be used return this.entityData == other.entityData; //// return this.hashCode() == other.hashCode(); // if (entityData == null || other.entityData == null) { // // todo: it would be good for this to never be null, or at least to aways have the UniqueIdentifier to compare // return false; // if (this.getUniqueIdentifier() != other.getUniqueIdentifier() && (this.getUniqueIdentifier() == null || !this.getUniqueIdentifier().equals(other.getUniqueIdentifier()))) { // return false; // return true; } @Override public int hashCode() { int hash = 0; hash = 37 * hash + (this.uniqueIdentifier != null ? this.uniqueIdentifier.hashCode() : 0); return hash; } }
package nl.mpi.kinnate.data; import java.net.URI; import java.util.ArrayList; import java.util.Vector; import javax.swing.ImageIcon; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.svg.SymbolGraphic; public class KinTreeNode extends ArbilNode implements Comparable { public EntityData entityData; DataTypes.RelationType subnodeFilter; ArbilNode[] childNodes = null; static SymbolGraphic symbolGraphic = new SymbolGraphic(); public KinTreeNode(EntityData entityData) { super(); this.entityData = entityData; this.subnodeFilter = null; } public KinTreeNode(EntityData entityData, DataTypes.RelationType subnodeFilter) { super(); this.entityData = entityData; this.subnodeFilter = subnodeFilter; // subnode filter should be null unless the child nodes are to be filtered } @Override public String toString() { StringBuilder labelBuilder = new StringBuilder(); if (entityData == null) { labelBuilder.append("(entity not loaded)"); } else { final String[] labelArray = entityData.getLabel(); if (labelArray != null && labelArray.length > 0) { for (String labelString : labelArray) { labelBuilder.append(labelString); labelBuilder.append(" "); } } else { labelBuilder.append("(unnamed entity)"); } } return labelBuilder.toString(); } @Override public ArbilDataNode[] getAllChildren() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void getAllChildren(Vector<ArbilDataNode> allChildren) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ArbilNode[] getChildArray() { if (childNodes != null) { return childNodes; } else if (entityData != null) { ArrayList<ArbilNode> relationList = new ArrayList<ArbilNode>(); // todo: add metanodes and ui option to hide show relation types for (EntityRelation entityRelation : entityData.getAllRelations()) { final boolean showFiltered = subnodeFilter == DataTypes.RelationType.ancestor || subnodeFilter == DataTypes.RelationType.descendant; if (subnodeFilter == null || (subnodeFilter == entityRelation.relationType && showFiltered)) { relationList.add(new KinTreeNode(entityRelation.getAlterNode(), entityRelation.relationType)); } } if (entityData.archiveLinkArray != null) { for (URI archiveLink : entityData.archiveLinkArray) { ArbilDataNode linkedArbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, archiveLink); relationList.add(linkedArbilDataNode); } } childNodes = relationList.toArray(new ArbilNode[]{}); return childNodes; } else { return new ArbilNode[]{}; } // todo: inthe case of metadata nodes load them via the arbil data loader // try { // String entityPath = entityData.getEntityPath(); // if (entityPath != null) { //// ArbilDataNode arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(entityPath)); // if (entityData.isEgo || egoIdentifiers.contains(entityData.getUniqueIdentifier())) { // egoNodeArray.add(arbilDataNode); // } else if (requiredEntityIdentifiers.contains(entityData.getUniqueIdentifier())) { // requiredNodeArray.add(arbilDataNode); // } else { // remainingNodeArray.add(arbilDataNode); // } catch (URISyntaxException exception) { // System.err.println(exception.getMessage()); } @Override public int getChildCount() { throw new UnsupportedOperationException("Not supported yet."); } @Override public ImageIcon getIcon() { if (entityData != null) { return symbolGraphic.getSymbolGraphic(entityData.getSymbolType(), entityData.isEgo); } return null; } @Override public boolean hasCatalogue() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasHistory() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasLocalResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isArchivableFile() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCatalogue() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isChildNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCmdiMetaDataNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCorpus() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isDataLoaded() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isDirectory() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isEditable() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isEmptyMetaNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isFavorite() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLoading() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLocal() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isMetaDataNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isResourceSet() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isSession() { throw new UnsupportedOperationException("Not supported yet."); } public int compareTo(Object o) { if (o instanceof KinTreeNode) { int compResult = this.toString().compareTo(o.toString()); if (compResult == 0) { // todo: compare by age if the labels match // compResult = entityData } return compResult; } else { // put kin nodes in front of other nodes return 1; } } }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.Component; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.JScrollPane; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.ui.ArbilTable; import nl.mpi.arbil.ui.ArbilTableModel; import nl.mpi.kinnate.svg.GraphPanel; public class MetadataPanel extends JPanel { private KinTree kinTree; // JScrollPane tableScrollPane; private ArbilTableModel kinTableModel; private ArbilTableModel archiveTableModel; private JScrollPane kinTableScrollPane; private HidePane editorHidePane; private ArrayList<ArbilDataNode> archiveNodes = new ArrayList<ArbilDataNode>(); public MetadataPanel(GraphPanel graphPanel, HidePane editorHidePane, TableCellDragHandler tableCellDragHandler) { // todo: #1101 The metadata pane should always be available rather then for specific diagrams this.kinTree = new KinTree(graphPanel); this.kinTableModel = new ArbilTableModel(); this.archiveTableModel = new ArbilTableModel(); ArbilTable kinTable = new ArbilTable(kinTableModel, "Selected Nodes"); ArbilTable archiveTable = new ArbilTable(archiveTableModel, "Selected Nodes"); kinTable.setTransferHandler(tableCellDragHandler); kinTable.setDragEnabled(true); this.editorHidePane = editorHidePane; this.setLayout(new BorderLayout()); kinTableScrollPane = new JScrollPane(kinTable); JScrollPane archiveTableScrollPane = new JScrollPane(archiveTable); this.add(archiveTableScrollPane, BorderLayout.CENTER); this.add(kinTree, BorderLayout.LINE_START); } public void removeAllArbilDataNodeRows() { kinTableModel.removeAllArbilDataNodeRows(); archiveTableModel.removeAllArbilDataNodeRows(); archiveNodes.clear(); } public void addSingleArbilDataNode(ArbilDataNode arbilDataNode) { kinTableModel.addSingleArbilDataNode(arbilDataNode); // if (arbilDataNode instanceof KinTreeNode) archiveTableModel.addSingleArbilDataNode(arbilDataNode); archiveNodes.add(arbilDataNode); } public void addTab(String labelString, Component elementEditor) { editorHidePane.addTab(labelString, elementEditor); } public void removeTab(Component elementEditor) { editorHidePane.remove(elementEditor); } public void updateEditorPane() { // todo: add only imdi nodes to the tree and the root node of them // todo: maybe have a table for entities and one for achive metdata if (archiveTableModel.getArbilDataNodeCount() > 0) { addTab("Archive Links", this); } else { removeTab(this); } if (kinTableModel.getArbilDataNodeCount() > 0) { addTab("Metadata", kinTableScrollPane); } else { removeTab(kinTableScrollPane); } boolean showEditor = editorHidePane.getComponentCount() > 0; kinTree.rootNodeChildren = archiveNodes.toArray(new ArbilDataNode[]{}); kinTree.requestResort(); if (showEditor && editorHidePane.isHidden()) { editorHidePane.toggleHiddenState(); } editorHidePane.setVisible(showEditor); } }
package StevenDimDoors.mod_pocketDim.world; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.item.ItemDoor; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraftforge.common.DimensionManager; import StevenDimDoors.mod_pocketDim.DDProperties; import StevenDimDoors.mod_pocketDim.Point3D; import StevenDimDoors.mod_pocketDim.blocks.DimensionalDoor; import StevenDimDoors.mod_pocketDim.blocks.IDimDoor; import StevenDimDoors.mod_pocketDim.core.DimLink; import StevenDimDoors.mod_pocketDim.core.LinkTypes; import StevenDimDoors.mod_pocketDim.core.NewDimData; import StevenDimDoors.mod_pocketDim.core.PocketManager; import StevenDimDoors.mod_pocketDim.dungeon.DungeonData; import StevenDimDoors.mod_pocketDim.dungeon.DungeonSchematic; import StevenDimDoors.mod_pocketDim.dungeon.pack.DungeonPackConfig; import StevenDimDoors.mod_pocketDim.helpers.DungeonHelper; import StevenDimDoors.mod_pocketDim.helpers.yCoordHelper; import StevenDimDoors.mod_pocketDim.schematic.BlockRotator; import StevenDimDoors.mod_pocketDim.util.Pair; import StevenDimDoors.mod_pocketDim.util.Point4D; import StevenDimDoors.mod_pocketDim.items.BaseItemDoor; import StevenDimDoors.mod_pocketDim.items.ItemDimensionalDoor; public class PocketBuilder { public static final int MIN_POCKET_SIZE = 5; public static final int MAX_POCKET_SIZE = 51; public static final int DEFAULT_POCKET_SIZE = 39; public static final int MIN_POCKET_WALL_THICKNESS = 1; public static final int MAX_POCKET_WALL_THICKNESS = 10; public static final int DEFAULT_POCKET_WALL_THICKNESS = 5; private static final Random random = new Random(); private PocketBuilder() { } public static boolean generateNewDungeonPocket(DimLink link, DDProperties properties) { if (link == null) { throw new IllegalArgumentException("link cannot be null."); } if (properties == null) { throw new IllegalArgumentException("properties cannot be null."); } if (link.hasDestination()) { throw new IllegalArgumentException("link cannot have a destination assigned already."); } try { //Register a new dimension NewDimData parent = PocketManager.getDimensionData(link.source().getDimension()); NewDimData dimension = PocketManager.registerPocket(parent, true); //Load a world World world = PocketManager.loadDimension(dimension.id()); if (world == null || world.provider == null) { System.err.println("Could not initialize dimension for a dungeon!"); return false; } //Choose a dungeon to generate Pair<DungeonData, DungeonSchematic> pair = selectDungeon(dimension, random, properties); if (pair == null) { System.err.println("Could not select a dungeon for generation!"); return false; } DungeonData dungeon = pair.getFirst(); DungeonSchematic schematic = pair.getSecond(); //Calculate the destination point DungeonPackConfig packConfig = dungeon.dungeonType().Owner != null ? dungeon.dungeonType().Owner.getConfig() : null; Point4D source = link.source(); int orientation = getDoorOrientation(source, properties); Point3D destination; if (packConfig != null && packConfig.doDistortDoorCoordinates()) { destination = calculateNoisyDestination(source, dimension, dungeon, orientation); } else { destination = new Point3D(source.getX(), source.getY(), source.getZ()); } destination.setY( yCoordHelper.adjustDestinationY(destination.getY(), world.getHeight(), schematic.getEntranceDoorLocation().getY(), schematic.getHeight()) ); //Generate the dungeon schematic.copyToWorld(world, destination, orientation, link, random); //Finish up destination initialization dimension.initializeDungeon(destination.getX(), destination.getY(), destination.getZ(), orientation, link, dungeon); dimension.setFilled(true); return true; } catch (Exception e) { e.printStackTrace(); return false; } } private static Point3D calculateNoisyDestination(Point4D source, NewDimData dimension, DungeonData dungeon, int orientation) { int depth = NewDimData.calculatePackDepth(dimension.parent(), dungeon); int forwardNoise = MathHelper.getRandomIntegerInRange(random, 10 * depth, 130 * depth); int sidewaysNoise = MathHelper.getRandomIntegerInRange(random, -10 * depth, 10 * depth); //Rotate the link destination noise to point in the same direction as the door exit //and add it to the door's location. Use EAST as the reference orientation since linkDestination //is constructed as if pointing East. Point3D linkDestination = new Point3D(forwardNoise, 0, sidewaysNoise); Point3D sourcePoint = new Point3D(source.getX(), source.getY(), source.getZ()); Point3D zeroPoint = new Point3D(0, 0, 0); BlockRotator.transformPoint(linkDestination, zeroPoint, orientation - BlockRotator.EAST_DOOR_METADATA, sourcePoint); return linkDestination; } private static Pair<DungeonData, DungeonSchematic> selectDungeon(NewDimData dimension, Random random, DDProperties properties) { //We assume the dimension doesn't have a dungeon assigned if (dimension.dungeon() != null) { throw new IllegalArgumentException("dimension cannot have a dungeon assigned already."); } DungeonData dungeon = null; DungeonSchematic schematic = null; dungeon = DungeonHelper.instance().selectDungeon(dimension, random); if (dungeon != null) { schematic = loadAndValidateDungeon(dungeon, properties); } else { System.err.println("Could not select a dungeon at all!"); } if (schematic == null) { //TODO: In the future, remove this dungeon from the generation lists altogether. //That will have to wait until our code is updated to support that more easily. try { System.err.println("Loading the default error dungeon instead..."); dungeon = DungeonHelper.instance().getDefaultErrorDungeon(); schematic = loadAndValidateDungeon(dungeon, properties); } catch (Exception e) { e.printStackTrace(); return null; } } return new Pair<DungeonData, DungeonSchematic>(dungeon, schematic); } private static DungeonSchematic loadAndValidateDungeon(DungeonData dungeon, DDProperties properties) { try { DungeonSchematic schematic = dungeon.loadSchematic(); //Validate the dungeon's dimensions if (hasValidDimensions(schematic)) { schematic.applyImportFilters(properties); //Check that the dungeon has an entrance or we'll have a crash if (schematic.getEntranceDoorLocation() == null) { System.err.println("The following schematic file does not have an entrance: " + dungeon.schematicPath()); return null; } } else { System.err.println("The following schematic file has dimensions that exceed the maximum permitted dimensions for dungeons: " + dungeon.schematicPath()); return null; } return schematic; } catch (Exception e) { System.err.println("An error occurred while loading the following schematic: " + dungeon.schematicPath()); System.err.println(e.getMessage()); return null; } } private static boolean hasValidDimensions(DungeonSchematic schematic) { return (schematic.getWidth() <= DungeonHelper.MAX_DUNGEON_WIDTH && schematic.getHeight() <= DungeonHelper.MAX_DUNGEON_HEIGHT && schematic.getLength() <= DungeonHelper.MAX_DUNGEON_LENGTH); } public static boolean generateNewPocket(DimLink link, DDProperties properties, Block door) { return generateNewPocket(link, DEFAULT_POCKET_SIZE, DEFAULT_POCKET_WALL_THICKNESS, properties, door); } private static int getDoorOrientation(Point4D source, DDProperties properties) { World world = DimensionManager.getWorld(source.getDimension()); if (world == null) { throw new IllegalStateException("The link's source world should be loaded!"); } //Check if the block below that point is actually a door int blockID = world.getBlockId(source.getX(), source.getY() - 1, source.getZ()); if (blockID != properties.DimensionalDoorID && blockID != properties.WarpDoorID && blockID != properties.TransientDoorID && blockID != properties.GoldDimDoorID) { throw new IllegalStateException("The link's source is not a door block. It should be impossible to traverse a rift without a door!"); } //Return the orientation portion of its metadata int orientation = world.getBlockMetadata(source.getX(), source.getY() - 1, source.getZ()) & 3; return orientation; } public static boolean generateNewPocket(DimLink link, int size, int wallThickness, DDProperties properties, Block door) { if (link == null) { throw new IllegalArgumentException(); } if (properties == null) { throw new IllegalArgumentException("properties cannot be null."); } if (link.hasDestination()) { throw new IllegalArgumentException("link cannot have a destination assigned already."); } if(door==null) { throw new IllegalArgumentException("Must have a doorItem to gen one!!"); } if (size < MIN_POCKET_SIZE || size > MAX_POCKET_SIZE) { throw new IllegalArgumentException("size must be between " + MIN_POCKET_SIZE + " and " + MAX_POCKET_SIZE + ", inclusive."); } if (wallThickness < MIN_POCKET_WALL_THICKNESS || wallThickness > MAX_POCKET_WALL_THICKNESS) { throw new IllegalArgumentException("wallThickness must be between " + MIN_POCKET_WALL_THICKNESS + " and " + MAX_POCKET_WALL_THICKNESS + ", inclusive."); } if (size % 2 == 0) { throw new IllegalArgumentException("size must be an odd number."); } if (size < 2 * wallThickness + 3) { throw new IllegalArgumentException("size must be large enough to fit the specified wall thickness and some air space."); } try { //Register a new dimension NewDimData parent = PocketManager.getDimensionData(link.source().getDimension()); NewDimData dimension = PocketManager.registerPocket(parent, false); //Load a world World world = PocketManager.loadDimension(dimension.id()); if (world == null || world.provider == null) { System.err.println("Could not initialize dimension for a pocket!"); return false; } //Calculate the destination point Point4D source = link.source(); int destinationY = yCoordHelper.adjustDestinationY(source.getY(), world.getHeight(), wallThickness + 1, size); int orientation = getDoorOrientation(source, properties); //Place a link leading back out of the pocket DimLink reverseLink = dimension.createLink(source.getX(), destinationY, source.getZ(), LinkTypes.REVERSE); parent.setDestination(reverseLink, source.getX(), source.getY(), source.getZ()); //Build the actual pocket area buildPocket(world, source.getX(), destinationY, source.getZ(), orientation, size, wallThickness, properties, door); //Finish up destination initialization dimension.initializePocket(source.getX(), destinationY, source.getZ(), orientation, link); dimension.setFilled(true); return true; } catch (Exception e) { e.printStackTrace(); return false; } } private static void buildPocket(World world, int x, int y, int z, int orientation, int size, int wallThickness, DDProperties properties, Block doorBlock) { if (properties == null) { throw new IllegalArgumentException("properties cannot be null."); } if (size < MIN_POCKET_SIZE || size > MAX_POCKET_SIZE) { throw new IllegalArgumentException("size must be between " + MIN_POCKET_SIZE + " and " + MAX_POCKET_SIZE + ", inclusive."); } if (wallThickness < MIN_POCKET_WALL_THICKNESS || wallThickness > MAX_POCKET_WALL_THICKNESS) { throw new IllegalArgumentException("wallThickness must be between " + MIN_POCKET_WALL_THICKNESS + " and " + MAX_POCKET_WALL_THICKNESS + ", inclusive."); } if (size % 2 == 0) { throw new IllegalArgumentException("size must be an odd number."); } if (size < 2 * wallThickness + 3) { throw new IllegalArgumentException("size must be large enough to fit the specified wall thickness and some air space."); } if (!(doorBlock instanceof IDimDoor)) { throw new IllegalArgumentException("Door must implement IDimDoor"); } Point3D center = new Point3D(x - wallThickness + 1 + (size / 2), y - wallThickness - 1 + (size / 2), z); Point3D door = new Point3D(x, y, z); BlockRotator.transformPoint(center, door, orientation - BlockRotator.EAST_DOOR_METADATA, door); //Build the outer layer of Eternal Fabric buildBox(world, center.getX(), center.getY(), center.getZ(), (size / 2), properties.PermaFabricBlockID, false, 0); //Build the (wallThickness - 1) layers of Fabric of Reality for (int layer = 1; layer < wallThickness; layer++) { buildBox(world, center.getX(), center.getY(), center.getZ(), (size / 2) - layer, properties.FabricBlockID, layer < (wallThickness - 1) && properties.TNFREAKINGT_Enabled, properties.NonTntWeight); } //Build the door int doorOrientation = BlockRotator.transformMetadata(BlockRotator.EAST_DOOR_METADATA, orientation - BlockRotator.EAST_DOOR_METADATA + 2, properties.DimensionalDoorID); ItemDimensionalDoor.placeDoorBlock(world, x, y - 1, z, doorOrientation, doorBlock); } private static void buildBox(World world, int centerX, int centerY, int centerZ, int radius, int blockID, boolean placeTnt, int nonTntWeight) { int x, y, z; final int startX = centerX - radius; final int startY = centerY - radius; final int startZ = centerZ - radius; final int endX = centerX + radius; final int endY = centerY + radius; final int endZ = centerZ + radius; //Build faces of the box for (x = startX; x <= endX; x++) { for (z = startZ; z <= endZ; z++) { setBlockDirectlySpecial(world, x, startY, z, blockID, 0, placeTnt, nonTntWeight); setBlockDirectlySpecial(world, x, endY, z, blockID, 0, placeTnt, nonTntWeight); } for (y = startY; y <= endY; y++) { setBlockDirectlySpecial(world, x, y, startZ, blockID, 0, placeTnt, nonTntWeight); setBlockDirectlySpecial(world, x, y, endZ, blockID, 0, placeTnt, nonTntWeight); } } for (y = startY; y <= endY; y++) { for (z = startZ; z <= endZ; z++) { setBlockDirectlySpecial(world, startX, y, z, blockID, 0, placeTnt, nonTntWeight); setBlockDirectlySpecial(world, endX, y, z, blockID, 0, placeTnt, nonTntWeight); } } } private static void setBlockDirectlySpecial(World world, int x, int y, int z, int blockID, int metadata, boolean placeTnt, int nonTntWeight) { if (placeTnt && random.nextInt(nonTntWeight + 1) == 0) { setBlockDirectly(world, x, y, z, Block.tnt.blockID, 1); } else { setBlockDirectly(world, x, y, z, blockID, metadata); } } private static void setBlockDirectly(World world, int x, int y, int z, int blockID, int metadata) { if (blockID != 0 && Block.blocksList[blockID] == null) { return; } int cX = x >> 4; int cZ = z >> 4; int cY = y >> 4; Chunk chunk; int localX = (x % 16) < 0 ? (x % 16) + 16 : (x % 16); int localZ = (z % 16) < 0 ? (z % 16) + 16 : (z % 16); ExtendedBlockStorage extBlockStorage; chunk = world.getChunkFromChunkCoords(cX, cZ); extBlockStorage = chunk.getBlockStorageArray()[cY]; if (extBlockStorage == null) { extBlockStorage = new ExtendedBlockStorage(cY << 4, !world.provider.hasNoSky); chunk.getBlockStorageArray()[cY] = extBlockStorage; } extBlockStorage.setExtBlockID(localX, y & 15, localZ, blockID); extBlockStorage.setExtBlockMetadata(localX, y & 15, localZ, metadata); } }
package net.java.sip.communicator.impl.media; import java.awt.Component; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import javax.media.*; import javax.media.control.*; import javax.media.format.*; import javax.media.protocol.*; import javax.media.rtp.*; import javax.media.rtp.event.*; import javax.sdp.*; import net.java.sip.communicator.impl.media.codec.*; import net.java.sip.communicator.impl.media.keyshare.*; import net.java.sip.communicator.impl.media.transform.*; import net.java.sip.communicator.impl.media.transform.zrtp.*; import net.java.sip.communicator.service.media.*; import net.java.sip.communicator.service.media.MediaException; import net.java.sip.communicator.service.netaddr.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import gnu.java.zrtp.*; /** * Contains parameters associated with a particular Call such as media (audio * video), a reference to the call itself, RTPManagers and others. * <p> * Currently the class works in the following way: * <p> * We create 2 rtp managers (one for video and one for audio) upon * initialization of this call session and initialize/bind them on local * addresses. * <p> * When we are asked to create an SDP offer we ask the <tt>MediaControl</tt> * for the Formats/Encodings that we support and create a media description that * would advertise these formats as well as the ports that our RTP managers are * bound upon. * <p> * When we need to process an incoming offer we ask the <tt>MediaControl</tt> * for the Formats/Encodings that we support, intersect them with those that * were sent by the offerer and make <tt>MediaControl</tt> configure our source * processor so that it would transmit in the format that it is expected to * according to the format set that resulted from the intersection. We also * prepare our <tt>RTPManager</tt>-s to send streams for every media type * requested in the offer. (Note that these streams are not started until * the associated call enters the CONNECTED state). * <p> * Processing an SDP answer is quite similar to processing an offer with the * exception that the intersection of all supported formats has been performed * bye the remote party and we only need to configure our processor and * <tt>RTPManager</tt>s. * * @author Emil Ivov * @author Damian Minkov * @author Ryan Ricard * @author Ken Larson * @author Dudek Przemyslaw * @author Lubomir Marinov * @author Emanuel Onica */ public class CallSessionImpl implements CallSession , CallParticipantListener , CallChangeListener , ReceiveStreamListener , SendStreamListener , SessionListener , ControllerListener // , SecureEventListener { private static final Logger logger = Logger.getLogger(CallSessionImpl.class); /** * The call associated with this session. */ private final Call call; /** * The session address that is used for audio communication in this call. */ private SessionAddress audioSessionAddress = null; /** * The public address returned by the net address manager for the audio * session address. */ private InetSocketAddress audioPublicAddress = null; /** * The session address that is used for video communication in this call. */ private SessionAddress videoSessionAddress = null; /** * The public address returned by the net address manager for the video * session address. */ private InetSocketAddress videoPublicAddress = null; /** * The rtpManager that handles audio streams in this session. */ private RTPManager audioRtpManager = RTPManager.newInstance(); /** * The rtpManager that handles video streams in this session. */ private RTPManager videoRtpManager = RTPManager.newInstance(); /** * The media service instance that created us. */ private final MediaServiceImpl mediaServCallback; /** * The minimum port number that we'd like our rtp managers to bind upon. */ private static int minPortNumber = 5000; /** * The maximum port number that we'd like our rtp managers to bind upon. */ private static int maxPortNumber = 6000; /** * The name of the property indicating the length of our receive buffer. */ private static final String PROPERTY_NAME_RECEIVE_BUFFER_LENGTH = "net.java.sip.communicator.impl.media.RECEIVE_BUFFER_LENGTH"; /** * The list of currently active players that we have created during this * session. */ private final List<Player> players = new ArrayList<Player>(); private final List<VideoListener> videoListeners = new ArrayList<VideoListener>(); /** * SRTP TransformConnectors corresponding to each RTPManager when SRTP * feature is enabled. */ private final Hashtable<RTPManager, TransformConnector> transConnectors = new Hashtable<RTPManager, TransformConnector>(); /** * Toggles default (from the call start) activation * of secure communication */ private boolean usingZRTP = true; /** * Vector used to hold references of the various key management solutions * that are implemented. For now only ZRTP and dummy (hardcoded keys) are * present. */ private Vector<KeyProviderAlgorithm> keySharingAlgorithms = null; /** * The key management solution type used for the current session */ private KeyProviderAlgorithm selectedKeyProviderAlgorithm = null; /** * The Custom Data Destination used for this call session. */ private final URL dataSink; /** * RFC 4566 specifies that an SDP description may contain a URI with * additional call information. Some servers, such as SEMS use this URI to * deliver a link to a call control page, so in case it is there we better * store it and show it to the user. */ private URL callURL = null; /** * The flag which signals that this side of the call has put the other on * hold. */ private static final byte ON_HOLD_LOCALLY = 1 << 1; /** * The flag which signals that the other side of the call has put this on * hold. */ private static final byte ON_HOLD_REMOTELY = 1 << 2; /** * The flags which determine whether this side of the call has put the other * on hold and whether the other side of the call has put this on hold. */ private byte onHold; private final Map<Component, LocalVisualComponentData> localVisualComponents = new HashMap<Component, LocalVisualComponentData>(); /** * List of RTP format strings which are supported by SIP Communicator in addition * to the JMF standard formats. * * @see #registerCustomCodecFormats(RTPManager) * @see MediaControl#registerCustomCodecs() */ private static final javax.media.Format[] CUSTOM_CODEC_FORMATS = new javax.media.Format[] { // these formats are specific, since RTP uses format numbers with no parameters. new AudioFormat(Constants.ILBC_RTP, 8000.0, 16, 1, AudioFormat.LITTLE_ENDIAN, AudioFormat.SIGNED), new AudioFormat(Constants.ALAW_RTP, 8000, 8, 1, -1, AudioFormat.SIGNED), new AudioFormat(Constants.SPEEX_RTP, 8000, 8, 1, -1, AudioFormat.SIGNED) }; /** * Additional info codes for and data to support ZRTP4J. * These could be added to the library. However they are specific for this * implementation, needing them for various GUI changes. */ public static enum ZRTPCustomInfoCodes { ZRTPNotEnabledByUser, ZRTPDisabledByCallEnd, ZRTPEngineInitFailure, ZRTPEnabledByDefault; } /** * Holds the "Master" ZRTP session. * * This session must be started first and must have negotiated the key material * before any other media session to the same client can be started. See the * ZRTP specification, topic multi-streaming mode. */ private TransformConnector zrtpDHSession = null; /** * JMF stores CUSTOM_CODEC_FORMATS statically, so they only need to be * registered once. FMJ does this dynamically (per instance), so it needs * to be done for every time we instantiate an RTP manager. */ private static boolean formatsRegisteredOnce = false; private static boolean formatsRegisteredOnceVideo = false; /** * The last <code>intendedDestination</code> to which * {@link #allocateMediaPorts(InetAddress)} was applied (and which is * supposedly currently in effect). */ private InetAddress lastIntendedDestination; /** * Creates a new session for the specified <tt>call</tt> with a custom * destination for incoming data. * * @param call The call associated with this session. * @param mediaServCallback the media service instance that created us. * @param dataSink the place to send incoming data. */ public CallSessionImpl(Call call, MediaServiceImpl mediaServCallback, URL dataSink ) { this.call = call; this.mediaServCallback = mediaServCallback; this.dataSink = dataSink; registerCustomCodecFormats(audioRtpManager); // not currently needed, we don't have any custom video formats. registerCustomVideoCodecFormats(videoRtpManager); call.addCallChangeListener(this); initializePortNumbers(); initializeSupportedKeyProviders(); } /** * Creates a new session for the specified <tt>call</tt>. * * @param call The call associated with this session. * @param mediaServCallback the media service instance that created us. */ public CallSessionImpl(Call call, MediaServiceImpl mediaServCallback) { this(call, mediaServCallback, null); } /** * Returns the call associated with this Session. * * @return the Call associated with this session. */ public Call getCall() { return call; } /** * Returns the port that we are using for receiving video data in this * <tt>CallSession</tt>. * <p> * @return the port number we are using for receiving video data in this * <tt>CallSession</tt>. */ public int getVideoPort() { return videoSessionAddress.getDataPort(); } /** * Returns the port that we are using for receiving audio data in this * <tt>CallSession</tt>. * <p> * @return the port number we are using for receiving audio data in this * <tt>CallSession</tt>. */ public int getAudioPort() { return audioSessionAddress.getDataPort(); } /** * Returns the rtp manager that we are using for audio streams. * @return the RTPManager instance that we are using for audio streams. */ public RTPManager getAudioRtpManager() { return this.audioRtpManager; } /** * Returns the rtp manager that we are using for video streams. * @return the RTPManager instance that we are using for audio streams. */ public RTPManager getVideoRtpManager() { return this.videoRtpManager; } /** * Opens all streams that have been initialized for local RTP managers. * * @throws MediaException if start() fails for all send streams. */ private void startStreaming() throws MediaException { //start all audio streams boolean startedAtLeastOneStream = false; RTPManager rtpManager = getAudioRtpManager(); Vector<SendStream> sendStreams = rtpManager.getSendStreams(); if(sendStreams != null && sendStreams.size() > 0) { logger.trace("Will be starting " + sendStreams.size() + " audio send streams."); Iterator<SendStream> ssIter = sendStreams.iterator(); while (ssIter.hasNext()) { SendStream stream = ssIter.next(); try { /** @todo are we sure we want to connect here? */ stream.getDataSource().connect(); stream.start(); startedAtLeastOneStream = true; } catch (IOException ex) { logger.warn("Failed to start stream.", ex); } } } else { logger.trace("No audio send streams will be started."); } //start video streams rtpManager = getVideoRtpManager(); sendStreams = rtpManager.getSendStreams(); if(sendStreams != null && sendStreams.size() > 0) { logger.trace("Will be starting " + sendStreams.size() + " video send streams."); Iterator<SendStream> ssIter = sendStreams.iterator(); while (ssIter.hasNext()) { SendStream stream = (SendStream) ssIter.next(); try { stream.start(); startedAtLeastOneStream = true; } catch (IOException ex) { logger.warn("Failed to start stream.", ex); } } } else { logger.trace("No video send streams will be started."); } if(!startedAtLeastOneStream && sendStreams.size() > 0) { stopStreaming(); throw new MediaException("Failed to start streaming" , MediaException.INTERNAL_ERROR); } } /** * Stops and closes all streams that have been initialized for local * RTP managers. */ public boolean stopStreaming() { boolean stoppedStreaming = false; RTPManager audioRtpManager = getAudioRtpManager(); if (audioRtpManager != null) { stoppedStreaming = stopStreaming(audioRtpManager); this.audioRtpManager = null; } RTPManager videoRtpManager = getVideoRtpManager(); if (videoRtpManager != null) { stoppedStreaming = stopStreaming(videoRtpManager) || stoppedStreaming; this.videoRtpManager = null; } lastIntendedDestination = null; return stoppedStreaming; } /** * Stops and closes all streams currently handled by <tt>rtpManager</tt>. * * @param rtpManager the rtpManager whose streams we'll be stopping. * @return <tt>true</tt> if there was an actual change in the streaming i.e. * the streaming wasn't already stopped before this request; * <tt>false</tt>, otherwise */ private boolean stopStreaming(RTPManager rtpManager) { boolean stoppedAtLeastOneStream = false; Vector<SendStream> sendStreams = rtpManager.getSendStreams(); Iterator<SendStream> ssIter = sendStreams.iterator(); while(ssIter.hasNext()) { SendStream stream = (SendStream) ssIter.next(); try { stream.getDataSource().stop(); stream.stop(); stream.close(); } catch (IOException ex) { logger.warn("Failed to stop stream.", ex); } stoppedAtLeastOneStream = true; } Vector<ReceiveStream> receiveStreams = rtpManager.getReceiveStreams(); Iterator<ReceiveStream> rsIter = receiveStreams.iterator(); while(rsIter.hasNext()) { ReceiveStream stream = rsIter.next(); try { stream.getDataSource().stop(); } catch (IOException ex) { logger.warn("Failed to stop stream.", ex); } stoppedAtLeastOneStream = true; } //remove targets if (selectedKeyProviderAlgorithm != null && selectedKeyProviderAlgorithm.getProviderType() == KeyProviderAlgorithm.ProviderType.ZRTP_PROVIDER) { TransformConnector transConnector = this.transConnectors.get(rtpManager); if (transConnector != null) { if (usingZRTP) { ZRTPTransformEngine engine = (ZRTPTransformEngine) transConnector .getEngine(); engine.stopZrtp(); engine.cleanup(); } transConnector.removeTargets(); } } else { rtpManager.removeTargets("Session ended."); } printFlowStatistics(rtpManager); //stop listening rtpManager.removeReceiveStreamListener(this); rtpManager.removeSendStreamListener(this); rtpManager.removeSessionListener(this); rtpManager.dispose(); return stoppedAtLeastOneStream; } /** * Prints all statistics available for rtpManager. (Method contributed by * Michael Koch). * * @param rtpManager the RTP manager that we'd like to print statistics for. */ private void printFlowStatistics(RTPManager rtpManager) { if(! logger.isDebugEnabled()) return; String rtpManagerDescription = (rtpManager == getAudioRtpManager()) ? "(for audio flows)" : "(for video flows)"; //print flow statistics. GlobalTransmissionStats s = rtpManager.getGlobalTransmissionStats(); logger.debug( "global transmission stats (" + rtpManagerDescription + "): \n" + "bytes sent: " + s.getBytesSent() + "\n" + "local colls: " + s.getLocalColls() + "\n" + "remote colls: " + s.getRemoteColls() + "\n" + "RTCP sent: " + s.getRTCPSent() + "\n" + "RTP sent: " + s.getRTPSent() + "\n" + "transmit failed: " + s.getTransmitFailed() ); GlobalReceptionStats rs = rtpManager.getGlobalReceptionStats(); logger.debug( "global reception stats (" + rtpManagerDescription + "): \n" + "bad RTCP packets: " + rs.getBadRTCPPkts() + "\n" + "bad RTP packets: " + rs.getBadRTPkts() + "\n" + "bytes received: " + rs.getBytesRecd() + "\n" + "local collisions: " + rs.getLocalColls() + "\n" + "malformed BYEs: " + rs.getMalformedBye() + "\n" + "malformed RRs: " + rs.getMalformedRR() + "\n" + "malformed SDESs: " + rs.getMalformedSDES() + "\n" + "malformed SRs: " + rs.getMalformedSR() + "\n" + "packets looped: " + rs.getPacketsLooped() + "\n" + "packets received: " + rs.getPacketsRecd() + "\n" + "remote collisions: " + rs.getRemoteColls() + "\n" + "RTCPs received: " + rs.getRTCPRecd() + "\n" + "SRRs received: " + rs.getSRRecd() + "\n" + "transmit failed: " + rs.getTransmitFailed() + "\n" + "unknown types: " + rs.getUnknownTypes() ); } /** * The method is meant for use by protocol service implementations when * willing to send an invitation to a remote callee. The * resources (address and port) allocated for the <tt>callParticipant</tt> * should be kept by the media service implementation until the originating * <tt>callParticipant</tt> enters the DISCONNECTED state. Subsequent sdp * offers/answers requested for the <tt>Call</tt> that the original * <tt>callParticipant</tt> belonged to MUST receive the same IP/port couple * as the first one in order to allow for conferencing. The associated port * will be released once the call has ended. * * @todo implement ice. * * @return a new SDP description String advertising all params of * <tt>callSession</tt>. * * @throws MediaException code SERVICE_NOT_STARTED if this method is called * before the service was started. */ public String createSdpOffer() throws net.java.sip.communicator.service.media.MediaException { return createSessionDescription(null, null).toString(); } /** * The method is meant for use by protocol service implementations when * willing to send an invitation to a remote callee. The intendedDestination * parameter, may contain the address that the offer is to be sent to. In * case it is null we'll try our best to determine a default local address. * * @param intendedDestination the address of the call participant that the * descriptions is to be sent to. * @return a new SDP description String advertising all params of * <tt>callSession</tt>. * * @throws MediaException code SERVICE_NOT_STARTED if this method is called * before the service was started. */ public String createSdpOffer(InetAddress intendedDestination) throws net.java.sip.communicator.service.media.MediaException { return createSessionDescription(null, intendedDestination).toString(); } /** * The method is meant for use by protocol service implementations when * willing to send an in-dialog invitation to a remote callee to put her * on/off hold or to send an answer to an offer to be put on/off hold. * * @param participantSdpDescription the last SDP description of the remote * callee * @param on <tt>true</tt> if the SDP description should offer the remote * callee to be put on hold or answer an offer from the remote * callee to be put on hold; <tt>false</tt> to work in the * context of a put-off-hold offer * @return an SDP description <tt>String</tt> which offers the remote * callee to be put her on/off hold or answers an offer from the * remote callee to be put on/off hold * @throws MediaException */ public String createSdpDescriptionForHold(String participantSdpDescription, boolean on) throws MediaException { SessionDescription participantDescription = null; try { participantDescription = mediaServCallback.getSdpFactory().createSessionDescription( participantSdpDescription); } catch (SdpParseException ex) { throw new MediaException( "Failed to parse the SDP description of the participant.", MediaException.INTERNAL_ERROR, ex); } SessionDescription sdpOffer = createSessionDescription(participantDescription, null); Vector<MediaDescription> mediaDescriptions = null; try { mediaDescriptions = sdpOffer.getMediaDescriptions(true); } catch (SdpException ex) { throw new MediaException( "Failed to get media descriptions from SDP offer.", MediaException.INTERNAL_ERROR, ex); } for (Iterator<MediaDescription> mediaDescriptionIter = mediaDescriptions.iterator(); mediaDescriptionIter.hasNext();) { MediaDescription mediaDescription = mediaDescriptionIter.next(); Vector<Attribute> attributes = mediaDescription.getAttributes(false); try { modifyMediaDescriptionForHold(on, mediaDescription, attributes); } catch (SdpException ex) { throw new MediaException( "Failed to modify media description for hold.", MediaException.INTERNAL_ERROR, ex); } } try { sdpOffer.setMediaDescriptions(mediaDescriptions); } catch (SdpException ex) { throw new MediaException( "Failed to set media descriptions to SDP offer.", MediaException.INTERNAL_ERROR, ex); } return sdpOffer.toString(); } /** * Modifies the attributes of a specific <tt>MediaDescription</tt> in * order to make them reflect the state of being on/off hold. * * @param onHold <tt>true</tt> if the state described by the modified * <tt>MediaDescription</tt> should reflect being put on hold; * <tt>false</tt> for being put off hold * @param mediaDescription the <tt>MediaDescription</tt> to modify the * attributes of * @param attributes the attributes of <tt>mediaDescription</tt> * @throws SdpException */ private void modifyMediaDescriptionForHold( boolean onHold, MediaDescription mediaDescription, Vector<Attribute> attributes) throws SdpException { /* * The SDP offer to be put on hold represents a transition between * sendrecv and sendonly or between recvonly and inactive depending on * the current state. */ String oldAttribute = onHold ? "recvonly" : "inactive"; String newAttribute = null; if (attributes != null) for (Iterator<Attribute> attributeIter = attributes.iterator(); attributeIter.hasNext();) { String attribute = attributeIter.next().getName(); if (oldAttribute.equalsIgnoreCase(attribute)) newAttribute = onHold ? "inactive" : "recvonly"; } if (newAttribute == null) newAttribute = onHold ? "sendonly" : "sendrecv"; mediaDescription.removeAttribute("inactive"); mediaDescription.removeAttribute("recvonly"); mediaDescription.removeAttribute("sendonly"); mediaDescription.removeAttribute("sendrecv"); mediaDescription.setAttribute(newAttribute, null); } /** * Determines whether a specific SDP description <tt>String</tt> offers * this party to be put on hold. * * @param sdpOffer the SDP description <tt>String</tt> to be examined for * an offer to this party to be put on hold * @return <tt>true</tt> if the specified SDP description <tt>String</tt> * offers this party to be put on hold; <tt>false</tt>, otherwise * @throws MediaException */ public boolean isSdpOfferToHold(String sdpOffer) throws MediaException { SessionDescription description = null; try { description = mediaServCallback.getSdpFactory().createSessionDescription( sdpOffer); } catch (SdpParseException ex) { throw new MediaException("Failed to parse SDP offer.", MediaException.INTERNAL_ERROR, ex); } Vector<MediaDescription> mediaDescriptions = null; try { mediaDescriptions = description.getMediaDescriptions(true); } catch (SdpException ex) { throw new MediaException( "Failed to get media descriptions from SDP offer.", MediaException.INTERNAL_ERROR, ex); } boolean isOfferToHold = true; for (Iterator<MediaDescription> mediaDescriptionIter = mediaDescriptions.iterator(); mediaDescriptionIter.hasNext() && isOfferToHold;) { MediaDescription mediaDescription = (MediaDescription) mediaDescriptionIter.next(); Vector<Attribute> attributes = mediaDescription.getAttributes(false); isOfferToHold = false; if (attributes != null) { for (Iterator<Attribute> attributeIter = attributes.iterator(); attributeIter.hasNext() && !isOfferToHold;) { try { String attribute = attributeIter.next().getName(); if ("sendonly".equalsIgnoreCase(attribute) || "inactive".equalsIgnoreCase(attribute)) { isOfferToHold = true; } } catch (SdpParseException ex) { throw new MediaException( "Failed to get SDP media description attribute name", MediaException.INTERNAL_ERROR, ex); } } } } return isOfferToHold; } /** * Puts the media of this <tt>CallSession</tt> on/off hold depending on * the origin of the request. * <p> * For example, a remote request to have this party put off hold cannot * override an earlier local request to put the remote party on hold. * </p> * * @param on <tt>true</tt> to request the media of this * <tt>CallSession</tt> be put on hold; <tt>false</tt>, * otherwise * @param here <tt>true</tt> if the request comes from this side of the * call; <tt>false</tt> if the remote party is the issuer of * the request i.e. it's the result of a remote offer */ public void putOnHold(boolean on, boolean here) { if (on) { onHold |= (here ? ON_HOLD_LOCALLY : ON_HOLD_REMOTELY); } else { onHold &= ~ (here ? ON_HOLD_LOCALLY : ON_HOLD_REMOTELY); } applyOnHold(); } /** * Applies the current <code>onHold</code> state to the current streaming. */ private void applyOnHold() { // Put the send on/off hold. boolean sendOnHold = (0 != (onHold & (ON_HOLD_LOCALLY | ON_HOLD_REMOTELY))); putOnHold(getAudioRtpManager(), sendOnHold); putOnHold(getVideoRtpManager(), sendOnHold); // Put the receive on/off hold. boolean receiveOnHold = (0 != (onHold & ON_HOLD_LOCALLY)); for (Iterator<Player> playerIter = players.iterator(); playerIter .hasNext();) { Player player = playerIter.next(); if (receiveOnHold) player.stop(); else player.start(); } } /** * Puts a the <tt>SendSteam</tt>s of a specific <tt>RTPManager</tt> * on/off hold i.e. stops/starts them. * * @param rtpManager the <tt>RTPManager</tt> to have its * <tt>SendStream</tt>s on/off hold i.e. stopped/started * @param on <tt>true</tt> to have the <tt>SendStream</tt>s of * <tt>rtpManager</tt> put on hold i.e. stopped; <tt>false</tt>, * otherwise */ private void putOnHold(RTPManager rtpManager, boolean on) { for (Iterator<SendStream> sendStreamIter = rtpManager.getSendStreams().iterator(); sendStreamIter.hasNext();) { SendStream sendStream = sendStreamIter.next(); if (on) { try { sendStream.getDataSource().stop(); sendStream.stop(); } catch (IOException ex) { logger.warn("Failed to stop SendStream.", ex); } } else { try { sendStream.getDataSource().start(); sendStream.start(); } catch (IOException ex) { logger.warn("Failed to start SendStream.", ex); } } } } /** * The method is meant for use by protocol service implementations upon * reception of an SDP answer in response to an offer sent by us earlier. * * @param sdpAnswerStr the SDP answer that we'd like to handle. * @param responder the participant that has sent the answer. * * @throws MediaException code SERVICE_NOT_STARTED if this method is called * before the service was started. * @throws ParseException if sdpAnswerStr does not contain a valid sdp * String. */ public void processSdpAnswer(CallParticipant responder, String sdpAnswerStr) throws MediaException, ParseException { logger.trace("Parsing sdp answer: " + sdpAnswerStr); //first parse the answer SessionDescription sdpAnswer = null; try { sdpAnswer = mediaServCallback.getSdpFactory() .createSessionDescription(sdpAnswerStr); } catch (SdpParseException ex) { throw new ParseException("Failed to parse SDPOffer: " + ex.getMessage() , ex.getCharOffset()); } //extract URI (rfc4566 says that if present it should be before the //media description so let's start with it) setCallURL(sdpAnswer.getURI()); //extract media descriptions Vector<MediaDescription> mediaDescriptions = null; try { mediaDescriptions = sdpAnswer.getMediaDescriptions(true); } catch (SdpException exc) { logger.error("failed to extract media descriptions", exc); throw new MediaException("failed to extract media descriptions" , MediaException.INTERNAL_ERROR , exc); } //add the RTP targets this.initStreamTargets(sdpAnswer.getConnection(), mediaDescriptions); //create and init the streams (don't start streaming just yet but wait //for the call to enter the connected state). createSendStreams(mediaDescriptions); } /** * The method is meant for use by protocol service implementations when * willing to respond to an invitation received from a remote caller. Apart * from simply generating an SDP response description, the method records * details * * @param sdpOfferStr the SDP offer that we'd like to create an answer for. * @param offerer the participant that has sent the offer. * * @return a String containing an SDP answer describing parameters of the * <tt>Call</tt> associated with this session and matching those advertised * by the caller in their <tt>sdpOffer</tt>. * * @throws MediaException code INTERNAL_ERROR if processing the offer and/or * generating the answer fail for some reason. * @throws ParseException if <tt>sdpOfferStr</tt> does not contain a valid * sdp string. */ public String processSdpOffer(CallParticipant offerer, String sdpOfferStr) throws MediaException, ParseException { //first parse the offer SessionDescription sdpOffer = null; try { sdpOffer = mediaServCallback.getSdpFactory() .createSessionDescription(sdpOfferStr); } catch (SdpParseException ex) { throw new ParseException("Failed to parse SDPOffer: " + ex.getMessage() , ex.getCharOffset()); } //create an sdp answer. SessionDescription sdpAnswer = createSessionDescription(sdpOffer, null); //extract the remote addresses. Vector<MediaDescription> mediaDescriptions = null; try { mediaDescriptions = sdpOffer.getMediaDescriptions(true); } catch (SdpException exc) { logger.error("failed to extract media descriptions", exc); throw new MediaException("failed to extract media descriptions" , MediaException.INTERNAL_ERROR , exc); } //add the RTP targets this.initStreamTargets(sdpOffer.getConnection(), mediaDescriptions); //create and init the streams (don't start streaming just yet but wait //for the call to enter the connected state). createSendStreams(mediaDescriptions); return sdpAnswer.toString(); } /** * Tries to extract a java.net.URL from the specified sdpURI param and sets * it as the default call info URL for this call session. * * @param sdpURI the sdp uri as extracted from the call session description. */ private void setCallURL(javax.sdp.URI sdpURI) { if (sdpURI == null) { logger.trace("Call URI was null."); return; } try { this.callURL = sdpURI.get(); } catch (SdpParseException exc) { logger.warn("Failed to parse SDP URI.", exc); } } /** * RFC 4566 specifies that an SDP description may contain a URI (i.r. a * "u=" param ) with additional call information. Some servers, such as * SEMS use this URI to deliver a link to a call control page. This method * returns this call URL or <tt>null</tt> if the call session description * did not contain a "u=" parameter. * * @return a call URL as indicated by the "u=" parameter of the call * session description or null if there was no such parameter. */ public URL getCallInfoURL() { return this.callURL; } /** * Creates a DataSource for all encodings in the mediaDescriptions vector * and initializes send streams in our rtp managers for every stream in the * data source. * @param mediaDescriptions a <tt>Vector</tt> containing * <tt>MediaDescription</tt> instances as sent by the remote side with their * SDP description. * @throws MediaException if we fail to create our data source with the * proper encodings and/or fail to initialize the RTP managers with the * necessary streams and/or don't find encodings supported by both the * remote participant and the local controller. */ private void createSendStreams(Vector<MediaDescription> mediaDescriptions) throws MediaException { //extract the encodings these media descriptions specify Hashtable<String, List<String>> mediaEncodings = extractMediaEncodings(mediaDescriptions); //make our processor output in these encodings. DataSource dataSource = mediaServCallback.getMediaControl(getCall()) .createDataSourceForEncodings(mediaEncodings); //get all the steams that our processor creates as output. PushBufferStream[] streams = ((PushBufferDataSource)dataSource).getStreams(); //for each stream - determine whether it is a video or an audio //stream and assign it to the corresponding rtpmanager for (int i = 0; i < streams.length; i++) { RTPManager rtpManager = null; if(streams[i].getFormat() instanceof VideoFormat) { rtpManager = getVideoRtpManager(); } else if (streams[i].getFormat() instanceof AudioFormat) { rtpManager = getAudioRtpManager(); } else { logger.warn("We are apparently capable of sending a format " + " that is neither videro nor audio. Is " + "this really possible?:" + streams[i].getFormat()); continue; } try { SendStream stream = rtpManager.createSendStream(dataSource, i); logger.trace("Created a send stream for format " + streams[i].getFormat()); } catch (Exception exc) { throw new MediaException( "Failed to create an RTP send stream for format " + streams[i].getFormat() , MediaException.IO_ERROR , exc); } } } /** * Extracts the addresses that our interlocutor has sent for receiving media * and adds them as targets to our RTP manager. * * @param globalConnParam the global <tt>Connection</tt> (if there was one) * specified by our interlocutor outside any media description. * @param mediaDescriptions a Vector containing all media descriptions sent * by our interlocutor, that we'd use to verify whether connection level * parameters have been specified. * * @throws ParseException if there was a problem with the sdp * @throws MediaException if we simply fail to initialize the remote * addresses or set them as targets on our RTPManagers. */ private void initStreamTargets(Connection globalConnParam, Vector<MediaDescription> mediaDescriptions) throws MediaException, ParseException { try { String globalConnectionAddress = null; if (globalConnParam != null) globalConnectionAddress = globalConnParam.getAddress(); Iterator<MediaDescription> mediaDescsIter = mediaDescriptions.iterator(); while (mediaDescsIter.hasNext()) { SessionAddress target = null; MediaDescription mediaDescription = mediaDescsIter.next(); int port = mediaDescription.getMedia().getMediaPort(); String type = mediaDescription.getMedia().getMediaType(); // If there's a global address, we use it. // If there is no global address, we get the address from // the media Description // Fix by Pablo L. - Telefonica String address; if (globalConnectionAddress != null) { address = globalConnectionAddress; } else { address = mediaDescription.getConnection().getAddress(); } //check if we have a media level address Connection mediaLevelConnection = mediaDescription. getConnection(); if (mediaLevelConnection != null) { address = mediaLevelConnection.getAddress(); } InetAddress inetAddress = null; try { inetAddress = NetworkUtils.getInetAddress(address); } catch (UnknownHostException exc) { throw new MediaException( "Failed to resolve address " + address , MediaException.NETWORK_ERROR , exc); } //create the session address for this media type and add it to //the RTPManager. target = new SessionAddress(inetAddress, port); /** @todo the following line assumes that we have a single rtp * manager per media type which is not necessarily true (e.g. we * may have two distinct video streams: 1 for a webcam video and * another one desktop capture stream) */ RTPManager rtpManager = type.equals("video") ? getVideoRtpManager() : getAudioRtpManager(); try { if (selectedKeyProviderAlgorithm != null) { TransformConnector transConnector = this.transConnectors.get(rtpManager); transConnector.addTarget(target); } else { rtpManager.addTarget(target); } logger.trace("added target " + target + " for type " + type); } catch (Throwable exc) { throw new MediaException("Failed to add RTPManager target." , MediaException.INTERNAL_ERROR , exc); } } } catch(SdpParseException exc) { throw new ParseException("Failed to parse SDP data. Error on line " + exc.getLineNumber() + " " + exc.getMessage() , exc.getCharOffset()); } } /** * Creates an SDP description of this session using the offer descirption * (if not null) for limiting. The intendedDestination parameter, which may * contain the address that the offer is to be sent to, will only be used if * the <tt>offer</tt> or its connection parameter are <tt>null</tt>. In the * oposite case we are using the address provided in the connection param as * an intended destination. * * @param offer the call participant meant to receive the offer or null if * we are to construct our own offer. * @param intendedDestination the address of the call participant that the * descriptions is to be sent to. * @return a SessionDescription of this CallSession. * * @throws MediaException code INTERNAL_ERROR if we get an SDP exception * while creating and/or parsing the sdp description. */ private SessionDescription createSessionDescription( SessionDescription offer, InetAddress intendedDestination) throws MediaException { SdpFactory sdpFactory = mediaServCallback.getSdpFactory(); try { SessionDescription sessDescr = sdpFactory.createSessionDescription(); Version v = sdpFactory.createVersion(0); sessDescr.setVersion(v); //we don't yet implement ice so just try to choose a local address //that corresponds to the address provided by the offer or as an //intended destination. NetworkAddressManagerService netAddressManager = MediaActivator.getNetworkAddressManagerService(); if(offer != null) { Connection c = offer.getConnection(); if(c != null) { try { intendedDestination = NetworkUtils.getInetAddress( c.getAddress()); } catch (SdpParseException ex) { logger.warn("error reading remote sdp. " + c.toString() + " is not a valid connection parameter.", ex); } catch (UnknownHostException ex) { logger.warn("error reading remote sdp. " + c.toString() + " does not contain a valid address.", ex); } } //in case the offer contains a media level connection param, it // needs to override the connection one. Iterator<MediaDescription> mediaDescriptions = offer.getMediaDescriptions(true).iterator(); while(mediaDescriptions.hasNext()) { Connection conn = mediaDescriptions.next().getConnection(); if (conn != null) { try { intendedDestination = NetworkUtils.getInetAddress(conn.getAddress()); break; } catch (UnknownHostException e) { logger.debug("Couldn't determine indtended " + "destination from address" + conn.getAddress(), e); } } } } /* * Only allocate ports if this is a call establishing event. The * opposite could happen for example, when issuing a Request.INVITE * that would put a CallParticipant on hold. */ boolean allocateMediaPorts = false; /* * TODO Should the reinitializing for the purposes of re-INVITE * start the streaming before ACK? */ boolean startStreaming = false; if ((audioSessionAddress == null) || (videoSessionAddress == null)) { allocateMediaPorts = true; } else { if (((lastIntendedDestination == null) && (intendedDestination != null)) || ((lastIntendedDestination != null) && !lastIntendedDestination .equals(intendedDestination))) { startStreaming = stopStreaming(); audioRtpManager = RTPManager.newInstance(); videoRtpManager = RTPManager.newInstance(); allocateMediaPorts = true; } } if (allocateMediaPorts) { allocateMediaPorts(intendedDestination); lastIntendedDestination = intendedDestination; if (startStreaming) { startStreaming(); applyOnHold(); } } InetAddress publicIpAddress = audioPublicAddress.getAddress(); String addrType = publicIpAddress instanceof Inet6Address ? Connection.IP6 : Connection.IP4; //spaces in the user name mess everything up. //bug report - Alessandro Melzi Origin o = sdpFactory.createOrigin( call.getProtocolProvider().getAccountID().getUserID() , 0 , 0 , "IN" , addrType , publicIpAddress.getHostAddress()); sessDescr.setOrigin(o); Connection c = sdpFactory.createConnection( "IN" , addrType , publicIpAddress.getHostAddress()); sessDescr.setConnection(c); sessDescr.setSessionName(sdpFactory.createSessionName("-")); //"t=0 0" TimeDescription t = sdpFactory.createTimeDescription(); Vector<TimeDescription> timeDescs = new Vector<TimeDescription>(); timeDescs.add(t); sessDescr.setTimeDescriptions(timeDescs); //media descriptions. Vector<MediaDescription> offeredMediaDescriptions = null; if(offer != null) offeredMediaDescriptions = offer.getMediaDescriptions(false); logger.debug("Will create media descs with: audio public address=" + audioPublicAddress + " and video public address=" + videoPublicAddress); Vector<MediaDescription> mediaDescs = createMediaDescriptions(offeredMediaDescriptions , audioPublicAddress , videoPublicAddress); sessDescr.setMediaDescriptions(mediaDescs); if (logger.isTraceEnabled()) { logger.trace("Generated SDP - " + sessDescr.toString()); } return sessDescr; } catch (SdpException exc) { throw new MediaException( "An SDP exception occurred while generating local " + "sdp description" , MediaException.INTERNAL_ERROR , exc); } } /** * Creates a vector containing SDP descriptions of media types and formats * that we support. If the offerVector is non null * @param offerMediaDescs the media descriptions sent by the offerer (could * be null). * * @param publicAudioAddress the <tt>InetSocketAddress</tt> that we should * be using for sending audio. * @param publicVideoAddress the <tt>InetSocketAddress</tt> that we should * be using for sending video. * * @return a <tt>Vector</tt> containing media descriptions that we support * and (if this is an answer to an offer) that the offering * <tt>CallParticipant</tt> supports as well. * * @throws SdpException we fail creating the media descriptions * @throws MediaException with code UNSUPPORTED_FORMAT_SET_ERROR if we don't * support any of the offered media formats. */ private Vector<MediaDescription> createMediaDescriptions( Vector<MediaDescription> offerMediaDescs, InetSocketAddress publicAudioAddress, InetSocketAddress publicVideoAddress) throws SdpException ,MediaException { MediaControl mediaControl = mediaServCallback.getMediaControl(getCall()); // supported audio formats. String[] supportedAudioEncodings = mediaControl.getSupportedAudioEncodings(); // supported video formats String[] supportedVideoEncodings = mediaControl.getSupportedVideoEncodings(); //if there was an offer extract the offered media formats and use //the intersection between the formats we support and those in the //offer. if (offerMediaDescs != null && offerMediaDescs.size() > 0) { Vector<String> offeredVideoEncodings = new Vector<String>(); Vector<String> offeredAudioEncodings = new Vector<String>(); Iterator<MediaDescription> offerDescsIter = offerMediaDescs.iterator(); while (offerDescsIter.hasNext()) { MediaDescription desc = offerDescsIter.next(); Media media = desc.getMedia(); String mediaType = media.getMediaType(); if (mediaType.equalsIgnoreCase("video")) { offeredVideoEncodings = media.getMediaFormats(true); continue; } if (mediaType.equalsIgnoreCase("audio")) { offeredAudioEncodings = media.getMediaFormats(true); continue; } } //now intersect the offered encodings with what we support Hashtable<String, List<String>> encodings = new Hashtable<String, List<String>>(2); encodings.put("audio", offeredAudioEncodings); encodings.put("video", offeredVideoEncodings); encodings = intersectMediaEncodings(encodings); List<String> intersectedAudioEncsList = (List<String>)encodings.get("audio"); List<String> intersectedVideoEncsList = (List<String>)encodings.get("video"); //now replace the encodings arrays with the intersection supportedAudioEncodings = intersectedAudioEncsList.toArray(new String[0]); supportedVideoEncodings = intersectedVideoEncsList.toArray(new String[0]); } Vector<MediaDescription> mediaDescs = new Vector<MediaDescription>(); if(supportedAudioEncodings.length > 0) { //make sure preferred formats come first MediaDescription am = mediaServCallback.getSdpFactory().createMediaDescription( "audio" , publicAudioAddress.getPort() , 1 , "RTP/AVP" , supportedAudioEncodings); // if we support g723 it is in 6.3 bitrate String g723Str = String.valueOf(SdpConstants.G723); for (int i = 0; i < supportedAudioEncodings.length; i++) { if(supportedAudioEncodings[i].equals(g723Str)) { am.setAttribute("rtpmap", "4 G723/8000"); am.setAttribute("fmtp", "4 annexa=no;bitrate=6.3"); } } byte onHold = this.onHold; if (!mediaServCallback.getDeviceConfiguration() .isAudioCaptureSupported()) { /* We don't have anything to send. */ onHold |= ON_HOLD_REMOTELY; } setAttributeOnHold(am, onHold); // check if ZRTP engine is used and set SDP attribute TransformConnector transConnector = this.transConnectors .get(audioRtpManager); if (transConnector != null) { TransformEngine engine = transConnector.getEngine(); if (engine instanceof ZRTPTransformEngine) { ZRTPTransformEngine ze = (ZRTPTransformEngine) engine; am.setAttribute("zrtp-hash", ze.getHelloHash()); } } mediaDescs.add(am); } if(supportedVideoEncodings.length> 0) { //"m=video 22222 RTP/AVP 34"; MediaDescription vm = mediaServCallback.getSdpFactory().createMediaDescription( "video" , publicVideoAddress.getPort() , 1 , "RTP/AVP" , supportedVideoEncodings); String h264Str = String.valueOf(Constants.H264_RTP_SDP); for (int i = 0; i < supportedVideoEncodings.length; i++) { if(supportedVideoEncodings[i].equals(h264Str)) { vm.setAttribute("rtpmap", Constants.H264_RTP_SDP + " H264/90000"); vm.setAttribute("fmtp", Constants.H264_RTP_SDP + " packetization-mode=1"); } } byte onHold = this.onHold; if (!mediaServCallback.getDeviceConfiguration() .isVideoCaptureSupported()) { /* We don't have anything to send. */ onHold |= ON_HOLD_REMOTELY; } setAttributeOnHold(vm, onHold); // check if ZRTP engine is used and set SDP attribute TransformConnector transConnector = this.transConnectors .get(videoRtpManager); if (transConnector != null) { TransformEngine engine = transConnector.getEngine(); if (engine instanceof ZRTPTransformEngine) { ZRTPTransformEngine ze = (ZRTPTransformEngine) engine; vm.setAttribute("zrtp-hash", ze.getHelloHash()); } } mediaDescs.add(vm); } /** @todo record formats for participant. */ return mediaDescs; } /** * Sets the call-hold related attribute of a specific * <tt>MediaDescription</tt> to a specific value depending on the type of * hold this <tt>CallSession</tt> is currently in. * * @param mediaDescription the <tt>MediaDescription</tt> to set the * call-hold related attribute of * @param onHold the call-hold state of this <tt>CallSession</tt> which is * a combination of {@link #ON_HOLD_LOCALLY} and * {@link #ON_HOLD_REMOTELY} * @throws SdpException */ private void setAttributeOnHold(MediaDescription mediaDescription, byte onHold) throws SdpException { String attribute; if (ON_HOLD_LOCALLY == (onHold & ON_HOLD_LOCALLY)) attribute = (ON_HOLD_REMOTELY == (onHold & ON_HOLD_REMOTELY)) ? "inactive" : "sendonly"; else attribute = (ON_HOLD_REMOTELY == (onHold & ON_HOLD_REMOTELY)) ? "recvonly" : null; if (attribute != null) mediaDescription.setAttribute(attribute, null); } /** * Compares audio/video encodings in the <tt>offeredEncodings</tt> * hashtable with those supported by the currently valid media controller * and returns the set of those that were present in both. The hashtable * a maps "audio"/"video" specifier to a list of encodings present in both * the source <tt>offeredEncodings</tt> hashtable and the list of supported * encodings. * * @param offeredEncodings a Hashtable containing sets of encodings that an * interlocutor has sent to us. * @return a <tt>Hashtable</tt> mapping an "audio"/"video" specifier to a * list of encodings present in both the source <tt>offeredEncodings</tt> * hashtable and the list of encodings supported by the local media * controller. * @throws MediaException code UNSUPPORTED_FORMAT_SET_ERROR if the * intersection of both encoding sets does not contain any elements. */ private Hashtable<String, List<String>> intersectMediaEncodings( Hashtable<String, List<String>> offeredEncodings) throws MediaException { MediaControl mediaControl = mediaServCallback.getMediaControl(getCall()); // audio encodings supported by the media controller String[] supportedAudioEncodings = mediaControl.getSupportedAudioEncodings(); // video encodings supported by the media controller String[] supportedVideoEncodings = mediaControl.getSupportedVideoEncodings(); //audio encodings offered by the remote party List<String> offeredAudioEncodings = offeredEncodings.get("audio"); //video encodings offered by the remote party List<String> offeredVideoEncodings = offeredEncodings.get("video"); //recreate the formats we create according to what the other party // offered. List<String> supportedAudioEncsList = Arrays.asList(supportedAudioEncodings); List<String> intersectedAudioEncsList = new LinkedList<String>(); List<String> supportedVideoEncsList = Arrays.asList(supportedVideoEncodings); List<String> intersectedVideoEncsList = new LinkedList<String>(); //intersect supported audio formats with offered audio formats if (offeredAudioEncodings != null && offeredAudioEncodings.size() > 0) { Iterator<String> offeredAudioEncsIter = offeredAudioEncodings.iterator(); while (offeredAudioEncsIter.hasNext()) { String format = offeredAudioEncsIter.next(); if (supportedAudioEncsList.contains(format)) intersectedAudioEncsList.add(format); } } if (offeredVideoEncodings != null && offeredVideoEncodings.size() > 0) { // intersect supported video formats with offered video formats Iterator<String> offeredVideoEncsIter = offeredVideoEncodings.iterator(); while (offeredVideoEncsIter.hasNext()) { String format = offeredVideoEncsIter.next(); if (supportedVideoEncsList.contains(format)) intersectedVideoEncsList.add(format); } } //if the intersection contains no common formats then we need to //bail. if (intersectedAudioEncsList.size() == 0 && intersectedVideoEncsList.size() == 0) { throw new MediaException( "None of the offered formats was supported by this " + "media implementation" , MediaException.UNSUPPORTED_FORMAT_SET_ERROR); } Hashtable<String, List<String>> intersection = new Hashtable<String, List<String>>(2); intersection.put("audio", intersectedAudioEncsList); intersection.put("video", intersectedVideoEncsList); return intersection; } /** * Returns a <tt>Hashtable</tt> mapping media types (e.g. audio or video) to * lists of JMF encoding strings corresponding to the SDP formats specified * in the <tt>mediaDescriptions</tt> vector. * * @param mediaDescriptions a <tt>Vector</tt> containing * <tt>MediaDescription</tt> instances extracted from an SDP * offer or answer. * @return a <tt>Hashtable</tt> mapping media types (e.g. audio or video) to * lists of JMF encoding strings corresponding to the SDP formats * specified in the <tt>mediaDescriptions</tt> vector. */ private Hashtable<String, List<String>> extractMediaEncodings( Vector<MediaDescription> mediaDescriptions) { Hashtable<String, List<String>> mediaEncodings = new Hashtable<String, List<String>>(2); Iterator<MediaDescription> descriptionsIter = mediaDescriptions.iterator(); while(descriptionsIter.hasNext()) { MediaDescription mediaDescription = descriptionsIter.next(); Media media = mediaDescription.getMedia(); Vector<String> mediaFormats = null; String mediaType = null; try { mediaFormats = media.getMediaFormats(true); mediaType = media.getMediaType(); } catch (SdpParseException ex) { //this shouldn't happen since nist-sdp is not doing //lasy parsing but log anyway logger.warn("Error parsing sdp.",ex); continue; } if(mediaFormats.size() > 0) { List<String> jmfEncodings = MediaUtils.sdpToJmfEncodings(mediaFormats); if(jmfEncodings.size() > 0) mediaEncodings.put(mediaType, jmfEncodings); } } logger.trace("Possible media encodings="+mediaEncodings); return mediaEncodings; } /** * Create the RTP managers and bind them on some ports. */ private void initializePortNumbers() { //first reset to default values minPortNumber = 5000; maxPortNumber = 6000; //then set to anything the user might have specified. String minPortNumberStr = MediaActivator.getConfigurationService() .getString(MediaService.MIN_PORT_NUMBER_PROPERTY_NAME); if (minPortNumberStr != null) { try{ minPortNumber = Integer.parseInt(minPortNumberStr); }catch (NumberFormatException ex){ logger.warn(minPortNumberStr + " is not a valid min port number value. " +"using min port " + minPortNumber); } } String maxPortNumberStr = MediaActivator.getConfigurationService() .getString(MediaService.MAX_PORT_NUMBER_PROPERTY_NAME); if (maxPortNumberStr != null) { try{ maxPortNumber = Integer.parseInt(maxPortNumberStr); }catch (NumberFormatException ex){ logger.warn(maxPortNumberStr + " is not a valid max port number value. " +"using max port " + maxPortNumber, ex); } } } /** * Allocates a local port for the RTP manager, tries to obtain a public * address for it and after succeeding makes the network address manager * protect the address until we are ready to bind on it. * * @param intendedDestination a destination that the rtp manager would be * communicating with. * @param sessionAddress the sessionAddress that we're locally bound on. * @param bindRetries the number of times that we need to retry a bind. * * @return the SocketAddress the public address that the network address * manager returned for the session address that we're bound on. * * @throws MediaException if we fail to initialize rtp manager. */ private InetSocketAddress allocatePort(InetAddress intendedDestination, SessionAddress sessionAddress, int bindRetries) throws MediaException { InetSocketAddress publicAddress = null; boolean initialized = false; NetworkAddressManagerService netAddressManager = MediaActivator.getNetworkAddressManagerService(); //try to initialize a public address for the rtp manager. for (int i = bindRetries; i > 0; i { // first try to obtain a binding for the address. // check both ports - data and control port try { publicAddress = netAddressManager.getPublicAddressFor( intendedDestination, sessionAddress.getDataPort()); // Just check control port, not used here any further netAddressManager.getPublicAddressFor( intendedDestination, sessionAddress.getControlPort()); initialized =true; break; } catch (IOException ex) { logger.warn("Retrying a bind because of a failure. " + "Failed Address is: " + sessionAddress.toString(), ex); //reinit the session address we tried with and prepare to retry. sessionAddress .setDataPort(sessionAddress.getDataPort()+2); sessionAddress .setControlPort(sessionAddress.getControlPort()+2); } } if(!initialized) throw new MediaException("Failed to bind to a local port in " + Integer.toString(bindRetries) + " tries." , MediaException.INTERNAL_ERROR); return publicAddress; } /** * Looks for free ports and initializes the RTP manager according toe the * specified <tt>intendedDestination</tt>. * * @param intendedDestination the InetAddress that we will be transmitting * to. * @throws MediaException if we fail initializing the RTP managers. */ private void allocateMediaPorts(InetAddress intendedDestination) throws MediaException { NetworkAddressManagerService netAddressManager = MediaActivator .getNetworkAddressManagerService(); // Get our local address for the intended destination. // Use this address to bind our local RTP sockets InetAddress inAddrLocal = netAddressManager.getLocalHost(intendedDestination); //check the number of times that we'd have to retry binding to local //ports before giving up. String bindRetriesStr = MediaActivator.getConfigurationService().getString( MediaService.BIND_RETRIES_PROPERTY_NAME); int bindRetries = MediaService.BIND_RETRIES_DEFAULT_VALUE; try { if(bindRetriesStr != null && bindRetriesStr.length() > 0) bindRetries = Integer.parseInt(bindRetriesStr); } catch (NumberFormatException ex) { logger.warn(bindRetriesStr + " is not a valid value for number of bind retries." , ex); } //initialize audio rtp manager. audioSessionAddress = new SessionAddress(inAddrLocal, minPortNumber); audioPublicAddress = allocatePort(intendedDestination, audioSessionAddress, bindRetries); if (logger.isDebugEnabled()) { logger.debug("AudioSessionAddress=" + audioSessionAddress); logger.debug("AudioPublicAddress=" + audioPublicAddress); } //augment min port number so that no one else tries to bind here. minPortNumber = audioSessionAddress.getDataPort() + 2; //initialize video rtp manager. videoSessionAddress = new SessionAddress(inAddrLocal, minPortNumber); videoPublicAddress = allocatePort(intendedDestination, videoSessionAddress, bindRetries); //augment min port number so that no one else tries to bind here. minPortNumber = videoSessionAddress.getDataPort() + 2; //if we have reached the max port number - reinit. if(minPortNumber > maxPortNumber -2) initializePortNumbers(); //now init the rtp managers and make them bind initializeRtpManager(audioRtpManager, audioSessionAddress); initializeRtpManager(videoRtpManager, videoSessionAddress); } /** * Initializes the RTP manager so that it would start listening on the * <tt>address</tt> session address. The method also initializes the RTP * manager buffer control. * * @param rtpManager the <tt>RTPManager</tt> to initialize. * @param bindAddress the <tt>SessionAddress</tt> to use when initializing * the RTPManager. * * @throws MediaException if we fail to initialize the RTP manager. */ private void initializeRtpManager(RTPManager rtpManager, SessionAddress bindAddress) throws MediaException { /* Select a key management type from the present ones to use * for now using the zero - top priority solution (ZRTP); * TODO: should be extended to a selection algorithm to choose the * key management type */ selectedKeyProviderAlgorithm = selectKeyProviderAlgorithm(0); try { // Selected key management type == ZRTP branch if (selectedKeyProviderAlgorithm != null && selectedKeyProviderAlgorithm.getProviderType() == KeyProviderAlgorithm.ProviderType.ZRTP_PROVIDER) { TransformManager.initializeProviders(); // The connector is created based also on the crypto services // The crypto provider solution should be queried somehow // or taken from a resources file TransformConnector transConnector = TransformManager.createZRTPConnector( bindAddress, "BouncyCastle", this); rtpManager.initialize(transConnector); this.transConnectors.put(rtpManager, transConnector); SCCallback callback = new SCCallback(this); boolean zrtpAutoStart = false; // Decide if this will become the ZRTP Master session: // - Statement: audio media session will be started before video media session // - if no other audio session was started before then this will become // ZRTP Master session // - only the ZRTP master sessions start in "auto-sensing" mode to // immediately catch ZRTP communication from other client // - after the master session has completed its key negotiation it will // start other media sessions (see SCCallback) if (rtpManager.equals(audioRtpManager)) { if (zrtpDHSession == null) { zrtpDHSession = transConnector; zrtpAutoStart = true; callback.setDHSession(true); } callback.setType(SecurityGUIEventZrtp.AUDIO); } else if (rtpManager.equals(videoRtpManager)) { callback.setType(SecurityGUIEventZrtp.VIDEO); } // ZRTP engine initialization ZRTPTransformEngine engine = (ZRTPTransformEngine)transConnector.getEngine(); engine.setUserCallback(callback); // Case 1: user toggled secure communication prior to the call // call is encrypted by default due to the option set in // the account registration wizard if (this.getCall().isDefaultEncrypted()) { if (engine.initialize("GNUZRTP4J.zid", zrtpAutoStart)) { usingZRTP = true; engine.sendInfo( ZrtpCodes.MessageSeverity.Info, EnumSet.of( ZRTPCustomInfoCodes.ZRTPEnabledByDefault)); } else { engine.sendInfo(ZrtpCodes.MessageSeverity.Info, EnumSet.of(ZRTPCustomInfoCodes.ZRTPEngineInitFailure)); } } // Case 2: user will toggle secure communication during the call // (it's not set on at this point) else { engine.sendInfo( ZrtpCodes.MessageSeverity.Info, EnumSet.of(ZRTPCustomInfoCodes.ZRTPNotEnabledByUser)); } logger.trace( "RTP" + (rtpManager.equals(audioRtpManager)?" audio ":"video") + "manager initialized through connector"); } // else // // Selected key management type == Dummy branch - hardcoded keys // if (selectedKeyProviderAlgorithm != null && // selectedKeyProviderAlgorithm.getProviderType() == // KeyProviderAlgorithm.ProviderType.DUMMY_PROVIDER // /* TODO: Video securing related code // * remove the next condition as part of enabling video securing // * (see comments in secureStatusChanged method for more info) // */ // && rtpManager.equals(audioRtpManager)) // SRTPPolicy srtpPolicy = new SRTPPolicy( // SRTPPolicy.AESF8_ENCRYPTION, 16, // SRTPPolicy.HMACSHA1_AUTHENTICATION, 20, 10, 14); // // Master key and master salt are hardcoded // byte[] masterKey = // {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; // byte[] masterSalt = // {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d}; // TransformConnector transConnector = null; // TransformManager.initializeProviders(); // // The connector is created based also on the crypto services // // provider type; // // The crypto provider solution should be queried somehow // // or taken from a resources file // transConnector = // TransformManager.createSRTPConnector(bindAddress, // masterKey, // masterSalt, // srtpPolicy, // srtpPolicy, // "BouncyCastle"); // rtpManager.initialize(transConnector); // this.transConnectors.put(rtpManager, transConnector); // logger.trace("RTP"+ // (rtpManager.equals(audioRtpManager)?" audio ":"video")+ // "manager initialized through connector"); // // No key management solution - unsecure communication branch else { rtpManager.initialize(bindAddress); logger.trace("RTP"+ (rtpManager.equals(audioRtpManager)?" audio ":"video")+ "manager initialized normally"); } } catch (Exception exc) { exc.printStackTrace(); logger.error("Failed to init an RTP manager.", exc); throw new MediaException("Failed to init an RTP manager." , MediaException.IO_ERROR , exc); } //it appears that if we don't do this managers don't play // You can try out some other buffer size to see // if you can get better smoothness. BufferControl bc = (BufferControl)rtpManager .getControl(BufferControl.class.getName()); if (bc != null) { long buff = 100; String buffStr = MediaActivator.getConfigurationService() .getString(PROPERTY_NAME_RECEIVE_BUFFER_LENGTH); try { if(buffStr != null && buffStr.length() > 0) buff = Long.parseLong(buffStr); } catch (NumberFormatException exc) { logger.warn(buffStr + " is not a valid receive buffer value (integer)." , exc); } buff = bc.setBufferLength(buff); logger.trace("set receiver buffer len to=" + buff); bc.setEnabledThreshold(true); bc.setMinimumThreshold(100); } //add listeners rtpManager.addReceiveStreamListener(this); rtpManager.addSendStreamListener(this); rtpManager.addSessionListener(this); } /** * Registers the RTP formats which are supported by SIP Communicator in * addition to the JMF standard formats. This has to be done for every RTP * Manager instance. * <p> * JMF stores this statically, so it only has to be done once. FMJ does it * dynamically (per instance, so it needs to be done for each instance. * <p> * @param rtpManager The manager with which to register the formats. * @see MediaControl#registerCustomCodecs() */ static void registerCustomCodecFormats(RTPManager rtpManager) { // if we have already registered custom formats and we are running JMF // we bail out. if (!FMJConditionals.REGISTER_FORMATS_WITH_EVERY_RTP_MANAGER && formatsRegisteredOnce) { return; } for (int i=0; i<CUSTOM_CODEC_FORMATS.length; i++) { javax.media.Format format = CUSTOM_CODEC_FORMATS[i]; logger.debug("registering format " + format + " with RTP manager"); /* * NOTE (mkoch@rowa.de): com.sun.media.rtp.RtpSessionMgr.addFormat * leaks memory, since it stores the Format in a static Vector. * AFAIK there is no easy way around it, but the memory impact * should not be too bad. */ rtpManager.addFormat( format, MediaUtils.jmfToSdpEncoding(format.getEncoding())); } formatsRegisteredOnce = true; } static void registerCustomVideoCodecFormats(RTPManager rtpManager) { // if we have already registered custom formats and we are running JMF // we bail out. if (!FMJConditionals.REGISTER_FORMATS_WITH_EVERY_RTP_MANAGER && formatsRegisteredOnceVideo) { return; } javax.media.Format format = new VideoFormat(Constants.H264_RTP); logger.debug("registering format " + format + " with RTP manager"); /* * NOTE (mkoch@rowa.de): com.sun.media.rtp.RtpSessionMgr.addFormat * leaks memory, since it stores the Format in a static Vector. * AFAIK there is no easy way around it, but the memory impact * should not be too bad. */ rtpManager.addFormat( format, MediaUtils.jmfToSdpEncoding(format.getEncoding())); formatsRegisteredOnceVideo = true; } /** * Indicates that a change has occurred in the state of the source call. * * @param evt the <tt>CallChangeEvent</tt> instance containing the source * calls and its old and new state. */ public void callStateChanged(CallChangeEvent evt) { Object newValue = evt.getNewValue(); if (newValue == evt.getOldValue()) { if (logger.isDebugEnabled()) { logger.debug("Ignoring call state change from " + newValue + " to the same state."); } return; } if (newValue == CallState.CALL_IN_PROGRESS) { try { logger.debug("call connected. starting streaming"); startStreaming(); mediaServCallback.getMediaControl(getCall()) .startProcessingMedia(this); } catch (MediaException ex) { /** @todo need to notify someone */ logger.error("Failed to start streaming.", ex); } } else if (newValue == CallState.CALL_ENDED) { logger.warn("Stopping streaming."); stopStreaming(); mediaServCallback.getMediaControl(getCall()).stopProcessingMedia( this); // close all players that we have created in this session Iterator<Player> playersIter = players.iterator(); while (playersIter.hasNext()) { Player player = playersIter.next(); player.stop(); /* * The player is being disposed so let the (interested) * listeners know its Player#getVisualComponent() (if any) * should be released. */ Component visualComponent = getVisualComponent(player); if (visualComponent != null) { fireVideoEvent(VideoEvent.VIDEO_REMOVED, visualComponent, VideoEvent.REMOTE); } player.deallocate(); player.close(); playersIter.remove(); } // remove ourselves as listeners from the call evt.getSourceCall().removeCallChangeListener(this); /* * The disposal of the audio and video RTPManager which used to be * here shouldn't be necessary because #stopStreaming() should've * already take care of it. */ } } /** * Indicates that a change has occurred in the status of the source * CallParticipant. * * @param evt The <tt>CallParticipantChangeEvent</tt> instance containing * the source event as well as its previous and its new status. */ public void participantStateChanged(CallParticipantChangeEvent evt) { /** @todo implement participantStateChanged() */ /** @todo remove target for participant. */ } /** * Indicates that a new call participant has joined the source call. * @param evt the <tt>CallParticipantEvent</tt> containing the source call * and call participant. */ public synchronized void callParticipantAdded(CallParticipantEvent evt) { CallParticipant sourceParticipant = evt.getSourceCallParticipant(); sourceParticipant.addCallParticipantListener(this); } /** * Indicates that a call participant has left the source call. * @param evt the <tt>CallParticipantEvent</tt> containing the source call * and call participant. */ public void callParticipantRemoved(CallParticipantEvent evt) { } /** * Ignore - we're not concerned by this event inside a call session. * * @param evt ignore. */ public void participantImageChanged(CallParticipantChangeEvent evt) { } /** * Ignore - we're not concerned by this event inside a call session. * * @param evt ignore. */ public void participantDisplayNameChanged(CallParticipantChangeEvent evt) { } /** * Ignore - we're not concerned by this event inside a call session. * * @param evt ignore. */ public void participantTransportAddressChanged( CallParticipantChangeEvent evt) { /** @todo i am not sure we should be ignoring this one ... */ } /** * Ignore - we're not concerned by this event inside a call session. * * @param evt ignore. */ public void participantAddressChanged(CallParticipantChangeEvent evt) { } //implementation of jmf listener methods /** * Method called back in the SessionListener to notify * listener of all Session Events.SessionEvents could be one * of NewParticipantEvent or LocalCollisionEvent. * * @param event the newly received SessionEvent */ public synchronized void update(SessionEvent event) { if (event instanceof NewParticipantEvent) { Participant participant = ( (NewParticipantEvent) event).getParticipant(); if (logger.isDebugEnabled()) { logger.debug("A new participant had just joined: " + participant.getCNAME()); } } else { if (logger.isDebugEnabled()) { logger.debug( "Received the following JMF Session event - " + event.getClass().getName() + "=" + event); } } } /** * Method called back in the RTPSessionListener to notify * listener of all SendStream Events. * * @param event the newly received SendStreamEvent */ public synchronized void update(SendStreamEvent event) { logger.debug( "received the following JMF SendStreamEvent - " + event.getClass().getName() + "="+ event); } /** * Method called back in the RTPSessionListener to notify * listener of all ReceiveStream Events. * * @param evt the newly received ReceiveStreamEvent */ public synchronized void update(ReceiveStreamEvent evt) { Participant participant = evt.getParticipant(); // could be null. ReceiveStream stream = evt.getReceiveStream(); // could be null. if (evt instanceof NewReceiveStreamEvent) { try { logger.debug("received a new incoming stream. " + evt); DataSource ds = stream.getDataSource(); // Find out the formats. RTPControl ctl = (RTPControl) ds.getControl( "javax.media.rtp.RTPControl"); if (logger.isDebugEnabled()) { if (ctl != null) { logger.debug("Received new RTP stream: " + ctl.getFormat()); } else { logger.debug("Received new RTP stream"); } } Player player = null; //if we are using a custom destination, create a processor //if not, a player will suffice if (dataSink != null) { player = Manager.createProcessor(ds); } else { player = Manager.createPlayer(ds); } player.addControllerListener(this); //a processor needs to be configured then realized. if (dataSink != null) { ((Processor)player).configure(); } else { player.realize(); } players.add(player); } catch (Exception e) { logger.error("NewReceiveStreamEvent exception ", e); return; } } else if (evt instanceof StreamMappedEvent) { if (stream != null && stream.getDataSource() != null) { DataSource ds = stream.getDataSource(); // Find out the formats. RTPControl ctl = (RTPControl) ds.getControl( "javax.media.rtp.RTPControl"); if (logger.isDebugEnabled()) { String msg = "The previously unidentified stream "; if (ctl != null) { msg += ctl.getFormat(); } msg += " had now been identified as sent by: " + participant.getCNAME(); logger.debug(msg); } } } else if (evt instanceof ByeEvent) { logger.debug("Got \"bye\" from: " + participant.getCNAME()); } } /** * This method is called when an event is generated by a * <code>Controller</code> that this listener is registered with. * * @param ce The event generated. */ public synchronized void controllerUpdate(ControllerEvent ce) { logger.debug("Received a ControllerEvent: " + ce); Player player = (Player) ce.getSourceController(); if (player == null) { return; } // if configuration is completed and this is a processor // we need to set file format and explicitly call realize(). if (ce instanceof ConfigureCompleteEvent) { try { ((Processor) player) .setContentDescriptor(new FileTypeDescriptor( FileTypeDescriptor.WAVE)); player.realize(); } catch (Exception exc) { logger.error("failed to record to file", exc); } } // Get this when the internal players are realized. else if (ce instanceof RealizeCompleteEvent) { // set the volume as it is not on max by default. // XXX: I am commenting this since apparently it is causing some // problems on windows. // GainControl gc // = (GainControl)player.getControl(GainControl.class.getName()); // if (gc != null) // logger.debug("Setting volume to max"); // gc.setLevel(1); // else // logger.debug("Player does not have gain control."); logger.debug("A player was realized and will be started."); player.start(); if (dataSink != null) { try { logger.info("starting recording to file: " + dataSink); MediaLocator dest = new MediaLocator(dataSink); DataSink sink = Manager.createDataSink(((Processor) player) .getDataOutput(), dest); player.start(); // do we know the output file's duration RecordInitiator record = new RecordInitiator(sink); record.start(); } catch (Exception e) { logger.error("failed while trying to record to file", e); } } else { player.start(); } Component visualComponent = player.getVisualComponent(); if (visualComponent != null) { fireVideoEvent(VideoEvent.VIDEO_ADDED, visualComponent, VideoEvent.REMOTE); } } else if (ce instanceof StartEvent) { logger.debug("Received a StartEvent"); } else if (ce instanceof ControllerErrorEvent) { logger .error("The following error was reported while starting a player" + ce); } else if (ce instanceof ControllerClosedEvent) { /* * XXX ControllerClosedEvent is the super of ControllerErrorEvent so * the check for the latter should be kept in front of the check for * the former. */ logger.debug("Received a ControllerClosedEvent"); } } /** * The record initiator is started after taking a call that is supposed to * be answered by a mailbox plug-in. It waits for the outgoing message to * stop transmitting and starts recording whatever comes after that. */ private class RecordInitiator extends Thread { private DataSink sink; public RecordInitiator(DataSink sink) { this.sink = sink; } public void run() { //determine how long to wait for the outgoing //message to stop playing javax.media.Time timeToWait = mediaServCallback .getMediaControl(call) .getOutputDuration(); //if the time is unknown, we will start recording immediately if (timeToWait != javax.media.Time.TIME_UNKNOWN) { double millisToWait = timeToWait.getSeconds() * 1000; long timeStartedPlaying = System.currentTimeMillis(); while (System.currentTimeMillis() < timeStartedPlaying + millisToWait) { try { Thread.sleep(100); } catch (InterruptedException e) { logger.error("Interrupted while waiting to start " + "recording incoming message",e); } } } //open the dataSink and start recording try { sink.open(); sink.start(); } catch (IOException e) { logger.error("IO Exception while attempting to start " + "recording incoming message",e); } } } /** * Method for getting the default secure status value for communication * * @return the default enabled/disabled status value for secure * communication */ public boolean getSecureCommunicationStatus() { return usingZRTP; } /** * Method for setting the default secure status value for communication * Also has the role to trigger going secure from not secure or viceversa * Notifies any present CallSession of change in the status value for this * purpose * * @param activator setting for default communication securing * @param source the source of changing the secure status (local or remote) */ public void setSecureCommunicationStatus(boolean activator, OperationSetSecureTelephony. SecureStatusChangeSource source) { logger.trace("Call session secure status change event received"); // Make the change for default security enabled/disabled start option usingZRTP = activator; // Fire the change event to notify any present CallSession of security // change status // if not the case of a reverted secure state // (usually case of previous change rejected due to an error) if (source != OperationSetSecureTelephony. SecureStatusChangeSource.SECURE_STATUS_REVERTED) { SecureEvent secureEvent = null; if (activator) { secureEvent = new SecureEvent(this, SecureEvent.SECURE_COMMUNICATION, source); } else { secureEvent = new SecureEvent(this, SecureEvent.UNSECURE_COMMUNICATION, source); } if (selectedKeyProviderAlgorithm.getProviderType() == KeyProviderAlgorithm.ProviderType.ZRTP_PROVIDER) { zrtpChangeStatus(this.audioRtpManager, secureEvent); /* TODO: Video securing related code * * We disable for the moment the video securing due to (yet) * unsuported multistream mode in ZRTP4J; This can be re-enabled and * attempted as is implemented, using a separate instance of ZRTP * engine which will attempt securing through DH mode; This might * result in some unexpected behavior at the GUI level, but in * theory should work; However, due to incomplete standard * compliance and potential problems mentioned we leave it disabled; * To enable just check the other "Video securing related code" * sections in this source * * Uncomment the next line as part of enabling video securing */ //zrtpChangeStatus(this.videoRtpManager, secureEvent); } } } /* * The following methods are specific to ZRTP key management implementation. */ /* * (non-Javadoc) * @see net.java.sip.communicator.service.media.CallSession#setZrtpSASVerification(boolean) */ public boolean setZrtpSASVerification(boolean verified) { ZRTPTransformEngine engine = (ZRTPTransformEngine) zrtpDHSession .getEngine(); if (verified) { engine.SASVerified(); } else { engine.resetSASVerified(); } return true; } /** * The method for changing security status for a specific RTPManager when * the ZRTP key sharing solution is used. * Called when a new SecureEvent is received. * * @param manager The RTP manager for which the media streams * will be secure or unsecure * @param event The secure status changed event */ private void zrtpChangeStatus(RTPManager manager, SecureEvent event) { int newStatus = event.getEventID(); OperationSetSecureTelephony.SecureStatusChangeSource source = event.getSource(); TransformConnector transConnector = this.transConnectors.get(manager); ZRTPTransformEngine engine = (ZRTPTransformEngine)transConnector.getEngine(); // Perform ZRTP engine actions only if triggered by user commands; // If the remote peer caused the event only general call session //security status is changed (done before event processing) if (source == OperationSetSecureTelephony. SecureStatusChangeSource.SECURE_STATUS_CHANGE_BY_LOCAL) { if (newStatus == SecureEvent.SECURE_COMMUNICATION) { // Secure the comm after the call begins if (!engine.isStarted()) { logger.trace("Normal call securing event processing"); if (!engine.initialize("GNUZRTP4J.zid")) { engine.sendInfo( ZrtpCodes.MessageSeverity.Info, EnumSet.of( ZRTPCustomInfoCodes.ZRTPEngineInitFailure)); } } } } } /** * Start multi-stream ZRTP sessions. * * After the ZRTP Master (DH) session reached secure state the SCCallback calls * this method to start the multi-stream ZRTP sessions. * * First get the multi-stream data from the ZRTP DH session. Then iterate over * all known connectors, set multi-stream mode data, and enable auto-start * mode (auto-sensing). * * @return Number of started ZRTP multi-stream mode sessions */ public int startZrtpMultiStreams() { ZRTPTransformEngine engine = (ZRTPTransformEngine)zrtpDHSession.getEngine(); int counter = 0; byte[] multiStreamData = engine.getMultiStrParams(); Enumeration<TransformConnector> tcs = transConnectors.elements(); while (tcs.hasMoreElements()) { TransformConnector tc = tcs.nextElement(); if (tc.equals(zrtpDHSession)) { continue; } engine = (ZRTPTransformEngine)tc.getEngine(); engine.setMultiStrParams(multiStreamData); engine.setEnableZrtp(true); counter++; } return counter; } /** * Initializes the supported key management types and establishes * default usage priorities for them. * This part should be further developed (by adding a more detailed * priority setting mechanism in case of addition of other security * providers). */ public void initializeSupportedKeyProviders() { if (keySharingAlgorithms == null) keySharingAlgorithms = new Vector<KeyProviderAlgorithm>(); DummyKeyProvider dummyProvider = new DummyKeyProvider(1); ZRTPKeyProvider zrtpKeyProvider = new ZRTPKeyProvider(0); keySharingAlgorithms.add( zrtpKeyProvider.getPriority(), zrtpKeyProvider); keySharingAlgorithms.add(dummyProvider.getPriority(), dummyProvider); } /** * Selects a default key management type to use in securing based * on which the actual implementation for that solution will be started * This part should be further developed (by adding a more detailed * priority choosing mechanism in case of addition of other security * providers). * * @return the default keymanagement type used in securing */ public KeyProviderAlgorithm selectDefaultKeyProviderAlgorithm() { KeyProviderAlgorithm defaultProvider = keySharingAlgorithms.get(0); return (defaultProvider == null) ? new DummyKeyProvider(0) : defaultProvider; } /** * Selects a key management type to use in securing based on priority * For now the priorities are equal with the position in the Vector * holding the keymanagement types. * This part should be further developed (by adding a more detailed * priority choosing mechanism in case of addition of other security * providers). * * @param priority the priority of the selected key management type with * 0 indicating top priority * @return the selected key management type */ public KeyProviderAlgorithm selectKeyProviderAlgorithm(int priority) { return keySharingAlgorithms.get(priority); } /** * Determines whether the audio of this session is (set to) mute. * * @return <tt>true</tt> if the audio of this session is (set to) mute; * otherwise, <tt>false</tt> */ public boolean isMute() { return mediaServCallback.getMediaControl(getCall()).isMute(); } /** * Sets the mute state of the audio of this session. * * @param mute <tt>true</tt> to mute the audio of this session; otherwise, * <tt>false</tt> */ public void setMute(boolean mute) { mediaServCallback.getMediaControl(getCall()).setMute(mute); } public void addVideoListener(VideoListener listener) { if (listener == null) throw new NullPointerException("listener"); synchronized (videoListeners) { if (!videoListeners.contains(listener)) videoListeners.add(listener); } } public Component createLocalVisualComponent(final VideoListener listener) throws MediaException { DataSource dataSource = mediaServCallback.getMediaControl(getCall()) .createLocalVideoDataSource(); if (dataSource != null) { Player player; try { player = Manager.createPlayer(dataSource); } catch (IOException ex) { throw new MediaException( "Failed to create Player for local video DataSource.", MediaException.IO_ERROR, ex); } catch (NoPlayerException ex) { throw new MediaException( "Failed to create Player for local video DataSource.", MediaException.INTERNAL_ERROR, ex); } player.addControllerListener(new ControllerListener() { public void controllerUpdate(ControllerEvent event) { controllerUpdateForCreateLocalVisualComponent(event, listener); } }); player.start(); } return null; } private void controllerUpdateForCreateLocalVisualComponent( ControllerEvent controllerEvent, VideoListener listener) { if (controllerEvent instanceof RealizeCompleteEvent) { Player player = (Player) controllerEvent.getSourceController(); Component visualComponent = player.getVisualComponent(); if (visualComponent != null) { VideoEvent videoEvent = new VideoEvent(this, VideoEvent.VIDEO_ADDED, visualComponent, VideoEvent.LOCAL); listener.videoAdded(videoEvent); if (videoEvent.isConsumed()) { localVisualComponents.put(visualComponent, new LocalVisualComponentData(player, listener)); } } } } public void disposeLocalVisualComponent(Component component) { if (component == null) throw new IllegalArgumentException("component"); LocalVisualComponentData data = localVisualComponents.get(component); if (data != null) { Player player = data.player; player.stop(); player.deallocate(); player.close(); localVisualComponents.remove(component); VideoListener listener = data.listener; if (listener != null) { VideoEvent videoEvent = new VideoEvent(this, VideoEvent.VIDEO_REMOVED, component, VideoEvent.LOCAL); listener.videoRemoved(videoEvent); } } } /* * Gets the visual Components of the #players of this CallSession by calling * Player#getVisualComponent(). Ignores the failures to access the visual * Components of unrealized Players. */ public Component[] getVisualComponents() { List<Component> visualComponents = new ArrayList<Component>(); for (Iterator<Player> playerIter = players.iterator(); playerIter .hasNext();) { Component visualComponent = getVisualComponent(playerIter.next()); if (visualComponent != null) visualComponents.add(visualComponent); } return visualComponents.toArray(new Component[visualComponents.size()]); } /** * Gets the visual <code>Component</code> of a specific <code>Player</code> * if it has one and ignores the failure to access it if the specified * <code>Player</code> is unrealized. * * @param player the <code>Player</code> to get the visual * <code>Component</code> of if it has one * @return the visual <code>Component</code> of the specified * <code>Player</code> if it has one; <tt>null</tt> if the specified * <code>Player</code> does not have a visual <code>Component</code> * or the <code>Player</code> is unrealized */ private Component getVisualComponent(Player player) { Component visualComponent; try { visualComponent = player.getVisualComponent(); } catch (NotRealizedError e) { visualComponent = null; if (logger.isDebugEnabled()) { logger .debug("Called Player#getVisualComponent() on Unrealized player " + player); } } return visualComponent; } public void removeVideoListener(VideoListener listener) { videoListeners.remove(listener); } /** * Notifies the <code>VideoListener</code>s registered with this * <code>CallSession</code> about a specific type of change in the * availability of a specific visual <code>Component</code> depicting video. * * @param type the type of change as defined by <code>VideoEvent</code> in * the availability of the specified visual * <code>Component</code> depciting video * @param visualComponent the visual <code>Component</code> depicting video * which has been added or removed in this * <code>CallSession</code> * @param origin */ protected void fireVideoEvent(int type, Component visualComponent, int origin) { VideoListener[] listeners; synchronized (videoListeners) { listeners = videoListeners .toArray(new VideoListener[videoListeners.size()]); } if (listeners.length > 0) { VideoEvent event = new VideoEvent(this, type, visualComponent, origin); for (int listenerIndex = 0; listenerIndex < listeners.length; listenerIndex++) { VideoListener listener = listeners[listenerIndex]; switch (type) { case VideoEvent.VIDEO_ADDED: listener.videoAdded(event); break; case VideoEvent.VIDEO_REMOVED: listener.videoRemoved(event); break; } } } } private static class LocalVisualComponentData { public final VideoListener listener; public final Player player; public LocalVisualComponentData(Player player, VideoListener listener) { this.player = player; this.listener = listener; } } }
package com.deuteriumlabs.dendrite.model; import java.util.Date; 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.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.PreparedQuery.TooManyResultsException; import com.google.appengine.api.datastore.Query; /** * Represents the data of the website. An interface is provided for putting and * getting data from the Google App Engine datastore. */ public abstract class Model { private static final String CREATION_DATE_PROPERTY = "creationDate"; /** * Returns a single entity from the prepared query. * * @param preparedQuery * the prepared query matching a single entity * @return The single entity from the prepared query */ protected static Entity getSingleEntity(final PreparedQuery preparedQuery) { try { return preparedQuery.asSingleEntity(); } catch (TooManyResultsException e) { return null; } } /** * Returns the datastore. The main purpose of this method is to shorten the * method name for less clumsy regular use. * * @return The datastore */ protected static DatastoreService getStore() { return DatastoreServiceFactory.getDatastoreService(); } /** * Builds an entity containing the current data of this model and puts it in * the datastore. */ public void create() { final String kindName = this.getKindName(); final Entity entity = createNewEntity(kindName); putEntityInStore(entity); } /** * Retrieves the entity matching this model instance and deletes it from the * store. */ public void delete() { final Entity entity = this.getMatchingEntity(); if (entity != null) { deleteEntityByKey(entity); } } /** * Returns <code>true</code> if this model instance is in the store. * * @return <code>true</code> if this is in the store, <code>false</code> * otherwise. */ public boolean isInStore() { final Query query = this.getMatchingQuery(); final DatastoreService store = getStore(); final PreparedQuery preparedQuery = store.prepare(query); final FetchOptions fetchOptions = FetchOptions.Builder.withDefaults(); final int count = preparedQuery.countEntities(fetchOptions); return (count > 0); } /** * Retrieves the matching entity from the datastore, reads the properties * from the entity, and inserts those properties into this model instance. */ public void read() { final Entity entity = this.getMatchingEntity(); if (entity != null) { this.readPropertiesFromEntity(entity); } } /** * Retrieves the matching entity from the datastore, replaces all of the * properties in that entity, and then puts it back in the datastore. */ public void update() { final Entity entity = this.getMatchingEntity(); if (entity != null) { putEntityInStore(entity); } } private void deleteEntityByKey(final Entity entity) { final Key key = entity.getKey(); final DatastoreService store = getStore(); store.delete(key); } /** * Returns the entity matching this model instance. Returns * <code>null</code> if there is a problem. * * @return The entity matching this model instance, or <code>null</code> if * the retrieval fails */ private Entity getMatchingEntity() { final DatastoreService store = getStore(); final Query query = this.getMatchingQuery(); final PreparedQuery preparedQuery = store.prepare(query); return getSingleEntity(preparedQuery); } private void putEntityInStore(final Entity entity) { this.setCreationDate(entity); this.setPropertiesInEntity(entity); final DatastoreService store = getStore(); store.put(entity); } private void setCreationDate(final Entity entity) { final Date date = new Date(); entity.setProperty(CREATION_DATE_PROPERTY, date); } protected Entity createNewEntity(final String kindName) { return new Entity(kindName); } /** * Returns the model's kind. Each model kind has a unique name which allows * for identification in the datastore. Subclasses implement this method to * manage their own kind name. * * @return The kind of this model */ abstract String getKindName(); /** * Returns a query which should identify a single entity matching this * model. Subclasses implement this method to use their own unique * identifying properties to build filters for building this query. * * @return The query for identifying this model instance */ abstract Query getMatchingQuery(); /** * Reads the values from the entity corresponding to the properties of this * model instance. * * @param entity * The entity storing the properties */ abstract void readPropertiesFromEntity(final Entity entity); /** * Sets the values in the entity corresponding to the properties of this * model instance. * * @param entity * The entity storing the properties */ abstract void setPropertiesInEntity(final Entity entity); }
package org.adaptlab.chpir.android.survey; import java.text.SimpleDateFormat; import java.util.List; import org.adaptlab.chpir.android.activerecordcloudsync.ActiveRecordCloudSync; import org.adaptlab.chpir.android.activerecordcloudsync.NetworkNotificationUtils; import org.adaptlab.chpir.android.survey.Models.AdminSettings; import org.adaptlab.chpir.android.survey.Models.Instrument; import org.adaptlab.chpir.android.survey.Models.Survey; import org.adaptlab.chpir.android.survey.Tasks.DownloadImagesTask; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.text.InputType; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class InstrumentFragment extends ListFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setListAdapter(new InstrumentAdapter(Instrument.getAll())); AppUtil.appInit(getActivity()); } private void downloadInstrumentImages() { new DownloadImagesTask(getActivity()).execute(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_instrument, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_admin: displayPasswordPrompt(); return true; case R.id.menu_item_refresh: new RefreshInstrumentsTask().execute(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onResume() { super.onResume(); if (getListAdapter() != null) { ((BaseAdapter) getListAdapter()).notifyDataSetChanged(); } else { setListAdapter(new InstrumentAdapter(Instrument.getAll())); } createTabs(); } public void createTabs() { if (AdminSettings.getInstance().getShowSurveys()) { final ActionBar actionBar = getActivity().getActionBar(); ActionBar.TabListener tabListener = new ActionBar.TabListener() { @Override public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) { if (tab.getText().equals(getActivity().getResources().getString(R.string.surveys))) { if (Survey.getAll().isEmpty()) setListAdapter(null); else setListAdapter(new SurveyAdapter(Survey.getAll())); } else { setListAdapter(new InstrumentAdapter(Instrument.getAll())); } } // Required by interface public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) { } public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) { } }; actionBar.removeAllTabs(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab().setText(getActivity().getResources().getString(R.string.instruments)).setTabListener(tabListener)); actionBar.addTab(actionBar.newTab().setText(getActivity().getResources().getString(R.string.surveys)).setTabListener(tabListener)); } } private class InstrumentAdapter extends ArrayAdapter<Instrument> { public InstrumentAdapter(List<Instrument> instruments) { super(getActivity(), 0, instruments); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate( R.layout.list_item_instrument, null); } Instrument instrument = getItem(position); TextView titleTextView = (TextView) convertView .findViewById(R.id.instrument_list_item_titleTextView); titleTextView.setText(instrument.getTitle()); titleTextView.setTypeface(instrument.getTypeFace(getActivity().getApplicationContext())); TextView questionCountTextView = (TextView) convertView .findViewById(R.id.instrument_list_item_questionCountTextView); int numQuestions = instrument.questions().size(); questionCountTextView.setText(numQuestions + " " + FormatUtils.pluralize(numQuestions, getString(R.string.question), getString(R.string.questions))); return convertView; } } private class SurveyAdapter extends ArrayAdapter<Survey> { public SurveyAdapter(List<Survey> surveys) { super(getActivity(), 0, surveys); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate( R.layout.list_item_survey, null); } Survey survey = getItem(position); TextView titleTextView = (TextView) convertView .findViewById(R.id.survey_list_item_titleTextView); titleTextView.setText(survey.identifier(getActivity())); titleTextView.setTypeface(survey.getInstrument().getTypeFace(getActivity().getApplicationContext())); TextView progressTextView = (TextView) convertView.findViewById(R.id.survey_list_item_progressTextView); progressTextView.setText(survey.responses().size() + " " + getString(R.string.of) + " " + survey.getInstrument().questions().size()); TextView instrumentTitleTextView = (TextView) convertView.findViewById(R.id.survey_list_item_instrumentTextView); instrumentTitleTextView.setText(survey.getInstrument().getTitle()); TextView lastUpdatedTextView = (TextView) convertView.findViewById(R.id.survey_list_item_lastUpdatedTextView); SimpleDateFormat df = new SimpleDateFormat("HH:mm yyyy-MM-dd"); lastUpdatedTextView.setText(df.format(survey.getLastUpdated())); return convertView; } } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (l.getAdapter() instanceof InstrumentAdapter) { Instrument instrument = ((InstrumentAdapter) getListAdapter()).getItem(position); if (instrument == null) return; new LoadInstrumentTask().execute(instrument); } else if (l.getAdapter() instanceof SurveyAdapter) { Survey survey = ((SurveyAdapter) getListAdapter()).getItem(position); if (survey == null) return; new LoadSurveyTask().execute(survey); } } /* * Only display admin area if correct password. */ private void displayPasswordPrompt() { final EditText input = new EditText(getActivity()); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); new AlertDialog.Builder(getActivity()) .setTitle(R.string.password_title) .setMessage(R.string.password_message) .setView(input) .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int button) { if (AppUtil.checkAdminPassword(input.getText().toString())) { Intent i = new Intent(getActivity(), AdminActivity.class); startActivity(i); } else { Toast.makeText(getActivity(), R.string.incorrect_password, Toast.LENGTH_LONG).show(); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int button) { } }).show(); } /* * Refresh the receive tables from the server */ private class RefreshInstrumentsTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { getActivity().setProgressBarIndeterminateVisibility(true); setListAdapter(null); } @Override protected Void doInBackground(Void... params) { if (isAdded() && NetworkNotificationUtils.checkForNetworkErrors(getActivity())) ActiveRecordCloudSync.syncReceiveTables(getActivity()); return null; } @Override protected void onPostExecute(Void param) { if (isAdded()) { downloadInstrumentImages(); setListAdapter(new InstrumentAdapter(Instrument.getAll())); getActivity().setProgressBarIndeterminateVisibility(false); } } } /* * Check that the instrument has been fully loaded from the server before allowing * user to begin survey. */ private class LoadInstrumentTask extends AsyncTask<Instrument, Void, Long> { ProgressDialog mProgressDialog; @Override protected void onPreExecute() { mProgressDialog = ProgressDialog.show( getActivity(), getString(R.string.instrument_loading_progress_header), getString(R.string.instrument_loading_progress_message) ); } /* * If instrument is loaded, return the instrument id. * If not, return -1. */ @Override protected Long doInBackground(Instrument... params) { Instrument instrument = params[0]; if (instrument.loaded()) { return instrument.getRemoteId(); } else { return Long.valueOf(-1); } } @Override protected void onPostExecute(Long instrumentId) { mProgressDialog.dismiss(); if (instrumentId == Long.valueOf(-1)) { Toast.makeText(getActivity(), R.string.instrument_not_loaded, Toast.LENGTH_LONG).show(); } else { Intent i = new Intent(getActivity(), SurveyActivity.class); i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, instrumentId); startActivity(i); } } } private class LoadSurveyTask extends AsyncTask<Survey, Void, Survey> { ProgressDialog mProgressDialog; @Override protected void onPreExecute() { mProgressDialog = ProgressDialog.show( getActivity(), getString(R.string.instrument_loading_progress_header), getString(R.string.instrument_loading_progress_message) ); } /* * If instrument is loaded, return the survey. * If not, return null. */ @Override protected Survey doInBackground(Survey... params) { Survey survey = params[0]; Instrument instrument = survey.getInstrument(); if (instrument.loaded()) { return survey; } else { return null; } } @Override protected void onPostExecute(Survey survey) { mProgressDialog.dismiss(); if (survey == null) { Toast.makeText(getActivity(), R.string.instrument_not_loaded, Toast.LENGTH_LONG).show(); } else { Intent i = new Intent(getActivity(), SurveyActivity.class); i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, survey.getInstrument().getRemoteId()); i.putExtra(SurveyFragment.EXTRA_SURVEY_ID, survey.getId()); i.putExtra(SurveyFragment.EXTRA_QUESTION_ID, survey.getLastQuestion().getId()); startActivity(i); } } } }
package org.appwork.swing.exttable.columns; import java.awt.Rectangle; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.border.CompoundBorder; import org.appwork.swing.exttable.ExtColumn; import org.appwork.swing.exttable.ExtDefaultRowSorter; import org.appwork.swing.exttable.ExtTableModel; import org.appwork.swing.exttable.renderercomponents.RendererProgressBar; abstract public class ExtProgressColumn<E> extends ExtColumn<E> { private static final long serialVersionUID = -2473320164484034664L; public static double getPercentString(final long current, final long total) { if (total <= 0) { return 0.00d; } return current * 10000 / total / 100.0d; } protected RendererProgressBar determinatedRenderer; protected CompoundBorder defaultBorder; private RendererProgressBar indeterminatedRenderer; private RendererProgressBar renderer; private HashMap<E, Long> map; private int columnIndex = -1; public ExtProgressColumn(final String title) { this(title, null); } public ExtProgressColumn(final String name, final ExtTableModel<E> extModel) { super(name, extModel); this.map = new HashMap<E, Long>(); this.determinatedRenderer = new RendererProgressBar() { }; this.indeterminatedRenderer = new RendererProgressBar() { private static final long serialVersionUID = 1L; private long cleanupTimer = 0; private volatile boolean indeterminate = false; private volatile long timer = 0; @Override public boolean isDisplayable() { return true; } @Override public boolean isIndeterminate() { return this.indeterminate; } @Override public boolean isVisible() { return false; } @Override public void repaint() { if (ExtProgressColumn.this.isModifying()) { return; } final ExtTableModel<E> mod = ExtProgressColumn.this.getModel(); if (mod != null && mod.getTable() != null && ExtProgressColumn.this.indeterminatedRenderer.isIndeterminate() && mod.getTable().isShowing()) { // cleanup map in case we removed a indeterminated value if (System.currentTimeMillis() - this.cleanupTimer > 30000) { Entry<E, Long> next; for (final Iterator<Entry<E, Long>> it = ExtProgressColumn.this.map.entrySet().iterator(); it.hasNext();) { next = it.next(); final long lastUpdate = System.currentTimeMillis() - next.getValue(); if (lastUpdate > 5000) { it.remove(); } } this.cleanupTimer = System.currentTimeMillis(); if (ExtProgressColumn.this.map.size() == 0 && ExtProgressColumn.this.indeterminatedRenderer.isIndeterminate()) { ExtProgressColumn.this.indeterminatedRenderer.setIndeterminate(false); return; } } if (ExtProgressColumn.this.columnIndex >= 0) { if (System.currentTimeMillis() - this.timer > 1000 / ExtProgressColumn.this.getFps()) { // mod._fireTableStructureChanged(mod.getTableData(), // false); // System.out.println(getLocation()); ExtProgressColumn.this.repaint(); this.timer = System.currentTimeMillis(); } } } } @Override public void repaint(final Rectangle r) { this.repaint(); } @Override public void setIndeterminate(final boolean newValue) { if (newValue == this.indeterminate) { return; } this.indeterminate = newValue; super.setIndeterminate(newValue); } }; // this.getModel().addTableModelListener(new TableModelListener() { // @Override // public void tableChanged(final TableModelEvent e) { // switch (e.getType()) { // case TableModelEvent.DELETE: // System.out.println(e); // if (ExtProgressColumn.this.map.size() == 0) { // ExtProgressColumn.this.indeterminatedRenderer.setIndeterminate(false); this.renderer = this.determinatedRenderer; this.defaultBorder = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(1, 1, 2, 1), this.determinatedRenderer.getBorder()); this.setRowSorter(new ExtDefaultRowSorter<E>() { @Override public int compare(final E o1, final E o2) { final double v1 = (double) ExtProgressColumn.this.getValue(o1) / ExtProgressColumn.this.getMax(o1); final double v2 = (double) ExtProgressColumn.this.getValue(o2) / ExtProgressColumn.this.getMax(o2); if (v1 == v2) { return 0; } if (this.getSortOrderIdentifier() != ExtColumn.SORT_ASC) { return v1 > v2 ? -1 : 1; } else { return v2 > v1 ? -1 : 1; } } }); } @Override public void configureEditorComponent(final E value, final boolean isSelected, final int row, final int column) { // TODO Auto-generated method stub } @Override public void configureRendererComponent(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { this.prepareGetter(value); if (this.renderer == this.determinatedRenderer) { // Normalize value and maxvalue to fit in the integer range long m = this.getMax(value); long v = 0; if (m >= 0) { v = this.getValue(value); final double factor = Math.max(v / (double) Integer.MAX_VALUE, m / (double) Integer.MAX_VALUE); if (factor >= 1.0) { v /= factor; m /= factor; } } v = Math.min(m, v); // take care to set the maximum before the value!! this.renderer.setMaximum((int) m); this.renderer.setValue((int) v); this.renderer.setMinimum(0); this.renderer.setString(this.getString(value, v, m)); } else { this.renderer.setString(this.getString(value, -1, -1)); if (!this.renderer.isIndeterminate()) { this.renderer.setIndeterminate(true); } } } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#getCellEditorValue * () */ @Override public Object getCellEditorValue() { return null; } /** * @return */ @Override public JComponent getEditorComponent(final E value, final boolean isSelected, final int row, final int column) { return null; } /** * @return */ protected int getFps() { return 15; } protected long getMax(final E value) { return 100; } /** * @return */ @Override public JComponent getRendererComponent(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { this.columnIndex = column; if (this.isIndeterminated(value, isSelected, hasFocus, row, column)) { this.renderer = this.indeterminatedRenderer; if (this.map.size() == 0) { if (!this.indeterminatedRenderer.isIndeterminate()) { this.map.put(value, System.currentTimeMillis()); this.indeterminatedRenderer.setIndeterminate(true); } } this.map.put(value, System.currentTimeMillis()); } else { this.renderer = this.determinatedRenderer; this.map.remove(value); if (this.map.size() == 0) { if (this.indeterminatedRenderer.isIndeterminate()) { this.indeterminatedRenderer.setIndeterminate(false); } } } return this.renderer; } abstract protected String getString(E value, long current, long total); @Override protected String getTooltipText(final E value) { long v = this.getValue(value); long m = this.getMax(value); final double factor = Math.max(v / (double) Integer.MAX_VALUE, m / (double) Integer.MAX_VALUE); if (factor >= 1.0) { v /= factor; m /= factor; } return this.getString(value, v, m); } abstract protected long getValue(E value); /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#isEditable(java * .lang.Object) */ @Override public boolean isEditable(final E obj) { return false; } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#isEnabled(java * .lang.Object) */ @Override public boolean isEnabled(final E obj) { return true; } /** * @param column * @param row * @param hasFocus * @param isSelected * @param value * @return */ protected boolean isIndeterminated(final E value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#isSortable(java * .lang.Object) */ @Override public boolean isSortable(final E obj) { return true; } /** * @param value */ protected void prepareGetter(final E value) { } @Override public void resetEditor() { // TODO Auto-generated method stub } @Override public void resetRenderer() { this.renderer.setOpaque(false); this.renderer.setStringPainted(true); this.renderer.setBorder(this.defaultBorder); } /* * (non-Javadoc) * * @see * com.rapidshare.rsmanager.gui.components.table.ExtColumn#setValue(java * .lang.Object, java.lang.Object) */ @Override public void setValue(final Object value, final E object) { } }
package org.fife.ui.rsyntaxtextarea; import java.awt.event.ActionEvent; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.UIManager; import javax.swing.text.BadLocationException; import org.fife.ui.rtextarea.RTextArea; /** * Base class for JFlex-based token makers using C-style syntax. This class * knows how to auto-indent after opening braces and parens. * * @author Robert Futrell * @version 1.0 */ public abstract class AbstractJFlexCTokenMaker extends AbstractJFlexTokenMaker { protected static final Action INSERT_BREAK_ACTION = new InsertBreakAction(); /** * Returns <code>true</code> always as C-style languages use curly braces * to denote code blocks. * * @return <code>true</code> always. */ @Override public boolean getCurlyBracesDenoteCodeBlocks() { return true; } /** * Returns an action to handle "insert break" key presses (i.e. Enter). * An action is returned that handles newlines differently in multi-line * comments. * * @return The action. */ @Override public Action getInsertBreakAction() { return INSERT_BREAK_ACTION; } /** * {@inheritDoc} */ @Override public boolean getMarkOccurrencesOfTokenType(int type) { return type==Token.IDENTIFIER || type==Token.FUNCTION; } /** * {@inheritDoc} */ @Override public boolean getShouldIndentNextLineAfter(Token t) { if (t!=null && t.length()==1) { char ch = t.charAt(0); return ch=='{' || ch=='('; } return false; } /** * Action that knows how to special-case inserting a newline in a * multi-line comment for languages like C and Java. */ private static class InsertBreakAction extends RSyntaxTextAreaEditorKit.InsertBreakAction { private static final Pattern p = Pattern.compile("([ \\t]*)(/?[\\*]+)([ \\t]*)"); @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } RSyntaxTextArea rsta = (RSyntaxTextArea)getTextComponent(e); RSyntaxDocument doc = (RSyntaxDocument)rsta.getDocument(); int line = textArea.getCaretLineNumber(); int type = doc.getLastTokenTypeOnLine(line); if (type<0) { type = doc.getClosestStandardTokenTypeForInternalType(type); } // Only in MLC's should we try this if (type==Token.COMMENT_DOCUMENTATION || type==Token.COMMENT_MULTILINE) { insertBreakInMLC(e, rsta, line); } else { handleInsertBreak(rsta, true); } } * to have a "nested" comment (i.e., contains "<code>/*</code>" * somewhere inside of it). This implies that it is likely a "new" MLC * and needs to be closed. While not foolproof, this is usually good * enough of a sign. * * @param textArea * @param line * @param offs * @return Whether a comment appears to be nested inside this one. */ private boolean appearsNested(RSyntaxTextArea textArea, int line, int offs) { final int firstLine = line; // Remember the line we start at. while (line<textArea.getLineCount()) { Token t = textArea.getTokenListForLine(line); int i = 0; // If examining the first line, start at offs. if (line++==firstLine) { t = RSyntaxUtilities.getTokenAtOffset(t, offs); if (t==null) { // offs was at end of the line continue; } i = t.documentToToken(offs); } else { i = t.getTextOffset(); } int textOffset = t.getTextOffset(); while (i<textOffset+t.length()-1) { if (t.charAt(i-textOffset)=='/' && t.charAt(i-textOffset+1)=='*') { return true; } i++; } // If tokens come after this one on this line, our MLC ended. if (t.getNextToken()!=null) { return false; } } return true; // No match - MLC goes to the end of the file } private void insertBreakInMLC(ActionEvent e, RSyntaxTextArea textArea, int line) { Matcher m = null; int start = -1; int end = -1; String text = null; try { start = textArea.getLineStartOffset(line); end = textArea.getLineEndOffset(line); text = textArea.getText(start, end-start); m = p.matcher(text); } catch (BadLocationException ble) { // Never happens UIManager.getLookAndFeel().provideErrorFeedback(textArea); ble.printStackTrace(); return; } if (m.lookingAt()) { String leadingWS = m.group(1); String mlcMarker = m.group(2); // If the caret is "inside" any leading whitespace or MLC // marker, move it to the end of the line. int dot = textArea.getCaretPosition(); if (dot>=start && dot<start+leadingWS.length()+mlcMarker.length()) { // If we're in the whitespace before the very start of the // MLC though, just insert a normal newline if (mlcMarker.charAt(0)=='/') { handleInsertBreak(textArea, true); return; } textArea.setCaretPosition(end-1); } else { // Ensure caret is at the "end" of any whitespace // immediately after the '*', but before any possible // non-whitespace chars. boolean moved = false; System.out.println("Original dot==" + dot + " (end==" + end + ")"); while (dot<end-1 && Character.isWhitespace(text.charAt(dot-start))) { moved = true; dot++; } if (moved) { System.out.println("New dot==" + dot); textArea.setCaretPosition(dot); } } boolean firstMlcLine = mlcMarker.charAt(0)=='/'; boolean nested = appearsNested(textArea, line, start+leadingWS.length()+2); String header = leadingWS + (firstMlcLine ? " * " : "*") + m.group(3); textArea.replaceSelection("\n" + header); if (nested) { dot = textArea.getCaretPosition(); // Has changed textArea.insert("\n" + leadingWS + " */", dot); textArea.setCaretPosition(dot); } } else { handleInsertBreak(textArea, true); } } } }
package org.jsecurity.session.support; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jsecurity.authz.HostUnauthorizedException; import org.jsecurity.session.*; import org.jsecurity.session.event.*; import org.jsecurity.session.support.eis.SessionDAO; import org.jsecurity.util.Initializable; import java.io.Serializable; import java.net.InetAddress; import java.security.Principal; import java.text.DateFormat; import java.util.Date; /** * @since 0.1 * @author Les Hazlewood */ public abstract class AbstractSessionManager implements SessionManager, Initializable { protected static final int GLOBAL_SESSION_TIMEOUT = 60 * 30; //30 minutes by default; protected transient final Log log = LogFactory.getLog( getClass() ); protected SessionDAO sessionDAO = null; protected SessionEventSender sessionEventSender = null; protected boolean validateHost = true; protected Class<? extends Session> sessionClass = null; protected int globalSessionTimeout = GLOBAL_SESSION_TIMEOUT; public AbstractSessionManager(){} public void setSessionDAO( SessionDAO sessionDAO ) { this.sessionDAO = sessionDAO; } public SessionDAO getSessionDAO() { return this.sessionDAO; } /** * Sets the {@link org.jsecurity.session.event.SessionEventSender} this Manager will use to send/publish events when * a meaningful session event occurs. * <p>The instance given can do anything from traditional-style synchronous listener * notification to more sophisticated publishing of JMS messages or anything else. * @param sessionEventSender the sender to use to propagate session events. */ public void setSessionEventSender( SessionEventSender sessionEventSender ) { this.sessionEventSender = sessionEventSender; } public SessionEventSender getSessionEventSender() { return this.sessionEventSender; } /** * Returns the Class that will be used to instantiate new {@link Session} objects when * a session starts. * @return the Class used to instantiate new {@link Session} objects */ public Class<? extends Session> getSessionClass() { return sessionClass; } /** * Sets the class of the {@link Session} implementation to use when instantiating a new * session object. This must be a JavaBeans&reg;-compatible class, with a default, * no-argument constructor such that {@link Class#newInstance()} may be invoked. * @param sessionClass the Class used to instantiate new {@link Session} objects */ public void setSessionClass( Class<? extends Session> sessionClass ) { this.sessionClass = sessionClass; } /** * Returns <tt>true</tt> if this SessionManager will validate the originating host address * before creating a session, false otherwise. * * <p>If <tt>true</tt>, the originating host address will be validated via the * {@link #validate(InetAddress)} method. Subclasses should override that method for * application-specific validation. * * <p>The default implementation always returns <tt>true</tt> * * @return true if the originating host address will be validated prior to creating a session, * false otherwise. * * @see #validate(InetAddress) */ public boolean isValidateHost() { return validateHost; } /** * If set to <tt>true</tt> the <tt>originatingHost</tt> address will be validated prior to * starting a new Session. A value of <tt>false</tt> disables host validation. * <p>Defaults to <tt>true</tt>. * @param validateHost whether or not to validate the originatingHost address prior to * session creation. * * @see #validate * @see #createSession */ public void setValidateHost( boolean validateHost ) { this.validateHost = validateHost; } /** * Returns the time in seconds that any session may remain idle before expiring. This * value is just a global default for all sessions and may be overridden by subclasses on a * <em>per-session</em> basis by overriding the {@link #getTimeout(Session)} method if * so desired. * * <p> * <ul> * <li>A negative return value means sessions never expire.</li> * <li>A <tt>zero</tt> return value means sessions expire immediately.</li> * <li>A positive return alue indicates normal session timeout will be calculated.</li> * </ul> * </p> * * <p>Unless overridden via the {@link #setGlobalSessionTimeout} method, the default value is * 60 * 30 (30 minutes). * * @return the time in seconds that any session may remain idle before expiring. */ public int getGlobalSessionTimeout() { return globalSessionTimeout; } /** * Sets the time in seconds that any session may remain idle before expiring. This * value is just a global default for all sessions. Subclasses may override the * {@link #getTimeout} method to determine time-out values on a <em>per-session</em> basis. * * @param globalSessionTimeout the time in seconds any session may remain idle before * expiring. */ public void setGlobalSessionTimeout( int globalSessionTimeout ) { this.globalSessionTimeout = globalSessionTimeout; } public void init() { if ( sessionDAO == null ) { String msg = "sessionDAO property has not been set. The sessionDAO is required to " + "access session objects during runtime."; throw new IllegalStateException( msg ); } if ( sessionClass == null ) { String msg = "sessionClass property has not been set"; throw new IllegalStateException( msg ); } if ( sessionEventSender == null ) { if ( log.isInfoEnabled() ) { String msg = "sessionEventSender property has not been set. SessionEvents will " + "not be propagated."; log.info( msg ); } } } protected void send( SessionEvent event ) { if ( this.sessionEventSender != null ) { if ( log.isDebugEnabled() ) { String msg = "Using sessionEventSender to send event [" + event + "]"; log.debug( msg ); } this.sessionEventSender.send( event ); } else { if ( log.isTraceEnabled() ) { String msg = "No sessionEventSender set. Event of type [" + event.getClass().getName() + "] will not be propagated."; log.trace( msg ); } } } /** * Ensures the originatingHost is a value allowed by the system for session interaction. * Default implementation just ensures the value is not null. Subclasses may override this * method to do any number of checks, such as ensuring the originatingHost is in a valid * range, part of a particular subnet, or configured in the database as a valid IP. * @param originatingHost the originating host address associated with the session * creation attempt. */ protected void validate( InetAddress originatingHost ) throws IllegalArgumentException { if ( originatingHost == null ) { String msg = "originatingHost argument is null. A valid non-null originating " + "host address must be specified when initiating a session"; throw new IllegalArgumentException( msg ); } } protected void stop( Session session ) { if ( log.isDebugEnabled() ) { log.debug( "Stopping session with id [" + session.getSessionId() + "]" ); } onStop( session ); sessionDAO.update( session ); send( createStopEvent( session ) ); } /** * Subclasses should override this method to update the state of the given * {@link Session} implementation prior to updating the EIS with the stopped object. * @param session the session object to update w/ data related to being stopped. */ protected void onStop( Session session ){} protected void expire( Session session ) { if ( log.isDebugEnabled() ) { log.debug( "Expiring session with id [" + session.getSessionId() + "]" ); } onExpire( session ); sessionDAO.update( session ); send( createExpireEvent( session ) ); } protected SessionEvent createStartEvent( Session session ) { return new StartedSessionEvent( this, session.getSessionId() ); } protected SessionEvent createStopEvent( Session session ) { return new StoppedSessionEvent( this, session.getSessionId() ); } protected SessionEvent createExpireEvent( Session session ) { return new ExpiredSessionEvent( this, session.getSessionId() ); } /** * Allows subclasses to update the state of the specified <tt>session</tt> object prior to * being saved to the EIS. * Default implementation does nothing, since it can't make assumptions about * implementations of the interface. * @param session the session object to update with data related to be being expired. */ protected void onExpire( Session session ) {} protected void validate( Session session ) throws InvalidSessionException { if ( isExpired( session ) ) { //update EIS entry if it hasn't been updated already: if ( !session.isExpired() ) { expire( session ); } //throw an exception explaining details of why it expired: Date lastAccessTime = session.getLastAccessTime(); int timeout = getTimeout( session ); Serializable sessionId = session.getSessionId(); DateFormat df = DateFormat.getInstance(); String msg = "Session with id [" + sessionId + "] has expired. " + "Last access time: " + df.format( lastAccessTime ) + ". Current time: " + df.format( new Date() ) + ". Session timeout is set to " + timeout + " seconds (" + timeout / 60 + " minutes)"; if ( log.isTraceEnabled() ) { log.trace( msg ); } throw new ExpiredSessionException( msg, sessionId ); } //check for stopped (but not expired): if ( session.getStopTimestamp() != null ) { //destroy timestamp is set, so the session is considered stopped: String msg = "Session with id [" + session.getSessionId() + "] has been " + "explicitly stopped. No further interaction under this session is " + "allowed."; throw new InvalidSessionException( msg, session.getSessionId() ); } } protected Session newSessionInstance() { try { if ( log.isDebugEnabled() ) { log.debug( "Instantiating new [" + getSessionClass().getName() + "] instance" ); } return getSessionClass().newInstance(); } catch ( Exception e ) { String msg = "Unable to instantiate an instance of class [" + getSessionClass().getName() + "]"; throw new SessionException( msg, e ); } } /** * Subclasses can implement this method to apply properties to the the new session * instance created via the {@link #newSessionInstance()} method. * * <p>Implementations of this method at a minimum would probably want to associate the given host * address with the session via an implementation setter method, e.g. * <pre>newInstance.setHostAddress( hostAddr );</pre> * for session tracking and reporting options. * * <p>Note that the <tt>hostAddr</tt> parameter may be <tt>null</tt> if * {@link #isValidateHost() host validation} is disabled. * * @param newInstance new instance of the {@link #getSessionClass() sessionClass} * @param hostAddr the originating address associated with the session creation - may be * <tt>null</tt> if {@link #isValidateHost() host validation} is disabled. */ protected void init( Session newInstance, InetAddress hostAddr ) {} protected Session createSession( InetAddress originatingHost ) { if ( log.isTraceEnabled() ) { log.trace( "Creating session for originating host [" + originatingHost + "]" ); } if ( isValidateHost() ) { if ( log.isDebugEnabled() ) { log.debug( "Host validation enabled. Validating originating host [" + originatingHost + "]" ); } validate( originatingHost ); } Session s = newSessionInstance(); if ( log.isDebugEnabled() ) { log.debug( "Initializing new Session instance [" + s + "]" ); } init( s, originatingHost ); //save initialized Session to EIS: if ( log.isDebugEnabled() ) { log.debug( "Creating new EIS record for new session instance [" + s + "]" ); } sessionDAO.create( s ); send( createStartEvent( s ) ); return s; } protected Session retrieveSession( Serializable sessionId ) { if ( log.isTraceEnabled() ) { log.trace( "Retrieving session with id [" + sessionId + "] from the EIS" ); } Session s = sessionDAO.readSession( sessionId ); if ( s == null ) { String msg = "There is no session in the EIS database with session id [" + sessionId + "]"; throw new UnknownSessionException( msg ); } return s; } protected Session retrieveAndValidateSession( Serializable sessionId ) { Session s = retrieveSession( sessionId ); validate( s ); return s; } /** * Returns whether or not a particular session can expire. * * <p>Default implementation always returns <tt>true</tt>. * * <p>Overriding this method can be particularly useful in some circumstances. For example, * daemon users (background process users) can be configured in a system like any other user. * It is much easier to define a daemon account and use the same session and security framework * that supports normal human users, rather than program special-case logic. Daemon accounts * are often expected to interact with the system at any time, regardless of (in)activity. * This method provides a means to disable session expiration in such cases. * * <p>Most overriding implementations usually infer a user or user id from the specified * <tt>Session</tt> and determine per-user timeout settings in a specific manner. * * @param session the session for which to determine if timeout expiration is enabled. */ protected boolean isExpirationEnabled( Session session ) { return true; } /** * Returns the time in seconds the specified session may remain idle before expiring. * * <p>Most overriding implementations usually infer a user or user id from the specified * <tt>Session</tt> and determine per-user timeout values in a specific manner. * * <p> * <ul> * <li>A negative return value means the session does not time-out/expire.</li> * <li>A <tt>zero</tt> return value means the session should expire immediately (of little value).</li> * <li>A positive return alue indicates normal session timeout will be calculated.</li> * </ul> * </p> * * <p>Default implementation returns the * {@link #getGlobalSessionTimeout() global session timeout} for all sessions. * * @param session the session for which to determine session timeout. * @return the time in seconds the specified session may remain idle before expiring. */ protected int getTimeout( Session session ) { return getGlobalSessionTimeout(); } /** * Determines if the specified session is expired. * @param session * @return true if the specified session has expired, false otherwise. */ protected boolean isExpired( Session session ) { //If the EIS data has already been set as expired, return true: //WARNING: This will cause an infinite loop if the session argument is a proxy back //to this instance (e.g. as would be the case if passing in a DelegatingSession instace. //To be safe, make sure the argument is representative of EIS data and //the isExpired method returns a boolean class attribute and does not call another object. if ( session.isExpired() ) { return true; } if ( isExpirationEnabled( session ) ) { int timeout = getTimeout( session ); if ( timeout >= 0 ) { Date lastAccessTime = session.getLastAccessTime(); if ( lastAccessTime == null ) { String msg = "session.lastAccessTime for session with id [" + session.getSessionId() + "] is null. This value must be set at " + "least once. Please check the " + session.getClass().getName() + " implementation and ensure " + "this value will be set (perhaps in the constructor?)"; throw new IllegalStateException( msg ); } // Calculate at what time a session would have been last accessed // for it to be expired at this point. In other words, subtract // from the current time the amount of time that a session can // be inactive before expiring. If the session was last accessed // before this time it is expired. long expireTimeMillis = System.currentTimeMillis() - ( 1000 * timeout ); Date expireTime = new Date( expireTimeMillis ); return lastAccessTime.before( expireTime ); } else { if ( log.isInfoEnabled() ) { log.info( "No timeout for session with id [" + session.getSessionId() + "]. Session is not considered expired." ); } } } else { if ( log.isInfoEnabled() ) { log.info( "Time-out is disabled for Session with id [" + session.getSessionId() + "]. Session is not expired." ); } } return false; } public Serializable start( InetAddress originatingHost ) throws HostUnauthorizedException, IllegalArgumentException { Session s = createSession( originatingHost ); return s.getSessionId(); } public Date getStartTimestamp( Serializable sessionId ) { return retrieveSession( sessionId ).getStartTimestamp(); } public Date getStopTimestamp( Serializable sessionId ) { return retrieveSession( sessionId ).getStopTimestamp(); } public Date getLastAccessTime( Serializable sessionId ) { return retrieveSession( sessionId ).getLastAccessTime(); } public boolean isStopped( Serializable sessionId ) { return retrieveSession( sessionId ).getStopTimestamp() != null; } public boolean isExpired( Serializable sessionId ) { return retrieveSession( sessionId ).isExpired(); } protected void onTouch( Session session ){} public void touch( Serializable sessionId ) throws InvalidSessionException { Session s = retrieveAndValidateSession( sessionId ); onTouch( s ); sessionDAO.update( s ); } public Principal getPrincipal( Serializable sessionId ) { //todo Implement principal lookup from session return null; } public InetAddress getHostAddress( Serializable sessionId ) { return retrieveSession( sessionId ).getHostAddress(); } public void stop( Serializable sessionId ) throws InvalidSessionException { Session s = retrieveAndValidateSession( sessionId ); stop( s ); } public Object getAttribute( Serializable sessionId, Object key ) throws InvalidSessionException { return retrieveAndValidateSession( sessionId ).getAttribute( key ); } public void setAttribute( Serializable sessionId, Object key, Object value ) throws InvalidSessionException { retrieveAndValidateSession( sessionId ).setAttribute( key, value ); } public Object removeAttribute( Serializable sessionId, Object key ) throws InvalidSessionException { return retrieveAndValidateSession( sessionId ).removeAttribute( key ); } }
package serviceResources; import db.DBConnector; import serviceRepresentations.GameCharacter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class CharacterDAO { private DBConnector dbConnector; public CharacterDAO(DBConnector dbConnector) { this.dbConnector = dbConnector; } /** * Inserts a new entry in characters table. * @param character The new character that will be inserted. * @return TRUE if action succeeded, FALSE otherwise. */ public Boolean createCharacter(GameCharacter character) { // TODO: Needs testing. try { Connection connection = dbConnector.getDBConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO CHARACTERS VALUES (?, ?, ?)"); statement.setString(1, character.getName()); statement.setString( 2, character.getPicturePath()); statement.setLong(3, character.getQuestionsNumber()); int affectedRowss = statement.executeUpdate(); if (affectedRowss == 0) { return Boolean.FALSE; // not sure about this } return Boolean.TRUE; } catch (SQLException e) { e.printStackTrace(); } return Boolean.TRUE; } /** * Returns a new `GameCharacter` object representing the NPC at that row. * @param id The `id` of the NPC. * @return A `GameCharacter`. */ public GameCharacter getCharacter(Long id) { GameCharacter gameCharacter = null; try { Connection connection = dbConnector.getDBConnection(); PreparedStatement statement = connection.prepareStatement("SELECT " + "NAME, " + "PICTURE_PATH, " + "QUESTION_NUMBER FROM CHARACTERS WHERE ID = ?"); statement.setLong(1, id); ResultSet rs = statement.executeQuery(); rs.next(); gameCharacter = new GameCharacter(); gameCharacter.setId(id); gameCharacter.setName(rs.getString("NAME")); gameCharacter.setPicturePath(rs.getString("PICTURE_PATH")); gameCharacter.setQuestionsNumber(rs.getLong("QUESTION_NUMBER")); return gameCharacter; } catch (SQLException e) { e.printStackTrace(); } return gameCharacter; } /** * Removes the NPC with the id `id` from the database. * @param id The `id` of the targeted NPC. * @return TRUE if success, FALSE otherwise. */ public Boolean removeCharacter(Long id) { try { Connection connection = dbConnector.getDBConnection(); PreparedStatement statement = connection.prepareStatement("DELETE FROM CHARACTERS WHERE ID = ?"); statement.setLong(1, id); int affectedRows = statement.executeUpdate(); if (affectedRows == 0) { return Boolean.FALSE; } return Boolean.TRUE; } catch (SQLException e) { e.printStackTrace(); } return Boolean.FALSE; } /** * Updates a character in the database. * @param character A character object. It should contain the id of the original * and the fields that won't be updated should be the same as * in the original. * @return TRUE if the update succeeded, FALSE otherwise. An update could fail if there * was nothing to update. */ public Boolean updateCharacter(GameCharacter character) { try { Connection connection = dbConnector.getDBConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE CHARACTERS SET " + "NAME = ?," + "PICTURE_PATH = ?" + "QUESTION_NUMBER = ?" + "WHERE ID = ?"); statement.setString(1, character.getName()); statement.setString(2, character.getPicturePath()); statement.setLong(3, character.getQuestionsNumber()); int affectedRows = statement.executeUpdate(); if (affectedRows == 0) return Boolean.FALSE; return Boolean.TRUE; } catch (SQLException e) { e.printStackTrace(); } // Spaghetti code ftw! return Boolean.FALSE; } /** * @return Returns a list with all the questions. */ public List<GameCharacter> getCharacters() { // TODO: Security and edge cases. List<GameCharacter> characters = null; try { characters = new ArrayList<>(); Connection connection = dbConnector.getDBConnection(); PreparedStatement statement = connection.prepareStatement("SELECT ID, " + "NAME, " + "PICTURE_PATH, " + "QUESTION_NUMBER FROM CHARACTERS"); ResultSet rs = statement.executeQuery(); while (rs.next()) { GameCharacter character = new GameCharacter(); character.setId(rs.getLong("ID")); character.setName(rs.getString("NAME")); character.setPicturePath(rs.getString("PICTURE_PATH")); character.setQuestionsNumber(rs.getLong("QUESTION_NUMBER")); characters.add(character); rs.next(); } } catch (SQLException e) { e.printStackTrace(); } return characters; } }
package de.loskutov.fs.builder; import java.util.HashMap; import java.util.Map; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener; import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent; import de.loskutov.fs.FileSyncPlugin; import de.loskutov.fs.command.FileMapping; import de.loskutov.fs.properties.ProjectProperties; /** * @author Andrey */ public class FileSyncBuilder extends IncrementalProjectBuilder implements IPreferenceChangeListener { public static final String BUILDER_ID = FileSyncPlugin.PLUGIN_ID + ".FSBuilder"; /** * I don't know who and where in Eclipse creates the ".settings" dir */ public static final String SETTINGS_DIR = ".settings"; /** * I don't know who and where in Eclipse adds the ".prefs" suffix */ public static final String SETTINGS_FILE = FileSyncPlugin.PLUGIN_ID + ".prefs"; private static final IPath SETTINGS_PATH = new Path(SETTINGS_DIR).append(SETTINGS_FILE); public static final int MAPPING_CHANGED_IN_GUI_BUILD = 999; public static final Integer MAPPING_CHANGED_IN_GUI = Integer.valueOf(MAPPING_CHANGED_IN_GUI_BUILD); private boolean wizardNotAvailable; private boolean disabled; private IProject project2; private long modificationStamp; private Long mappingHashCode; private final Map pathToTimeStamp; volatile boolean ignorePrefChange; volatile private int visitorFlags; private static final IProject [] NO_PROJECTS = new IProject[0]; /** called by Eclipse through reflection */ public FileSyncBuilder() { super(); pathToTimeStamp = new HashMap(); } /** caled by us on click */ public FileSyncBuilder(IProject project) { this(); project2 = project; } protected IProject getProjectInternal() { IProject project = null; try { project = getProject(); } catch (NullPointerException e) { // TODO: since Eclipse 3.7 getProject() throws NPE if the builder // was created manually (as we do for the manually triggered build) // Have no time to fix properly, so just catch the NPE } if (project == null) { project = project2; } return project; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public void build(int kind, IProgressMonitor monitor) { build(kind, new HashMap(), monitor); } @Override protected void clean(IProgressMonitor monitor) throws CoreException { build(CLEAN_BUILD, new HashMap(), monitor); } @SuppressWarnings("unchecked") @Override protected IProject[] build(int kind, Map args, IProgressMonitor monitor) { if (isDisabled()) { return NO_PROJECTS; } if (args == null) { args = new HashMap(); } ProjectProperties props = ProjectProperties.getInstance(getProjectInternal()); updateVisitorFlags(props); SyncWizard wizard = new SyncWizard(); IProject[] result = NO_PROJECTS; try { switch (kind) { case AUTO_BUILD: result = buildAuto(args, props, wizard, monitor); break; case INCREMENTAL_BUILD: result = buildIncremental(args, props, wizard, monitor); break; case CLEAN_BUILD: // Currently it seems that Eclipse does not use "clean" flag for builders // on "clean project" action... result = buildClean(args, props, wizard, monitor); break; case MAPPING_CHANGED_IN_GUI_BUILD: args.put(MAPPING_CHANGED_IN_GUI, MAPPING_CHANGED_IN_GUI); result = buildFull(args, props, wizard, monitor); break; case FULL_BUILD: // fall-through default: result = buildFull(args, props, wizard, monitor); break; } wizardNotAvailable = false; } catch (IllegalArgumentException e) { if (!wizardNotAvailable) { FileSyncPlugin.log("Couldn't run file sync for project '" + getProjectInternal().getName() + "': " + e.getMessage(), e, IStatus.WARNING); wizardNotAvailable = true; } return NO_PROJECTS; } catch (IllegalStateException e) { if (!wizardNotAvailable) { FileSyncPlugin.log("Couldn't run file sync for project '" + getProjectInternal().getName() + "': " + e.getMessage(), e, IStatus.WARNING); wizardNotAvailable = true; } return NO_PROJECTS; } return result; } /** * Automatic build * @param args build parameters * @param wizard * @param monitor progress indicator * @return IProject[] related projects list */ private IProject[] buildAuto(Map args, ProjectProperties props, SyncWizard wizard, IProgressMonitor monitor) { return buildIncremental(args, props, wizard, monitor); } /** * Full build * @param args build parameters * @param wizard * @param monitor progress indicator * @return IProject[] related projects list */ private IProject[] buildFull(Map args, ProjectProperties props, SyncWizard wizard, IProgressMonitor monitor) { IProject currentProject = getProjectInternal(); if (currentProject != null) { fullProjectBuild(args, currentProject, props, wizard, monitor, false); } return NO_PROJECTS; } /** * Full build * @param args build parameters * @param wizard * @param monitor progress indicator * @return IProject[] related projects list */ private IProject[] buildClean(Map args, ProjectProperties props, SyncWizard wizard, IProgressMonitor monitor) { IProject currentProject = getProjectInternal(); if (currentProject != null) { fullProjectBuild(args, currentProject, props, wizard, monitor, true); } return NO_PROJECTS; } /** * Incremental build * @param args build parameters * @param wizard * @param monitor progress indicator * @return IProject[] related projects list */ private IProject[] buildIncremental(final Map args, final ProjectProperties props, final SyncWizard wizard, final IProgressMonitor monitor) { IProject result[] = null; final IProject currentProject = getProjectInternal(); if (currentProject != null) { final IResourceDelta resourceDelta = getDelta(currentProject); if (resourceDelta == null) { /* * Builder deltas may be null. If a builder has never been invoked before, * any request for deltas will return null. Also, if a builder is not run * for a long time, the platform reserves the right to return a null delta */ return buildFull(args, props, wizard, monitor); } if (resourceDelta.getAffectedChildren().length == 0) { // FileSyncPlugin.log("nothing happens because delta is empty", null, IStatus.INFO); } else { /* * check if my own props file is changed - before going to * synchronize all other files */ FSPropsChecker propsChecker = new FSPropsChecker(monitor, props); try { resourceDelta.accept(propsChecker, false); } catch (CoreException e) { FileSyncPlugin.log("Errors during sync of the resource delta:" + resourceDelta + " for project '" + currentProject.getName() + "'", e, IStatus.ERROR); } // props are in-sync now wizard.setProjectProps(props); int elementCount = countDeltaElement(resourceDelta); if (propsChecker.propsChanged) { Job[] jobs = Job.getJobManager().find(FileSyncBuilder.class); if (jobs.length == 0) { // start full build (not clean!) because properties are changed!!! Job job = new Job("Filesync") { @Override public boolean belongsTo(Object family) { return family == FileSyncBuilder.class; } @Override protected IStatus run(IProgressMonitor monitor1) { build(FULL_BUILD, monitor1); return Status.OK_STATUS; } }; /* * we starting the full build intensionally asynchron, because the current * build need to be finished first. The background is not completely clear for * me, but interrupting the build here lead to failures of "delete" * test case, if variables files are deleted too. * So let the current build finish and shedule another one to do * the full sync again, with changed preferences */ job.setUser(false); job.schedule(1000); } } else { try { monitor.beginTask("Incremental file sync", elementCount); final FSDeltaVisitor visitor = new FSDeltaVisitor(monitor, wizard); resourceDelta.accept(visitor, visitorFlags); } catch (CoreException e) { FileSyncPlugin.log( "Errors during sync of the resource delta:" + resourceDelta + " for project '" + currentProject + "'", e, IStatus.ERROR); } finally { wizard.cleanUp(monitor); monitor.done(); } } } } return result; } /** * Process all files in the project * @param project the project * @param monitor a progress indicator * @param wizard */ protected void fullProjectBuild(Map args, final IProject project, ProjectProperties props, SyncWizard wizard, final IProgressMonitor monitor, boolean clean) { if (!args.containsKey(MAPPING_CHANGED_IN_GUI) && wizard.getProjectProps() == null) { /* * check if my own props file is changed - before going to * synchronize all other files, but only if the build was *not* * initiated by changing mapping in the GUI */ FSPropsChecker propsChecker = new FSPropsChecker(monitor, props); try { project.accept(propsChecker, IResource.DEPTH_INFINITE, false); } catch (CoreException e) { FileSyncPlugin.log("Error during visiting project: " + project.getName(), e, IStatus.ERROR); } } // props are in-sync now wizard.setProjectProps(props); int elementCount = countProjectElements(project); try { if (clean) { monitor.beginTask("Clean project sync", elementCount); } else { monitor.beginTask("Full project sync", elementCount); } final FSResourceVisitor visitor = new FSResourceVisitor(monitor, wizard, clean); project.accept(visitor, IResource.DEPTH_INFINITE, visitorFlags); } catch (CoreException e) { FileSyncPlugin.log("Error during visiting project: " + project.getName(), e, IStatus.ERROR); } finally { wizard.cleanUp(monitor); monitor.done(); } } /** * Count the number of sub-resources of a project * @param project a project * @return the element count */ private int countProjectElements(IProject project) { CountVisitor visitor = new CountVisitor(); try { project.accept(visitor, IResource.DEPTH_INFINITE, visitorFlags); } catch (CoreException e) { FileSyncPlugin.log("Exception when counting elements of a project '" + project.getName() + "'", e, IStatus.ERROR); } return visitor.count; } /** * Count the number of sub-resources of a delta * @param delta a resource delta * @return the element count */ private int countDeltaElement(IResourceDelta delta) { CountVisitor visitor = new CountVisitor(); try { delta.accept(visitor, visitorFlags); } catch (CoreException e) { FileSyncPlugin.log("Exception counting elements in the delta: " + delta, e, IStatus.ERROR); } return visitor.count; } @Override protected void startupOnInitialize() { super.startupOnInitialize(); checkSettingsTimestamp(getProject().getFile(SETTINGS_PATH)); ProjectProperties props = ProjectProperties.getInstance(getProjectInternal()); // add self to listeners - if we already listen on ProjectProperties, // then this operation has no effect props.addPreferenceChangeListener(this); updateVisitorFlags(props); mappingHashCode = props.getHashCode(); } private void updateVisitorFlags(ProjectProperties props) { IEclipsePreferences preferences = props.getPreferences(false); boolean includeTeamFiles = preferences.getBoolean( ProjectProperties.KEY_INCLUDE_TEAM_PRIVATE, false); visitorFlags = includeTeamFiles? IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS : IResource.NONE; } /** * remember the timestamp for the project settings file * @return true, if the timestamp was changed since first run */ protected boolean checkSettingsTimestamp(IResource settingsFile) { long oldStamp = modificationStamp; IPath location = settingsFile.getLocation(); if(location == null){ return true; } long localTimeStamp = location.toFile().lastModified(); boolean changed = oldStamp != 0 && oldStamp != localTimeStamp; if (oldStamp == 0 || changed) { modificationStamp = localTimeStamp; } return changed; } protected void checkCancel(IProgressMonitor monitor, SyncWizard wizard) { if (monitor.isCanceled()) { wizard.cleanUp(monitor); // forgetLastBuiltState();//not always necessary throw new OperationCanceledException(); } } /** * @author Andrey */ private class FSDeltaVisitor implements IResourceDeltaVisitor { private final IProgressMonitor monitor; private final SyncWizard wizard; /** * @param monitor */ public FSDeltaVisitor(IProgressMonitor monitor, SyncWizard wizard) { this.monitor = monitor; this.wizard = wizard; } @Override public boolean visit(IResourceDelta delta) { if (delta == null) { return false; } checkCancel(monitor, wizard); monitor.worked(1); if (delta.getResource().getType() == IResource.PROJECT) { return true; } boolean shouldVisit = wizard.checkResource(delta); if (!shouldVisit) { // return true, if there children with mappings to visit return wizard.hasMappedChildren(delta); } String resStr = delta.getResource().toString(); monitor.subTask("sync: " + resStr); boolean ok = wizard.sync(delta, monitor); if (!ok) { FileSyncPlugin.log("Errors during sync of the resource delta: '" + resStr + "' in project '" + delta.getResource().getProject().getName() + "'", null, IStatus.WARNING); } // always visit children return true; } } /** * @author Andrey */ private class FSResourceVisitor implements IResourceVisitor { private final IProgressMonitor monitor; private final SyncWizard wizard; private final boolean clean; /** * @param monitor * @param clean */ public FSResourceVisitor(IProgressMonitor monitor, SyncWizard wizard, boolean clean) { this.monitor = monitor; this.wizard = wizard; this.clean = clean; } @Override public boolean visit(IResource resource) { monitor.worked(1); checkCancel(monitor, wizard); if (resource.getType() == IResource.PROJECT) { return true; } boolean shouldVisit = wizard.checkResource(resource); if (clean && !shouldVisit) { // this resource could be on the mapping path but filtered out - // on "clean" build it should be deleted shouldVisit = wizard.mappingExists(resource); } if (!shouldVisit) { // return true, if there children with mappings to visit return wizard.hasMappedChildren(resource); } String resStr = resource.getProjectRelativePath().toString(); monitor.subTask("check for " + resStr); boolean ok = wizard.sync(resource, monitor, clean); if (!ok) { FileSyncPlugin.log("Errors during sync of the resource '" + resStr + "' in project '" + resource.getProject().getName() + "'", null, IStatus.WARNING); } // always visit children return true; } } private class FSPropsChecker implements IResourceVisitor, IResourceDeltaVisitor { private final IProgressMonitor monitor; private final ProjectProperties props; boolean propsChanged; public FSPropsChecker(IProgressMonitor monitor, ProjectProperties props) { this.monitor = monitor; this.props = props; } @SuppressWarnings("unchecked") @Override public boolean visit(IResource resource) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (resource.getType() == IResource.PROJECT) { return true; } boolean continueVisit = isSettingsDir(resource); if (continueVisit && isSettingsFile(resource) && checkSettingsTimestamp(resource)) { // mappings changed ignorePrefChange = true; props.refreshPreferences(); Long hashCode = props.getHashCode(); ignorePrefChange = false; if (!hashCode.equals(mappingHashCode)) { propsChanged = true; continueVisit = false; mappingHashCode = hashCode; updateVisitorFlags(props); } } else { // check if variables are changed in any directory continueVisit = true; FileMapping[] mappings = props.getMappings(); for (int i = 0; i < mappings.length; i++) { IPath variablesPath = mappings[i].getVariablesPath(); if (variablesPath != null) { boolean match = variablesPath.equals(resource .getProjectRelativePath()); if (match) { Long time = (Long) pathToTimeStamp.get(variablesPath); IPath location = resource.getLocation(); if(location == null){ // full refresh here? return true; } long newTime = location.toFile().lastModified(); if (time != null && time.longValue() != newTime) { time = Long.valueOf(newTime); pathToTimeStamp.put(variablesPath, time); // we could stop and do full build, because vars are changed props.refreshPathMap(); Long hashCode = props.getHashCode(); if (!hashCode.equals(mappingHashCode)) { continueVisit = false; propsChanged = true; mappingHashCode = hashCode; break; } } else if (time == null) { time = Long.valueOf(newTime); pathToTimeStamp.put(variablesPath, time); } } } } } // visit children only from settings directory return continueVisit; } /** * @param file * @return true if this resource is my own prefs file */ private boolean isSettingsFile(IResource file) { // the directory is already ok, so we check only for the file name IPath relativePath = file.getProjectRelativePath(); if (relativePath == null) { return false; } return SETTINGS_FILE.equals(relativePath.lastSegment()); } /** * @param dir * @return true if this resource is my own prefs directory */ private boolean isSettingsDir(IResource dir) { IPath relativePath = dir.getProjectRelativePath(); // should match 1:1 to the settings dir, which is always under the // project root if (relativePath == null || relativePath.segmentCount() > 2) { return false; } return SETTINGS_DIR.equals(relativePath.segment(0)); } /* (non-Javadoc) * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta) */ @Override public boolean visit(IResourceDelta delta) { return visit(delta.getResource()); } } /* (non-Javadoc) * @see org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener#preferenceChange(org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent) */ @Override public void preferenceChange(PreferenceChangeEvent event) { if (ignorePrefChange) { return; } String key = event.getKey(); if (!ProjectProperties.KEY_PROJECT.equals(key)) { return; } Job[] jobs = Job.getJobManager().find(getClass()); if (jobs.length == 0) { final Job myJob = new Job("Mapping is changed => full project sync") { @Override public boolean belongsTo(Object family) { return family == FileSyncBuilder.class; } @Override public IStatus run(IProgressMonitor monitor) { build(MAPPING_CHANGED_IN_GUI_BUILD, monitor); return Status.OK_STATUS;//new JobStatus(IStatus.INFO, 0, this, "", null); } }; myJob.setUser(false); myJob.schedule(); } } /** * Visitor which only counts visited resources * @author Andrey */ protected final static class CountVisitor implements IResourceDeltaVisitor, IResourceVisitor { public int count = 0; @Override public boolean visit(IResourceDelta delta) { count++; return true; } @Override public boolean visit(IResource resource) { count++; return true; } } }
package radlab.rain.workload.rubis.util; import java.util.Arrays; import java.util.Random; /** * Generate random numbers according to the given probability table. * * @author Marco Guazzone (marco.guazzone@gmail.com) */ public final class DiscreteDistribution { private double[] _cdf; public DiscreteDistribution(double[] probs) { if (probs.length > 0) { this._cdf = new double[probs.length]; this._cdf[0] = probs[0]; for (int i = 0; i < probs.length; ++i) { this._cdf[i] = this._cdf[i-1]+probs[i]; } } } public int nextInt(Random rng) { double p = rng.nextDouble(); // for (int x = 0; x < this._cdf.length; ++x) // if (p > this._cdf[x]) // return x; // return this._cdf.length-1; int x = Arrays.binarySearch(this._cdf, p); return (x >= 0 ? x : -x); } }
package com.forecast.io; import android.os.Bundle; import android.app.Activity; import android.widget.Toast; import com.forecast.io.network.responses.INetworkResponse; import com.forecast.io.network.responses.NetworkResponse; import com.forecast.io.toolbox.NetworkServiceTask; import com.forecast.io.v1.network.requests.HourlyForecastService; import com.forecast.io.v1.network.requests.InterestingStormsService; import com.forecast.io.v1.network.requests.MultiplePointsService; import com.forecast.io.v1.network.responses.InterestingStormsResponse; import com.forecast.io.v1.network.responses.MultiplePointsTimesResponse; import com.forecast.io.v1.transfer.LatLng; public class MainActivity extends Activity { private static final String API_KEY = "8163ba583b4762bec42eb90eda85c893"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); HourlyForecastService.Request request = HourlyForecastService.Request.newBuilder( API_KEY ) .setForecastType( HourlyForecastService.ForecastType.FORECAST ) .setLatitude( 37.422006 ) .setLongitude(-122.084095) .build(); new NetworkServiceTask() { @Override protected void onPostExecute( INetworkResponse network ) { if ( network == null || network.getStatus() == NetworkResponse.Status.FAIL ) { Toast.makeText( MainActivity.this, "HOURLY ERROR", Toast.LENGTH_SHORT ).show(); return; } HourlyForecastService.Response response = (HourlyForecastService.Response) network; Toast.makeText( MainActivity.this, response.getForecastResponse().getCurrentSummary(), Toast.LENGTH_SHORT ).show(); } }.execute( request ); MultiplePointsService.Request multiple = MultiplePointsService.Request.newBuilder( API_KEY ) .setPoint( LatLng.newBuilder() .setLatitude(37.422006) .setLongitude(-122.084095) .setTime(1364956418)) .setPoint( LatLng.newBuilder() .setLatitude( 37.422006 ) .setLongitude( -122.084095 ) .setTime( 1364956418 ) ) .build(); new NetworkServiceTask() { @Override protected void onPostExecute( INetworkResponse network ) { if ( network == null || network.getStatus() == NetworkResponse.Status.FAIL ) { Toast.makeText( MainActivity.this, "MULTI POINT ERROR", Toast.LENGTH_SHORT ).show(); return; } MultiplePointsService.Response response = (MultiplePointsService.Response) network; MultiplePointsTimesResponse points = response.getMultiplePointsTimes(); Toast.makeText( MainActivity.this, points.getSkyPrecipitation() != null ? points.getSkyPrecipitation().get( 0 ).getType() : "NO MULTIPLE POINTS AND TIMES", Toast.LENGTH_SHORT ).show(); } }.execute( multiple ); new NetworkServiceTask() { @Override protected void onPostExecute( INetworkResponse network ) { if ( network == null || network.getStatus() == NetworkResponse.Status.FAIL ) { Toast.makeText( MainActivity.this, "INTERESTING STORMS ERROR", Toast.LENGTH_SHORT ).show(); return; } InterestingStormsService.Response response = (InterestingStormsService.Response) network; InterestingStormsResponse storms = response.getInterestingStorms(); Toast.makeText( MainActivity.this, storms.getInterestingStorms() != null ? storms.getInterestingStorms().get( 0 ).getCity() : "NO INTERESTING STORMS", Toast.LENGTH_SHORT ).show(); } }.execute( InterestingStormsService.Request.newBuilder( API_KEY ).build() ); } }
package org.akvo.flow.xml; import java.io.IOException; import java.util.List; import java.util.TreeMap; import org.akvo.flow.xml.PublishedForm; import org.akvo.flow.xml.XmlForm; import org.akvo.flow.xml.XmlQuestionGroup; import org.akvo.flow.xml.XmlQuestion; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.CascadeResource; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.Survey; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; class FlowXmlObjectWriterTests { private final static String EXPECTED_CASCADE_QUESTION = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey version=\"12.0\" name=\"This is a form\" defaultLanguageCode=\"en\" surveyGroupName=\"Name of containing survey\" surveyId=\"17\"><questionGroup repeatable=\"false\"><question id=\"1001\" order=\"1\" type=\"cascade\" mandatory=\"false\" localeNameFlag=\"false\" cascadeResource=\"cascade-123456789-v1.sqlite\"><text>This is question one</text></question><heading>This is a group</heading></questionGroup></survey>"; private final String expectedQuestionlessXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey version=\"11.0\" name=\"This is a form\" defaultLanguageCode=\"en\" surveyGroupName=\"Name of containing survey\" surveyId=\"17\"><questionGroup repeatable=\"false\"><heading>This is a group</heading></questionGroup></survey>"; private final String expectedMinimaXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey version=\"12.0\" name=\"This is a form\" defaultLanguageCode=\"en\" surveyGroupName=\"Name of containing survey\" surveyId=\"17\"><questionGroup repeatable=\"false\"><question id=\"1001\" order=\"1\" type=\"free\" mandatory=\"false\" localeNameFlag=\"false\"><text>This is question one</text></question><question id=\"1002\" order=\"2\" type=\"free\" mandatory=\"true\" localeNameFlag=\"false\"><validationRule validationType=\"numeric\" allowDecimal=\"false\" signed=\"false\"/><text>This is question two</text></question><question id=\"1003\" order=\"3\" type=\"geoshape\" mandatory=\"false\" localeNameFlag=\"false\" allowPoints=\"false\" allowLine=\"false\" allowPolygon=\"false\"><text>This is question three</text></question><heading>This is a group</heading></questionGroup></survey>"; private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); @BeforeEach public void setUp() { helper.setUp(); } @AfterEach public void tearDown() { helper.tearDown(); } @Test void testSerialiseEmptyForm() throws IOException { //Mock up a domain tree Survey form1 = new Survey(); form1.setKey(KeyFactory.createKey("Survey", 17L)); form1.setName("This is a form"); form1.setVersion(10.0); //No question groups. Completely empty form. //Convert domain tree to Jackson tree XmlForm form = new XmlForm(form1, "Name of containing survey"); //...and test it assertNotEquals(null, form); assertEquals(17L, form.getSurveyId()); assertEquals("This is a form", form.getName()); assertEquals("Name of containing survey", form.getSurveyGroupName()); assertEquals("10.0", form.getVersion()); assertNotEquals(null, form.getQuestionGroup()); assertEquals(0, form.getQuestionGroup().size()); //Convert Jackson tree into an XML string String xml = PublishedForm.generate(form); } @Test void testSerialiseQuestionlessForm() throws IOException { //Mock up a form tree Survey form1 = new Survey(); form1.setKey(KeyFactory.createKey("Survey", 17L)); form1.setName("This is a form"); form1.setVersion(11.0); //Add a QuestionGroup QuestionGroup qg = new QuestionGroup(); qg.setKey(KeyFactory.createKey("Survey", 18L)); qg.setSurveyId(17L); qg.setName("This is a group"); qg.setOrder(1); TreeMap<Integer, QuestionGroup> gl = new TreeMap<>(); gl.put(1, qg); form1.setQuestionGroupMap(gl); //No questions //Convert domain tree to Jackson tree XmlForm form = new XmlForm(form1, "Name of containing survey"); //...and test it assertNotEquals(null, form); assertNotEquals(null, form.getQuestionGroup()); List<XmlQuestionGroup> ga = form.getQuestionGroup(); assertEquals(1, ga.size()); assertEquals("This is a group", ga.get(0).getHeading()); assertEquals(1, ga.get(0).getOrder()); assertFalse(ga.get(0).getRepeatable()); //Convert Jackson tree into an XML string String xml = PublishedForm.generate(form); assertEquals(expectedQuestionlessXml, xml); //And finally parse to DTO to see that it is valid SurveyDto dto = PublishedForm.parse(xml, true).toDto(); //be strict assertNotEquals(null, dto); assertEquals(17L, dto.getKeyId()); assertEquals("This is a form", dto.getName()); assertEquals("11.0", dto.getVersion()); assertEquals("This is a form", dto.getName()); } @Test void testSerialiseMinimalForm() throws IOException { //Mock up a DTO tree Survey form1 = new Survey(); form1.setKey(KeyFactory.createKey("Survey", 17L)); form1.setName("This is a form"); form1.setVersion(12.0); //Add a QuestionGroup QuestionGroup qg = new QuestionGroup(); qg.setKey(KeyFactory.createKey("Survey", 18L)); qg.setSurveyId(17L); qg.setName("This is a group"); qg.setOrder(1); TreeMap<Integer, QuestionGroup> gm = new TreeMap<>(); gm.put(1, qg); form1.setQuestionGroupMap(gm); TreeMap<Integer,Question> qm = new TreeMap<>(); qg.setQuestionMap(qm); //Add some questions //Intentionally do not set mandatory; it should be null Question q1 = new Question(); q1.setKey(KeyFactory.createKey("Question", 1001L)); //Must have a key q1.setOrder(1); q1.setText("This is question one"); q1.setType(Question.Type.FREE_TEXT); qm.put(1,q1); Question q2 = new Question(); q2.setKey(KeyFactory.createKey("Question", 1002L)); //Must have a key q2.setOrder(2); q2.setText("This is question two"); q2.setType(Question.Type.NUMBER); q2.setMandatoryFlag(true); qm.put(2,q2); Question q3 = new Question(); q3.setKey(KeyFactory.createKey("Question", 1003L)); //Must have a key q3.setOrder(3); q3.setText("This is question three"); q3.setType(Question.Type.GEOSHAPE); q3.setMandatoryFlag(false); qm.put(3,q3); int questionCount = qm.size(); //Convert domain tree to Jackson tree XmlForm form = new XmlForm(form1, "Name of containing survey"); //...and test it assertNotEquals(null, form); assertNotEquals(null, form.getQuestionGroup()); XmlQuestionGroup xqg = form.getQuestionGroup().get(0); assertNotEquals(null, xqg); assertNotEquals(null, xqg.getQuestion()); assertEquals(questionCount, xqg.getQuestion().size()); XmlQuestion xq1 = xqg.getQuestion().get(0); assertNotEquals(null, xq1); assertEquals(1001L, xq1.getId()); assertEquals("This is question one", xq1.getText()); assertEquals(Boolean.FALSE, xq1.getMandatory()); assertEquals("free", xq1.getType()); XmlQuestion xq2 = xqg.getQuestion().get(1); assertNotEquals(null, xq2); assertEquals(1002L, xq2.getId()); assertEquals("This is question two", xq2.getText()); assertEquals(Boolean.TRUE, xq2.getMandatory()); assertEquals("free", xq2.getType()); XmlQuestion xq3 = xqg.getQuestion().get(2); assertNotEquals(null, xq3); assertEquals(1003L, xq3.getId()); assertEquals("This is question three", xq3.getText()); assertEquals(Boolean.FALSE, xq3.getMandatory()); assertEquals("geoshape", xq3.getType()); //Convert Jackson tree into an XML string String xml = PublishedForm.generate(form); assertEquals(expectedMinimaXml, xml); //And finally parse it to a DTO SurveyDto dto = PublishedForm.parse(xml, true).toDto(); //be strict assertNotEquals(null, dto); assertEquals(17L, dto.getKeyId()); assertEquals("This is a form", dto.getName()); assertEquals("12.0", dto.getVersion()); assertEquals("This is a form", dto.getName()); } @Test void testSerialiseFormWithCascade() throws IOException { //Mock up a DTO tree Survey form1 = new Survey(); form1.setKey(KeyFactory.createKey("Survey", 17L)); form1.setName("This is a form"); form1.setVersion(12.0); //Add a QuestionGroup QuestionGroup qg = new QuestionGroup(); qg.setKey(KeyFactory.createKey("QuestionGroup", 18L)); qg.setSurveyId(17L); qg.setName("This is a group"); qg.setOrder(1); TreeMap<Integer, QuestionGroup> gm = new TreeMap<>(); gm.put(1, qg); form1.setQuestionGroupMap(gm); TreeMap<Integer,Question> qm = new TreeMap<>(); qg.setQuestionMap(qm); //Add some questions //Intentionally do not set mandatory; it should be null Question q1 = new Question(); q1.setKey(KeyFactory.createKey("Question", 1001L)); //Must have a key q1.setOrder(1); q1.setText("This is question one"); q1.setType(Question.Type.CASCADE); CascadeResource cr = new CascadeResource(); cr.setKey(KeyFactory.createKey("CascadeResource", 123456789L)); cr.setVersion(1); q1.setCascadeResource(cr.getResourceId()); qm.put(1, q1); int questionCount = qm.size(); //Convert domain tree to Jackson tree XmlForm form = new XmlForm(form1, "Name of containing survey"); //...and test it assertNotEquals(null, form); assertNotEquals(null, form.getQuestionGroup()); XmlQuestionGroup xqg = form.getQuestionGroup().get(0); assertNotEquals(null, xqg); assertNotEquals(null, xqg.getQuestion()); assertEquals(questionCount, xqg.getQuestion().size()); XmlQuestion xq1 = xqg.getQuestion().get(0); assertNotEquals(null, xq1); assertEquals(1001L, xq1.getId()); assertEquals("This is question one", xq1.getText()); assertEquals(Boolean.FALSE, xq1.getMandatory()); assertEquals("cascade", xq1.getType()); assertEquals("cascade-123456789-v1.sqlite", xq1.getCascadeResource()); //Convert Jackson tree into an XML string String xml = PublishedForm.generate(form); assertEquals(EXPECTED_CASCADE_QUESTION, xml); //And finally parse it to a DTO SurveyDto dto = PublishedForm.parse(xml, true).toDto(); //be strict assertNotEquals(null, dto); assertEquals(17L, dto.getKeyId()); assertEquals("This is a form", dto.getName()); assertEquals("12.0", dto.getVersion()); assertEquals("This is a form", dto.getName()); } }
/* * $Id: TestArchiveMembers.java,v 1.9 2012-11-06 17:17:27 fergaloy-sf Exp $ */ package org.lockss.plugin.base; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import java.math.BigInteger; import junit.framework.*; import de.schlichtherle.truezip.file.*; import org.lockss.plugin.*; import org.lockss.plugin.PluginManager.CuContentReq; import org.lockss.plugin.simulated.*; import org.lockss.config.*; import org.lockss.daemon.*; import org.lockss.test.*; import org.lockss.util.*; import org.lockss.truezip.*; import org.lockss.repository.*; /** Tests for CachedUrls that refer to archive members */ public class TestArchiveMembers extends LockssTestCase { protected static Logger log = Logger.getLogger("TestArchiveMembers"); private MockLockssDaemon daemon; PluginManager pluginMgr; private String tempDirPath; private SimulatedArchivalUnit simau; MySimulatedArchivalUnit msau; String url1 = "http: String url2 = "http: String url3 = "http: public void setUp() throws Exception { super.setUp(); tempDirPath = setUpDiskSpace(); ConfigurationUtil.addFromArgs(TrueZipManager.PARAM_CACHE_DIR, tempDirPath); daemon = getMockLockssDaemon(); pluginMgr = daemon.getPluginManager(); pluginMgr.setLoadablePluginsReady(true); daemon.setDaemonInited(true); pluginMgr.startService(); daemon.getTrueZipManager().startService(); daemon.getAlertManager(); daemon.getCrawlManager(); // // make and start a UrlManager to set up the URLStreamHandlerFactory // UrlManager uMgr = new UrlManager(); // uMgr.initService(daemon); // daemon.setDaemonInited(true); // uMgr.startService(); TConfig config = TConfig.get(); config.setLenient(false); simau = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin.class, simAuConfig(tempDirPath)); msau = (MySimulatedArchivalUnit)simau; simau.generateContentTree(); msau.setArchiveFileTypes(ArchiveFileTypes.DEFAULT); } public void tearDown() throws Exception { simau.deleteContentTree(); getMockLockssDaemon().stopDaemon(); daemon.getTrueZipManager().stopService(); super.tearDown(); } Configuration simAuConfig(String rootPath) { Configuration conf = ConfigManager.newConfiguration(); conf.put("root", rootPath); conf.put("depth", "2"); conf.put("branch", "8"); conf.put("numFiles", "2"); conf.put("fileTypes", "" + (SimulatedContentGenerator.FILE_TYPE_HTML + SimulatedContentGenerator.FILE_TYPE_XML)); conf.put("redirectDirToIndex", "true"); conf.put("autoGenIndexHtml", "true"); return conf; } CachedUrl memberCu(String url, String memberName) throws IOException { CachedUrl cu0 = simau.makeCachedUrl(url); assertTrue(cu0.hasContent()); return cu0.getArchiveMemberCu(ArchiveMemberSpec.fromCu(cu0, memberName)); } void assertNoArchive(String url, String memberName) throws IOException { CachedUrl cu0 = simau.makeCachedUrl(url); assertFalse(cu0.hasContent()); CachedUrl cu = cu0.getArchiveMemberCu(ArchiveMemberSpec.fromCu(cu0, memberName)); assertFalse(cu.hasContent()); assertNull(cu.getUnfilteredInputStream()); } void assertNoArchiveMember(String url, String memberName) throws IOException { CachedUrl cu0 = simau.makeCachedUrl(url); assertTrue(cu0.hasContent()); CachedUrl cu = cu0.getArchiveMemberCu(ArchiveMemberSpec.fromCu(cu0, memberName)); assertFalse(cu.hasContent()); assertNull(cu.getUnfilteredInputStream()); } void assertArchiveMember(String expContentRe, String expMime, long expSize, String url, String memberName) throws IOException { CachedUrl cu0 = simau.makeCachedUrl(url); assertTrue(cu0.hasContent()); CachedUrl cu = cu0.getArchiveMemberCu(ArchiveMemberSpec.fromCu(cu0, memberName)); assertArchiveMemberCu(expContentRe, expMime, expSize, url + "!/" + memberName, cu); } void assertArchiveMemberCu(String expContentRe, String expMime, long expSize, String expMembUrl, CachedUrl cu) throws IOException { assertArchiveMemberCu(expContentRe, expMime, expSize, expMembUrl, cu, null); } void assertArchiveMemberCu(String expContentRe, String expMime, long expSize, String expMembUrl, CachedUrl cu, CachedUrl arcCu) throws IOException { assertClass(BaseCachedUrl.Member.class, cu); assertTrue(cu.hasContent()); assertEquals(expMembUrl, cu.getUrl()); InputStream is = cu.getUnfilteredInputStream(); assertNotNull("getUnfilteredInputStream was null: " + cu, is); String s = StringUtil.fromInputStream(is); is.close(); assertMatchesRE(expContentRe, s); assertEquals(expSize, cu.getContentSize()); Properties props = cu.getProperties(); assertEquals(expSize, props.get("Length")); assertEquals(expMembUrl, props.get(CachedUrl.PROPERTY_NODE_URL)); assertEquals(expMime, props.get(CachedUrl.PROPERTY_CONTENT_TYPE)); if (arcCu != null) { Properties arcProps = arcCu.getProperties(); // Last-Modified should be present and not the same as that of the // archive (see BaseCachedUrl.synthesizeProperties() ) assertNotEquals(arcProps.get(CachedUrl.PROPERTY_LAST_MODIFIED), props.get(CachedUrl.PROPERTY_LAST_MODIFIED)); } assertNotNull(props.get(CachedUrl.PROPERTY_LAST_MODIFIED)); } public void testReadMember() throws Exception { PluginTestUtil.crawlSimAu(simau); String aurl = "http: assertArchiveMember("file 1, depth 0, branch 0", "text/html", 226, aurl, "001file.html"); assertArchiveMember("file 2, depth 0, branch 0", "text/html", 226, aurl, "002file.html"); assertArchiveMember("<key>file</key><value>2</value>.*<key>depth</key><value>2</value>", "application/xml", 230, aurl, "branch5/branch2/002file.xml"); assertNoArchiveMember(aurl, "none.html"); assertNoArchiveMember(aurl, "branch0/002file.html"); assertNoArchive(aurl + "bogus", "branch0/002file.html"); assertNoArchive("bogus" + aurl, "branch0/002file.html"); } public void testIll() throws Exception { PluginTestUtil.crawlSimAu(simau); String aurl = "http: String memberName = "001file.html"; CachedUrl cu0 = simau.makeCachedUrl(aurl); assertTrue(cu0.hasContent()); CachedUrl cu = cu0.getArchiveMemberCu(ArchiveMemberSpec.fromCu(cu0, memberName)); try { cu.getArchiveMemberCu(ArchiveMemberSpec.fromCu(cu, memberName)); fail("Shouldn't be able to create a CU member from a CU member"); } catch (UnsupportedOperationException e) { } try { cu.getCuVersion(1); fail("Shouldn't be able to get a version of a CU member"); } catch (UnsupportedOperationException e) { } try { cu.getCuVersions(3); fail("Shouldn't be able to get versions of a CU member"); } catch (UnsupportedOperationException e) { } } public void testIter1() throws Exception { PluginTestUtil.crawlSimAu(simau); String aurl = "http: CachedUrlSet cus = simau.makeCachedUrlSet(new RangeCachedUrlSetSpec(aurl)); Iterator<CachedUrl> iter = cus.archiveMemberIterator(); int cnt = 0; while (iter.hasNext()) { CachedUrl cu = iter.next(); assertTrue(cu.hasContent()); cnt++; } assertEquals(16, cnt); } List<String> readLinesFromResource(String resource) throws IOException { InputStream urlsIn = this.getClass().getResourceAsStream(resource); BufferedReader rdr = new BufferedReader(StringUtil.getLineReader(urlsIn)); List<String> res = new ArrayList<String>(); for (String line = rdr.readLine(); line != null; line = rdr.readLine()) { line = line.trim(); if (StringUtil.startsWithIgnoreCase(line, " continue; } res.add(line); } return res; } Pattern pat = Pattern.compile(".*?(?:branch([0-9])/)?(?:branch([0-9])/)?00([0-9])file\\.html"); public void testIter2() throws Exception { PluginTestUtil.crawlSimAu(simau); CachedUrlSet cus = simau.makeCachedUrlSet(new AuCachedUrlSetSpec()); List urls = readLinesFromResource("srcpub_urls.txt"); Iterator<CachedUrl> cuIter = cus.archiveMemberIterator(); Iterator<String> urlIter = urls.iterator(); int cnt = 0; int htmlcnt = 0; boolean didCheckDelete = false; while (cuIter.hasNext()) { CachedUrl cu = cuIter.next(); String url = cu.getUrl(); assertTrue(cu.hasContent()); assertEquals(url, urlIter.next(), url); cnt++; // This won't work until we add the necessary logic to recreate // TFiles that have been umounted // // While traversing an archive, delete the temp file backing that // // archive, then continue the iteration to ensure that the TFile // // remains usable even though its file has ben deleted. Just // // documenting that it works in this case - I don't know whether the // // TFile contract allows it or if we need a locking protocol to // // prevent it. // String trigger = "branch5/002file.xml"; // if (url.equals(arcurl + "!/" + trigger)) { // CachedUrl arccu = simau.makeCachedUrl(arcurl); // org.lockss.truezip.TFileCache tfc = // getMockLockssDaemon().getTrueZipManager().getTFileCache(); // org.lockss.truezip.TFileCache.Entry ent = // tfc.getCachedTFileEntry(arccu); // assertTrue(ent.isValid()); // assertTrue(ent.exists()); // tfc.flushEntry(ent); // assertFalse(ent.isValid()); // assertFalse(ent.exists()); // didCheckDelete = true; Matcher m1 = pat.matcher(url); if (m1.matches()) { htmlcnt++; int depth = (m1.group(1) != null ? 1 : 0) + (m1.group(2) != null ? 1 : 0); String expContent = String.format("This is file %s, depth %s, branch %s", m1.group(3), depth, (m1.group(2) != null ? m1.group(2) : (m1.group(1) != null ? m1.group(1) : "0"))); String content = stringFromCu(cu); assertEquals(content.length(), cu.getContentSize()); assertMatchesRE(url, expContent, content); } } assertEquals(urls.size(), cnt++); assertEquals(170, htmlcnt); // assertTrue(didCheckDelete); } public void testIterPruned() throws Exception { PluginTestUtil.crawlSimAu(simau); CachedUrlSetSpec cuss = PrunedCachedUrlSetSpec.excludeMatchingSubTrees("http: "http: CachedUrlSet cus = simau.makeCachedUrlSet(cuss); List urls = new ArrayList(); for (String s : readLinesFromResource("srcpub_urls.txt")) { if (!s.matches(".*\\.zip.*")) { urls.add(s); } } Iterator<CachedUrl> cuIter = cus.archiveMemberIterator(); Iterator<String> urlIter = urls.iterator(); int cnt = 0; int htmlcnt = 0; while (cuIter.hasNext()) { CachedUrl cu = cuIter.next(); String url = cu.getUrl(); assertTrue(cu.hasContent()); assertEquals(url, urlIter.next(), url); cnt++; Matcher m1 = pat.matcher(url); if (m1.matches()) { htmlcnt++; int depth = (m1.group(1) != null ? 1 : 0) + (m1.group(2) != null ? 1 : 0); String expContent = String.format("This is file %s, depth %s, branch %s", m1.group(3), depth, (m1.group(2) != null ? m1.group(2) : (m1.group(1) != null ? m1.group(1) : "0"))); String content = stringFromCu(cu); assertEquals(content.length(), cu.getContentSize()); assertMatchesRE(url, expContent, content); } } assertEquals(urls.size(), cnt++); assertEquals(106, htmlcnt); } void copyCu(String fromUrl, String toUrl) throws IOException { CachedUrl cu = simau.makeCachedUrl(fromUrl); UrlCacher uc = simau.makeUrlCacher(toUrl); InputStream ins = cu.getUnfilteredInputStream(); CIProperties props = cu.getProperties(); props.setProperty(CachedUrl.PROPERTY_FETCH_TIME, Long.toString(TimeBase.nowMs())); uc.storeContent(ins, props); } // Sample of URLs in recent archives String[] shouldContain = { "http: "http: "http: "http: "http: "http: "http: "http: "http: "http: "http: "http: "http: "http: }; // Sample of URLs in old archives String[] shouldNotContain = { "http: "http: "http: "http: "http: "http: "http: "http: }; public void testIterExcludeFilesUnchangedAfter() throws Exception { TimeBase.setSimulated(100000); PluginTestUtil.crawlSimAu(simau); TimeBase.setSimulated(500000); copyCu("http: "http: TimeBase.setSimulated(700000); copyCu("http: "http: CachedUrlSet cus = simau.makeCachedUrlSet(new AuCachedUrlSetSpec()); cus.setExcludeFilesUnchangedAfter(200000); Set urls = new HashSet(); Iterator<CachedUrl> cuIter = cus.archiveMemberIterator(); while (cuIter.hasNext()) { CachedUrl cu = cuIter.next(); urls.add(cu.getUrl()); } for (String url : shouldContain) { assertContains(urls, url); } for (String url : shouldNotContain) { assertDoesNotContain(urls, url); } assertEquals(108, urls.size()); cus.setExcludeFilesUnchangedAfter(600000); Set urls2 = new HashSet(); Iterator<CachedUrl> cuIter2 = cus.archiveMemberIterator(); while (cuIter2.hasNext()) { CachedUrl cu = cuIter2.next(); urls2.add(cu.getUrl()); } assertEquals(92, urls2.size()); } public void testFindCu() throws Exception { PluginTestUtil.crawlSimAu(simau); CachedUrl cu; String arcUrl = "http: cu = pluginMgr.findCachedUrl(arcUrl + "!/001file.html"); assertArchiveMemberCu("file 1, depth 0, branch 0", "text/html", 226, arcUrl + "!/001file.html", cu); // The archive file itesle cu = pluginMgr.findCachedUrl(arcUrl); assertTrue(cu.hasContent()); assertEquals(5162, cu.getContentSize()); cu = pluginMgr.findCachedUrl(arcUrl + "!/no/such/member"); assertNull(cu); cu = pluginMgr.findCachedUrl(arcUrl + "!/no/such/member", CuContentReq.DontCare); assertFalse(cu.hasContent()); cu = pluginMgr.findCachedUrl(arcUrl + "nofile!/no/such/member"); assertNull(cu); cu = pluginMgr.findCachedUrl(arcUrl + "nofile!/no/such/member", CuContentReq.DontCare); assertFalse(cu.hasContent()); // If AU has no archive file types, currently CU will still be a Member // but with no content. Must use a different member name because of // PluginManager.recentCuMap msau.setArchiveFileTypes(null); cu = pluginMgr.findCachedUrl(arcUrl + "!/002file.html"); assertNull(cu); cu = pluginMgr.findCachedUrl(arcUrl + "!/002file.html", CuContentReq.DontCare); assertNotClass(BaseCachedUrl.Member.class, cu); assertFalse(cu.hasContent()); } String stringFromCu(CachedUrl cu) throws IOException { InputStream is = cu.getUnfilteredInputStream(); try { return StringUtil.fromInputStream(is); } finally { IOUtil.safeClose(is); } } public static class MySimulatedPlugin extends SimulatedPlugin { public SimulatedContentGenerator getContentGenerator(Configuration cf, String fileRoot) { return new MySimulatedContentGenerator(fileRoot); } public ArchivalUnit createAu0(Configuration auConfig) throws ArchivalUnit.ConfigurationException { ArchivalUnit au = new MySimulatedArchivalUnit(this); au.setConfiguration(auConfig); return au; } } public static class MySimulatedArchivalUnit extends SimulatedArchivalUnit { ArchiveFileTypes aft = null; public MySimulatedArchivalUnit(Plugin owner) { super(owner); } public ArchiveFileTypes getArchiveFileTypes() { return aft; } public void setArchiveFileTypes(ArchiveFileTypes aft) { this.aft = aft; } } public static class MySimulatedContentGenerator extends SimulatedContentGenerator { protected MySimulatedContentGenerator(String fileRoot) { super(fileRoot); } @Override public String generateContentTree() { File rootDir = new File(contentRoot); InputStream in = this.getClass().getResourceAsStream("srcpub.zip"); try { ZipUtil.unzip(in, rootDir); } catch (Exception e) { throw new RuntimeException("Couldn't unzip prototype srcpub tree", e); } finally { IOUtil.safeClose(in); } return rootDir.toString(); } } private static class MyCachedUrl extends BaseCachedUrl { private boolean gotUnfilteredStream = false; private boolean gotFilteredStream = false; private CIProperties props = new CIProperties(); public MyCachedUrl(ArchivalUnit au, String url) { super(au, url); props.setProperty(PROPERTY_CONTENT_TYPE, "text/html"); } public InputStream getUnfilteredInputStream() { gotUnfilteredStream = true; return null; } public boolean gotUnfilteredStream() { return gotUnfilteredStream; } protected InputStream getFilteredStream() { gotFilteredStream = true; return super.getFilteredStream(); } public boolean hasContent() { throw new UnsupportedOperationException("Not implemented"); } public Reader openForReading() { return new StringReader("Test"); } public CIProperties getProperties() { return props; } public void setProperties(CIProperties props) { this.props = props; } } }
package com.github.commonsrdf.dummyimpl; import com.github.commonsrdf.api.BlankNodeOrIRI; import com.github.commonsrdf.api.IRI; import com.github.commonsrdf.api.RDFTerm; import com.github.commonsrdf.api.Triple; public class TripleImpl implements Triple { private BlankNodeOrIRI subject; private IRI predicate; private RDFTerm object; public TripleImpl(BlankNodeOrIRI subject, IRI predicate, RDFTerm object) { this.subject = subject; this.predicate = predicate; this.object = object; } @Override public BlankNodeOrIRI getSubject() { return subject; } @Override public IRI getPredicate() { return predicate; } @Override public RDFTerm getObject() { return object; } @Override public String toString() { return getSubject().ntriplesString() + " " + getPredicate().ntriplesString() + " " + getObject().ntriplesString() + " ."; } }
package com.github.davidmoten.rx.jdbc; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import rx.Observable; import rx.util.functions.Func1; import rx.util.functions.Func2; import com.github.davidmoten.rx.jdbc.tuple.Tuple2; import com.github.davidmoten.rx.jdbc.tuple.Tuple3; import com.github.davidmoten.rx.jdbc.tuple.Tuple4; import com.github.davidmoten.rx.jdbc.tuple.Tuple5; import com.github.davidmoten.rx.jdbc.tuple.Tuple6; import com.github.davidmoten.rx.jdbc.tuple.Tuple7; import com.github.davidmoten.rx.jdbc.tuple.TupleN; public class DatabaseTest { private static final Logger log = Logger.getLogger(DatabaseTest.class); private static AtomicInteger dbNumber = new AtomicInteger(); @Test public void testOldStyle() { Connection con = connectionProvider().get(); createDatabase(con); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("select name from person where name > ?"); ps.setObject(1, "ALEX"); rs = ps.executeQuery(); List<String> list = new ArrayList<String>(); while (rs.next()) { list.add(rs.getString(1)); } assertEquals(asList("FRED", "JOSEPH", "MARMADUKE"), list); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (ps != null) try { ps.close(); } catch (SQLException e) { } try { con.close(); } catch (SQLException e) { } } } @Test public void testSimpleExample() { Observable<String> names = db().select( "select name from person order by name").getAs(String.class); // convert the names to a list for unit test List<String> list = names.toList().toBlockingObservable().single(); log.debug(list); assertEquals(asList("FRED", "JOSEPH", "MARMADUKE"), list); } @Test public void testCountQuery() { int count = db().select("select name from person where name >?") .parameter("ALEX").get().count().first().toBlockingObservable() .single(); assertEquals(3, count); } @Test public void testTransactionUsingCount() { Database db = db(); Func1<? super Integer, Boolean> isZero = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer t1) { return t1 == 0; } }; db.beginTransaction(); Observable<Integer> existingRows = db .select("select name from person where name=?") .parameter("FRED").get().count().filter(isZero); db.update("insert into person(name,score) values(?,0)") .parameters(existingRows.map(Util.constant("FRED"))).getCount(); boolean committed = db.commit().toBlockingObservable().single(); assertTrue(committed); } @Test public void testTransactionOnCommit() { Database db = db().beginTransaction(); Observable<Integer> updateCount = db .update("update person set score=?").parameter(99).getCount(); db.commit(updateCount); long count = db.select("select count(*) from person where score=?") .parameter(99).dependsOnLastTransaction().getAs(Long.class) .toBlockingObservable().single(); assertEquals(3, count); } @Test public void testTransactionOnCommitDoesntOccurUnlessSubscribedTo() { Database db = db(); db.beginTransaction(); Observable<Integer> u = db.update("update person set score=?") .parameter(99).getCount(); db.commit(u); // note that last transaction was not listed as a dependency of the next // query long count = db.select("select count(*) from person where score=?") .parameter(99).getAs(Long.class).toBlockingObservable() .single(); assertEquals(0, count); } @Test public void testTransactionOnRollback() { Database db = db(); db.beginTransaction(); Observable<Integer> updateCount = db .update("update person set score=?").parameter(99).getCount(); db.rollback(updateCount); long count = db.select("select count(*) from person where score=?") .parameter(99).dependsOnLastTransaction().getAs(Long.class) .toBlockingObservable().single(); assertEquals(0, count); } @Test public void testUseParameterObservable() { int count = db().select("select name from person where name >?") .parameters(Observable.from("ALEX")).get().count().first() .toBlockingObservable().single(); assertEquals(3, count); } @Test public void testTwoParameters() { List<String> list = db() .select("select name from person where name > ? and name < ?") .parameter("ALEX").parameter("LOUIS").getAs(String.class) .toList().toBlockingObservable().single(); assertEquals(asList("FRED", "JOSEPH"), list); } @Test public void testTakeFewerThanAvailable() { int count = db().select("select name from person where name >?") .parameter("ALEX").get().take(2).count().first() .toBlockingObservable().single(); assertEquals(2, count); } @Test public void testJdbcObservableCountLettersInAllNames() { Func1<ResultSet, Integer> countLettersInName = new Func1<ResultSet, Integer>() { @Override public Integer call(ResultSet rs) { try { return rs.getString("name").length(); } catch (SQLException e) { throw new RuntimeException(e); } } }; int count = Observable .sumInteger( db().select("select name from person where name >?") .parameter("ALEX").get(countLettersInName)) .first().toBlockingObservable().single(); assertEquals(19, count); } @Test public void testTransformToTuple2AndTestActionsPrintln() { Tuple2<String, Integer> tuple = db() .select("select name,score from person where name >? order by name") .parameter("ALEX").getAs(String.class, Integer.class).last() .toBlockingObservable().single(); assertEquals("MARMADUKE", tuple.value1()); assertEquals(25, (int) tuple.value2()); } @Test public void testTransformToTupleN() { TupleN<String> tuple = db() .select("select name, lower(name) from person order by name") .getTupleN(String.class).first().toBlockingObservable() .single(); assertEquals("FRED", tuple.values().get(0)); assertEquals("fred", tuple.values().get(1)); } @Test public void testMultipleSetsOfParameters() { List<Integer> list = db() .select("select score from person where name=?") .parameter("FRED").parameter("JOSEPH").getAs(Integer.class) .toSortedList().toBlockingObservable().single(); assertEquals(asList(21, 34), list); } @Test public void testNoParams() { List<Tuple2<String, Integer>> tuples = db() .select("select name, score from person where name=? order by name") .getAs(String.class, Integer.class).toList() .toBlockingObservable().single(); assertEquals(0, tuples.size()); } @Test public void testComposition2() { log.debug("running testComposition2"); Func1<Integer, Boolean> isZero = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer count) { return count == 0; } }; Database db = db(); Observable<Integer> existingRows = db .select("select name from person where name=?") .parameter("FRED").getAs(String.class).count().filter(isZero); List<Integer> counts = db .update("insert into person(name,score) values(?,?)") .parameters(existingRows).getCount().toList() .toBlockingObservable().single(); assertEquals(0, counts.size()); } @Test public void testEmptyResultSet() { int count = db().select("select name from person where name >?") .parameters(Observable.from("ZZTOP")).get().count().first() .toBlockingObservable().single(); assertEquals(0, count); } @Test public void testMixingExplicitAndObservableParameters() { String name = db() .select("select name from person where name > ? and score < ? order by name") .parameter("BARRY").parameters(Observable.from(100)) .getAs(String.class).first().toBlockingObservable().single(); assertEquals("FRED", name); } @Test public void testInstantiateDatabaseWithUrl() throws SQLException { Database db = new Database("jdbc:h2:mem:test" + dbNumber.incrementAndGet()); Connection con = db.getQueryContext().connectionProvider().get(); con.close(); } @Test public void testComposition() { // use composition to find the first person alphabetically with // a score less than the person with the last name alphabetically // whose name is not XAVIER. Two threads and connections will be used. Database db = db(); Observable<Integer> score = db .select("select score from person where name <> ? order by name") .parameter("XAVIER").getAs(Integer.class).last(); String name = db .select("select name from person where score < ? order by name") .parameters(score).getAs(String.class).first() .toBlockingObservable().single(); assertEquals("FRED", name); } @Test public void testCompositionTwoLevels() { Database db = db(); Observable<String> names = db.select( "select name from person order by name").getAs(String.class); Observable<String> names2 = db .select("select name from person where name<>? order by name") .parameters(names).parameters(names).getAs(String.class); List<String> list = db.select("select name from person where name>?") .parameters(names2).getAs(String.class).toList() .toBlockingObservable().single(); System.out.println(list); assertEquals(12, list.size()); } @Test(expected = RuntimeException.class) public void testSqlProblem() { String name = db().select("select name from pperson where name >?") .parameter("ALEX").getAs(String.class).first() .toBlockingObservable().single(); log.debug(name); } @Test(expected = ClassCastException.class) public void testException() { Integer name = db().select("select name from person where name >?") .parameter("ALEX").getAs(Integer.class).first() .toBlockingObservable().single(); log.debug(name); } @Test public void testDependsUsingAsynchronousQueriesWaitsForFirstByDelayingCalculation() { Database db = db(); Observable<Integer> insert = db .update("insert into person(name,score) values(?,?)") .parameters("JOHN", 45) .getCount() .zip(Observable.interval(100, TimeUnit.MILLISECONDS), new Func2<Integer, Long, Integer>() { @Override public Integer call(Integer t1, Long t2) { return t1; } }); int count = db.select("select name from person").dependsOn(insert) .get().count().toBlockingObservable().single(); assertEquals(4, count); } @Test public void testAutoMapWillMapStringToStringAndIntToDouble() { Person person = db() .select("select name,score,dob,registered from person order by name") .autoMap(Person.class).first().toBlockingObservable().single(); assertEquals("FRED", person.getName()); assertEquals(21, person.getScore(), 0.001); assertNull(person.getDateOfBirth()); } @Test public void testGetTimestamp() { Database db = db(); java.sql.Timestamp registered = new java.sql.Timestamp(100); Observable<Integer> u = db .update("update person set registered=? where name=?") .parameter(registered).parameter("FRED").getCount(); Date regTime = db.select("select registered from person order by name") .dependsOn(u).getAs(Date.class).first().toBlockingObservable() .single(); assertEquals(100, regTime.getTime()); } @Test public void insertClobAndReadAsString() throws SQLException { Database db = db(); insertClob(db); // read clob as string String text = db.select("select document from person_clob") .getAs(String.class).first().toBlockingObservable().single(); assertTrue(text.contains("about Fred")); } private static void insertClob(Database db) { int count = db .update("insert into person_clob(name,document) values(?,?)") .parameter("FRED") .parameter( "A description about Fred that is rather long and needs a Clob to store it") .getCount().toBlockingObservable().single(); assertEquals(1, count); } private static void insertBlob(Database db) { int count = db .update("insert into person_blob(name,document) values(?,?)") .parameter("FRED") .parameter( "A description about Fred that is rather long and needs a Clob to store it" .getBytes()).getCount().toBlockingObservable() .single(); assertEquals(1, count); } @Test public void insertClobAndReadAsReader() throws SQLException, IOException { Database db = db(); insertClob(db); // read clob as Reader String text = db.select("select document from person_clob") .getAs(Reader.class).map(Util.READER_TO_STRING).first() .toBlockingObservable().single(); assertTrue(text.contains("about Fred")); } @Test public void insertBlobAndReadAsByteArray() throws SQLException { Database db = db(); insertBlob(db); // read clob as string byte[] bytes = db.select("select document from person_blob") .getAs(byte[].class).first().toBlockingObservable().single(); assertTrue(new String(bytes).contains("about Fred")); } @Test public void testInsertNull() { int count = db() .update("insert into person(name,score,dob) values(?,?,?)") .parameters("JACK", 42, null).getCount().toBlockingObservable() .single(); assertEquals(1, count); } @Test public void testAutoMap() { TimeZone current = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("AEST")); Database db = db(); Date dob = new Date(100); long now = System.currentTimeMillis(); java.sql.Timestamp registered = new java.sql.Timestamp(now); Observable<Integer> u = db .update("update person set dob=?, registered=? where name=?") .parameter(dob).parameter(registered).parameter("FRED") .getCount(); Person person = db .select("select name,score,dob,registered from person order by name") .dependsOn(u).autoMap(Person.class).first() .toBlockingObservable().single(); assertEquals("FRED", person.getName()); assertEquals(21, person.getScore(), 0.001); // Dates are truncated to start of day assertEquals(0, (long) person.getDateOfBirth()); assertEquals(now, (long) person.getRegistered()); } finally { TimeZone.setDefault(current); } } @Test public void testLastTransactionWithoutTransaction() { Database db = db(); List<Boolean> list = db.getLastTransactionResult().toList() .toBlockingObservable().single(); assertTrue(list.isEmpty()); } @Test public void testTuple3() { Tuple3<String, Integer, String> tuple = db() .select("select name,1,lower(name) from person order by name") .getAs(String.class, Integer.class, String.class).first() .toBlockingObservable().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); } @Test public void testTuple4() { Tuple4<String, Integer, String, Integer> tuple = db() .select("select name,1,lower(name),2 from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class) .first().toBlockingObservable().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); } @Test public void testTuple5() { Tuple5<String, Integer, String, Integer, String> tuple = db() .select("select name,1,lower(name),2,name from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class).first() .toBlockingObservable().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); assertEquals("FRED", tuple.value5()); } @Test public void testTuple6() { Tuple6<String, Integer, String, Integer, String, Integer> tuple = db() .select("select name,1,lower(name),2,name,3 from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class).first() .toBlockingObservable().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); assertEquals("FRED", tuple.value5()); assertEquals(3, (int) tuple.value6()); } @Test public void testTuple7() { Tuple7<String, Integer, String, Integer, String, Integer, Integer> tuple = db() .select("select name,1,lower(name),2,name,3,4 from person order by name") .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class, Integer.class).first().toBlockingObservable().single(); assertEquals("FRED", tuple.value1()); assertEquals(1, (int) tuple.value2()); assertEquals("fred", tuple.value3()); assertEquals(2, (int) tuple.value4()); assertEquals("FRED", tuple.value5()); assertEquals(3, (int) tuple.value6()); assertEquals(4, (int) tuple.value7()); } @Test public void testAutoMapClob() { Database db = db(); insertClob(db); List<PersonClob> list = db .select("select name, document from person_clob") .autoMap(PersonClob.class).toList().toBlockingObservable() .single(); assertEquals(1, list.size()); assertEquals("FRED", list.get(0).getName()); assertTrue(list.get(0).getDocument().contains("rather long")); } @Test public void testAutoMapBlob() { Database db = db(); insertBlob(db); List<PersonBlob> list = db .select("select name, document from person_blob") .autoMap(PersonBlob.class).toList().toBlockingObservable() .single(); assertEquals(1, list.size()); assertEquals("FRED", list.get(0).getName()); assertTrue(new String(list.get(0).getDocument()) .contains("rather long")); } static class PersonClob { private final String name; private final String document; public PersonClob(String name, String document) { this.name = name; this.document = document; } public String getName() { return name; } public String getDocument() { return document; } } static class PersonBlob { private final String name; private final byte[] document; public PersonBlob(String name, byte[] document) { this.name = name; this.document = document; } public String getName() { return name; } public byte[] getDocument() { return document; } } static class Person { private final String name; private final double score; private final Long dateOfBirthEpochMs; private final Long registered; Person(String name, double score, Long dateOfBirthEpochMs, Long registered) { this.name = name; this.score = score; this.dateOfBirthEpochMs = dateOfBirthEpochMs; this.registered = registered; } public String getName() { return name; } public double getScore() { return score; } public Long getDateOfBirth() { return dateOfBirthEpochMs; } public Long getRegistered() { return registered; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Pair [name="); builder.append(name); builder.append(", score="); builder.append(score); builder.append("]"); return builder.toString(); } } private ConnectionProvider connectionProvider() { return new ConnectionProviderFromUrl("jdbc:h2:mem:test" + dbNumber.incrementAndGet() + ";DB_CLOSE_DELAY=-1"); } private Database db() { ConnectionProvider cp = connectionProvider(); createDatabase(cp.get()); return new Database(cp); } private static void createDatabase(Connection c) { try { c.setAutoCommit(true); c.prepareStatement( "create table person (name varchar(50) primary key, score int not null,dob date, registered timestamp)") .execute(); c.prepareStatement( "insert into person(name,score) values('FRED',21)") .execute(); c.prepareStatement( "insert into person(name,score) values('JOSEPH',34)") .execute(); c.prepareStatement( "insert into person(name,score) values('MARMADUKE',25)") .execute(); c.prepareStatement( "create table person_clob (name varchar(50) not null, document clob not null)") .execute(); c.prepareStatement( "create table person_blob (name varchar(50) not null, document blob not null)") .execute(); } catch (SQLException e) { throw new RuntimeException(e); } } }
package com.google.javascript.clutz; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assert_; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singletonList; import com.google.common.base.Joiner; import com.google.common.truth.FailureStrategy; import com.google.common.truth.StringSubject; import com.google.common.truth.Subject; import com.google.common.truth.SubjectFactory; import com.google.javascript.jscomp.SourceFile; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; /** * A subject that supports assertions on {@link DeclarationGenerator}'s results. */ class ProgramSubject extends Subject<ProgramSubject, ProgramSubject.Program> { enum Externs { NONE, PLATFORM, THIRD_PARTY_AND_PLATFORM,; static Externs fromTestName(String name) { if (name.contains("_3p_externs")) return Externs.THIRD_PARTY_AND_PLATFORM; if (name.contains("_externs")) return PLATFORM; return NONE; } } /** A stripped down version of Closure's base.js for Clutz tests. */ private static final SourceFile CLUTZ_GOOG_BASE = SourceFile.fromFile("src/test/java/com/google/javascript/clutz/base.js", UTF_8); static ProgramSubject assertThatProgram(String... sourceLines) { String sourceText = Joiner.on('\n').join(sourceLines); return assert_().about(ProgramSubject.FACTORY).that(new Program(sourceText)); } static ProgramSubject assertThatProgram(File singleInput) { return assertThatProgram(singletonList(singleInput), Collections.<File>emptyList()); } static ProgramSubject assertThatProgram(List<File> roots, List<File> nonroots) { Program program = new Program(roots, nonroots); return assert_().about(ProgramSubject.FACTORY).that(program); } static final SubjectFactory<ProgramSubject, ProgramSubject.Program> FACTORY = new SubjectFactory<ProgramSubject, ProgramSubject.Program>() { @Override public ProgramSubject getSubject(FailureStrategy fs, ProgramSubject.Program that) { return new ProgramSubject(fs, that); } }; static final List<SourceFile> NO_EXTERNS = Collections.emptyList(); static final List<SourceFile> THIRD_PARTY_EXTERNS = singletonList(SourceFile.fromFile("src/resources/third_party_externs.js")); private Externs externs = Externs.NONE; ProgramSubject(FailureStrategy failureStrategy, ProgramSubject.Program subject) { super(failureStrategy, subject); } ProgramSubject withExterns(Externs newExterns) { ProgramSubject result = assert_().about(ProgramSubject.FACTORY).that(getSubject()); result.externs = newExterns; return result; } void generatesDeclarations(String expected) { String[] parseResult = parse(); assertThat(parseResult[1].isEmpty()); String actual = parseResult[0]; String stripped = DeclarationGeneratorTests.GOLDEN_FILE_COMMENTS_REGEXP.matcher(actual).replaceAll(""); if (!stripped.equals(expected)) { failureStrategy.failComparing("compilation result doesn't match", expected, stripped); } } StringSubject diagnosticStream() { String[] parseResult = parse(); return assertThat(parseResult[1]); } private String[] parse() throws AssertionError { Options opts = new Options(externs == Externs.NONE); opts.debug = true; List<SourceFile> sourceFiles = new ArrayList<>(); // base.js is needed for the type declaration of goog.require for // all tests, except the base.js one itself. if (getSubject().roots.isEmpty() || !getSubject().roots.get(0).getName().equals("base.js")) { sourceFiles.add(CLUTZ_GOOG_BASE); } for (File nonroot : getSubject().nonroots) { sourceFiles.add(SourceFile.fromFile(nonroot, UTF_8)); } List<String> roots = new ArrayList<>(); for (File root : getSubject().roots) { sourceFiles.add(SourceFile.fromFile(root, UTF_8)); roots.add(root.getPath()); } if (getSubject().sourceText != null) { sourceFiles.add(SourceFile.fromCode("main.js", getSubject().sourceText)); roots.add("main.js"); } List<SourceFile> externFiles; switch (externs) { case NONE: externFiles = NO_EXTERNS; break; case PLATFORM: externFiles = DeclarationGenerator.getDefaultExterns(opts); break; case THIRD_PARTY_AND_PLATFORM: externFiles = DeclarationGenerator.getDefaultExterns(opts); externFiles.addAll(THIRD_PARTY_EXTERNS); break; default: throw new AssertionError(); } PrintStream err = System.err; try { // Admittedly the PrintStream setting is a bit hacky, but it's closest to how users would // run Clutz. ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); DeclarationGenerator generator = new DeclarationGenerator(opts); String dts = generator.generateDeclarations(sourceFiles, externFiles, new Depgraph(roots)); String diagnostics = out.toString(); return new String[] {dts, diagnostics}; } finally { System.setErr(err); } } static class Program { private final List<File> roots; private final List<File> nonroots; @Nullable private final String sourceText; Program(String sourceText) { this.roots = Collections.emptyList(); this.nonroots = Collections.emptyList(); this.sourceText = sourceText; } Program(List<File> roots, List<File> nonroots) { this.roots = roots; this.nonroots = nonroots; this.sourceText = null; } } }
package algorithms.imageProcessing; import algorithms.util.PairInt; import algorithms.util.ResourceFinder; import algorithms.util.PairIntArray; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import static org.junit.Assert.*; /** * * @author nichole */ public class ContourFinderTest extends TestCase { public ContourFinderTest() { } public void testFindContours() throws Exception { String filePath = ResourceFinder.findFileInTestResources( "closed_curve.png"); ImageExt img = ImageIOHelper.readImageExt(filePath); CurvatureScaleSpaceImageMaker instance = new CurvatureScaleSpaceImageMaker(img); instance.useLineDrawingMode(); instance.initialize(); assertTrue(instance.getInitialized()); List<PairIntArray> curves = instance.getClosedCurves(); //Collections.sort(curves, new PairIntArrayComparator()); assertTrue(curves.size() == 1); Map<Float, ScaleSpaceCurve> scaleSpaceMap = instance.createScaleSpaceMetricsForEdge2(curves.get(0)); ScaleSpaceCurveImage scaleSpaceImage = instance.convertScaleSpaceMapToSparseImage(scaleSpaceMap, 0, curves.get(0).getN()); ContourFinder contourFinder = new ContourFinder(); List<CurvatureScaleSpaceContour> result = contourFinder.findContours( scaleSpaceImage, 0); debugPlot(result, ImageIOHelper.readImageExt(filePath), instance.getTrimmedXOffset(), instance.getTrimmedYOffset()); assertTrue(result.size() >= 3); /* there are 3 main large peaks around the inner curves of the clover, and with a better line thinner, there are now peaks for the inflection points around the large lobes, but unevenly so. so, will assert the 3 large inner curve peaks */ List<Float> expectedScaleFreeLength = new ArrayList<Float>(); List<Float> expectedPeakSigma = new ArrayList<Float>(); List<Integer> expectedEdgeNumber = new ArrayList<Integer>(); List<PairInt> expectedPeakCoords0 = new ArrayList<PairInt>(); List<PairInt> expectedPeakCoords1 = new ArrayList<PairInt>(); expectedScaleFreeLength.add(Float.valueOf(0.51f)); expectedPeakSigma.add(Float.valueOf(32)); expectedEdgeNumber.add(Integer.valueOf(0)); expectedPeakCoords0.add(new PairInt(24, 59)); expectedPeakCoords1.add(new PairInt(23, 71)); expectedScaleFreeLength.add(Float.valueOf(0.17f)); expectedPeakSigma.add(Float.valueOf(27.5f)); expectedEdgeNumber.add(Integer.valueOf(0)); expectedPeakCoords0.add(new PairInt(58, 43)); expectedPeakCoords1.add(new PairInt(51, 37)); expectedScaleFreeLength.add(Float.valueOf(0.87f)); expectedPeakSigma.add(Float.valueOf(27.5f)); expectedEdgeNumber.add(Integer.valueOf(0)); expectedPeakCoords0.add(new PairInt(52, 88)); expectedPeakCoords1.add(new PairInt(60, 83)); Set<Integer> found = new HashSet<Integer>(); for (int i = 0; i < result.size(); i++) { CurvatureScaleSpaceContour contour = result.get(i); float sfl = contour.getPeakScaleFreeLength(); float sigma = contour.getPeakSigma(); int edgeNumber = contour.getEdgeNumber(); CurvatureScaleSpaceImagePoint[] peakDetails = contour.getPeakDetails(); for (int j = 0; j < expectedScaleFreeLength.size(); j++) { Integer index = Integer.valueOf(j); if (found.contains(index)) { continue; } if (Math.abs(sfl - expectedScaleFreeLength.get(j)) < 0.15f) { if (Math.abs(sigma - expectedPeakSigma.get(j)) < 5f) { if (edgeNumber == expectedEdgeNumber.get(j)) { PairInt exp0 = expectedPeakCoords0.get(j); PairInt exp1 = expectedPeakCoords1.get(j); if ( ((Math.abs(peakDetails[0].getXCoord() - exp0.getX()) < 5) && (Math.abs(peakDetails[0].getYCoord() - exp0.getY()) < 5))) { if ( ((Math.abs(peakDetails[1].getXCoord() - exp1.getX()) < 5) && (Math.abs(peakDetails[1].getYCoord() - exp1.getY()) < 5))) { found.add(index); break; } } else if ( ((Math.abs(peakDetails[1].getXCoord() - exp0.getX()) < 5) && (Math.abs(peakDetails[1].getYCoord() - exp0.getY()) < 5))) { if ( ((Math.abs(peakDetails[0].getXCoord() - exp1.getX()) < 5) && (Math.abs(peakDetails[0].getYCoord() - exp1.getY()) < 5))) { found.add(index); break; } } } } } } } assertTrue(found.size() == 3); } public void estFindContours2() throws Exception { String filePath = ResourceFinder.findFileInTestResources( "blox.gif"); //"closed_curve_translate.png"); ImageExt img = ImageIOHelper.readImageExt(filePath); CurvatureScaleSpaceImageMaker instance = new CurvatureScaleSpaceImageMaker(img); instance.initialize(); assertTrue(instance.getInitialized()); List<PairIntArray> curves = instance.getClosedCurves(); //Collections.sort(curves, new PairIntArrayComparator()); Map<Float, ScaleSpaceCurve> scaleSpaceMap = instance.createScaleSpaceMetricsForEdge2(curves.get(0)); ScaleSpaceCurveImage scaleSpaceImage = instance.convertScaleSpaceMapToSparseImage(scaleSpaceMap, 0, curves.get(0).getN()); ContourFinder contourFinder = new ContourFinder(); List<CurvatureScaleSpaceContour> result = contourFinder.findContours( scaleSpaceImage, 0); for (int i = 0; i < result.size(); i++) { CurvatureScaleSpaceContour c = result.get(i); CurvatureScaleSpaceImagePoint[] peakPoints = c.getPeakDetails(); int[] x = new int[peakPoints.length]; int[] y = new int[x.length]; for (int j = 0; j < x.length; j++) { x[j] = peakPoints[j].getXCoord(); y[j] = peakPoints[j].getYCoord(); } System.out.println("CONTOUR: (" + c.getPeakSigma() + ", " + c.getPeakScaleFreeLength() + ") at x=" + Arrays.toString(x) + " y=" + Arrays.toString(y)); } } public static void main(String[] args) { try { ContourFinderTest test = new ContourFinderTest(); test.testFindContours(); } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: " + e.getMessage()); } } private void debugPlot(List<CurvatureScaleSpaceContour> result, ImageExt img, int xOffset, int yOffset) throws IOException { if (result.isEmpty()) { return; } int nExtraForDot = 1; int rClr = 255; int gClr = 0; int bClr = 0; for (int i = 0; i < result.size(); i++) { CurvatureScaleSpaceContour cssC = result.get(i); CurvatureScaleSpaceImagePoint[] peakDetails = cssC.getPeakDetails(); for (CurvatureScaleSpaceImagePoint peakDetail : peakDetails) { int x = peakDetail.getXCoord() + xOffset; int y = peakDetail.getYCoord() + yOffset; for (int dx = (-1*nExtraForDot); dx < (nExtraForDot + 1); dx++) { float xx = x + dx; if ((xx > -1) && (xx < (img.getWidth() - 1))) { for (int dy = (-1*nExtraForDot); dy < (nExtraForDot + 1); dy++) { float yy = y + dy; if ((yy > -1) && (yy < (img.getHeight() - 1))) { img.setRGB((int)xx, (int)yy, rClr, gClr, bClr); } } } } } } String dirPath = ResourceFinder.findDirectory("bin"); ImageIOHelper.writeOutputImage(dirPath + "/contours.png", img); } }
package com.lambdaworks.redis; import static org.assertj.core.api.Assertions.*; import static org.junit.Assume.*; import java.io.File; import java.io.IOException; import java.util.Locale; import org.apache.log4j.Logger; import org.junit.Test; import io.netty.util.internal.SystemPropertyUtil; /** * @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a> */ public class UnixDomainSocketTest { protected Logger log = Logger.getLogger(getClass()); protected String key = "key"; protected String value = "value"; @Test public void standalone_Linux_x86_64_socket() throws Exception { linuxOnly(); RedisURI redisURI = getSocketRedisUri(); RedisClient redisClient = new RedisClient(redisURI); RedisConnection<String, String> connection = redisClient.connect(); someRedisAction(connection); connection.close(); redisClient.shutdown(); } private void linuxOnly() { String osName = SystemPropertyUtil.get("os.name").toLowerCase(Locale.UK).trim(); assumeTrue("Only supported on Linux, your os is " + osName, osName.startsWith("linux")); } private RedisURI getSocketRedisUri() throws IOException { File file = new File("work/socket-6479").getCanonicalFile(); return RedisURI.create(RedisURI.URI_SCHEME_REDIS_SOCKET + "://" + file.getCanonicalPath()); } private RedisURI getSentinelSocketRedisUri() throws IOException { File file = new File("work/socket-26379").getCanonicalFile(); return RedisURI.create(RedisURI.URI_SCHEME_REDIS_SOCKET + "://" + file.getCanonicalPath()); } @Test public void sentinel_Linux_x86_64_socket() throws Exception { linuxOnly(); RedisURI uri = new RedisURI(); uri.getSentinels().add(getSentinelSocketRedisUri()); uri.setSentinelMasterId("mymaster"); RedisClient redisClient = new RedisClient(uri); RedisConnection<String, String> connection = redisClient.connect(); someRedisAction(connection); connection.close(); RedisSentinelAsyncConnection<String, String> sentinelConnection = redisClient.connectSentinelAsync(); assertThat(sentinelConnection.ping().get()).isEqualTo("PONG"); sentinelConnection.close(); redisClient.shutdown(); } @Test public void sentinel_Linux_x86_64_socket_and_inet() throws Exception { linuxOnly(); RedisURI uri = new RedisURI(); uri.getSentinels().add(getSentinelSocketRedisUri()); uri.getSentinels().add(RedisURI.create(RedisURI.URI_SCHEME_REDIS + "://" + TestSettings.host() + ":26379")); uri.setSentinelMasterId("mymaster"); RedisClient redisClient = new RedisClient(uri); RedisSentinelAsyncConnection<String, String> sentinelConnection = redisClient .connectSentinelAsync(getSentinelSocketRedisUri()); log.info("Masters: " + sentinelConnection.masters().get()); try { redisClient.connect(); fail("Missing validation exception"); } catch (RedisConnectionException e) { assertThat(e).hasMessageContaining("You cannot mix unix domain socket and IP socket URI's"); } finally { redisClient.shutdown(); } } private void someRedisAction(RedisConnection<String, String> connection) { connection.set(key, value); String result = connection.get(key); assertThat(result).isEqualTo(value); } }
package de.jowisoftware.sshclient; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.Timer; import org.apache.commons.io.IOUtils; import de.jowisoftware.sshclient.settings.AWTProfile; import de.jowisoftware.sshclient.terminal.events.DisplayType; import de.jowisoftware.sshclient.ui.SSHConsole; public class DebugConsoleMain { public static void main(final String args[]) throws Exception { new DebugConsoleMain().run(); } public void run() throws Exception { final InputStream stream = getClass().getClassLoader().getResourceAsStream("debug.txt"); if (stream == null) { JOptionPane.showMessageDialog(null, "place debug.txt in src/test/resource (and re-run mvn package)"); return; } final String text = readFile(stream); final SSHConsole console = showFrame(); (new Thread("network-simulator") { @Override public void run() { try { Thread.sleep(1000); } catch (final InterruptedException e) { throw new RuntimeException(e); } console.gotChars(text.getBytes(), text.getBytes().length); } }).start(); } private SSHConsole showFrame() { final JFrame frame = new JFrame("test"); final SSHConsole console = new SSHConsole(new AWTProfile()); frame.add(console); startTimer(console); frame.setSize(630, 480); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); console.setOutputStream(System.out); console.setDisplayType(DisplayType.FIXED80X24); return console; } private void startTimer(final SSHConsole console) { final Timer timer = new Timer(200, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { console.redrawConsole(); } }); timer.setRepeats(true); timer.start(); } private String readFile(final InputStream stream) throws IOException { final String text = IOUtils.toString(stream, "UTF-8").replace("\n", "").replace("\r", ""); IOUtils.closeQuietly(stream); final StringBuffer builder = new StringBuffer(); final Matcher m = Pattern.compile("(\\\\(\\\\|n|r|u[0-9a-fA-F]{4}))").matcher(text); while(m.find()) { final String g = m.group(2); final String rep; if (g.equals("n")) { rep = "\n"; } else if (g.equals("r")) { rep = "\r"; } else if (g.equals("\\")) { rep = "\\"; } else { rep = Character.toString((char) Integer.parseInt(g.substring(1).toUpperCase(), 16)); } m.appendReplacement(builder, rep.replace("\\", "\\\\")); } m.appendTail(builder); String result = builder.toString(); if (result.contains(" result = result.substring(0, result.indexOf(" } return result; } }
package jstore.testhelpers.rivals; import java.util.Arrays; import java.util.Collection; import jstore.Messages; import jstore.StringSet; public abstract class StringSetFactory { public StringSet create(String[] strings) { if (strings == null) { throw new IllegalArgumentException(Messages.STRING_COLLECTION_CAN_NOT_BE_NULL); } return create(Arrays.asList(strings)); } public abstract StringSet create(Collection<String> strings); }
package org.amc.game.chessserver; import static org.amc.game.chessserver.StompController.MESSAGE_HEADER_TYPE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import org.amc.DAOException; import org.amc.dao.DAO; import org.amc.dao.EntityManagerCache; import org.amc.dao.ServerChessGameDAO; import org.amc.game.chess.ChessBoardUtilities; import org.amc.game.chess.HumanPlayer; import org.amc.game.chess.Move; import org.amc.game.chess.Player; import org.amc.game.chessserver.ServerChessGameFactory.GameType; import org.amc.game.chessserver.observers.JsonChessGameView; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.AbstractSubscribableChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.WebApplicationContext; import java.security.Principal; import java.util.HashMap; import java.util.List; import java.util.Map; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({ "/SpringTestConfig.xml", "/GameServerSecurity.xml", "/GameServerWebSockets.xml", "/EmailServiceContext.xml" }) public class StompControllerIT { private static final String SESSION_ID = "20"; private static final String SUBSCRIPTION_ID = "20"; private static final String SESSION_ATTRIBUTE = "PLAYER"; private static final String MESSAGE_DESTINATION = "/app/move/"; private static final String SAVE_MESSAGE_DESTINATION = "/app/save/"; private static final String ONEVIEW_MESSAGE_DESTINATION = "/app/oneViewMove/"; @Autowired private WebApplicationContext wac; @Autowired private AbstractSubscribableChannel clientInboundChannel; @Autowired private AbstractSubscribableChannel clientOutboundChannel; @Autowired private AbstractSubscribableChannel brokerChannel; private TestChannelInterceptor clientOutboundChannelInterceptor; private TestChannelInterceptor brokerChannelInterceptor; private final long gameUUID = 1234L; private final long oneViewChessGameUUID = 4321L; private String[] moves = { "A2-A3", "A7-A6", "B2-B3", "B7-B6", "C2-C3", "C7-C6", "D2-D3", "D7-D6", "E2-E3", "E7-E6", "F2-F3", "F7-F6", "G2-G3", "G7-G6", "H2-H3", "H7-H6" }; private DatabaseSignUpFixture fixture = new DatabaseSignUpFixture(); private DAO<Player> playerDAO; private Player stephen; private Player nobby; private JsonChessGameView view; private SimpMessagingTemplate template; private ServerChessGameDAO serverChessGameDAO; @Before public void setup() throws Exception { fixture.setUp(); playerDAO = new DAO<Player>(HumanPlayer.class); stephen = playerDAO.findEntities("userName", "stephen").get(0); nobby = playerDAO.findEntities("userName", "nobby").get(0); this.brokerChannelInterceptor = new TestChannelInterceptor();
package org.cojen.tupl.repl; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TransferQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.cojen.tupl.Cursor; import org.cojen.tupl.Database; import org.cojen.tupl.DatabaseConfig; import org.cojen.tupl.EventPrinter; import org.cojen.tupl.Index; import org.cojen.tupl.LockResult; import org.cojen.tupl.Transaction; import org.cojen.tupl.UnmodifiableReplicaException; import org.cojen.tupl.ext.RecoveryHandler; import org.cojen.tupl.io.Utils; import org.cojen.tupl.TestUtils; import org.junit.*; import static org.junit.Assert.*; /** * * * @author Brian S O'Neill */ public class DatabaseReplicatorTest { public static void main(String[] args) throws Exception { org.junit.runner.JUnitCore.main(DatabaseReplicatorTest.class.getName()); } @Before public void setup() throws Exception { } @After public void teardown() throws Exception { if (mDatabases != null) { for (Database db : mDatabases) { if (db != null) { db.close(); } } } TestUtils.deleteTempFiles(getClass()); } private ServerSocket[] mSockets; private File[] mReplBaseFiles; private int[] mReplPorts; private ReplicatorConfig[] mReplConfigs; private DatabaseReplicator[] mReplicators; private DatabaseConfig[] mDbConfigs; private Database[] mDatabases; /** * @return first is the leader */ private Database[] startGroup(int members) throws Exception { return startGroup(members, Role.NORMAL, null); } /** * @return first is the leader */ private Database[] startGroup(int members, Role replicaRole, Supplier<RecoveryHandler> handlerSupplier) throws Exception { if (members < 1) { throw new IllegalArgumentException(); } mSockets = new ServerSocket[members]; for (int i=0; i<members; i++) { mSockets[i] = new ServerSocket(0); } mReplBaseFiles = new File[members]; mReplPorts = new int[members]; mReplConfigs = new ReplicatorConfig[members]; mReplicators = new DatabaseReplicator[members]; mDbConfigs = new DatabaseConfig[members]; mDatabases = new Database[members]; for (int i=0; i<members; i++) { mReplBaseFiles[i] = TestUtils.newTempBaseFile(getClass()); mReplPorts[i] = mSockets[i].getLocalPort(); mReplConfigs[i] = new ReplicatorConfig() .groupToken(1) .localSocket(mSockets[i]) .baseFile(mReplBaseFiles[i]); if (i > 0) { mReplConfigs[i].addSeed(mSockets[0].getLocalSocketAddress()); mReplConfigs[i].localRole(replicaRole); } mReplicators[i] = DatabaseReplicator.open(mReplConfigs[i]); mDbConfigs[i] = new DatabaseConfig() .baseFile(mReplBaseFiles[i]) .replicate(mReplicators[i]) //.eventListener(new EventPrinter()) .lockTimeout(5, TimeUnit.SECONDS) .directPageAccess(false); if (handlerSupplier != null) { mDbConfigs[i].recoveryHandler(handlerSupplier.get()); } Database db = Database.open(mDbConfigs[i]); mDatabases[i] = db; readyCheck: { for (int trial=0; trial<100; trial++) { Thread.sleep(100); if (i == 0) { try { db.openIndex("control"); // Ensure that replicas obtain the index in the snapshot. db.checkpoint(); break readyCheck; } catch (UnmodifiableReplicaException e) { // Not leader yet. } } else { assertNotNull(db.openIndex("control")); break readyCheck; } } throw new AssertionError(i == 0 ? "No leader" : "Not joined"); } } return mDatabases; } @Test public void basicTestOneMember() throws Exception { basicTest(1); } @Test public void basicTestThreeMembers() throws Exception { for (int i=3; --i>=0; ) { try { basicTest(3); break; } catch (UnmodifiableReplicaException e) { // Test is load sensitive and leadership is sometimes lost. if (i <= 0) { throw e; } teardown(); } } } private void basicTest(int memberCount) throws Exception { Database[] dbs = startGroup(memberCount); Index ix0 = dbs[0].openIndex("test"); for (int t=0; t<10; t++) { byte[] key = ("hello-" + t).getBytes(); byte[] value = ("world-" + t).getBytes(); ix0.store(null, key, value); TestUtils.fastAssertArrayEquals(value, ix0.load(null, key)); for (int i=0; i<dbs.length; i++) { for (int q=100; --q>=0; ) { byte[] actual = null; try { Index ix = dbs[i].openIndex("test"); actual = ix.load(null, key); TestUtils.fastAssertArrayEquals(value, actual); break; } catch (UnmodifiableReplicaException e) { // Index doesn't exist yet due to replication delay. if (q == 0) { throw e; } } catch (AssertionError e) { // Value doesn't exist yet due to replication delay. if (q == 0 || actual != null) { throw e; } } TestUtils.sleep(100); } } } } @Test public void txnPrepare() throws Exception { for (int i=3; --i>=0; ) { try { doTxnPrepare(); break; } catch (UnmodifiableReplicaException e) { // Test is load sensitive and leadership is sometimes lost. if (i <= 0) { throw e; } teardown(); } } } private void doTxnPrepare() throws Exception { // Test that unfinished prepared transactions are passed to the new leader. TransferQueue<Database> recovered = new LinkedTransferQueue<>(); Supplier<RecoveryHandler> supplier = () -> new RecoveryHandler() { private Database mDb; @Override public void init(Database db) { mDb = db; } @Override public void recover(Transaction txn) throws IOException { try { recovered.transfer(mDb); // Wait for the signal... recovered.take(); // Modify the value before committing. Index ix = mDb.openIndex("test"); Cursor c = ix.newCursor(txn); c.find("hello".getBytes()); byte[] newValue = Arrays.copyOfRange(c.value(), 0, c.value().length + 1); newValue[newValue.length - 1] = '!'; c.store(newValue); c.reset(); txn.commit(); } catch (Exception e) { throw Utils.rethrow(e); } } }; final int memberCount = 3; Database[] dbs = startGroup(memberCount, Role.NORMAL, supplier); Index ix0 = dbs[0].openIndex("test"); // Wait for all members to be electable. allElectable: { int count = 0; for (int i=0; i<100; i++) { count = 0; for (DatabaseReplicator repl : mReplicators) { if (repl.getLocalRole() == Role.NORMAL) { count++; } } if (count >= mReplicators.length) { break allElectable; } Thread.sleep(100); } fail("Not all members are electable: " + count); } Transaction txn = dbs[0].newTransaction(); byte[] key = "hello".getBytes(); ix0.store(txn, key, "world".getBytes()); txn.prepare(); // Close the leader and verify handoff. dbs[0].close(); Database db = recovered.take(); assertNotEquals(dbs[0], db); // Still locked. Index ix = db.openIndex("test"); txn = db.newTransaction(); assertEquals(LockResult.TIMED_OUT_LOCK, ix.tryLockShared(txn, key, 0)); txn.reset(); // Signal that the handler can finish the transaction. recovered.add(db); assertArrayEquals("world!".getBytes(), ix.load(null, key)); // Verify replication. Database remaining = dbs[1]; if (remaining == db) { remaining = dbs[2]; } ix = remaining.openIndex("test"); for (int i=10; --i>=0; ) { try { assertArrayEquals("world!".getBytes(), ix.load(null, key)); break; } catch (Throwable e) { if (i <= 0) { throw e; } Thread.sleep(100); } } } @Test public void largeWrite() throws Exception { Database[] dbs = startGroup(1); Database db = dbs[0]; Index ix = db.openIndex("test"); byte[] value = new byte[100_000]; Arrays.fill(value, 0, value.length, (byte) 0x7f); byte[] key = "hello".getBytes(); Transaction txn = db.newTransaction(); Cursor c = ix.newCursor(txn); c.find(key); // This used to hang due to a bug. The commit index was too high, and so it wouldn't be // confirmed. c.commit(value); db.checkpoint(); db = closeAndReopen(0); ix = db.openIndex("test"); TestUtils.fastAssertArrayEquals(value, ix.load(null, key)); db.close(); } @Test public void valueWriteRecover() throws Exception { // Verifies that a checkpoint in the middle of a value write on the replica can still // properly recover the registered cursor. Database[] dbs = startGroup(2, Role.OBSERVER, null); Database leaderDb = dbs[0]; Database replicaDb = dbs[1]; Index leaderIx = leaderDb.openIndex("test"); Random rnd = new Random(); byte[] part1 = new byte[1000]; rnd.nextBytes(part1); byte[] part2 = new byte[1000]; rnd.nextBytes(part2); Transaction txn = leaderDb.newTransaction(); byte[] key = "key1".getBytes(); Cursor c = leaderIx.newAccessor(txn, key); c.valueWrite(0, part1, 0, part1.length); txn.flush(); // Wait for replica to catch up. fence(leaderDb, replicaDb); Index replicaIx = replicaDb.openIndex("test"); assertTrue(replicaIx.exists(Transaction.BOGUS, key)); replicaDb.checkpoint(); replicaDb = closeAndReopen(1); replicaIx = replicaDb.openIndex("test"); assertTrue(replicaIx.exists(Transaction.BOGUS, key)); // Finish writing and wait for replica to catch up. c.valueWrite(part1.length, part2, 0, part2.length); c.close(); txn.commit(); fence(leaderDb, replicaDb); byte[] expect = new byte[part1.length + part2.length]; System.arraycopy(part1, 0, expect, 0, part1.length); System.arraycopy(part2, 0, expect, part1.length, part2.length); TestUtils.fastAssertArrayEquals(expect, leaderIx.load(null, key)); TestUtils.fastAssertArrayEquals(expect, replicaIx.load(null, key)); replicaDb.close(); } /** * Writes a message to the "control" index, and block the replica until it's received. */ private void fence(Database leaderDb, Database replicaDb) throws Exception { Index leaderIx = leaderDb.openIndex("control"); Index replicaIx = replicaDb.openIndex("control"); byte[] key = (System.nanoTime() + ":" + ThreadLocalRandom.current().nextLong()).getBytes(); leaderIx.store(null, key, key); for (int i=0; i<1000; i++) { byte[] value = replicaIx.load(null, key); if (value != null) { if (Arrays.equals(key, value)) { return; } fail("Mismatched fence"); } Thread.sleep(10); } fail("No fence received"); } private Database closeAndReopen(int member) throws Exception { mDatabases[member].close(); // Replace closed socket. int port = mSockets[member].getLocalPort(); ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(port)); mReplConfigs[member].localSocket(ss); mReplicators[member] = DatabaseReplicator.open(mReplConfigs[member]); mDbConfigs[member].replicate(mReplicators[member]); return Database.open(mDbConfigs[member]); } }
package org.mariadb.jdbc; import org.junit.Assume; import org.junit.Test; import org.mariadb.jdbc.internal.util.pool.Pools; import org.mariadb.jdbc.internal.util.scheduler.MariaDbThreadFactory; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.sql.*; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public class MariaDbPoolDataSourceTest extends BaseTest { @Test public void testResetDatabase() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); statement.execute("CREATE DATABASE IF NOT EXISTS testingReset"); connection.setCatalog("testingReset"); } try (Connection connection = pool.getConnection()) { assertEquals(database, connection.getCatalog()); Statement statement = connection.createStatement(); statement.execute("DROP DATABASE testingReset"); } } } @Test public void testResetSessionVariable() throws SQLException { testResetSessionVariable(false); if ( (isMariadbServer() && minVersion(10,2)) || (!isMariadbServer() && minVersion(5,7)) ) { testResetSessionVariable(true); } } private void testResetSessionVariable(boolean useResetConnection) throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1&useResetConnection=" + useResetConnection)) { long nowMillis; int initialWaitTimeout; try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); nowMillis = getNowTime(statement); initialWaitTimeout = getWaitTimeout(statement); statement.execute("SET @@timestamp=UNIX_TIMESTAMP('1970-10-01 01:00:00'), @@wait_timeout=2000"); long newNowMillis = getNowTime(statement); int waitTimeout = getWaitTimeout(statement); assertTrue(nowMillis - newNowMillis > 23_587_200_000L); assertEquals(2_000, waitTimeout); } try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); long newNowMillis = getNowTime(statement); int waitTimeout = getWaitTimeout(statement); if (useResetConnection) { assertTrue(nowMillis - newNowMillis < 10L); assertEquals(initialWaitTimeout, waitTimeout); } else { assertTrue(nowMillis - newNowMillis > 23_587_200_000L); assertEquals(2_000, waitTimeout); } } } } private long getNowTime(Statement statement) throws SQLException { ResultSet rs = statement.executeQuery("SELECT NOW()"); assertTrue(rs.next()); return rs.getTimestamp(1).getTime(); } private int getWaitTimeout(Statement statement) throws SQLException { ResultSet rs = statement.executeQuery("SELECT @@wait_timeout"); assertTrue(rs.next()); return rs.getInt(1); } @Test public void testResetUserVariable() throws SQLException { testResetUserVariable(false); if ( (isMariadbServer() && minVersion(10,2)) || (!isMariadbServer() && minVersion(5,7)) ) { testResetUserVariable(true); } } private void testResetUserVariable(boolean useResetConnection) throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1&useResetConnection=" + useResetConnection)) { long nowMillis; try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); assertNull(getUserVariableStr(statement)); statement.execute("SET @str = '123'"); assertEquals("123", getUserVariableStr(statement)); } try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); if (useResetConnection) { assertNull(getUserVariableStr(statement)); } else { assertEquals("123", getUserVariableStr(statement)); } } } } private String getUserVariableStr(Statement statement) throws SQLException { ResultSet rs = statement.executeQuery("SELECT @str"); assertTrue(rs.next()); return rs.getString(1); } @Test public void testNetworkTimeout() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1&socketTimeout=10000")) { try (Connection connection = pool.getConnection()) { assertEquals(10_000, connection.getNetworkTimeout()); connection.setNetworkTimeout(null, 5_000); } try (Connection connection = pool.getConnection()) { assertEquals(10_000, connection.getNetworkTimeout()); } } } @Test public void testResetReadOnly() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { assertFalse(connection.isReadOnly()); connection.setReadOnly(true); assertTrue(connection.isReadOnly()); } try (Connection connection = pool.getConnection()) { assertFalse(connection.isReadOnly()); } } } @Test public void testResetAutoCommit() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { assertTrue(connection.getAutoCommit()); connection.setAutoCommit(false); assertFalse(connection.getAutoCommit()); } try (Connection connection = pool.getConnection()) { assertTrue(connection.getAutoCommit()); } } } @Test public void testResetAutoCommitOption() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1&autocommit=false&poolName=PoolTest")) { try (Connection connection = pool.getConnection()) { assertFalse(connection.getAutoCommit()); connection.setAutoCommit(true); assertTrue(connection.getAutoCommit()); } try (Connection connection = pool.getConnection()) { assertFalse(connection.getAutoCommit()); } } } @Test public void testResetTransactionIsolation() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { assertEquals(Connection.TRANSACTION_REPEATABLE_READ, connection.getTransactionIsolation()); connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); assertEquals(Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation()); } try (Connection connection = pool.getConnection()) { assertEquals(Connection.TRANSACTION_REPEATABLE_READ, connection.getTransactionIsolation()); } } } @Test public void testJmx() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=PoolTestJmx-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=5&minPoolSize=0&poolName=PoolTestJmx")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(1, objectNames.size()); ObjectName name = objectNames.iterator().next(); MBeanInfo info = server.getMBeanInfo(name); assertEquals(4, info.getAttributes().length); checkJmxInfo(server, name, 1, 1, 0, 0); try (Connection connection2 = pool.getConnection()) { checkJmxInfo(server, name, 2, 2, 0, 0); } checkJmxInfo(server, name, 1, 2, 1, 0); } } } @Test public void testNoMinConnection() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=testNoMinConnection-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=5&poolName=testNoMinConnection")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(1, objectNames.size()); ObjectName name = objectNames.iterator().next(); MBeanInfo info = server.getMBeanInfo(name); assertEquals(4, info.getAttributes().length); //wait to ensure pool has time to create 5 connections try { Thread.sleep(sharedIsAurora() ? 10_000 : 500); } catch (InterruptedException interruptEx) { //eat } checkJmxInfo(server, name, 1, 5, 4, 0); try (Connection connection2 = pool.getConnection()) { checkJmxInfo(server, name, 2, 5, 3, 0); } checkJmxInfo(server, name, 1, 5, 4, 0); } } } @Test public void testIdleTimeout() throws Throwable { Assume.assumeTrue(System.getenv("MAXSCALE_VERSION") == null); //not for maxscale, testing thread id is not relevant. MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=testIdleTimeout-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=5&minPoolSize=3&poolName=testIdleTimeout")) { pool.testForceMaxIdleTime(sharedIsAurora() ? 10 : 3); //wait to ensure pool has time to create 3 connections Thread.sleep(sharedIsAurora() ? 5_000 : 1_000); Set<ObjectName> objectNames = server.queryNames(filter, null); ObjectName name = objectNames.iterator().next(); checkJmxInfo(server, name, 0, 3, 3, 0); List<Long> initialThreadIds = pool.testGetConnectionIdleThreadIds(); Thread.sleep(sharedIsAurora() ? 12_000 : 3_500); //must still have 3 connections, but must be other ones checkJmxInfo(server, name, 0, 3, 3, 0); List<Long> threadIds = pool.testGetConnectionIdleThreadIds(); assertEquals(initialThreadIds.size(), threadIds.size()); for (Long initialThread : initialThreadIds) { assertFalse(threadIds.contains(initialThread)); } } } @Test public void testMinConnection() throws Throwable { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=testMinConnection-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=5&minPoolSize=3&poolName=testMinConnection")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(1, objectNames.size()); ObjectName name = objectNames.iterator().next(); MBeanInfo info = server.getMBeanInfo(name); assertEquals(4, info.getAttributes().length); //to ensure pool has time to create minimal connection number Thread.sleep(sharedIsAurora() ? 5000 : 500); checkJmxInfo(server, name, 1, 3, 2, 0); try (Connection connection2 = pool.getConnection()) { checkJmxInfo(server, name, 2, 3, 1, 0); } checkJmxInfo(server, name, 1, 3, 2, 0); } } } private void checkJmxInfo(MBeanServer server, ObjectName name, long expectedActive, long expectedTotal, long expectedIdle, long expectedRequest) throws Exception { assertEquals(expectedActive, ((Long) server.getAttribute(name, "ActiveConnections")).longValue()); assertEquals(expectedTotal, ((Long) server.getAttribute(name, "TotalConnections")).longValue()); assertEquals(expectedIdle, ((Long) server.getAttribute(name, "IdleConnections")).longValue()); assertEquals(expectedRequest, ((Long) server.getAttribute(name, "ConnectionRequests")).longValue()); } @Test public void testJmxDisable() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=PoolTest-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=2&registerJmxPool=false&poolName=PoolTest")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(0, objectNames.size()); } } } @Test public void testResetRollback() throws SQLException { createTable("testResetRollback", "id int not null primary key auto_increment, test varchar(20)"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO testResetRollback (test) VALUES ('heja')"); connection.setAutoCommit(false); stmt.executeUpdate("INSERT INTO testResetRollback (test) VALUES ('japp')"); } try (Connection connection = pool.getConnection()) { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT count(*) FROM testResetRollback"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); } } } @Test public void ensureUsingPool() throws Exception { ThreadPoolExecutor connectionAppender = new ThreadPoolExecutor(50, 5000, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5000), new MariaDbThreadFactory("testPool")); final long start = System.currentTimeMillis(); Set<Integer> threadIds = new HashSet<>(); for (int i = 0; i < 500; i++) { connectionAppender.execute(() -> { try (Connection connection = DriverManager.getConnection(connUri + "&pool&staticGlobal&poolName=PoolEnsureUsingPool&log=true")) { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT CONNECTION_ID()"); rs.next(); Integer connectionId = rs.getInt(1); if (!threadIds.contains(connectionId)) threadIds.add(connectionId); stmt.execute("SELECT * FROM mysql.user"); } catch (SQLException e) { e.printStackTrace(); } }); } connectionAppender.shutdown(); connectionAppender.awaitTermination(sharedIsAurora() ? 200 : 30, TimeUnit.SECONDS); int numberOfConnection = 0; for (Integer integer : threadIds) { System.out.println("Connection id : " + integer); numberOfConnection++; } System.out.println("Size : " + threadIds.size() + " " + numberOfConnection); assertTrue("connection ids must be less than 8 : " + numberOfConnection, numberOfConnection <= 8); assertTrue(System.currentTimeMillis() - start < (sharedIsAurora() ? 120_000 : 5_000)); Pools.close("PoolTest"); } @Test public void ensureClosed() throws Throwable { int initialConnection = getCurrentConnections(); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=10&minPoolSize=1")) { try (Connection connection = pool.getConnection()) { connection.isValid(10_000); } assertTrue(getCurrentConnections() > initialConnection); //reuse IdleConnection try (Connection connection = pool.getConnection()) { connection.isValid(10_000); } assertTrue(getCurrentConnections() > initialConnection); } assertEquals(initialConnection, getCurrentConnections()); } @Test public void wrongUrlHandling() throws SQLException { int initialConnection = getCurrentConnections(); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource("jdbc:mariadb://unknownHost/db?user=wrong&maxPoolSize=10&connectTimeout=500")) { pool.initialize(); long start = System.currentTimeMillis(); try (Connection connection = pool.getConnection()) { fail(); } catch (SQLException sqle) { assertTrue("timeout does not correspond to option. Elapsed time:" + (System.currentTimeMillis() - start), (System.currentTimeMillis() - start) >= 500 && (System.currentTimeMillis() - start) < 700); assertTrue(sqle.getMessage().contains("No connection available within the specified time (option 'connectTimeout': 500 ms)")); } } } //TODO check that threads are destroy when closing pool }
package org.rakam.kume.service.ringmap; import com.google.common.collect.ImmutableList; import org.rakam.kume.Cluster; import org.rakam.kume.ClusterBuilder; import org.rakam.kume.ClusterMembership; import org.rakam.kume.JoinerService; import org.rakam.kume.KumeTest; import org.rakam.kume.Member; import org.rakam.kume.MigrationListener; import org.rakam.kume.NoNetworkTransport; import org.rakam.kume.service.ServiceListBuilder; import org.rakam.kume.service.crdt.counter.GCounterService; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import static java.util.stream.IntStream.range; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class RingMapTest extends KumeTest { // @Test public void testMapNotEnoughNodeForReplication() throws InterruptedException, TimeoutException, ExecutionException, IOException { ImmutableList<ServiceListBuilder.Constructor> services = new ServiceListBuilder() .add("map", bus -> new RingMap<String, Long>(bus, GCounterService::merge, 2)).build(); Cluster cluster0 = new ClusterBuilder().services(services).start(); RingMap ringMap0 = cluster0.getService("map"); for (int i = 0; i < 1000; i++) { ringMap0.put("test" + System.currentTimeMillis() + i, i).get(); } assertEquals(ringMap0.getLocalSize(), 1000); } // @Test public void testMapReplication() throws InterruptedException, TimeoutException, ExecutionException { ImmutableList<ServiceListBuilder.Constructor> services = new ServiceListBuilder() .add("map", bus -> new RingMap<String, Long>(bus, GCounterService::merge, 2)).build(); List<Cluster> clusters = createFixedFakeCluster(2, services).map(ClusterBuilder::start).collect(Collectors.toList());; RingMap ringMap0 = clusters.get(0).getService("map"); RingMap ringMap1 = clusters.get(1).getService("map"); for (int i = 0; i < 100000; i++) { ringMap0.put("test" + i, 5).get(); } assertEquals(ringMap1.getLocalSize(), ringMap1.getLocalSize()); for (int i = 0; i < ringMap0.getBucketCount(); i++) { assertEquals(ringMap0.getBucket(i), ringMap1.getBucket(i)); } } // @Test public void testMapDistribution() throws InterruptedException, TimeoutException, ExecutionException { ImmutableList<ServiceListBuilder.Constructor> services = new ServiceListBuilder() .add("map", bus -> new RingMap<String, Long>(bus, GCounterService::merge, 1)).build(); List<Cluster> clusters = createFixedFakeCluster(2, services).map(ClusterBuilder::start).collect(Collectors.toList()); RingMap ringMap0 = clusters.get(0).getService("map"); RingMap ringMap1 = clusters.get(1).getService("map"); for (int i = 0; i < 100000; i++) { ringMap0.put("test" + i, 5).get(); } assertEquals(ringMap1.getLocalSize()+ringMap0.getLocalSize(), 100000); } // @Test public void testMapNewNode() throws InterruptedException, TimeoutException, ExecutionException { ImmutableList<ServiceListBuilder.Constructor> services = new ServiceListBuilder() .add("map", bus -> new RingMap<String, Long>(bus, GCounterService::merge, 2)).build(); Member baseMember = new Member("", 0); NoNetworkTransport baseTransport = new NoNetworkTransport(baseMember); ProxyJoinerService joinerService = new ProxyJoinerService(); Cluster cluster0 = new ClusterBuilder().transport(baseTransport::setContext) .joinStrategy(joinerService).services(services).serverAddress(baseMember.getAddress()) .start(); RingMap ringMap0 = cluster0.getService("map"); for (int i = 0; i < 100000; i++) { ringMap0.put("test" + i, 5).get(); } List<Cluster> newNodes = createFixedFakeCluster(range(1, 3), services).map(e -> { e.members().add(baseMember); return e.start(); }).collect(Collectors.toList()); RingMap ringMap1 = cluster0.getService("map"); BlockerMigrationListener blocker = new BlockerMigrationListener(); ringMap1.listenMigrations(blocker); newNodes.stream().map(Cluster::getTransport).forEach(tr -> baseTransport.addMember((NoNetworkTransport) tr)); newNodes.stream().map(Cluster::getLocalMember).forEach(joinerService::addMember); blocker.waitForMigrationEnd(); Thread.sleep(2000); System.out.println(1); // CompletableFuture<Map<Member, Integer>> size1 = ringMap1.size(); // Integer size = size1.join().values().stream().reduce((x, y) -> x + y).get(); // assertEquals(size.intValue(), 2000); } // @Test public void testMapNodeFailure() throws InterruptedException, TimeoutException, ExecutionException { ImmutableList<ServiceListBuilder.Constructor> services = new ServiceListBuilder() .add("map", bus -> new RingMap<String, Long>(bus, GCounterService::merge, 2)).build(); Cluster cluster0 = new ClusterBuilder().services(services).start(); Cluster cluster1 = new ClusterBuilder().services(services).start(); Cluster cluster2 = new ClusterBuilder().services(services).start(); waitForDiscovery(cluster0, 3); waitForDiscovery(cluster1, 3); waitForDiscovery(cluster2, 3); RingMap ringMap0 = cluster0.getService("map"); for (int i = 0; i < 1000; i++) { ringMap0.put("test" + i, 5).get(); } cluster2.close(); waitForMigrationEnd(ringMap0); CompletableFuture<Map<Member, Integer>> size1 = ringMap0.size(); Optional<Integer> test = size1.get().values().stream().reduce((i0, i1) -> i0 + i1); assertTrue(test.isPresent()); assertEquals(test.get().intValue(), 200); } private void waitForMigrationEnd(RingMap ringMap0) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); ringMap0.listenMigrations(new BlockerMigrationListener()); countDownLatch.await(); } // @Test public void testMapMultipleThreads() throws InterruptedException, TimeoutException, ExecutionException { ImmutableList<ServiceListBuilder.Constructor> services = new ServiceListBuilder() .add("map", bus -> new RingMap<String, Long>(bus, GCounterService::merge, 2)).build(); Cluster cluster0 = new ClusterBuilder().services(services).start(); new ClusterBuilder().services(services).start(); waitForDiscovery(cluster0, 1); RingMap ringMap0 = cluster0.getService("map"); RingMap ringMap1 = cluster0.getService("map"); CountDownLatch countDownLatch = new CountDownLatch(2); for (int i = 0; i < 10; i++) { final int finalI = i; new Thread(() -> { try { for (int i1 = 0; i1 < 100; i1++) { ringMap0.put("s0" + finalI + i1, finalI + i1).get(); } } catch (Exception e) { e.printStackTrace(); } countDownLatch.countDown(); }).run(); new Thread(() -> { try { for (int i1 = 0; i1 < 100; i1++) { ringMap1.put("s1" + finalI + i1, finalI + i1).get(); } } catch (Exception e) { e.printStackTrace(); } countDownLatch.countDown(); }).run(); } countDownLatch.await(); CompletableFuture<Map<Member, Integer>> size = ringMap1.size(); Optional<Integer> test = size.get().values().stream().reduce((i0, i1) -> i0 + i1); assertTrue(test.isPresent()); assertEquals(test.get().intValue(), 2000 * 2); } private static class ProxyJoinerService implements JoinerService { public ClusterMembership clusterMembership; @Override public void onStart(ClusterMembership membership) { this.clusterMembership = membership; } public void addMember(Member member) { clusterMembership.addMember(member); } } private static class BlockerMigrationListener implements MigrationListener { private CountDownLatch countDownLatch; public BlockerMigrationListener() { this.countDownLatch = new CountDownLatch(1); } @Override public void migrationStart(Member removedMember) { } @Override public void migrationEnd(Member removedMember) { countDownLatch.countDown(); } public void waitForMigrationEnd() throws InterruptedException { countDownLatch.await(); synchronized (this) { countDownLatch = new CountDownLatch(1); } } } }
package org.ethereum.mine; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Random; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytes; import static org.ethereum.mine.MinerIfc.MiningResult; public class Ethash { private static final Logger logger = LoggerFactory.getLogger("mine"); private static EthashParams ethashParams = new EthashParams(); private static Ethash cachedInstance = null; private static long cachedBlockEpoch = 0; // private static ExecutorService executor = Executors.newSingleThreadExecutor(); private static ListeningExecutorService executor = MoreExecutors.listeningDecorator( new ThreadPoolExecutor(8, 8, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactoryBuilder().setNameFormat("ethash-pool-%d").build())); public static boolean fileCacheEnabled = true; /** * Returns instance for the specified block number either from cache or calculates a new one */ public static Ethash getForBlock(SystemProperties config, long blockNumber) { long epoch = blockNumber / ethashParams.getEPOCH_LENGTH(); if (cachedInstance == null || epoch != cachedBlockEpoch) { cachedInstance = new Ethash(config, epoch * ethashParams.getEPOCH_LENGTH()); cachedBlockEpoch = epoch; } return cachedInstance; } private EthashAlgo ethashAlgo = new EthashAlgo(ethashParams); private long blockNumber; private int[] cacheLight = null; private int[] fullData = null; private SystemProperties config; private long startNonce = -1; public Ethash(SystemProperties config, long blockNumber) { this.config = config; this.blockNumber = blockNumber; if (config.getConfig().hasPath("mine.startNonce")) { startNonce = config.getConfig().getLong("mine.startNonce"); } } public synchronized int[] getCacheLight() { if (cacheLight == null) { File file = new File(config.databaseDir(), "mine-dag-light.dat"); if (fileCacheEnabled && file.canRead()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { logger.info("Loading light dataset from " + file.getAbsolutePath()); long bNum = ois.readLong(); if (bNum == blockNumber) { cacheLight = (int[]) ois.readObject(); logger.info("Dataset loaded."); } else { logger.info("Dataset block number miss: " + bNum + " != " + blockNumber); } } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } } if (cacheLight == null) { logger.info("Calculating light dataset..."); cacheLight = getEthashAlgo().makeCache(getEthashAlgo().getParams().getCacheSize(blockNumber), getEthashAlgo().getSeedHash(blockNumber)); logger.info("Light dataset calculated."); if (fileCacheEnabled) { file.getParentFile().mkdirs(); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){ logger.info("Writing light dataset to " + file.getAbsolutePath()); oos.writeLong(blockNumber); oos.writeObject(cacheLight); } catch (IOException e) { throw new RuntimeException(e); } } } } return cacheLight; } public synchronized int[] getFullDataset() { if (fullData == null) { File file = new File(config.databaseDir(), "mine-dag.dat"); if (fileCacheEnabled && file.canRead()) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { logger.info("Loading dataset from " + file.getAbsolutePath()); long bNum = ois.readLong(); if (bNum == blockNumber) { fullData = (int[]) ois.readObject(); logger.info("Dataset loaded."); } else { logger.info("Dataset block number miss: " + bNum + " != " + blockNumber); } } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } } if (fullData == null){ logger.info("Calculating full dataset..."); fullData = getEthashAlgo().calcDataset(getFullSize(), getCacheLight()); logger.info("Full dataset calculated."); if (fileCacheEnabled) { file.getParentFile().mkdirs(); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) { logger.info("Writing dataset to " + file.getAbsolutePath()); oos.writeLong(blockNumber); oos.writeObject(fullData); } catch (IOException e) { throw new RuntimeException(e); } } } } return fullData; } private long getFullSize() { return getEthashAlgo().getParams().getFullSize(blockNumber); } private EthashAlgo getEthashAlgo() { return ethashAlgo; } /** * See {@link EthashAlgo#hashimotoLight} */ public Pair<byte[], byte[]> hashimotoLight(BlockHeader header, long nonce) { return hashimotoLight(header, longToBytes(nonce)); } private Pair<byte[], byte[]> hashimotoLight(BlockHeader header, byte[] nonce) { return getEthashAlgo().hashimotoLight(getFullSize(), getCacheLight(), sha3(header.getEncodedWithoutNonce()), nonce); } /** * See {@link EthashAlgo#hashimotoFull} */ public Pair<byte[], byte[]> hashimotoFull(BlockHeader header, long nonce) { return getEthashAlgo().hashimotoFull(getFullSize(), getFullDataset(), sha3(header.getEncodedWithoutNonce()), longToBytes(nonce)); } public ListenableFuture<MiningResult> mine(final Block block) { return mine(block, 1); } /** * Mines the nonce for the specified Block with difficulty BlockHeader.getDifficulty() * When mined the Block 'nonce' and 'mixHash' fields are updated * Uses the full dataset i.e. it faster but takes > 1Gb of memory and may * take up to 10 mins for starting up (depending on whether the dataset was cached) * * @param block The block to mine. The difficulty is taken from the block header * This block is updated when mined * @param nThreads CPU threads to mine on * @return the task which may be cancelled. On success returns nonce */ public ListenableFuture<MiningResult> mine(final Block block, int nThreads) { return new MineTask(block, nThreads, new Callable<MiningResult>() { AtomicLong taskStartNonce = new AtomicLong(startNonce >= 0 ? startNonce : new Random().nextLong()); @Override public MiningResult call() throws Exception { long threadStartNonce = taskStartNonce.getAndAdd(0x100000000L); long nonce = getEthashAlgo().mine(getFullSize(), getFullDataset(), sha3(block.getHeader().getEncodedWithoutNonce()), ByteUtil.byteArrayToLong(block.getHeader().getDifficulty()), threadStartNonce); final Pair<byte[], byte[]> pair = hashimotoLight(block.getHeader(), nonce); return new MiningResult(nonce, pair.getLeft(), block); } }).submit(); } public ListenableFuture<MiningResult> mineLight(final Block block) { return mineLight(block, 1); } /** * Mines the nonce for the specified Block with difficulty BlockHeader.getDifficulty() * When mined the Block 'nonce' and 'mixHash' fields are updated * Uses the light cache i.e. it slower but takes only ~16Mb of memory and takes less * time to start up * * @param block The block to mine. The difficulty is taken from the block header * This block is updated when mined * @param nThreads CPU threads to mine on * @return the task which may be cancelled. On success returns nonce */ public ListenableFuture<MiningResult> mineLight(final Block block, int nThreads) { return new MineTask(block, nThreads, new Callable<MiningResult>() { AtomicLong taskStartNonce = new AtomicLong(startNonce >= 0 ? startNonce : new Random().nextLong()); @Override public MiningResult call() throws Exception { long threadStartNonce = taskStartNonce.getAndAdd(0x100000000L); final long nonce = getEthashAlgo().mineLight(getFullSize(), getCacheLight(), sha3(block.getHeader().getEncodedWithoutNonce()), ByteUtil.byteArrayToLong(block.getHeader().getDifficulty()), threadStartNonce); final Pair<byte[], byte[]> pair = hashimotoLight(block.getHeader(), nonce); return new MiningResult(nonce, pair.getLeft(), block); } }).submit(); } /** * Validates the BlockHeader against its getDifficulty() and getNonce() */ public boolean validate(BlockHeader header) { byte[] boundary = header.getPowBoundary(); byte[] hash = hashimotoLight(header, header.getNonce()).getRight(); return FastByteComparisons.compareTo(hash, 0, 32, boundary, 0, 32) < 0; } class MineTask extends AnyFuture<MiningResult> { Block block; int nThreads; Callable<MiningResult> miner; public MineTask(Block block, int nThreads, Callable<MiningResult> miner) { this.block = block; this.nThreads = nThreads; this.miner = miner; } public MineTask submit() { for (int i = 0; i < nThreads; i++) { ListenableFuture<MiningResult> f = executor.submit(miner); add(f); } return this; } @Override protected void postProcess(MiningResult result) { Pair<byte[], byte[]> pair = hashimotoLight(block.getHeader(), result.nonce); block.setNonce(longToBytes(result.nonce)); block.setMixHash(pair.getLeft()); } } }
package thobe.logfileviewer.kernel.plugin.console; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import thobe.logfileviewer.gui.RestrictedTextFieldRegexp; import thobe.logfileviewer.kernel.plugin.IPluginUI; import thobe.logfileviewer.kernel.plugin.IPluginUIComponent; import thobe.logfileviewer.kernel.plugin.console.events.CEvtClear; import thobe.logfileviewer.kernel.plugin.console.events.CEvt_Scroll; import thobe.logfileviewer.kernel.plugin.console.events.CEvt_ScrollToLast; import thobe.logfileviewer.kernel.plugin.console.events.CEvt_SetAutoScrollMode; import thobe.logfileviewer.kernel.plugin.console.events.ConsoleEvent; import thobe.logfileviewer.kernel.source.logline.LogLine; import thobe.logfileviewer.kernel.util.FontHelper; import thobe.logfileviewer.kernel.util.SizeOf; import thobe.widgets.buttons.SmallButton; import thobe.widgets.textfield.RestrictedTextFieldAdapter; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; /** * @author Thomas Obenaus * @source ConsoleUI.java * @date Jul 24, 2014 */ @SuppressWarnings ( "serial") public class SubConsole extends Thread implements ConsoleDataListener, IPluginUIComponent { /** * Max time spent waiting for completion of the next block of {@link LogLine}s (in MS) */ private static long MAX_TIME_PER_BLOCK_IN_MS = 1000; /** * Max amount of {@link LogLine} waiting for completion of one block until the block will be drawn. */ private static long MAX_LINES_PER_BLOCK = 100; /** * Time in ms to wait for the next update of the console plugins display-values */ private static long UPDATE_DISPLAY_VALUES_INTERVAL = 1000; /** * Queue containing all scroll-events */ private Deque<CEvt_Scroll> scrollEventQueue; /** * Queue for misc console-events. */ private Deque<ConsoleEvent> eventQueue; /** * Queue containing all incoming {@link LogLine}s */ private Deque<LogLine> lineBuffer; /** * The internal {@link TableModel} */ private ConsoleTableModel tableModel; /** * The plugin-panel (returned by {@link IPluginUI#getUIComponent()}. */ private JPanel pa_logPanel; /** * True if autoscrolling is enabled, false otherwise */ private boolean autoScrollingEnabled; /** * The table. */ private JTable ta_logTable; /** * Semaphore for the internal event-main-loop */ private Semaphore eventSemaphore; private SmallButton bu_clear; private SmallButton bu_settings; private SmallButton bu_enableAutoScroll; private SmallButton bu_createFilter; private JLabel l_statusline; private ConsoleFilterCellRenderer rowFilter; /** * Timestamp of next time the console's display-values will be updated */ private long nextUpdateOfDisplayValues; /** * The {@link RestrictedTextFieldRegexp} containing the filter for filtering the log-file. */ private RestrictedTextFieldRegexp rtf_filter; private ISubConsoleFactoryAccess subConsoleFactoryAccess; private Logger log; private Pattern linePattern; private AtomicBoolean quitRequested; private String parentConsolePattern; private boolean closeable; private String title; private String description; public SubConsole( String parentConsolePattern, String pattern, ISubConsoleFactoryAccess subConsoleFactoryAccess, Logger log, boolean closeable ) { this.closeable = closeable; this.linePattern = Pattern.compile( pattern ); this.parentConsolePattern = parentConsolePattern; // create and set the thread-name this.setName( "SubConsole {pattern='" + this.getFullPattern( ) + "'}" ); this.subConsoleFactoryAccess = subConsoleFactoryAccess; this.quitRequested = new AtomicBoolean( false ); this.log = log; this.eventSemaphore = new Semaphore( 1, true ); this.lineBuffer = new ConcurrentLinkedDeque<>( ); this.scrollEventQueue = new ConcurrentLinkedDeque<>( ); this.eventQueue = new ConcurrentLinkedDeque<>( ); this.autoScrollingEnabled = true; this.nextUpdateOfDisplayValues = 0; this.title = this.subConsoleFactoryAccess.createTitle( this ); this.description = this.subConsoleFactoryAccess.createDescription( this ); this.buildGUI( ); } protected String getFullPattern( ) { String pattern = ""; if ( this.parentConsolePattern != null ) pattern += this.parentConsolePattern + " AND "; pattern += this.linePattern; return pattern; } private void buildGUI( ) { this.pa_logPanel = new JPanel( new BorderLayout( 0, 0 ) ); this.tableModel = new ConsoleTableModel( ); this.ta_logTable = new JTable( this.tableModel ); final JScrollPane scrpa_main = new JScrollPane( ta_logTable ); this.pa_logPanel.add( scrpa_main, BorderLayout.CENTER ); CellConstraints cc_settings = new CellConstraints( ); JPanel pa_settings = new JPanel( new FormLayout( "3dlu,fill:default,10dlu,default,1dlu,default,0dlu,10dlu,default:grow,default,3dlu", "3dlu,pref,3dlu" ) ); this.pa_logPanel.add( pa_settings, BorderLayout.NORTH ); this.l_statusline = new JLabel( "Lines: 0/" + this.tableModel.getMaxNumberOfConsoleEntries( ) ); pa_settings.add( this.l_statusline, cc_settings.xy( 2, 2 ) ); JLabel l_filter = new JLabel( "Filter: " ); pa_settings.add( l_filter, cc_settings.xy( 4, 2 ) ); String tt_filter = "<html><h4>Filter the Console using regular expressions (matching lines will be colored):</h4>"; tt_filter += "</br>"; tt_filter += "<ul>"; tt_filter += "<li>. - any character</li>"; tt_filter += "<li>.* - any character multiple times</li>"; tt_filter += "<li>| - this is a OR. E.g. 'Info|Debug' will match all lines containing 'Info' OR 'Debug'</li>"; tt_filter += "<li>^ - start of line</li>"; tt_filter += "<li>$ - end of line</li>"; tt_filter += "<li>[0-9] - any number between 0 and 9</li>"; tt_filter += "<li>[0-9]* - any number between 0 and 9 multiple times</li>"; tt_filter += "<li>[0-9]{3,} - any number between 0 and 9 at min 3 times in a row</li>"; tt_filter += "<li>[0-9]{,3} - any number between 0 and 9 at max 3 times in a row</li>"; tt_filter += "<li>\\[ - [ ... (since [ and ] are control characters they have to be escaped)</li>"; tt_filter += "<li>\\. - . ... (since . is a control character it has to be escaped)</li>"; tt_filter += "</ul>"; tt_filter += "</html>"; l_filter.setToolTipText( tt_filter ); this.rtf_filter = new RestrictedTextFieldRegexp( 60 ); pa_settings.add( rtf_filter, cc_settings.xy( 6, 2 ) ); rtf_filter.setToolTipText( tt_filter ); rtf_filter.addListener( new RestrictedTextFieldAdapter( ) { @Override public void valueChangeCommitted( ) { String value = rtf_filter.getValue( ); bu_createFilter.setEnabled( ( value != null ) && ( !value.trim( ).isEmpty( ) ) ); rowFilter.setFilterRegex( rtf_filter.getValue( ) ); // repaint/ filter the whole log on commit tableModel.fireTableDataChanged( ); } @Override public void valueChanged( ) { String value = rtf_filter.getValue( ); rowFilter.setFilterRegex( value ); bu_createFilter.setEnabled( ( value != null ) && ( !value.trim( ).isEmpty( ) ) ); }; } ); this.bu_createFilter = new SmallButton( ">" ); pa_settings.add( bu_createFilter, cc_settings.xy( 8, 2 ) ); this.bu_createFilter.addActionListener( new ActionListener( ) { @Override public void actionPerformed( ActionEvent e ) { SubConsole consoleUI = subConsoleFactoryAccess.createNewSubConsole( getFullPattern( ), rtf_filter.getValue( ), true ); subConsoleFactoryAccess.registerSubConsole( consoleUI, true ); } } ); this.bu_createFilter.setEnabled( false ); JPanel pa_buttons = new JPanel( new FlowLayout( FlowLayout.RIGHT, 0, 0 ) ); pa_settings.add( pa_buttons, cc_settings.xy( 10, 2 ) ); this.bu_enableAutoScroll = new SmallButton( "Autoscroll" ); pa_buttons.add( this.bu_enableAutoScroll ); this.bu_enableAutoScroll.addActionListener( new ActionListener( ) { @Override public void actionPerformed( ActionEvent e ) { toggleAutoScroll( ); } } ); this.bu_clear = new SmallButton( "clear" ); pa_buttons.add( this.bu_clear ); this.bu_clear.addActionListener( new ActionListener( ) { @Override public void actionPerformed( ActionEvent e ) { clear( ); } } ); this.bu_settings = new SmallButton( "Settings" ); pa_buttons.add( this.bu_settings ); // adjust column-sizes ta_logTable.getColumnModel( ).getColumn( 0 ).setMinWidth( 60 ); ta_logTable.getColumnModel( ).getColumn( 0 ).setWidth( 60 ); ta_logTable.getColumnModel( ).getColumn( 0 ).setMaxWidth( 60 ); ta_logTable.getColumnModel( ).getColumn( 0 ).setPreferredWidth( 60 ); ta_logTable.getColumnModel( ).getColumn( 0 ).setResizable( true ); ta_logTable.getColumnModel( ).getColumn( 1 ).setMinWidth( 110 ); ta_logTable.getColumnModel( ).getColumn( 1 ).setMaxWidth( 110 ); ta_logTable.getColumnModel( ).getColumn( 1 ).setPreferredWidth( 110 ); ta_logTable.getColumnModel( ).getColumn( 1 ).setResizable( false ); // listener that is responsible to scroll the table to the last entry this.tableModel.addTableModelListener( new TableModelListener( ) { @Override public void tableChanged( final TableModelEvent e ) { if ( e.getType( ) == TableModelEvent.INSERT && autoScrollingEnabled ) { addScrollEvent( new CEvt_ScrollToLast( ) ); } } } ); // Listener that disables autoscrolling if the user scrolls upwards scrpa_main.addMouseWheelListener( new MouseWheelListener( ) { @Override public void mouseWheelMoved( MouseWheelEvent evt ) { // disable autoscrolling if the wheel rotates up if ( evt.getWheelRotation( ) == -1 ) { addScrollEvent( new CEvt_SetAutoScrollMode( false ) ); }// if ( evt.getWheelRotation( ) == -1 ). } } ); // listener keeping track of disabling/enabling autoscrolling scrpa_main.getVerticalScrollBar( ).addAdjustmentListener( new AdjustmentListener( ) { @Override public void adjustmentValueChanged( AdjustmentEvent evt ) { // Disable auto-scrolling if the scrollbar is moved int extent = scrpa_main.getVerticalScrollBar( ).getModel( ).getExtent( ); int currentScrollPos = scrpa_main.getVerticalScrollBar( ).getValue( ) + extent; // bottom is reached in case the current-scrolling pos is greater than 98% of the maximum-scroll position of the table // if bottom is reached we want to enable autoscrolling boolean bottomReached = currentScrollPos >= ( scrpa_main.getVerticalScrollBar( ).getMaximum( ) * 0.98 ); // in case we have changed the autoscrolling-mode (disable/enable) we generate the according event to force the modification if ( ( evt.getValueIsAdjusting( ) == true ) && ( evt.getAdjustmentType( ) == AdjustmentEvent.TRACK ) && ( autoScrollingEnabled != bottomReached ) ) { addScrollEvent( new CEvt_SetAutoScrollMode( bottomReached ) ); }// if ( ( evt.getValueIsAdjusting( ) == true ) && ( evt.getAdjustmentType( ) == .. } } ); this.rowFilter = new ConsoleFilterCellRenderer( this.tableModel ); // set the cell-renderer that should be used for filtering this.ta_logTable.getColumnModel( ).getColumn( 0 ).setCellRenderer( this.rowFilter ); this.ta_logTable.getColumnModel( ).getColumn( 1 ).setCellRenderer( this.rowFilter ); this.ta_logTable.getColumnModel( ).getColumn( 2 ).setCellRenderer( this.rowFilter ); Font consoleFont = FontHelper.getConsoleFont( ); LOG( ).info( "Setting console-font to " + consoleFont ); this.ta_logTable.setFont( consoleFont ); } public void clear( ) { this.eventQueue.add( new CEvtClear( ) ); this.eventSemaphore.release( ); } public void toggleAutoScroll( ) { this.addScrollEvent( new CEvt_SetAutoScrollMode( !this.autoScrollingEnabled ) ); } private void addScrollEvent( CEvt_Scroll evt ) { this.scrollEventQueue.add( evt ); eventSemaphore.release( ); } private void updateDisplayValues( ) { if ( this.nextUpdateOfDisplayValues <= System.currentTimeMillis( ) ) { this.nextUpdateOfDisplayValues = System.currentTimeMillis( ) + UPDATE_DISPLAY_VALUES_INTERVAL; this.l_statusline.setText( "Lines: " + this.tableModel.getRowCount( ) + "/" + this.tableModel.getMaxNumberOfConsoleEntries( ) ); }// if ( this.nextUpdateOfDisplayValues <= System.currentTimeMillis( ) ) . } @Override public void run( ) { List<LogLine> block = new ArrayList<>( ); while ( !this.isQuitRequested( ) ) { // process next event from the event-queue processScrollEvents( ); // process misc events processEvents( ); // update display-values updateDisplayValues( ); long startTime = System.currentTimeMillis( ); boolean timeThresholdHurt = false; boolean blockSizeThresholdHurt = false; block.clear( ); // collect some lines synchronized ( this.lineBuffer ) { while ( ( !this.lineBuffer.isEmpty( ) ) && !timeThresholdHurt && !blockSizeThresholdHurt ) { LogLine ll = this.lineBuffer.pollFirst( ); // add only matching lines if ( matches( this.linePattern, ll.getData( ) ) ) { block.add( ll ); } blockSizeThresholdHurt = block.size( ) > MAX_LINES_PER_BLOCK; timeThresholdHurt = ( System.currentTimeMillis( ) - startTime ) > MAX_TIME_PER_BLOCK_IN_MS; }// while ( ( !this.lineBuffer.isEmpty( ) ) && !timeThresholdHurt && !blockSizeThresholdHurt ). }// synchronized ( this.lineBuffer ). // Add the block if we have collected some lines if ( !block.isEmpty( ) ) { this.tableModel.addBlock( block ); }// if ( !block.isEmpty( ) ). try { this.eventSemaphore.tryAcquire( 2, TimeUnit.SECONDS ); } catch ( InterruptedException e ) { LOG( ).severe( "Exception caught in console-plugin main-loop: " + e.getLocalizedMessage( ) ); } }// while ( !this.isQuitRequested( ) ). this.tableModel.quit( ); LOG( ).info( this + ": Leaving main-loop." ); } private void processEvents( ) { ConsoleEvent evt = null; synchronized ( this.eventQueue ) { while ( ( evt = this.eventQueue.poll( ) ) != null ) { switch ( evt.getType( ) ) { case CLEAR: this.tableModel.clear( ); break; default: LOG( ).warning( "Unknown event: " + evt ); break; }// switch ( evt.getType( ) ) . }// while ( ( evt = this.eventQueue.poll( ) ) != null ) . }// synchronized ( this.eventQueue ) . } private void processScrollEvents( ) { CEvt_Scroll evt = null; boolean hasScrollToLast = false; synchronized ( this.scrollEventQueue ) { while ( ( evt = this.scrollEventQueue.poll( ) ) != null ) { switch ( evt.getType( ) ) { case SCROLL_TO_LAST: hasScrollToLast = true; break; case SET_AUTOSCROLL_MODE: boolean prefAutoScrollValue = this.autoScrollingEnabled; this.autoScrollingEnabled = ( ( CEvt_SetAutoScrollMode ) evt ).isEnable( ); // scroll to last only if the autoscrolling was toggled to true hasScrollToLast = ( this.autoScrollingEnabled && ( prefAutoScrollValue != this.autoScrollingEnabled ) ); break; default: LOG( ).warning( "Unknown event: " + evt ); break; } } }// synchronized ( this.scrollEventQueue ) . // scroll to the last line if needed if ( hasScrollToLast && this.autoScrollingEnabled ) { SwingUtilities.invokeLater( new Runnable( ) { public void run( ) { int viewRow = ta_logTable.convertRowIndexToView( ta_logTable.getRowCount( ) - 1 ); ta_logTable.scrollRectToVisible( ta_logTable.getCellRect( viewRow, 0, true ) ); } } ); } } public long getCurrentMemory( ) { long memInLineBuffer = 0; for ( LogLine ll : this.lineBuffer ) memInLineBuffer += ll.getMem( ) + SizeOf.REFERENCE + SizeOf.HOUSE_KEEPING_ARRAY; long memInEventQueue = this.scrollEventQueue.size( ) * SizeOf.REFERENCE * SizeOf.HOUSE_KEEPING; memInEventQueue += SizeOf.REFERENCE + SizeOf.HOUSE_KEEPING_ARRAY; return memInLineBuffer + this.tableModel.getMem( ) + memInEventQueue; } public void setAutoScrollingEnabled( boolean autoScrollingEnabled ) { this.autoScrollingEnabled = autoScrollingEnabled; this.eventSemaphore.release( ); } public void freeMemory( ) { synchronized ( this.lineBuffer ) { this.tableModel.clear( ); this.lineBuffer.clear( ); } this.eventSemaphore.release( ); } protected Logger LOG( ) { return this.log; } public boolean isQuitRequested( ) { return quitRequested.get( ); } /** * {@link TableCellRenderer} for this {@link SubConsole}. */ private class ConsoleFilterCellRenderer extends DefaultTableCellRenderer { private ConsoleTableModel tableModel; private Pattern pattern; public ConsoleFilterCellRenderer( ConsoleTableModel tableModel ) { this.pattern = null; this.tableModel = tableModel; } public void setFilterRegex( String filterRegex ) { try { this.pattern = Pattern.compile( filterRegex ); } catch ( PatternSyntaxException e ) {} } @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) { Component result = super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column ); if ( !isSelected ) { if ( this.tableModel.matches( row, this.pattern ) ) { result.setBackground( Color.orange ); } else { result.setBackground( ta_logTable.getBackground( ) ); } } return result; } } @Override public void onNewData( List<LogLine> blockOfLines ) { this.lineBuffer.addAll( blockOfLines ); this.eventSemaphore.release( ); } private static boolean matches( final Pattern pattern, final String line ) { if ( pattern == null || pattern.pattern( ).trim( ).isEmpty( ) ) return false; boolean result = false; try { Matcher m = pattern.matcher( line ); result = m.find( ); } catch ( PatternSyntaxException e ) {} return result; } @Override public JComponent getVisualComponent( ) { return this.pa_logPanel; } @Override public String getTitle( ) { return this.title; } @Override public void onClosed( ) { LOG( ).info( this.title + ": closed." ); } @Override public void onClosing( ) { LOG( ).info( this.title + ": closing --> unregister" ); this.subConsoleFactoryAccess.unRegisterSubConsole( this ); } @Override public boolean isCloseable( ) { return this.closeable; } @Override public String getTooltip( ) { return this.description; } public void quit( ) { this.quitRequested.set( true ); this.eventSemaphore.release( ); } }
package com.github.miachm.SODS.spreadsheet; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.fail; public class RangeTest { @Test public void testClear() throws Exception { Sheet sheet = new Sheet("A"); Range range = sheet.getDataRange(); range.setValue(1); range.clear(); assertNull(range.getValue()); sheet.insertColumnAfter(0); sheet.insertRowAfter(0); range = sheet.getDataRange(); range.setValues(1,2,3,4); range.clear(); Object[][] values = range.getValues(); for (Object[] row : values) for (Object value : row) assertNull(value); } @Test public void testCopyTo() throws Exception { Sheet sheet = new Sheet("A"); sheet.insertColumnsAfter(0,3); sheet.insertRowAfter(0); Range range = sheet.getDataRange(); range.setValues(1,2,3,4,5,6,7,8); Range origin = sheet.getRange(0,0,2,2); Range dest = sheet.getRange(0,2,2,2); origin.copyTo(dest); Object[][] values = dest.getValues(); assertEquals(values[0][0],1); assertEquals(values[1][0],5); assertEquals(values[0][1],2); assertEquals(values[1][1],6); } @Test public void testGetCell() throws Exception { Sheet sheet = new Sheet("A"); sheet.insertColumnsAfter(0,2); sheet.insertRowAfter(0); Range range = sheet.getDataRange(); range.setValues(1,2,3,4,5,6); assertEquals(sheet.getCell(0,0).getValue(),1); assertEquals(sheet.getCell(0,1).getValue(),2); assertEquals(sheet.getCell(0,2).getValue(),3); assertEquals(sheet.getCell(1,0).getValue(),4); assertEquals(sheet.getCell(1,1).getValue(),5); assertEquals(sheet.getCell(1,2).getValue(),6); } @Test public void testGetColumn() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(10); sheet.appendColumns(10); for (int i = 0;i < sheet.getMaxRows()/2;i++) { for (int j = 0; j < sheet.getMaxColumns()/2; j++) { Range range = sheet.getRange(i,j,2,2); assertEquals(range.getColumn(),j); } } } @Test public void testGetFormula() throws Exception { fail("Not implemented"); } @Test public void testGetFormulas() throws Exception { fail("Not implemented"); } @Test public void testGetLastColumn() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(10); sheet.appendColumns(10); for (int i = 0;i < sheet.getMaxRows()/2;i++) { for (int j = 0; j < sheet.getMaxColumns()/2; j++) { Range range = sheet.getRange(i,j,2,2); assertEquals(range.getLastColumn(),j+1); } } } @Test public void testGetLastRow() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(10); sheet.appendColumns(10); for (int i = 0;i < sheet.getMaxRows()/2;i++) { for (int j = 0; j < sheet.getMaxColumns()/2; j++) { Range range = sheet.getRange(i,j,2,2); assertEquals(range.getLastRow(),i+1); } } } @Test public void testGetNumColumns() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(10); sheet.appendColumns(10); for (int i = 0;i < sheet.getMaxRows()/2;i++) { for (int j = 0; j < sheet.getMaxColumns()/2; j++) { Range range = sheet.getRange(i,j,3,2); assertEquals(range.getNumColumns(),2); } } } @Test public void testGetNumRows() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(10); sheet.appendColumns(10); for (int i = 0;i < sheet.getMaxRows()/2;i++) { for (int j = 0; j < sheet.getMaxColumns()/2; j++) { Range range = sheet.getRange(i,j,3,2); assertEquals(range.getNumRows(),3); } } } @Test public void testGetRow() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(10); sheet.appendColumns(10); for (int i = 0;i < sheet.getMaxRows()/2;i++) { for (int j = 0; j < sheet.getMaxColumns() / 2; j++) { Range range = sheet.getRange(i, j, 2, 2); assertEquals(range.getRow(), i); } } } @Test public void testGetSheet() throws Exception { Sheet sheet = new Sheet("A"); Range range = sheet.getDataRange(); Sheet parent = range.getSheet(); assertEquals(sheet,parent); } @Test public void testGetValue() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRow(); sheet.appendColumn(); Range range = sheet.getDataRange(); range.setValues(1,2,3,4); assertEquals(range.getValue(),1); range = sheet.getRange(1,1); assertEquals(range.getValue(),4); } @Test public void testGetValues() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRow(); sheet.appendColumn(); Range range = sheet.getDataRange(); range.setValues(1,2,3,4); Object[][] arr = range.getValues(); assertEquals(arr[0][0],1); assertEquals(arr[0][1],2); assertEquals(arr[1][0],3); assertEquals(arr[1][1],4); } @Test public void testGetNumValues() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(2); sheet.appendColumn(); Range range = sheet.getDataRange(); assertEquals(range.getNumValues(),6); } @Test public void testSetValue() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRow(); sheet.appendColumn(); Range range = sheet.getDataRange(); range.setValue(1); Object[][] arr = range.getValues(); assertEquals(arr[0][0],1); assertEquals(arr[0][1],1); assertEquals(arr[1][0],1); assertEquals(arr[1][1],1); } @Test public void testSetValues() throws Exception { } @Test public void testSetValues1() throws Exception { } }
package com.github.miachm.SODS.spreadsheet; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; public class RangeTest { @Test public void testClear() throws Exception { Sheet sheet = new Sheet("A"); Range range = sheet.getDataRange(); range.setValue(1); range.clear(); assertNull(range.getValue()); sheet.insertColumnAfter(0); sheet.insertRowAfter(0); range = sheet.getDataRange(); range.setValues(1,2,3,4); range.clear(); Object[][] values = range.getValues(); for (int i = 0;i < values.length;i++) for (int j = 0;j < values[i].length;j++) assertNull(values[i][j]); } @Test public void testCopyTo() throws Exception { Sheet sheet = new Sheet("A"); sheet.insertColumnsAfter(0,3); sheet.insertRowAfter(0); Range range = sheet.getDataRange(); range.setValues(1,2,3,4,5,6,7,8); Range origin = sheet.getRange(0,0,2,2); Range dest = sheet.getRange(0,2,2,2); origin.copyTo(dest); Object[][] values = dest.getValues(); assertEquals(values[0][0],1); assertEquals(values[1][0],5); assertEquals(values[0][1],2); assertEquals(values[1][1],6); } @Test public void testGetCell() throws Exception { Sheet sheet = new Sheet("A"); sheet.insertColumnsAfter(0,2); sheet.insertRowAfter(0); Range range = sheet.getDataRange(); range.setValues(1,2,3,4,5,6); assertEquals(sheet.getCell(0,0).getValue(),1); assertEquals(sheet.getCell(0,1).getValue(),2); assertEquals(sheet.getCell(0,2).getValue(),3); assertEquals(sheet.getCell(1,0).getValue(),4); assertEquals(sheet.getCell(1,1).getValue(),5); assertEquals(sheet.getCell(1,2).getValue(),6); } @Test public void testGetColumn() throws Exception { Sheet sheet = new Sheet("A"); sheet.appendRows(10); sheet.appendColumns(10); for (int i = 0;i < sheet.getMaxRows()/2;i++) { for (int j = 0; j < sheet.getMaxColumns()/2; j++) { Range range = sheet.getRange(i,j,2,2); assertEquals(range.getColumn(),j); } } } @Test public void testGetFormula() throws Exception { } @Test public void testGetFormulas() throws Exception { } @Test public void testGetLastColumn() throws Exception { } @Test public void testGetLastRow() throws Exception { } @Test public void testGetNumColumns() throws Exception { } @Test public void testGetNumRows() throws Exception { } @Test public void testGetRow() throws Exception { } @Test public void testGetSheet() throws Exception { } @Test public void testGetValue() throws Exception { } @Test public void testGetValues() throws Exception { } @Test public void testGetNumValues() throws Exception { } @Test public void testSetValue() throws Exception { } @Test public void testSetValues() throws Exception { } @Test public void testSetValues1() throws Exception { } }
package org.exist.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.backup.SystemExport; import org.exist.collections.CollectionCache; import org.exist.repo.Deployment; import org.exist.start.Main; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.exist.Indexer; import org.exist.indexing.IndexManager; import org.exist.dom.memtree.SAXAdapter; import org.exist.scheduler.JobConfig; import org.exist.scheduler.JobException; import org.exist.security.internal.RealmImpl; import org.exist.storage.BrokerFactory; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.storage.DefaultCacheManager; import org.exist.storage.IndexSpec; import org.exist.storage.NativeBroker; import org.exist.storage.NativeValueIndex; import org.exist.storage.XQueryPool; import org.exist.storage.journal.Journal; import org.exist.storage.serializers.CustomMatchListenerFactory; import org.exist.storage.serializers.Serializer; import org.exist.validation.GrammarPool; import org.exist.validation.resolver.eXistXMLCatalogResolver; import org.exist.xmldb.DatabaseImpl; import org.exist.xquery.FunctionFactory; import org.exist.xquery.PerformanceStats; import org.exist.xquery.XQueryContext; import org.exist.xquery.XQueryWatchDog; import org.exist.xslt.TransformerFactoryAllocator; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.exist.Namespaces; import org.exist.scheduler.JobType; import org.exist.xquery.Module; import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING; public class Configuration implements ErrorHandler { private final static Logger LOG = LogManager.getLogger(Configuration.class); //Logger protected Optional<Path> configFilePath = Optional.empty(); protected Optional<Path> existHome = Optional.empty(); protected DocumentBuilder builder = null; protected HashMap<String, Object> config = new HashMap<>(); //Configuration private static final String XQUERY_CONFIGURATION_ELEMENT_NAME = "xquery"; private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME = "builtin-modules"; private static final String XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME = "module"; public final static String BINARY_CACHE_CLASS_PROPERTY = "binary.cache.class"; public Configuration() throws DatabaseConfigurationException { this(DatabaseImpl.CONF_XML, Optional.empty()); } public Configuration(final String configFilename) throws DatabaseConfigurationException { this(configFilename, Optional.empty()); } public Configuration(String configFilename, Optional<Path> existHomeDirname) throws DatabaseConfigurationException { InputStream is = null; try { if(configFilename == null) { // Default file name configFilename = DatabaseImpl.CONF_XML; } // firstly, try to read the configuration from a file within the // classpath try { is = Configuration.class.getClassLoader().getResourceAsStream(configFilename); if(is != null) { LOG.info("Reading configuration from classloader"); configFilePath = Optional.of(Paths.get(Configuration.class.getClassLoader().getResource(configFilename).toURI())); } } catch(final Exception e) { // EB: ignore and go forward, e.g. in case there is an absolute // file name for configFileName LOG.debug( e ); } // otherwise, secondly try to read configuration from file. Guess the // location if necessary if(is == null) { existHome = existHomeDirname.map(Optional::of).orElse(ConfigurationHelper.getExistHome(configFilename)); if(!existHome.isPresent()) { // EB: try to create existHome based on location of config file // when config file points to absolute file location final Path absoluteConfigFile = Paths.get(configFilename); if(absoluteConfigFile.isAbsolute() && Files.exists(absoluteConfigFile) && Files.isReadable(absoluteConfigFile)) { existHome = Optional.of(absoluteConfigFile.getParent()); configFilename = FileUtils.fileName(absoluteConfigFile); } } Path configFile = Paths.get(configFilename); if(!configFile.isAbsolute() && existHome.isPresent()) { // try the passed or constructed existHome first configFile = existHome.get().resolve(configFilename); if (!Files.exists(configFile)) { configFile = existHome.get().resolve(Main.CONFIG_DIR_NAME).resolve(configFilename); } } //if( configFile == null ) { // configFile = ConfigurationHelper.lookup( configFilename ); if(!Files.exists(configFile) || !Files.isReadable(configFile)) { throw new DatabaseConfigurationException("Unable to read configuration file at " + configFile); } configFilePath = Optional.of(configFile.toAbsolutePath()); is = Files.newInputStream(configFile); } LOG.info("Reading configuration from file " + configFilePath.map(Path::toString).orElse("Unknown")); // set dbHome to parent of the conf file found, to resolve relative // path from conf file existHomeDirname = configFilePath.map(Path::getParent); // initialize xml parser // we use eXist's in-memory DOM implementation to work // around a bug in Xerces final SAXParserFactory factory = ExistSAXParserFactory.getSAXParserFactory(); factory.setNamespaceAware(true); final InputSource src = new InputSource(is); final SAXParser parser = factory.newSAXParser(); final XMLReader reader = parser.getXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); reader.setFeature(FEATURE_SECURE_PROCESSING, true); final SAXAdapter adapter = new SAXAdapter(); reader.setContentHandler(adapter); reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter); reader.parse(src); final Document doc = adapter.getDocument(); //indexer settings final NodeList indexers = doc.getElementsByTagName(Indexer.CONFIGURATION_ELEMENT_NAME); if(indexers.getLength() > 0) { configureIndexer( existHomeDirname, doc, (Element)indexers.item( 0 ) ); } //scheduler settings final NodeList schedulers = doc.getElementsByTagName(JobConfig.CONFIGURATION_ELEMENT_NAME); if(schedulers.getLength() > 0) { configureScheduler((Element)schedulers.item(0)); } //db connection settings final NodeList dbcon = doc.getElementsByTagName(BrokerPool.CONFIGURATION_CONNECTION_ELEMENT_NAME); if(dbcon.getLength() > 0) { configureBackend(existHomeDirname, (Element)dbcon.item(0)); } final NodeList repository = doc.getElementsByTagName("repository"); if(repository.getLength() > 0) { configureRepository((Element) repository.item(0)); } final NodeList binaryManager = doc.getElementsByTagName("binary-manager"); if(binaryManager.getLength() > 0) { configureBinaryManager((Element)binaryManager.item(0)); } //transformer settings final NodeList transformers = doc.getElementsByTagName(TransformerFactoryAllocator.CONFIGURATION_ELEMENT_NAME); if( transformers.getLength() > 0 ) { configureTransformer((Element)transformers.item(0)); } //parser settings final NodeList parsers = doc.getElementsByTagName(HtmlToXmlParser.PARSER_ELEMENT_NAME); if(parsers.getLength() > 0) { configureParser((Element)parsers.item(0)); } //serializer settings final NodeList serializers = doc.getElementsByTagName(Serializer.CONFIGURATION_ELEMENT_NAME); if(serializers.getLength() > 0) { configureSerializer((Element)serializers.item(0)); } //XUpdate settings final NodeList xupdates = doc.getElementsByTagName(DBBroker.CONFIGURATION_ELEMENT_NAME); if(xupdates.getLength() > 0) { configureXUpdate((Element)xupdates.item(0)); } //XQuery settings final NodeList xquery = doc.getElementsByTagName(XQUERY_CONFIGURATION_ELEMENT_NAME); if(xquery.getLength() > 0) { configureXQuery((Element)xquery.item(0)); } //Validation final NodeList validations = doc.getElementsByTagName(XMLReaderObjectFactory.CONFIGURATION_ELEMENT_NAME); if(validations.getLength() > 0) { configureValidation(existHomeDirname, doc, (Element)validations.item(0)); } } catch(final SAXException | IOException | ParserConfigurationException e) { LOG.error("error while reading config file: " + configFilename, e); throw new DatabaseConfigurationException(e.getMessage(), e); } finally { if(is != null) { try { is.close(); } catch(final IOException ioe) { LOG.error(ioe); } } } } private void configureRepository(Element element) { String root = element.getAttribute("root"); if (root != null && root.length() > 0) { if (!root.endsWith("/")) {root += "/";} config.put(Deployment.PROPERTY_APP_ROOT, root); } } private void configureBinaryManager(Element binaryManager) throws DatabaseConfigurationException { final NodeList nlCache = binaryManager.getElementsByTagName("cache"); if(nlCache.getLength() > 0) { final Element cache = (Element)nlCache.item(0); final String binaryCacheClass = cache.getAttribute("class"); config.put(BINARY_CACHE_CLASS_PROPERTY, binaryCacheClass); LOG.debug(BINARY_CACHE_CLASS_PROPERTY + ": " + config.get(BINARY_CACHE_CLASS_PROPERTY)); } } private void configureXQuery( Element xquery ) throws DatabaseConfigurationException { //java binding final String javabinding = getConfigAttributeValue( xquery, FunctionFactory.ENABLE_JAVA_BINDING_ATTRIBUTE ); if( javabinding != null ) { config.put( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING, javabinding ); LOG.debug( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING + ": " + config.get( FunctionFactory.PROPERTY_ENABLE_JAVA_BINDING ) ); } final String disableDeprecated = getConfigAttributeValue( xquery, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_ATTRIBUTE ); config.put( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS, Configuration.parseBoolean( disableDeprecated, FunctionFactory.DISABLE_DEPRECATED_FUNCTIONS_BY_DEFAULT ) ); LOG.debug( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS + ": " + config.get( FunctionFactory.PROPERTY_DISABLE_DEPRECATED_FUNCTIONS ) ); final String optimize = getConfigAttributeValue( xquery, XQueryContext.ENABLE_QUERY_REWRITING_ATTRIBUTE ); if( ( optimize != null ) && ( optimize.length() > 0 ) ) { config.put( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING, optimize ); LOG.debug( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING + ": " + config.get( XQueryContext.PROPERTY_ENABLE_QUERY_REWRITING ) ); } final String enforceIndexUse = getConfigAttributeValue( xquery, XQueryContext.ENFORCE_INDEX_USE_ATTRIBUTE ); if (enforceIndexUse != null) { config.put( XQueryContext.PROPERTY_ENFORCE_INDEX_USE, enforceIndexUse ); } final String backwardCompatible = getConfigAttributeValue( xquery, XQueryContext.XQUERY_BACKWARD_COMPATIBLE_ATTRIBUTE ); if( ( backwardCompatible != null ) && ( backwardCompatible.length() > 0 ) ) { config.put( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE, backwardCompatible ); LOG.debug( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE + ": " + config.get( XQueryContext.PROPERTY_XQUERY_BACKWARD_COMPATIBLE ) ); } final String raiseErrorOnFailedRetrieval = getConfigAttributeValue( xquery, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_ATTRIBUTE ); config.put( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, Configuration.parseBoolean( raiseErrorOnFailedRetrieval, XQueryContext.XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL_DEFAULT ) ); LOG.debug( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL + ": " + config.get( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL ) ); final String trace = getConfigAttributeValue( xquery, PerformanceStats.CONFIG_ATTR_TRACE ); config.put( PerformanceStats.CONFIG_PROPERTY_TRACE, trace ); // built-in-modules final Map<String, Class<?>> classMap = new HashMap<String, Class<?>>(); final Map<String, String> knownMappings = new HashMap<String, String>(); final Map<String, Map<String, List<? extends Object>>> moduleParameters = new HashMap<String, Map<String, List<? extends Object>>>(); loadModuleClasses(xquery, classMap, knownMappings, moduleParameters); config.put( XQueryContext.PROPERTY_BUILT_IN_MODULES, classMap); config.put( XQueryContext.PROPERTY_STATIC_MODULE_MAP, knownMappings); config.put( XQueryContext.PROPERTY_MODULE_PARAMETERS, moduleParameters); } /** * Read list of built-in modules from the configuration. This method will only make sure * that the specified module class exists and is a subclass of {@link org.exist.xquery.Module}. * * @param xquery configuration root * @param modulesClassMap map containing all classes of modules * @param modulesSourceMap map containing all source uris to external resources * * @throws DatabaseConfigurationException */ private void loadModuleClasses( Element xquery, Map<String, Class<?>> modulesClassMap, Map<String, String> modulesSourceMap, Map<String, Map<String, List<? extends Object>>> moduleParameters) throws DatabaseConfigurationException { // add the standard function module modulesClassMap.put(Namespaces.XPATH_FUNCTIONS_NS, org.exist.xquery.functions.fn.FnModule.class); // add other modules specified in configuration final NodeList builtins = xquery.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULES_ELEMENT_NAME); // search under <builtin-modules> if(builtins.getLength() > 0) { Element elem = (Element)builtins.item(0); final NodeList modules = elem.getElementsByTagName(XQUERY_BUILTIN_MODULES_CONFIGURATION_MODULE_ELEMENT_NAME); if(modules.getLength() > 0) { // iterate over all <module src= uri= class=> entries for(int i = 0; i < modules.getLength(); i++) { // Get element. elem = (Element)modules.item(i); // Get attributes uri class and src final String uri = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_URI_ATTRIBUTE); final String clazz = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_CLASS_ATTRIBUTE); final String source = elem.getAttribute(XQueryContext.BUILT_IN_MODULE_SOURCE_ATTRIBUTE); // uri attribute is the identifier and is always required if(uri == null) { throw(new DatabaseConfigurationException("element 'module' requires an attribute 'uri'" )); } // either class or source attribute must be present if((clazz == null) && (source == null)) { throw(new DatabaseConfigurationException("element 'module' requires either an attribute " + "'class' or 'src'" )); } if(source != null) { // Store src attribute info modulesSourceMap.put(uri, source); if(LOG.isDebugEnabled()) { LOG.debug( "Registered mapping for module '" + uri + "' to '" + source + "'"); } } else { // source class attribute info // Get class of module final Class<?> moduleClass = lookupModuleClass(uri, clazz); // Store class if thw module class actually exists if( moduleClass != null) { modulesClassMap.put(uri, moduleClass); } if(LOG.isDebugEnabled()) { LOG.debug("Configured module '" + uri + "' implemented in '" + clazz + "'"); } } //parse any module parameters moduleParameters.put(uri, ParametersExtractor.extract(elem.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME))); } } } } /** * Returns the Class object associated with the with the given module class name. All * important exceptions are caught. @see org.exist.xquery.Module * * @param uri namespace of class. For logging purposes only. * @param clazz the fully qualified name of the desired module class. * @return the module Class object for the module with the specified name. * @throws DatabaseConfigurationException if the given module class is not an instance * of org.exist.xquery.Module */ private Class<?> lookupModuleClass(String uri, String clazz) throws DatabaseConfigurationException { Class<?> mClass = null; try { mClass = Class.forName( clazz ); if( !( Module.class.isAssignableFrom( mClass ) ) ) { throw( new DatabaseConfigurationException( "Failed to load module: " + uri + ". Class " + clazz + " is not an instance of org.exist.xquery.Module." ) ); } } catch( final ClassNotFoundException e ) { // Note: can't throw an exception here since this would create // problems with test cases and jar dependencies LOG.error( "Configuration problem: class not found for module '" + uri + "' (ClassNotFoundException); class:'" + clazz + "'; message:'" + e.getMessage() + "'"); } catch( final NoClassDefFoundError e ) { LOG.error( "Module " + uri + " could not be initialized due to a missing " + "dependancy (NoClassDefFoundError): " + e.getMessage(), e ); } return mClass; } /** * DOCUMENT ME! * * @param xupdate * * @throws NumberFormatException */ private void configureXUpdate( Element xupdate ) throws NumberFormatException { final String fragmentation = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_FRAGMENTATION_FACTOR_ATTRIBUTE ); if( fragmentation != null ) { config.put( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR, Integer.valueOf(fragmentation) ); LOG.debug( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR + ": " + config.get( DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR ) ); } final String consistencyCheck = getConfigAttributeValue( xupdate, DBBroker.XUPDATE_CONSISTENCY_CHECKS_ATTRIBUTE ); if( consistencyCheck != null ) { config.put( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS, parseBoolean( consistencyCheck, false ) ); LOG.debug( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS + ": " + config.get( DBBroker.PROPERTY_XUPDATE_CONSISTENCY_CHECKS ) ); } } private void configureTransformer( Element transformer ) { final String className = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CLASS_ATTRIBUTE ); if( className != null ) { config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS, className ); LOG.debug( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS + ": " + config.get( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_CLASS ) ); // Process any specified attributes that should be passed to the transformer factory final NodeList attrs = transformer.getElementsByTagName( TransformerFactoryAllocator.CONFIGURATION_TRANSFORMER_ATTRIBUTE_ELEMENT_NAME ); final Hashtable<Object, Object> attributes = new Properties(); for( int a = 0; a < attrs.getLength(); a++ ) { final Element attr = (Element)attrs.item( a ); final String name = attr.getAttribute( "name" ); final String value = attr.getAttribute( "value" ); final String type = attr.getAttribute( "type" ); if( ( name == null ) || ( name.length() == 0 ) ) { LOG.warn( "Discarded invalid attribute for TransformerFactory: '" + className + "', name not specified" ); } else if( ( type == null ) || ( type.length() == 0 ) || type.equalsIgnoreCase( "string" ) ) { attributes.put( name, value ); } else if( type.equalsIgnoreCase( "boolean" ) ) { attributes.put( name, Boolean.valueOf( value ) ); } else if( type.equalsIgnoreCase( "integer" ) ) { try { attributes.put( name, Integer.valueOf( value ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Discarded invalid attribute for TransformerFactory: '" + className + "', name: " + name + ", value not integer: " + value, nfe); } } else { // Assume string type attributes.put( name, value ); } } config.put( TransformerFactoryAllocator.PROPERTY_TRANSFORMER_ATTRIBUTES, attributes ); } final String cachingValue = getConfigAttributeValue( transformer, TransformerFactoryAllocator.TRANSFORMER_CACHING_ATTRIBUTE ); if( cachingValue != null ) { config.put( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE, parseBoolean( cachingValue, false ) ); LOG.debug( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE + ": " + config.get( TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE ) ); } } private void configureParser(final Element parser) { configureXmlParser(parser); configureHtmlToXmlParser(parser); } private void configureXmlParser(final Element parser) { final NodeList nlXml = parser.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_ELEMENT); if(nlXml.getLength() > 0) { final Element xml = (Element)nlXml.item(0); final NodeList nlFeatures = xml.getElementsByTagName(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_ELEMENT); if(nlFeatures.getLength() > 0) { final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0)); if(pFeatures != null) { final Map<String, Boolean> features = new HashMap<>(); pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString()))); config.put(XMLReaderPool.XmlParser.XML_PARSER_FEATURES_PROPERTY, features); } } } } private void configureHtmlToXmlParser(final Element parser) { final NodeList nlHtmlToXml = parser.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_ELEMENT); if(nlHtmlToXml.getLength() > 0) { final Element htmlToXml = (Element)nlHtmlToXml.item(0); final String htmlToXmlParserClass = getConfigAttributeValue(htmlToXml, HtmlToXmlParser.HTML_TO_XML_PARSER_CLASS_ATTRIBUTE); config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTY, htmlToXmlParserClass); final NodeList nlProperties = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_ELEMENT); if(nlProperties.getLength() > 0) { final Properties pProperties = ParametersExtractor.parseProperties(nlProperties.item(0)); if(pProperties != null) { final Map<String, Object> properties = new HashMap<>(); pProperties.forEach((k,v) -> properties.put(k.toString(), v)); config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_PROPERTIES_PROPERTY, properties); } } final NodeList nlFeatures = htmlToXml.getElementsByTagName(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_ELEMENT); if(nlFeatures.getLength() > 0) { final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0)); if(pFeatures != null) { final Map<String, Boolean> features = new HashMap<>(); pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString()))); config.put(HtmlToXmlParser.HTML_TO_XML_PARSER_FEATURES_PROPERTY, features); } } } } /** * DOCUMENT ME! * * @param serializer */ private void configureSerializer( Element serializer ) { final String xinclude = getConfigAttributeValue( serializer, Serializer.ENABLE_XINCLUDE_ATTRIBUTE ); if( xinclude != null ) { config.put( Serializer.PROPERTY_ENABLE_XINCLUDE, xinclude ); LOG.debug( Serializer.PROPERTY_ENABLE_XINCLUDE + ": " + config.get( Serializer.PROPERTY_ENABLE_XINCLUDE ) ); } final String xsl = getConfigAttributeValue( serializer, Serializer.ENABLE_XSL_ATTRIBUTE ); if( xsl != null ) { config.put( Serializer.PROPERTY_ENABLE_XSL, xsl ); LOG.debug( Serializer.PROPERTY_ENABLE_XSL + ": " + config.get( Serializer.PROPERTY_ENABLE_XSL ) ); } final String indent = getConfigAttributeValue( serializer, Serializer.INDENT_ATTRIBUTE ); if( indent != null ) { config.put( Serializer.PROPERTY_INDENT, indent ); LOG.debug( Serializer.PROPERTY_INDENT + ": " + config.get( Serializer.PROPERTY_INDENT ) ); } final String compress = getConfigAttributeValue( serializer, Serializer.COMPRESS_OUTPUT_ATTRIBUTE ); if( compress != null ) { config.put( Serializer.PROPERTY_COMPRESS_OUTPUT, compress ); LOG.debug( Serializer.PROPERTY_COMPRESS_OUTPUT + ": " + config.get( Serializer.PROPERTY_COMPRESS_OUTPUT ) ); } final String internalId = getConfigAttributeValue( serializer, Serializer.ADD_EXIST_ID_ATTRIBUTE ); if( internalId != null ) { config.put( Serializer.PROPERTY_ADD_EXIST_ID, internalId ); LOG.debug( Serializer.PROPERTY_ADD_EXIST_ID + ": " + config.get( Serializer.PROPERTY_ADD_EXIST_ID ) ); } final String tagElementMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ELEMENTS_ATTRIBUTE ); if( tagElementMatches != null ) { config.put( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS, tagElementMatches ); LOG.debug( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS + ": " + config.get( Serializer.PROPERTY_TAG_MATCHING_ELEMENTS ) ); } final String tagAttributeMatches = getConfigAttributeValue( serializer, Serializer.TAG_MATCHING_ATTRIBUTES_ATTRIBUTE ); if( tagAttributeMatches != null ) { config.put( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES, tagAttributeMatches ); LOG.debug( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES + ": " + config.get( Serializer.PROPERTY_TAG_MATCHING_ATTRIBUTES ) ); } final NodeList nlFilters = serializer.getElementsByTagName( CustomMatchListenerFactory.CONFIGURATION_ELEMENT ); if( nlFilters != null ) { final List<String> filters = new ArrayList<>(nlFilters.getLength()); for (int i = 0; i < nlFilters.getLength(); i++) { final Element filterElem = (Element) nlFilters.item(i); final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS); if (filterClass != null) { filters.add(filterClass); LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": " + filterClass); } else { LOG.warn("Configuration element " + CustomMatchListenerFactory.CONFIGURATION_ELEMENT + " needs an attribute 'class'"); } } config.put(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS, filters); } final NodeList backupFilters = serializer.getElementsByTagName( SystemExport.CONFIGURATION_ELEMENT ); if( backupFilters != null ) { final List<String> filters = new ArrayList<>(backupFilters.getLength()); for (int i = 0; i < backupFilters.getLength(); i++) { final Element filterElem = (Element) backupFilters.item(i); final String filterClass = filterElem.getAttribute(CustomMatchListenerFactory.CONFIGURATION_ATTR_CLASS); if (filterClass != null) { filters.add(filterClass); LOG.debug(CustomMatchListenerFactory.CONFIG_MATCH_LISTENERS + ": " + filterClass); } else { LOG.warn("Configuration element " + SystemExport.CONFIGURATION_ELEMENT + " needs an attribute 'class'"); } } if (!filters.isEmpty()) config.put(SystemExport.CONFIG_FILTERS, filters); } } /** * Reads the scheduler configuration. * * @param scheduler DOCUMENT ME! */ private void configureScheduler(final Element scheduler) { final NodeList nlJobs = scheduler.getElementsByTagName(JobConfig.CONFIGURATION_JOB_ELEMENT_NAME); if(nlJobs == null) { return; } final List<JobConfig> jobList = new ArrayList<JobConfig>(); for(int i = 0; i < nlJobs.getLength(); i++) { final Element job = (Element)nlJobs.item( i ); //get the job type final String strJobType = getConfigAttributeValue(job, JobConfig.JOB_TYPE_ATTRIBUTE); final JobType jobType; if(strJobType == null) { jobType = JobType.USER; //default to user if unspecified } else { jobType = JobType.valueOf(strJobType.toUpperCase(Locale.ENGLISH)); } final String jobName = getConfigAttributeValue(job, JobConfig.JOB_NAME_ATTRIBUTE); //get the job resource String jobResource = getConfigAttributeValue(job, JobConfig.JOB_CLASS_ATTRIBUTE); if(jobResource == null) { jobResource = getConfigAttributeValue(job, JobConfig.JOB_XQUERY_ATTRIBUTE); } //get the job schedule String jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_CRON_TRIGGER_ATTRIBUTE); if(jobSchedule == null) { jobSchedule = getConfigAttributeValue(job, JobConfig.JOB_PERIOD_ATTRIBUTE); } final String jobUnschedule = getConfigAttributeValue(job, JobConfig.JOB_UNSCHEDULE_ON_EXCEPTION); //create the job config try { final JobConfig jobConfig = new JobConfig(jobType, jobName, jobResource, jobSchedule, jobUnschedule); //get and set the job delay final String jobDelay = getConfigAttributeValue(job, JobConfig.JOB_DELAY_ATTRIBUTE); if((jobDelay != null) && (jobDelay.length() > 0)) { jobConfig.setDelay(Long.parseLong(jobDelay)); } //get and set the job repeat final String jobRepeat = getConfigAttributeValue(job, JobConfig.JOB_REPEAT_ATTRIBUTE); if((jobRepeat != null) && (jobRepeat.length() > 0)) { jobConfig.setRepeat(Integer.parseInt(jobRepeat)); } final NodeList nlParam = job.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME); final Map<String, List<? extends Object>> params = ParametersExtractor.extract(nlParam); for(final Entry<String, List<? extends Object>> param : params.entrySet()) { final List<? extends Object> values = param.getValue(); if(values != null && values.size() > 0) { jobConfig.addParameter(param.getKey(), values.get(0).toString()); if(values.size() > 1) { LOG.warn("Parameter '" + param.getKey() + "' for job '" + jobName + "' has more than one value, ignoring further values."); } } } jobList.add(jobConfig); LOG.debug("Configured scheduled '" + jobType + "' job '" + jobResource + ((jobSchedule == null) ? "" : ("' with trigger '" + jobSchedule)) + ((jobDelay == null) ? "" : ("' with delay '" + jobDelay)) + ((jobRepeat == null) ? "" : ("' repetitions '" + jobRepeat)) + "'"); } catch(final JobException je) { LOG.error(je); } } if(jobList.size() > 0 ) { final JobConfig[] configs = new JobConfig[jobList.size()]; for(int i = 0; i < jobList.size(); i++) { configs[i] = (JobConfig)jobList.get(i); } config.put(JobConfig.PROPERTY_SCHEDULER_JOBS, configs); } } /** * DOCUMENT ME! * * @param dbHome * @param con * * @throws DatabaseConfigurationException */ private void configureBackend( final Optional<Path> dbHome, Element con ) throws DatabaseConfigurationException { final String mysql = getConfigAttributeValue( con, BrokerFactory.PROPERTY_DATABASE ); if( mysql != null ) { config.put( BrokerFactory.PROPERTY_DATABASE, mysql ); LOG.debug( BrokerFactory.PROPERTY_DATABASE + ": " + config.get( BrokerFactory.PROPERTY_DATABASE ) ); } // directory for database files final String dataFiles = getConfigAttributeValue( con, BrokerPool.DATA_DIR_ATTRIBUTE ); if (dataFiles != null) { final Path df = ConfigurationHelper.lookup( dataFiles, dbHome ); if (!Files.isReadable(df)) { try { Files.createDirectories(df); } catch (final IOException ioe) { throw new DatabaseConfigurationException("cannot read data directory: " + df.toAbsolutePath().toString(), ioe); } } config.put(BrokerPool.PROPERTY_DATA_DIR, df.toAbsolutePath()); LOG.debug(BrokerPool.PROPERTY_DATA_DIR + ": " + config.get(BrokerPool.PROPERTY_DATA_DIR)); } String cacheMem = getConfigAttributeValue( con, DefaultCacheManager.CACHE_SIZE_ATTRIBUTE ); if( cacheMem != null ) { if( cacheMem.endsWith( "M" ) || cacheMem.endsWith( "m" ) ) { cacheMem = cacheMem.substring( 0, cacheMem.length() - 1 ); } try { config.put( DefaultCacheManager.PROPERTY_CACHE_SIZE, Integer.valueOf(cacheMem) ); LOG.debug( DefaultCacheManager.PROPERTY_CACHE_SIZE + ": " + config.get( DefaultCacheManager.PROPERTY_CACHE_SIZE ) + "m" ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + DefaultCacheManager.PROPERTY_CACHE_SIZE + " value to integer: " + cacheMem, nfe); } } // Process the Check Max Cache value String checkMaxCache = getConfigAttributeValue( con, DefaultCacheManager.CACHE_CHECK_MAX_SIZE_ATTRIBUTE ); if( checkMaxCache == null ) { checkMaxCache = DefaultCacheManager.DEFAULT_CACHE_CHECK_MAX_SIZE_STRING; } config.put( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE, parseBoolean( checkMaxCache, true ) ); LOG.debug( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE + ": " + config.get( DefaultCacheManager.PROPERTY_CACHE_CHECK_MAX_SIZE ) ); String cacheShrinkThreshold = getConfigAttributeValue( con, DefaultCacheManager.SHRINK_THRESHOLD_ATTRIBUTE ); if( cacheShrinkThreshold == null ) { cacheShrinkThreshold = DefaultCacheManager.DEFAULT_SHRINK_THRESHOLD_STRING; } try { config.put(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY, Integer.valueOf(cacheShrinkThreshold)); LOG.debug(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + ": " + config.get(DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY)); } catch(final NumberFormatException nfe) { LOG.warn("Cannot convert " + DefaultCacheManager.SHRINK_THRESHOLD_PROPERTY + " value to integer: " + cacheShrinkThreshold, nfe); } String collectionCache = getConfigAttributeValue(con, CollectionCache.CACHE_SIZE_ATTRIBUTE); if(collectionCache != null) { collectionCache = collectionCache.toLowerCase(); try { final int collectionCacheBytes; if(collectionCache.endsWith("k")) { collectionCacheBytes = 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 1)); } else if(collectionCache.endsWith("kb")) { collectionCacheBytes = 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 2)); } else if(collectionCache.endsWith("m")) { collectionCacheBytes = 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 1)); } else if(collectionCache.endsWith("mb")) { collectionCacheBytes = 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 2)); } else if(collectionCache.endsWith("g")) { collectionCacheBytes = 1024 * 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 1)); } else if(collectionCache.endsWith("gb")) { collectionCacheBytes = 1024 * 1024 * 1024 * Integer.valueOf(collectionCache.substring(0, collectionCache.length() - 2)); } else { collectionCacheBytes = Integer.valueOf(collectionCache); } config.put(CollectionCache.PROPERTY_CACHE_SIZE_BYTES, collectionCacheBytes); if(LOG.isDebugEnabled()) { LOG.debug("Set config {} = {}", CollectionCache.PROPERTY_CACHE_SIZE_BYTES, config.get(CollectionCache.PROPERTY_CACHE_SIZE_BYTES)); } } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + CollectionCache.PROPERTY_CACHE_SIZE_BYTES + " value to integer: " + collectionCache, nfe); } } final String pageSize = getConfigAttributeValue( con, NativeBroker.PAGE_SIZE_ATTRIBUTE ); if( pageSize != null ) { try { config.put( BrokerPool.PROPERTY_PAGE_SIZE, Integer.valueOf(pageSize) ); LOG.debug( BrokerPool.PROPERTY_PAGE_SIZE + ": " + config.get( BrokerPool.PROPERTY_PAGE_SIZE ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + BrokerPool.PROPERTY_PAGE_SIZE + " value to integer: " + pageSize, nfe); } } //Not clear : rather looks like a buffers count final String collCacheSize = getConfigAttributeValue( con, BrokerPool.COLLECTION_CACHE_SIZE_ATTRIBUTE ); if( collCacheSize != null ) { try { config.put( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE, Integer.valueOf(collCacheSize) ); LOG.debug( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + ": " + config.get( BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + BrokerPool.PROPERTY_COLLECTION_CACHE_SIZE + " value to integer: " + collCacheSize, nfe); } } final String nodesBuffer = getConfigAttributeValue( con, BrokerPool.NODES_BUFFER_ATTRIBUTE ); if( nodesBuffer != null ) { try { config.put( BrokerPool.PROPERTY_NODES_BUFFER, Integer.valueOf(nodesBuffer) ); LOG.debug( BrokerPool.PROPERTY_NODES_BUFFER + ": " + config.get( BrokerPool.PROPERTY_NODES_BUFFER ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + BrokerPool.PROPERTY_NODES_BUFFER + " value to integer: " + nodesBuffer, nfe); } } final String docIds = con.getAttribute(BrokerPool.DOC_ID_MODE_ATTRIBUTE); if (docIds != null) { config.put(BrokerPool.DOC_ID_MODE_PROPERTY, docIds); } //Unused ! final String buffers = getConfigAttributeValue( con, "buffers" ); if( buffers != null ) { try { config.put( "db-connection.buffers", Integer.valueOf(buffers) ); LOG.debug( "db-connection.buffers: " + config.get( "db-connection.buffers" ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + "db-connection.buffers" + " value to integer: " + buffers, nfe); } } //Unused ! final String collBuffers = getConfigAttributeValue( con, "collection_buffers" ); if( collBuffers != null ) { try { config.put( "db-connection.collections.buffers", Integer.valueOf(collBuffers) ); LOG.debug( "db-connection.collections.buffers: " + config.get( "db-connection.collections.buffers" ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + "db-connection.collections.buffers" + " value to integer: " + collBuffers, nfe); } } //Unused ! final String wordBuffers = getConfigAttributeValue( con, "words_buffers" ); if( wordBuffers != null ) { try { config.put( "db-connection.words.buffers", Integer.valueOf(wordBuffers) ); LOG.debug( "db-connection.words.buffers: " + config.get( "db-connection.words.buffers" ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + "db-connection.words.buffers" + " value to integer: " + wordBuffers, nfe); } } //Unused ! final String elementBuffers = getConfigAttributeValue( con, "elements_buffers" ); if( elementBuffers != null ) { try { config.put( "db-connection.elements.buffers", Integer.valueOf(elementBuffers) ); LOG.debug( "db-connection.elements.buffers: " + config.get( "db-connection.elements.buffers" ) ); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + "db-connection.elements.buffers" + " value to integer: " + elementBuffers, nfe); } } String diskSpace = getConfigAttributeValue(con, BrokerPool.DISK_SPACE_MIN_ATTRIBUTE); if( diskSpace != null ) { if( diskSpace.endsWith( "M" ) || diskSpace.endsWith( "m" ) ) { diskSpace = diskSpace.substring( 0, diskSpace.length() - 1 ); } try { config.put(BrokerPool.DISK_SPACE_MIN_PROPERTY, Short.valueOf(diskSpace)); } catch( final NumberFormatException nfe ) { LOG.warn("Cannot convert " + BrokerPool.DISK_SPACE_MIN_PROPERTY + " value to integer: " + diskSpace, nfe); } } final String posixChownRestrictedStr = getConfigAttributeValue(con, DBBroker.POSIX_CHOWN_RESTRICTED_ATTRIBUTE); final boolean posixChownRestricted; if(posixChownRestrictedStr == null) { posixChownRestricted = true; // default } else { if(Boolean.valueOf(posixChownRestrictedStr)) { posixChownRestricted = true; } else { // configuration explicitly specifies that posix chown should NOT be restricted posixChownRestricted = false; } } config.put(DBBroker.POSIX_CHOWN_RESTRICTED_PROPERTY, posixChownRestricted); final String preserveOnCopyStr = getConfigAttributeValue(con, DBBroker.PRESERVE_ON_COPY_ATTRIBUTE); final DBBroker.PreserveType preserveOnCopy; if(preserveOnCopyStr == null) { preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE; // default } else { if(Boolean.valueOf(preserveOnCopyStr)) { // configuration explicitly specifies that attributes should be preserved on copy preserveOnCopy = DBBroker.PreserveType.PRESERVE; } else { preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE; } } config.put(DBBroker.PRESERVE_ON_COPY_PROPERTY, preserveOnCopy); final NodeList securityConf = con.getElementsByTagName( BrokerPool.CONFIGURATION_SECURITY_ELEMENT_NAME ); String securityManagerClassName = BrokerPool.DEFAULT_SECURITY_CLASS; if( securityConf.getLength() > 0 ) { final Element security = (Element)securityConf.item( 0 ); securityManagerClassName = getConfigAttributeValue( security, "class" ); //Unused final String encoding = getConfigAttributeValue( security, "password-encoding" ); config.put( "db-connection.security.password-encoding", encoding ); //Unused final String realm = getConfigAttributeValue( security, "password-realm" ); config.put( "db-connection.security.password-realm", realm ); if( realm != null ) { LOG.info( "db-connection.security.password-realm: " + config.get( "db-connection.security.password-realm" ) ); RealmImpl.setPasswordRealm( realm ); } else { LOG.info( "No password realm set, defaulting." ); } } try { config.put( BrokerPool.PROPERTY_SECURITY_CLASS, Class.forName( securityManagerClassName ) ); LOG.debug( BrokerPool.PROPERTY_SECURITY_CLASS + ": " + config.get( BrokerPool.PROPERTY_SECURITY_CLASS ) ); } catch( final Throwable ex ) { if( ex instanceof ClassNotFoundException ) { throw( new DatabaseConfigurationException( "Cannot find security manager class " + securityManagerClassName, ex ) ); } else { throw( new DatabaseConfigurationException( "Cannot load security manager class " + securityManagerClassName + " due to " + ex.getMessage(), ex ) ); } } final NodeList startupConf = con.getElementsByTagName(BrokerPool.CONFIGURATION_STARTUP_ELEMENT_NAME); if(startupConf.getLength() > 0) { configureStartup((Element)startupConf.item(0)); } else { // Prevent NPE final List<StartupTriggerConfig> startupTriggers = new ArrayList<StartupTriggerConfig>(); config.put(BrokerPool.PROPERTY_STARTUP_TRIGGERS, startupTriggers); } final NodeList poolConf = con.getElementsByTagName( BrokerPool.CONFIGURATION_POOL_ELEMENT_NAME ); if( poolConf.getLength() > 0 ) { configurePool( (Element)poolConf.item( 0 ) ); } final NodeList queryPoolConf = con.getElementsByTagName( XQueryPool.CONFIGURATION_ELEMENT_NAME ); if( queryPoolConf.getLength() > 0 ) { configureXQueryPool( (Element)queryPoolConf.item( 0 ) ); } final NodeList watchConf = con.getElementsByTagName( XQueryWatchDog.CONFIGURATION_ELEMENT_NAME ); if( watchConf.getLength() > 0 ) { configureWatchdog( (Element)watchConf.item( 0 ) ); } final NodeList recoveries = con.getElementsByTagName( BrokerPool.CONFIGURATION_RECOVERY_ELEMENT_NAME ); if( recoveries.getLength() > 0 ) { configureRecovery( dbHome, (Element)recoveries.item( 0 ) ); } } private void configureRecovery( final Optional<Path> dbHome, Element recovery ) throws DatabaseConfigurationException { String option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_ENABLED_ATTRIBUTE ); setProperty( BrokerPool.PROPERTY_RECOVERY_ENABLED, parseBoolean( option, true ) ); LOG.debug( BrokerPool.PROPERTY_RECOVERY_ENABLED + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_ENABLED ) ); option = getConfigAttributeValue( recovery, Journal.RECOVERY_SYNC_ON_COMMIT_ATTRIBUTE ); setProperty( Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT, parseBoolean( option, true ) ); LOG.debug( Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT + ": " + config.get( Journal.PROPERTY_RECOVERY_SYNC_ON_COMMIT ) ); option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_GROUP_COMMIT_ATTRIBUTE ); setProperty( BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT, parseBoolean( option, false ) ); LOG.debug( BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_GROUP_COMMIT ) ); option = getConfigAttributeValue( recovery, Journal.RECOVERY_JOURNAL_DIR_ATTRIBUTE ); if(option != null) { //DWES final Path rf = ConfigurationHelper.lookup( option, dbHome ); if(!Files.isReadable(rf)) { throw new DatabaseConfigurationException( "cannot read data directory: " + rf.toAbsolutePath()); } setProperty(Journal.PROPERTY_RECOVERY_JOURNAL_DIR, rf.toAbsolutePath()); LOG.debug(Journal.PROPERTY_RECOVERY_JOURNAL_DIR + ": " + config.get(Journal.PROPERTY_RECOVERY_JOURNAL_DIR)); } option = getConfigAttributeValue( recovery, Journal.RECOVERY_SIZE_LIMIT_ATTRIBUTE ); if( option != null ) { if( option.endsWith( "M" ) || option.endsWith( "m" ) ) { option = option.substring( 0, option.length() - 1 ); } try { final Integer size = Integer.valueOf( option ); setProperty( Journal.PROPERTY_RECOVERY_SIZE_LIMIT, size ); LOG.debug( Journal.PROPERTY_RECOVERY_SIZE_LIMIT + ": " + config.get( Journal.PROPERTY_RECOVERY_SIZE_LIMIT ) + "m" ); } catch( final NumberFormatException e ) { throw( new DatabaseConfigurationException( "size attribute in recovery section needs to be a number" ) ); } } option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_FORCE_RESTART_ATTRIBUTE ); boolean value = false; if( option != null ) { value = "yes".equals(option); } setProperty( BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART, Boolean.valueOf( value ) ); LOG.debug( BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_FORCE_RESTART ) ); option = getConfigAttributeValue( recovery, BrokerPool.RECOVERY_POST_RECOVERY_CHECK ); value = false; if( option != null ) { value = "yes".equals(option); } setProperty( BrokerPool.PROPERTY_RECOVERY_CHECK, Boolean.valueOf( value ) ); LOG.debug( BrokerPool.PROPERTY_RECOVERY_CHECK + ": " + config.get( BrokerPool.PROPERTY_RECOVERY_CHECK ) ); } /** * DOCUMENT ME! * * @param watchDog */ private void configureWatchdog( Element watchDog ) { final String timeout = getConfigAttributeValue( watchDog, "query-timeout" ); if( timeout != null ) { try { config.put( XQueryWatchDog.PROPERTY_QUERY_TIMEOUT, Long.valueOf(timeout) ); LOG.debug( XQueryWatchDog.PROPERTY_QUERY_TIMEOUT + ": " + config.get( XQueryWatchDog.PROPERTY_QUERY_TIMEOUT ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } final String maxOutput = getConfigAttributeValue( watchDog, "output-size-limit" ); if( maxOutput != null ) { try { config.put( XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT, Integer.valueOf(maxOutput) ); LOG.debug( XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT + ": " + config.get( XQueryWatchDog.PROPERTY_OUTPUT_SIZE_LIMIT ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } } /** * DOCUMENT ME! * * @param queryPool */ private void configureXQueryPool( Element queryPool ) { final String maxStackSize = getConfigAttributeValue( queryPool, XQueryPool.MAX_STACK_SIZE_ATTRIBUTE ); if( maxStackSize != null ) { try { config.put( XQueryPool.PROPERTY_MAX_STACK_SIZE, Integer.valueOf(maxStackSize) ); LOG.debug( XQueryPool.PROPERTY_MAX_STACK_SIZE + ": " + config.get( XQueryPool.PROPERTY_MAX_STACK_SIZE ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } final String maxPoolSize = getConfigAttributeValue( queryPool, XQueryPool.POOL_SIZE_ATTTRIBUTE ); if( maxPoolSize != null ) { try { config.put( XQueryPool.PROPERTY_POOL_SIZE, Integer.valueOf(maxPoolSize) ); LOG.debug( XQueryPool.PROPERTY_POOL_SIZE + ": " + config.get( XQueryPool.PROPERTY_POOL_SIZE ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } final String timeout = getConfigAttributeValue( queryPool, XQueryPool.TIMEOUT_ATTRIBUTE ); if( timeout != null ) { try { config.put( XQueryPool.PROPERTY_TIMEOUT, Long.valueOf(timeout) ); LOG.debug( XQueryPool.PROPERTY_TIMEOUT + ": " + config.get( XQueryPool.PROPERTY_TIMEOUT ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } } public static class StartupTriggerConfig { private final String clazz; private final Map<String, List<? extends Object>> params; public StartupTriggerConfig(final String clazz, final Map<String, List<? extends Object>> params) { this.clazz = clazz; this.params = params; } public String getClazz() { return clazz; } public Map<String, List<? extends Object>> getParams() { return params; } } private void configureStartup(final Element startup) { // Retrieve <triggers> final NodeList nlTriggers = startup.getElementsByTagName("triggers"); // If <triggers> exists if(nlTriggers != null && nlTriggers.getLength() > 0) { // Get <triggers> final Element triggers = (Element)nlTriggers.item(0); // Get <trigger> final NodeList nlTrigger = triggers.getElementsByTagName("trigger"); // If <trigger> exists and there are more than 0 if(nlTrigger != null && nlTrigger.getLength() > 0) { // Initialize trigger configuration List<StartupTriggerConfig> startupTriggers = (List<StartupTriggerConfig>)config.get(BrokerPool.PROPERTY_STARTUP_TRIGGERS); if(startupTriggers == null) { startupTriggers = new ArrayList<StartupTriggerConfig>(); config.put(BrokerPool.PROPERTY_STARTUP_TRIGGERS, startupTriggers); } // Iterate over <trigger> elements for(int i = 0; i < nlTrigger.getLength(); i++) { // Get <trigger> element final Element trigger = (Element)nlTrigger.item(i); // Get @class final String startupTriggerClass = trigger.getAttribute("class"); boolean isStartupTrigger = false; try { // Verify if class is StartupTrigger for(final Class iface : Class.forName(startupTriggerClass).getInterfaces()) { if("org.exist.storage.StartupTrigger".equals(iface.getName())) { isStartupTrigger = true; break; } } // if it actually is a StartupTrigger if(isStartupTrigger) { // Parse additional parameters final Map<String, List<? extends Object>> params = ParametersExtractor.extract(trigger.getElementsByTagName(ParametersExtractor.PARAMETER_ELEMENT_NAME)); // Register trigger startupTriggers.add(new StartupTriggerConfig(startupTriggerClass, params)); // Done LOG.info("Registered StartupTrigger: " + startupTriggerClass); } else { LOG.warn("StartupTrigger: " + startupTriggerClass + " does not implement org.exist.storage.StartupTrigger. IGNORING!"); } } catch(final ClassNotFoundException cnfe) { LOG.error("Could not find StartupTrigger class: " + startupTriggerClass + ". " + cnfe.getMessage(), cnfe); } } } } } /** * DOCUMENT ME! * * @param pool */ private void configurePool( Element pool ) { final String min = getConfigAttributeValue( pool, BrokerPool.MIN_CONNECTIONS_ATTRIBUTE ); if( min != null ) { try { config.put( BrokerPool.PROPERTY_MIN_CONNECTIONS, Integer.valueOf(min) ); LOG.debug( BrokerPool.PROPERTY_MIN_CONNECTIONS + ": " + config.get( BrokerPool.PROPERTY_MIN_CONNECTIONS ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } final String max = getConfigAttributeValue( pool, BrokerPool.MAX_CONNECTIONS_ATTRIBUTE ); if( max != null ) { try { config.put( BrokerPool.PROPERTY_MAX_CONNECTIONS, Integer.valueOf(max) ); LOG.debug( BrokerPool.PROPERTY_MAX_CONNECTIONS + ": " + config.get( BrokerPool.PROPERTY_MAX_CONNECTIONS ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } final String sync = getConfigAttributeValue( pool, BrokerPool.SYNC_PERIOD_ATTRIBUTE ); if( sync != null ) { try { config.put( BrokerPool.PROPERTY_SYNC_PERIOD, Long.valueOf(sync) ); LOG.debug( BrokerPool.PROPERTY_SYNC_PERIOD + ": " + config.get( BrokerPool.PROPERTY_SYNC_PERIOD ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } final String maxShutdownWait = getConfigAttributeValue( pool, BrokerPool.SHUTDOWN_DELAY_ATTRIBUTE ); if( maxShutdownWait != null ) { try { config.put( BrokerPool.PROPERTY_SHUTDOWN_DELAY, Long.valueOf(maxShutdownWait) ); LOG.debug( BrokerPool.PROPERTY_SHUTDOWN_DELAY + ": " + config.get( BrokerPool.PROPERTY_SHUTDOWN_DELAY ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } } private void configureIndexer( final Optional<Path> dbHome, Document doc, Element indexer ) throws DatabaseConfigurationException, MalformedURLException { final String caseSensitive = getConfigAttributeValue( indexer, NativeValueIndex.INDEX_CASE_SENSITIVE_ATTRIBUTE ); if( caseSensitive != null ) { config.put( NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE, parseBoolean( caseSensitive, false ) ); LOG.debug( NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE + ": " + config.get( NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE ) ); } int depth = 3; final String indexDepth = getConfigAttributeValue( indexer, NativeBroker.INDEX_DEPTH_ATTRIBUTE ); if( indexDepth != null ) { try { depth = Integer.parseInt( indexDepth ); if( depth < 3 ) { LOG.warn( "parameter index-depth should be >= 3 or you will experience a severe " + "performance loss for node updates (XUpdate or XQuery update extensions)" ); depth = 3; } config.put( NativeBroker.PROPERTY_INDEX_DEPTH, Integer.valueOf(depth) ); LOG.debug( NativeBroker.PROPERTY_INDEX_DEPTH + ": " + config.get( NativeBroker.PROPERTY_INDEX_DEPTH ) ); } catch( final NumberFormatException e ) { LOG.warn( e ); } } final String suppressWS = getConfigAttributeValue( indexer, Indexer.SUPPRESS_WHITESPACE_ATTRIBUTE ); if( suppressWS != null ) { config.put( Indexer.PROPERTY_SUPPRESS_WHITESPACE, suppressWS ); LOG.debug( Indexer.PROPERTY_SUPPRESS_WHITESPACE + ": " + config.get( Indexer.PROPERTY_SUPPRESS_WHITESPACE ) ); } final String suppressWSmixed = getConfigAttributeValue( indexer, Indexer.PRESERVE_WS_MIXED_CONTENT_ATTRIBUTE ); if( suppressWSmixed != null ) { config.put( Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT, parseBoolean( suppressWSmixed, false ) ); LOG.debug( Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT + ": " + config.get( Indexer.PROPERTY_PRESERVE_WS_MIXED_CONTENT ) ); } // index settings final NodeList cl = doc.getElementsByTagName( Indexer.CONFIGURATION_INDEX_ELEMENT_NAME ); if( cl.getLength() > 0 ) { final Element elem = (Element)cl.item( 0 ); final IndexSpec spec = new IndexSpec( null, elem ); config.put( Indexer.PROPERTY_INDEXER_CONFIG, spec ); //LOG.debug(Indexer.PROPERTY_INDEXER_CONFIG + ": " + config.get(Indexer.PROPERTY_INDEXER_CONFIG)); } // index modules NodeList modules = indexer.getElementsByTagName( IndexManager.CONFIGURATION_ELEMENT_NAME ); if( modules.getLength() > 0 ) { modules = ( (Element)modules.item( 0 ) ).getElementsByTagName( IndexManager.CONFIGURATION_MODULE_ELEMENT_NAME ); final IndexModuleConfig[] modConfig = new IndexModuleConfig[modules.getLength()]; for( int i = 0; i < modules.getLength(); i++ ) { final Element elem = (Element)modules.item( i ); final String className = elem.getAttribute( IndexManager.INDEXER_MODULES_CLASS_ATTRIBUTE ); final String id = elem.getAttribute( IndexManager.INDEXER_MODULES_ID_ATTRIBUTE ); if( ( className == null ) || ( className.length() == 0 ) ) { throw( new DatabaseConfigurationException( "Required attribute class is missing for module" ) ); } if( ( id == null ) || ( id.length() == 0 ) ) { throw( new DatabaseConfigurationException( "Required attribute id is missing for module" ) ); } modConfig[i] = new IndexModuleConfig( id, className, elem ); } config.put( IndexManager.PROPERTY_INDEXER_MODULES, modConfig ); } } private void configureValidation( final Optional<Path> dbHome, Document doc, Element validation ) throws DatabaseConfigurationException { // Determine validation mode final String mode = getConfigAttributeValue( validation, XMLReaderObjectFactory.VALIDATION_MODE_ATTRIBUTE ); if( mode != null ) { config.put( XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE, mode ); LOG.debug( XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE + ": " + config.get( XMLReaderObjectFactory.PROPERTY_VALIDATION_MODE ) ); } // Extract catalogs LOG.debug( "Creating eXist catalog resolver" ); final eXistXMLCatalogResolver resolver = new eXistXMLCatalogResolver(); final NodeList entityResolver = validation.getElementsByTagName( XMLReaderObjectFactory.CONFIGURATION_ENTITY_RESOLVER_ELEMENT_NAME ); if( entityResolver.getLength() > 0 ) { final Element r = (Element)entityResolver.item( 0 ); final NodeList catalogs = r.getElementsByTagName( XMLReaderObjectFactory.CONFIGURATION_CATALOG_ELEMENT_NAME ); LOG.debug( "Found " + catalogs.getLength() + " catalog uri entries." ); LOG.debug( "Using dbHome=" + dbHome ); // Determine webapps directory. SingleInstanceConfiguration cannot // be used at this phase. Trick is to check wether dbHOME is // pointing to a WEB-INF directory, meaning inside war file) final Path webappHome = dbHome.map(h -> { if(FileUtils.fileName(h).endsWith("WEB-INF")) { return h.getParent().toAbsolutePath(); } else { return h.resolve("webapp").toAbsolutePath(); } }).orElse(Paths.get("webapp").toAbsolutePath()); LOG.debug("using webappHome=" + webappHome.toString()); // Get and store all URIs final List<String> allURIs = new ArrayList<>(); for( int i = 0; i < catalogs.getLength(); i++ ) { String uri = ( (Element)catalogs.item( i ) ).getAttribute( "uri" ); if( uri != null ) { // when uri attribute is filled in // Substitute string, creating an uri from a local file if( uri.indexOf( "${WEBAPP_HOME}" ) != -1 ) { uri = uri.replaceAll( "\\$\\{WEBAPP_HOME\\}", webappHome.toUri().toString() ); } if( uri.indexOf( "${EXIST_HOME}" ) != -1 ) { uri = uri.replaceAll( "\\$\\{EXIST_HOME\\}", dbHome.toString() ); } // Add uri to confiuration LOG.info( "Add catalog uri " + uri + "" ); allURIs.add( uri ); } } resolver.setCatalogs( allURIs ); // Store all configured URIs config.put( XMLReaderObjectFactory.CATALOG_URIS, allURIs ); } // Store resolver config.put( XMLReaderObjectFactory.CATALOG_RESOLVER, resolver ); // cache final GrammarPool gp = new GrammarPool(); config.put( XMLReaderObjectFactory.GRAMMER_POOL, gp ); } /** * Gets the value of a configuration attribute * * The value typically is specified in the conf.xml file, but can be overriden with using a System Property * * @param element The attribute's parent element * @param attributeName The name of the attribute * * @return The value of the attribute */ private String getConfigAttributeValue( Element element, String attributeName ) { String value = null; if( element != null && attributeName != null ) { final String property = getAttributeSystemPropertyName( element, attributeName ); value = System.getProperty( property ); // If the value has not been overriden in a system property, then get it from the configuration if( value != null ) { LOG.warn( "Configuration value overriden by system property: " + property + ", with value: " + value ); } else { value = element.getAttribute( attributeName ); } } return( value ); } /** * Generates a suitable system property name from the given config attribute and parent element. * * values are of the form org.element.element.....attribute and follow the heirarchical structure of the conf.xml file. * For example, the db-connection cacheSize property name would be org.exist.db-connection.cacheSize * * @param element The attribute's parent element * @param attributeName The name of the attribute * * @return The generated system property name */ private String getAttributeSystemPropertyName( Element element, String attributeName ) { final StringBuilder property = new StringBuilder( attributeName ); Node parent = element.getParentNode(); property.insert( 0, "." ); property.insert( 0, element.getLocalName() ); while( parent != null && parent instanceof Element ) { final String parentName = ((Element)parent).getLocalName(); property.insert( 0, "." ); property.insert( 0, parentName ); parent = parent.getParentNode(); } property.insert( 0, "org." ); return( property.toString() ); } public Optional<Path> getConfigFilePath() { return configFilePath; } public Optional<Path> getExistHome() { return existHome; } public Object getProperty(final String name) { return config.get(name); } public <T> T getProperty(final String name, final T defaultValue) { return Optional.ofNullable((T)config.get(name)).orElse(defaultValue); } public boolean hasProperty(final String name) { return config.containsKey(name); } public void setProperty(final String name, final Object obj) { config.put(name, obj); } public void removeProperty(final String name) { config.remove(name); } /** * Takes the passed string and converts it to a non-null <code>Boolean</code> object. If value is null, the specified default value is used. * Otherwise, Boolean.TRUE is returned if and only if the passed string equals &quot;yes&quot; or &quot;true&quot;, ignoring case. * * @param value The string to parse * @param defaultValue The default if the string is null * * @return The parsed <code>Boolean</code> */ public static boolean parseBoolean(final String value, final boolean defaultValue) { return Optional.ofNullable(value) .map(v -> v.equalsIgnoreCase("yes") || v.equalsIgnoreCase("true")) .orElse(defaultValue); } public int getInteger(final String name) { return Optional.ofNullable(getProperty(name)) .filter(v -> v instanceof Integer) .map(v -> (int)v) .orElse(-1); } /** * (non-Javadoc). * * @param exception DOCUMENT ME! * * @throws SAXException DOCUMENT ME! * * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ @Override public void error( SAXParseException exception ) throws SAXException { LOG.error( "error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception ); } /** * (non-Javadoc). * * @param exception DOCUMENT ME! * * @throws SAXException DOCUMENT ME! * * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ @Override public void fatalError( SAXParseException exception ) throws SAXException { LOG.error("error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception); } /** * (non-Javadoc). * * @param exception DOCUMENT ME! * * @throws SAXException DOCUMENT ME! * * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ @Override public void warning( SAXParseException exception ) throws SAXException { LOG.error( "error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception ); } public static final class IndexModuleConfig { private final String id; private final String className; private final Element config; public IndexModuleConfig(final String id, final String className, final Element config) { this.id = id; this.className = className; this.config = config; } public String getId() { return( id ); } public String getClassName() { return( className ); } public Element getConfig() { return( config ); } } }
package kg.apc.jmeter.reporters; import kg.apc.jmeter.JMeterPluginsUtils; import org.apache.jmeter.engine.event.LoopIterationEvent; import org.apache.jmeter.reporters.ResultCollector; import org.apache.jmeter.samplers.SampleEvent; import org.apache.jmeter.samplers.SampleSaveConfiguration; import org.apache.jmeter.testelement.TestListener; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import org.loadosophia.jmeter.LoadosophiaAPIClient; import org.loadosophia.jmeter.LoadosophiaUploadResults; import org.loadosophia.jmeter.StatusNotifierCallback; import java.io.File; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public class LoadosophiaUploader extends ResultCollector implements StatusNotifierCallback, Runnable, TestListener { private static final Logger log = LoggingManager.getLoggerForClass(); public static final String TITLE = "title"; public static final String COLOR = "color"; public static final String UPLOAD_TOKEN = "uploadToken"; public static final String PROJECT = "project"; public static final String STORE_DIR = "storeDir"; public static final String USE_ONLINE = "useOnline"; private String fileName; private static final Object LOCK = new Object(); private boolean isSaving; private LoadosophiaUploadingNotifier perfMonNotifier = LoadosophiaUploadingNotifier.getInstance(); private String address; private boolean isOnlineInitiated = false; private LoadosophiaAPIClient apiClient; private BlockingQueue<SampleEvent> processingQueue; private Thread processorThread; private LoadosophiaAggregator aggregator; public LoadosophiaUploader() { super(); address = JMeterUtils.getPropDefault("loadosophia.address", "https://loadosophia.org/"); } @Override public void testStarted(String host) { synchronized (LOCK) { this.apiClient = getAPIClient(); try { if (!isSaving) { isSaving = true; setupSaving(); } } catch (IOException ex) { log.error("Error setting up saving", ex); } initiateOnline(); } super.testStarted(host); perfMonNotifier.startCollecting(); } @Override public void testEnded(String host) { super.testEnded(host); synchronized (LOCK) { if (isOnlineInitiated) { finishOnline(); } try { if (fileName == null) { throw new IOException("File for upload was not set, search for errors above in log"); } isSaving = false; LoadosophiaUploadResults uploadResult = this.apiClient.sendFiles(new File(fileName), perfMonNotifier.getFiles()); informUser("Uploaded successfully, go to results: " + uploadResult.getRedirectLink()); } catch (IOException ex) { informUser("Failed to upload results to Loadosophia.org, see log for detais"); log.error("Failed to upload results to loadosophia", ex); } } clearData(); perfMonNotifier.endCollecting(); } private void setupSaving() throws IOException { String dir = getStoreDir(); if (!dir.endsWith(File.separator)) { dir += File.separator; } File tmpFile; try { tmpFile = File.createTempFile("Loadosophia_", ".jtl", new File(dir)); } catch (IOException ex) { informUser("Unable to create temp file: " + ex.getMessage()); informUser("Try to set another directory in the above field."); throw ex; } fileName = tmpFile.getAbsolutePath(); tmpFile.delete(); // IMPORTANT! this is required to have CSV headers informUser("Storing results for upload to Loadosophia.org: " + fileName); setFilename(fileName); // OMG, I spent 2 days finding that setting properties in testStarted // marks them temporary, though they cleared in some places. // So we do dirty(?) hack here... clearTemporary(getProperty(FILENAME)); SampleSaveConfiguration conf = getSaveConfig(); JMeterPluginsUtils.doBestCSVSetup(conf); setSaveConfig(conf); } public void setProject(String proj) { setProperty(PROJECT, proj); } public String getProject() { return getPropertyAsString(PROJECT); } public void setUploadToken(String token) { setProperty(UPLOAD_TOKEN, token); } public String getUploadToken() { return getPropertyAsString(UPLOAD_TOKEN); } public void setTitle(String prefix) { setProperty(TITLE, prefix); } public String getTitle() { return getPropertyAsString(TITLE); } private void informUser(String string) { log.info(string); if (getVisualizer() != null && getVisualizer() instanceof LoadosophiaUploaderGui) { ((LoadosophiaUploaderGui) getVisualizer()).inform(string); } else { log.info(string); } } public String getStoreDir() { return getPropertyAsString(STORE_DIR); } public void setStoreDir(String prefix) { setProperty(STORE_DIR, prefix); } @Override public void testIterationStart(LoopIterationEvent lie) { } public void setColorFlag(String color) { setProperty(COLOR, color); } public String getColorFlag() { return getPropertyAsString(COLOR); } protected LoadosophiaAPIClient getAPIClient() { return new LoadosophiaAPIClient(this, address, getUploadToken(), getProject(), getColorFlag(), getTitle()); } @Override public void notifyAbout(String info) { informUser(info); } public boolean isUseOnline() { return getPropertyAsBoolean(USE_ONLINE); } public void setUseOnline(boolean selected) { setProperty(USE_ONLINE, selected); } @Override public void sampleOccurred(SampleEvent event) { super.sampleOccurred(event); if (isOnlineInitiated) { try { if (!processingQueue.offer(event, 1, TimeUnit.SECONDS)) { log.warn("Failed first dequeue insert try, retrying"); if (!processingQueue.offer(event, 1, TimeUnit.SECONDS)) { log.error("Failed second try to inser into deque, dropped sample"); } } } catch (InterruptedException ex) { log.info("Interrupted while putting sample event into deque", ex); } } } @Override public void run() { while (isOnlineInitiated) { try { SampleEvent event = processingQueue.poll(1, TimeUnit.SECONDS); if (event != null) { aggregator.addSample(event.getResult()); } if (aggregator.haveDataToSend()) { try { apiClient.sendOnlineData(aggregator.getDataToSend()); } catch (IOException ex) { log.warn("Failed to send active test data", ex); } } } catch (InterruptedException ex) { log.info("Interrupted while taking sample event from deque", ex); break; } } } private void initiateOnline() { if (isUseOnline()) { try { log.info("Starting Loadosophia online test"); informUser("Started active test: " + apiClient.startOnline()); aggregator = new LoadosophiaAggregator(); processingQueue = new LinkedBlockingQueue<SampleEvent>(); processorThread = new Thread(this); processorThread.setDaemon(true); isOnlineInitiated = true; processorThread.start(); } catch (IOException ex) { informUser("Failed to start active test"); log.warn("Failed to initiate active test", ex); this.isOnlineInitiated = false; } } } private void finishOnline() { isOnlineInitiated = false; processorThread.interrupt(); while (!processorThread.isInterrupted()) { log.debug("Waiting for bg thread to stop..."); try { Thread.sleep(50); processorThread.interrupt(); } catch (InterruptedException ex) { log.warn("Interrupted sleep", ex); } } log.info("Ending Loadosophia online test"); try { apiClient.endOnline(); } catch (IOException ex) { log.warn("Failed to finalize active test", ex); } } }
package edu.umd.cs.findbugs.ba.ch; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.DefaultAnnotationForParameters; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.bcel.BCELUtil; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.util.DualKeyHashMap; /** * Class for performing class hierarchy queries. * Does <em>not</em> require JavaClass objects to be in memory. * Instead, uses XClass objects. * * @author David Hovemeyer */ @DefaultAnnotationForParameters(NonNull.class) public class Subtypes2 { public static final boolean ENABLE_SUBTYPES2 = true; //SystemProperties.getBoolean("findbugs.subtypes2"); public static final boolean ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES = SystemProperties.getBoolean("findbugs.subtypes2.superclass"); public static final boolean DEBUG = SystemProperties.getBoolean("findbugs.subtypes2.debug"); public static final boolean DEBUG_QUERIES = SystemProperties.getBoolean("findbugs.subtypes2.debugqueries"); private final InheritanceGraph graph; private final Map<ClassDescriptor, ClassVertex> classDescriptorToVertexMap; private final Map<ClassDescriptor, SupertypeQueryResults> supertypeSetMap; private final Map<ClassDescriptor, Set<ClassDescriptor>> subtypeSetMap; private final Set<XClass> xclassSet; private final DualKeyHashMap<ObjectType, ObjectType, ObjectType> firstCommonSupertypeQueryCache; private final ObjectType SERIALIZABLE; private final ObjectType CLONEABLE; /** * Object to record the results of a supertype search. */ private static class SupertypeQueryResults { private Set<ClassDescriptor> supertypeSet = new HashSet<ClassDescriptor>(); private boolean encounteredMissingClasses = false; public void addSupertype(ClassDescriptor classDescriptor) { supertypeSet.add(classDescriptor); } public void setEncounteredMissingClasses(boolean encounteredMissingClasses) { this.encounteredMissingClasses = encounteredMissingClasses; } public boolean containsType(ClassDescriptor possibleSupertypeClassDescriptor) throws ClassNotFoundException { if (supertypeSet.contains(possibleSupertypeClassDescriptor)) { return true; } else if (!encounteredMissingClasses) { return false; } else { // We don't really know which class was missing. // However, any missing classes will already have been reported. throw new ClassNotFoundException(); } } } /** * Constructor. */ public Subtypes2() { this.graph = new InheritanceGraph(); this.classDescriptorToVertexMap = new HashMap<ClassDescriptor, ClassVertex>(); this.supertypeSetMap = new HashMap<ClassDescriptor, SupertypeQueryResults>();// XXX: use MapCache? this.subtypeSetMap = new HashMap<ClassDescriptor, Set<ClassDescriptor>>();// XXX: use MapCache? this.xclassSet = new HashSet<XClass>(); this.SERIALIZABLE = ObjectTypeFactory.getInstance("java.io.Serializable"); this.CLONEABLE = ObjectTypeFactory.getInstance("java.lang.Cloneable"); this.firstCommonSupertypeQueryCache = new DualKeyHashMap<ObjectType, ObjectType, ObjectType>(); } /** * @return Returns the graph. */ public InheritanceGraph getGraph() { return graph; } /** * Add an application class, and its transitive supertypes, to the inheritance graph. * * @param appXClass application XClass to add to the inheritance graph */ public void addApplicationClass(XClass appXClass) { ClassVertex vertex = addClassAndGetClassVertex(appXClass); vertex.markAsApplicationClass(); } /** * Add a class or interface, and its transitive supertypes, to the inheritance graph. * * @param xclass XClass to add to the inheritance graph */ public void addClass(XClass xclass) { addClassAndGetClassVertex(xclass); } /** * Add an XClass and all of its supertypes to * the InheritanceGraph. * * @param xclass an XClass * @return the ClassVertex representing the class in * the InheritanceGraph */ private ClassVertex addClassAndGetClassVertex(XClass xclass) { if (xclass == null) { throw new IllegalStateException(); } LinkedList<XClass> workList = new LinkedList<XClass>(); workList.add(xclass); while (!workList.isEmpty()) { XClass work = workList.removeFirst(); ClassVertex vertex = classDescriptorToVertexMap.get(work.getClassDescriptor()); if (vertex != null && vertex.isFinished()) { // This class has already been processed. continue; } if (vertex == null) { vertex = ClassVertex.createResolvedClassVertex(work.getClassDescriptor(), work); addVertexToGraph(work.getClassDescriptor(), vertex); } addSupertypeEdges(vertex, workList); vertex.setFinished(true); } return classDescriptorToVertexMap.get(xclass.getClassDescriptor()); } private void addVertexToGraph(ClassDescriptor classDescriptor, ClassVertex vertex) { if (classDescriptorToVertexMap.get(classDescriptor) != null) { throw new IllegalStateException(); } if (DEBUG) { System.out.println("Adding " + classDescriptor.toDottedClassName() + " to inheritance graph"); } graph.addVertex(vertex); classDescriptorToVertexMap.put(classDescriptor, vertex); if (vertex.isResolved()) { xclassSet.add(vertex.getXClass()); } if (vertex.isInterface()) { // There is no need to add additional worklist nodes because java/lang/Object has no supertypes. addInheritanceEdge(vertex, DescriptorFactory.instance().getClassDescriptor("java/lang/Object"), false, null); } } /** * Determine whether or not a given ReferenceType is a subtype of another. * Throws ClassNotFoundException if the question cannot be answered * definitively due to a missing class. * * @param type a ReferenceType * @param possibleSupertype another Reference type * @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not * @throws ClassNotFoundException if a missing class prevents a definitive answer */ public boolean isSubtype(ReferenceType type, ReferenceType possibleSupertype) throws ClassNotFoundException { // Eliminate some easy cases if (type.equals(possibleSupertype)) { return true; } // others? boolean typeIsObjectType = (type instanceof ObjectType); boolean possibleSupertypeIsObjectType = (possibleSupertype instanceof ObjectType); if (typeIsObjectType && possibleSupertypeIsObjectType) { // Both types are ordinary object (non-array) types. return isSubtype((ObjectType) type, (ObjectType) possibleSupertype); } boolean typeIsArrayType = (type instanceof ArrayType); boolean possibleSupertypeIsArrayType = (possibleSupertype instanceof ArrayType); if (typeIsArrayType) { // Check superclass/interfaces if (possibleSupertype.equals(ObjectType.OBJECT) || possibleSupertype.equals(SERIALIZABLE) || possibleSupertype.equals(CLONEABLE)) { return true; } // We checked all of the possible class/interface supertypes, // so if possibleSupertype is not an array type, // then we can definitively say no if (!possibleSupertypeIsArrayType) { return false; } // Check array/array subtype relationship ArrayType typeAsArrayType = (ArrayType) type; ArrayType possibleSupertypeAsArrayType = (ArrayType) possibleSupertype; // Must have same number of dimensions if (typeAsArrayType.getDimensions() < possibleSupertypeAsArrayType.getDimensions()) { return false; } Type possibleSupertypeBasicType = possibleSupertypeAsArrayType.getBasicType(); if (!(possibleSupertypeBasicType instanceof ObjectType)) { return false; } Type typeBasicType = typeAsArrayType.getBasicType(); // If dimensions differ, see if element types are compatible. if (typeAsArrayType.getDimensions() > possibleSupertypeAsArrayType.getDimensions()) { return isSubtype(new ArrayType(typeBasicType,typeAsArrayType.getDimensions() - possibleSupertypeAsArrayType.getDimensions() ), (ObjectType) possibleSupertypeBasicType); } // type's base type must be a subtype of possibleSupertype's base type. // Note that neither base type can be a non-ObjectType if we are to answer yes. if (!(typeBasicType instanceof ObjectType)) { return false; } return isSubtype((ObjectType) typeBasicType, (ObjectType) possibleSupertypeBasicType); } // OK, we've exhausted the possibilities now return false; } /** * Determine whether or not a given ObjectType is a subtype of another. * Throws ClassNotFoundException if the question cannot be answered * definitively due to a missing class. * * @param type a ReferenceType * @param possibleSupertype another Reference type * @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not * @throws ClassNotFoundException if a missing class prevents a definitive answer */ public boolean isSubtype(ObjectType type, ObjectType possibleSupertype) throws ClassNotFoundException { if (DEBUG_QUERIES) { System.out.println("isSubtype: check " + type + " subtype of " + possibleSupertype); } if (type.equals(possibleSupertype)) { if (DEBUG_QUERIES) { System.out.println(" ==> yes, types are same"); } return true; } ClassDescriptor typeClassDescriptor = BCELUtil.getClassDescriptor(type); ClassDescriptor possibleSuperclassClassDescriptor = BCELUtil.getClassDescriptor(possibleSupertype); ClassVertex possibleSuperclassClassVertex = resolveClassVertex(possibleSuperclassClassDescriptor); // In principle, we should be able to answer no if the ObjectType objects // are not equal and possibleSupertype is final. // However, internally FindBugs creates special "subtypes" of java.lang.String // These will end up resolving to the same ClassVertex as java.lang.String, // which will Do The Right Thing. /* if (possibleSuperclassClassVertex.isResolved() && possibleSuperclassClassVertex.getXClass().isFinal()) { if (DEBUG_QUERIES) { System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is final"); } return false; } */ // Get the supertype query results SupertypeQueryResults supertypeQueryResults = getSupertypeQueryResults(typeClassDescriptor); if (DEBUG_QUERIES) { System.out.println(" Superclass set: " + supertypeQueryResults.supertypeSet); } boolean isSubtype = supertypeQueryResults.containsType(possibleSuperclassClassDescriptor); if (DEBUG_QUERIES) { if (isSubtype) { System.out.println(" ==> yes, " + possibleSuperclassClassDescriptor + " is in superclass set"); } else { System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is not in superclass set"); } } return isSubtype; } public ReferenceType getFirstCommonSupertype(ReferenceType a, ReferenceType b) throws ClassNotFoundException { // Easy case: same types if (a.equals(b)) { return a; } boolean aIsArrayType = (a instanceof ArrayType); boolean bIsArrayType = (b instanceof ArrayType); if (aIsArrayType && bIsArrayType) { // Merging array types - kind of a pain. ArrayType aArrType = (ArrayType) a; ArrayType bArrType = (ArrayType) b; Type aBaseType = aArrType.getBasicType(); Type bBaseType = bArrType.getBasicType(); if ((aBaseType instanceof BasicType) || (bBaseType instanceof BasicType)) { // At least one of a or b has a primitive type as its base type, // and they differ either in number of dimensions or base types. return ObjectType.OBJECT; } int aNumDimensions = aArrType.getDimensions(); int bNumDimensions = bArrType.getDimensions(); if (aNumDimensions == bNumDimensions) { // Same number of dimensions is an easy case. // Compute the ObjectType which is the first common superclass // of the respective base types, and return a new array // with that base type and the same number of dimensions. ObjectType baseTypesFirstCommonSupertype = getFirstCommonSupertype((ObjectType) aBaseType, (ObjectType) bBaseType); return new ArrayType(baseTypesFirstCommonSupertype, aNumDimensions); } // Weird case: both arrays have an ObjectType as the base type, // but numbers of dimensions differ. // Common supertype is an array whose base type is Object // and whose number of dimensions is the // smaller number of dimensions of a and b. // E.g., first common supertype of String[][] and Integer[] // is Object[]. return new ArrayType(ObjectType.OBJECT, Math.min(aNumDimensions, bNumDimensions)); } if (aIsArrayType || bIsArrayType) { // One of a and b is an array type, but not both. // Common supertype is Object. return ObjectType.OBJECT; } // Neither a nor b is an array type. // Find first common supertypes of ObjectTypes. return getFirstCommonSupertype((ObjectType) a, (ObjectType) b); } public ObjectType getFirstCommonSupertype(ObjectType a, ObjectType b) throws ClassNotFoundException { // This function is commutative, so don't clutter up the cache // storing the answer to (A op B) and (B op A) separately. if (a.getSignature().compareTo(b.getSignature()) > 0) { ObjectType tmp = a; a = b; b = tmp; } // Try the cache ObjectType firstCommonSupertype = firstCommonSupertypeQueryCache.get(a, b); // Need to compute answer? if (firstCommonSupertype == null) { ClassDescriptor aDesc = BCELUtil.getClassDescriptor(a); ClassDescriptor bDesc = BCELUtil.getClassDescriptor(b); ClassVertex aVertex = resolveClassVertex(aDesc); ClassVertex bVertex = resolveClassVertex(bDesc); ArrayList<ClassVertex> aSuperList = getAllSuperclassVertices(aVertex); ArrayList<ClassVertex> bSuperList = getAllSuperclassVertices(bVertex); // Work backwards until the lists diverge. // The last element common to both lists is the first // common superclass. int aIndex = aSuperList.size() - 1; int bIndex = bSuperList.size() - 1; ClassVertex lastCommonInBackwardsSearch = null; while (aIndex >= 0 && bIndex >= 0) { if (aSuperList.get(aIndex) != bSuperList.get(bIndex)) { break; } lastCommonInBackwardsSearch = aSuperList.get(aIndex); aIndex bIndex } if (lastCommonInBackwardsSearch == null) { throw new IllegalStateException(); } firstCommonSupertype = ObjectTypeFactory.getInstance(lastCommonInBackwardsSearch.getClassDescriptor().toDottedClassName()); // Remember the answer firstCommonSupertypeQueryCache.put(a, b, firstCommonSupertype); } return firstCommonSupertype; } /** * Get list of all superclasses of class represented by given class vertex, * in order, including the class itself (which is trivially its own superclass * as far as "first common superclass" queries are concerned.) * * @param vertex a ClassVertex * @return list of all superclass vertices in order */ private ArrayList<ClassVertex> getAllSuperclassVertices(ClassVertex vertex) throws ClassNotFoundException { ArrayList<ClassVertex> result = new ArrayList<ClassVertex>(); ClassVertex cur = vertex; while (cur != null) { if (!cur.isResolved()) { BCELUtil.throwClassNotFoundException(cur.getClassDescriptor()); } result.add(cur); cur = cur.getDirectSuperclass(); } return result; } /** * Get known subtypes of given class. * * @param classDescriptor ClassDescriptor naming a class * @return Set of ClassDescriptors which are the known subtypes of the class * @throws ClassNotFoundException */ public Set<ClassDescriptor> getSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { Set<ClassDescriptor> result = subtypeSetMap.get(classDescriptor); if (result == null) { result = computeKnownSubtypes(classDescriptor); subtypeSetMap.put(classDescriptor, result); } return result; } /** * Get Collection of all XClass objects (resolved classes) * seen so far. * * @return Collection of all XClass objects */ public Collection<XClass> getXClassCollection() { return Collections.unmodifiableCollection(xclassSet); } /** * Compute set of known subtypes of class named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @throws ClassNotFoundException */ private Set<ClassDescriptor> computeKnownSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>(); ClassVertex startVertex = resolveClassVertex(classDescriptor); workList.addLast(startVertex); Set<ClassDescriptor> result = new HashSet<ClassDescriptor>(); while (!workList.isEmpty()) { ClassVertex current = workList.removeFirst(); if (result.contains(current.getClassDescriptor())) { // Already added this class continue; } // Add class to the result result.add(current.getClassDescriptor()); // Add all known subtype vertices to the work list Iterator<InheritanceEdge> i = graph.incomingEdgeIterator(current); while (i.hasNext()) { InheritanceEdge edge = i.next(); workList.addLast(edge.getSource()); } } return result; } /** * Look up or compute the SupertypeQueryResults for class * named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @return SupertypeQueryResults for the class named by the ClassDescriptor * @throws ClassNotFoundException */ private SupertypeQueryResults getSupertypeQueryResults(ClassDescriptor classDescriptor) throws ClassNotFoundException { SupertypeQueryResults supertypeQueryResults = supertypeSetMap.get(classDescriptor); if (supertypeQueryResults == null) { supertypeQueryResults = computeSupertypes(classDescriptor); supertypeSetMap.put(classDescriptor, supertypeQueryResults); } return supertypeQueryResults; } /** * Compute supertypes for class named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @return SupertypeQueryResults containing known supertypes of the class * @throws ClassNotFoundException if the class can't be found */ private SupertypeQueryResults computeSupertypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { if (DEBUG_QUERIES) { System.out.println("Computing supertypes for " + classDescriptor.toDottedClassName()); } // Try to fully resolve the class and its superclasses/superinterfaces. ClassVertex typeVertex = resolveClassVertex(classDescriptor); // Create new empty SupertypeQueryResults. SupertypeQueryResults supertypeSet = new SupertypeQueryResults(); // Add all known superclasses/superinterfaces. // The ClassVertexes for all of them should be in the // InheritanceGraph by now. LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>(); workList.addLast(typeVertex); while (!workList.isEmpty()) { ClassVertex vertex = workList.removeFirst(); if (vertex.isResolved()) { if (DEBUG_QUERIES) { System.out.println(" Adding supertype " + vertex.getClassDescriptor().toDottedClassName()); } supertypeSet.addSupertype(vertex.getClassDescriptor()); } else { if (DEBUG_QUERIES) { System.out.println( " Encountered unresolved class " + vertex.getClassDescriptor().toDottedClassName() + " in supertype query"); } supertypeSet.setEncounteredMissingClasses(true); } Iterator<InheritanceEdge> i = graph.outgoingEdgeIterator(vertex); while (i.hasNext()) { InheritanceEdge edge = i.next(); workList.addLast(edge.getTarget()); } } return supertypeSet; } /** * Resolve a class named by given ClassDescriptor and return * its resolved ClassVertex. * * @param classDescriptor a ClassDescriptor * @return resolved ClassVertex representing the class in the InheritanceGraph * @throws ClassNotFoundException if the class named by the ClassDescriptor does not exist */ private ClassVertex resolveClassVertex(ClassDescriptor classDescriptor) throws ClassNotFoundException { ClassVertex typeVertex = classDescriptorToVertexMap.get(classDescriptor); if (typeVertex == null) { // We have never tried to resolve this ClassVertex before. // Try to find the XClass for this class. XClass xclass = AnalysisContext.currentXFactory().getXClass(classDescriptor); if (xclass == null) { // Class we're trying to resolve doesn't exist. // XXX: unfortunately, we don't know if the missing class is a class or interface typeVertex = addClassVertexForMissingClass(classDescriptor, false); } else { // Add the class and all its superclasses/superinterfaces to the inheritance graph. // This will result in a resolved ClassVertex. typeVertex = addClassAndGetClassVertex(xclass); } } if (!typeVertex.isResolved()) { BCELUtil.throwClassNotFoundException(classDescriptor); } assert typeVertex.isResolved(); return typeVertex; } /** * Add supertype edges to the InheritanceGraph * for given ClassVertex. If any direct supertypes * have not been processed, add them to the worklist. * * @param vertex a ClassVertex whose supertype edges need to be added * @param workList work list of ClassVertexes that need to have * their supertype edges added */ private void addSupertypeEdges(ClassVertex vertex, LinkedList<XClass> workList) { XClass xclass = vertex.getXClass(); // Direct superclass addInheritanceEdge(vertex, xclass.getSuperclassDescriptor(), false, workList); // Directly implemented interfaces for (ClassDescriptor ifaceDesc : xclass.getInterfaceDescriptorList()) { addInheritanceEdge(vertex, ifaceDesc, true, workList); } } /** * Add supertype edge to the InheritanceGraph. * * @param vertex source ClassVertex (subtype) * @param superclassDescriptor ClassDescriptor of a direct supertype * @param isInterfaceEdge true if supertype is (as far as we know) an interface * @param workList work list of ClassVertexes that need to have * their supertype edges added (null if no further work will be generated) */ private void addInheritanceEdge( ClassVertex vertex, ClassDescriptor superclassDescriptor, boolean isInterfaceEdge, @CheckForNull LinkedList<XClass> workList) { if (superclassDescriptor == null) { return; } ClassVertex superclassVertex = classDescriptorToVertexMap.get(superclassDescriptor); if (superclassVertex == null) { // Haven't encountered this class previously. XClass superclassXClass = AnalysisContext.currentXFactory().getXClass(superclassDescriptor); if (superclassXClass == null) { // Inheritance graph will be incomplete. // Add a dummy node to inheritance graph and report missing class. superclassVertex = addClassVertexForMissingClass(superclassDescriptor, isInterfaceEdge); } else { // Haven't seen this class before. superclassVertex = ClassVertex.createResolvedClassVertex(superclassDescriptor, superclassXClass); addVertexToGraph(superclassDescriptor, superclassVertex); if (workList != null) { // We'll want to recursively process the superclass. workList.addLast(superclassXClass); } } } assert superclassVertex != null; if (graph.lookupEdge(vertex, superclassVertex) == null) { if (DEBUG) { System.out.println(" Add edge " + vertex.getClassDescriptor().toDottedClassName() + " -> " + superclassDescriptor.toDottedClassName()); } graph.createEdge(vertex, superclassVertex); } } /** * Add a ClassVertex representing a missing class. * * @param missingClassDescriptor ClassDescriptor naming a missing class * @param isInterfaceEdge * @return the ClassVertex representing the missing class */ private ClassVertex addClassVertexForMissingClass(ClassDescriptor missingClassDescriptor, boolean isInterfaceEdge) { ClassVertex missingClassVertex = ClassVertex.createMissingClassVertex(missingClassDescriptor, isInterfaceEdge); missingClassVertex.setFinished(true); addVertexToGraph(missingClassDescriptor, missingClassVertex); AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(missingClassDescriptor); return missingClassVertex; } }
package edu.umd.cs.findbugs.ba.ch; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BasicType; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.DefaultAnnotationForParameters; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.bcel.BCELUtil; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.util.DualKeyHashMap; /** * Class for performing class hierarchy queries. * Does <em>not</em> require JavaClass objects to be in memory. * Instead, uses XClass objects. * * @author David Hovemeyer */ @DefaultAnnotationForParameters(NonNull.class) public class Subtypes2 { public static final boolean ENABLE_SUBTYPES2 = true; //SystemProperties.getBoolean("findbugs.subtypes2"); public static final boolean ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES = true; //SystemProperties.getBoolean("findbugs.subtypes2.superclass"); public static final boolean DEBUG = SystemProperties.getBoolean("findbugs.subtypes2.debug"); public static final boolean DEBUG_QUERIES = SystemProperties.getBoolean("findbugs.subtypes2.debugqueries"); private final InheritanceGraph graph; private final Map<ClassDescriptor, ClassVertex> classDescriptorToVertexMap; private final Map<ClassDescriptor, SupertypeQueryResults> supertypeSetMap; private final Map<ClassDescriptor, Set<ClassDescriptor>> subtypeSetMap; private final Set<XClass> xclassSet; private final DualKeyHashMap<ReferenceType, ReferenceType, ReferenceType> firstCommonSuperclassQueryCache; private final ObjectType SERIALIZABLE; private final ObjectType CLONEABLE; /** * Object to record the results of a supertype search. */ private static class SupertypeQueryResults { private Set<ClassDescriptor> supertypeSet = new HashSet<ClassDescriptor>(); private boolean encounteredMissingClasses = false; public void addSupertype(ClassDescriptor classDescriptor) { supertypeSet.add(classDescriptor); } public void setEncounteredMissingClasses(boolean encounteredMissingClasses) { this.encounteredMissingClasses = encounteredMissingClasses; } public boolean containsType(ClassDescriptor possibleSupertypeClassDescriptor) throws ClassNotFoundException { if (supertypeSet.contains(possibleSupertypeClassDescriptor)) { return true; } else if (!encounteredMissingClasses) { return false; } else { // We don't really know which class was missing. // However, any missing classes will already have been reported. throw new ClassNotFoundException(); } } } /** * Constructor. */ public Subtypes2() { this.graph = new InheritanceGraph(); this.classDescriptorToVertexMap = new HashMap<ClassDescriptor, ClassVertex>(); this.supertypeSetMap = new HashMap<ClassDescriptor, SupertypeQueryResults>();// XXX: use MapCache? this.subtypeSetMap = new HashMap<ClassDescriptor, Set<ClassDescriptor>>();// XXX: use MapCache? this.xclassSet = new HashSet<XClass>(); this.SERIALIZABLE = ObjectTypeFactory.getInstance("java.io.Serializable"); this.CLONEABLE = ObjectTypeFactory.getInstance("java.lang.Cloneable"); this.firstCommonSuperclassQueryCache = new DualKeyHashMap<ReferenceType, ReferenceType, ReferenceType>(); } /** * @return Returns the graph. */ public InheritanceGraph getGraph() { return graph; } /** * Add an application class, and its transitive supertypes, to the inheritance graph. * * @param appXClass application XClass to add to the inheritance graph */ public void addApplicationClass(XClass appXClass) { ClassVertex vertex = addClassAndGetClassVertex(appXClass); vertex.markAsApplicationClass(); } /** * Add a class or interface, and its transitive supertypes, to the inheritance graph. * * @param xclass XClass to add to the inheritance graph */ public void addClass(XClass xclass) { addClassAndGetClassVertex(xclass); } /** * Add an XClass and all of its supertypes to * the InheritanceGraph. * * @param xclass an XClass * @return the ClassVertex representing the class in * the InheritanceGraph */ private ClassVertex addClassAndGetClassVertex(XClass xclass) { if (xclass == null) { throw new IllegalStateException(); } LinkedList<XClass> workList = new LinkedList<XClass>(); workList.add(xclass); while (!workList.isEmpty()) { XClass work = workList.removeFirst(); ClassVertex vertex = classDescriptorToVertexMap.get(work.getClassDescriptor()); if (vertex != null && vertex.isFinished()) { // This class has already been processed. continue; } if (vertex == null) { vertex = ClassVertex.createResolvedClassVertex(work.getClassDescriptor(), work); addVertexToGraph(work.getClassDescriptor(), vertex); } addSupertypeEdges(vertex, workList); vertex.setFinished(true); } return classDescriptorToVertexMap.get(xclass.getClassDescriptor()); } private void addVertexToGraph(ClassDescriptor classDescriptor, ClassVertex vertex) { assert classDescriptorToVertexMap.get(classDescriptor) == null; if (DEBUG) { System.out.println("Adding " + classDescriptor.toDottedClassName() + " to inheritance graph"); } graph.addVertex(vertex); classDescriptorToVertexMap.put(classDescriptor, vertex); if (vertex.isResolved()) { xclassSet.add(vertex.getXClass()); } if (vertex.isInterface()) { // There is no need to add additional worklist nodes because java/lang/Object has no supertypes. addInheritanceEdge(vertex, DescriptorFactory.instance().getClassDescriptor("java/lang/Object"), false, null); } } /** * Determine whether or not a given ReferenceType is a subtype of another. * Throws ClassNotFoundException if the question cannot be answered * definitively due to a missing class. * * @param type a ReferenceType * @param possibleSupertype another Reference type * @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not * @throws ClassNotFoundException if a missing class prevents a definitive answer */ public boolean isSubtype(ReferenceType type, ReferenceType possibleSupertype) throws ClassNotFoundException { // Eliminate some easy cases if (type.equals(possibleSupertype)) { return true; } // others? boolean typeIsObjectType = (type instanceof ObjectType); boolean possibleSupertypeIsObjectType = (possibleSupertype instanceof ObjectType); if (typeIsObjectType && possibleSupertypeIsObjectType) { // Both types are ordinary object (non-array) types. return isSubtype((ObjectType) type, (ObjectType) possibleSupertype); } boolean typeIsArrayType = (type instanceof ArrayType); boolean possibleSupertypeIsArrayType = (possibleSupertype instanceof ArrayType); if (typeIsArrayType) { // Check superclass/interfaces if (possibleSupertype.equals(ObjectType.OBJECT) || possibleSupertype.equals(SERIALIZABLE) || possibleSupertype.equals(CLONEABLE)) { return true; } // We checked all of the possible class/interface supertypes, // so if possibleSupertype is not an array type, // then we can definitively say no if (!possibleSupertypeIsArrayType) { return false; } // Check array/array subtype relationship ArrayType typeAsArrayType = (ArrayType) type; ArrayType possibleSupertypeAsArrayType = (ArrayType) possibleSupertype; // Must have same number of dimensions if (typeAsArrayType.getDimensions() < possibleSupertypeAsArrayType.getDimensions()) { return false; } Type possibleSupertypeBasicType = possibleSupertypeAsArrayType.getBasicType(); if (!(possibleSupertypeBasicType instanceof ObjectType)) { return false; } Type typeBasicType = typeAsArrayType.getBasicType(); // If dimensions differ, see if element types are compatible. if (typeAsArrayType.getDimensions() > possibleSupertypeAsArrayType.getDimensions()) { return isSubtype(new ArrayType(typeBasicType,typeAsArrayType.getDimensions() - possibleSupertypeAsArrayType.getDimensions() ), (ObjectType) possibleSupertypeBasicType); } // type's base type must be a subtype of possibleSupertype's base type. // Note that neither base type can be a non-ObjectType if we are to answer yes. if (!(typeBasicType instanceof ObjectType)) { return false; } return isSubtype((ObjectType) typeBasicType, (ObjectType) possibleSupertypeBasicType); } // OK, we've exhausted the possibilities now return false; } /** * Determine whether or not a given ObjectType is a subtype of another. * Throws ClassNotFoundException if the question cannot be answered * definitively due to a missing class. * * @param type a ReferenceType * @param possibleSupertype another Reference type * @return true if <code>type</code> is a subtype of <code>possibleSupertype</code>, false if not * @throws ClassNotFoundException if a missing class prevents a definitive answer */ public boolean isSubtype(ObjectType type, ObjectType possibleSupertype) throws ClassNotFoundException { if (DEBUG_QUERIES) { System.out.println("isSubtype: check " + type + " subtype of " + possibleSupertype); } if (type.equals(possibleSupertype)) { if (DEBUG_QUERIES) { System.out.println(" ==> yes, types are same"); } return true; } ClassDescriptor typeClassDescriptor = BCELUtil.getClassDescriptor(type); ClassDescriptor possibleSuperclassClassDescriptor = BCELUtil.getClassDescriptor(possibleSupertype); ClassVertex possibleSuperclassClassVertex = resolveClassVertex(possibleSuperclassClassDescriptor); // In principle, we should be able to answer no if the ObjectType objects // are not equal and possibleSupertype is final. // However, internally FindBugs creates special "subtypes" of java.lang.String // These will end up resolving to the same ClassVertex as java.lang.String, // which will Do The Right Thing. /* if (possibleSuperclassClassVertex.isResolved() && possibleSuperclassClassVertex.getXClass().isFinal()) { if (DEBUG_QUERIES) { System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is final"); } return false; } */ // Get the supertype query results SupertypeQueryResults supertypeQueryResults = getSupertypeQueryResults(typeClassDescriptor); if (DEBUG_QUERIES) { System.out.println(" Superclass set: " + supertypeQueryResults.supertypeSet); } boolean isSubtype = supertypeQueryResults.containsType(possibleSuperclassClassDescriptor); if (DEBUG_QUERIES) { if (isSubtype) { System.out.println(" ==> yes, " + possibleSuperclassClassDescriptor + " is in superclass set"); } else { System.out.println(" ==> no, " + possibleSuperclassClassDescriptor + " is not in superclass set"); } } return isSubtype; } /** * Get the first common superclass of the given reference types. * Note that an interface type is never returned unless <code>a</code> and <code>b</code> are the * same type. Otherwise, we try to return as accurate a type as possible. * This method is used as the meet operator in TypeDataflowAnalysis, * and is intended to follow (more or less) the JVM bytecode verifier * semantics. * * <p>This method should be used in preference to the getFirstCommonSuperclass() * method in {@link ReferenceType}.</p> * * @param a a ReferenceType * @param b another ReferenceType * @return the first common superclass of <code>a</code> and <code>b</code> * @throws ClassNotFoundException */ public ReferenceType getFirstCommonSuperclass(ReferenceType a, ReferenceType b) throws ClassNotFoundException { // Easy case: same types if (a.equals(b)) { return a; } ReferenceType answer = checkFirstCommonSuperclassQueryCache(a, b); if (answer == null) { answer = computeFirstCommonSuperclassOfReferenceTypes(a, b); putFirstCommonSuperclassQueryCache(a, b, answer); } return answer; } private ReferenceType computeFirstCommonSuperclassOfReferenceTypes(ReferenceType a, ReferenceType b) throws ClassNotFoundException { boolean aIsArrayType = (a instanceof ArrayType); boolean bIsArrayType = (b instanceof ArrayType); if (aIsArrayType && bIsArrayType) { // Merging array types - kind of a pain. ArrayType aArrType = (ArrayType) a; ArrayType bArrType = (ArrayType) b; if (aArrType.getDimensions() == bArrType.getDimensions()) { return computeFirstCommonSuperclassOfSameDimensionArrays(aArrType, bArrType); } else { return computeFirstCommonSuperclassOfDifferentDimensionArrays(aArrType, bArrType); } } if (aIsArrayType || bIsArrayType) { // One of a and b is an array type, but not both. // Common supertype is Object. return ObjectType.OBJECT; } // Neither a nor b is an array type. // Find first common supertypes of ObjectTypes. return getFirstCommonSuperclass((ObjectType) a, (ObjectType) b); } /** * Get first common supertype of arrays with the same number of dimensions. * * @param aArrType an ArrayType * @param bArrType another ArrayType with the same number of dimensions * @return first common supertype * @throws ClassNotFoundException */ private ReferenceType computeFirstCommonSuperclassOfSameDimensionArrays(ArrayType aArrType, ArrayType bArrType) throws ClassNotFoundException { assert aArrType.getDimensions() == bArrType.getDimensions(); Type aBaseType = aArrType.getBasicType(); Type bBaseType = bArrType.getBasicType(); boolean aBaseIsObjectType = (aBaseType instanceof ObjectType); boolean bBaseIsObjectType = (bBaseType instanceof ObjectType); if (!aBaseIsObjectType || !bBaseIsObjectType) { assert (aBaseType instanceof BasicType) || (bBaseType instanceof BasicType); if (aArrType.getDimensions() > 1) { // E.g.: first common supertype of int[][] and WHATEVER[][] is Object[] return new ArrayType(Type.OBJECT, aArrType.getDimensions() - 1); } else { assert aArrType.getDimensions() == 1; // E.g.: first common supertype type of int[] and WHATEVER[] is Object return Type.OBJECT; } } else { assert (aBaseType instanceof ObjectType); assert (bBaseType instanceof ObjectType); // Base types are both ObjectTypes, and number of dimensions is same. // We just need to find the first common supertype of base types // and return a new ArrayType using that base type. ObjectType firstCommonBaseType = getFirstCommonSuperclass((ObjectType) aBaseType, (ObjectType) bBaseType); return new ArrayType(firstCommonBaseType, aArrType.getDimensions()); } } /** * Get the first common superclass of * arrays with different numbers of dimensions. * * @param aArrType an ArrayType * @param bArrType another ArrayType * @return ReferenceType representing first common superclass */ private ReferenceType computeFirstCommonSuperclassOfDifferentDimensionArrays(ArrayType aArrType, ArrayType bArrType) { assert aArrType.getDimensions() != bArrType.getDimensions(); boolean aBaseTypeIsPrimitive = (aArrType.getBasicType() instanceof BasicType); boolean bBaseTypeIsPrimitive = (bArrType.getBasicType() instanceof BasicType); if (aBaseTypeIsPrimitive || bBaseTypeIsPrimitive) { int minDimensions, maxDimensions; if (aArrType.getDimensions() < bArrType.getDimensions()) { minDimensions = aArrType.getDimensions(); maxDimensions = bArrType.getDimensions(); } else { minDimensions = bArrType.getDimensions(); maxDimensions = aArrType.getDimensions(); } if (minDimensions == 1) { // One of the types was something like int[]. // The only possible common supertype is Object. return Type.OBJECT; } else { // Weird case: e.g., // - first common supertype of int[][] and char[][][] is Object[] // because f.c.s. of int[] and char[][] is Object // - first common supertype of int[][][] and char[][][][][] is Object[][] // because f.c.s. of int[] and char[][][] is Object return new ArrayType(Type.OBJECT, maxDimensions - minDimensions); } } else { // Both a and b have base types which are ObjectTypes. // Since the arrays have different numbers of dimensions, the // f.c.s. will have Object as its base type. // E.g., f.c.s. of Cat[] and Dog[][] is Object[] return new ArrayType(Type.OBJECT, Math.min(aArrType.getDimensions(), bArrType.getDimensions())); } } /** * Get the first common superclass of the given object types. * Note that an interface type is never returned unless <code>a</code> and <code>b</code> are the * same type. Otherwise, we try to return as accurate a type as possible. * This method is used as the meet operator in TypeDataflowAnalysis, * and is intended to follow (more or less) the JVM bytecode verifier * semantics. * * <p>This method should be used in preference to the getFirstCommonSuperclass() * method in {@link ReferenceType}.</p> * * @param a an ObjectType * @param b another ObjectType * @return the first common superclass of <code>a</code> and <code>b</code> * @throws ClassNotFoundException */ public ObjectType getFirstCommonSuperclass(ObjectType a, ObjectType b) throws ClassNotFoundException { // Easy case if (a.equals(b)) { return a; } ObjectType firstCommonSupertype = (ObjectType) checkFirstCommonSuperclassQueryCache(a, b); if (firstCommonSupertype == null) { firstCommonSupertype = computeFirstCommonSuperclassOfObjectTypes(a, b); firstCommonSuperclassQueryCache.put(a, b, firstCommonSupertype); } return firstCommonSupertype; } private ObjectType computeFirstCommonSuperclassOfObjectTypes(ObjectType a, ObjectType b) throws ClassNotFoundException { ObjectType firstCommonSupertype; ClassDescriptor aDesc = BCELUtil.getClassDescriptor(a); ClassDescriptor bDesc = BCELUtil.getClassDescriptor(b); ClassVertex aVertex = resolveClassVertex(aDesc); ClassVertex bVertex = resolveClassVertex(bDesc); ArrayList<ClassVertex> aSuperList = getAllSuperclassVertices(aVertex); ArrayList<ClassVertex> bSuperList = getAllSuperclassVertices(bVertex); // Work backwards until the lists diverge. // The last element common to both lists is the first // common superclass. int aIndex = aSuperList.size() - 1; int bIndex = bSuperList.size() - 1; ClassVertex lastCommonInBackwardsSearch = null; while (aIndex >= 0 && bIndex >= 0) { if (aSuperList.get(aIndex) != bSuperList.get(bIndex)) { break; } lastCommonInBackwardsSearch = aSuperList.get(aIndex); aIndex bIndex } if (lastCommonInBackwardsSearch == null) { return ObjectType.OBJECT; } firstCommonSupertype = ObjectTypeFactory.getInstance(lastCommonInBackwardsSearch.getClassDescriptor().toDottedClassName()); return firstCommonSupertype; } private void putFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b, ReferenceType answer) { if (a.getSignature().compareTo(b.getSignature()) > 0) { ReferenceType tmp = a; a = b; b = tmp; } firstCommonSuperclassQueryCache.put(a, b, answer); } private ReferenceType checkFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b) { if (a.getSignature().compareTo(b.getSignature()) > 0) { ReferenceType tmp = a; a = b; b = tmp; } return firstCommonSuperclassQueryCache.get(a, b); } /** * Get list of all superclasses of class represented by given class vertex, * in order, including the class itself (which is trivially its own superclass * as far as "first common superclass" queries are concerned.) * * @param vertex a ClassVertex * @return list of all superclass vertices in order */ private ArrayList<ClassVertex> getAllSuperclassVertices(ClassVertex vertex) throws ClassNotFoundException { ArrayList<ClassVertex> result = new ArrayList<ClassVertex>(); ClassVertex cur = vertex; while (cur != null) { if (!cur.isResolved()) { BCELUtil.throwClassNotFoundException(cur.getClassDescriptor()); } result.add(cur); cur = cur.getDirectSuperclass(); } return result; } /** * Get known subtypes of given class. * * @param classDescriptor ClassDescriptor naming a class * @return Set of ClassDescriptors which are the known subtypes of the class * @throws ClassNotFoundException */ public Set<ClassDescriptor> getSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { Set<ClassDescriptor> result = subtypeSetMap.get(classDescriptor); if (result == null) { result = computeKnownSubtypes(classDescriptor); subtypeSetMap.put(classDescriptor, result); } return result; } /** * Get Collection of all XClass objects (resolved classes) * seen so far. * * @return Collection of all XClass objects */ public Collection<XClass> getXClassCollection() { return Collections.unmodifiableCollection(xclassSet); } /** * An in-progress traversal of one path from a class or interface * to java.lang.Object. */ private static class SupertypeTraversalPath { ClassVertex next; Set<ClassDescriptor> seen; public SupertypeTraversalPath(ClassVertex next) { this.next = next; this.seen = new HashSet<ClassDescriptor>(); } public ClassVertex getNext() { return next; } public boolean hasBeenSeen(ClassDescriptor classDescriptor) { return seen.contains(classDescriptor); } public void markSeen(ClassDescriptor classDescriptor) { seen.add(classDescriptor); } public void setNext(ClassVertex next) { assert !hasBeenSeen(next.getClassDescriptor()); this.next = next; } public SupertypeTraversalPath fork(ClassVertex next) { SupertypeTraversalPath dup = new SupertypeTraversalPath(null); dup.seen.addAll(this.seen); dup.setNext(next); return dup; } } /** * Starting at the class or interface named by the given ClassDescriptor, * traverse the inheritance graph, exploring all paths from * the class or interface to java.lang.Object. * * @param start ClassDescriptor naming the class where the traversal should start * @param visitor an InheritanceGraphVisitor * @throws ClassNotFoundException */ public void traverseSupertypes(ClassDescriptor start, InheritanceGraphVisitor visitor) throws ClassNotFoundException { LinkedList<SupertypeTraversalPath> workList = new LinkedList<SupertypeTraversalPath>(); ClassVertex startVertex = resolveClassVertex(start); workList.addLast(new SupertypeTraversalPath(startVertex)); while (!workList.isEmpty()) { SupertypeTraversalPath cur = workList.removeFirst(); ClassVertex vertex = cur.getNext(); assert !cur.hasBeenSeen(vertex.getClassDescriptor()); cur.markSeen(vertex.getClassDescriptor()); if (!visitor.visitClass(vertex.getClassDescriptor(), vertex.getXClass())) { // Visitor doesn't want to continue on this path continue; } if (!vertex.isResolved()) { // Unknown class - so, we don't know its immediate supertypes continue; } // Advance to direct superclass if (traverseEdge(vertex, vertex.getXClass().getSuperclassDescriptor(), false, visitor)) { addToWorkList(workList, cur, vertex.getXClass().getSuperclassDescriptor()); } // Advance to directly-implemented interfaces for (ClassDescriptor ifaceDesc : vertex.getXClass().getInterfaceDescriptorList()) { if (traverseEdge(vertex, ifaceDesc, true, visitor)) { addToWorkList(workList, cur, ifaceDesc); } } } } private void addToWorkList( LinkedList<SupertypeTraversalPath> workList, SupertypeTraversalPath curPath, ClassDescriptor supertypeDescriptor) { ClassVertex vertex = classDescriptorToVertexMap.get(supertypeDescriptor); // The vertex should already have been added to the graph assert vertex != null; if (curPath.hasBeenSeen(vertex.getClassDescriptor())) { // This can only happen when the inheritance graph has a cycle return; } SupertypeTraversalPath newPath = curPath.fork(vertex); workList.addLast(newPath); } private boolean traverseEdge( ClassVertex vertex, @CheckForNull ClassDescriptor supertypeDescriptor, boolean isInterfaceEdge, InheritanceGraphVisitor visitor) { if (supertypeDescriptor == null) { // We reached java.lang.Object return false; } ClassVertex supertypeVertex = classDescriptorToVertexMap.get(supertypeDescriptor); if (supertypeVertex == null) { try { supertypeVertex = resolveClassVertex(supertypeDescriptor); } catch (ClassNotFoundException e) { supertypeVertex = addClassVertexForMissingClass(supertypeDescriptor, isInterfaceEdge); } } assert supertypeVertex != null; return visitor.visitEdge(vertex.getClassDescriptor(), vertex.getXClass(), supertypeDescriptor, supertypeVertex.getXClass()); } /** * Compute set of known subtypes of class named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @throws ClassNotFoundException */ private Set<ClassDescriptor> computeKnownSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>(); ClassVertex startVertex = resolveClassVertex(classDescriptor); workList.addLast(startVertex); Set<ClassDescriptor> result = new HashSet<ClassDescriptor>(); while (!workList.isEmpty()) { ClassVertex current = workList.removeFirst(); if (result.contains(current.getClassDescriptor())) { // Already added this class continue; } // Add class to the result result.add(current.getClassDescriptor()); // Add all known subtype vertices to the work list Iterator<InheritanceEdge> i = graph.incomingEdgeIterator(current); while (i.hasNext()) { InheritanceEdge edge = i.next(); workList.addLast(edge.getSource()); } } return result; } /** * Look up or compute the SupertypeQueryResults for class * named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @return SupertypeQueryResults for the class named by the ClassDescriptor * @throws ClassNotFoundException */ private SupertypeQueryResults getSupertypeQueryResults(ClassDescriptor classDescriptor) throws ClassNotFoundException { SupertypeQueryResults supertypeQueryResults = supertypeSetMap.get(classDescriptor); if (supertypeQueryResults == null) { supertypeQueryResults = computeSupertypes(classDescriptor); supertypeSetMap.put(classDescriptor, supertypeQueryResults); } return supertypeQueryResults; } /** * Compute supertypes for class named by given ClassDescriptor. * * @param classDescriptor a ClassDescriptor * @return SupertypeQueryResults containing known supertypes of the class * @throws ClassNotFoundException if the class can't be found */ private SupertypeQueryResults computeSupertypes(ClassDescriptor classDescriptor) throws ClassNotFoundException { if (DEBUG_QUERIES) { System.out.println("Computing supertypes for " + classDescriptor.toDottedClassName()); } // Try to fully resolve the class and its superclasses/superinterfaces. ClassVertex typeVertex = resolveClassVertex(classDescriptor); // Create new empty SupertypeQueryResults. SupertypeQueryResults supertypeSet = new SupertypeQueryResults(); // Add all known superclasses/superinterfaces. // The ClassVertexes for all of them should be in the // InheritanceGraph by now. LinkedList<ClassVertex> workList = new LinkedList<ClassVertex>(); workList.addLast(typeVertex); while (!workList.isEmpty()) { ClassVertex vertex = workList.removeFirst(); if (vertex.isResolved()) { if (DEBUG_QUERIES) { System.out.println(" Adding supertype " + vertex.getClassDescriptor().toDottedClassName()); } supertypeSet.addSupertype(vertex.getClassDescriptor()); } else { if (DEBUG_QUERIES) { System.out.println( " Encountered unresolved class " + vertex.getClassDescriptor().toDottedClassName() + " in supertype query"); } supertypeSet.setEncounteredMissingClasses(true); } Iterator<InheritanceEdge> i = graph.outgoingEdgeIterator(vertex); while (i.hasNext()) { InheritanceEdge edge = i.next(); workList.addLast(edge.getTarget()); } } return supertypeSet; } /** * Resolve a class named by given ClassDescriptor and return * its resolved ClassVertex. * * @param classDescriptor a ClassDescriptor * @return resolved ClassVertex representing the class in the InheritanceGraph * @throws ClassNotFoundException if the class named by the ClassDescriptor does not exist */ private ClassVertex resolveClassVertex(ClassDescriptor classDescriptor) throws ClassNotFoundException { ClassVertex typeVertex = classDescriptorToVertexMap.get(classDescriptor); if (typeVertex == null) { // We have never tried to resolve this ClassVertex before. // Try to find the XClass for this class. XClass xclass = AnalysisContext.currentXFactory().getXClass(classDescriptor); if (xclass == null) { // Class we're trying to resolve doesn't exist. // XXX: unfortunately, we don't know if the missing class is a class or interface typeVertex = addClassVertexForMissingClass(classDescriptor, false); } else { // Add the class and all its superclasses/superinterfaces to the inheritance graph. // This will result in a resolved ClassVertex. typeVertex = addClassAndGetClassVertex(xclass); } } if (!typeVertex.isResolved()) { BCELUtil.throwClassNotFoundException(classDescriptor); } assert typeVertex.isResolved(); return typeVertex; } /** * Add supertype edges to the InheritanceGraph * for given ClassVertex. If any direct supertypes * have not been processed, add them to the worklist. * * @param vertex a ClassVertex whose supertype edges need to be added * @param workList work list of ClassVertexes that need to have * their supertype edges added */ private void addSupertypeEdges(ClassVertex vertex, LinkedList<XClass> workList) { XClass xclass = vertex.getXClass(); // Direct superclass addInheritanceEdge(vertex, xclass.getSuperclassDescriptor(), false, workList); // Directly implemented interfaces for (ClassDescriptor ifaceDesc : xclass.getInterfaceDescriptorList()) { addInheritanceEdge(vertex, ifaceDesc, true, workList); } } /** * Add supertype edge to the InheritanceGraph. * * @param vertex source ClassVertex (subtype) * @param superclassDescriptor ClassDescriptor of a direct supertype * @param isInterfaceEdge true if supertype is (as far as we know) an interface * @param workList work list of ClassVertexes that need to have * their supertype edges added (null if no further work will be generated) */ private void addInheritanceEdge( ClassVertex vertex, ClassDescriptor superclassDescriptor, boolean isInterfaceEdge, @CheckForNull LinkedList<XClass> workList) { if (superclassDescriptor == null) { return; } ClassVertex superclassVertex = classDescriptorToVertexMap.get(superclassDescriptor); if (superclassVertex == null) { // Haven't encountered this class previously. XClass superclassXClass = AnalysisContext.currentXFactory().getXClass(superclassDescriptor); if (superclassXClass == null) { // Inheritance graph will be incomplete. // Add a dummy node to inheritance graph and report missing class. superclassVertex = addClassVertexForMissingClass(superclassDescriptor, isInterfaceEdge); } else { // Haven't seen this class before. superclassVertex = ClassVertex.createResolvedClassVertex(superclassDescriptor, superclassXClass); addVertexToGraph(superclassDescriptor, superclassVertex); if (workList != null) { // We'll want to recursively process the superclass. workList.addLast(superclassXClass); } } } assert superclassVertex != null; if (graph.lookupEdge(vertex, superclassVertex) == null) { if (DEBUG) { System.out.println(" Add edge " + vertex.getClassDescriptor().toDottedClassName() + " -> " + superclassDescriptor.toDottedClassName()); } graph.createEdge(vertex, superclassVertex); } } /** * Add a ClassVertex representing a missing class. * * @param missingClassDescriptor ClassDescriptor naming a missing class * @param isInterfaceEdge * @return the ClassVertex representing the missing class */ private ClassVertex addClassVertexForMissingClass(ClassDescriptor missingClassDescriptor, boolean isInterfaceEdge) { ClassVertex missingClassVertex = ClassVertex.createMissingClassVertex(missingClassDescriptor, isInterfaceEdge); missingClassVertex.setFinished(true); addVertexToGraph(missingClassDescriptor, missingClassVertex); AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(missingClassDescriptor); return missingClassVertex; } }
package edu.umd.cs.findbugs.gui2; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import javax.annotation.Nonnull; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JToolTip; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ProgressMonitor; import javax.swing.ProgressMonitorInputStream; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.text.JTextComponent; import javax.swing.text.TextAction; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugAnnotationWithSourceLines; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.FindBugs; import edu.umd.cs.findbugs.FindBugsDisplayFeatures; import edu.umd.cs.findbugs.I18N; import edu.umd.cs.findbugs.IGuiCallback; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.Project; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ProjectPackagePrefixes.PrefixFilter; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.SourceFinder; import edu.umd.cs.findbugs.cloud.Cloud; import edu.umd.cs.findbugs.cloud.CloudListener; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.filter.LastVersionMatcher; import edu.umd.cs.findbugs.filter.Matcher; import edu.umd.cs.findbugs.gui.ConsoleLogger; import edu.umd.cs.findbugs.gui.LogSync; import edu.umd.cs.findbugs.gui.Logger; import edu.umd.cs.findbugs.gui2.BugTreeModel.TreeModification; import edu.umd.cs.findbugs.sourceViewer.NavigableTextPane; import edu.umd.cs.findbugs.util.LaunchBrowser; import edu.umd.cs.findbugs.util.Multiset; @SuppressWarnings("serial") /* * This is where it all happens... seriously... all of it... * All the menus are set up, all the listeners, all the frames, dockable window functionality * There is no one style used, no one naming convention, its all just kinda here. This is another one of those * classes where no one knows quite why it works. */ /** * The MainFrame is just that, the main application window where just about everything happens. */ public class MainFrame extends FBFrame implements LogSync, IGuiCallback { static JButton newButton(String key, String name) { JButton b = new JButton(); edu.umd.cs.findbugs.L10N.localiseButton(b, key, name, false); return b; } static JMenuItem newJMenuItem(String key, String string, int vkF) { JMenuItem m = new JMenuItem(); edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, false); m.setMnemonic(vkF); return m; } static JMenuItem newJMenuItem(String key, String string) { JMenuItem m = new JMenuItem(); edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true); return m; } static JMenu newJMenu(String key, String string) { JMenu m = new JMenu(); edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true); return m; } JTree tree; private BasicTreeUI treeUI; boolean userInputEnabled; static boolean isMacLookAndFeel() { return UIManager.getLookAndFeel().getClass().getName().startsWith("apple"); } static final String DEFAULT_SOURCE_CODE_MSG = edu.umd.cs.findbugs.L10N.getLocalString("msg.nosource_txt", "No available source"); static final int COMMENTS_TAB_STRUT_SIZE = 5; static final int COMMENTS_MARGIN = 5; static final int SEARCH_TEXT_FIELD_SIZE = 32; static final String TITLE_START_TXT = "FindBugs: "; private JTextField sourceSearchTextField = new JTextField(SEARCH_TEXT_FIELD_SIZE); private JButton findButton = newButton("button.find", "First"); private JButton findNextButton = newButton("button.findNext", "Next"); private JButton findPreviousButton = newButton("button.findPrev", "Previous"); public static final boolean DEBUG = SystemProperties.getBoolean("gui2.debug"); static final boolean MAC_OS_X = SystemProperties.getProperty("os.name").toLowerCase().startsWith("mac os x"); final static String WINDOW_MODIFIED = "windowModified"; NavigableTextPane sourceCodeTextPane = new NavigableTextPane(); private JScrollPane sourceCodeScrollPane; final CommentsArea comments; private SorterTableColumnModel sorter; private JTableHeader tableheader; private JLabel statusBarLabel = new JLabel(); private JPanel summaryTopPanel; private final HTMLEditorKit htmlEditorKit = new HTMLEditorKit(); private final JEditorPane summaryHtmlArea = new JEditorPane(); private JScrollPane summaryHtmlScrollPane = new JScrollPane(summaryHtmlArea); final private FindBugsLayoutManagerFactory findBugsLayoutManagerFactory; final private FindBugsLayoutManager guiLayout; /* To change this value must use setProjectChanged(boolean b). * This is because saveProjectItemMenu is dependent on it for when * saveProjectMenuItem should be enabled. */ boolean projectChanged = false; final private JMenuItem reconfigMenuItem = newJMenuItem("menu.reconfig", "Reconfigure...", KeyEvent.VK_F); private JMenuItem redoAnalysis; BugLeafNode currentSelectedBugLeaf; BugAspects currentSelectedBugAspects; private JPopupMenu bugPopupMenu; private JPopupMenu branchPopupMenu; private static MainFrame instance; private RecentMenu recentMenuCache; private JMenu recentMenu; private JMenuItem preferencesMenuItem; private Project curProject = new Project(); private JScrollPane treeScrollPane; private JPanel treePanel; SourceFinder sourceFinder; private Object lock = new Object(); private boolean newProject = false; final ProjectPackagePrefixes projectPackagePrefixes = new ProjectPackagePrefixes(); final CountDownLatch mainFrameInitialized = new CountDownLatch(1); private Class<?> osxAdapter; private Method osxPrefsEnableMethod; private Logger logger = new ConsoleLogger(this); SourceCodeDisplay displayer = new SourceCodeDisplay(this); private SaveType saveType = SaveType.NOT_KNOWN; FBFileChooser saveOpenFileChooser; FBFileChooser filterOpenFileChooser; @CheckForNull private File saveFile = null; enum SaveReturn {SAVE_SUCCESSFUL, SAVE_IO_EXCEPTION, SAVE_ERROR}; JMenuItem saveMenuItem = newJMenuItem("menu.save_item", "Save", KeyEvent.VK_S); public static void makeInstance(FindBugsLayoutManagerFactory factory) { if (instance != null) throw new IllegalStateException(); instance=new MainFrame(factory); instance.initializeGUI(); } public static MainFrame getInstance() { if (instance==null) throw new IllegalStateException(); return instance; } public static boolean isAvailable() { return instance != null; } private void initializeGUI() { SwingUtilities.invokeLater(new InitializeGUI()); } private MainFrame(FindBugsLayoutManagerFactory factory) { this.findBugsLayoutManagerFactory = factory; this.guiLayout = factory.getInstance(this); this.comments = new CommentsArea(this); FindBugsDisplayFeatures.setAbridgedMessages(true); } /** * Show About */ void about() { AboutDialog dialog = new AboutDialog(this, logger, true); dialog.setSize(600, 554); dialog.setLocationRelativeTo(this); dialog.setVisible(true); } /** * Show Preferences */ void preferences() { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); PreferencesFrame.getInstance().setLocationRelativeTo(MainFrame.this); PreferencesFrame.getInstance().setVisible(true); } /** * enable/disable preferences menu */ void enablePreferences(boolean b) { preferencesMenuItem.setEnabled(b); if (MAC_OS_X) { if (osxPrefsEnableMethod != null) { Object args[] = {Boolean.valueOf(b)}; try { osxPrefsEnableMethod.invoke(osxAdapter, args); } catch (Exception e) { System.err.println("Exception while enabling Preferences menu: " + e); } } } } /** * This method is called when the application is closing. This is either by * the exit menuItem or by clicking on the window's system menu. */ void callOnClose(){ comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); if(projectChanged && !SystemProperties.getBoolean("findbugs.skipSaveChangesWarning")){ int value = JOptionPane.showConfirmDialog(MainFrame.this, getActionWithoutSavingMsg("closing"), edu.umd.cs.findbugs.L10N.getLocalString("msg.confirm_save_txt", "Do you want to save?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(value == JOptionPane.CANCEL_OPTION || value == JOptionPane.CLOSED_OPTION) return ; else if(value == JOptionPane.YES_OPTION){ if(saveFile == null){ if(!saveAs()) return; } else save(); } } GUISaveState.getInstance().setPreviousComments(comments.prevCommentsList); guiLayout.saveState(); GUISaveState.getInstance().setFrameBounds( getBounds() ); GUISaveState.getInstance().save(); if (this.bugCollection != null) { Cloud cloud = this.bugCollection.getCloud(); if (cloud != null) cloud.shutdown(); } System.exit(0); } /** * @return */ private String getActionWithoutSavingMsg(String action) { String msg = edu.umd.cs.findbugs.L10N.getLocalString("msg.you_are_"+action+"_without_saving_txt", null); if (msg != null) return msg; return edu.umd.cs.findbugs.L10N.getLocalString("msg.you_are_"+action+"_txt", "You are "+action) + " " + edu.umd.cs.findbugs.L10N.getLocalString("msg.without_saving_txt", "without saving. Do you want to save?"); } /* * A lot of if(false) here is for switching from special cases based on localSaveType * to depending on the SaveType.forFile(f) method. Can delete when sure works. */ JMenuItem createRecentItem(final File f, final SaveType localSaveType) { if (DEBUG) System.out.println("createRecentItem("+f+", "+localSaveType +")"); String name = f.getName(); final JMenuItem item=new JMenuItem(name); item.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); if (!f.exists()) { JOptionPane.showMessageDialog(null,edu.umd.cs.findbugs.L10N.getLocalString("msg.proj_not_found", "This project can no longer be found")); GUISaveState.getInstance().fileNotFound(f); return; } GUISaveState.getInstance().fileReused(f);//Move to front in GUISaveState, so it will be last thing to be removed from the list MainFrame.this.recentMenuCache.addRecentFile(f); if (!f.exists()) throw new IllegalStateException ("User used a recent projects menu item that didn't exist."); //Moved this outside of the thread, and above the line saveFile=f.getParentFile() //Since if this save goes on in the thread below, there is no way to stop the save from //overwriting the files we are about to load. if (curProject != null && projectChanged) { int response = JOptionPane.showConfirmDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?") ,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) { if(saveFile != null) save(); else saveAs(); } else if (response == JOptionPane.CANCEL_OPTION) return; //IF no, do nothing. } SaveType st = SaveType.forFile(f); boolean result = true; switch(st){ case PROJECT: openProject(f); break; case XML_ANALYSIS: result = openAnalysis(f, st); break; case FBP_FILE: result = openFBPFile(f); break; case FBA_FILE: result = openFBAFile(f); break; default: error("Wrong file type in recent menu item."); } if(!result){ JOptionPane.showMessageDialog(MainFrame.getInstance(), "There was an error in opening the file", "Recent Menu Opening Error", JOptionPane.WARNING_MESSAGE); } } finally { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); setSaveType(localSaveType); } } }); item.setFont(item.getFont().deriveFont(Driver.getFontSize())); return item; } BugCollection bugCollection; CloudListener userAnnotationListener = null; @SwingThread void setProjectWithNoBugCollection(Project project) { setProjectAndBugCollection(project, null); } @SwingThread void setBugCollection(BugCollection bugCollection) { setProjectAndBugCollection(bugCollection.getProject(), bugCollection); } @SwingThread private void setProjectAndBugCollection(Project project, @CheckForNull BugCollection bugCollection) { Filter suppressionMatcher = project.getSuppressionFilter(); if (suppressionMatcher != null) { suppressionMatcher.softAdd(LastVersionMatcher.DEAD_BUG_MATCHER); } if (this.bugCollection != null && userAnnotationListener != null) { Cloud plugin = this.bugCollection.getCloud(); if (plugin != null) { plugin.removeListener(userAnnotationListener); plugin.shutdown(); } } // setRebuilding(false); if (bugCollection == null) { showTreeCard(); } else { setProject(project); this.bugCollection = bugCollection; bugCollection.setRequestDatabaseCloud(true); displayer.clearCache(); BugTreeModel model = (BugTreeModel) getTree().getModel(); setSourceFinder(new SourceFinder(project)); BugSet bs = new BugSet(bugCollection); model.getOffListenerList(); model.changeSet(bs); if (bs.size() == 0 && bs.sizeUnfiltered() > 0) { warnUserOfFilters(); } updateStatusBar(); } PreferencesFrame.getInstance().updateFilterPanel(); setProjectChanged(false); reconfigMenuItem.setEnabled(true); comments.configureForCurrentCloud(); setViewMenu(); newProject(); clearSourcePane(); clearSummaryTab(); /* This is here due to a threading issue. It can only be called after * curProject has been changed. Since this method is called by both open methods * it is put here.*/ changeTitle(); if (bugCollection != null) { Cloud plugin = bugCollection.getCloud(); if (plugin != null) { userAnnotationListener = new CloudListener() { public void issueUpdate(BugInstance bug) { if (currentSelectedBugLeaf != null && currentSelectedBugLeaf.getBug() == bug) comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf); } public void statusUpdated() { SwingUtilities.invokeLater(updateStatusBarRunner); } }; plugin.addListener(userAnnotationListener); } } } void resetViewCache() { ((BugTreeModel) getTree().getModel()).clearViewCache(); } final Runnable updateStatusBarRunner = new Runnable() { public void run() { updateStatusBar(); }}; void updateProjectAndBugCollection(Project project, BugCollection bugCollection, BugTreeModel previousModel) { setRebuilding(false); if (bugCollection != null) { displayer.clearCache(); BugSet bs = new BugSet(bugCollection); //Dont clear data, the data's correct, just get the tree off the listener lists. BugTreeModel model = (BugTreeModel) tree.getModel(); model.getOffListenerList(); model.changeSet(bs); //curProject=BugLoader.getLoadedProject(); setProjectChanged(true); } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } /** * Changes the title based on curProject and saveFile. * */ public void changeTitle(){ String name = getProject().getProjectName(); if(name == null && saveFile != null) name = saveFile.getAbsolutePath(); if(name == null) name = Project.UNNAMED_PROJECT; MainFrame.this.setTitle(TITLE_START_TXT + name); } /** * Creates popup menu for bugs on tree. * @return */ private JPopupMenu createBugPopupMenu() { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem filterMenuItem = newJMenuItem("menu.filterBugsLikeThis", "Filter bugs like this"); filterMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); new NewFilterFromBug(currentSelectedBugLeaf.getBug()); setProjectChanged(true); MainFrame.getInstance().getTree().setSelectionRow(0);//Selects the top of the Jtree so the CommentsArea syncs up. } }); popupMenu.add(filterMenuItem); JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation"); int i = 0; int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9}; for(String key : I18N.instance().getUserDesignationKeys(true)) { String name = I18N.instance().getUserDesignation(key); comments.addDesignationItem(changeDesignationMenu, name, keyEvents[i++]); } popupMenu.add(changeDesignationMenu); return popupMenu; } boolean shouldDisplayIssueIgnoringPackagePrefixes(BugInstance b) { Project project = getProject(); Filter suppressionFilter = project.getSuppressionFilter(); if (null == bugCollection || suppressionFilter.match(b)) return false; return viewFilter.showIgnoringPackagePrefixes(b); } boolean shouldDisplayIssue(BugInstance b) { Project project = getProject(); Filter suppressionFilter = project.getSuppressionFilter(); if (null == bugCollection || suppressionFilter.match(b)) return false; return viewFilter.show(b); } /** * Creates the branch pop up menu that ask if the user wants * to hide all the bugs in that branch. * @return */ private JPopupMenu createBranchPopUpMenu(){ JPopupMenu popupMenu = new JPopupMenu(); JMenuItem filterMenuItem = newJMenuItem("menu.filterTheseBugs", "Filter these bugs"); filterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { //TODO This code does a smarter version of filtering that is only possible for branches, and does so correctly //However, it is still somewhat of a hack, because if we ever add more tree listeners than simply the bugtreemodel, //They will not be called by this code. Using FilterActivity to notify all listeners will however destroy any //benefit of using the smarter deletion method. saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); int startCount; TreePath path=MainFrame.getInstance().getTree().getSelectionPath(); TreePath deletePath=path; startCount=((BugAspects)(path.getLastPathComponent())).getCount(); int count=((BugAspects)(path.getParentPath().getLastPathComponent())).getCount(); while(count==startCount) { deletePath=deletePath.getParentPath(); if (deletePath.getParentPath()==null)//We are at the top of the tree, don't let this be removed, rebuild tree from root. { Matcher m = currentSelectedBugAspects.getMatcher(); Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter(); suppressionFilter.addChild(m); PreferencesFrame.getInstance().updateFilterPanel(); FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null); return; } count=((BugAspects)(deletePath.getParentPath().getLastPathComponent())).getCount(); } /* deletePath should now be a path to the highest ancestor branch with the same number of elements as the branch to be deleted in other words, the branch that we actually have to remove in order to correctly remove the selected branch. */ BugTreeModel model=MainFrame.getInstance().getBugTreeModel(); TreeModelEvent event=new TreeModelEvent(this,deletePath.getParentPath(), new int[]{model.getIndexOfChild(deletePath.getParentPath().getLastPathComponent(),deletePath.getLastPathComponent())}, new Object[]{deletePath.getLastPathComponent()}); Matcher m = currentSelectedBugAspects.getMatcher(); Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter(); suppressionFilter.addChild(m); PreferencesFrame.getInstance().updateFilterPanel(); model.sendEvent(event, TreeModification.REMOVE); // FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null); setProjectChanged(true); MainFrame.getInstance().getTree().setSelectionRow(0);//Selects the top of the Jtree so the CommentsArea syncs up. } }); popupMenu.add(filterMenuItem); JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation"); int i = 0; int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9}; for(String key : I18N.instance().getUserDesignationKeys(true)) { String name = I18N.instance().getUserDesignation(key); addDesignationItem(changeDesignationMenu, name, keyEvents[i++]); } popupMenu.add(changeDesignationMenu); return popupMenu; } /** * Creates the MainFrame's menu bar. * @return the menu bar for the MainFrame */ protected JMenuBar createMainMenuBar() { JMenuBar menuBar = new JMenuBar(); //Create JMenus for menuBar. JMenu fileMenu = newJMenu("menu.file_menu", "File"); fileMenu.setMnemonic(KeyEvent.VK_F); JMenu editMenu = newJMenu("menu.edit_menu", "Edit"); editMenu.setMnemonic(KeyEvent.VK_E); //Edit fileMenu JMenu object. JMenuItem openMenuItem = newJMenuItem("menu.open_item", "Open...", KeyEvent.VK_O); recentMenu = newJMenu("menu.recent", "Recent"); recentMenuCache=new RecentMenu(recentMenu); JMenuItem saveAsMenuItem = newJMenuItem("menu.saveas_item", "Save As...", KeyEvent.VK_A); JMenuItem importFilter = newJMenuItem("menu.importFilter_item", "Import filter..."); JMenuItem exportFilter = newJMenuItem("menu.exportFilter_item", "Export filter..."); JMenuItem exitMenuItem = null; if (!MAC_OS_X) { exitMenuItem = newJMenuItem("menu.exit", "Exit", KeyEvent.VK_X); exitMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ callOnClose(); } }); } JMenu windowMenu = guiLayout.createWindowMenu(); JMenuItem newProjectMenuItem = null; if (!FindBugs.noAnalysis) { newProjectMenuItem = newJMenuItem("menu.new_item", "New Project", KeyEvent.VK_N); attachAcceleratorKey(newProjectMenuItem, KeyEvent.VK_N); newProjectMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { newProjectMenu(); } }); } reconfigMenuItem.setEnabled(false); attachAcceleratorKey(reconfigMenuItem, KeyEvent.VK_F); reconfigMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); new NewProjectWizard(curProject); } }); JMenuItem mergeMenuItem = newJMenuItem("menu.mergeAnalysis", "Merge Analysis..."); mergeMenuItem.setEnabled(true); mergeMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ mergeAnalysis(); } }); if (!FindBugs.noAnalysis) { redoAnalysis = newJMenuItem("menu.rerunAnalysis", "Redo Analysis", KeyEvent.VK_R); redoAnalysis.setEnabled(false); attachAcceleratorKey(redoAnalysis, KeyEvent.VK_R); redoAnalysis.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ redoAnalysis(); } }); } openMenuItem.setEnabled(true); attachAcceleratorKey(openMenuItem, KeyEvent.VK_O); openMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ open(); } }); saveAsMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { saveAs(); } }); exportFilter.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { exportFilter(); } }); importFilter.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { importFilter(); } }); saveMenuItem.setEnabled(false); attachAcceleratorKey(saveMenuItem, KeyEvent.VK_S); saveMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt) { save(); } }); if (!FindBugs.noAnalysis) fileMenu.add(newProjectMenuItem); fileMenu.add(reconfigMenuItem); fileMenu.addSeparator(); fileMenu.add(openMenuItem); fileMenu.add(recentMenu); fileMenu.addSeparator(); fileMenu.add(importFilter); fileMenu.add(exportFilter); fileMenu.addSeparator(); fileMenu.add(saveAsMenuItem); fileMenu.add(saveMenuItem); if (!FindBugs.noAnalysis) { fileMenu.addSeparator(); fileMenu.add(redoAnalysis); } // fileMenu.add(mergeMenuItem); if (exitMenuItem != null) { fileMenu.addSeparator(); fileMenu.add(exitMenuItem); } menuBar.add(fileMenu); //Edit editMenu Menu object. JMenuItem cutMenuItem = new JMenuItem(new CutAction()); JMenuItem copyMenuItem = new JMenuItem(new CopyAction()); JMenuItem pasteMenuItem = new JMenuItem(new PasteAction()); preferencesMenuItem = newJMenuItem("menu.preferences_menu", "Filters/Suppressions..."); JMenuItem sortMenuItem = newJMenuItem("menu.sortConfiguration", "Sort Configuration..."); JMenuItem goToLineMenuItem = newJMenuItem("menu.gotoLine", "Go to line..."); attachAcceleratorKey(cutMenuItem, KeyEvent.VK_X); attachAcceleratorKey(copyMenuItem, KeyEvent.VK_C); attachAcceleratorKey(pasteMenuItem, KeyEvent.VK_V); preferencesMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ preferences(); } }); sortMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); SorterDialog.getInstance().setLocationRelativeTo(MainFrame.this); SorterDialog.getInstance().setVisible(true); } }); attachAcceleratorKey(goToLineMenuItem, KeyEvent.VK_L); goToLineMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ guiLayout.makeSourceVisible(); try{ int num = Integer.parseInt(JOptionPane.showInputDialog(MainFrame.this, "", edu.umd.cs.findbugs.L10N.getLocalString("dlg.go_to_line_lbl", "Go To Line") + ":", JOptionPane.QUESTION_MESSAGE)); displayer.showLine(num); } catch(NumberFormatException e){} }}); editMenu.add(cutMenuItem); editMenu.add(copyMenuItem); editMenu.add(pasteMenuItem); editMenu.addSeparator(); editMenu.add(goToLineMenuItem); editMenu.addSeparator(); //editMenu.add(selectAllMenuItem); // editMenu.addSeparator(); if (!MAC_OS_X) { // Preferences goes in Findbugs menu and is handled by OSXAdapter editMenu.add(preferencesMenuItem); } editMenu.add(sortMenuItem); menuBar.add(editMenu); if (windowMenu != null) menuBar.add(windowMenu); viewMenu = newJMenu("menu.view", "View"); setViewMenu(); menuBar.add(viewMenu); final ActionMap map = tree.getActionMap(); JMenu navMenu = newJMenu("menu.navigation", "Navigation"); addNavItem(map, navMenu, "menu.expand", "Expand", "expand", KeyEvent.VK_RIGHT ); addNavItem(map, navMenu, "menu.collapse", "Collapse", "collapse", KeyEvent.VK_LEFT); addNavItem(map, navMenu, "menu.up", "Up", "selectPrevious", KeyEvent.VK_UP ); addNavItem(map, navMenu, "menu.down", "Down", "selectNext", KeyEvent.VK_DOWN); menuBar.add(navMenu); JMenu designationMenu = newJMenu("menu.designation", "Designation"); int i = 0; int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9}; for(String key : I18N.instance().getUserDesignationKeys(true)) { String name = I18N.instance().getUserDesignation(key); addDesignationItem(designationMenu, name, keyEvents[i++]); } menuBar.add(designationMenu); if (!MAC_OS_X) { // On Mac, 'About' appears under Findbugs menu, so no need for it here JMenu helpMenu = newJMenu("menu.help_menu", "Help"); JMenuItem aboutItem = newJMenuItem("menu.about_item", "About FindBugs"); helpMenu.add(aboutItem); aboutItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { about(); } }); menuBar.add(helpMenu); } return menuBar; } static class ProjectSelector { public ProjectSelector(String projectName, String filter, int count) { this.projectName = projectName; this.filter = filter; this.count = count; } final String projectName; final String filter; final int count; @Override public String toString() { return String.format("%s -- [%d issues]", projectName, count); } } public void selectPackagePrefixByProject() { TreeSet<String> projects = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); Multiset<String> count = new Multiset<String>(); int total = 0; for (BugInstance b : bugCollection.getCollection()) if (shouldDisplayIssueIgnoringPackagePrefixes(b)){ TreeSet<String> projectsForThisBug = projectPackagePrefixes.getProjects(b.getPrimaryClass().getClassName()); projects.addAll(projectsForThisBug); count.addAll(projectsForThisBug); total++; } if (projects.size() == 0) { JOptionPane.showMessageDialog(this, "No issues in current view"); return; } ArrayList<ProjectSelector> selectors = new ArrayList<ProjectSelector>(projects.size() + 1); ProjectSelector everything = new ProjectSelector("all projects", "", total); selectors.add(everything); for (String projectName : projects) { ProjectPackagePrefixes.PrefixFilter filter = projectPackagePrefixes.getFilter(projectName); selectors.add(new ProjectSelector(projectName, filter.toString(), count.getCount(projectName))); } ProjectSelector choice = (ProjectSelector) JOptionPane.showInputDialog(null, "Choose a project to set appropriate package prefix(es)", "Select package prefixes by package", JOptionPane.QUESTION_MESSAGE, null, selectors.toArray(), everything); if (choice == null) return; textFieldForPackagesToDisplay.setText(choice.filter); viewFilter.setPackagesToDisplay(choice.filter); resetViewCache(); } JMenu viewMenu ; public void setViewMenu() { Cloud cloud = this.bugCollection == null ? null : this.bugCollection.getCloud(); viewMenu.removeAll(); if (cloud != null && cloud.supportsCloudSummaries()) { JMenuItem cloudReport = new JMenuItem("Cloud summary"); cloudReport.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayCloudReport(); } }); viewMenu.add(cloudReport); } if (projectPackagePrefixes.size() > 0 && this.bugCollection != null) { JMenuItem selectPackagePrefixMenu = new JMenuItem("Select class search strings by project..."); selectPackagePrefixMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectPackagePrefixByProject(); } }); viewMenu.add(selectPackagePrefixMenu); } if (viewMenu.getItemCount() > 0) viewMenu.addSeparator(); ButtonGroup rankButtonGroup = new ButtonGroup(); for(final ViewFilter.RankFilter r : ViewFilter.RankFilter.values()) { JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); rankButtonGroup.add(rbMenuItem); if (r == ViewFilter.RankFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { viewFilter.setRank(r); resetViewCache(); }}); viewMenu.add(rbMenuItem); } viewMenu.addSeparator(); if (cloud != null && cloud.getMode() == Cloud.Mode.COMMUNAL) { ButtonGroup overallClassificationButtonGroup = new ButtonGroup(); for (final ViewFilter.OverallClassificationFilter r : ViewFilter.OverallClassificationFilter.values()) { if (cloud != null && !r.supported(cloud)) continue; JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); overallClassificationButtonGroup.add(rbMenuItem); if (r == ViewFilter.OverallClassificationFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { viewFilter.setClassification(r); resetViewCache(); } }); viewMenu.add(rbMenuItem); } viewMenu.addSeparator(); } ButtonGroup evalButtonGroup = new ButtonGroup(); for(final ViewFilter.CloudFilter r : ViewFilter.CloudFilter.values()) { if (cloud != null && !r.supported(cloud)) continue; JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); evalButtonGroup.add(rbMenuItem); if (r == ViewFilter.CloudFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { viewFilter.setEvaluation(r); resetViewCache(); }}); viewMenu.add(rbMenuItem); } viewMenu.addSeparator(); ButtonGroup ageButtonGroup = new ButtonGroup(); for(final ViewFilter.FirstSeenFilter r : ViewFilter.FirstSeenFilter.values()) { JRadioButtonMenuItem rbMenuItem = new JRadioButtonMenuItem(r.toString()); ageButtonGroup.add(rbMenuItem); if (r == ViewFilter.FirstSeenFilter.ALL) rbMenuItem.setSelected(true); rbMenuItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { viewFilter.setFirstSeen(r); resetViewCache(); }}); viewMenu.add(rbMenuItem); } } public void resetCommentsInputPane() { guiLayout.resetCommentsInputPane(); } ViewFilter viewFilter = new ViewFilter(this); /** * @param map * @param navMenu */ private void addNavItem(final ActionMap map, JMenu navMenu, String menuNameKey, String menuNameDefault, String actionName, int keyEvent) { JMenuItem toggleItem = newJMenuItem(menuNameKey, menuNameDefault); toggleItem.addActionListener(treeActionAdapter(map, actionName)); attachAcceleratorKey(toggleItem, keyEvent); navMenu.add(toggleItem); } ActionListener treeActionAdapter(ActionMap map, String actionName) { final Action selectPrevious = map.get(actionName); return new ActionListener() { public void actionPerformed(ActionEvent e) { e.setSource(tree); selectPrevious.actionPerformed(e); }}; } static void attachAcceleratorKey(JMenuItem item, int keystroke) { attachAcceleratorKey(item, keystroke, 0); } static void attachAcceleratorKey(JMenuItem item, int keystroke, int additionalMask) { // As far as I know, Mac is the only platform on which it is normal // practice to use accelerator masks such as Shift and Alt, so // if we're not running on Mac, just ignore them if (!MAC_OS_X && additionalMask != 0) { return; } item.setAccelerator(KeyStroke.getKeyStroke(keystroke, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | additionalMask)); } @SwingThread void expandTree() { expandTree(Integer.MAX_VALUE); } @SwingThread void expandTree(int max) { Debug.printf("expandTree(%d)\n", max); JTree jTree = getTree(); int i = 0; while (true) { int rows = jTree.getRowCount(); if (i >= rows || rows >= max) break; jTree.expandRow(i++); } } @SwingThread boolean leavesShown() { JTree jTree = getTree(); int rows = jTree.getRowCount(); for(int i = 0; i < rows; i++) { TreePath treePath = jTree.getPathForRow(i); Object lastPathComponent = treePath.getLastPathComponent(); if (lastPathComponent instanceof BugLeafNode) return true; } return false; } @SwingThread void expandToFirstLeaf(int max) { Debug.println("expand to first leaf"); if (leavesShown()) return; JTree jTree = getTree(); int i = 0; while (true) { int rows = jTree.getRowCount(); if (i >= rows || rows >= max) break; TreePath treePath = jTree.getPathForRow(i); Object lastPathComponent = treePath.getLastPathComponent(); if (lastPathComponent instanceof BugLeafNode) return; jTree.expandRow(i++); } } void newProject(){ clearSourcePane(); if (curProject == null) redoAnalysis.setEnabled(false); else redoAnalysis.setEnabled(!curProject.getFileList().isEmpty()); if(newProject){ setProjectChanged(true); // setTitle(TITLE_START_TXT + Project.UNNAMED_PROJECT); saveFile = null; saveMenuItem.setEnabled(false); reconfigMenuItem.setEnabled(true); newProject=false; } } /** * This method is for when the user wants to open a file. */ private void importFilter() { filterOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.importFilter_ttl", "Import and merge filter...")); boolean retry = true; File f = null; while (retry) { retry = false; int value = filterOpenFileChooser.showOpenDialog(MainFrame.this); if (value != JFileChooser.APPROVE_OPTION) return; f = filterOpenFileChooser.getSelectedFile(); if (!f.exists()) { JOptionPane.showMessageDialog(filterOpenFileChooser, "No such file", "Invalid File", JOptionPane.WARNING_MESSAGE); retry = true; continue; } Filter filter; try { filter = Filter.parseFilter(f.getPath()); } catch (IOException e) { JOptionPane.showMessageDialog(filterOpenFileChooser, "Could not load filter."); retry = true; continue; } projectChanged = true; if (getProject().getSuppressionFilter() == null) { getProject().setSuppressionFilter(filter); } else { for (Matcher m : filter.getChildren()) getProject().getSuppressionFilter().addChild(m); } PreferencesFrame.getInstance().updateFilterPanel(); } } /** * This method is for when the user wants to open a file. */ private void open(){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); if (projectChanged) { int response = JOptionPane.showConfirmDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?") ,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) { if (saveFile!=null) save(); else saveAs(); } else if (response == JOptionPane.CANCEL_OPTION) return; //IF no, do nothing. } boolean loading = true; SaveType fileType = SaveType.NOT_KNOWN; tryAgain: while (loading) { int value=saveOpenFileChooser.showOpenDialog(MainFrame.this); if(value!=JFileChooser.APPROVE_OPTION) return; loading = false; fileType = convertFilterToType(saveOpenFileChooser.getFileFilter()); final File f = saveOpenFileChooser.getSelectedFile(); if(!fileType.isValid(f)){ JOptionPane.showMessageDialog(saveOpenFileChooser, "That file is not compatible with the choosen file type", "Invalid File", JOptionPane.WARNING_MESSAGE); loading = true; continue; } switch (fileType) { case PROJECT: File xmlFile = OriginalGUI2ProjectFile.fileContainingXMLData(f); if (!xmlFile.exists()) { JOptionPane.showMessageDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_xml_data_lbl", "This directory does not contain saved bug XML data, please choose a different directory.")); loading=true; continue tryAgain; } openProject(f); break; case XML_ANALYSIS: if(!f.getName().endsWith(".xml")){ JOptionPane.showMessageDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.not_xml_data_lbl", "This is not a saved bug XML data file.")); loading=true; continue tryAgain; } if(!openAnalysis(f, fileType)){ //TODO: Deal if something happens when loading analysis JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis."); loading=true; continue tryAgain; } break; case FBP_FILE: if(!openFBPFile(f)){ //TODO: Deal if something happens when loading analysis JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis."); loading=true; continue tryAgain; } break; case FBA_FILE: if(!openFBAFile(f)){ //TODO: Deal if something happens when loading analysis JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis."); loading=true; continue tryAgain; } break; } } } /** * Method called to open FBA file. * @param f * @return */ private boolean openFBAFile(File f) { return openAnalysis(f, SaveType.FBA_FILE); } /** * Method called to open FBP file. * @param f * @return */ private boolean openFBPFile(File f) { if (!f.exists() || !f.canRead()) { return false; } prepareForFileLoad(f, SaveType.FBP_FILE); loadProjectFromFile(f); return true; } private boolean exportFilter() { if (getProject().getSuppressionFilter() == null) { JOptionPane.showMessageDialog(MainFrame.this,edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_filter", "There is no filter")); return false; } filterOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.exportFilter_ttl", "Export filter...")); boolean retry = true; boolean alreadyExists = true; File f = null; while(retry){ retry = false; int value=filterOpenFileChooser.showSaveDialog(MainFrame.this); if (value!=JFileChooser.APPROVE_OPTION) return false; f = filterOpenFileChooser.getSelectedFile(); alreadyExists = f.exists(); if(alreadyExists){ int response = JOptionPane.showConfirmDialog(filterOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.file_exists_lbl", "This file already exists.\nReplace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if(response == JOptionPane.OK_OPTION) retry = false; if(response == JOptionPane.CANCEL_OPTION){ retry = true; continue; } } Filter suppressionFilter = getProject().getSuppressionFilter(); try { suppressionFilter.writeEnabledMatchersAsXML(new FileOutputStream(f)); } catch (IOException e) { JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.saving_error_lbl", "An error occurred in saving.")); return false; } } return true; } private boolean saveAs(){ saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); saveOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.saveas_ttl", "Save as...")); if (curProject==null) { JOptionPane.showMessageDialog(MainFrame.this,edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_proj_save_lbl", "There is no project to save")); return false; } boolean retry = true; SaveType fileType = SaveType.NOT_KNOWN; boolean alreadyExists = true; File f = null; while(retry){ retry = false; int value=saveOpenFileChooser.showSaveDialog(MainFrame.this); if (value!=JFileChooser.APPROVE_OPTION) return false; fileType = convertFilterToType(saveOpenFileChooser.getFileFilter()); if(fileType == SaveType.NOT_KNOWN){ Debug.println("Error! fileType == SaveType.NOT_KNOWN"); //This should never happen b/c saveOpenFileChooser can only display filters //given it. retry = true; continue; } f = saveOpenFileChooser.getSelectedFile(); f = convertFile(f, fileType); if(!fileType.isValid(f)){ JOptionPane.showMessageDialog(saveOpenFileChooser, "That file is not compatible with the chosen file type", "Invalid File", JOptionPane.WARNING_MESSAGE); retry = true; continue; } alreadyExists = fileAlreadyExists(f, fileType); if(alreadyExists){ int response = -1; switch(fileType){ case XML_ANALYSIS: response = JOptionPane.showConfirmDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.analysis_exists_lbl", "This analysis already exists.\nReplace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); break; case PROJECT: response = JOptionPane.showConfirmDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.proj_already_exists_lbl", "This project already exists.\nDo you want to replace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); break; case FBP_FILE: response = JOptionPane.showConfirmDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("FB Project File already exists", "This FB project file already exists.\nDo you want to replace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); break; case FBA_FILE: response = JOptionPane.showConfirmDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("FB Analysis File already exists", "This FB analysis file already exists.\nDo you want to replace it?"), edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); break; } if(response == JOptionPane.OK_OPTION) retry = false; if(response == JOptionPane.CANCEL_OPTION){ retry = true; continue; } } SaveReturn successful = SaveReturn.SAVE_ERROR; switch(fileType){ case PROJECT: successful = saveProject(f); break; case XML_ANALYSIS: successful = saveAnalysis(f); break; case FBA_FILE: successful = saveFBAFile(f); break; case FBP_FILE: successful = saveFBPFile(f); break; } if (successful != SaveReturn.SAVE_SUCCESSFUL) { JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.saving_error_lbl", "An error occurred in saving.")); return false; } } // saveProjectMenuItem.setEnabled(false); saveMenuItem.setEnabled(false); setSaveType(fileType); saveFile = f; File xmlFile; if (getSaveType()==SaveType.PROJECT) xmlFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".xml"); else xmlFile=f; addFileToRecent(xmlFile, getSaveType()); return true; } /* * Returns SaveType equivalent depending on what kind of FileFilter passed. */ private SaveType convertFilterToType(FileFilter f){ if (f instanceof FindBugsFileFilter) return ((FindBugsFileFilter)f).getSaveType(); return SaveType.NOT_KNOWN; } /* * Depending on File and SaveType determines if f already exists. Returns false if not * exist, true otherwise. For a project calls * OriginalGUI2ProjectFile.fileContainingXMLData(f).exists */ private boolean fileAlreadyExists(File f, SaveType fileType){ if(fileType == SaveType.PROJECT){ /*File xmlFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".xml"); File fasFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".fas"); return xmlFile.exists() || fasFile.exists();*/ return (OriginalGUI2ProjectFile.fileContainingXMLData(f).exists()); } return f.exists(); } /* * If f is not of type FileType will convert file so it is. */ private File convertFile(File f, SaveType fileType){ //WARNING: This assumes the filefilter for project is working so f can only be a directory. if(fileType == SaveType.PROJECT) return f; //Checks that it has the correct file extension, makes a new file if it doesn't. if(!f.getName().endsWith(fileType.getFileExtension())) f = new File(f.getAbsolutePath() + fileType.getFileExtension()); return f; } private void save(){ File sFile = saveFile; assert sFile != null; saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); SaveReturn result = SaveReturn.SAVE_ERROR; switch(getSaveType()){ case PROJECT: result = saveProject(sFile); break; case XML_ANALYSIS: result = saveAnalysis(sFile); break; case FBA_FILE: result = saveFBAFile(sFile); break; case FBP_FILE: result = saveFBPFile(sFile); break; } if(result != SaveReturn.SAVE_SUCCESSFUL){ JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString( "dlg.saving_error_lbl", "An error occurred in saving.")); } } /** * @param saveFile2 * @return */ private SaveReturn saveFBAFile(File saveFile2) { return saveAnalysis(saveFile2); } /** * @param saveFile2 * @return */ private SaveReturn saveFBPFile(File saveFile2) { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); try { getProject().writeXML(saveFile2); } catch (IOException e) { AnalysisContext.logError("Couldn't save FBP file to " + saveFile2, e); return SaveReturn.SAVE_IO_EXCEPTION; } setProjectChanged(false); return SaveReturn.SAVE_SUCCESSFUL; } static final String TREECARD = "Tree"; static final String WAITCARD = "Wait"; public void showWaitCard() { showCard(WAITCARD, new Cursor(Cursor.WAIT_CURSOR)); } public void showTreeCard() { showCard(TREECARD, new Cursor(Cursor.DEFAULT_CURSOR)); } private void showCard(final String c, final Cursor cursor) { if (SwingUtilities.isEventDispatchThread()) { setCursor(cursor); CardLayout layout = (CardLayout) cardPanel.getLayout(); layout.show(cardPanel, c); } else SwingUtilities.invokeLater(new Runnable() { public void run() { setCursor(cursor); CardLayout layout = (CardLayout) cardPanel.getLayout(); layout.show(cardPanel, c); } }); } JPanel waitPanel, cardPanel; JPanel makeNavigationPanel(String packageSelectorLabel, JComponent packageSelector, JComponent treeHeader, JComponent tree) { JPanel topPanel = new JPanel(); topPanel.setMinimumSize(new Dimension(150,150)); topPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.ipadx = c.ipady = 3; c.insets = new Insets(6,6,6,6); c.gridx = 0; c.gridy = 0; c.fill=GridBagConstraints.NONE; JLabel label = new JLabel(packageSelectorLabel); topPanel.add(label, c); c.gridx = 1; c.fill=GridBagConstraints.HORIZONTAL; c.weightx = 1; topPanel.add(packageSelector, c); c.gridx = 0; c.gridwidth=2; c.gridy++; c.ipadx = c.ipady = 2; c.fill = GridBagConstraints.HORIZONTAL; topPanel.add(treeHeader, c); c.fill = GridBagConstraints.BOTH; c.gridy++; c.weighty = 1; c.ipadx = c.ipady = 0; c.insets = new Insets(0,0,0,0); topPanel.add(tree, c); return topPanel; } /** * * @return */ JPanel bugListPanel() { tableheader = new JTableHeader(); //Listener put here for when user double clicks on sorting //column header SorterDialog appears. tableheader.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { Debug.println("tableheader.getReorderingAllowed() = " + tableheader.getReorderingAllowed()); if (!tableheader.getReorderingAllowed()) return; if (e.getClickCount()==2) SorterDialog.getInstance().setVisible(true); } @Override public void mouseReleased(MouseEvent arg0) { if (!tableheader.getReorderingAllowed()) return; BugTreeModel bt=(BugTreeModel) (MainFrame.this.getTree().getModel()); bt.checkSorter(); } }); sorter = GUISaveState.getInstance().getStarterTable(); tableheader.setColumnModel(sorter); tableheader.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.reorder_message", "Drag to reorder tree folder and sort order")); tree = new JTree(); treeUI = (BasicTreeUI) tree.getUI(); tree.setLargeModel(true); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setCellRenderer(new BugRenderer()); tree.setRowHeight((int)(Driver.getFontSize() + 7)); if (false) { System.out.println("Left indent had been " + treeUI.getLeftChildIndent()); System.out.println("Right indent had been " + treeUI.getRightChildIndent()); treeUI.setLeftChildIndent(30 ); treeUI.setRightChildIndent(30 ); } tree.setModel(new BugTreeModel(tree, sorter, new BugSet(new ArrayList<BugLeafNode>()))); setupTreeListeners(); setProject(new Project()); treeScrollPane = new JScrollPane(tree); treePanel = new JPanel(new BorderLayout()); treePanel.add(treeScrollPane, BorderLayout.CENTER); //New code to fix problem in Windows JTable t = new JTable(new DefaultTableModel(0, sortables().length)); t.setTableHeader(tableheader); if (false) { JScrollPane tableHeaderScrollPane = new JScrollPane(t); //This sets the height of the scrollpane so it is dependent on the fontsize. int num = (int) (Driver.getFontSize()); tableHeaderScrollPane.setPreferredSize(new Dimension(0, 0)); tableHeaderScrollPane.setMaximumSize(new Dimension(200, 5)); } //End of new code. //Changed code. textFieldForPackagesToDisplay = new JTextField(); textFieldForPackagesToDisplay.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { try { viewFilter.setPackagesToDisplay(textFieldForPackagesToDisplay.getText()); resetViewCache(); } catch (IllegalArgumentException err) { JOptionPane.showMessageDialog(MainFrame.this, err.getMessage(), "Bad class search string", JOptionPane.ERROR_MESSAGE); } }}); textFieldForPackagesToDisplay.setToolTipText("Provide a comma separated list of class search strings to restrict the view to classes containing those substrings"); JPanel topPanel = makeNavigationPanel("Class search strings:", textFieldForPackagesToDisplay, tableheader, treePanel); cardPanel = new JPanel(new CardLayout()); waitPanel = new JPanel(); waitPanel.add(new JLabel("Please wait...")); cardPanel.add(topPanel, TREECARD); cardPanel.add(waitPanel, WAITCARD); return cardPanel; } JTextField textFieldForPackagesToDisplay; public void newTree(final JTree newTree, final BugTreeModel newModel) { SwingUtilities.invokeLater(new Runnable() { public void run() { tree = newTree; tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setLargeModel(true); tree.setCellRenderer(new BugRenderer()); showTreeCard(); treePanel.remove(treeScrollPane); treeScrollPane = new JScrollPane(newTree); treePanel.add(treeScrollPane); setFontSizeHelper(Driver.getFontSize(), treeScrollPane); tree.setRowHeight((int)(Driver.getFontSize() + 7)); MainFrame.this.getContentPane().validate(); MainFrame.this.getContentPane().repaint(); setupTreeListeners(); newModel.openPreviouslySelected(((BugTreeModel)(tree.getModel())).getOldSelectedBugs()); MainFrame.this.expandTree(10); MainFrame.this.expandToFirstLeaf(14); MainFrame.this.getSorter().addColumnModelListener(newModel); FilterActivity.addFilterListener(newModel.bugTreeFilterListener); MainFrame.this.setSorting(true); } }); } private void setupTreeListeners() { if (false) tree.addTreeExpansionListener(new TreeExpansionListener(){ public void treeExpanded(TreeExpansionEvent event) { System.out.println("Tree expanded"); TreePath path = event.getPath(); Object lastPathComponent = path.getLastPathComponent(); int children = tree.getModel().getChildCount(lastPathComponent); if (children == 1) { Object o = tree.getModel().getChild(lastPathComponent, 0); if (o instanceof BugAspects) { final TreePath p = path.pathByAddingChild(o); SwingUtilities.invokeLater(new Runnable() { public void run() {try { System.out.println("auto expanding " + p); tree.expandPath(p); } catch (Exception e) { e.printStackTrace(); } }}); } } } public void treeCollapsed(TreeExpansionEvent event) { // do nothing }}); tree.addTreeSelectionListener(new TreeSelectionListener(){ public void valueChanged(TreeSelectionEvent selectionEvent) { TreePath path = selectionEvent.getNewLeadSelectionPath(); if (path != null) { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); Object lastPathComponent = path.getLastPathComponent(); if (lastPathComponent instanceof BugLeafNode) { boolean beforeProjectChanged = projectChanged; currentSelectedBugLeaf = (BugLeafNode)lastPathComponent; currentSelectedBugAspects = null; syncBugInformation(); setProjectChanged(beforeProjectChanged); } else { boolean beforeProjectChanged = projectChanged; updateDesignationDisplay(); currentSelectedBugLeaf = null; currentSelectedBugAspects = (BugAspects)lastPathComponent; syncBugInformation(); setProjectChanged(beforeProjectChanged); } } // Debug.println("Tree selection count:" + tree.getSelectionCount()); if (tree.getSelectionCount() !=1) { Debug.println("Tree selection count not equal to 1, disabling comments tab" + selectionEvent); MainFrame.this.setUserCommentInputEnable(false); } } }); tree.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if(path == null) return; if ((e.getButton() == MouseEvent.BUTTON3) || (e.getButton() == MouseEvent.BUTTON1 && e.isControlDown())){ if (tree.getModel().isLeaf(path.getLastPathComponent())){ tree.setSelectionPath(path); bugPopupMenu.show(tree, e.getX(), e.getY()); } else{ tree.setSelectionPath(path); if (!(path.getParentPath()==null))//If the path's parent path is null, the root was selected, dont allow them to filter out the root. branchPopupMenu.show(tree, e.getX(), e.getY()); } } } public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) {} public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} }); } void syncBugInformation (){ boolean prevProjectChanged = projectChanged; if (currentSelectedBugLeaf != null) { BugInstance bug = currentSelectedBugLeaf.getBug(); displayer.displaySource(bug, bug.getPrimarySourceLineAnnotation()); updateDesignationDisplay(); comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf); updateSummaryTab(currentSelectedBugLeaf); } else if (currentSelectedBugAspects != null) { updateDesignationDisplay(); comments.updateCommentsFromNonLeafInformation(currentSelectedBugAspects); displayer.displaySource(null, null); clearSummaryTab(); } else { displayer.displaySource(null, null); clearSummaryTab(); } setProjectChanged(prevProjectChanged); } /** * Clears the source code text pane. * */ void clearSourcePane(){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ setSourceTab("Source", null); sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT); } }); } /** * @param b */ private void setUserCommentInputEnable(boolean b) { comments.setUserCommentInputEnable(b); } /** * Creates the status bar of the GUI. * @return */ JPanel statusBar() { JPanel statusBar = new JPanel(); // statusBar.setBackground(Color.WHITE); statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED)); statusBar.setLayout(new BorderLayout()); statusBar.add(statusBarLabel,BorderLayout.WEST); JLabel logoLabel = new JLabel(); ImageIcon logoIcon = new ImageIcon(MainFrame.class.getResource("logo_umd.png")); logoLabel.setIcon(logoIcon); statusBar.add(logoLabel, BorderLayout.EAST); return statusBar; } private String join(String s1, String s2) { if (s1 == null || s1.length() == 0) return s2; if (s2 == null || s2.length() == 0) return s1; return s1 + "; " + s2; } @SwingThread void updateStatusBar() { int countFilteredBugs = BugSet.countFilteredBugs(); String msg = ""; if (countFilteredBugs == 1) { msg = " 1 " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bug_hidden", "bug hidden by filters"); } else if (countFilteredBugs > 1) { msg = " " + countFilteredBugs + " " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bugs_hidden", "bugs hidden by filters"); } if (bugCollection != null) { Cloud plugin = bugCollection.getCloud(); if (plugin != null) { String pluginMsg = plugin.getStatusMsg(); if (pluginMsg != null && pluginMsg.length() > 1) msg = join(msg, pluginMsg); } } if (errorMsg != null && errorMsg.length() > 0) msg = join(msg, errorMsg); if (msg.length() == 0) msg = "http://findbugs.sourceforge.net"; statusBarLabel.setText(msg); } volatile String errorMsg = ""; public void setErrorMessage(String errorMsg) { this.errorMsg = errorMsg; SwingUtilities.invokeLater(new Runnable(){ public void run() { updateStatusBar(); }}); } private void updateSummaryTab(BugLeafNode node) { final BugInstance bug = node.getBug(); final ArrayList<BugAnnotation> primaryAnnotations = new ArrayList<BugAnnotation>(); boolean classIncluded = false; //This ensures the order of the primary annotations of the bug if(bug.getPrimarySourceLineAnnotation() != null) primaryAnnotations.add(bug.getPrimarySourceLineAnnotation()); if(bug.getPrimaryMethod() != null) primaryAnnotations.add(bug.getPrimaryMethod()); if(bug.getPrimaryField() != null) primaryAnnotations.add(bug.getPrimaryField()); /* * This makes the primary class annotation appear only when * the visible field and method primary annotations don't have * the same class. */ if(bug.getPrimaryClass() != null){ FieldAnnotation primeField = bug.getPrimaryField(); MethodAnnotation primeMethod = bug.getPrimaryMethod(); ClassAnnotation primeClass = bug.getPrimaryClass(); String fieldClass = ""; String methodClass = ""; if(primeField != null) fieldClass = primeField.getClassName(); if(primeMethod != null) methodClass = primeMethod.getClassName(); if((primaryAnnotations.size() < 2) || (!(primeClass.getClassName().equals(fieldClass) || primeClass.getClassName().equals(methodClass)))){ primaryAnnotations.add(primeClass); classIncluded = true; } } final boolean classIncluded2 = classIncluded; SwingUtilities.invokeLater(new Runnable(){ public void run(){ summaryTopPanel.removeAll(); summaryTopPanel.add(bugSummaryComponent(bug.getMessageWithoutPrefix(), bug)); for(BugAnnotation b : primaryAnnotations) summaryTopPanel.add(bugSummaryComponent(b, bug)); if(!classIncluded2 && bug.getPrimaryClass() != null) primaryAnnotations.add(bug.getPrimaryClass()); for(Iterator<BugAnnotation> i = bug.annotationIterator(); i.hasNext();){ BugAnnotation b = i.next(); boolean cont = true; for(BugAnnotation p : primaryAnnotations) if(p == b) cont = false; if(cont) summaryTopPanel.add(bugSummaryComponent(b, bug)); } summaryHtmlArea.setText(bug.getBugPattern().getDetailHTML()); summaryTopPanel.add(Box.createVerticalGlue()); summaryTopPanel.revalidate(); SwingUtilities.invokeLater(new Runnable(){ public void run(){ summaryHtmlScrollPane.getVerticalScrollBar().setValue(summaryHtmlScrollPane.getVerticalScrollBar().getMinimum()); } }); } }); } private void clearSummaryTab() { summaryHtmlArea.setText(""); summaryTopPanel.removeAll(); summaryTopPanel.revalidate(); } /** * Creates initial summary tab and sets everything up. * @return */ JSplitPane summaryTab() { int fontSize = (int) Driver.getFontSize(); summaryTopPanel = new JPanel(); summaryTopPanel.setLayout(new GridLayout(0,1)); summaryTopPanel.setBorder(BorderFactory.createEmptyBorder(2,4,2,4)); summaryTopPanel.setMinimumSize(new Dimension(fontSize * 50, fontSize*5)); JPanel summaryTopOuter = new JPanel(new BorderLayout()); summaryTopOuter.add(summaryTopPanel, BorderLayout.NORTH); summaryHtmlArea.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.longer_description", "This gives a longer description of the detected bug pattern")); summaryHtmlArea.setContentType("text/html"); summaryHtmlArea.setEditable(false); summaryHtmlArea.addHyperlinkListener(new javax.swing.event.HyperlinkListener() { public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) { AboutDialog.editorPaneHyperlinkUpdate(evt); } }); setStyleSheets(); //JPanel temp = new JPanel(new BorderLayout()); //temp.add(summaryTopPanel, BorderLayout.CENTER); JScrollPane summaryScrollPane = new JScrollPane(summaryTopOuter); summaryScrollPane.getVerticalScrollBar().setUnitIncrement( (int)Driver.getFontSize() ); JSplitPane splitP = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, summaryScrollPane, summaryHtmlScrollPane); splitP.setDividerLocation(GUISaveState.getInstance().getSplitSummary()); splitP.setOneTouchExpandable(true); return splitP; } /** * Creates bug summary component. If obj is a string will create a JLabel * with that string as it's text and return it. If obj is an annotation * will return a JLabel with the annotation's toString(). If that * annotation is a SourceLineAnnotation or has a SourceLineAnnotation * connected to it and the source file is available will attach * a listener to the label. * @param obj * @param bug TODO * @return */ private Component bugSummaryComponent(String str, BugInstance bug){ JLabel label = new JLabel(); label.setFont(label.getFont().deriveFont(Driver.getFontSize())); label.setFont(label.getFont().deriveFont(Font.PLAIN)); label.setForeground(Color.BLACK); label.setText(str); return label; } private Component bugSummaryComponent(BugAnnotation value, BugInstance bug){ JLabel label = new JLabel(); label.setFont(label.getFont().deriveFont(Driver.getFontSize())); label.setFont(label.getFont().deriveFont(Font.PLAIN)); label.setForeground(Color.BLACK); ClassAnnotation primaryClass = bug.getPrimaryClass(); String sourceCodeLabel = edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code."); String summaryLine = edu.umd.cs.findbugs.L10N.getLocalString("summary.line", "Line"); String summaryLines = edu.umd.cs.findbugs.L10N.getLocalString("summary.lines", "Lines"); String clickToGoToText = edu.umd.cs.findbugs.L10N.getLocalString("tooltip.click_to_go_to", "Click to go to"); if (value instanceof SourceLineAnnotation) { final SourceLineAnnotation note = (SourceLineAnnotation) value; if (sourceCodeExist(note)) { String srcStr = ""; int start = note.getStartLine(); int end = note.getEndLine(); if (start < 0 && end < 0) srcStr = sourceCodeLabel; else if (start == end) srcStr = " [" + summaryLine + " " + start + "]"; else if (start < end) srcStr = " [" + summaryLines + " " + start + " - " + end + "]"; label.setToolTipText(clickToGoToText + " " + srcStr); label.addMouseListener(new BugSummaryMouseListener(bug, label, note)); } label.setText(note.toString()); } else if (value instanceof BugAnnotationWithSourceLines) { BugAnnotationWithSourceLines note = (BugAnnotationWithSourceLines) value; final SourceLineAnnotation noteSrc = note.getSourceLines(); String srcStr = ""; if (noteSrc != null && sourceCodeExist(noteSrc)) { int start = noteSrc.getStartLine(); int end = noteSrc.getEndLine(); if (start < 0 && end < 0) srcStr = sourceCodeLabel; else if (start == end) srcStr = " [" + summaryLine + " " + start + "]"; else if (start < end) srcStr = " [" + summaryLines + " " + start + " - " + end + "]"; if (!srcStr.equals("")) { label.setToolTipText(clickToGoToText + " " + srcStr); label.addMouseListener(new BugSummaryMouseListener(bug, label, noteSrc)); } } String noteText; if (note == bug.getPrimaryMethod() || note == bug.getPrimaryField()) noteText = note.toString(); else noteText = note.toString(primaryClass); if (!srcStr.equals(sourceCodeLabel)) label.setText(noteText + srcStr); else label.setText(noteText); } else { label.setText(value.toString(primaryClass)); } return label; } /** * @author pugh */ private final class InitializeGUI implements Runnable { public void run() { setTitle("FindBugs"); try { guiLayout.initialize(); } catch(Exception e) { // If an exception was encountered while initializing, this may // be because of a bug in the particular look-and-feel selected // (as in sourceforge bug 1899648). In an attempt to recover // gracefully, this code reverts to the cross-platform look- // and-feel and attempts again to initialize the layout. if(!UIManager.getLookAndFeel().getName().equals("Metal")) { System.err.println("Exception caught initializing GUI; reverting to CrossPlatformLookAndFeel"); try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch(Exception e2) { System.err.println("Exception while setting CrossPlatformLookAndFeel: " + e2); throw new Error(e2); } guiLayout.initialize(); } else { throw new Error(e); } } bugPopupMenu = createBugPopupMenu(); branchPopupMenu = createBranchPopUpMenu(); comments.loadPrevCommentsList(GUISaveState.getInstance().getPreviousComments().toArray(new String[GUISaveState.getInstance().getPreviousComments().size()])); updateStatusBar(); setBounds(GUISaveState.getInstance().getFrameBounds()); Toolkit.getDefaultToolkit().setDynamicLayout(true); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setJMenuBar(createMainMenuBar()); setVisible(true); //Initializes save and open filechooser. - Kristin saveOpenFileChooser = new FBFileChooser(); saveOpenFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); saveOpenFileChooser.setAcceptAllFileFilterUsed(false); saveOpenFileChooser.addChoosableFileFilter(FindBugsProjectFileFilter.INSTANCE); saveOpenFileChooser.addChoosableFileFilter(FindBugsAnalysisFileFilter.INSTANCE); saveOpenFileChooser.addChoosableFileFilter(FindBugsFBPFileFilter.INSTANCE); saveOpenFileChooser.addChoosableFileFilter(FindBugsFBAFileFilter.INSTANCE); saveOpenFileChooser.setFileFilter(FindBugsAnalysisFileFilter.INSTANCE); filterOpenFileChooser = new FBFileChooser(); filterOpenFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); filterOpenFileChooser.setFileFilter(FindBugsFilterFileFilter.INSTANCE); //Sets the size of the tooltip to match the rest of the GUI. - Kristin JToolTip tempToolTip = tableheader.createToolTip(); UIManager.put( "ToolTip.font", new FontUIResource(tempToolTip.getFont().deriveFont(Driver.getFontSize()))); if (MAC_OS_X) { try { osxAdapter = Class.forName("edu.umd.cs.findbugs.gui2.OSXAdapter"); Class[] defArgs = {MainFrame.class}; Method registerMethod = osxAdapter.getDeclaredMethod("registerMacOSXApplication", defArgs); if (registerMethod != null) { registerMethod.invoke(osxAdapter, MainFrame.this); } defArgs[0] = boolean.class; osxPrefsEnableMethod = osxAdapter.getDeclaredMethod("enablePrefs", defArgs); enablePreferences(true); } catch (NoClassDefFoundError e) { // This will be thrown first if the OSXAdapter is loaded on a system without the EAWT // because OSXAdapter extends ApplicationAdapter in its def System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")"); } catch (ClassNotFoundException e) { // This shouldn't be reached; if there's a problem with the OSXAdapter we should get the // above NoClassDefFoundError first. System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")"); } catch (Exception e) { System.err.println("Exception while loading the OSXAdapter: " + e); e.printStackTrace(); if (DEBUG) { e.printStackTrace(); } } } String loadFromURL = SystemProperties.getOSDependentProperty("findbugs.loadBugsFromURL"); if (loadFromURL != null) { try { loadFromURL = SystemProperties.rewriteURLAccordingToProperties(loadFromURL); URL url = new URL(loadFromURL); BugTreeModel.pleaseWait(edu.umd.cs.findbugs.L10N.getLocalString("msg.loading_bugs_over_network_txt", "Loading bugs over network...")); loadAnalysis(url); } catch (MalformedURLException e1) { JOptionPane.showMessageDialog(MainFrame.this, "Error loading " + loadFromURL); } } addComponentListener(new ComponentAdapter(){ @Override public void componentResized(ComponentEvent e){ comments.resized(); } }); addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent e) { if(comments.hasFocus()) setProjectChanged(true); callOnClose(); } }); Driver.removeSplashScreen(); mainFrameInitialized.countDown(); } } public void waitUntilReady() throws InterruptedException { mainFrameInitialized.await(); } /** * Listens for when cursor is over the label and when it is clicked. * When the cursor is over the label will make the label text blue * and the cursor the hand cursor. When clicked will take the * user to the source code tab and to the lines of code connected * to the SourceLineAnnotation. * @author Kristin Stephens * */ private class BugSummaryMouseListener extends MouseAdapter{ private final BugInstance bugInstance; private final JLabel label; private final SourceLineAnnotation note; BugSummaryMouseListener(@NonNull BugInstance bugInstance, @NonNull JLabel label, @NonNull SourceLineAnnotation note){ this.bugInstance = bugInstance; this.label = label; this.note = note; } @Override public void mouseClicked(MouseEvent e) { displayer.displaySource(bugInstance, note); } @Override public void mouseEntered(MouseEvent e){ label.setForeground(Color.blue); setCursor(new Cursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e){ label.setForeground(Color.black); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } /** * Checks if source code file exists/is available * @param note * @return */ private boolean sourceCodeExist(@Nonnull SourceLineAnnotation note){ try{ sourceFinder.findSourceFile(note); }catch(FileNotFoundException e){ return false; }catch(IOException e){ return false; } return true; } private void setStyleSheets() { StyleSheet styleSheet = new StyleSheet(); styleSheet.addRule("body {font-size: " + Driver.getFontSize() +"pt}"); styleSheet.addRule("H1 {color: red; font-size: 120%; font-weight: bold;}"); styleSheet.addRule("code {font-family: courier; font-size: " + Driver.getFontSize() +"pt}"); styleSheet.addRule(" a:link { color: #0000FF; } "); styleSheet.addRule(" a:visited { color: #800080; } "); styleSheet.addRule(" a:active { color: #FF0000; text-decoration: underline; } "); htmlEditorKit.setStyleSheet(styleSheet); summaryHtmlArea.setEditorKit(htmlEditorKit); } JPanel createCommentsInputPanel() { return comments.createCommentsInputPanel(); } /** * Creates the source code panel, but does not put anything in it. * @param text * @return */ JPanel createSourceCodePanel() { Font sourceFont = new Font("Monospaced", Font.PLAIN, (int)Driver.getFontSize()); sourceCodeTextPane.setFont(sourceFont); sourceCodeTextPane.setEditable(false); sourceCodeTextPane.getCaret().setSelectionVisible(true); sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT); sourceCodeScrollPane = new JScrollPane(sourceCodeTextPane); sourceCodeScrollPane.getVerticalScrollBar().setUnitIncrement(20); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(sourceCodeScrollPane, BorderLayout.CENTER); panel.revalidate(); if (DEBUG) System.out.println("Created source code panel"); return panel; } JPanel createSourceSearchPanel() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JPanel thePanel = new JPanel(); thePanel.setLayout(gridbag); findButton.setToolTipText("Find first occurrence"); findNextButton.setToolTipText("Find next occurrence"); findPreviousButton.setToolTipText("Find previous occurrence"); c.gridx = 0; c.gridy = 0; c.weightx = 1.0; c.insets = new Insets(0, 5, 0, 5); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(sourceSearchTextField, c); thePanel.add(sourceSearchTextField); //add the buttons findButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ searchSource(0); } }); c.gridx = 1; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; gridbag.setConstraints(findButton, c); thePanel.add(findButton); findNextButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ searchSource(1); } }); c.gridx = 2; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; gridbag.setConstraints(findNextButton, c); thePanel.add(findNextButton); findPreviousButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ searchSource(2); } }); c.gridx = 3; c.weightx = 0.0; c.fill = GridBagConstraints.NONE; gridbag.setConstraints(findPreviousButton, c); thePanel.add(findPreviousButton); return thePanel; } void searchSource(int type) { int targetLineNum = -1; String targetString = sourceSearchTextField.getText(); switch(type) { case 0: targetLineNum = displayer.find(targetString); break; case 1: targetLineNum = displayer.findNext(targetString); break; case 2: targetLineNum = displayer.findPrevious(targetString); break; } if(targetLineNum != -1) displayer.foundItem(targetLineNum); } /** * Sets the title of the source tabs for either docking or non-docking * versions. * @param title * @param bug TODO */ void setSourceTab(String title, @CheckForNull BugInstance bug){ JComponent label = guiLayout.getSourceViewComponent(); if (label != null) { URL u = null; if (bug != null) { Cloud plugin = this.bugCollection.getCloud(); if (plugin.supportsSourceLinks()) u = plugin.getSourceLink(bug); } if (u != null) addLink(label, u); else removeLink(label); } guiLayout.setSourceTitle(title); } URL sourceLink; boolean listenerAdded = false; void addLink(JComponent component, URL source) { this.sourceLink = source; component.setEnabled(true); if (!listenerAdded) { listenerAdded = true; component.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { URL u = sourceLink; if (u != null) LaunchBrowser.showDocument(u); } }); } component.setCursor(new Cursor(Cursor.HAND_CURSOR)); Cloud plugin = this.bugCollection.getCloud(); if (plugin != null) component.setToolTipText(plugin.getSourceLinkToolTip(null)); } void removeLink(JComponent component) { this.sourceLink = null; component.setEnabled(false); component.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); component.setToolTipText(""); } /** * Returns the SorterTableColumnModel of the MainFrame. * @return */ SorterTableColumnModel getSorter() { return sorter; } /* * This is overridden for changing the font size */ @Override public void addNotify(){ super.addNotify(); float size = Driver.getFontSize(); getJMenuBar().setFont(getJMenuBar().getFont().deriveFont(size)); for(int i = 0; i < getJMenuBar().getMenuCount(); i++){ for(int j = 0; j < getJMenuBar().getMenu(i).getMenuComponentCount(); j++){ Component temp = getJMenuBar().getMenu(i).getMenuComponent(j); temp.setFont(temp.getFont().deriveFont(size)); } } bugPopupMenu.setFont(bugPopupMenu.getFont().deriveFont(size)); setFontSizeHelper(size, bugPopupMenu.getComponents()); branchPopupMenu.setFont(branchPopupMenu.getFont().deriveFont(size)); setFontSizeHelper(size, branchPopupMenu.getComponents()); } public JTree getTree() { return tree; } public BugTreeModel getBugTreeModel() { return (BugTreeModel)getTree().getModel(); } static class CutAction extends TextAction { public CutAction() { super(edu.umd.cs.findbugs.L10N.getLocalString("txt.cut", "Cut")); } public void actionPerformed( ActionEvent evt ) { JTextComponent text = getTextComponent( evt ); if(text == null) return; text.cut(); } } static class CopyAction extends TextAction { public CopyAction() { super(edu.umd.cs.findbugs.L10N.getLocalString("txt.copy", "Copy")); } public void actionPerformed( ActionEvent evt ) { JTextComponent text = getTextComponent( evt ); if(text == null) return; text.copy(); } } static class PasteAction extends TextAction { public PasteAction() { super(edu.umd.cs.findbugs.L10N.getLocalString("txt.paste", "Paste")); } public void actionPerformed( ActionEvent evt ) { JTextComponent text = getTextComponent( evt ); if(text == null) return; text.paste(); } } /** * @return never null */ public synchronized Project getProject() { if(curProject == null){ curProject = new Project(); } return curProject; } public synchronized void setProject(Project p) { curProject=p; } public SourceFinder getSourceFinder() { return sourceFinder; } public void setSourceFinder(SourceFinder sf) { sourceFinder=sf; } @SwingThread public void setRebuilding(boolean b) { tableheader.setReorderingAllowed(!b); enablePreferences(!b); if (b) { SorterDialog.getInstance().freeze(); showWaitCard(); } else { SorterDialog.getInstance().thaw(); showTreeCard(); } recentMenu.setEnabled(!b); } public void setSorting(boolean b) { tableheader.setReorderingAllowed(b); } private void setSaveMenu() { File s = saveFile; saveMenuItem.setEnabled(projectChanged && s != null && getSaveType() != SaveType.FBP_FILE && s.exists()); } /** * Called when something in the project is changed and the change needs to be saved. * This method should be called instead of using projectChanged = b. */ public void setProjectChanged(boolean b){ if(curProject == null) return; if(projectChanged == b) return; projectChanged = b; setSaveMenu(); // if(projectDirectory != null && projectDirectory.exists()) // saveProjectMenuItem.setEnabled(b); getRootPane().putClientProperty(WINDOW_MODIFIED, Boolean.valueOf(b)); } public boolean getProjectChanged(){ return projectChanged; } /* * DO NOT use the projectDirectory variable to figure out the current project directory in this function * use the passed in value, as that variable may or may not have been set to the passed in value at this point. */ private SaveReturn saveProject(File dir) { if (!dir.mkdir()) { return SaveReturn.SAVE_IO_EXCEPTION; } File f = new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".xml"); File filtersAndSuppressions=new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".fas"); BugSaver.saveBugs(f,bugCollection, getProject()); try { ProjectSettings.getInstance().save(new FileOutputStream(filtersAndSuppressions)); } catch (IOException e) { Debug.println(e); return SaveReturn.SAVE_IO_EXCEPTION; } setProjectChanged(false); return SaveReturn.SAVE_SUCCESSFUL; } /** * @param currentSelectedBugLeaf2 * @param currentSelectedBugAspects2 */ private void saveComments(BugLeafNode theNode, BugAspects theAspects) { comments.saveComments(theNode, theAspects); } void saveComments() { comments.saveComments(); } /** * Returns the color of the source code pane's background. * @return the color of the source code pane's background */ public Color getSourceColor(){ return sourceCodeTextPane.getBackground(); } /** * Show an error dialog. */ public void error(String message) { JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE); } /** * Write a message to the console window. * * @param message the message to write */ public void writeToLog(String message) { if (DEBUG) System.out.println(message); // consoleMessageArea.append(message); // consoleMessageArea.append("\n"); } /** * Save current analysis as file passed in. Return SAVE_SUCCESSFUL if save successful. */ /* * Method doesn't do much. This method is more if need to do other things in the future for * saving analysis. And to keep saving naming convention. */ private SaveReturn saveAnalysis(File f){ BugSaver.saveBugs(f, bugCollection, getProject()); setProjectChanged(false); return SaveReturn.SAVE_SUCCESSFUL; } /** * Opens the analysis. Also clears the source and summary panes. Makes comments enabled false. * Sets the saveType and adds the file to the recent menu. * @param f * @return whether the operation was successful */ public boolean openAnalysis(File f, SaveType saveType){ if (!f.exists() || !f.canRead()) { throw new IllegalArgumentException("Can't read " + f.getPath()); } prepareForFileLoad(f, saveType); loadAnalysis(f); return true; } public void openBugCollection(SortedBugCollection bugs){ prepareForFileLoad(null, null); Project project = bugs.getProject(); project.setGuiCallback(MainFrame.this); BugLoader.addDeadBugMatcher(project); setProjectAndBugCollectionInSwingThread(project, bugs); } private void prepareForFileLoad(File f, SaveType saveType) { setRebuilding(true); //This creates a new filters and suppressions so don't use the previoues one. ProjectSettings.newInstance(); clearSourcePane(); clearSummaryTab(); comments.setUserCommentInputEnable(false); reconfigMenuItem.setEnabled(true); setProjectChanged(false); this.setSaveType(saveType); saveFile = f; addFileToRecent(f, saveType); } private void loadAnalysis(final File file) { Runnable runnable = new Runnable() { public void run() { Project project = new Project(); project.setGuiCallback(MainFrame.this); SortedBugCollection bc; project.setCurrentWorkingDirectory(file.getParentFile()); bc = BugLoader.loadBugs(MainFrame.this, project, file); setProjectAndBugCollectionInSwingThread(project, bc); } }; if (EventQueue.isDispatchThread()) new Thread(runnable, "Analysis loading thread").start(); else runnable.run(); return; } private void loadAnalysis(final URL url) { Runnable runnable = new Runnable() { public void run() { Project project = new Project(); project.setGuiCallback(MainFrame.this); SortedBugCollection bc; bc = BugLoader.loadBugs(MainFrame.this, project, url); setProjectAndBugCollectionInSwingThread(project, bc); } }; if (EventQueue.isDispatchThread()) new Thread(runnable, "Analysis loading thread").start(); else runnable.run(); return; } /** * @param file * @return */ private void loadProjectFromFile(final File f) { Runnable runnable = new Runnable(){ public void run() { final Project project = BugLoader.loadProject(MainFrame.this, f); final BugCollection bc = project == null ? null : BugLoader.doAnalysis(project); updateProjectAndBugCollection(project, bc, null); setProjectAndBugCollectionInSwingThread(project, bc); } }; if (EventQueue.isDispatchThread()) new Thread(runnable).start(); else runnable.run(); return; } /** * Redo the analysis */ void redoAnalysis() { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); showWaitCard(); new Thread() { @Override public void run() { updateDesignationDisplay(); BugCollection bc=BugLoader.redoAnalysisKeepComments(getProject()); updateProjectAndBugCollection(getProject(), bc, null); } }.start(); } private void mergeAnalysis() { saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); showWaitCard(); BugCollection bc=BugLoader.combineBugHistories(); setBugCollection(bc); } /** * This takes a directory and opens it as a project. * @param dir */ private void openProject(final File dir){ File xmlFile= new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".xml"); File fasFile=new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".fas"); if (!fasFile.exists()) { JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString( "dlg.filter_settings_not_found_lbl", "Filter settings not found, using default settings.")); ProjectSettings.newInstance(); } else { try { ProjectSettings.loadInstance(new FileInputStream(fasFile)); } catch (FileNotFoundException e) { //Impossible. if (MainFrame.DEBUG) System.err.println(".fas file not found, using default settings"); ProjectSettings.newInstance(); } } final File extraFinalReferenceToXmlFile=xmlFile; new Thread(new Runnable(){ public void run() { BugTreeModel.pleaseWait(); MainFrame.this.setRebuilding(true); Project project = new Project(); SortedBugCollection bc=BugLoader.loadBugs(MainFrame.this, project, extraFinalReferenceToXmlFile); setProjectAndBugCollection(project, bc); } }).start(); // addFileToRecent(xmlFile, SaveType.PROJECT); addFileToRecent(dir, SaveType.PROJECT); clearSourcePane(); clearSummaryTab(); comments.setUserCommentInputEnable(false); setProjectChanged(false); setSaveType(SaveType.PROJECT); saveFile = dir; changeTitle(); } /** * This checks if the xmlFile is in the GUISaveState. If not adds it. Then adds the file * to the recentMenuCache. * @param xmlFile */ /* * If the file already existed, its already in the preferences, as well as * the recent projects menu items, only add it if they change the name, * otherwise everything we're storing is still accurate since all we're * storing is the location of the file. */ private void addFileToRecent(File xmlFile, SaveType st){ ArrayList<File> xmlFiles=GUISaveState.getInstance().getRecentFiles(); if (!xmlFiles.contains(xmlFile)) { GUISaveState.getInstance().addRecentFile(xmlFile); } MainFrame.this.recentMenuCache.addRecentFile(xmlFile); } private void newProjectMenu() { comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects); new NewProjectWizard(); newProject = true; } void updateDesignationDisplay() { comments.updateDesignationComboBox(); } void addDesignationItem(JMenu menu, final String menuName, int keyEvent) { comments.addDesignationItem(menu, menuName, keyEvent); } void warnUserOfFilters() { JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.everything_is_filtered", "All bugs in this project appear to be filtered out. \nYou may wish to check your filter settings in the preferences menu."), "Warning",JOptionPane.WARNING_MESSAGE); } /** * @param saveType The saveType to set. */ void setSaveType(SaveType saveType) { if (DEBUG && this.saveType != saveType) System.out.println("Changing save type from " + this.saveType + " to " + saveType); this.saveType = saveType; } /** * @return Returns the saveType. */ SaveType getSaveType() { return saveType; } public void showMessageDialog(final String message) { if (SwingUtilities.isEventDispatchThread()) JOptionPane.showMessageDialog(this, message); else SwingUtilities.invokeLater(new Runnable(){ public void run() { JOptionPane.showMessageDialog(MainFrame.this, message); }}); } public int showConfirmDialog(String message, String title, int optionType) { return JOptionPane.showConfirmDialog(this, message, title, optionType); } /** * @param project * @param bc */ private void setProjectAndBugCollectionInSwingThread(final Project project, final BugCollection bc) { SwingUtilities.invokeLater(new Runnable() { public void run() { project.setGuiCallback(MainFrame.this); if (bc == null) setProjectWithNoBugCollection(project); else { assert project == bc.getProject(); setBugCollection(bc); } changeTitle(); }}); } Sortables[] sortables; { ArrayList<Sortables> a = new ArrayList<Sortables>(Sortables.values().length); for(Sortables s : Sortables.values()) if (s.isAvailable(this)) a.add(s); sortables = new Sortables[a.size()]; a.toArray(sortables); } public Sortables[] sortables() { return Sortables.values(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#progessMonitoredInputStream(java.io.File, java.lang.String) */ public InputStream getProgressMonitorInputStream(InputStream in, int length, String msg) { ProgressMonitorInputStream pmin = new ProgressMonitorInputStream(this, msg, in); ProgressMonitor pm = pmin.getProgressMonitor(); if (length > 0) pm.setMaximum(length); return pmin; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#showStatus(java.lang.String) */ public void showStatus(String msg) { guiLayout.setSourceTitle(msg); } public void displayNonmodelMessage(String title, String message) { DisplayNonmodelMessage.displayNonmodelMessage(title, message, this, true); } public void displayCloudReport() { Cloud cloud = this.bugCollection.getCloud(); if (cloud == null) { JOptionPane.showMessageDialog(this, "There is no cloud"); return; } StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); cloud.printCloudSummary(writer, getDisplayedBugs(), viewFilter.getPackagePrefixes()); writer.close(); String report = stringWriter.toString(); DisplayNonmodelMessage.displayNonmodelMessage("Cloud summary", report, this, false); } public Iterable<BugInstance> getDisplayedBugs() { return new Iterable<BugInstance>(){ public Iterator<BugInstance> iterator() { return new ShownBugsIterator(); }}; } class ShownBugsIterator implements Iterator<BugInstance> { Iterator<BugInstance> base = bugCollection.getCollection().iterator(); boolean nextKnown; BugInstance next; /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if (!nextKnown) { nextKnown = true; while (base.hasNext()) { next = base.next(); if (shouldDisplayIssue(next)) return true; } next = null; return false; } return next != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public BugInstance next() { if (!hasNext()) throw new NoSuchElementException(); BugInstance result = next; next = null; nextKnown = false; return result; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#showQuestionDialog(java.lang.String, java.lang.String, java.lang.String) */ public String showQuestionDialog(String message, String title, String defaultValue) { return (String) JOptionPane.showInputDialog(this, message, title, JOptionPane.QUESTION_MESSAGE, null, null, defaultValue); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.IGuiCallback#showDocument(java.net.URL) */ public boolean showDocument(URL u) { return LaunchBrowser.showDocument(u); } }
package step.core.entities; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import step.attachments.FileResolver; import step.core.AbstractContext; import step.core.AbstractStepContext; import step.core.accessors.AbstractIdentifiableObject; import step.core.accessors.CRUDAccessor; import step.core.dynamicbeans.DynamicValue; import step.core.objectenricher.ObjectPredicate; import step.resources.ResourceManager; public class EntityManager { private static Logger logger = LoggerFactory.getLogger(EntityManager.class); public final static String executions = "executions"; public final static String plans = "plans"; public static final String functions = "functions"; public final static String reports = "reports"; public final static String tasks = "tasks"; public final static String users = "users"; public final static String resources = "resources"; public final static String resourceRevisions = "resourceRevisions"; public final static String recursive = "recursive"; private Map<String, Entity<?,?>> entities = new ConcurrentHashMap<String, Entity<?,?>>(); private Map<Class<?>, Entity<?,?>> entitiesByClass = new ConcurrentHashMap<Class<?>, Entity<?,?>>(); private AbstractStepContext context; Map<Class<?>,BeanInfo> beanInfoCache = new ConcurrentHashMap<>(); public EntityManager(AbstractStepContext context) { this.context = context; } public EntityManager register(Entity<?,?> entity) { entities.put(entity.getName(), entity); entitiesByClass.put(entity.getEntityClass(), entity); return this; } public Entity<?,?> getEntityByName(String entityName) { return entities.get(entityName); } /** * Retrieve all existing references from the DB for give entity type * @param entityType type of entities to retrieve * @param objectPredicate to apply to filter entities (i.e. project) * @param recursively flag to export references recursively (i.e by exporting a plan recursively the plan will be scanned to find sub references) * @param refs the map of entity references to be populated during the process */ public void getEntitiesReferences(String entityType, ObjectPredicate objectPredicate, boolean recursively, EntityReferencesMap refs) { Entity<?, ?> entity = getEntityByName(entityType); if (entity == null ) { throw new RuntimeException("Entity of type " + entityType + " is not supported"); } entity.getAccessor().getAll().forEachRemaining(a -> { if ((entity.isByPassObjectPredicate() || objectPredicate.test(a)) && entity.shouldExport(a)) { refs.addElementTo(entityType, a.getId().toHexString()); if (recursively) { getAllEntities(entityType, a.getId().toHexString(), refs); } } }); } /** * get entities recursively by scanning the given entity (aka artefact), the entity is retrieved and deserialized from the db * @param entityName name of the type of entity * @param id the id of the entity * @param references the map of references to be populated */ public void getAllEntities (String entityName, String id, EntityReferencesMap references) { Entity<?, ?> entity = getEntityByName(entityName); if (entity == null) { logger.error("Entities of type '" + entityName + "' are not supported"); throw new RuntimeException("Entities of type '" + entityName + "' are not supported"); } CRUDAccessor<?> accessor = entity.getAccessor(); AbstractIdentifiableObject a = accessor.get(id); if (a == null ) { logger.warn("Referenced entity with id '" + id + "' and type '" + entityName + "' is missing"); references.addReferenceNotFoundWarning("Referenced entity with id '" + id + "' and type '" + entityName + "' is missing"); } else { resolveReferences(a, references); entity.getReferencesHook().forEach(h->h.accept(a,references)); } } /** * scan the given object with introspection to find references. The method is called recursively. * @param object to be introspected * @param references map to be populated */ private void resolveReferences(Object object, EntityReferencesMap references) { if(object!=null) { Class<?> clazz = object.getClass(); BeanInfo beanInfo = beanInfoCache.get(clazz); if(beanInfo==null) { try { beanInfo = Introspector.getBeanInfo(clazz, Object.class); } catch (IntrospectionException e) { references.addReferenceNotFoundWarning("Introspection failed for class " + clazz.getName()); } beanInfoCache.put(clazz, beanInfo); } for(PropertyDescriptor descriptor:beanInfo.getPropertyDescriptors()) { Method method = descriptor.getReadMethod(); if(method!=null) { if(method.isAnnotationPresent(EntityReference.class)) { EntityReference eRef = method.getAnnotation(EntityReference.class); String entityType = eRef.type(); Object value = null; try { value = method.invoke(object); } catch (IllegalAccessException e) { references.addReferenceNotFoundWarning("IllegalAccessException failed for method " + method.getName()); } catch (InvocationTargetException e) { e.printStackTrace(); } if (entityType.equals(recursive)) { //No actual references, but need to process the field recursively if (value instanceof Collection) { Collection<?> c = (Collection<?>) value; c.forEach(o->resolveReferences(o, references)); } else { resolveReferences(value, references); } } else { if (value instanceof Collection) { Collection<?> c = (Collection<?>) value; c.forEach(r->resolveReference(r, references, entityType, r.getClass())); } else { if (value == null) { try { value = getEntityByName(entityType).resolve(object); } catch (Exception e) { references.addReferenceNotFoundWarning("Unable to resolve reference of type " + entityType + " from artefact " + object.getClass().getCanonicalName() + ". Error: " + e.getMessage()); } } resolveReference(value, references, entityType, method.getReturnType()); } } } } } } } /** Resolve a single reference to an actual value * @param value * @param references * @param entityType * @param type */ private void resolveReference(Object value, EntityReferencesMap references, String entityType, Class<?> type) { FileResolver fileResolver = context.getFileResolver(); String refId = null; if (type.equals(DynamicValue.class) && value!=null) { DynamicValue<?> dynamicValue = (DynamicValue<?>) value; if (!dynamicValue.isDynamic()) { Object dValue = dynamicValue.get(); refId = (dValue != null) ? dValue.toString() : null; if (entityType.equals(resources)) { refId = fileResolver.resolveResourceId(refId); } } else { logger.warn("Reference using dynamic expression found and cannot be resolved during export. Expression: " + dynamicValue.getExpression()); } } else if (type.equals(String.class)) { refId = (String) value; } else if (type.equals(ObjectId.class)) { refId = ((ObjectId) value).toHexString(); } if (refId != null && ObjectId.isValid(refId)) { boolean added = references.addElementTo(entityType, refId); //hack for resource revisions (no explicit references for now) if (entityType.equals(resources)) { String revisionId = context.getResourceManager().getResourceRevisionByResourceId(refId).getId().toHexString(); references.addElementTo(EntityManager.resourceRevisions, revisionId); } //avoid circular references issue if (added) { getAllEntities(entityType, refId, references); } } } public Entity<?,?> getEntitiesByClass(Class<?> c) { Entity<?,?> result = entitiesByClass.get(c); while (result == null && !c.equals(Object.class)) { c = c.getSuperclass(); result = entitiesByClass.get(c); } return result; } public void updateReferences(Object object, Map<String, String> references) { Entity<?,?> entity = getEntitiesByClass(object.getClass()); if (entity != null) { entity.getUpdateReferencesHook().forEach(r->r.accept(object, references)); } if(object!=null) { Class<?> clazz = object.getClass(); try { BeanInfo beanInfo = beanInfoCache.get(clazz); if(beanInfo==null) { beanInfo = Introspector.getBeanInfo(clazz, Object.class); beanInfoCache.put(clazz, beanInfo); } for(PropertyDescriptor descriptor:beanInfo.getPropertyDescriptors()) { Method method = descriptor.getReadMethod(); if(method!=null) { if(method.isAnnotationPresent(EntityReference.class)) { EntityReference eRef = method.getAnnotation(EntityReference.class); String entityType = eRef.type(); Object value = method.invoke(object); if (entityType.equals(recursive)) { //No actual references, but need to process the field recursively if (value != null) { if (value instanceof Collection) { Collection<?> c = (Collection<?>) value; c.forEach(o -> updateReferences(o, references)); } else { updateReferences(value, references); } } else { logger.warn("Skipping import of reference with null value"); } } else { Object newValue = getNewValue(value, method.getReturnType(), references, entityType); if (newValue != null) { Method writeMethod = descriptor.getWriteMethod(); if(writeMethod!=null) { descriptor.getWriteMethod().invoke(object, newValue); } else { //throw new RuntimeException("Unable to clone object "+o.toString()+". No setter found for "+descriptor); } } } } } } } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | InstantiationException e) { throw new RuntimeException("Import failed, unabled to updates references by reflections",e); } } } private Object getNewValue_(Object value, Class<?> returnType, Map<String, String> references, String entityType) { FileResolver fileResolver = context.getFileResolver(); Object newValue = null; String origRefId = null; String newRefId = null; //Get original id if (returnType.equals(DynamicValue.class) && value != null && !((DynamicValue<?>) value).isDynamic() && ((DynamicValue<?>) value).get() != null) { origRefId = ((DynamicValue<?>) value).get().toString(); } else if (returnType.equals(String.class)) { origRefId = (String) value; } else if (returnType.equals(ObjectId.class)) { origRefId = ((ObjectId) value).toHexString(); } if (entityType.equals(resources)) { origRefId = fileResolver.resolveResourceId(origRefId); } if (origRefId == null || !ObjectId.isValid(origRefId)) { return null; } //get or create new ref if (references.containsKey(origRefId)) { newRefId = references.get(origRefId); } else { newRefId = new ObjectId().toHexString(); references.put(origRefId, newRefId); } //build new value if (entityType.equals(resources)) { newRefId = FileResolver.RESOURCE_PREFIX + references.get(origRefId); } if (returnType.equals(DynamicValue.class) && !((DynamicValue<?>) value).isDynamic()) { newValue = new DynamicValue<String> (newRefId); } else if (returnType.equals(String.class)) { newValue = newRefId; } else if (returnType.equals(ObjectId.class)) { newValue = new ObjectId(newRefId); } return newValue; } private Object getNewValue(Object value, Class<?> returnType, Map<String, String> references, String entityType) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (value instanceof Collection) { Collection<Object> c = (Collection<Object>) value; Collection<Object> newCol = c.getClass().getConstructor().newInstance(); c.forEach(e-> { newCol.add(getNewValue_(e,e.getClass(),references, entityType)); }); return newCol; } else { return getNewValue_(value,returnType,references, entityType); } } }
package thredds.server.wcs.v1_0_0_1; import thredds.servlet.ServletUtil; import thredds.servlet.UsageLog; import thredds.server.wcs.VersionHandler; import thredds.util.Version; import thredds.wcs.v1_0_0_1.*; import thredds.wcs.Request; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.File; import java.io.FileNotFoundException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import ucar.nc2.util.DiskCache2; /** * _more_ * * @author edavis * @since 4.0 */ public class WcsHandler implements VersionHandler { private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger( WcsHandler.class ); private Version version; /** * Declare the default constructor to be package private. * @param verString the version string. */ public WcsHandler( String verString ) { this.version = new Version( verString ); } public Version getVersion() { return this.version; } public VersionHandler setDiskCache( DiskCache2 diskCache ) { WcsCoverage.setDiskCache( diskCache); return this; } private boolean deleteImmediately = true; public VersionHandler setDeleteImmediately( boolean deleteImmediately ) { this.deleteImmediately = deleteImmediately; return this; } public void handleKVP( HttpServlet servlet, HttpServletRequest req, HttpServletResponse res ) throws IOException //, ServletException { WcsRequest request = null; try { URI serverURI = new URI( req.getRequestURL().toString()); request = WcsRequestParser.parseRequest( this.getVersion().getVersionString(), serverURI, req, res); if ( request.getOperation().equals( Request.Operation.GetCapabilities)) { res.setContentType( "text/xml" ); res.setStatus( HttpServletResponse.SC_OK ); PrintWriter pw = res.getWriter(); ((GetCapabilities) request).writeCapabilitiesReport( pw ); pw.flush(); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_OK, -1 ) ); } else if ( request.getOperation().equals( Request.Operation.DescribeCoverage ) ) { res.setContentType( "text/xml" ); res.setStatus( HttpServletResponse.SC_OK ); PrintWriter pw = res.getWriter(); ((DescribeCoverage) request).writeDescribeCoverageDoc( pw ); pw.flush(); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_OK, -1 ) ); } else if ( request.getOperation().equals( Request.Operation.GetCoverage ) ) { File covFile = ((GetCoverage) request).writeCoverageDataToFile(); if ( covFile != null && covFile.exists()) { int pos = covFile.getPath().lastIndexOf( "." ); String suffix = covFile.getPath().substring( pos ); String resultFilename = request.getDataset().getDatasetName(); // this is name browser will show if ( !resultFilename.endsWith( suffix ) ) resultFilename = resultFilename + suffix; res.setHeader( "Content-Disposition", "attachment; filename=\"" + resultFilename + "\"" ); ServletUtil.returnFile( servlet, "", covFile.getPath(), req, res, ((GetCoverage) request).getFormat().getMimeType() ); if ( deleteImmediately ) covFile.delete(); } else { log.error( "handleKVP(): Failed to create coverage file" + (covFile == null ? "" : (": " + covFile.getAbsolutePath() )) ); throw new WcsException( "Problem creating requested coverage."); } } } catch ( WcsException e) { handleExceptionReport( res, e); } catch ( URISyntaxException e ) { handleExceptionReport( res, new WcsException( "Bad URI: " + e.getMessage())); } catch ( Throwable t) { log.error( "Unknown problem.", t); handleExceptionReport( res, new WcsException( "Unknown problem", t)); } finally { if ( request != null && request.getDataset() != null ) { request.getDataset().close(); } } } public GetCapabilities.ServiceInfo getServiceInfo() { // Todo Figure out how to configure serviceId info. GetCapabilities.ServiceInfo sid; GetCapabilities.ResponsibleParty respParty; GetCapabilities.ResponsibleParty.ContactInfo contactInfo; contactInfo = new GetCapabilities.ResponsibleParty.ContactInfo( Collections.singletonList( "voice phone"), Collections.singletonList( "voice phone"), new GetCapabilities.ResponsibleParty.Address( Collections.singletonList( "address"), "city", "admin area", "postal code", "country", Collections.singletonList( "email") ), new GetCapabilities.ResponsibleParty.OnlineResource(null, "title") ); respParty= new GetCapabilities.ResponsibleParty( "indiv name", "org name", "position", contactInfo ); sid = new GetCapabilities.ServiceInfo( "name", "label", "description", Collections.singletonList( "keyword" ), respParty, "no fees", Collections.singletonList( "no access constraints" ) ); return sid; } public void handleExceptionReport( HttpServletResponse res, WcsException exception ) throws IOException { res.setContentType( "application/vnd.ogc.se_xml" ); res.setStatus( HttpServletResponse.SC_BAD_REQUEST ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_BAD_REQUEST, -1 )); ExceptionReport exceptionReport = new ExceptionReport( exception ); PrintWriter pw = res.getWriter(); exceptionReport.writeExceptionReport( pw ); pw.flush(); } public void handleExceptionReport( HttpServletResponse res, String code, String locator, String message ) throws IOException { WcsException.Code c; WcsException exception; try { c = WcsException.Code.valueOf( code); exception = new WcsException( c, locator, message ); } catch ( IllegalArgumentException e ) { exception = new WcsException( message ); log.debug( "handleExceptionReport(): bad code given [" + code + "]."); } handleExceptionReport( res, exception); } public void handleExceptionReport( HttpServletResponse res, String code, String locator, Throwable t ) throws IOException { handleExceptionReport( res, code, locator, t.getMessage()); if ( t instanceof FileNotFoundException ) log.info( "handleExceptionReport", t.getMessage() ); // dont clutter up log files else log.info( "handleExceptionReport", t ); } }
package util; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable; /** * @author fhaertig * @since 14.03.16 */ public class WebDriverPaydirekt extends CustomWebDriver { private static String LOGIN_FORM_USERNAME_FIELD_ID = "username"; private static String LOGIN_FORM_PASSWORD_FIELD_ID = "password"; private static String LOGIN_FORM_SUBMIT_BUTTON_NAME = "loginBtn"; private static String CONFIRM_BUTTON_NAME = "confirmPaymentButton"; private static String URL_SUCCESS_PATTERN = "-Success"; private static Logger LOG = LoggerFactory.getLogger(WebDriverPaydirekt.class); public WebDriverPaydirekt() { super(); } private boolean doLogin(String userid, String pin) { boolean loggedIn = false; final WebElement useridInput = findElement(By.id(LOGIN_FORM_USERNAME_FIELD_ID)); useridInput.clear(); useridInput.sendKeys(userid.trim()); final WebElement pinInput = findElement(By.id(LOGIN_FORM_PASSWORD_FIELD_ID)); pinInput.sendKeys(pin.trim()); final WebElement submitButton = findElement(By.name(LOGIN_FORM_SUBMIT_BUTTON_NAME)); if (submitButton == null) { LOG.error(String.format("Submit button with name %S not found on the page", LOGIN_FORM_SUBMIT_BUTTON_NAME)); } else { loggedIn = true; submitButton.click(); } return loggedIn; } /** * Submits the given {@code password} at the given {@code url}'s "password" element, waits for a redirect and * returns the URL it was redirected to. * * @param url the URL to navigate to * @param userid the account id to use * @return the URL the browser was redirected to after submitting the {@code password} */ public String executePayDirectRedirect(final String url, final String userid, final String pin) { boolean success = false; getDriver().get(url); if (doLogin(userid, pin)) { WebDriverWait wait = new WebDriverWait(getDriver(), 10); wait.until(elementToBeClickable(findElement(By.name(CONFIRM_BUTTON_NAME)))).click(); success = wait.until(ExpectedConditions.urlContains(URL_SUCCESS_PATTERN)); } return success ? getUrl() : ""; } }
package org.mozilla.javascript.tests; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.Set; import org.junit.Test; import org.mozilla.javascript.CompilerEnvirons; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextAction; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ErrorReporter; import org.mozilla.javascript.IRFactory; import org.mozilla.javascript.Parser; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.ast.AstRoot; import org.mozilla.javascript.ast.FunctionNode; import org.mozilla.javascript.ast.ScriptNode; import org.mozilla.javascript.optimizer.Codegen; import org.mozilla.javascript.optimizer.OptFunctionNode; public class Bug708801Test { private static final ContextFactory factory = new ContextFactory() { static final int COMPILER_MODE = 9; @Override protected Context makeContext() { Context cx = super.makeContext(); cx.setLanguageVersion(Context.VERSION_1_8); cx.setOptimizationLevel(COMPILER_MODE); return cx; } }; private abstract static class Action implements ContextAction<Object> { protected Context cx; protected ScriptableObject scope; @SuppressWarnings("unused") protected Object evaluate(String s) { return cx.evaluateString(scope, s, "<eval>", 1, null); } /** Compiles {@code source} and returns the transformed and optimized {@link ScriptNode} */ protected ScriptNode compile(CharSequence source) { final String mainMethodClassName = "Main"; final String scriptClassName = "Main"; CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(cx); ErrorReporter compilationErrorReporter = compilerEnv.getErrorReporter(); Parser p = new Parser(compilerEnv, compilationErrorReporter); AstRoot ast = p.parse(source.toString(), "<eval>", 1); IRFactory irf = new IRFactory(compilerEnv); ScriptNode tree = irf.transformTree(ast); Codegen codegen = new Codegen(); codegen.setMainMethodClass(mainMethodClassName); codegen.compileToClassFile( compilerEnv, scriptClassName, tree, tree.getEncodedSource(), false); return tree; } /** * Checks every variable {@code v} in {@code source} is marked as a number-variable iff * {@code numbers} contains {@code v} */ protected void assertNumberVars(CharSequence source, String... numbers) { // wrap source in function ScriptNode tree = compile("function f(o, fn){" + source + "}"); FunctionNode fnode = tree.getFunctionNode(0); assertNotNull(fnode); OptFunctionNode opt = OptFunctionNode.get(fnode); assertNotNull(opt); assertSame(fnode, opt.fnode); for (int i = 0, c = fnode.getParamCount(); i < c; ++i) { assertTrue(opt.isParameter(i)); assertFalse(opt.isNumberVar(i)); } Set<String> set = new HashSet<String>(asList(numbers)); for (int i = fnode.getParamCount(), c = fnode.getParamAndVarCount(); i < c; ++i) { assertFalse(opt.isParameter(i)); String name = fnode.getParamOrVarName(i); String msg = format("{%s -> number? = %b}", name, opt.isNumberVar(i)); assertEquals(msg, set.contains(name), opt.isNumberVar(i)); } } public final Object run(Context cx) { this.cx = cx; scope = cx.initStandardObjects(null, true); return run(); } protected abstract Object run(); } @Test public void testIncDec() { factory.call( new Action() { @Override protected Object run() { // pre-inc assertNumberVars("var b; ++b"); assertNumberVars("var b=0; ++b", "b"); assertNumberVars("var b; ++[1][++b]"); assertNumberVars("var b=0; ++[1][++b]", "b"); assertNumberVars("var b; ++[1][b=0,++b]", "b"); // pre-dec assertNumberVars("var b; --b"); assertNumberVars("var b=0; --b", "b"); assertNumberVars("var b; assertNumberVars("var b=0; --[1][--b]", "b"); assertNumberVars("var b; --[1][b=0,--b]", "b"); // post-inc assertNumberVars("var b; b++"); assertNumberVars("var b=0; b++", "b"); assertNumberVars("var b; [1][b++]++"); assertNumberVars("var b=0; [1][b++]++", "b"); assertNumberVars("var b; [1][b=0,b++]++", "b"); // post-dec assertNumberVars("var b; b assertNumberVars("var b=0; b assertNumberVars("var b; [1][b assertNumberVars("var b=0; [1][b assertNumberVars("var b; [1][b=0,b return null; } }); } @Test public void testTypeofName() { factory.call( new Action() { @Override protected Object run() { // Token.TYPEOFNAME assertNumberVars("var b; typeof b"); assertNumberVars("var b=0; typeof b", "b"); assertNumberVars("var b; if(new Date()<0){b=0} typeof b"); // Token.TYPEOF assertNumberVars("var b; typeof (b,b)"); assertNumberVars("var b=0; typeof (b,b)", "b"); assertNumberVars("var b; if(new Date()<0){b=0} typeof (b,b)"); return null; } }); } @Test public void testEval() { factory.call( new Action() { @Override protected Object run() { // direct eval => requires activation assertNumberVars("var b; eval('typeof b')"); assertNumberVars("var b=0; eval('typeof b')"); assertNumberVars("var b; if(new Date()<0){b=0} eval('typeof b')"); // indirect eval => requires no activation assertNumberVars("var b; (1,eval)('typeof b');"); assertNumberVars("var b=0; (1,eval)('typeof b')", "b"); assertNumberVars("var b; if(new Date()<0){b=0} (1,eval)('typeof b')", "b"); return null; } }); } @Test public void testRelOp() { factory.call( new Action() { @Override protected Object run() { // relational operators: <, <=, >, >= assertNumberVars("var b = 1 < 1"); assertNumberVars("var b = 1 <= 1"); assertNumberVars("var b = 1 > 1"); assertNumberVars("var b = 1 >= 1"); assertNumberVars("var b = 1 == 1"); assertNumberVars("var b = 1 != 1"); assertNumberVars("var b = 1 === 1"); assertNumberVars("var b = 1 !== 1"); return null; } }); } @Test public void testMore() { factory.call( new Action() { @Override protected Object run() { // simple assignment: assertNumberVars("var b"); assertNumberVars("var b = 1", "b"); assertNumberVars("var b = 'a'"); assertNumberVars("var b = true"); assertNumberVars("var b = /(?:)/"); assertNumberVars("var b = o"); assertNumberVars("var b = fn"); // use before assignment assertNumberVars("b; var b = 1"); assertNumberVars("b || c; var b = 1, c = 2"); assertNumberVars("if(b) var b = 1"); assertNumberVars("typeof b; var b=1"); assertNumberVars("typeof (b,b); var b=1"); // relational operators: in, instanceof assertNumberVars("var b = 1 instanceof 1"); assertNumberVars("var b = 1 in 1"); // other operators with nested comma expression: assertNumberVars("var b = !(1,1)"); assertNumberVars("var b = typeof(1,1)"); assertNumberVars("var b = void(1,1)"); // nested assignment assertNumberVars("var b = 1; var f = (b = 'a')"); // let expression: assertNumberVars("var b = let(x=1) x", "b", "x"); assertNumberVars("var b = let(x=1,y=1) x,y", "b", "x", "y"); // conditional operator: assertNumberVars("var b = 0 ? 1 : 2", "b"); assertNumberVars("var b = 'a' ? 1 : 2", "b"); // comma expression: assertNumberVars("var b = (0,1)", "b"); assertNumberVars("var b = ('a',1)", "b"); // assignment operations: assertNumberVars("var b; var c=0; b=c", "b", "c"); assertNumberVars("var b; var c=0; b=(c=1)", "b", "c"); assertNumberVars("var b; var c=0; b=(c='a')"); assertNumberVars("var b; var c=0; b=(c+=1)", "b", "c"); assertNumberVars("var b; var c=0; b=(c*=1)", "b", "c"); assertNumberVars("var b; var c=0; b=(c%=1)", "b", "c"); assertNumberVars("var b; var c=0; b=(c/=1)", "b", "c"); // property access: assertNumberVars("var b; b=(o.p)"); assertNumberVars("var b; b=(o.p=1)", "b"); assertNumberVars("var b; b=(o.p+=1)"); assertNumberVars("var b; b=(o['p']=1)", "b"); assertNumberVars("var b; b=(o['p']+=1)"); assertNumberVars("var b; var o = {p:0}; b=(o.p=1)", "b"); assertNumberVars("var b; var o = {p:0}; b=(o.p+=1)"); assertNumberVars("var b; var o = {p:0}; b=(o['p']=1)", "b"); assertNumberVars("var b; var o = {p:0}; b=(o['p']+=1)"); assertNumberVars("var b = 1; b.p = true", "b"); assertNumberVars("var b = 1; b.p", "b"); assertNumberVars("var b = 1; b.p()", "b"); assertNumberVars("var b = 1; b[0] = true", "b"); assertNumberVars("var b = 1; b[0]", "b"); assertNumberVars("var b = 1; b[0]()", "b"); // assignment (global) assertNumberVars("var b = foo"); assertNumberVars("var b = foo1=1", "b"); assertNumberVars("var b = foo2+=1"); // boolean operators: assertNumberVars("var b = 1||2", "b"); assertNumberVars("var b; var c=1; b=c||2", "b", "c"); assertNumberVars("var b; var c=1; b=c||c||2", "b", "c"); assertNumberVars("var b = 1&&2", "b"); assertNumberVars("var b; var c=1; b=c&&2", "b", "c"); assertNumberVars("var b; var c=1; b=c&&c&&2", "b", "c"); // bit not: assertNumberVars("var b = ~0", "b"); assertNumberVars("var b = ~o", "b"); assertNumberVars("var b; var c=1; b=~c", "b", "c"); // increment, function call: assertNumberVars("var b; var g; b = (g=0,g++)", "b", "g"); assertNumberVars("var b; var x = fn(b=1)", "b"); assertNumberVars("var b; var x = fn(b=1).p++", "b", "x"); assertNumberVars("var b; ({1:{}})[b=1].p++", "b"); assertNumberVars("var b; o[b=1]++", "b"); // destructuring assertNumberVars("var r,s; [r,s] = [1,1]"); assertNumberVars("var r=0, s=0; [r,s] = [1,1]"); assertNumberVars("var r,s; ({a: r, b: s}) = {a:1, b:1}"); assertNumberVars("var r=0, s=0; ({a: r, b: s}) = {a:1, b:1}"); // array comprehension assertNumberVars("var b=[i*i for each (i in [1,2,3])]"); assertNumberVars("var b=[j*j for each (j in [1,2,3]) if (j>1)]"); return null; } }); } }
package se.sics.cooja.plugins; import java.awt.Font; import java.awt.event.MouseEvent; import java.util.*; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableColumn; import org.apache.log4j.Logger; import org.jdom.Element; import se.sics.cooja.*; import se.sics.cooja.interfaces.MoteID; import se.sics.cooja.interfaces.Radio; import se.sics.cooja.util.StringUtils; /** * Radio logger listens to the simulation radio medium and lists all transmitted * data in a table. * * @author Fredrik Osterlind */ @ClassDescription("Radio Logger") @PluginType(PluginType.SIM_PLUGIN) public class RadioLogger extends VisPlugin { private static Logger logger = Logger.getLogger(RadioLogger.class); private final static int COLUMN_TIME = 0; private final static int COLUMN_FROM = 1; private final static int COLUMN_TO = 2; private final static int COLUMN_DATA = 3; private final static String[] COLUMN_NAMES = { "Time", "From", "To", "Data" }; private Simulation simulation; private ArrayList<RadioConnectionLog> connections = new ArrayList<RadioConnectionLog>(); private JTable dataTable = null; private RadioMedium radioMedium; private Observer radioMediumObserver; public RadioLogger(final Simulation simulationToControl, final GUI gui) { super("Radio Logger", gui); simulation = simulationToControl; radioMedium = simulation.getRadioMedium(); final AbstractTableModel model = new AbstractTableModel() { public String getColumnName(int col) { return COLUMN_NAMES[col]; } public int getRowCount() { return connections.size(); } public int getColumnCount() { return COLUMN_NAMES.length; } public Object getValueAt(int row, int col) { RadioConnectionLog conn = connections.get(row); if (col == COLUMN_TIME) { return conn.startTime; } else if (col == COLUMN_FROM) { return getMoteID(conn.connection.getSource().getMote()); } else if (col == COLUMN_TO) { Radio[] dests = conn.connection.getDestinations(); if (dests.length == 1) { return getMoteID(dests[0].getMote()); } return "[" + dests.length + " motes]"; } else if (col == COLUMN_DATA) { if (conn.data == null) { prepareDataString(connections.get(row)); } return conn.data; } return null; } public boolean isCellEditable(int row, int col) { if (col == COLUMN_FROM) { /* Highlight source */ gui.signalMoteHighlight(connections.get(row).connection.getSource().getMote()); return false; } if (col == COLUMN_TO) { /* Highlight all destinations */ Radio dests[] = connections.get(row).connection.getDestinations(); for (Radio dest: dests) { gui.signalMoteHighlight(dest.getMote()); } return false; } return false; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } }; dataTable = new JTable(model) { public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); int realColumnIndex = convertColumnIndexToModel(colIndex); RadioConnectionLog conn = connections.get(rowIndex); if (realColumnIndex == COLUMN_TIME) { return "<html>" + "Start time: " + conn.startTime + "<br>" + "End time: " + conn.endTime + "<br><br>" + "Duration: " + (conn.endTime - conn.startTime) + "</html>"; } else if (realColumnIndex == COLUMN_FROM) { return conn.connection.getSource().getMote().toString(); } else if (realColumnIndex == COLUMN_TO) { StringBuilder tip = new StringBuilder(); tip.append("<html>"); Radio[] dests = conn.connection.getDestinations(); for (Radio radio: dests) { tip.append(radio.getMote()).append("<br>"); } tip.append("</html>"); return tip.toString(); } else if (realColumnIndex == COLUMN_DATA) { if (conn.tooltip == null) { prepareTooltipString(conn); } return conn.tooltip; } return super.getToolTipText(e); } }; // Set data column width greedy dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); dataTable.getColumnModel().getColumn(COLUMN_TIME).setPreferredWidth(130); // dataTable.getColumnModel().getColumn(COLUMN_TIME).setResizable(false); dataTable.getColumnModel().getColumn(COLUMN_FROM).setPreferredWidth(90); dataTable.getColumnModel().getColumn(COLUMN_TO).setPreferredWidth(150); dataTable.getColumnModel().getColumn(COLUMN_DATA).setPreferredWidth(1500); dataTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); dataTable.setFont(new Font("Monospaced", Font.PLAIN, 12)); simulation.getRadioMedium().addRadioMediumObserver(radioMediumObserver = new Observer() { public void update(Observable obs, Object obj) { RadioConnection[] conns = radioMedium.getLastTickConnections(); if (conns == null) { return; } for (RadioConnection conn : conns) { RadioConnectionLog loggedConn = new RadioConnectionLog(); loggedConn.startTime = conn.getStartTime(); loggedConn.endTime = simulation.getSimulationTime(); loggedConn.connection = conn; loggedConn.packet = conn.getSource().getLastPacketTransmitted(); connections.add(loggedConn); } model.fireTableRowsInserted(connections.size() - conns.length + 1, connections.size()); setTitle("Radio Logger: " + connections.size() + " packets"); } }); add(new JScrollPane(dataTable)); setSize(500, 300); try { setSelected(true); } catch (java.beans.PropertyVetoException e) { // Could not select } } private String getMoteID(Mote mote) { MoteID moteID = mote.getInterfaces().getMoteID(); if (moteID != null) { return Integer.toString(moteID.getMoteID()); } return mote.toString(); } private void prepareDataString(RadioConnectionLog conn) { byte[] data; if (conn.packet == null) { data = null; } else if (conn.packet instanceof ConvertedRadioPacket) { data = ((ConvertedRadioPacket)conn.packet).getOriginalPacketData(); } else { data = conn.packet.getPacketData(); } if (data == null) { conn.data = "[unknown data]"; return; } conn.data = data.length + ": 0x" + StringUtils.toHex(data, 4); } private void prepareTooltipString(RadioConnectionLog conn) { RadioPacket packet = conn.packet; if (packet == null) { conn.tooltip = ""; return; } if (packet instanceof ConvertedRadioPacket && packet.getPacketData().length > 0) { byte[] original = ((ConvertedRadioPacket)packet).getOriginalPacketData(); byte[] converted = ((ConvertedRadioPacket)packet).getPacketData(); conn.tooltip = "<html><font face=\"Monospaced\">" + "<b>Packet data (" + original.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(original) + "</pre>" + "</font><font face=\"Monospaced\">" + "<b>Cross-level packet data (" + converted.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(converted) + "</pre>" + "</font></html>"; } else if (packet instanceof ConvertedRadioPacket) { byte[] original = ((ConvertedRadioPacket)packet).getOriginalPacketData(); conn.tooltip = "<html><font face=\"Monospaced\">" + "<b>Packet data (" + original.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(original) + "</pre>" + "</font><font face=\"Monospaced\">" + "<b>No cross-level conversion available</b><br>" + "</font></html>"; } else { byte[] data = packet.getPacketData(); conn.tooltip = "<html><font face=\"Monospaced\">" + "<b>Packet data (" + data.length + " bytes)</b><br>" + "<pre>" + StringUtils.hexDump(data) + "</pre>" + "</font></html>"; } } public void closePlugin() { if (radioMediumObserver != null) { radioMedium.deleteRadioMediumObserver(radioMediumObserver); } } public Collection<Element> getConfigXML() { return null; } public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) { return true; } private static class RadioConnectionLog { long startTime; long endTime; RadioConnection connection; RadioPacket packet; String data = null; String tooltip = null; } }
package debugging.jsonclientcaller; import static debugging.jsonclientcaller.JsonClientCaller.streamToString; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.abstracthandle.AbstractHandleClient; import us.kbase.auth.AuthService; import us.kbase.auth.AuthToken; public class JsonClientCallerGutsTest { private static final String URL = "http://dev03.berkeley.kbase.us:7109"; private static final int SLEEP = 1000; //ms between requests public static void main(String [] args) throws Exception{ System.out.println(URL); String user = args[0]; String pwd = args[1]; int count = Integer.parseInt(args[2]); int excepts = 0; for (int i = 0; i < count; i++) { System.out.print(i + "\n"); try { HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); AuthToken accessToken = AuthService.login( user, pwd).getToken(); conn.setRequestProperty("Authorization", accessToken.toString()); final long[] sizeWrapper = new long[] {0}; OutputStream os = new OutputStream() { @Override public void write(int b) {sizeWrapper[0]++;} @Override public void write(byte[] b) {sizeWrapper[0] += b.length;} @Override public void write(byte[] b, int o, int l) {sizeWrapper[0] += l;} }; String method = "AbstractHandle.are_readable"; Object arg = Arrays.asList(Arrays.asList("KBH_3")); String id = "12345"; writeRequestData(method, arg, os, id); // Set content-length conn.setFixedLengthStreamingMode(sizeWrapper[0]); writeRequestData(method, arg, conn.getOutputStream(), id); System.out.print(conn.getResponseCode() + " "); System.out.println(conn.getResponseMessage()); conn.getResponseMessage(); InputStream istream; if (conn.getResponseCode() == 500) { istream = conn.getErrorStream(); } else { istream = conn.getInputStream(); } // Parse response into json System.out.println(streamToString(istream)); } catch (Exception e) { excepts++; System.out.println(e.getClass().getName() + ": " + e.getLocalizedMessage()); } Thread.sleep(SLEEP); } System.out.println(String.format("Sleep: %s, failures %s/%s", SLEEP, excepts, count)); } public static void writeRequestData(String method, Object arg, OutputStream os, String id) throws IOException { JsonGenerator g = new ObjectMapper().getFactory() .createGenerator(os, JsonEncoding.UTF8); g.writeStartObject(); g.writeObjectField("params", arg); g.writeStringField("method", method); g.writeStringField("version", "1.1"); g.writeStringField("id", id); g.writeEndObject(); g.close(); os.flush(); } }
package org.sagebionetworks.bridge.services; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.dao.TaskDao; import org.sagebionetworks.bridge.dao.UserConsentDao; import org.sagebionetworks.bridge.dynamodb.DynamoSurvey; import org.sagebionetworks.bridge.dynamodb.DynamoSurveyResponse; import org.sagebionetworks.bridge.dynamodb.DynamoTask; import org.sagebionetworks.bridge.dynamodb.DynamoTaskDao; import org.sagebionetworks.bridge.dynamodb.DynamoUserConsent2; import org.sagebionetworks.bridge.exceptions.BadRequestException; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolder; import org.sagebionetworks.bridge.models.accounts.User; import org.sagebionetworks.bridge.models.accounts.UserConsent; import org.sagebionetworks.bridge.models.schedules.ScheduleContext; import org.sagebionetworks.bridge.models.schedules.Task; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.sagebionetworks.bridge.models.surveys.Survey; import org.sagebionetworks.bridge.models.surveys.SurveyResponse; import org.sagebionetworks.bridge.models.surveys.SurveyResponseView; import com.google.common.collect.Maps; public class TaskServiceTest { private static final DateTime ENROLLMENT = DateTime.parse("2015-04-10T10:40:34.000-07:00"); private static final StudyIdentifier STUDY_IDENTIFIER = new StudyIdentifierImpl("foo"); private static final String HEALTH_CODE = "BBB"; private TaskService service; private SchedulePlanService schedulePlanService; private UserConsentDao userConsentDao; private User user; private TaskDao taskDao; private DateTime endsOn; @SuppressWarnings("unchecked") @Before public void before() { user = new User(); user.setStudyKey(STUDY_IDENTIFIER.getIdentifier()); user.setHealthCode(HEALTH_CODE); endsOn = DateTime.now().plusDays(2); service = new TaskService(); schedulePlanService = mock(SchedulePlanService.class); when(schedulePlanService.getSchedulePlans(STUDY_IDENTIFIER)).thenReturn(TestUtils.getSchedulePlans()); UserConsent consent = mock(DynamoUserConsent2.class); when(consent.getSignedOn()).thenReturn(ENROLLMENT.getMillis()); userConsentDao = mock(UserConsentDao.class); when(userConsentDao.getUserConsent(HEALTH_CODE, STUDY_IDENTIFIER)).thenReturn(consent); Map<String,DateTime> map = Maps.newHashMap(); TaskEventService taskEventService = mock(TaskEventService.class); when(taskEventService.getTaskEventMap(anyString())).thenReturn(map); ScheduleContext context = createScheduleContext(endsOn); List<Task> tasks = TestUtils.runSchedulerForTasks(user, context); taskDao = mock(DynamoTaskDao.class); when(taskDao.getTasks(context)).thenReturn(tasks); when(taskDao.taskRunHasNotOccurred(anyString(), anyString())).thenReturn(true); Survey survey = new DynamoSurvey(); survey.setGuid("guid"); survey.setIdentifier("identifier"); survey.setCreatedOn(20000L); SurveyService surveyService = mock(SurveyService.class); when(surveyService.getSurveyMostRecentlyPublishedVersion(any(StudyIdentifier.class), anyString())).thenReturn(survey); SurveyResponse response = new DynamoSurveyResponse(); response.setHealthCode("healthCode"); response.setIdentifier("identifier"); SurveyResponseView surveyResponse = new SurveyResponseView(response, survey); SurveyResponseService surveyResponseService = mock(SurveyResponseService.class); when(surveyResponseService.createSurveyResponse( any(GuidCreatedOnVersionHolder.class), anyString(), any(List.class), anyString())).thenReturn(surveyResponse); service.setSchedulePlanService(schedulePlanService); service.setUserConsentDao(userConsentDao); service.setSurveyService(surveyService); service.setSurveyResponseService(surveyResponseService); service.setTaskDao(taskDao); service.setTaskEventService(taskEventService); } @Test(expected = BadRequestException.class) public void rejectsEndsOnBeforeNow() { service.getTasks(user, new ScheduleContext(DateTimeZone.UTC, DateTime.now().minusSeconds(1), null, null, null)); } @Test(expected = BadRequestException.class) public void rejectsEndsOnTooFarInFuture() { service.getTasks(user, new ScheduleContext(DateTimeZone.UTC, DateTime.now().plusDays(TaskService.MAX_EXPIRES_ON_DAYS).plusSeconds(1), null, null, null)); } @Test(expected = BadRequestException.class) public void rejectsListOfTasksWithNullElement() { ScheduleContext context = createScheduleContext(endsOn); List<Task> tasks = TestUtils.runSchedulerForTasks(user, context); tasks.set(0, (DynamoTask)null); service.updateTasks("AAA", tasks); } @Test(expected = BadRequestException.class) public void rejectsListOfTasksWithTaskThatLacksGUID() { ScheduleContext context = createScheduleContext(endsOn); List<Task> tasks = TestUtils.runSchedulerForTasks(user, context); tasks.get(0).setGuid(null); service.updateTasks("AAA", tasks); } @Test public void updateTasksWorks() { ScheduleContext context = createScheduleContext(endsOn); List<Task> tasks = TestUtils.runSchedulerForTasks(user, context); service.updateTasks("BBB", tasks); verify(taskDao).updateTasks("BBB", tasks); verifyNoMoreInteractions(taskDao); } @Test public void deleteTasksDeletes() { service.deleteTasks("BBB"); verify(taskDao).deleteTasks("BBB"); verifyNoMoreInteractions(taskDao); } @SuppressWarnings({"unchecked","rawtypes","deprecation"}) @Test public void changePublishedAndAbsoluteSurveyActivity() { service.getTasks(user, new ScheduleContext(DateTimeZone.UTC, endsOn.plusDays(2), null, null, null)); ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class); verify(taskDao).saveTasks(anyString(), argument.capture()); boolean foundTask3 = false; for (Task task : (List<Task>)argument.getValue()) { // ignoring tapTest if (!"tapTest".equals(task.getActivity().getRef())) { String ref = task.getActivity().getSurveyResponse().getHref(); assertTrue("Found task with survey response ref", ref.contains("/v3/surveyresponses/identifier")); } else { foundTask3 = true; } } assertTrue("Found task with tapTest ref", foundTask3); } private ScheduleContext createScheduleContext(DateTime endsOn) { Map<String,DateTime> events = Maps.newHashMap(); events.put("enrollment", ENROLLMENT); return new ScheduleContext(DateTimeZone.UTC, endsOn, HEALTH_CODE, events, null); } }
package org.zstack.image; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.CoreGlobalProperty; import org.zstack.core.Platform; import org.zstack.core.asyncbatch.AsyncBatchRunner; import org.zstack.core.asyncbatch.LoopAsyncBatch; import org.zstack.core.asyncbatch.While; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.config.GlobalConfig; import org.zstack.core.config.GlobalConfigUpdateExtensionPoint; import org.zstack.core.db.*; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.defer.Defer; import org.zstack.core.defer.Deferred; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.notification.N; import org.zstack.core.thread.CancelablePeriodicTask; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.AbstractService; import org.zstack.header.core.AsyncLatch; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.ErrorCodeList; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.identity.*; import org.zstack.header.image.*; import org.zstack.header.image.APICreateRootVolumeTemplateFromVolumeSnapshotEvent.Failure; import org.zstack.header.image.ImageConstant.ImageMediaType; import org.zstack.header.image.ImageDeletionPolicyManager.ImageDeletionPolicy; import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.MessageReply; import org.zstack.header.message.NeedQuotaCheckMessage; import org.zstack.header.quota.QuotaConstant; import org.zstack.header.rest.RESTFacade; import org.zstack.header.search.SearchOp; import org.zstack.header.storage.backup.*; import org.zstack.header.storage.primary.PrimaryStorageVO; import org.zstack.header.storage.primary.PrimaryStorageVO_; import org.zstack.header.storage.snapshot.*; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeMsg; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeReply; import org.zstack.header.vm.VmInstanceConstant; import org.zstack.header.volume.*; import org.zstack.identity.AccountManager; import org.zstack.identity.QuotaUtil; import org.zstack.search.SearchQuery; import org.zstack.tag.TagManager; import org.zstack.utils.CollectionUtils; import org.zstack.utils.ObjectUtils; import org.zstack.utils.RunOnce; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import java.sql.Timestamp; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.zstack.core.Platform.operr; import static org.zstack.utils.CollectionDSL.list; public class ImageManagerImpl extends AbstractService implements ImageManager, ManagementNodeReadyExtensionPoint, ReportQuotaExtensionPoint, ResourceOwnerPreChangeExtensionPoint { private static final CLogger logger = Utils.getLogger(ImageManagerImpl.class); @Autowired private CloudBus bus; @Autowired private PluginRegistry pluginRgty; @Autowired private DatabaseFacade dbf; @Autowired private AccountManager acntMgr; @Autowired private ErrorFacade errf; @Autowired private TagManager tagMgr; @Autowired private ThreadFacade thdf; @Autowired private ResourceDestinationMaker destMaker; @Autowired private ImageDeletionPolicyManager deletionPolicyMgr; @Autowired protected RESTFacade restf; private Map<String, ImageFactory> imageFactories = Collections.synchronizedMap(new HashMap<>()); private static final Set<Class> allowedMessageAfterDeletion = new HashSet<>(); private Future<Void> expungeTask; static { allowedMessageAfterDeletion.add(ImageDeletionMsg.class); } @Override @MessageSafe public void handleMessage(Message msg) { if (msg instanceof ImageMessage) { passThrough((ImageMessage) msg); } else if (msg instanceof APIMessage) { handleApiMessage(msg); } else { handleLocalMessage(msg); } } private void handleLocalMessage(Message msg) { bus.dealWithUnknownMessage(msg); } private void handleApiMessage(Message msg) { if (msg instanceof APIAddImageMsg) { handle((APIAddImageMsg) msg); } else if (msg instanceof APIListImageMsg) { handle((APIListImageMsg) msg); } else if (msg instanceof APISearchImageMsg) { handle((APISearchImageMsg) msg); } else if (msg instanceof APIGetImageMsg) { handle((APIGetImageMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromRootVolumeMsg) { handle((APICreateRootVolumeTemplateFromRootVolumeMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromVolumeSnapshotMsg) { handle((APICreateRootVolumeTemplateFromVolumeSnapshotMsg) msg); } else if (msg instanceof APICreateDataVolumeTemplateFromVolumeMsg) { handle((APICreateDataVolumeTemplateFromVolumeMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(final APICreateDataVolumeTemplateFromVolumeMsg msg) { final APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(msg.getId()); List<ImageBackupStorageRefVO> refs = new ArrayList<>(); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-data-volume-template-from-volume-%s", msg.getVolumeUuid())); chain.then(new ShareFlow() { List<BackupStorageInventory> backupStorages = new ArrayList<>(); ImageVO image; long actualSize; @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-actual-size-of-data-volume"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg smsg = new SyncVolumeSizeMsg(); smsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeTargetServiceIdByResourceUuid(smsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); bus.send(smsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); actualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; @Override public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.select(VolumeVO_.format, VolumeVO_.size); q.add(VolumeVO_.uuid, Op.EQ, msg.getVolumeUuid()); Tuple t = q.findTuple(); String format = t.get(0, String.class); long size = t.get(1, Long.class); final ImageVO vo = new ImageVO(); vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid()); vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setMediaType(ImageMediaType.DataVolumeTemplate); vo.setSize(size); vo.setActualSize(actualSize); vo.setState(ImageState.Enabled); vo.setStatus(ImageStatus.Creating); vo.setSystem(false); vo.setFormat(format); vo.setUrl(String.format("volume://%s", msg.getVolumeUuid())); image = dbf.persistAndRefresh(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (image != null) { dbf.remove(image); } trigger.rollback(); } }); flow(new Flow() { String __name__ = "select-backup-storage"; @Override public void run(final FlowTrigger trigger, Map data) { final String zoneUuid = new Callable<String>() { @Override @Transactional(readOnly = true) public String call() { String sql = "select ps.zoneUuid" + " from PrimaryStorageVO ps, VolumeVO vol" + " where vol.primaryStorageUuid = ps.uuid" + " and vol.uuid = :volUuid"; TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class); q.setParameter("volUuid", msg.getVolumeUuid()); return q.getSingleResult(); } }.call(); if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { backupStorages.add(((AllocateBackupStorageReply) reply).getInventory()); saveRefVOByBsInventorys(backupStorages, image.getUuid()); for (BackupStorageInventory bs: backupStorages) { for (CreateImageExtensionPoint ext : pluginRgty.getExtensionList(CreateImageExtensionPoint.class)) { ext.beforeCreateImage(ImageInventory.valueOf(image), bs.getUuid()); } } trigger.next(); } else { trigger.fail(errf.stringToOperationError("cannot find proper backup storage", reply.getError())); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); amsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); return amsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { backupStorages.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (backupStorages.isEmpty()) { trigger.fail(operr("failed to allocate all backup storage[uuid:%s], a list of error: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))); } else { saveRefVOByBsInventorys(backupStorages, image.getUuid()); for (BackupStorageInventory bs: backupStorages) { for (CreateImageExtensionPoint ext : pluginRgty.getExtensionList(CreateImageExtensionPoint.class)) { ext.beforeCreateImage(ImageInventory.valueOf(image), bs.getUuid()); } } trigger.next(); } } }); } } @Override public void rollback(FlowRollback trigger, Map data) { if (!backupStorages.isEmpty()) { List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(backupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(actualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(null) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { BackupStorageInventory bs = backupStorages.get(replies.indexOf(r)); logger.warn(String.format("failed to return %s bytes to backup storage[uuid:%s]", acntMgr, bs.getUuid())); } } }); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "create-data-volume-template-from-volume"; @Override public void run(final FlowTrigger trigger, Map data) { List<CreateDataVolumeTemplateFromDataVolumeMsg> cmsgs = CollectionUtils.transformToList(backupStorages, new Function<CreateDataVolumeTemplateFromDataVolumeMsg, BackupStorageInventory>() { @Override public CreateDataVolumeTemplateFromDataVolumeMsg call(BackupStorageInventory bs) { CreateDataVolumeTemplateFromDataVolumeMsg cmsg = new CreateDataVolumeTemplateFromDataVolumeMsg(); cmsg.setVolumeUuid(msg.getVolumeUuid()); cmsg.setBackupStorageUuid(bs.getUuid()); cmsg.setImageUuid(image.getUuid()); bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(msg) { @Override public void run(List<MessageReply> replies) { int fail = 0; String mdsum = null; ErrorCode err = null; String format = null; for (MessageReply r : replies) { BackupStorageInventory bs = backupStorages.get(replies.indexOf(r)); if (!r.isSuccess()) { logger.warn(String.format("failed to create data volume template from volume[uuid:%s] on backup storage[uuid:%s], %s", msg.getVolumeUuid(), bs.getUuid(), r.getError())); fail++; err = r.getError(); continue; } CreateDataVolumeTemplateFromDataVolumeReply reply = r.castReply(); ImageBackupStorageRefVO vo = Q.New(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.backupStorageUuid, bs.getUuid()) .eq(ImageBackupStorageRefVO_.imageUuid, image.getUuid()) .find(); vo.setStatus(ImageStatus.Ready); vo.setInstallPath(reply.getInstallPath()); dbf.update(vo); if (mdsum == null) { mdsum = reply.getMd5sum(); } if (reply.getFormat() != null) { format = reply.getFormat(); } } int backupStorageNum = msg.getBackupStorageUuids() == null ? 1 : msg.getBackupStorageUuids().size(); if (fail == backupStorageNum) { ErrorCode errCode = operr("failed to create data volume template from volume[uuid:%s] on all backup storage%s. See cause for one of errors", msg.getVolumeUuid(), msg.getBackupStorageUuids()).causedBy(err); trigger.fail(errCode); } else { image = dbf.reload(image); if (format != null) { image.setFormat(format); } image.setMd5Sum(mdsum); image.setStatus(ImageStatus.Ready); image = dbf.updateAndRefresh(image); trigger.next(); } } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { evt.setInventory(ImageInventory.valueOf(image)); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { evt.setError(errCode); bus.publish(evt); } }); } }).start(); } private void handle(final APICreateRootVolumeTemplateFromVolumeSnapshotMsg msg) { final APICreateRootVolumeTemplateFromVolumeSnapshotEvent evt = new APICreateRootVolumeTemplateFromVolumeSnapshotEvent(msg.getId()); SimpleQuery<VolumeSnapshotVO> q = dbf.createQuery(VolumeSnapshotVO.class); q.select(VolumeSnapshotVO_.format); q.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); String format = q.findValue(); final ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setSystem(msg.isSystem()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); vo.setGuestOsType(vo.getGuestOsType()); vo.setStatus(ImageStatus.Creating); vo.setState(ImageState.Enabled); vo.setFormat(format); vo.setMediaType(ImageMediaType.RootVolumeTemplate); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setUrl(String.format("volumeSnapshot://%s", msg.getSnapshotUuid())); dbf.persist(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class); sq.select(VolumeSnapshotVO_.volumeUuid, VolumeSnapshotVO_.treeUuid); sq.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); Tuple t = sq.findTuple(); String volumeUuid = t.get(0, String.class); String treeUuid = t.get(1, String.class); List<CreateTemplateFromVolumeSnapshotMsg> cmsgs = msg.getBackupStorageUuids().stream().map(bsUuid -> { CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg(); cmsg.setSnapshotUuid(msg.getSnapshotUuid()); cmsg.setImageUuid(vo.getUuid()); cmsg.setVolumeUuid(volumeUuid); cmsg.setTreeUuid(treeUuid); cmsg.setBackupStorageUuid(bsUuid); String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid; bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid); return cmsg; }).collect(Collectors.toList()); List<Failure> failures = new ArrayList<>(); AsyncLatch latch = new AsyncLatch(cmsgs.size(), new NoErrorCompletion(msg) { @Override public void done() { if (failures.size() == cmsgs.size()) { // failed on all ErrorCodeList error = errf.stringToOperationError(String.format("failed to create template from" + " the volume snapshot[uuid:%s] on backup storage[uuids:%s]", msg.getSnapshotUuid(), msg.getBackupStorageUuids()), failures.stream().map(f -> f.error).collect(Collectors.toList())); evt.setError(error); dbf.remove(vo); } else { ImageVO imvo = dbf.reload(vo); evt.setInventory(ImageInventory.valueOf(imvo)); logger.debug(String.format("successfully created image[uuid:%s, name:%s] from volume snapshot[uuid:%s]", imvo.getUuid(), imvo.getName(), msg.getSnapshotUuid())); } if (!failures.isEmpty()) { evt.setFailuresOnBackupStorage(failures); } bus.publish(evt); } }); RunOnce once = new RunOnce(); for (CreateTemplateFromVolumeSnapshotMsg cmsg : cmsgs) { bus.send(cmsg, new CloudBusCallBack(latch) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { synchronized (failures) { Failure failure = new Failure(); failure.error = reply.getError(); failure.backupStorageUuid = cmsg.getBackupStorageUuid(); failures.add(failure); } } else { CreateTemplateFromVolumeSnapshotReply cr = reply.castReply(); ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(cr.getBackupStorageUuid()); ref.setInstallPath(cr.getBackupStorageInstallPath()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(vo.getUuid()); dbf.persist(ref); once.run(() -> { vo.setSize(cr.getSize()); vo.setActualSize(cr.getActualSize()); vo.setStatus(ImageStatus.Ready); dbf.update(vo); }); } latch.ack(); } }); } } private void passThrough(ImageMessage msg) { ImageVO vo = dbf.findByUuid(msg.getImageUuid(), ImageVO.class); if (vo == null && allowedMessageAfterDeletion.contains(msg.getClass())) { ImageEO eo = dbf.findByUuid(msg.getImageUuid(), ImageEO.class); vo = ObjectUtils.newAndCopy(eo, ImageVO.class); } if (vo == null) { String err = String.format("Cannot find image[uuid:%s], it may have been deleted", msg.getImageUuid()); logger.warn(err); bus.replyErrorByMessageType((Message) msg, errf.instantiateErrorCode(SysErrors.RESOURCE_NOT_FOUND, err)); return; } ImageFactory factory = getImageFacotry(ImageType.valueOf(vo.getType())); Image img = factory.getImage(vo); img.handleMessage((Message) msg); } private void handle(final APICreateRootVolumeTemplateFromRootVolumeMsg msg) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-template-from-root-volume-%s", msg.getRootVolumeUuid())); chain.then(new ShareFlow() { ImageVO imageVO; VolumeInventory rootVolume; Long imageActualSize; List<BackupStorageInventory> targetBackupStorages = new ArrayList<>(); String zoneUuid; { VolumeVO rootvo = dbf.findByUuid(msg.getRootVolumeUuid(), VolumeVO.class); rootVolume = VolumeInventory.valueOf(rootvo); SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.zoneUuid); q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid()); zoneUuid = q.findValue(); } @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-volume-actual-size"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg msg = new SyncVolumeSizeMsg(); msg.setVolumeUuid(rootVolume.getUuid()); bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, rootVolume.getPrimaryStorageUuid()); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); imageActualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, Op.EQ, msg.getRootVolumeUuid()); final VolumeVO volvo = q.find(); String accountUuid = acntMgr.getOwnerAccountUuidOfResource(volvo.getUuid()); final ImageVO imvo = new ImageVO(); if (msg.getResourceUuid() != null) { imvo.setUuid(msg.getResourceUuid()); } else { imvo.setUuid(Platform.getUuid()); } imvo.setDescription(msg.getDescription()); imvo.setMediaType(ImageMediaType.RootVolumeTemplate); imvo.setState(ImageState.Enabled); imvo.setGuestOsType(msg.getGuestOsType()); imvo.setFormat(volvo.getFormat()); imvo.setName(msg.getName()); imvo.setSystem(msg.isSystem()); imvo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); imvo.setStatus(ImageStatus.Downloading); imvo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); imvo.setUrl(String.format("volume://%s", msg.getRootVolumeUuid())); imvo.setSize(volvo.getSize()); imvo.setActualSize(imageActualSize); dbf.persist(imvo); acntMgr.createAccountResourceRef(accountUuid, imvo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, imvo.getUuid(), ImageVO.class.getSimpleName()); imageVO = imvo; trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (imageVO != null) { dbf.remove(imageVO); } trigger.rollback(); } }); flow(new Flow() { String __name__ = String.format("select-backup-storage"); @Override public void run(final FlowTrigger trigger, Map data) { List<ImageBackupStorageRefVO> refs = new ArrayList<>(); if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setRequiredZoneUuid(zoneUuid); abmsg.setSize(imageActualSize); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); bus.send(abmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) reply).getInventory()); saveRefVOByBsInventorys(targetBackupStorages, imageVO.getUuid()); trigger.next(); } else { trigger.fail(reply.getError()); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setSize(imageActualSize); abmsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); return abmsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (targetBackupStorages.isEmpty()) { trigger.fail(operr("unable to allocate backup storage specified by uuids%s, list errors are: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))); } else { saveRefVOByBsInventorys(targetBackupStorages, imageVO.getUuid()); trigger.next(); } } }); } } @Override public void rollback(final FlowRollback trigger, Map data) { if (targetBackupStorages.isEmpty()) { trigger.rollback(); return; } List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(imageActualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { if (!r.isSuccess()) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); logger.warn(String.format("failed to return capacity[%s] to backup storage[uuid:%s], because %s", imageActualSize, bs.getUuid(), r.getError())); } } trigger.rollback(); } }); } }); flow(new NoRollbackFlow() { String __name__ = String.format("start-creating-template"); @Override public void run(final FlowTrigger trigger, Map data) { List<CreateTemplateFromVmRootVolumeMsg> cmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<CreateTemplateFromVmRootVolumeMsg, BackupStorageInventory>() { @Override public CreateTemplateFromVmRootVolumeMsg call(BackupStorageInventory arg) { CreateTemplateFromVmRootVolumeMsg cmsg = new CreateTemplateFromVmRootVolumeMsg(); cmsg.setRootVolumeInventory(rootVolume); cmsg.setBackupStorageUuid(arg.getUuid()); cmsg.setImageInventory(ImageInventory.valueOf(imageVO)); bus.makeTargetServiceIdByResourceUuid(cmsg, VmInstanceConstant.SERVICE_ID, rootVolume.getVmInstanceUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { boolean success = false; ErrorCode err = null; for (MessageReply r : replies) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); ImageBackupStorageRefVO ref = Q.New(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.backupStorageUuid, bs.getUuid()) .eq(ImageBackupStorageRefVO_.imageUuid, imageVO.getUuid()) .find(); if (dbf.reload(imageVO) == null) { SQL.New("delete from ImageBackupStorageRefVO where imageUuid = :uuid") .param("uuid", imageVO.getUuid()) .execute(); trigger.fail(operr("image [uuid:%s] has been deleted", imageVO.getUuid())); return; } if (!r.isSuccess()) { logger.warn(String.format("failed to create image from root volume[uuid:%s] on backup storage[uuid:%s], because %s", msg.getRootVolumeUuid(), bs.getUuid(), r.getError())); err = r.getError(); dbf.remove(ref); continue; } CreateTemplateFromVmRootVolumeReply reply = (CreateTemplateFromVmRootVolumeReply) r; ref.setStatus(ImageStatus.Ready); ref.setInstallPath(reply.getInstallPath()); dbf.update(ref); imageVO.setStatus(ImageStatus.Ready); if (reply.getFormat() != null) { imageVO.setFormat(reply.getFormat()); } imageVO = dbf.updateAndRefresh(imageVO); success = true; logger.debug(String.format("successfully created image[uuid:%s] from root volume[uuid:%s] on backup storage[uuid:%s]", imageVO.getUuid(), msg.getRootVolumeUuid(), bs.getUuid())); } if (success) { trigger.next(); } else { trigger.fail(operr("failed to create image from root volume[uuid:%s] on all backup storage, see cause for one of errors", msg.getRootVolumeUuid()).causedBy(err)); } } }); } }); flow(new Flow() { String __name__ = "copy-system-tag-to-image"; public void run(FlowTrigger trigger, Map data) { // find the rootimage and create some systemtag if it has SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, SimpleQuery.Op.EQ, msg.getRootVolumeUuid()); q.select(VolumeVO_.vmInstanceUuid); String vmInstanceUuid = q.findValue(); if (tagMgr.hasSystemTag(vmInstanceUuid, ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat())) { tagMgr.createNonInherentSystemTag(imageVO.getUuid(), ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat(), ImageVO.class.getSimpleName()); } trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = String.format("sync-image-size"); @Override public void run(final FlowTrigger trigger, Map data) { new While<>(targetBackupStorages).all((arg, completion) -> { SyncImageSizeMsg smsg = new SyncImageSizeMsg(); smsg.setBackupStorageUuid(arg.getUuid()); smsg.setImageUuid(imageVO.getUuid()); bus.makeTargetServiceIdByResourceUuid(smsg, ImageConstant.SERVICE_ID, imageVO.getUuid()); bus.send(smsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { completion.done(); } }); }).run(new NoErrorCompletion(trigger) { @Override public void done() { trigger.next(); } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); imageVO = dbf.reload(imageVO); ImageInventory iinv = ImageInventory.valueOf(imageVO); evt.setInventory(iinv); logger.warn(String.format("successfully create template[uuid:%s] from root volume[uuid:%s]", iinv.getUuid(), msg.getRootVolumeUuid())); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); evt.setError(errCode); logger.warn(String.format("failed to create template from root volume[uuid:%s], because %s", msg.getRootVolumeUuid(), errCode)); bus.publish(evt); } }); } }).start(); } private void handle(APIGetImageMsg msg) { SearchQuery<ImageInventory> sq = new SearchQuery(ImageInventory.class); sq.addAccountAsAnd(msg); sq.add("uuid", SearchOp.AND_EQ, msg.getUuid()); List<ImageInventory> invs = sq.list(); APIGetImageReply reply = new APIGetImageReply(); if (!invs.isEmpty()) { reply.setInventory(JSONObjectUtil.toJsonString(invs.get(0))); } bus.reply(msg, reply); } private void handle(APISearchImageMsg msg) { SearchQuery<ImageInventory> sq = SearchQuery.create(msg, ImageInventory.class); sq.addAccountAsAnd(msg); String content = sq.listAsString(); APISearchImageReply reply = new APISearchImageReply(); reply.setContent(content); bus.reply(msg, reply); } private void handle(APIListImageMsg msg) { List<ImageVO> vos = dbf.listAll(ImageVO.class); List<ImageInventory> invs = ImageInventory.valueOf(vos); APIListImageReply reply = new APIListImageReply(); reply.setInventories(invs); bus.reply(msg, reply); } @Deferred private void handle(final APIAddImageMsg msg) { String imageType = msg.getType(); imageType = imageType == null ? DefaultImageFactory.type.toString() : imageType; final APIAddImageEvent evt = new APIAddImageEvent(msg.getId()); ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); if (msg.getFormat().equals(ImageConstant.ISO_FORMAT_STRING)) { vo.setMediaType(ImageMediaType.ISO); } else { vo.setMediaType(ImageMediaType.valueOf(msg.getMediaType())); } vo.setType(imageType); vo.setSystem(msg.isSystem()); vo.setGuestOsType(msg.getGuestOsType()); vo.setFormat(msg.getFormat()); vo.setStatus(ImageStatus.Downloading); vo.setState(ImageState.Enabled); vo.setUrl(msg.getUrl()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); ImageFactory factory = getImageFacotry(ImageType.valueOf(imageType)); final ImageVO ivo = new SQLBatchWithReturn<ImageVO>() { @Override protected ImageVO scripts() { final ImageVO ivo = factory.createImage(vo, msg); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); return ivo; } }.execute(); List<ImageBackupStorageRefVO> refs = new ArrayList<>(); for (String uuid : msg.getBackupStorageUuids()) { ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setInstallPath(""); ref.setBackupStorageUuid(uuid); ref.setStatus(ImageStatus.Downloading); ref.setImageUuid(ivo.getUuid()); refs.add(ref); } dbf.persistCollection(refs); Defer.guard(() -> dbf.remove(ivo)); final ImageInventory inv = ImageInventory.valueOf(ivo); for (AddImageExtensionPoint ext : pluginRgty.getExtensionList(AddImageExtensionPoint.class)) { ext.preAddImage(inv); } final List<DownloadImageMsg> dmsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<DownloadImageMsg, String>() { @Override public DownloadImageMsg call(String arg) { DownloadImageMsg dmsg = new DownloadImageMsg(inv); dmsg.setBackupStorageUuid(arg); dmsg.setFormat(msg.getFormat()); dmsg.setSystemTags(msg.getSystemTags()); bus.makeTargetServiceIdByResourceUuid(dmsg, BackupStorageConstant.SERVICE_ID, arg); return dmsg; } }); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), ext -> ext.beforeAddImage(inv)); new LoopAsyncBatch<DownloadImageMsg>(msg) { AtomicBoolean success = new AtomicBoolean(false); @Override protected Collection<DownloadImageMsg> collect() { return dmsgs; } @Override protected AsyncBatchRunner forEach(DownloadImageMsg dmsg) { return new AsyncBatchRunner() { @Override public void run(NoErrorCompletion completion) { ImageBackupStorageRefVO ref = Q.New(ImageBackupStorageRefVO.class) .eq(ImageBackupStorageRefVO_.imageUuid, ivo.getUuid()) .eq(ImageBackupStorageRefVO_.backupStorageUuid, dmsg.getBackupStorageUuid()) .find(); bus.send(dmsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { errors.add(reply.getError()); dbf.remove(ref); } else { DownloadImageReply re = reply.castReply(); ref.setStatus(ImageStatus.Ready); ref.setInstallPath(re.getInstallPath()); if (dbf.reload(ref) == null) { logger.debug(String.format("image[uuid: %s] has been deleted", ref.getImageUuid())); completion.done(); return; } dbf.update(ref); if (success.compareAndSet(false, true)) { // In case 'Platform' etc. is changed. ImageVO vo = dbf.reload(ivo); vo.setMd5Sum(re.getMd5sum()); vo.setSize(re.getSize()); vo.setActualSize(re.getActualSize()); vo.setStatus(ImageStatus.Ready); dbf.update(vo); } logger.debug(String.format("successfully downloaded image[uuid:%s, name:%s] to backup storage[uuid:%s]", inv.getUuid(), inv.getName(), dmsg.getBackupStorageUuid())); } completion.done(); } }); } }; } @Override protected void done() { // check if the database still has the record of the image // if there is no record, that means user delete the image during the downloading, // then we need to cleanup ImageVO vo = dbf.reload(ivo); if (vo == null) { evt.setError(operr("image [uuid:%s] has been deleted", ivo.getUuid())); SQL.New("delete from ImageBackupStorageRefVO where imageUuid = :uuid") .param("uuid", ivo.getUuid()) .execute(); bus.publish(evt); return; } if (success.get()) { final ImageInventory einv = ImageInventory.valueOf(vo); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.afterAddImage(einv); } }); evt.setInventory(einv); } else { final ErrorCode err = errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, String.format("Failed to download image[name:%s] on all backup storage%s.", inv.getName(), msg.getBackupStorageUuids()), errors); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.failedToAddImage(inv, err); } }); dbf.remove(ivo); evt.setError(err); } bus.publish(evt); } }.start(); } @Override public String getId() { return bus.makeLocalServiceId(ImageConstant.SERVICE_ID); } private void populateExtensions() { for (ImageFactory f : pluginRgty.getExtensionList(ImageFactory.class)) { ImageFactory old = imageFactories.get(f.getType().toString()); if (old != null) { throw new CloudRuntimeException(String.format("duplicate ImageFactory[%s, %s] for type[%s]", f.getClass().getName(), old.getClass().getName(), f.getType())); } imageFactories.put(f.getType().toString(), f); } } @Override public boolean start() { populateExtensions(); installGlobalConfigUpdater(); return true; } private void installGlobalConfigUpdater() { ImageGlobalConfig.DELETION_POLICY.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_PERIOD.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); } private void startExpungeTask() { if (expungeTask != null) { expungeTask.cancel(true); } expungeTask = thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask() { private List<Tuple> getDeletedImageManagedByUs() { int qun = 1000; SimpleQuery q = dbf.createQuery(ImageBackupStorageRefVO.class); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); long amount = q.count(); int times = (int) (amount / qun) + (amount % qun != 0 ? 1 : 0); int start = 0; List<Tuple> ret = new ArrayList<Tuple>(); for (int i = 0; i < times; i++) { q = dbf.createQuery(ImageBackupStorageRefVO.class); q.select(ImageBackupStorageRefVO_.imageUuid, ImageBackupStorageRefVO_.lastOpDate, ImageBackupStorageRefVO_.backupStorageUuid); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); q.setLimit(qun); q.setStart(start); List<Tuple> ts = q.listTuple(); start += qun; for (Tuple t : ts) { String imageUuid = t.get(0, String.class); if (!destMaker.isManagedByUs(imageUuid)) { continue; } ret.add(t); } } return ret; } @Override public boolean run() { final List<Tuple> images = getDeletedImageManagedByUs(); if (images.isEmpty()) { logger.debug("[Image Expunge Task]: no images to expunge"); return false; } for (Tuple t : images) { String imageUuid = t.get(0, String.class); Timestamp date = t.get(1, Timestamp.class); String bsUuid = t.get(2, String.class); final Timestamp current = dbf.getCurrentSqlTime(); if (current.getTime() >= date.getTime() + TimeUnit.SECONDS.toMillis(ImageGlobalConfig.EXPUNGE_PERIOD.value(Long.class))) { ImageDeletionPolicy deletionPolicy = deletionPolicyMgr.getDeletionPolicy(imageUuid); if (ImageDeletionPolicy.Never == deletionPolicy) { logger.debug(String.format("the deletion policy[Never] is set for the image[uuid:%s] on the backup storage[uuid:%s]," + "don't expunge it", images, bsUuid)); continue; } ExpungeImageMsg msg = new ExpungeImageMsg(); msg.setImageUuid(imageUuid); msg.setBackupStorageUuid(bsUuid); bus.makeTargetServiceIdByResourceUuid(msg, ImageConstant.SERVICE_ID, imageUuid); bus.send(msg, new CloudBusCallBack(null) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { N.New(ImageVO.class, imageUuid).warn_("failed to expunge the image[uuid:%s] on the backup storage[uuid:%s], will try it later. %s", imageUuid, bsUuid, reply.getError()); } } }); } } return false; } @Override public TimeUnit getTimeUnit() { return TimeUnit.SECONDS; } @Override public long getInterval() { return ImageGlobalConfig.EXPUNGE_INTERVAL.value(Long.class); } @Override public String getName() { return "expunge-image"; } }); } @Override public boolean stop() { return true; } private ImageFactory getImageFacotry(ImageType type) { ImageFactory factory = imageFactories.get(type.toString()); if (factory == null) { throw new CloudRuntimeException(String.format("Unable to find ImageFactory with type[%s]", type)); } return factory; } @Override public void managementNodeReady() { startExpungeTask(); } @Override public List<Quota> reportQuota() { Quota.QuotaOperator checker = new Quota.QuotaOperator() { @Override public void checkQuota(APIMessage msg, Map<String, Quota.QuotaPair> pairs) { if (!new QuotaUtil().isAdminAccount(msg.getSession().getAccountUuid())) { if (msg instanceof APIAddImageMsg) { check((APIAddImageMsg) msg, pairs); } else if (msg instanceof APIRecoverImageMsg) { check((APIRecoverImageMsg) msg, pairs); } else if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } else { if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } } @Override public void checkQuota(NeedQuotaCheckMessage msg, Map<String, Quota.QuotaPair> pairs) { } @Override public List<Quota.QuotaUsage> getQuotaUsageByAccount(String accountUuid) { List<Quota.QuotaUsage> usages = new ArrayList<>(); ImageQuotaUtil.ImageQuota imageQuota = new ImageQuotaUtil().getUsed(accountUuid); Quota.QuotaUsage usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_NUM); usage.setUsed(imageQuota.imageNum); usages.add(usage); usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_SIZE); usage.setUsed(imageQuota.imageSize); usages.add(usage); return usages; } @Transactional(readOnly = true) private void check(APIChangeResourceOwnerMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getAccountUuid(); if (new QuotaUtil().isAdminAccount(resourceTargetOwnerAccountUuid)) { return; } SimpleQuery<AccountResourceRefVO> q = dbf.createQuery(AccountResourceRefVO.class); q.add(AccountResourceRefVO_.resourceUuid, Op.EQ, msg.getResourceUuid()); AccountResourceRefVO accResRefVO = q.find(); if (accResRefVO.getResourceType().equals(ImageVO.class.getSimpleName())) { long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getResourceUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } } @Transactional(readOnly = true) private void check(APIRecoverImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = new QuotaUtil().getResourceOwnerAccountUuid(msg.getImageUuid()); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getImageUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } @Transactional(readOnly = true) private void check(APIAddImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getSession().getAccountUuid(); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageNumAsked = 1; QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } new ImageQuotaUtil().checkImageSizeQuotaUseHttpHead(msg, pairs); } }; Quota quota = new Quota(); quota.setOperator(checker); quota.addMessageNeedValidation(APIAddImageMsg.class); quota.addMessageNeedValidation(APIRecoverImageMsg.class); quota.addMessageNeedValidation(APIChangeResourceOwnerMsg.class); Quota.QuotaPair p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_NUM); p.setValue(QuotaConstant.QUOTA_IMAGE_NUM); quota.addPair(p); p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_SIZE); p.setValue(QuotaConstant.QUOTA_IMAGE_SIZE); quota.addPair(p); return list(quota); } @Override @Transactional(readOnly = true) public void resourceOwnerPreChange(AccountResourceRefInventory ref, String newOwnerUuid) { } private void saveRefVOByBsInventorys(List<BackupStorageInventory> inventorys, String imageUuid) { List<ImageBackupStorageRefVO> refs = new ArrayList<>(); for (BackupStorageInventory backupStorageInventory : inventorys) { ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(backupStorageInventory.getUuid()); ref.setStatus(ImageStatus.Creating); ref.setImageUuid(imageUuid); ref.setInstallPath(""); refs.add(ref); } dbf.persistCollection(refs); } }
package org.pdxfinder.commands; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.lang3.StringUtils; import org.neo4j.ogm.json.JSONArray; import org.neo4j.ogm.json.JSONObject; import org.neo4j.ogm.session.Session; import org.pdxfinder.dao.*; import org.pdxfinder.services.DataImportService; import org.pdxfinder.services.ds.Standardizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Load data from IRCC. */ @Component @Order(value = 0) public class LoadIRCC implements CommandLineRunner { private final static Logger log = LoggerFactory.getLogger(LoadIRCC.class); private final static String DATASOURCE_ABBREVIATION = "IRCC-CRC"; private final static String DATASOURCE_NAME = "Candiolo Cancer Institute - Colorectal"; private final static String DATASOURCE_DESCRIPTION = "IRCC"; private final static String DATASOURCE_CONTACT = "andrea.bertotti@ircc.it"; private final static String PROVIDER_TYPE = ""; private final static String ACCESSIBILITY = ""; private final static String NSG_BS_NAME = "NOD scid gamma"; private final static String NSG_BS_SYMBOL = "NOD.Cg-Prkdc<sup>scid</sup> Il2rg<sup>tm1Wjl</sup>/SzJ"; //yay HTML in name private final static String NSG_BS_URL = "http://jax.org/strain/005557"; private final static String TECH = "MUT targeted NGS"; private final static String DOSING_STUDY_URL = "/platform/ircc-dosing-studies/"; private final static String TARGETEDNGS_PLATFORM_URL = "/platform/ircc-gene-panel/"; private final static String SOURCE_URL = "/source/ircc-crc/"; // for now all samples are of tumor tissue private final static Boolean NORMAL_TISSUE_FALSE = false; private final static String NOT_SPECIFIED = Standardizer.NOT_SPECIFIED; public static final String FINGERPRINT_DESCRIPTION = "Model validated against patient germline."; private HostStrain nsgBS; private Group irccDS; private Group projectGroup; private Options options; private CommandLineParser parser; private CommandLine cmd; private HelpFormatter formatter; private DataImportService dataImportService; private Session session; // samples -> markerAsssociations private HashMap<String, HashSet<MarkerAssociation>> markerAssociations = new HashMap(); private HashMap<String, HashMap<String, String>> specimenSamples = new HashMap(); private HashMap<String, HashMap<String, String>> modelSamples = new HashMap(); private HashSet<Integer> loadedModelHashes = new HashSet<>(); @Value("${irccpdx.url}") private String urlStr; @Value("${irccpdx.variation.url}") private String variationURLStr; @Value("${irccpdx.variation.max}") private int variationMax; @PostConstruct public void init() { formatter = new HelpFormatter(); } public LoadIRCC(DataImportService dataImportService) { this.dataImportService = dataImportService; } @Override public void run(String... args) throws Exception { OptionParser parser = new OptionParser(); parser.allowsUnrecognizedOptions(); parser.accepts("loadIRCC", "Load IRCC PDX data"); parser.accepts("loadALL", "Load all, including IRCC PDX data"); OptionSet options = parser.parse(args); if (options.has("loadIRCC") || options.has("loadALL")) { log.info("Loading IRCC PDX data."); irccDS = dataImportService.getProviderGroup(DATASOURCE_NAME, DATASOURCE_ABBREVIATION, DATASOURCE_DESCRIPTION, PROVIDER_TYPE, ACCESSIBILITY, "transnational access", DATASOURCE_CONTACT, SOURCE_URL); nsgBS = dataImportService.getHostStrain(NSG_BS_NAME, NSG_BS_SYMBOL, NSG_BS_URL, NSG_BS_NAME); projectGroup = dataImportService.getProjectGroup("EurOPDX"); if (urlStr != null) { log.info("Loading from URL " + urlStr); parseModels(parseURL(urlStr)); } if (variationURLStr != null && variationMax != 0) { loadVariants(variationURLStr, "TargetedNGS_MUT", "mutation"); } else { log.error("No irccpdx.url provided in properties"); } } } private void parseModels(String json) { try { JSONObject job = new JSONObject(json); JSONArray jarray = job.getJSONArray("IRCC"); for (int i = 0; i < jarray.length(); i++) { JSONObject j = jarray.getJSONObject(i); createGraphObjects(j); } } catch (Exception e) { log.error("Error getting IRCC PDX models", e); } } @Transactional void createGraphObjects(JSONObject job) throws Exception { if(loadedModelHashes.contains(job.toString().hashCode())) return; loadedModelHashes.add(job.toString().hashCode()); String id = job.getString("Model ID"); // the preference is for histology String diagnosis = job.getString("Clinical Diagnosis"); String classification = job.getString("Stage"); String stage = job.getString("Stage"); String age = Standardizer.getAge(job.getString("Age")); String gender = Standardizer.getGender(job.getString("Gender")); String patientId = job.getString("Patient ID"); String tumorType = Standardizer.getTumorType(job.getString("Tumor Type")); String primarySite = job.getString("Primary Site"); String sampleSite = job.getString("Sample Site"); Patient patient = dataImportService.getPatientWithSnapshots(patientId, irccDS); if(patient == null){ patient = dataImportService.createPatient(patientId, irccDS, gender, "", NOT_SPECIFIED); } PatientSnapshot pSnap = dataImportService.getPatientSnapshot(patient, age, "", "", ""); //String sourceSampleId, String dataSource, String typeStr, String diagnosis, String originStr, //String sampleSiteStr, String extractionMethod, Boolean normalTissue, String stage, String stageClassification, // String grade, String gradeClassification Sample ptSample = dataImportService.getSample(id, irccDS.getAbbreviation(), tumorType, diagnosis, primarySite, sampleSite, NOT_SPECIFIED, false, stage, "", "", ""); pSnap.addSample(ptSample); dataImportService.saveSample(ptSample); dataImportService.savePatientSnapshot(pSnap); List<ExternalUrl> externalUrls = new ArrayList<>(); externalUrls.add(dataImportService.getExternalUrl(ExternalUrl.Type.CONTACT, DATASOURCE_CONTACT)); QualityAssurance qa = new QualityAssurance(); if ("TRUE".equals(job.getString("Fingerprinting").toUpperCase())) { qa.setTechnology("Fingerprint"); qa.setDescription(FINGERPRINT_DESCRIPTION); // If the model includes which passages have had QA performed, set the passages on the QA node if (job.has("QA Passage") && !job.getString("QA Passage").isEmpty()) { List<String> passages = Stream.of(job.getString("QA Passage").split(",")) .map(String::trim) .distinct() .collect(Collectors.toList()); List<Integer> passageInts = new ArrayList<>(); // NOTE: IRCC uses passage 0 to mean Patient Tumor, so we need to harmonize according to the other // sources. Subtract 1 from every passage. for (String p : passages) { Integer intPassage = Integer.parseInt(p); passageInts.add(intPassage - 1); } qa.setPassages(StringUtils.join(passageInts, ", ")); } } ModelCreation modelCreation = dataImportService.createModelCreation(id, this.irccDS.getAbbreviation(), ptSample, qa, externalUrls); modelCreation.addGroup(projectGroup); JSONArray specimens = job.getJSONArray("Specimens"); for (int i = 0; i < specimens.length(); i++) { JSONObject specimenJSON = specimens.getJSONObject(i); String specimenId = specimenJSON.getString("Specimen ID"); Specimen specimen = dataImportService.getSpecimen(modelCreation, specimenId, irccDS.getAbbreviation(), specimenJSON.getString("Passage")); specimen.setHostStrain(this.nsgBS); EngraftmentSite is = dataImportService.getImplantationSite(specimenJSON.getString("Engraftment Site")); specimen.setEngraftmentSite(is); EngraftmentType it = dataImportService.getImplantationType(specimenJSON.getString("Engraftment Type")); specimen.setEngraftmentType(it); Sample specSample = new Sample(); specSample.setSourceSampleId(specimenId); specSample.setDataSource(irccDS.getAbbreviation()); specimen.setSample(specSample); modelCreation.addSpecimen(specimen); modelCreation.addRelatedSample(specSample); } //Create Treatment summary without linking TreatmentProtocols to specimens TreatmentSummary ts; try{ if(job.has("Treatment")){ JSONObject treatment = job.optJSONObject("Treatment"); //if the treatment attribute is not an object = it is an array if(treatment == null && job.optJSONArray("Treatment") != null){ JSONArray treatments = job.getJSONArray("Treatment"); if(treatments.length() > 0){ //log.info("Treatments found for model "+mc.getSourcePdxId()); ts = new TreatmentSummary(); ts.setUrl(DOSING_STUDY_URL); for(int t = 0; t<treatments.length(); t++){ JSONObject treatmentObject = treatments.getJSONObject(t); TreatmentProtocol tp = dataImportService.getTreatmentProtocol(treatmentObject.getString("Drug"), treatmentObject.getString("Dose"), treatmentObject.getString("Response Class"), ""); if(tp != null){ ts.addTreatmentProtocol(tp); } } ts.setModelCreation(modelCreation); modelCreation.setTreatmentSummary(ts); } } } } catch(Exception e){ e.printStackTrace(); } dataImportService.savePatient(patient); dataImportService.savePatientSnapshot(pSnap); dataImportService.saveModelCreation(modelCreation); } @Transactional public void loadVariants(String variationURLStr, String platformName, String molcharType){ log.info("Loading variation for platform "+platformName); //STEP 1: Save the platform Platform platform = dataImportService.getPlatform(platformName, this.irccDS); platform.setGroup(irccDS); platform.setUrl(TARGETEDNGS_PLATFORM_URL); dataImportService.savePlatform(platform); //STEP 2: get markers and save them with the platform linked try{ JSONObject job = new JSONObject(parseURL(variationURLStr)); JSONArray jarray = job.getJSONArray("IRCCVariation"); Set<String> markers = new HashSet<>(); log.info("Saving Markers to DB"); for (int i = 0; i < jarray.length(); i++) { JSONObject variation = jarray.getJSONObject(i); String gene = variation.getString("Gene"); markers.add(gene); } for(String m:markers){ Marker marker = dataImportService.getMarker(m, m); //PlatformAssociation pa = loaderUtils.createPlatformAssociation(platform, marker); //loaderUtils.savePlatformAssociation(pa); } log.info("Saved "+markers.size()+" to the DB."); //STEP 3: assemble MolecularCharacterization objects for samples //sampleId = > molchar HashMap<String, MolecularCharacterization> sampleMolCharMap = new HashMap(); for (int i = 0; i < jarray.length(); i++) { if (i == variationMax) { System.out.println("qutting after loading "+i+" variants"); break; } JSONObject variation = jarray.getJSONObject(i); String sample = variation.getString("Sample ID"); String specimen = variation.getString("Specimen ID"); String sampleId = variation.getString("Specimen ID"); String samplePlatformId = sampleId+"____"+platformName; String gene = variation.getString("Gene"); String type = variation.getString("Type"); Marker marker = dataImportService.getMarker(gene,gene); MarkerAssociation ma = new MarkerAssociation(); ma.setMarker(marker); ma.setType(type); ma.setCdsChange(variation.getString("CDS")); ma.setChromosome(variation.getString("Chrom")); ma.setConsequence(variation.getString("Effect")); ma.setSeqPosition(variation.getString("Pos")); ma.setRefAllele(variation.getString("Ref")); ma.setAltAllele(variation.getString("Alt")); ma.setAminoAcidChange(variation.getString("Protein")); ma.setAlleleFrequency(variation.getString("VAF")); ma.setRsVariants(variation.getString("avsnp147")); if(sampleMolCharMap.containsKey(sampleId)){ sampleMolCharMap.get(sampleId).addMarkerAssociation(ma); } else{ MolecularCharacterization mcNew = new MolecularCharacterization(); mcNew.setPlatform(platform); mcNew.setType(molcharType); mcNew.addMarkerAssociation(ma); sampleMolCharMap.put(sampleId,mcNew); } } //STEP 3: loop through sampleMolCharMap to hook mc objects to proper samples then save the graph for (Map.Entry<String, MolecularCharacterization> entry : sampleMolCharMap.entrySet()) { String sampleId = entry.getKey(); MolecularCharacterization mc = entry.getValue(); try{ Sample s = dataImportService.findSampleByDataSourceAndSourceSampleId(irccDS.getAbbreviation(), sampleId); if(s == null){ log.error("Sample not found: "+sampleId); } else{ s.addMolecularCharacterization(mc); dataImportService.saveSample(s); log.info("Saving molchar for sample: "+sampleId); } } catch(Exception e1){ log.error(sampleId); e1.printStackTrace(); } } } catch (Exception e){ e.printStackTrace(); } } @Transactional public void loadVariantsBySpecimen() { try { JSONObject job = new JSONObject(parseURL(variationURLStr)); JSONArray jarray = job.getJSONArray("IRCCVariation"); // System.out.println("loading "+jarray.length()+" variant records"); Platform platform = dataImportService.getPlatform(TECH, this.irccDS, TARGETEDNGS_PLATFORM_URL); platform.setGroup(irccDS); dataImportService.savePlatform(platform); for (int i = 0; i < jarray.length(); i++) { if (i == variationMax) { System.out.println("qutting after loading "+i+" variants"); break; } JSONObject variation = jarray.getJSONObject(i); String sample = variation.getString("Sample ID"); String specimen = variation.getString("Specimen ID"); // System.out.println("specimen "+specimen+" has sample "+sample); if(specimenSamples.containsKey(specimen)){ specimenSamples.get(specimen).put(sample, sample); }else{ HashMap<String,String> samples = new HashMap(); samples.put(sample,sample); specimenSamples.put(specimen,samples); } String gene = variation.getString("Gene"); String type = variation.getString("Type"); Marker marker = dataImportService.getMarker(gene,gene); MarkerAssociation ma = new MarkerAssociation(); ma.setMarker(marker); ma.setType(type); ma.setCdsChange(variation.getString("CDS")); ma.setChromosome(variation.getString("Chrom")); ma.setConsequence(variation.getString("Effect")); ma.setSeqPosition(variation.getString("Pos")); ma.setRefAllele(variation.getString("Ref")); ma.setAltAllele(variation.getString("Alt")); ma.setAminoAcidChange(variation.getString("Protein")); ma.setAlleleFrequency(variation.getString("VAF")); ma.setRsVariants(variation.getString("avsnp147")); PlatformAssociation pa = dataImportService.createPlatformAssociation(platform, marker); dataImportService.savePlatformAssociation(pa); if (markerAssociations.containsKey(sample)) { markerAssociations.get(sample).add(ma); } else { HashSet<MarkerAssociation> mas = new HashSet(); mas.add(ma); markerAssociations.put(sample, mas); } } } catch (Exception e) { log.error("Unable to load variants"); e.printStackTrace(); } } private String parseURL(String urlStr) { StringBuilder sb = new StringBuilder(); try { URL url = new URL(urlStr); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); } catch (Exception e) { log.error("Unable to read from IRCC JSON URL " + urlStr, e); } return sb.toString(); } }
package com.kii.thingif; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.kii.thingif.actions.AirConditionerActions; import com.kii.thingif.actions.HumidityActions; import com.kii.thingif.command.Action; import com.kii.thingif.command.Command; import com.kii.thingif.command.CommandState; import com.kii.thingif.query.HistoryState; import com.kii.thingif.states.AirConditionerState; import com.kii.thingif.states.HumidityState; import com.kii.thingif.trigger.Predicate; import com.kii.thingif.trigger.ServerCode; import com.kii.thingif.trigger.Trigger; import com.kii.thingif.trigger.TriggerOptions; import com.kii.thingif.trigger.TriggeredServerCodeResult; import com.kii.thingif.utils.JsonUtil; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Assert; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ThingIFAPITestBase extends SmallTestBase { protected final String APP_ID = "smalltest"; protected final String APP_KEY = "abcdefghijklmnopqrstuvwxyz123456789"; protected static final String BASE_PATH = "/thing-if/apps/smalltest"; protected static final String ALIAS1 = "AirConditionerAlias"; protected static final String ALIAS2 = "HumidityAlias"; private final String SDK_VERSION = "0.13.0"; protected MockWebServer server; protected static Map<String, Class<? extends Action>> getDefaultActionTypes () { Map<String, Class<? extends Action>> actionTypes = new HashMap<>(); actionTypes.put(ALIAS1, AirConditionerActions.class); actionTypes.put(ALIAS2, HumidityActions.class); return actionTypes; } protected static Map<String, Class<? extends TargetState>> getDefaultStateTypes () { Map<String, Class<? extends TargetState>> stateTypes = new HashMap<>(); stateTypes.put(ALIAS1, AirConditionerState.class); stateTypes.put(ALIAS2, HumidityState.class); return stateTypes; } protected void addMockResponseForOnBoard(int httpStatus, String thingID, String accessToken) { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (thingID != null && accessToken != null) { JsonObject responseBody = new JsonObject(); responseBody.addProperty("thingID", thingID); responseBody.addProperty("accessToken", accessToken); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected ThingIFAPI createDefaultThingIFAPI(Context context, String appID, String appKey) { String ownerID = UUID.randomUUID().toString(); Owner owner = new Owner(new TypedID(TypedID.Types.USER, ownerID), "owner-access-token-1234"); KiiApp app = getApp(appID, appKey); ThingIFAPI.Builder builder = ThingIFAPI.Builder.newBuilder( context, app, owner, getDefaultActionTypes(), getDefaultStateTypes()); return builder.build(); } protected ThingIFAPI.Builder createDefaultThingIFAPIBuilder(Context context, String appID, String appKey) throws Exception { String ownerID = UUID.randomUUID().toString(); Owner owner = new Owner(new TypedID(TypedID.Types.USER, ownerID), "owner-access-token-1234"); KiiApp app = getApp(appID, appKey); return ThingIFAPI.Builder.newBuilder( context, app, owner, getDefaultActionTypes(), getDefaultStateTypes()); } public KiiApp getApp(String appId, String appKey) { String hostName = server.getHostName(); KiiApp app = KiiApp.Builder.builderWithHostName(appId, appKey, hostName). setPort(server.getPort()).setURLSchema("http").build(); return app; } /** * Utilities of checking request header. * Don't include X-Kii-SDK header in expected param and don't remove it from * actual param. * @param expected * @param actual */ protected void assertRequestHeader(Map<String, String> expected, RecordedRequest actual) { Map<String, List<String>> actualMap = new HashMap<String, List<String>>(); for (String headerName : actual.getHeaders().names()) { actualMap.put(headerName, actual.getHeaders().values(headerName)); } // following headers are added by OkHttp client automatically. So we need to ignore them. actualMap.remove("Content-Length"); actualMap.remove("Host"); actualMap.remove("Connection"); actualMap.remove("Accept-Encoding"); actualMap.remove("User-Agent"); // Check X-Kii-SDK Header List<String> kiiSDK = actualMap.remove("X-Kii-SDK"); Assert.assertEquals(1, kiiSDK.size()); Pattern p = Pattern.compile("sn=at;sv=" + SDK_VERSION + ";pv=\\d*"); Matcher m = p.matcher(kiiSDK.get(0)); Assert.assertTrue(m.matches()); Assert.assertEquals("number of request headers", expected.size(), actualMap.size()); for (Map.Entry<String, String> h : expected.entrySet()) { String expectedHeaderValue = h.getValue(); if ("Content-Type".equalsIgnoreCase(h.getKey())) { // OkHttp adds charset to the Content-Type automatically. if (expectedHeaderValue.indexOf("; charset=utf-8") < 0) { expectedHeaderValue += "; charset=utf-8"; } } Assert.assertEquals("request header(" + h.getKey() + ")", expectedHeaderValue, actualMap.get(h.getKey()).get(0)); } } protected void assertRequestBody(String expected, RecordedRequest actual) { this.assertRequestBody(new JsonParser().parse(expected), actual); } protected void assertRequestBody(JSONObject expected, RecordedRequest actual) { this.assertRequestBody(new JsonParser().parse(expected.toString()), actual); } protected void assertRequestBody(JsonElement expected, RecordedRequest actual) { Assert.assertEquals("request body", expected, new JsonParser().parse(actual.getBody().readUtf8())); } protected void addEmptyMockResponse(int httpStatus) { this.server.enqueue(new MockResponse().setResponseCode(httpStatus)); } protected void clearSharedPreferences(Context context) throws Exception { SharedPreferences sharedPreferences = context.getSharedPreferences("com.kii.thingif.preferences", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); } protected void addMockResponseForPostNewCommand(int httpStatus, String commandID) { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (commandID != null) { JsonObject responseBody = new JsonObject(); responseBody.addProperty("commandID", commandID); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected void addMockResponseForGetCommand( int httpStatus, String commandID, TypedID issuer, TypedID target, JSONArray aliasActions, JSONArray aliasActionResults, CommandState state, Long created, Long modified, String firedByTriggerID, String title, String description, JSONObject metadata) { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (httpStatus == 200) { try { response.setBody( createCommandJson( commandID, issuer, target, aliasActions, aliasActionResults, state, firedByTriggerID, created, modified, title, description, metadata).toString()); }catch (JSONException ex) { throw new RuntimeException(ex); } } this.server.enqueue(response); } protected void addMockResponseForListCommands( int httpStatus, JSONArray commands, String paginationKey) throws JSONException{ MockResponse response = new MockResponse().setResponseCode(httpStatus); if (commands != null) { JSONObject responseBody = new JSONObject(); responseBody.put("commands", commands); if (paginationKey != null) { responseBody.put("nextPaginationKey", paginationKey); } response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected JSONObject createCommandJson( String commandID, TypedID issuer, TypedID target, JSONArray actions, JSONArray results, CommandState state, String firedTriggerID, Long created, Long modified, String title, String description, JSONObject metadata) throws JSONException{ JSONObject ret = new JSONObject(); ret.put("issuer", issuer.toString()); ret.put("actions", actions); if (commandID != null) { ret.put("commandID", commandID); } if (target != null) { ret.put("target", target.toString()); } if (results != null) { ret.put("actionResults", results); } if (state != null) { ret.put("commandState", state.name()); } if (firedTriggerID != null) { ret.put("firedByTriggerID", firedTriggerID); } if (created != null) { ret.put("createdAt", created); } if (modified != null) { ret.put("modifiedAt", modified); } if (title != null) { ret.put("title", title); } if (description != null) { ret.put("description", description); } if (metadata != null) { ret.put("metadata", metadata); } return ret; } protected void addMockResponseForGetTriggerWithCommand( int httpStatus, String triggerID, Command command, Predicate predicate, TriggerOptions options, Boolean disabled, String disabledReason) { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (httpStatus == 200) { JSONObject responseBody = JsonUtil.createTriggerJson( triggerID, command, null, predicate, options, disabled, disabledReason); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected void addMockResponseForGetTriggerWithServerCode( int httpStatus, String triggerID, ServerCode serverCode, Predicate predicate, TriggerOptions options, Boolean disabled, String disabledReason) throws Exception { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (httpStatus == 200) { JSONObject responseBody = JsonUtil.createTriggerJson( triggerID, null, serverCode, predicate, options, disabled, disabledReason); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected void addMockResponseForListTriggers(int httpStatus, Trigger[] triggers, String paginationKey) throws Exception{ MockResponse response = new MockResponse().setResponseCode(httpStatus); if (triggers != null) { JSONObject responseBody = new JSONObject(); JSONArray array = new JSONArray(); for (Trigger trigger : triggers) { array.put(JsonUtil.triggerToJson(trigger)); } responseBody.put("triggers", array); responseBody.putOpt("nextPaginationKey", paginationKey); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected void addMockResponseForPostNewTrigger(int httpStatus, String triggerID) { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (triggerID != null) { JsonObject responseBody = new JsonObject(); responseBody.addProperty("triggerID", triggerID); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected void addMockResponseForListTriggeredServerCodeResults( int httpStatus, TriggeredServerCodeResult[] results, String paginationKey) throws Exception{ MockResponse response = new MockResponse().setResponseCode(httpStatus); if (results != null) { JSONObject responseBody = new JSONObject(); JSONArray array = new JSONArray(); for (TriggeredServerCodeResult result : results) { array.put(JsonUtil.triggeredServerCodeResultToJson(result)); } responseBody.put("triggerServerCodeResults", array); responseBody.putOpt("nextPaginationKey", paginationKey); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected void addMockResponseForQueryUngroupedHistoryState( int httpStatus, List<HistoryState<? extends TargetState>> states, String paginationKey) throws Exception { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (httpStatus == 200) { JSONArray stateArray = new JSONArray(); for (HistoryState state : states) { stateArray.put(JsonUtil.historyStateToJson(state)); } JSONObject responseBody = new JSONObject(); responseBody.put("results", stateArray); responseBody.putOpt("nextPaginationKey", paginationKey); response.setBody(responseBody.toString()); } this.server.enqueue(response); } protected void assertTriggerOptions( TriggerOptions expected, Trigger actual) { Assert.assertEquals(expected.getTitle(), actual.getTitle()); Assert.assertEquals(expected.getDescription(), actual.getDescription()); assertJSONObject(expected.getMetadata(), actual.getMetadata()); } protected void addMockResponseForOnBoardEndnode(int httpStatus, String thingID, String accessToken) { MockResponse response = new MockResponse().setResponseCode(httpStatus); if (thingID != null && accessToken != null) { JsonObject responseBody = new JsonObject(); responseBody.addProperty("endNodeThingID", thingID); responseBody.addProperty("accessToken", accessToken); response.setBody(responseBody.toString()); } this.server.enqueue(response); } }
package com.thaiopensource.relaxng.input.dtd; import java.util.Hashtable; import java.util.Map; import java.util.Vector; import java.util.List; import java.util.Iterator; import com.thaiopensource.xml.dtd.om.*; import com.thaiopensource.xml.em.ExternalId; import com.thaiopensource.xml.util.WellKnownNamespaces; import com.thaiopensource.util.Localizer; import com.thaiopensource.relaxng.output.common.ErrorReporter; import com.thaiopensource.relaxng.edit.Pattern; import com.thaiopensource.relaxng.edit.TextPattern; import com.thaiopensource.relaxng.edit.NotAllowedPattern; import com.thaiopensource.relaxng.edit.ChoicePattern; import com.thaiopensource.relaxng.edit.EmptyPattern; import com.thaiopensource.relaxng.edit.GroupPattern; import com.thaiopensource.relaxng.edit.OneOrMorePattern; import com.thaiopensource.relaxng.edit.ZeroOrMorePattern; import com.thaiopensource.relaxng.edit.OptionalPattern; import com.thaiopensource.relaxng.edit.RefPattern; import com.thaiopensource.relaxng.edit.DataPattern; import com.thaiopensource.relaxng.edit.ValuePattern; import com.thaiopensource.relaxng.edit.AttributePattern; import com.thaiopensource.relaxng.edit.AttributeAnnotation; import com.thaiopensource.relaxng.edit.NameClass; import com.thaiopensource.relaxng.edit.Container; import com.thaiopensource.relaxng.edit.DefineComponent; import com.thaiopensource.relaxng.edit.Combine; import com.thaiopensource.relaxng.edit.ElementPattern; import com.thaiopensource.relaxng.edit.GrammarPattern; import com.thaiopensource.relaxng.edit.IncludeComponent; import com.thaiopensource.relaxng.edit.NameNameClass; import com.thaiopensource.relaxng.edit.SchemaCollection; import com.thaiopensource.relaxng.parse.SchemaBuilder; import org.xml.sax.SAXException; public class Converter { private ErrorReporter er; private SchemaCollection sc = new SchemaCollection(); private boolean inlineAttlistDecls = false; private boolean hadAny = false; private boolean hadDefaultValue = false; private Map elementNameTable = new Hashtable(); private Map attlistDeclTable = new Hashtable(); private Map defTable = new Hashtable(); private Map prefixTable = new Hashtable(); private String initialComment = null; private Map duplicateAttributeTable = new Hashtable(); private Map currentDuplicateAttributeTable = null; private String defaultNamespace = null; private String annotationPrefix = null; // These variables control the names use for definitions. private String colonReplacement = null; private String elementDeclPattern; private String attlistDeclPattern; private String anyName; private static final int ELEMENT_DECL = 01; private static final int ATTLIST_DECL = 02; private static final int ELEMENT_REF = 04; private static final String SEPARATORS = ".-_"; // # is the category; % is the name in the category private static final String DEFAULT_PATTERN = " private String[] ELEMENT_KEYWORDS = { "element", "elem", "e" }; private String[] ATTLIST_KEYWORDS = { "attlist", "attributes", "attribs", "atts", "a" }; private String[] ANY_KEYWORDS = { "any", "ANY", "anyElement" }; private static abstract class VisitorBase implements TopLevelVisitor { public void processingInstruction(String target, String value) throws Exception { } public void comment(String value) throws Exception { } public void flagDef(String name, Flag flag) throws Exception { } public void includedSection(Flag flag, TopLevel[] contents) throws Exception { for (int i = 0; i < contents.length; i++) contents[i].accept(this); } public void ignoredSection(Flag flag, String contents) throws Exception { } public void internalEntityDecl(String name, String value) throws Exception { } public void externalEntityDecl(String name, ExternalId externalId) throws Exception { } public void notationDecl(String name, ExternalId externalId) throws Exception { } public void nameSpecDef(String name, NameSpec nameSpec) throws Exception { } public void overriddenDef(Def def, boolean isDuplicate) throws Exception { } public void externalIdDef(String name, ExternalId externalId) throws Exception { } public void externalIdRef(String name, ExternalId externalId, String uri, String encoding, TopLevel[] contents) throws Exception { for (int i = 0; i < contents.length; i++) contents[i].accept(this); } public void paramDef(String name, String value) throws Exception { } public void attributeDefaultDef(String name, AttributeDefault ad) throws Exception { } } private class Analyzer extends VisitorBase implements ModelGroupVisitor, AttributeGroupVisitor { public void elementDecl(NameSpec nameSpec, ModelGroup modelGroup) throws Exception { noteElementName(nameSpec.getValue(), ELEMENT_DECL); modelGroup.accept(this); } public void attlistDecl(NameSpec nameSpec, AttributeGroup attributeGroup) throws Exception { noteElementName(nameSpec.getValue(), ATTLIST_DECL); if (inlineAttlistDecls) noteAttlist(nameSpec.getValue(), attributeGroup); attributeGroup.accept(this); } public void modelGroupDef(String name, ModelGroup modelGroup) throws Exception { noteDef(name); modelGroup.accept(this); } public void attributeGroupDef(String name, AttributeGroup attributeGroup) throws Exception { noteDef(name); attributeGroup.accept(this); } public void enumGroupDef(String name, EnumGroup enumGroup) { noteDef(name); } public void datatypeDef(String name, Datatype datatype) { noteDef(name); } public void choice(ModelGroup[] members) throws Exception { for (int i = 0; i < members.length; i++) members[i].accept(this); } public void sequence(ModelGroup[] members) throws Exception { for (int i = 0; i < members.length; i++) members[i].accept(this); } public void oneOrMore(ModelGroup member) throws Exception { member.accept(this); } public void zeroOrMore(ModelGroup member) throws Exception { member.accept(this); } public void optional(ModelGroup member) throws Exception { member.accept(this); } public void modelGroupRef(String name, ModelGroup modelGroup) { } public void elementRef(NameSpec name) { noteElementName(name.getValue(), ELEMENT_REF); } public void pcdata() { } public void any() { hadAny = true; } public void attribute(NameSpec nameSpec, Datatype datatype, AttributeDefault attributeDefault) { noteAttribute(nameSpec.getValue(), attributeDefault.getDefaultValue()); } public void attributeGroupRef(String name, AttributeGroup attributeGroup) { } } private class ComponentOutput extends VisitorBase { private final List components; ComponentOutput(Container container) { components = container.getComponents(); } public void elementDecl(NameSpec nameSpec, ModelGroup modelGroup) throws Exception { GroupPattern gp = new GroupPattern(); if (inlineAttlistDecls) { List groups = (List)attlistDeclTable.get(nameSpec.getValue()); if (groups != null) { currentDuplicateAttributeTable = new Hashtable(); AttributeGroupVisitor agv = new AttributeGroupOutput(gp); for (Iterator iter = groups.iterator(); iter.hasNext();) ((AttributeGroup)iter.next()).accept(agv); } } else gp.getChildren().add(ref(attlistDeclName(nameSpec.getValue()))); Pattern pattern = convert(modelGroup); if (gp.getChildren().size() > 0) { if (pattern instanceof GroupPattern) gp.getChildren().addAll(((GroupPattern)pattern).getChildren()); else gp.getChildren().add(pattern); pattern = gp; } components.add(new DefineComponent(elementDeclName(nameSpec.getValue()), new ElementPattern(convertQName(nameSpec.getValue(), true), pattern))); if (!inlineAttlistDecls && (nameFlags(nameSpec.getValue()) & ATTLIST_DECL) == 0) { DefineComponent dc = new DefineComponent(attlistDeclName(nameSpec.getValue()), new EmptyPattern()); dc.setCombine(Combine.INTERLEAVE); components.add(dc); } if (anyName != null) { DefineComponent dc = new DefineComponent(anyName, ref(elementDeclName(nameSpec.getValue()))); dc.setCombine(Combine.CHOICE); components.add(dc); } } public void attlistDecl(NameSpec nameSpec, AttributeGroup attributeGroup) throws Exception { if (inlineAttlistDecls) return; String name = nameSpec.getValue(); currentDuplicateAttributeTable = (Map)duplicateAttributeTable.get(name); if (currentDuplicateAttributeTable == null) { currentDuplicateAttributeTable = new Hashtable(); duplicateAttributeTable.put(name, currentDuplicateAttributeTable); } else { EmptyAttributeGroupDetector emptyDetector = new EmptyAttributeGroupDetector(); attributeGroup.accept(emptyDetector); if (!emptyDetector.containsAttribute) return; } DefineComponent dc = new DefineComponent(attlistDeclName(name), convert(attributeGroup)); dc.setCombine(Combine.INTERLEAVE); components.add(dc); } public void modelGroupDef(String name, ModelGroup modelGroup) throws Exception { components.add(new DefineComponent(name, convert(modelGroup))); } public void attributeGroupDef(String name, AttributeGroup attributeGroup) throws Exception { // This takes care of duplicates within the group currentDuplicateAttributeTable = new Hashtable(); Pattern pattern; AttributeGroupMember[] members = attributeGroup.getMembers(); if (members.length == 0) pattern = new EmptyPattern(); else { GroupPattern group = new GroupPattern(); AttributeGroupVisitor agv = new AttributeGroupOutput(group); for (int i = 0; i < members.length; i++) members[i].accept(agv); if (group.getChildren().size() == 1) pattern = (Pattern)group.getChildren().get(0); else pattern = group; } components.add(new DefineComponent(name, pattern)); } public void enumGroupDef(String name, EnumGroup enumGroup) throws Exception { ChoicePattern choice = new ChoicePattern(); enumGroup.accept(new EnumGroupOutput(choice)); Pattern pattern; if (choice.getChildren().size() == 1) pattern = (Pattern)choice.getChildren().get(0); else pattern = choice; components.add(new DefineComponent(name, pattern)); } public void datatypeDef(String name, Datatype datatype) throws Exception { components.add(new DefineComponent(name, convert(datatype))); } public void comment(String value) { // XXX } public void externalIdRef(String name, ExternalId externalId, String uri, String encoding, TopLevel[] contents) throws Exception { if (uri == null) { super.externalIdRef(name, externalId, uri, encoding, contents); return; } SignificanceDetector sd = new SignificanceDetector(); try { sd.externalIdRef(name, externalId, uri, encoding, contents); if (!sd.significant) return; } catch (Exception e) { throw (RuntimeException)e; } IncludeComponent ic = new IncludeComponent(uri); ic.setNs(defaultNamespace); components.add(ic); GrammarPattern included = new GrammarPattern(); TopLevelVisitor tlv = new ComponentOutput(included); for (int i = 0; i < contents.length; i++) contents[i].accept(tlv); // XXX what if included multiple times sc.getSchemas().put(uri, included); } } private class AttributeGroupOutput implements AttributeGroupVisitor { List group; AttributeGroupOutput(GroupPattern gp) { group = gp.getChildren(); } public void attribute(NameSpec nameSpec, Datatype datatype, AttributeDefault attributeDefault) throws Exception { String name = nameSpec.getValue(); if (currentDuplicateAttributeTable.get(name) != null) return; currentDuplicateAttributeTable.put(name, name); if (name.equals("xmlns") || name.startsWith("xmlns:")) { group.add(new EmptyPattern()); return; } String dv = attributeDefault.getDefaultValue(); String fv = attributeDefault.getFixedValue(); Pattern dt; if (fv != null) { String[] typeName = valueType(datatype); dt = new ValuePattern(typeName[0], typeName[1], fv); } else if (datatype.getType() != Datatype.CDATA) dt = convert(datatype); else dt = new TextPattern(); AttributePattern pattern = new AttributePattern(convertQName(name, false), dt); if (dv != null) { AttributeAnnotation anno = new AttributeAnnotation(WellKnownNamespaces.RELAX_NG_COMPATIBILITY_ANNOTATIONS, "defaultValue", dv); anno.setPrefix(annotationPrefix); pattern.getAttributeAnnotations().add(anno); } if (!attributeDefault.isRequired()) group.add(new OptionalPattern(pattern)); else group.add(pattern); } public void attributeGroupRef(String name, AttributeGroup attributeGroup) throws Exception { DuplicateAttributeDetector detector = new DuplicateAttributeDetector(); attributeGroup.accept(detector); if (detector.containsDuplicate) attributeGroup.accept(this); else { group.add(ref(name)); for (Iterator iter = detector.names.iterator(); iter.hasNext();) { String tem = (String)iter.next(); currentDuplicateAttributeTable.put(tem, tem); } } } } private class DatatypeOutput implements DatatypeVisitor { Pattern pattern; public void cdataDatatype() { pattern = new DataPattern("", "string"); } public void tokenizedDatatype(String typeName) { pattern = new DataPattern(WellKnownNamespaces.XML_SCHEMA_DATATYPES, typeName); } public void enumDatatype(EnumGroup enumGroup) throws Exception { if (enumGroup.getMembers().length == 0) pattern = new NotAllowedPattern(); else { ChoicePattern tem = new ChoicePattern(); pattern = tem; enumGroup.accept(new EnumGroupOutput(tem)); } } public void notationDatatype(EnumGroup enumGroup) throws Exception { enumDatatype(enumGroup); } public void datatypeRef(String name, Datatype datatype) { pattern = ref(name); } } private class EnumGroupOutput implements EnumGroupVisitor { final private List list; EnumGroupOutput(ChoicePattern choice) { list = choice.getChildren(); } public void enumValue(String value) { list.add(new ValuePattern("", "token", value)); } public void enumGroupRef(String name, EnumGroup enumGroup) { list.add(ref(name)); } } private class ModelGroupOutput implements ModelGroupVisitor { private Pattern pattern; public void choice(ModelGroup[] members) throws Exception { if (members.length == 0) pattern = new NotAllowedPattern(); else if (members.length == 1) members[0].accept(this); else { ChoicePattern tem = new ChoicePattern(); pattern = tem; List children = tem.getChildren(); for (int i = 0; i < members.length; i++) children.add(convert(members[i])); } } public void sequence(ModelGroup[] members) throws Exception { if (members.length == 0) pattern = new EmptyPattern(); else if (members.length == 1) members[0].accept(this); else { GroupPattern tem = new GroupPattern(); pattern = tem; List children = tem.getChildren(); for (int i = 0; i < members.length; i++) children.add(convert(members[i])); } } public void oneOrMore(ModelGroup member) throws Exception { pattern = new OneOrMorePattern(convert(member)); } public void zeroOrMore(ModelGroup member) throws Exception { pattern = new ZeroOrMorePattern(convert(member)); } public void optional(ModelGroup member) throws Exception { pattern = new OptionalPattern(convert(member)); } public void modelGroupRef(String name, ModelGroup modelGroup) { pattern = ref(name); } public void elementRef(NameSpec name) { pattern = ref(elementDeclName(name.getValue())); } public void pcdata() { pattern = new TextPattern(); } public void any() { pattern = new ZeroOrMorePattern(ref(anyName)); } } private class DuplicateAttributeDetector implements AttributeGroupVisitor { private boolean containsDuplicate = false; private List names = new Vector(); public void attribute(NameSpec nameSpec, Datatype datatype, AttributeDefault attributeDefault) { String name = nameSpec.getValue(); if (currentDuplicateAttributeTable.get(name) != null) containsDuplicate = true; names.add(name); } public void attributeGroupRef(String name, AttributeGroup attributeGroup) throws Exception { attributeGroup.accept(this); } } private class EmptyAttributeGroupDetector implements AttributeGroupVisitor { private boolean containsAttribute = false; public void attribute(NameSpec nameSpec, Datatype datatype, AttributeDefault attributeDefault) { if (currentDuplicateAttributeTable.get(nameSpec.getValue()) == null) containsAttribute = true; } public void attributeGroupRef(String name, AttributeGroup attributeGroup) throws Exception { attributeGroup.accept(this); } } private class SignificanceDetector extends VisitorBase { boolean significant = false; public void elementDecl(NameSpec nameSpec, ModelGroup modelGroup) throws Exception { significant = true; } public void attlistDecl(NameSpec nameSpec, AttributeGroup attributeGroup) throws Exception { significant = true; } public void modelGroupDef(String name, ModelGroup modelGroup) throws Exception { significant = true; } public void attributeGroupDef(String name, AttributeGroup attributeGroup) throws Exception { significant = true; } public void enumGroupDef(String name, EnumGroup enumGroup) { significant = true; } public void datatypeDef(String name, Datatype datatype) { significant = true; } } public Converter(ErrorReporter er) { this.er = er; } public SchemaCollection convertDtd(Dtd dtd) throws SAXException { try { dtd.accept(new Analyzer()); chooseNames(); if (defaultNamespace == null) defaultNamespace = SchemaBuilder.INHERIT_NS; GrammarPattern grammar = new GrammarPattern(); sc.setMainSchema(grammar); dtd.accept(new ComponentOutput(grammar)); outputUndefinedElements(grammar.getComponents()); outputStart(grammar.getComponents()); return sc; } catch (Exception e) { throw (RuntimeException)e; } } private void chooseNames() { chooseAny(); chooseColonReplacement(); chooseDeclPatterns(); chooseAnnotationPrefix(); } private void chooseAny() { if (!hadAny) return; for (int n = 0;; n++) { for (int i = 0; i < ANY_KEYWORDS.length; i++) { anyName = repeatChar('_', n) + ANY_KEYWORDS[i]; if (defTable.get(anyName) == null) { defTable.put(anyName, anyName); return; } } } } private void chooseAnnotationPrefix() { if (!hadDefaultValue) return; for (int n = 0;; n++) { annotationPrefix = repeatChar('_', n) + "a"; if (prefixTable.get(annotationPrefix) == null) return; } } private void chooseColonReplacement() { if (colonReplacementOk()) return; for (int n = 1;; n++) { for (int i = 0; i < SEPARATORS.length(); i++) { colonReplacement = repeatChar(SEPARATORS.charAt(i), n); if (colonReplacementOk()) return; } } } private boolean colonReplacementOk() { Hashtable table = new Hashtable(); for (Iterator iter = elementNameTable.keySet().iterator(); iter.hasNext();) { String name = mungeQName((String)iter.next()); if (table.get(name) != null) return false; table.put(name, name); } return true; } private void chooseDeclPatterns() { // XXX Try to match length and case of best prefix String pattern = namingPattern(); if (patternOk("%")) elementDeclPattern = "%"; else elementDeclPattern = choosePattern(pattern, ELEMENT_KEYWORDS); attlistDeclPattern = choosePattern(pattern, ATTLIST_KEYWORDS); } private String choosePattern(String metaPattern, String[] keywords) { for (;;) { for (int i = 0; i < keywords.length; i++) { String pattern = substitute(metaPattern, '#', keywords[i]); if (patternOk(pattern)) return pattern; } // add another separator metaPattern = (metaPattern.substring(0, 1) + metaPattern.substring(1, 2) + metaPattern.substring(1, 2) + metaPattern.substring(2)); } } private String namingPattern() { Map patternTable = new Hashtable(); for (Iterator iter = defTable.keySet().iterator(); iter.hasNext();) { String name = (String)iter.next(); for (int i = 0; i < SEPARATORS.length(); i++) { char sep = SEPARATORS.charAt(i); int k = name.indexOf(sep); if (k > 0) inc(patternTable, name.substring(0, k + 1) + "%"); k = name.lastIndexOf(sep); if (k >= 0 && k < name.length() - 1) inc(patternTable, "%" + name.substring(k)); } } String bestPattern = null; int bestCount = 0; for (Iterator iter = patternTable.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); int count = ((Integer)entry.getValue()).intValue(); if (bestPattern == null || count > bestCount) { bestCount = count; bestPattern = (String)entry.getKey(); } } if (bestPattern == null) return DEFAULT_PATTERN; if (bestPattern.charAt(0) == '%') return bestPattern.substring(0, 2) + " else return "#" + bestPattern.substring(bestPattern.length() - 2); } private static void inc(Map table, String str) { Integer n = (Integer)table.get(str); if (n == null) table.put(str, new Integer(1)); else table.put(str, new Integer(n.intValue() + 1)); } private boolean patternOk(String pattern) { for (Iterator iter = elementNameTable.keySet().iterator(); iter.hasNext();) { String name = mungeQName((String)iter.next()); if (defTable.get(substitute(pattern, '%', name)) != null) return false; } return true; } private void noteDef(String name) { defTable.put(name, name); } private void noteElementName(String name, int flags) { Integer n = (Integer)elementNameTable.get(name); if (n != null) { flags |= n.intValue(); if (n.intValue() == flags) return; } else noteNamePrefix(name); elementNameTable.put(name, new Integer(flags)); } private void noteAttlist(String name, AttributeGroup group) { List groups = (List)attlistDeclTable.get(name); if (groups == null) { groups = new Vector(); attlistDeclTable.put(name, groups); } groups.add(group); } private void noteAttribute(String name, String defaultValue) { if (name.equals("xmlns")) { if (defaultValue != null) { if (defaultNamespace != null && !defaultNamespace.equals(defaultValue)) error("INCONSISTENT_DEFAULT_NAMESPACE"); else defaultNamespace = defaultValue; } } else if (name.startsWith("xmlns:")) { if (defaultValue != null) { String prefix = name.substring(6); String ns = (String)prefixTable.get(prefix); if (ns != null && !ns.equals("") && !ns.equals(defaultValue)) error("INCONSISTENT_PREFIX", prefix); else if (!prefix.equals("xml")) prefixTable.put(prefix, defaultValue); } } else { if (defaultValue != null) hadDefaultValue = true; noteNamePrefix(name); } } private void noteNamePrefix(String name) { int i = name.indexOf(':'); if (i < 0) return; String prefix = name.substring(0, i); if (prefixTable.get(prefix) == null && !prefix.equals("xml")) prefixTable.put(prefix, ""); } private int nameFlags(String name) { Integer n = (Integer)elementNameTable.get(name); if (n == null) return 0; return n.intValue(); } private String elementDeclName(String name) { return substitute(elementDeclPattern, '%', mungeQName(name)); } private String attlistDeclName(String name) { return substitute(attlistDeclPattern, '%', mungeQName(name)); } private String mungeQName(String name) { if (colonReplacement == null) { int i = name.indexOf(':'); if (i < 0) return name; return name.substring(i + 1); } return substitute(name, ':', colonReplacement); } private static String repeatChar(char c, int n) { char[] buf = new char[n]; for (int i = 0; i < n; i++) buf[i] = c; return new String(buf); } /* Replace the first occurrence of ch in pattern by value. */ private static String substitute(String pattern, char ch, String value) { int i = pattern.indexOf(ch); if (i < 0) return pattern; StringBuffer buf = new StringBuffer(); buf.append(pattern.substring(0, i)); buf.append(value); buf.append(pattern.substring(i + 1)); return buf.toString(); } private void outputStart(List components) { ChoicePattern choice = new ChoicePattern(); components.add(new DefineComponent(DefineComponent.START, choice)); // Use the defined but unreferenced elements. // If there aren't any, use all defined elements. int mask = ELEMENT_REF|ELEMENT_DECL; for (;;) { boolean gotOne = false; for (Iterator iter = elementNameTable.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); if ((((Integer)entry.getValue()).intValue() & mask) == ELEMENT_DECL) { gotOne = true; choice.getChildren().add(ref(elementDeclName((String)entry.getKey()))); } } if (gotOne) break; if (mask == ELEMENT_DECL) break; mask = ELEMENT_DECL; } if (anyName != null) { DefineComponent dc = new DefineComponent(anyName, new TextPattern()); dc.setCombine(Combine.CHOICE); components.add(dc); } } private void outputUndefinedElements(List components) { for (Iterator iter = elementNameTable.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); if ((((Integer)entry.getValue()).intValue() & ELEMENT_DECL) == 0) { DefineComponent dc = new DefineComponent(elementDeclName((String)entry.getKey()), new NotAllowedPattern()); dc.setCombine(Combine.CHOICE); components.add(dc); } } } static private Pattern ref(String name) { return new RefPattern(name); } private void error(String key) { er.error(key, null); } private void error(String key, String arg) { er.error(key, arg, null); } private void warning(String key) { er.warning(key, null); } private void warning(String key, String arg) { er.warning(key, arg, null); } private static String[] valueType(Datatype datatype) { datatype = datatype.deref(); switch (datatype.getType()) { case Datatype.CDATA: return new String[] { "", "string" }; case Datatype.TOKENIZED: return new String[] { WellKnownNamespaces.XML_SCHEMA_DATATYPES, ((TokenizedDatatype)datatype).getTypeName() }; } return new String[] { "", "token" }; } private Pattern convert(ModelGroup mg) throws Exception { ModelGroupOutput mgo = new ModelGroupOutput(); mg.accept(mgo); return mgo.pattern; } private Pattern convert(Datatype dt) throws Exception { DatatypeOutput dto = new DatatypeOutput(); dt.accept(dto); return dto.pattern; } private Pattern convert(AttributeGroup ag) throws Exception { GroupPattern group = new GroupPattern(); ag.accept(new AttributeGroupOutput(group)); if (group.getChildren().size() == 1) return (Pattern)group.getChildren().get(0); return group; } private NameClass convertQName(String name, boolean useDefault) { int i = name.indexOf(':'); if (i < 0) return new NameNameClass(useDefault ? defaultNamespace : "", name); String prefix = name.substring(0, i); String localName = name.substring(i + 1); String ns; if (prefix.equals("xml")) ns = WellKnownNamespaces.XML; else { ns = (String)prefixTable.get(prefix); if (ns.equals("")) { error("UNDECLARED_PREFIX", prefix); ns = prefix; } } NameNameClass nnc = new NameNameClass(ns, localName); nnc.setPrefix(prefix); return nnc; } }
package com.thaiopensource.relaxng.output.rng; import com.thaiopensource.relaxng.edit.AbstractVisitor; import com.thaiopensource.relaxng.edit.DefineComponent; import com.thaiopensource.relaxng.edit.DivComponent; import com.thaiopensource.relaxng.edit.IncludeComponent; import com.thaiopensource.relaxng.edit.GrammarPattern; import com.thaiopensource.relaxng.edit.Container; import com.thaiopensource.relaxng.edit.Component; import com.thaiopensource.relaxng.edit.UnaryPattern; import com.thaiopensource.relaxng.edit.CompositePattern; import com.thaiopensource.relaxng.edit.Pattern; import com.thaiopensource.relaxng.edit.NameClassedPattern; import com.thaiopensource.relaxng.edit.ChoiceNameClass; import com.thaiopensource.relaxng.edit.NameClass; import com.thaiopensource.relaxng.edit.ValuePattern; import com.thaiopensource.relaxng.edit.DataPattern; import com.thaiopensource.relaxng.edit.NameNameClass; import com.thaiopensource.relaxng.edit.AnyNameNameClass; import com.thaiopensource.relaxng.edit.NsNameNameClass; import com.thaiopensource.relaxng.edit.Annotated; import com.thaiopensource.relaxng.edit.AttributeAnnotation; import com.thaiopensource.relaxng.edit.AnnotationChild; import com.thaiopensource.relaxng.edit.ElementAnnotation; import com.thaiopensource.relaxng.parse.Context; import com.thaiopensource.xml.util.WellKnownNamespaces; import java.util.List; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.Enumeration; class Analyzer extends AbstractVisitor { private Object visitAnnotated(Annotated anno) { if (anno.getAttributeAnnotations().size() > 0 || anno.getChildElementAnnotations().size() > 0 || anno.getFollowingElementAnnotations().size() > 0) noteContext(anno.getContext()); visitAnnotationAttributes(anno.getAttributeAnnotations()); visitAnnotationChildren(anno.getChildElementAnnotations()); visitAnnotationChildren(anno.getFollowingElementAnnotations()); return null; } void visitAnnotationAttributes(List list) { for (int i = 0, len = list.size(); i < len; i++) { AttributeAnnotation att = (AttributeAnnotation)list.get(i); if (att.getNamespaceUri().length() != 0) noteNs(att.getPrefix(), att.getNamespaceUri()); } } void visitAnnotationChildren(List list) { for (int i = 0, len = list.size(); i < len; i++) { AnnotationChild ac = (AnnotationChild)list.get(i); if (ac instanceof ElementAnnotation) { ElementAnnotation elem = (ElementAnnotation)ac; if (elem.getPrefix() != null) noteNs(elem.getPrefix(), elem.getNamespaceUri()); visitAnnotationAttributes(elem.getAttributes()); visitAnnotationChildren(elem.getChildren()); } } } public Object visitPattern(Pattern p) { return visitAnnotated(p); } public Object visitDefine(DefineComponent c) { visitAnnotated(c); return c.getBody().accept(this); } public Object visitDiv(DivComponent c) { visitAnnotated(c); return visitContainer(c); } public Object visitInclude(IncludeComponent c) { visitAnnotated(c); return visitContainer(c); } public Object visitGrammar(GrammarPattern p) { visitAnnotated(p); return visitContainer(p); } public Object visitContainer(Container c) { List list = c.getComponents(); for (int i = 0, len = list.size(); i < len; i++) ((Component)list.get(i)).accept(this); return null; } public Object visitUnary(UnaryPattern p) { visitAnnotated(p); return p.getChild().accept(this); } public Object visitComposite(CompositePattern p) { visitAnnotated(p); List list = p.getChildren(); for (int i = 0, len = list.size(); i < len; i++) ((Pattern)list.get(i)).accept(this); return null; } public Object visitNameClassed(NameClassedPattern p) { p.getNameClass().accept(this); return visitUnary(p); } public Object visitChoice(ChoiceNameClass nc) { visitAnnotated(nc); List list = nc.getChildren(); for (int i = 0, len = list.size(); i < len; i++) ((NameClass)list.get(i)).accept(this); return null; } public Object visitValue(ValuePattern p) { visitAnnotated(p); if (!p.getType().equals("token") || !p.getDatatypeLibrary().equals("")) noteDatatypeLibrary(p.getDatatypeLibrary()); for (Iterator iter = p.getPrefixMap().entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); noteNs((String)entry.getKey(), (String)entry.getValue()); } return null; } public Object visitData(DataPattern p) { visitAnnotated(p); noteDatatypeLibrary(p.getDatatypeLibrary()); Pattern except = p.getExcept(); if (except != null) except.accept(this); return null; } public Object visitName(NameNameClass nc) { visitAnnotated(nc); noteNs(nc.getPrefix(), nc.getNamespaceUri()); return null; } public Object visitAnyName(AnyNameNameClass nc) { visitAnnotated(nc); NameClass except = nc.getExcept(); if (except != null) except.accept(this); return null; } public Object visitNsName(NsNameNameClass nc) { visitAnnotated(nc); noteNs(null, nc.getNs()); NameClass except = nc.getExcept(); if (except != null) except.accept(this); return null; } private String datatypeLibrary = null; private final Map prefixMap = new HashMap(); private boolean haveInherit = false; private Context lastContext = null; private void noteDatatypeLibrary(String uri) { if (datatypeLibrary == null || datatypeLibrary.length() == 0) datatypeLibrary = uri; } private void noteNs(String prefix, String ns) { if (ns == NameClass.INHERIT_NS) { haveInherit = true; return; } if (ns == null || ns.length() == 0) return; if (prefix == null) prefix = ""; prefixMap.put(prefix, ns); } private void noteContext(Context context) { if (context == null || context == lastContext) return; lastContext = context; for (Enumeration enum = context.prefixes(); enum.hasMoreElements();) { String prefix = (String)enum.nextElement(); noteNs(prefix, context.resolveNamespacePrefix(prefix)); } } Map getPrefixMap() { if (haveInherit) prefixMap.remove(""); prefixMap.put("xml", WellKnownNamespaces.XML); return prefixMap; } String getDatatypeLibrary() { return datatypeLibrary; } }
package org.ops4j.pax.web.itest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.cleanCaches; import static org.ops4j.pax.exam.CoreOptions.frameworkProperty; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemPackages; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.workingDirectory; import static org.ops4j.pax.exam.CoreOptions.wrappedBundle; import static org.ops4j.pax.exam.MavenUtils.asInProject; import static org.ops4j.pax.exam.OptionUtils.combine; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.List; import javax.inject.Inject; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Before; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.EagerSingleStagedReactorFactory; import org.ops4j.pax.web.service.spi.ServletEvent; import org.ops4j.pax.web.service.spi.ServletListener; import org.ops4j.pax.web.service.spi.WebEvent; import org.ops4j.pax.web.service.spi.WebListener; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ExamReactorStrategy(EagerSingleStagedReactorFactory.class) public class ITestBase { protected class ServletListenerImpl implements ServletListener { private boolean event = false; @Override public void servletEvent(ServletEvent event) { LOG.info("Got event: " + event); if (event.getType() == 2) this.event = true; } public boolean gotEvent() { return event; } } protected Logger LOG = LoggerFactory.getLogger(getClass()); @Inject protected BundleContext bundleContext; protected static final String WEB_CONTEXT_PATH = "Web-ContextPath"; protected static final String WEB_CONNECTORS = "Web-Connectors"; protected static final String WEB_VIRTUAL_HOSTS = "Web-VirtualHosts"; protected static final String WEB_BUNDLE = "webbundle:"; protected static final String REALM_NAME = "realm.properties"; protected DefaultHttpClient httpclient; protected WebListener webListener; protected ServletListener servletListener; public static Option[] baseConfigure() { return options( workingDirectory("target/paxexam/"), cleanCaches(true), junitBundles(), frameworkProperty("osgi.console").value("6666"), frameworkProperty("felix.bootdelegation.implicit").value( "false"), // frameworkProperty("felix.log.level").value("4"), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level") .value("INFO"), systemProperty("org.osgi.service.http.hostname").value( "127.0.0.1"), systemProperty("org.osgi.service.http.port").value("8181"), systemProperty("java.protocol.handler.pkgs").value( "org.ops4j.pax.url"), systemProperty("org.ops4j.pax.url.war.importPaxLoggingPackages") .value("true"), systemProperty("org.ops4j.pax.web.log.ncsa.enabled").value( "true"), systemProperty("org.ops4j.pax.web.log.ncsa.directory").value( "target/logs"), systemProperty("ProjectVersion").value(getProjectVersion()), // javax.servlet may be on the system classpath so we need to // make sure // that all bundles load it from there systemPackages("javax.servlet;version=2.6.0", "javax.servlet;version=3.0.0"), // do not include pax-logging-api, this is already provisioned // by Pax Exam mavenBundle().groupId("org.ops4j.pax.logging") .artifactId("pax-logging-service").version("1.6.4"), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-war").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-wrap").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-commons").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.swissbox") .artifactId("pax-swissbox-bnd").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.swissbox") .artifactId("pax-swissbox-property") .version(asInProject()), mavenBundle().groupId("biz.aQute").artifactId("bndlib") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-spi").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-api").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-extender-war") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-extender-whiteboard") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-runtime").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-jsp").version(asInProject()), mavenBundle().groupId("org.eclipse.jdt.core.compiler") .artifactId("ecj").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-servlet_3.0_spec") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-aether").version(asInProject()), mavenBundle("commons-codec", "commons-codec").version( asInProject()), wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpclient", "4.1")), wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpcore", "4.1"))); } public static Option[] configureJetty() { return combine( baseConfigure(), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-jetty").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-util").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-io").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-http").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-continuation") .version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-server").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-security").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-xml").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-servlet").version(asInProject())); } public static Option[] configureTomcat() { return combine( baseConfigure(), systemPackages("javax.xml.namespace;version=1.0.0", "javax.transaction;version=1.1.0", "javax.servlet;version=2.6.0", "javax.servlet;version=3.0.0", "javax.servlet.descriptor;version=2.6.0", "javax.servlet.descriptor;version=3.0.0" ), systemProperty("org.osgi.service.http.hostname").value("127.0.0.1"), systemProperty("org.osgi.service.http.port").value("8282"), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-tomcat").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.ext.tomcat") .artifactId("catalina").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.ext.tomcat") .artifactId("shared").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.ext.tomcat") .artifactId("util").version(asInProject()), mavenBundle().groupId("org.apache.servicemix.specs") .artifactId("org.apache.servicemix.specs.saaj-api-1.3") .version(asInProject()), mavenBundle().groupId("org.apache.servicemix.specs") .artifactId("org.apache.servicemix.specs.jaxb-api-2.2") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-jaxws_2.2_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-jaxrpc_1.1_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-servlet_3.0_spec") .version(asInProject()), mavenBundle() .groupId("org.apache.servicemix.specs") .artifactId( "org.apache.servicemix.specs.jsr303-api-1.0.0") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-annotation_1.1_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-activation_1.1_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-stax-api_1.2_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-ejb_3.1_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-jpa_2.0_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-javamail_1.4_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-osgi-registry") .version(asInProject())); } @Before public void setUpITestBase() throws Exception { httpclient = new DefaultHttpClient(); } @After public void tearDown() throws Exception { httpclient.clearRequestInterceptors(); httpclient.clearResponseInterceptors(); httpclient = null; } protected static String getProjectVersion() { String projectVersion = System.getProperty("ProjectVersion"); System.out.println("*** The ProjectVersion is " + projectVersion + " ***"); return projectVersion; } protected static String getMyFacesVersion() { String myFacesVersion = System.getProperty("MyFacesVersion"); System.out.println("*** The MyFacesVersion is " + myFacesVersion + " ***"); return myFacesVersion; } /** * @return * @return * @throws IOException * @throws CertificateException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws KeyManagementException * @throws HttpException */ protected String testWebPath(String path, String expectedContent) throws Exception { return testWebPath(path, expectedContent, 200, false); } protected String testWebPath(String path, int httpRC) throws Exception { return testWebPath(path, null, httpRC, false); } protected String testWebPath(String path, String expectedContent, int httpRC, boolean authenticate) throws Exception { return testWebPath(path, expectedContent, httpRC, authenticate, null); } protected String testWebPath(String path, String expectedContent, int httpRC, boolean authenticate, BasicHttpContext basicHttpContext) throws Exception { int count = 0; while (!checkServer(path) && count++ < 5) if (count > 5) break; HttpResponse response = null; response = getHttpResponse(path, authenticate, basicHttpContext); assertEquals("HttpResponseCode", httpRC, response.getStatusLine() .getStatusCode()); String responseBodyAsString = null; if (expectedContent != null) { responseBodyAsString = EntityUtils.toString(response.getEntity()); assertTrue(responseBodyAsString.contains(expectedContent)); } return responseBodyAsString; } private boolean isSecuredConnection(String path) { int schemeSeperator = path.indexOf(":"); String scheme = path.substring(0, schemeSeperator); if ("https".equalsIgnoreCase(scheme)) return true; return false; } protected void testPost(String path, List<NameValuePair> nameValuePairs, String expectedContent, int httpRC) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(path); post.setEntity(new UrlEncodedFormEntity( (List<NameValuePair>) nameValuePairs)); HttpResponse response = httpclient.execute(post); assertEquals("HttpResponseCode", httpRC, response.getStatusLine() .getStatusCode()); if (expectedContent != null) { String responseBodyAsString = EntityUtils.toString(response .getEntity()); assertTrue(responseBodyAsString.contains(expectedContent)); } } protected HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext) throws IOException, ClientProtocolException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException { HttpGet httpget = null; HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("src/test/resources/keystore")); try { trustStore.load(instream, "password".toCharArray()); } finally { try { instream.close(); } catch (Exception ignore) {} } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme("https", 443, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); HttpHost targetHost = getHttpHost(path); // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext; if (authenticate) { ((DefaultHttpClient) httpclient).getCredentialsProvider() .setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); } httpget = new HttpGet(path); HttpResponse response = null; if (!authenticate && basicHttpContext == null) response = httpclient.execute(httpget); else response = httpclient.execute(targetHost, httpget, localcontext); return response; } private HttpHost getHttpHost(String path) { int schemeSeperator = path.indexOf(":"); String scheme = path.substring(0, schemeSeperator); int portSeperator = path.lastIndexOf(":"); String hostname = path.substring(schemeSeperator+3, portSeperator); int port = Integer.parseInt(path.substring(portSeperator+1, portSeperator+5)); HttpHost targetHost = new HttpHost(hostname, port, scheme); return targetHost; } protected boolean checkServer(String path) throws Exception { LOG.info("checking server path {}", path); HttpGet httpget = null; HttpClient myHttpClient = new DefaultHttpClient(); HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("src/test/resources/keystore")); try { trustStore.load(instream, "password".toCharArray()); } finally { try { instream.close(); } catch (Exception ignore) {} } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme("https", 443, socketFactory); myHttpClient.getConnectionManager().getSchemeRegistry().register(sch); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); HttpHost targetHost = getHttpHost(path); // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); httpget = new HttpGet("/"); LOG.info("calling remote ..."); HttpResponse response = null; try { response = myHttpClient.execute(targetHost, httpget); } catch (IOException ioe) { LOG.info("... caught IOException"); return false; } int statusCode = response.getStatusLine().getStatusCode(); LOG.info("... respondet with: {}", statusCode); if (statusCode == 404 || statusCode == 200) return true; else return false; } protected void initWebListener() { webListener = new WebListenerImpl(); bundleContext.registerService(WebListener.class.getName(), webListener, null); } protected void initServletListener() { servletListener = new ServletListenerImpl(); bundleContext.registerService(ServletListener.class.getName(), servletListener, null); } /** * @throws InterruptedException */ protected void waitForWebListener() throws InterruptedException { int count = 0; while (!((WebListenerImpl) webListener).gotEvent() && count < 100) { synchronized (this) { this.wait(100); count++; } } LOG.info("waited for bundle startup for {} seconds", count*100); } protected void waitForServletListener() throws InterruptedException { int count = 0; while (!((ServletListenerImpl)servletListener).gotEvent() && count < 100) { synchronized (this) { this.wait(100); count++; } } LOG.info("waited for servlet startup for {} seconds", count*100); } }
package net.iaeste.iws.api.dtos; import net.iaeste.iws.api.constants.IWSConstants; import net.iaeste.iws.api.util.AbstractVerification; import java.util.HashMap; import java.util.Map; public final class Address extends AbstractVerification { /** {@link IWSConstants#SERIAL_VERSION_UID}. */ private static final long serialVersionUID = IWSConstants.SERIAL_VERSION_UID; /** * Most fields of type String in this Object, are allowed to be as big as * this number. */ private static final int FIELD_LENGTH = 100; private static final int ZIP_LENGTH = 12; private String street1 = null; private String street2 = null; private String zip = null; private String city = null; private String state = null; private String pobox = null; private Country country = null; // Object Constructors /** * Empty Constructor, to use if the setters are invoked. This is required * for WebServices to work properly. */ public Address() { } /** * Copy Constructor. * * @param address Address Object to copy */ public Address(final Address address) { if (address != null) { street1 = address.street1; street2 = address.street2; zip = address.zip; city = address.city; state = address.state; pobox = address.pobox; country = new Country(address.country); } } // Standard Setters & Getters public void setStreet1(final String street1) throws IllegalArgumentException { ensureNotTooLong("street1", street1, FIELD_LENGTH); this.street1 = street1; } public String getStreet1() { return street1; } public void setStreet2(final String street2) throws IllegalArgumentException { ensureNotTooLong("street2", street2, FIELD_LENGTH); this.street2 = street2; } public String getStreet2() { return street2; } public void setZip(final String zip) throws IllegalArgumentException { ensureNotTooLong("zip", zip, ZIP_LENGTH); this.zip = zip; } public String getZip() { return zip; } public void setCity(final String city) throws IllegalArgumentException { ensureNotTooLong("city", city, FIELD_LENGTH); this.city = city; } public String getCity() { return city; } public void setState(final String state) throws IllegalArgumentException { ensureNotTooLong("state", state, FIELD_LENGTH); this.state = state; } public String getState() { return state; } public void setPobox(final String pobox) throws IllegalArgumentException { ensureNotTooLong("pobox", pobox, FIELD_LENGTH); this.pobox = pobox; } public String getPobox() { return pobox; } public void setCountry(final Country country) throws IllegalArgumentException { ensureVerifiable("country", country); this.country = new Country(country); } public Country getCountry() { return new Country(country); } // Standard DTO Methods /** * {@inheritDoc} */ @Override public Map<String, String> validate() { // Since an Address is an optional Object, we're not going to make any // validity checks here return new HashMap<>(0); } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof Address)) { return false; } final Address address = (Address) obj; if (street1 != null ? !street1.equals(address.street1) : address.street1 != null) { return false; } if (street2 != null ? !street2.equals(address.street2) : address.street2 != null) { return false; } if (zip != null ? !zip.equals(address.zip) : address.zip != null) { return false; } if (city != null ? !city.equals(address.city) : address.city != null) { return false; } if (state != null ? !state.equals(address.state) : address.state != null) { return false; } return !(country != null ? !country.equals(address.country) : address.country != null); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = IWSConstants.HASHCODE_INITIAL_VALUE; result = IWSConstants.HASHCODE_MULTIPLIER * result + (street1 != null ? street1.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (street2 != null ? street2.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (zip != null ? zip.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (city != null ? city.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (state != null ? state.hashCode() : 0); result = IWSConstants.HASHCODE_MULTIPLIER * result + (country != null ? country.hashCode() : 0); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "Address{" + ", street1='" + street1 + '\'' + ", street2='" + street2 + '\'' + ", zip='" + zip + '\'' + ", city='" + city + '\'' + ", state='" + state + '\'' + ", country=" + country + '}'; } }
package com.intellij.uiDesigner; import com.intellij.lang.properties.PropertiesReferenceManager; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.uiDesigner.compiler.AsmCodeGenerator; import com.intellij.uiDesigner.componentTree.ComponentTreeBuilder; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.designSurface.ComponentDropLocation; import com.intellij.uiDesigner.designSurface.DraggedComponentList; import com.intellij.uiDesigner.designSurface.GuiEditor; import com.intellij.uiDesigner.designSurface.Painter; import com.intellij.uiDesigner.editor.UIFormEditor; import com.intellij.uiDesigner.lw.*; import com.intellij.uiDesigner.palette.ComponentItem; import com.intellij.uiDesigner.palette.Palette; import com.intellij.uiDesigner.propertyInspector.UIDesignerToolWindowManager; import com.intellij.uiDesigner.propertyInspector.properties.BindingProperty; import com.intellij.uiDesigner.propertyInspector.properties.IntroComponentProperty; import com.intellij.uiDesigner.radComponents.RadAbstractGridLayoutManager; import com.intellij.uiDesigner.radComponents.RadComponent; import com.intellij.uiDesigner.radComponents.RadContainer; import com.intellij.uiDesigner.radComponents.RadRootContainer; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; /** * @author Anton Katilin * @author Vladimir Kondratyev */ public final class FormEditingUtil { private FormEditingUtil() { } public static boolean canDeleteSelection(final GuiEditor editor){ final ArrayList<RadComponent> selection = getSelectedComponents(editor); if (selection.isEmpty()) return false; final RadRootContainer rootContainer = editor.getRootContainer(); if (rootContainer.getComponentCount() > 0 && selection.contains(rootContainer.getComponent(0))) { return false; } return true; } /** * <b>This method must be executed in command</b> * * @param editor the editor in which the selection is deleted. */ public static void deleteSelection(final GuiEditor editor){ final List<RadComponent> selection = getSelectedComponents(editor); deleteComponents(selection, true); editor.refreshAndSave(true); } public static void deleteComponents(final Collection<? extends RadComponent> selection, boolean deleteEmptyCells) { if (selection.size() == 0) { return; } final RadRootContainer rootContainer = (RadRootContainer) getRoot(selection.iterator().next()); final Set<String> deletedComponentIds = new HashSet<String>(); for (final RadComponent component : selection) { boolean wasSelected = component.isSelected(); final RadContainer parent = component.getParent(); boolean wasPackedHorz = false; boolean wasPackedVert = false; if (parent.getParent() != null && parent.getParent().isXY()) { final Dimension minSize = parent.getMinimumSize(); wasPackedHorz = parent.getWidth() == minSize.width; wasPackedVert = parent.getHeight() == minSize.height; } FormEditingUtil.iterate(component, new ComponentVisitor() { public boolean visit(final IComponent c) { RadComponent rc = (RadComponent) c; BindingProperty.checkRemoveUnusedField(rootContainer, rc.getBinding(), null); deletedComponentIds.add(rc.getId()); return true; } }); GridConstraints delConstraints = parent.getLayoutManager().isGrid() ? component.getConstraints() : null; int index = parent.indexOfComponent(component); parent.removeComponent(component); if (wasSelected) { if (parent.getComponentCount() > index) { parent.getComponent(index).setSelected(true); } else if (index > 0 && parent.getComponentCount() == index) { parent.getComponent(index-1).setSelected(true); } else { parent.setSelected(true); } } if (delConstraints != null && deleteEmptyCells) { deleteEmptyGridCells(parent, delConstraints); } if (wasPackedHorz || wasPackedVert) { final Dimension minSize = parent.getMinimumSize(); Dimension newSize = new Dimension(parent.getWidth(), parent.getHeight()); if (wasPackedHorz) { newSize.width = minSize.width; } if (wasPackedVert) { newSize.height = minSize.height; } parent.setSize(newSize); } } FormEditingUtil.iterate(rootContainer, new ComponentVisitor() { public boolean visit(final IComponent component) { RadComponent rc = (RadComponent) component; for(IProperty p: component.getModifiedProperties()) { if (p instanceof IntroComponentProperty) { IntroComponentProperty icp = (IntroComponentProperty) p; final String value = icp.getValue(rc); if (deletedComponentIds.contains(value)) { try { icp.resetValue(rc); } catch (Exception e) { // ignore } } } } return true; } }); } public static void deleteEmptyGridCells(final RadContainer parent, final GridConstraints delConstraints) { deleteEmptyGridCells(parent, delConstraints, true); deleteEmptyGridCells(parent, delConstraints, false); } private static void deleteEmptyGridCells(final RadContainer parent, final GridConstraints delConstraints, final boolean isRow) { final RadAbstractGridLayoutManager layoutManager = parent.getGridLayoutManager(); for(int cell=delConstraints.getCell(isRow) + delConstraints.getSpan(isRow)-1; cell>= delConstraints.getCell(isRow); cell if (cell < parent.getGridCellCount(isRow) && GridChangeUtil.canDeleteCell(parent, cell, isRow) == GridChangeUtil.CellStatus.Empty && !layoutManager.isGapCell(parent, isRow, cell)) { layoutManager.deleteGridCells(parent, cell, isRow); } } } /** * @param x in editor pane coordinates * @param y in editor pane coordinates */ public static RadComponent getRadComponentAt(final RadRootContainer rootContainer, final int x, final int y){ Component c = SwingUtilities.getDeepestComponentAt(rootContainer.getDelegee(), x, y); RadComponent result = null; while (c != null) { if (c instanceof JComponent){ final RadComponent component = (RadComponent)((JComponent)c).getClientProperty(RadComponent.CLIENT_PROP_RAD_COMPONENT); if (component != null) { if (result == null) { result = component; } else { final Point p = SwingUtilities.convertPoint(rootContainer.getDelegee(), x, y, c); if (Painter.getResizeMask(component, p.x, p.y) != 0) { result = component; } } } } c = c.getParent(); } return result; } /** * @return component which has dragger. There is only one component with the dargger * at a time. */ @Nullable public static RadComponent getDraggerHost(@NotNull final GuiEditor editor){ final Ref<RadComponent> result = new Ref<RadComponent>(); iterate( editor.getRootContainer(), new ComponentVisitor<RadComponent>() { public boolean visit(final RadComponent component) { if(component.hasDragger()){ result.set(component); return false; } return true; } } ); return result.get(); } public static Cursor getMoveDropCursor() { try { return Cursor.getSystemCustomCursor("MoveDrop.32x32"); } catch (Exception ex) { return Cursor.getDefaultCursor(); } } public static Cursor getMoveNoDropCursor() { try { return Cursor.getSystemCustomCursor("MoveNoDrop.32x32"); } catch (Exception ex) { return Cursor.getDefaultCursor(); } } public static Cursor getCopyDropCursor() { try { return Cursor.getSystemCustomCursor("CopyDrop.32x32"); } catch (Exception ex) { return Cursor.getDefaultCursor(); } } /** * @return currently selected components. Method returns the minimal amount of * selected component which contains all selected components. It means that if the * selected container contains some selected children then only this container * will be added to the returned array. */ @NotNull public static ArrayList<RadComponent> getSelectedComponents(@NotNull final GuiEditor editor){ final ArrayList<RadComponent> result = new ArrayList<RadComponent>(); calcSelectedComponentsImpl(result, editor.getRootContainer()); return result; } private static void calcSelectedComponentsImpl(final ArrayList<RadComponent> result, final RadContainer container){ if (container.isSelected()) { if (container.getParent() != null) { // ignore RadRootContainer result.add(container); return; } } for (int i = 0; i < container.getComponentCount(); i++) { final RadComponent component = container.getComponent(i); if (component instanceof RadContainer) { calcSelectedComponentsImpl(result, (RadContainer)component); } else { if (component.isSelected()) { result.add(component); } } } } /** * @return all selected component inside the <code>editor</code> */ @NotNull public static ArrayList<RadComponent> getAllSelectedComponents(@NotNull final GuiEditor editor){ final ArrayList<RadComponent> result = new ArrayList<RadComponent>(); iterate( editor.getRootContainer(), new ComponentVisitor<RadComponent>(){ public boolean visit(final RadComponent component) { if(component.isSelected()){ result.add(component); } return true; } } ); return result; } public static String getExceptionMessage(Throwable ex) { if (ex instanceof RuntimeException) { final Throwable cause = ex.getCause(); if (cause != null && cause != ex) { return getExceptionMessage(cause); } } else if (ex instanceof InvocationTargetException) { final Throwable target = ((InvocationTargetException)ex).getTargetException(); if (target != null && target != ex) { return getExceptionMessage(target); } } String message = ex.getMessage(); if (ex instanceof ClassNotFoundException) { message = message != null? UIDesignerBundle.message("error.class.not.found.N", message) : UIDesignerBundle.message("error.class.not.found"); } else if (ex instanceof NoClassDefFoundError) { message = message != null? UIDesignerBundle.message("error.required.class.not.found.N", message) : UIDesignerBundle.message("error.required.class.not.found"); } return message; } public static IComponent findComponentWithBinding(IComponent component, final String binding) { return findComponentWithBinding(component, binding, null); } public static IComponent findComponentWithBinding(IComponent component, final String binding, @Nullable final IComponent exceptComponent) { // Check that binding is unique final Ref<IComponent> boundComponent = new Ref<IComponent>(); iterate( component, new ComponentVisitor() { public boolean visit(final IComponent component) { if(component != exceptComponent && binding.equals(component.getBinding())) { boundComponent.set(component); return false; } return true; } } ); return boundComponent.get(); } @Nullable public static RadContainer getRadContainerAt(final RadRootContainer rootContainer, final int x, final int y, int epsilon) { RadComponent component = getRadComponentAt(rootContainer, x, y); if (isNullOrRoot(component) && epsilon > 0) { // try to find component near specified location component = getRadComponentAt(rootContainer, x-epsilon, y-epsilon); if (isNullOrRoot(component)) component = getRadComponentAt(rootContainer, x-epsilon, y+epsilon); if (isNullOrRoot(component)) component = getRadComponentAt(rootContainer, x+epsilon, y-epsilon); if (isNullOrRoot(component)) component = getRadComponentAt(rootContainer, x+epsilon, y+epsilon); } if (component != null) { return component instanceof RadContainer ? (RadContainer)component : component.getParent(); } return null; } private static boolean isNullOrRoot(final RadComponent component) { return component == null || component instanceof RadRootContainer; } public static GridConstraints getDefaultConstraints(final RadComponent component) { final Palette palette = Palette.getInstance(component.getModule().getProject()); final ComponentItem item = palette.getItem(component.getComponentClassName()); if (item != null) { return item.getDefaultConstraints(); } return new GridConstraints(); } public static IRootContainer getRoot(IComponent component) { while(component != null) { if (component.getParentContainer() instanceof IRootContainer) { return (IRootContainer) component.getParentContainer(); } component = component.getParentContainer(); } return null; } /** * Iterates component and its children (if any) */ public static void iterate(final IComponent component, final ComponentVisitor visitor){ iterateImpl(component, visitor); } private static boolean iterateImpl(final IComponent component, final ComponentVisitor visitor) { final boolean shouldContinue; try { shouldContinue = visitor.visit(component); } catch (ProcessCanceledException ex) { return false; } if (!shouldContinue) { return false; } if (!(component instanceof IContainer)) { return true; } final IContainer container = (IContainer)component; for (int i = 0; i < container.getComponentCount(); i++) { final IComponent c = container.getComponent(i); if (!iterateImpl(c, visitor)) { return false; } } return true; } public static Set<String> collectUsedBundleNames(final IRootContainer rootContainer) { final Set<String> bundleNames = new HashSet<String>(); iterateStringDescriptors(rootContainer, new StringDescriptorVisitor<IComponent>() { public boolean visit(final IComponent component, final StringDescriptor descriptor) { if (descriptor.getBundleName() != null && !bundleNames.contains(descriptor.getBundleName())) { bundleNames.add(descriptor.getBundleName()); } return true; } }); return bundleNames; } public static Locale[] collectUsedLocales(final Module module, final IRootContainer rootContainer) { final Set<Locale> locales = new HashSet<Locale>(); final PropertiesReferenceManager propManager = module.getProject().getComponent(PropertiesReferenceManager.class); for(String bundleName: collectUsedBundleNames(rootContainer)) { List<PropertiesFile> propFiles = propManager.findPropertiesFiles(module, bundleName.replace('/', '.')); for(PropertiesFile propFile: propFiles) { locales.add(propFile.getLocale()); } } return locales.toArray(new Locale[locales.size()]); } public static void deleteRowOrColumn(final GuiEditor editor, final RadContainer container, final int[] cellsToDelete, final boolean isRow) { Arrays.sort(cellsToDelete); final int[] cells = ArrayUtil.reverseArray(cellsToDelete); if (!editor.ensureEditable()) { return; } Runnable runnable = new Runnable() { public void run() { if (!GridChangeUtil.canDeleteCells(container, cells, isRow)) { Set<RadComponent> componentsInColumn = new HashSet<RadComponent>(); for(RadComponent component: container.getComponents()) { GridConstraints c = component.getConstraints(); for(int cell: cells) { if (c.contains(isRow, cell)) { componentsInColumn.add(component); break; } } } if (componentsInColumn.size() > 0) { String message = isRow ? UIDesignerBundle.message("delete.row.nonempty", componentsInColumn.size(), cells.length) : UIDesignerBundle.message("delete.column.nonempty", componentsInColumn.size(), cells.length); final int rc = Messages.showYesNoDialog(editor, message, isRow ? UIDesignerBundle.message("delete.row.title") : UIDesignerBundle.message("delete.column.title"), Messages.getQuestionIcon()); if (rc != DialogWrapper.OK_EXIT_CODE) { return; } deleteComponents(componentsInColumn, false); } } for(int cell: cells) { container.getGridLayoutManager().deleteGridCells(container, cell, isRow); } editor.refreshAndSave(true); } }; CommandProcessor.getInstance().executeCommand(editor.getProject(), runnable, isRow ? UIDesignerBundle.message("command.delete.row") : UIDesignerBundle.message("command.delete.column"), null); } /** * @return id * @param rootContainer */ public static String generateId(final RadRootContainer rootContainer) { while (true) { final String id = Integer.toString((int)(Math.random() * 1024 * 1024), 16); if (findComponent(rootContainer, id) == null) { return id; } } } /** * @return {@link com.intellij.uiDesigner.designSurface.GuiEditor} from the context. Can be <code>null</code>. */ @Nullable public static GuiEditor getEditorFromContext(@NotNull final DataContext context){ final FileEditor editor = DataKeys.FILE_EDITOR.getData(context); if(editor instanceof UIFormEditor){ return ((UIFormEditor)editor).getEditor(); } else { return (GuiEditor) context.getData(GuiEditor.class.getName()); } } @Nullable public static GuiEditor getActiveEditor(final DataContext context){ Project project = DataKeys.PROJECT.getData(context); if (project == null) { return null; } final UIDesignerToolWindowManager toolWindowManager = UIDesignerToolWindowManager.getInstance(project); if (toolWindowManager == null) { return null; } return toolWindowManager.getActiveFormEditor(); } /** * * @param componentToAssignBinding * @param binding * @param component topmost container where to find duplicate binding. In most cases * it should be {@link com.intellij.uiDesigner.designSurface.GuiEditor#getRootContainer()} */ public static boolean isBindingUnique( final IComponent componentToAssignBinding, final String binding, final IComponent component ) { return findComponentWithBinding(component, binding, componentToAssignBinding) == null; } @Nullable public static String buildResourceName(final PsiFile file) { PsiDirectory directory = file.getContainingDirectory(); if (directory != null) { PsiPackage pkg = directory.getPackage(); String packageName = pkg != null ? pkg.getQualifiedName() : ""; return packageName.replace('.', '/') + '/' + file.getName(); } return null; } @Nullable public static RadContainer getSelectionParent(final List<RadComponent> selection) { RadContainer parent = null; for(RadComponent c: selection) { if (parent == null) { parent = c.getParent(); } else if (parent != c.getParent()) { parent = null; break; } } return parent; } public static Rectangle getSelectionBounds(List<RadComponent> selection) { int minRow = Integer.MAX_VALUE; int minCol = Integer.MAX_VALUE; int maxRow = 0; int maxCol = 0; for(RadComponent c: selection) { minRow = Math.min(minRow, c.getConstraints().getRow()); minCol = Math.min(minCol, c.getConstraints().getColumn()); maxRow = Math.max(maxRow, c.getConstraints().getRow() + c.getConstraints().getRowSpan()); maxCol = Math.max(maxCol, c.getConstraints().getColumn() + c.getConstraints().getColSpan()); } return new Rectangle(minCol, minRow, maxCol-minCol, maxRow-minRow); } public static boolean isComponentSwitchedInView(@NotNull RadComponent component) { while(component.getParent() != null) { if (!component.getParent().getLayoutManager().isSwitchedToChild(component.getParent(), component)) { return false; } component = component.getParent(); } return true; } /** * Selects the component and ensures that the tabbed panes containing the component are * switched to the correct tab. * * @param editor * @param component the component to select. @return true if the component is enclosed in at least one tabbed pane, false otherwise. */ public static boolean selectComponent(final GuiEditor editor, @NotNull final RadComponent component) { boolean hasTab = false; RadComponent parent = component; while(parent.getParent() != null) { if (parent.getParent().getLayoutManager().switchContainerToChild(parent.getParent(), parent)) { hasTab = true; } parent = parent.getParent(); } component.setSelected(true); editor.setSelectionLead(component); return hasTab; } public static void selectSingleComponent(final GuiEditor editor, final RadComponent component) { final RadContainer root = (RadContainer)getRoot(component); if (root == null) return; ComponentTreeBuilder builder = UIDesignerToolWindowManager.getInstance(component.getProject()).getComponentTreeBuilder(); // this can return null if the click to select the control also requested to grab the focus - // the component tree will be instantiated after the event has been processed completely if (builder != null) { builder.beginUpdateSelection(); } try { clearSelection(root); selectComponent(editor, component); editor.setSelectionAnchor(component); editor.scrollComponentInView(component); } finally { if (builder != null) { builder.endUpdateSelection(); } } } public static void selectComponents(final GuiEditor editor, List<RadComponent> components) { if (components.size() > 0) { RadComponent component = components.get(0); ComponentTreeBuilder builder = UIDesignerToolWindowManager.getInstance(component.getProject()).getComponentTreeBuilder(); builder.beginUpdateSelection(); try { clearSelection((RadContainer) getRoot(component)); for(RadComponent aComponent: components) { selectComponent(editor, aComponent); } } finally { builder.endUpdateSelection(); } } } public static boolean isDropOnChild(final DraggedComponentList draggedComponentList, final ComponentDropLocation location) { if (location.getContainer() == null) { return false; } for(RadComponent component: draggedComponentList.getComponents()) { if (isChild(location.getContainer(), component)) { return true; } } return false; } private static boolean isChild(RadContainer maybeChild, RadComponent maybeParent) { while(maybeChild != null) { if (maybeParent == maybeChild) { return true; } maybeChild = maybeChild.getParent(); } return false; } public static PsiMethod findCreateComponentsMethod(final PsiClass aClass) { PsiElementFactory factory = aClass.getManager().getElementFactory(); PsiMethod method; try { method = factory.createMethodFromText("void " + AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME + "() {}", aClass); } catch (IncorrectOperationException e) { throw new RuntimeException(e); } return aClass.findMethodBySignature(method, true); } public static Object getNextSaveUndoGroupId(final Project project) { final GuiEditor guiEditor = UIDesignerToolWindowManager.getInstance(project).getActiveFormEditor(); return guiEditor == null ? null : guiEditor.getNextSaveGroupId(); } public static int adjustForGap(final RadContainer container, final int cellIndex, final boolean isRow, final int delta) { if (container.getGridLayoutManager().isGapCell(container, isRow, cellIndex)) { return cellIndex+delta; } return cellIndex; } public static int prevRow(final RadContainer container, final int row) { return adjustForGap(container, row-1, true, -1); } public static int nextRow(final RadContainer container, final int row) { return adjustForGap(container, row+1, true, 1); } public static int prevCol(final RadContainer container, final int col) { return adjustForGap(container, col-1, false, -1); } public static int nextCol(final RadContainer container, final int col) { return adjustForGap(container, col+1, false, 1); } @Nullable public static IButtonGroup findGroupForComponent(final IRootContainer radRootContainer, @NotNull final IComponent component) { for(IButtonGroup group: radRootContainer.getButtonGroups()) { for(String id: group.getComponentIds()) { if (component.getId().equals(id)) { return group; } } } return null; } public static void remapToActionTargets(final List<RadComponent> selection) { for(int i=0; i<selection.size(); i++) { final RadComponent c = selection.get(i); if (c.getParent() != null) { selection.set(i, c.getParent().getActionTargetComponent(c)); } } } public static void showPopupUnderComponent(final JBPopup popup, final RadComponent selectedComponent) { // popup.showUnderneathOf() doesn't work on invisible components Rectangle rc = selectedComponent.getBounds(); Point pnt = new Point(rc.x, rc.y + rc.height); popup.show(new RelativePoint(selectedComponent.getDelegee().getParent(), pnt)); } public static interface StringDescriptorVisitor<T extends IComponent> { boolean visit(T component, StringDescriptor descriptor); } public static void iterateStringDescriptors(final IComponent component, final StringDescriptorVisitor<IComponent> visitor) { iterate(component, new ComponentVisitor<IComponent>() { public boolean visit(final IComponent component) { for(IProperty prop: component.getModifiedProperties()) { Object value = prop.getPropertyValue(component); if (value instanceof StringDescriptor) { if (!visitor.visit(component, (StringDescriptor) value)) { return false; } } } if (component.getParentContainer() instanceof ITabbedPane) { StringDescriptor tabTitle = ((ITabbedPane) component.getParentContainer()).getTabProperty(component, ITabbedPane.TAB_TITLE_PROPERTY); if (tabTitle != null && !visitor.visit(component, tabTitle)) { return false; } StringDescriptor tabToolTip = ((ITabbedPane) component.getParentContainer()).getTabProperty(component, ITabbedPane.TAB_TOOLTIP_PROPERTY); if (tabToolTip != null && !visitor.visit(component, tabToolTip)) { return false; } } if (component instanceof IContainer) { final StringDescriptor borderTitle = ((IContainer) component).getBorderTitle(); if (borderTitle != null && !visitor.visit(component, borderTitle)) { return false; } } return true; } }); } public static void clearSelection(@NotNull final RadContainer container){ container.setSelected(false); for (int i = 0; i < container.getComponentCount(); i++) { final RadComponent c = container.getComponent(i); if (c instanceof RadContainer) { clearSelection((RadContainer)c); } else { c.setSelected(false); } } } /** * Finds component with the specified <code>id</code> starting from the * <code>container</code>. The method goes recursively through the hierarchy * of components. Note, that if <code>container</code> itself has <code>id</code> * then the method immediately retuns it. * @return the found component. */ @Nullable public static IComponent findComponent(@NotNull final IComponent component, @NotNull final String id) { if (id.equals(component.getId())) { return component; } if (!(component instanceof IContainer)) { return null; } final IContainer uiContainer = (IContainer)component; for (int i=0; i < uiContainer.getComponentCount(); i++){ final IComponent found = findComponent(uiContainer.getComponent(i), id); if (found != null){ return found; } } return null; } @Nullable public static PsiClass findClassToBind(@NotNull final Module module, @NotNull final String classToBindName) { return PsiManager.getInstance(module.getProject()).findClass( classToBindName.replace('$','.'), module.getModuleWithDependenciesScope() ); } public static interface ComponentVisitor <Type extends IComponent>{ /** * @return true if iteration should continue */ boolean visit(Type component); } }
package jadx.gui.settings; import java.awt.Font; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Window; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxArgs; import jadx.cli.JadxCLIArgs; import jadx.gui.ui.codearea.EditorTheme; import jadx.gui.utils.LangLocale; import jadx.gui.utils.NLS; import jadx.gui.utils.Utils; public class JadxSettings extends JadxCLIArgs { private static final Logger LOG = LoggerFactory.getLogger(JadxSettings.class); private static final String USER_HOME = System.getProperty("user.home"); private static final int RECENT_FILES_COUNT = 15; private static final int CURRENT_SETTINGS_VERSION = 8; private static final Font DEFAULT_FONT = new RSyntaxTextArea().getFont(); static final Set<String> SKIP_FIELDS = new HashSet<>(Arrays.asList( "files", "input", "outDir", "outDirSrc", "outDirRes", "verbose", "printVersion", "printHelp" )); private String lastOpenFilePath = USER_HOME; private String lastSaveFilePath = USER_HOME; private boolean flattenPackage = false; private boolean checkForUpdates = false; private List<String> recentFiles = new ArrayList<>(); private String fontStr = ""; private String editorThemePath = ""; private LangLocale langLocale = NLS.defaultLocale(); private boolean autoStartJobs = false; protected String excludedPackages = ""; private boolean showHeapUsageBar = true; private int settingsVersion = 0; private Map<String, WindowLocation> windowPos = new HashMap<>(); public static JadxSettings makeDefault() { JadxSettings jadxSettings = new JadxSettings(); jadxSettings.fixOnLoad(); return jadxSettings; } public void sync() { JadxSettingsAdapter.store(this); } public void partialSync(ISettingsUpdater updater) { JadxSettings settings = JadxSettingsAdapter.load(); updater.update(settings); JadxSettingsAdapter.store(settings); } public void fixOnLoad() { if (threadsCount <= 0) { threadsCount = JadxArgs.DEFAULT_THREADS_COUNT; } if (deobfuscationMinLength < 0) { deobfuscationMinLength = 0; } if (deobfuscationMaxLength < 0) { deobfuscationMaxLength = 0; } if (settingsVersion != CURRENT_SETTINGS_VERSION) { upgradeSettings(settingsVersion); } } public String getLastOpenFilePath() { return lastOpenFilePath; } public void setLastOpenFilePath(String lastOpenFilePath) { this.lastOpenFilePath = lastOpenFilePath; partialSync(settings -> settings.lastOpenFilePath = JadxSettings.this.lastOpenFilePath); } public String getLastSaveFilePath() { return lastSaveFilePath; } public void setLastSaveFilePath(String lastSaveFilePath) { this.lastSaveFilePath = lastSaveFilePath; partialSync(settings -> settings.lastSaveFilePath = JadxSettings.this.lastSaveFilePath); } public boolean isFlattenPackage() { return flattenPackage; } public void setFlattenPackage(boolean flattenPackage) { this.flattenPackage = flattenPackage; partialSync(settings -> settings.flattenPackage = JadxSettings.this.flattenPackage); } public boolean isCheckForUpdates() { return checkForUpdates; } public void setCheckForUpdates(boolean checkForUpdates) { this.checkForUpdates = checkForUpdates; sync(); } public Iterable<String> getRecentFiles() { return recentFiles; } public void addRecentFile(String filePath) { recentFiles.remove(filePath); recentFiles.add(0, filePath); int count = recentFiles.size(); if (count > RECENT_FILES_COUNT) { recentFiles.subList(RECENT_FILES_COUNT, count).clear(); } partialSync(settings -> settings.recentFiles = recentFiles); } public void saveWindowPos(Window window) { WindowLocation pos = new WindowLocation(window.getClass().getSimpleName(), window.getX(), window.getY(), window.getWidth(), window.getHeight() ); windowPos.put(pos.getWindowId(), pos); partialSync(settings -> settings.windowPos = windowPos); } public boolean loadWindowPos(Window window) { WindowLocation pos = windowPos.get(window.getClass().getSimpleName()); if (pos == null || !isContainedInAnyScreen(pos)) { return false; } window.setLocation(pos.getX(), pos.getY()); window.setSize(pos.getWidth(), pos.getHeight()); return true; } private static boolean isContainedInAnyScreen(WindowLocation pos) { for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) { if (gd.getDefaultConfiguration().getBounds().contains( pos.getX(), pos.getY(), pos.getWidth(), pos.getHeight())) { return true; } } return false; } public boolean isShowHeapUsageBar() { return showHeapUsageBar; } public void setShowHeapUsageBar(boolean showHeapUsageBar) { this.showHeapUsageBar = showHeapUsageBar; partialSync(settings -> settings.showHeapUsageBar = showHeapUsageBar); } public String getExcludedPackages() { return excludedPackages; } public void setExcludedPackages(String excludedPackages) { this.excludedPackages = excludedPackages; } public void setThreadsCount(int threadsCount) { this.threadsCount = threadsCount; } public void setFallbackMode(boolean fallbackMode) { this.fallbackMode = fallbackMode; } public void setSkipResources(boolean skipResources) { this.skipResources = skipResources; } public void setSkipSources(boolean skipSources) { this.skipSources = skipSources; } public void setShowInconsistentCode(boolean showInconsistentCode) { this.showInconsistentCode = showInconsistentCode; } public LangLocale getLangLocale() { return this.langLocale; } public void setLangLocale(LangLocale langLocale) { this.langLocale = langLocale; } public void setCfgOutput(boolean cfgOutput) { this.cfgOutput = cfgOutput; } public void setRawCfgOutput(boolean rawCfgOutput) { this.rawCfgOutput = rawCfgOutput; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public void setDeobfuscationOn(boolean deobfuscationOn) { this.deobfuscationOn = deobfuscationOn; } public void setDeobfuscationMinLength(int deobfuscationMinLength) { this.deobfuscationMinLength = deobfuscationMinLength; } public void setDeobfuscationMaxLength(int deobfuscationMaxLength) { this.deobfuscationMaxLength = deobfuscationMaxLength; } public void setDeobfuscationForceSave(boolean deobfuscationForceSave) { this.deobfuscationForceSave = deobfuscationForceSave; } public void setDeobfuscationUseSourceNameAsAlias(boolean deobfuscationUseSourceNameAsAlias) { this.deobfuscationUseSourceNameAsAlias = deobfuscationUseSourceNameAsAlias; } public void setEscapeUnicode(boolean escapeUnicode) { this.escapeUnicode = escapeUnicode; } public void setReplaceConsts(boolean replaceConsts) { this.replaceConsts = replaceConsts; } public void setRespectBytecodeAccessModifiers(boolean respectBytecodeAccessModifiers) { this.respectBytecodeAccessModifiers = respectBytecodeAccessModifiers; } public void setUseImports(boolean useImports) { this.useImports = useImports; } public boolean isAutoStartJobs() { return autoStartJobs; } public void setAutoStartJobs(boolean autoStartJobs) { this.autoStartJobs = autoStartJobs; } public void setExportAsGradleProject(boolean exportAsGradleProject) { this.exportAsGradleProject = exportAsGradleProject; } public Font getFont() { if (fontStr.isEmpty()) { return DEFAULT_FONT; } return Font.decode(fontStr); } public void setFont(@Nullable Font font) { if (font == null) { this.fontStr = ""; return; } StringBuilder sb = new StringBuilder(); sb.append(font.getFontName()); String fontStyleName = Utils.getFontStyleName(font.getStyle()).replaceAll(" ", ""); if (!fontStyleName.isEmpty()) { sb.append('-').append(fontStyleName.toUpperCase()); } sb.append('-').append(font.getSize()); this.fontStr = sb.toString(); } public String getEditorThemePath() { return editorThemePath; } public void setEditorThemePath(String editorThemePath) { this.editorThemePath = editorThemePath; } private void upgradeSettings(int fromVersion) { LOG.debug("upgrade settings from version: {} to {}", fromVersion, CURRENT_SETTINGS_VERSION); if (fromVersion == 0) { setDeobfuscationMinLength(3); setDeobfuscationUseSourceNameAsAlias(true); setDeobfuscationForceSave(true); setThreadsCount(1); setReplaceConsts(true); setSkipResources(false); setAutoStartJobs(false); fromVersion++; } if (fromVersion == 1) { setEditorThemePath(EditorTheme.getDefaultTheme().getPath()); fromVersion++; } if (fromVersion == 2) { if (getDeobfuscationMinLength() == 4) { setDeobfuscationMinLength(3); } fromVersion++; } if (fromVersion == 3) { setLangLocale(NLS.defaultLocale()); fromVersion++; } if (fromVersion == 4) { setUseImports(true); fromVersion++; } if (fromVersion == 5) { setRespectBytecodeAccessModifiers(false); fromVersion++; } if (fromVersion == 6) { if (getFont().getFontName().equals("Hack Regular")) { setFont(null); } fromVersion++; } if (fromVersion == 7) { outDir = null; outDirSrc = null; outDirRes = null; } settingsVersion = CURRENT_SETTINGS_VERSION; sync(); } }
package com.markjmind.uni.boot; import android.content.Context; import android.os.Build; import android.os.PowerManager; import android.view.View; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.markjmind.uni.OnBackpressCallback; import com.markjmind.uni.R; import com.markjmind.uni.UniFragment; import com.markjmind.uni.common.Store; import com.markjmind.uni.util.ReflectionUtil; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * <br><br> * * @author (JaeWoong-Oh) * @email markjmind@gmail.com * @since 2016-06-02 */ public class FragmentBuilder { private static final String DEFALUT_TAG = "UNI"; private FragmentActivity activity; private FragmentManager fragmentManager; // private FragmentTransaction transaction; private boolean allowingStateLoss = false; private boolean history = true; private Store param; private OnBackpressCallback finishedListener; private int parentsViewID = -1; private int inAnimRes=-1, outAnimRes=-1; protected FragmentBuilder(FragmentActivity activity){ this.activity = activity; this.finishedListener = null; } public static <T extends UniBoot>T setContentView(FragmentActivity activity, Class<T> boot){ return (T) ReflectionUtil.getInstance(boot).initLayout(activity); } /** * Class<T> Type UniBoot .<br> * UniBoot null . * @param boot UniBoot Type * @param <T> UniBoot Class * @return T Type UniBoot */ public static <T extends UniBoot>T getBoot(FragmentActivity activity, Class<T> boot){ View rootView = activity.findViewById(R.id.uni_boot_frame_root); T bootStrap = null; if(rootView!=null){ bootStrap = (T)rootView.getTag(); if(bootStrap==null){ bootStrap = ReflectionUtil.getInstance(boot); if(bootStrap!=null){ bootStrap.initLayout(activity); } } } return bootStrap; } public static FragmentBuilder getBuilder(FragmentActivity activity){ return new FragmentBuilder(activity); } public static FragmentBuilder getBuilder(UniFragment uniFragment){ return new FragmentBuilder(uniFragment.getActivity()).setParentsId(uniFragment.getParentsViewID()); } public FragmentBuilder setParentsId(int id){ this.parentsViewID = id; return this; } public int getParentsId(){ return parentsViewID; } public void replace(UniFragment uniFragment, String tag){ if(parentsViewID < 0) { throw new RuntimeException(new NullPointerException("parentsID is null")); }else{ this.replace(getParentsId(), uniFragment, tag); } } public void replace(UniFragment uniFragment){ this.replace(uniFragment, FragmentBuilder.getDefalutTag(getParentsId())); } public void replace(int parentsID, UniFragment uniFragment, String tag){ uniFragment.setRefreshBackStack(true); String stackName = FragmentBuilder.getDefalutStack(parentsID); UniFragment currFragment = getCurrentFragment(parentsID); setOption(parentsID, uniFragment); if(finishedListener != null) { currFragment.setRefreshBackStack(false); finishedListener.setCallbackClass(currFragment.getClass()); } FragmentTransaction transaction = getTransaction(); if(inAnimRes > 0 && outAnimRes > 0){ // transaction.setCustomAnimations(inAnimRes, inAnimRes); } // replace // if(outAnimRes > 0 ) { // if (currFragment != null && currFragment.getView() != null) { // ViewParent parent = currFragment.getView().getParent(); // if (parent instanceof ViewGroup) { // ViewGroup parentViewGroup = (ViewGroup) parent; // parentViewGroup.removeAllViews(); if(currFragment != null){ transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); transaction.hide(currFragment); transaction.remove(currFragment); } transaction .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .add(parentsID, uniFragment, tag); transaction.show(uniFragment); if(history){ if ( allowingStateLoss ) { transaction.addToBackStack(stackName) .commitAllowingStateLoss(); } else { // () fragment replace transaction.addToBackStack(stackName).commit(); } }else{ if ( allowingStateLoss || !isScreenOn() ) { transaction.commitAllowingStateLoss(); } else { try { transaction.commitAllowingStateLoss(); } catch ( IllegalStateException e ) { e.printStackTrace(); } } } } private void setOption(int parentsID, UniFragment uniFragment){ if(param!=null){ uniFragment.param.putAll(param); } uniFragment.setParentsViewID(parentsID); if(finishedListener!=null) { uniFragment.setPreOnBackpressListener(finishedListener); } } public UniFragment getCurrentFragment(int parentsID){ return getCurrentFragment(FragmentBuilder.getDefalutTag(parentsID)); } private UniFragment getCurrentFragment(String tagName){ return (UniFragment)(getFragmentManager().findFragmentByTag(tagName)); } public void replace(int parentsID, UniFragment uniFragment){ // this.replace(parentsID, uniFragment, ""+uniFragment.getClass()); this.replace(parentsID, uniFragment, FragmentBuilder.getDefalutTag(parentsID)); } private boolean isScreenOn() { PowerManager powerManager = (PowerManager) activity.getSystemService(Context.POWER_SERVICE); boolean result = false; if ( Build.VERSION.SDK_INT >= 20 ) result = powerManager.isInteractive(); else if ( Build.VERSION.SDK_INT < 20 ) result = powerManager.isScreenOn(); return result; } public FragmentBuilder popBackStackClear(boolean clearAll, int parentsID){ String stackName = FragmentBuilder.getDefalutStack(parentsID); if(containStackEntry(stackName)) { try { int entry = getFragmentManager().getBackStackEntryCount(); Stack<UniFragment> uniFragments = new Stack<>(); for (int i = entry - 1; i >= 0; i String tagName = getFragmentManager().getBackStackEntryAt(i).getName(); if (tagName.contains(stackName)) { getFragmentManager().popBackStackImmediate(); } else { UniFragment uniFragment = getCurrentFragment(tagName); uniFragments.push(uniFragment); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.hide(uniFragment); transaction.remove(uniFragment); getFragmentManager().executePendingTransactions(); transaction.commitAllowingStateLoss(); getFragmentManager().popBackStackImmediate(); } } if (clearAll) { getFragmentManager().beginTransaction() .remove(getCurrentFragment(stackName)) .commitAllowingStateLoss(); } int stackCount = uniFragments.size(); if (stackCount > 0) { for (int i = 0; i < stackCount; i++) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); UniFragment uniFragment = uniFragments.pop(); uniFragment.setRefreshBackStack(false); String tagName = getDefalutTag(uniFragment.getParentsViewID()); transaction.addToBackStack(tagName); transaction.replace(uniFragment.getParentsViewID(), uniFragment, tagName); transaction.commitAllowingStateLoss(); } } }catch (IllegalStateException e){ e.printStackTrace(); if(stackName!=null) { UniFragment currentFragment = getCurrentFragment(stackName); if (currentFragment != null) { currentFragment.getFragmentStack().clearHistoryOnResume(clearAll, parentsID); } } } } return this; } public FragmentBuilder popBackStackClear(boolean clearAll) { if(clearAll) { int entry = getFragmentManager().getBackStackEntryCount(); ArrayList<String> stackNames = new ArrayList<>(); for (int i = entry - 1; i >= 0; i String tagName = getFragmentManager().getBackStackEntryAt(i).getName(); if (!stackNames.contains(tagName)) { stackNames.add(tagName); } } try { for (String tagName : stackNames) { getFragmentManager().popBackStackImmediate(tagName, FragmentManager.POP_BACK_STACK_INCLUSIVE); } List<Fragment> fragmentList = getFragmentManager().getFragments(); if(fragmentList.size() > 0) { int i = 0; for (Fragment fragment : fragmentList) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction .hide(fragment) .remove(fragment); transaction.commitAllowingStateLoss(); i++; } } }catch (IllegalStateException e){ e.printStackTrace(); List<Fragment> fragmentList = getFragmentManager().getFragments(); if(fragmentList.size() > 0) { int i = 0; for (Fragment fragment : fragmentList) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction .hide(fragment) .remove(fragment); transaction.commitAllowingStateLoss(); i++; } } String stackName = getFirstStackName(); if(stackName!=null) { UniFragment currentFragment = getCurrentFragment(stackName); if (currentFragment != null) { currentFragment.getFragmentStack().clearHistoryOnResume(true, null); } } } }else{ popBackStackClear(); } return this; } public FragmentBuilder historyAllClear(){ // FragmentManager manager = getFragmentManager(); // if (manager.getBackStackEntryCount() > 0) { // FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0); // manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE); // return this; return popBackStackClear(true); } private FragmentBuilder popBackStackClear() { try { getFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); }catch (IllegalStateException e){ e.printStackTrace(); String stackName = getFirstStackName(); if(stackName!=null) { UniFragment currentFragment = getCurrentFragment(stackName); if (currentFragment != null) { currentFragment.getFragmentStack().clearHistoryOnResume(false, null); } } } return this; } public boolean popBackStack(int parentsID) { boolean result = false; String stackName = FragmentBuilder.getDefalutStack(parentsID); if(containStackEntry(stackName)) { try { int entry = getFragmentManager().getBackStackEntryCount(); Stack<UniFragment> uniFragments = new Stack<>(); for (int i = entry - 1; i >= 0; i String tagName = getFragmentManager().getBackStackEntryAt(i).getName(); if (tagName.contains(stackName)) { popBackStackImmediateToCallback(stackName, parentsID); result = true; break; } else { UniFragment uniFragment = getCurrentFragment(tagName); uniFragments.push(uniFragment); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.remove(uniFragment); getFragmentManager().executePendingTransactions(); transaction.commitAllowingStateLoss(); getFragmentManager().popBackStackImmediate(); } } int stackCount = uniFragments.size(); if (stackCount > 0) { for (int i = 0; i < stackCount; i++) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); UniFragment uniFragment = uniFragments.pop(); uniFragment.setRefreshBackStack(false); String tagName = getDefalutTag(uniFragment.getParentsViewID()); transaction.addToBackStack(tagName); transaction.replace(uniFragment.getParentsViewID(), uniFragment, tagName); transaction.commitAllowingStateLoss(); } } }catch (IllegalStateException e){ e.printStackTrace(); popStackOnResume(stackName, parentsID); } } return result; } private void popStackOnResume(String stackName, int parentsID){ UniFragment currentFragment; if(stackName == null) { currentFragment = getCurrentFragment(parentsID); }else{ currentFragment = getCurrentFragment(stackName); } if (currentFragment != null) { try{ FragmentTransaction transaction = getFragmentManager().beginTransaction(); getFragmentManager().executePendingTransactions(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); transaction.show(currentFragment); transaction.commitNowAllowingStateLoss(); }catch (Exception ex){ currentFragment.getFragmentStack().popStackOnResume(parentsID); ex.printStackTrace(); } } } public boolean popBackStack() { if(getFragmentManager().getBackStackEntryCount()>0) { try { popBackStackImmediateToCallback(null, getParentsId()); }catch (IllegalStateException e){ e.printStackTrace(); String stackName = getFirstStackName(); popStackOnResume(stackName, getParentsId()); } return true; } return false; } private void popBackStackImmediateToCallback(String stackName, int parentsViewID){ UniFragment currFragment = getCurrentFragment(parentsViewID); OnBackpressCallback backpressCallback = currFragment.getPreOnBackpressListener(); try { getFragmentManager().popBackStackImmediate(); if(currFragment!=null){ FragmentTransaction transaction = getFragmentManager().beginTransaction(); getFragmentManager().executePendingTransactions(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); transaction.hide(currFragment); transaction.remove(currFragment); transaction.commitNowAllowingStateLoss(); } }catch (Exception e){ if(currFragment!=null){ FragmentTransaction transaction = getFragmentManager().beginTransaction(); getFragmentManager().executePendingTransactions(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); transaction.hide(currFragment); transaction.remove(currFragment); transaction.commitNowAllowingStateLoss(); } popStackOnResume(stackName, parentsViewID); } if (backpressCallback != null) { getCurrentFragment(parentsViewID).setOriginOnBackpressCallback(backpressCallback); } } private int getStackEntryCount(String stackName){ int entry = getFragmentManager().getBackStackEntryCount(); int count = 0; for (int i = entry - 1; i >= 0; i if (getFragmentManager().getBackStackEntryAt(i).getName().contains(stackName)) { count++; } } return count; } private boolean equalsStackEntry(String stackName){ int entry = getFragmentManager().getBackStackEntryCount(); for (int i = entry - 1; i >= 0; i if (getFragmentManager().getBackStackEntryAt(i).getName().equals(stackName)) { return true; } } return false; } private boolean containStackEntry(String stackName){ int entry = getFragmentManager().getBackStackEntryCount(); for (int i = entry - 1; i >= 0; i if (getFragmentManager().getBackStackEntryAt(i).getName().contains(stackName)) { return true; } } return false; } private String getFirstStackName(){ int entry = getFragmentManager().getBackStackEntryCount(); if(entry>0){ return getFragmentManager().getBackStackEntryAt(entry-1).getName(); } return null; } public FragmentBuilder setHistory(boolean isHistory){ history = isHistory; return this; } public FragmentBuilder addParam(String key, Object value){ if(param==null){ param = new Store(); } param.add(key, value); return this; } public FragmentBuilder setAnimations(int inRes, int outRes){ this.inAnimRes = inRes; this.outAnimRes = outRes; return this; } public FragmentTransaction getTransaction(){ // if(transaction == null){ // this.transaction = getFragmentManager().beginTransaction(); return getFragmentManager().beginTransaction(); } public FragmentBuilder setOnBackCallback(OnBackpressCallback onBackCallback){ this.finishedListener = onBackCallback; return this; } /** * Sync * @param isSync * @return */ // public FragmentBuilder setSync(boolean isSync){ // fragment.setAsync(isSync); // return this; /** * @param isAllowingStateLoss * @return */ public FragmentBuilder setAllowingStateLoss(boolean isAllowingStateLoss) { this.allowingStateLoss = isAllowingStateLoss; return this; } public FragmentManager getFragmentManager(){ if(fragmentManager == null){ fragmentManager = activity.getSupportFragmentManager(); } return fragmentManager; } public static String getDefalutStack(int parentsID){ return DEFALUT_TAG + parentsID; } public static String getDefalutTag(int parentsID){ return DEFALUT_TAG + parentsID; } }
package de.schlichtherle.xml; public final class GenericCertificate { private String encoded, signature, signatureAlgorithm, signatureEncoding; public String getEncoded() { return encoded; } public void setEncoded(final String encoded) { this.encoded = encoded; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public String getSignatureAlgorithm() { return signatureAlgorithm; } public void setSignatureAlgorithm(final String signatureAlgorithm) { this.signatureAlgorithm = signatureAlgorithm; } public String getSignatureEncoding() { return signatureEncoding; } public void setSignatureEncoding(final String signatureEncoding) { this.signatureEncoding = signatureEncoding; } }
package VASSAL.counters; import VASSAL.build.Configurable; import VASSAL.build.GameModule; import VASSAL.build.module.PrototypeDefinition; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.widget.CardSlot; import VASSAL.build.widget.PieceSlot; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.ConfigureTree; import VASSAL.configure.DirectoryConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.configure.TranslatingStringEnumConfigurer; import VASSAL.i18n.Resources; import VASSAL.tools.BrowserSupport; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.image.ImageUtils; import VASSAL.tools.swing.Dialogs; import VASSAL.tools.swing.SwingUtils; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.swing.BoxLayout; import javax.swing.DefaultCellEditor; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; import net.miginfocom.swing.MigLayout; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; /** * Class to load a directory full of images and create counters * */ public class MassPieceLoader { protected static final int DESC_COL = 0; protected static final int NAME_COL = 2; protected static final int IMAGE_COL = 1; protected static final int SKIP_COL = 3; protected static final int COPIES_COL = 4; protected static final int COLUMN_COUNT = 5; protected static final Color EDITABLE_COLOR = Color.blue; protected Configurable target; protected ConfigureTree configureTree; private final List<String> imageNames = new ArrayList<>(); private final List<String> baseImages = new ArrayList<>(); private final List<String> levelImages = new ArrayList<>(); private final Map<String, PieceInfo> pieceInfo = new HashMap<>(); private final List<Emb> layers = new ArrayList<>(); protected MassLoaderDialog dialog; private static final DirectoryConfigurer dirConfig = new DirectoryConfigurer(null, ""); private static final BooleanConfigurer basicConfig = new BooleanConfigurer(null, "", Boolean.FALSE); private static final BooleanConfigurer emptyLevelConfig = new BooleanConfigurer(null, "", Boolean.FALSE); private static final MassPieceDefiner definer = new MassPieceDefiner(); public MassPieceLoader(ConfigureTree tree, Configurable target) { this.target = target; this.configureTree = tree; } // The Dialog does all the work. public void load() { dialog = new MassLoaderDialog(); SwingUtils.ensureOnScreen(dialog); dialog.setVisible(true); if (!dialog.isCancelled()) { dialog.load(); } } /** * Mass Piece Loader dialog */ class MassLoaderDialog extends JDialog { private static final long serialVersionUID = 1L; protected boolean cancelled = false; protected DefineDialog defineDialog; protected MyTreeTable tree; protected MyTreeTableModel model; protected BasicNode root; protected File loadDirectory; public MassLoaderDialog() { super(configureTree.getFrame()); setModal(true); setTitle(Resources.getString("Editor.MassPieceLoader.load_multiple")); setLayout(new MigLayout("ins panel,wrap 2," + TraitLayout.STANDARD_GAPY, "[right]rel[grow,fill]", "[][][][grow,fill][]")); // NON-NLS setPreferredSize(new Dimension(800, 600)); dirConfig.addPropertyChangeListener(e -> { if (e.getNewValue() != null) { buildTree((File) e.getNewValue()); } }); add(new JLabel(Resources.getString("Editor.MassPieceLoader.image_directory"))); add(dirConfig.getControls(), "grow"); // NON-NLS basicConfig.addPropertyChangeListener(e -> { if (e.getNewValue() != null) { buildTree(dirConfig.getFileValue()); } }); add(new JLabel(Resources.getString("Editor.MassPieceLoader.no_basic_piece"))); add(basicConfig.getControls()); emptyLevelConfig.addPropertyChangeListener(e -> { if (e.getNewValue() != null) { buildTree(dirConfig.getFileValue()); } }); add(new JLabel(Resources.getString("Editor.MassPieceLoader.no_empty_level"))); add(emptyLevelConfig.getControls()); defineDialog = new DefineDialog(this); final JButton defineButton = new JButton(Resources.getString("Editor.MassPieceLoader.edit_piece_template")); defineButton.addActionListener(e -> { final GamePiece savePiece = definer.getPiece(); SwingUtils.ensureOnScreen(defineDialog); defineDialog.setVisible(true); if (defineDialog.isCancelled()) { definer.setPiece(savePiece); } else { buildTree(dirConfig.getFileValue()); } }); add(defineButton, "skip 1,growx 0"); // NON-NLS tree = new MyTreeTable(); buildTree(dirConfig.getFileValue()); //final JPanel treePanel = new JPanel(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]")); // NON-NLS //treePanel.add(tree, "grow"); // NON-NLS final JScrollPane scrollPane = new JScrollPane(tree); add(scrollPane, "span 2,grow"); // NON-NLS final JPanel buttonBox = new JPanel(new MigLayout("ins 0", "push[]rel[]rel[]push")); // NON-NLS final JButton okButton = new JButton(Resources.getString(Resources.OK)); okButton.addActionListener(e -> save()); buttonBox.add(okButton); final JButton cancelButton = new JButton(Resources .getString(Resources.CANCEL)); cancelButton.addActionListener(e -> cancel()); buttonBox.add(cancelButton); final JButton skipAllButton = new JButton(Resources.getString("Editor.MassPieceLoader.skip_all")); skipAllButton.addActionListener(e -> skipAll()); buttonBox.add(skipAllButton); final JButton skipNoneButton = new JButton(Resources.getString("Editor.MassPieceLoader.skip_none")); skipNoneButton.addActionListener(e -> skipNone()); buttonBox.add(skipNoneButton); final JButton helpButton = new JButton(Resources .getString(Resources.HELP)); helpButton.addActionListener(e -> { final HelpFile h = HelpFile.getReferenceManualPage("MassPieceLoader.html"); //NON-NLS BrowserSupport.openURL(h.getContents().toString()); }); buttonBox.add(helpButton); add(buttonBox, "span 2,center,grow 0"); // NON-NLS pack(); setLocationRelativeTo(getParent()); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { cancel(); } }); } public void skipAll() { for (int i = 0; i < root.getChildCount(); i++) { final PieceNode pieceNode = (PieceNode) root.getChildAt(i); pieceNode.setSkip(true); } repaint(); } public void skipNone() { for (int i = 0; i < root.getChildCount(); i++) { final PieceNode pieceNode = (PieceNode) root.getChildAt(i); pieceNode.setSkip(false); } repaint(); } public void cancel() { cancelled = true; dispose(); } public void save() { // Count the pieces to be loaded int pieceCount = 0; for (int i = 0; i < root.getChildCount(); i++) { final PieceNode node = (PieceNode) root.getChildAt(i); if (! node.isSkip()) { pieceCount += node.getCopies(); } } // Do they really want to do this? if (pieceCount > 0) { final String message = Resources.getString("Editor.MassPieceLoader.this_will_load", pieceCount, target.getConfigureName()); final int result = Dialogs.showConfirmDialog(null, Resources.getString("Editor.MassPieceLoader.confirm_load"), Resources.getString("Editor.MassPieceLoader.confirm_load"), message, JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION); if (result == 1) { cancel(); return; } else if (result == 2) { return; } } cancelled = false; dispose(); } public boolean isCancelled() { return cancelled; } public File getDirectory() { return dirConfig.getFileValue(); } /** * Build a tree representing the Game Pieces, Layers, Levels and images to * be loaded. This tree is used as a model for the JxTreeTable, and also as * the guide to load the counters. * * @param dir * Directory containing images */ protected void buildTree(File dir) { loadDirectory = dir; // Make a list of the Layer traits in the template layers.clear(); GamePiece piece = definer.getPiece(); while (piece instanceof Decorator) { piece = Decorator.getDecorator(piece, Emb.class); if (piece instanceof Emb) { layers.add(0, (Emb) piece); piece = ((Emb) piece).getInner(); } } // Find all of the images in the target directory loadImageNames(dir); // Check each image in the target directory to see if it matches the // level specification in any of the Embellishments in the template. // The remaining images that do not match any Level are our baseImages baseImages.clear(); levelImages.clear(); for (final String imageName : imageNames) { boolean match = false; for (final Emb emb : layers) { match = emb.matchLayer(imageName); if (match) { break; } } if (match) { levelImages.add(imageName); } else { baseImages.add(imageName); } } // Generate a table node for each base Image. // Create a child Layer Node for each layer that has at least one image root = new BasicNode(); for (final String baseImage : baseImages) { final BasicNode pieceNode = new PieceNode(baseImage); for (final Emb emb : layers) { final Emb newLayer = new Emb(emb.getType(), null); if (newLayer.buildLayers(baseImage, levelImages)) { final BasicNode layerNode = new LayerNode(newLayer.getLayerName()); for (int i = 0; i < newLayer.getImageNames().length; i++) { final String levelName = newLayer.getLevelNames()[i]; final BasicNode levelNode = new LevelNode( levelName == null ? "" : levelName, newLayer .getImageNames()[i], i); layerNode.add(levelNode); } pieceNode.add(layerNode); } } root.add(pieceNode); } // Set the tree model = new MyTreeTableModel(root); tree.setTreeTableModel(model); final TableColumnModel tcm = tree.getColumnModel(); tcm.getColumn(SKIP_COL).setPreferredWidth(50); tcm.getColumn(SKIP_COL).setMaxWidth(50); tcm.getColumn(DESC_COL).setPreferredWidth(100); tcm.getColumn(DESC_COL).setCellRenderer(new ImageNameRenderer()); tcm.getColumn(NAME_COL).setPreferredWidth(200); tcm.getColumn(NAME_COL).setCellRenderer(new NameRenderer()); tcm.getColumn(NAME_COL).setCellEditor(new NameEditor(new JTextField())); tcm.getColumn(IMAGE_COL).setPreferredWidth(200); tcm.getColumn(IMAGE_COL).setCellRenderer(new ImageNameRenderer()); tcm.getColumn(COPIES_COL).setPreferredWidth(50); tcm.getColumn(COPIES_COL).setMaxWidth(50); tcm.getColumn(COPIES_COL).setCellRenderer(new CopiesRenderer()); } class NameRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); final BasicNode node = (BasicNode) tree.getPathForRow(row) .getLastPathComponent(); c.setEnabled(!node.isSkip()); c.setForeground(EDITABLE_COLOR); return c; } } class CopiesRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel renderedLabel = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); final BasicNode node = (BasicNode) tree.getPathForRow(row).getLastPathComponent(); renderedLabel.setHorizontalAlignment(SwingConstants.CENTER); renderedLabel.setEnabled(!node.isSkip()); renderedLabel.setForeground(EDITABLE_COLOR); return renderedLabel; } } class ImageNameRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { final DefaultTableCellRenderer c = (DefaultTableCellRenderer) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); final BasicNode node = (BasicNode) tree.getPathForRow(row) .getLastPathComponent(); c.setEnabled(!node.isSkip()); if (node instanceof PieceNode) { final String image = node.getImageName(); final String i = "<html><img src=\"file:/" + loadDirectory.getAbsolutePath() + "/" + image + "\"></html>"; //NON-NLS c.setToolTipText(i); } return c; } } class NameEditor extends DefaultCellEditor { private static final long serialVersionUID = 1L; public NameEditor(JTextField textField) { super(textField); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { final Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column); c.setForeground(Color.blue); return c; } } /** * Load all image names in the target directory * * @param dir Image Directory */ protected void loadImageNames(File dir) { imageNames.clear(); if (dir != null && dir.isDirectory()) { final File[] files = dir.listFiles(); if (files != null) { Arrays.sort(files); for (final File file : files) { final String imageName = file.getName(); if (ImageUtils.hasImageSuffix(imageName)) { imageNames.add(imageName); } } } } } /** * Load the Pieces based on the Node Tree built while user was editing */ public void load() { // Check a Directory has been entered final File dir = dialog.getDirectory(); if (dir == null) { return; } // For each PieceNode, load the required images into the module and // generate the piece for (int i = 0; i < root.getChildCount(); i++) { final PieceNode pieceNode = (PieceNode) root.getChildAt(i); if (!pieceNode.isSkip()) { load(pieceNode); } } } /** * Load a specific piece and and all referenced images. * * @param pieceNode * Sub-tree representing piece */ public void load(PieceNode pieceNode) { // Add the Base Image to the module final String baseImage = pieceNode.getBaseImageName(); addImageToModule(baseImage); // Create the BasicPiece final String basicType = new SequenceEncoder("", ';') .append("") .append(basicConfig.booleanValue() ? "" : baseImage) .append(pieceNode.getName()).getValue(); final BasicPiece basic = (BasicPiece) GameModule.getGameModule().createPiece(BasicPiece.ID + basicType); // Build the piece from the template GamePiece template = definer.getPiece(); final ArrayList<Decorator> traits = new ArrayList<>(); // Reverse the order of the traits to innermost out while (template instanceof Decorator) { traits.add(0, (Decorator) template); template = ((Decorator) template).getInner(); } for (int count = 0; count < pieceNode.getCopies(); count++) { GamePiece piece = basic; // Build the new piece. Note special Handling for Embellishment templates // that will // have actual images added for references to matching images. If an // Embellishment // has no matching images at all, do not add it to the new counter. for (final Decorator trait : traits) { if (trait.getClass().equals(Emb.class)) { final Emb newLayer = new Emb(trait.myGetType(), null); if (newLayer.buildLayers(baseImage, levelImages)) { for (final String image : newLayer.getBuiltImageList()) { addImageToModule(image); } newLayer.setInner(piece); final String saveState = newLayer.getState(); piece = GameModule.getGameModule().createPiece(newLayer.getType()); piece.setState(saveState); } } else { final Decorator newTrait = (Decorator) GameModule.getGameModule().createPiece(trait.getType()); newTrait.setState(trait.getState()); newTrait.setInner(piece); final String saveState = newTrait.getState(); piece = GameModule.getGameModule().createPiece(newTrait.getType()); piece.setState(saveState); } } // Create the PieceSlot for the new piece PieceSlot slot = null; final Class<?>[] c = target.getAllowableConfigureComponents(); for (int i = 0; i < c.length && slot == null; i++) { if (c[i].equals(CardSlot.class)) { slot = new CardSlot(); slot.setPiece(piece); } } if (slot == null) { slot = new PieceSlot(piece); } // Generate a gpid configureTree.updateGpIds(slot); // Add the new piece to the tree configureTree.externalInsert(target, slot); } } } /** * Add the named image to the module * * @param name * Image name */ protected void addImageToModule(String name) { if (name != null && name.length() > 0) { try { GameModule.getGameModule().getArchiveWriter().addImage( new File(dirConfig.getFileValue(), name).getCanonicalPath(), name); } catch (IOException e) { // FIXME: Log error properly // ErrorLog.log() } } } /** * Maintain a record of all names changed by the user for image basenames. * Default name is image name with image suffix stripped. * * @param baseName * Image name * @return user modified name */ protected String getPieceName(String baseName) { final PieceInfo info = pieceInfo.get(baseName); return info == null ? ImageUtils.stripImageSuffix(baseName) : info .getName(); } /** * * A custom piece definer based on the Prototype piece definer * */ static class MassPieceDefiner extends PrototypeDefinition.Config.Definer { private static final long serialVersionUID = 1L; protected static DefaultListModel<GamePiece> newModel; protected boolean copyIsEmb; /** Is the current trait in the Clipboard an Emb trait? */ public MassPieceDefiner() { super(GameModule.getGameModule().getGpIdSupport()); // Build a replacement model that uses a modified Embellishment trait // with a replacement ImagePicker. if (newModel == null) { newModel = new DefaultListModel<>(); for (final Enumeration<?> e = availableModel.elements(); e.hasMoreElements();) { final Object o = e.nextElement(); newModel.addElement((GamePiece) o); if (o instanceof Embellishment) { newModel.addElement(new MassPieceLoader.Emb()); } } } availableList.setModel(newModel); setPiece(null); } @Override protected void copy(int index) { copyIsEmb = inUseModel.get(index).getClass().equals(Emb.class); super.copy(index); } @Override protected void paste() { final String type = clipBoard.getType(); final Decorator c = (type.startsWith(Embellishment.ID) && copyIsEmb) ? new Emb(type, null) : (Decorator) GameModule.getGameModule().createPiece(type, null); if (c instanceof PlaceMarker) { ((PlaceMarker) c).updateGpId(GameModule.getGameModule().getGpIdSupport()); } final int selectedIndex = getInUseSelectedIndex(); c.setInner(inUseModel.lastElement()); inUseModel.addElement(c); c.mySetState(clipBoard.getState()); moveDecorator(inUseModel.size() - 1, selectedIndex + 1); refresh(); } } /** * * Dialog to hold the PieceDefiner used to specify the multi-load piece * template. * */ private static class DefineDialog extends JDialog { private static final long serialVersionUID = 1L; protected boolean cancelled = false; public DefineDialog(JDialog owner) { super(owner); setModal(true); setVisible(false); setTitle(Resources.getString("Editor.MassPieceLoader.multiple_piece_template")); setLocationRelativeTo(owner); setLayout(new MigLayout("ins panel,wrap 1," + TraitLayout.STANDARD_GAPY, "[grow,fill]", "[grow,fill][]")); // NON-NLS add(definer, "grow"); // NON-NLS final JButton saveButton = new JButton(Resources.getString(Resources.SAVE)); saveButton.addActionListener(e -> save()); final JButton canButton = new JButton(Resources.getString(Resources.CANCEL)); canButton.addActionListener(e -> cancel()); final JPanel bbox = new JPanel(new MigLayout("ins 0", "push[][]push")); // NON-NLS bbox.add(saveButton); bbox.add(canButton); add(bbox, "center"); // NON-NLS setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { cancel(); } }); pack(); } protected void save() { cancelled = false; setVisible(false); } protected void cancel() { cancelled = true; setVisible(false); } public boolean isCancelled() { return cancelled; } } private class MyTreeTableModel extends DefaultTreeTableModel { public MyTreeTableModel(BasicNode rootNode) { super(rootNode); } @Override public int getColumnCount() { return COLUMN_COUNT; } @Override public String getColumnName(int col) { switch (col) { case DESC_COL: return Resources.getString("Editor.MassPieceLoader.item"); case NAME_COL: return Resources.getString("Editor.MassPieceLoader.piece_name"); case IMAGE_COL: return Resources.getString("Editor.MassPieceLoader.image_name"); case SKIP_COL: return Resources.getString("Editor.MassPieceLoader.skip"); case COPIES_COL: return Resources.getString("Editor.MassPieceLoader.copies"); } return ""; } @Override public Class<?> getColumnClass(int column) { if (column == SKIP_COL) { return Boolean.class; } else if (column == COPIES_COL) { return Integer.class; } else { return String.class; } } @Override public boolean isCellEditable(Object node, int column) { if (node instanceof PieceNode) { if (column == NAME_COL || column == COPIES_COL) { return !((PieceNode) node).isSkip(); } else { return column == SKIP_COL; } } return false; } @Override public Object getValueAt(Object node, int column) { return ((BasicNode) node).getValueAt(column); } @Override public void setValueAt(Object value, Object node, int column) { if (node instanceof PieceNode) { if (column == NAME_COL) { ((PieceNode) node).setName((String) value); } else if (column == SKIP_COL) { ((PieceNode) node).setSkip((Boolean) value); } else if (column == COPIES_COL) { int val = value == null ? 1 : (Integer) value; if (val < 1) val = 1; ((PieceNode) node).setCopies(val); } } else { super.setValueAt(value, node, column); } } } private class MyTreeTable extends JXTreeTable { private static final long serialVersionUID = 1L; public MyTreeTable() { super(); setRootVisible(false); } // Hide the Skip checkbox on rows other than Piece rows @Override public TableCellRenderer getCellRenderer(int row, int column) { if (column == SKIP_COL || column == COPIES_COL) { if (this.getPathForRow(row) == null) { return new NullRenderer(); } if (!(this.getPathForRow(row).getLastPathComponent() instanceof PieceNode)) { return new NullRenderer(); } } return super.getCellRenderer(row, column); } } /** * Blank Cell Renderer */ private static class NullRenderer implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable arg0, Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) { return new JLabel(""); } } private static class BasicNode extends DefaultMutableTreeTableNode { protected String name; protected String imageName; protected boolean skip; protected int copies; public BasicNode() { this("", ""); } public BasicNode(String name, String imageName) { this.name = name; this.imageName = imageName; this.skip = false; this.copies = 1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public boolean isSkip() { return skip; } public void setSkip(boolean b) { skip = b; } public void setCopies(int i) { copies = i; } public int getCopies() { return copies; } public String getDescription() { return Resources.getString("Editor.MassPieceLoader.root"); } @Override public Object getValueAt(int col) { switch (col) { case DESC_COL: return getDescription(); case NAME_COL: return getName(); case IMAGE_COL: return getImageName(); case SKIP_COL: return isSkip(); case COPIES_COL: return getCopies(); } return ""; } } /** * Node representing a GamePiece to be loaded. imageName is the name of the * Basic Piece image * */ private class PieceNode extends BasicNode { public PieceNode(String imageName) { super(); setImageName(imageName); final PieceInfo info = pieceInfo.get(imageName); if (info == null) { setName(ImageUtils.stripImageSuffix(imageName)); setSkip(false); } else { setName(info.getName()); setSkip(info.isSkip()); } } public String getBaseImageName() { return super.getImageName(); } @Override public String getImageName() { if (basicConfig.booleanValue()) { return ""; } else { return super.getImageName(); } } @Override public String getDescription() { return Resources.getString("Editor.MassPieceLoader.piece_desc"); } @Override public void setName(String name) { super.setName(name); pieceInfo.put(getImageName(), new PieceInfo(name, isSkip())); } @Override public void setSkip(boolean skip) { super.setSkip(skip); pieceInfo.put(getImageName(), new PieceInfo(getName(), skip)); } } /** * Node representing a Layer trait of a GamePiece */ private static class LayerNode extends BasicNode { public LayerNode(String name) { super(name, ""); } @Override public String getDescription() { return Resources.getString("Editor.MassPieceLoader.layer_desc") + (name.length() > 0 ? " [" + name + "]" : ""); } @Override public String getName() { return ""; } } /** * Node representing an individual Image Level within a Layer trait * */ private static class LevelNode extends BasicNode { int levelNumber; public LevelNode(String name, String imageName, int level) { super(name, imageName); levelNumber = level; } @Override public String getDescription() { return Resources.getString("Editor.MassPieceLoader.level") + " " + (levelNumber + 1) + (name.length() > 0 ? " [" + name + "]" : ""); } @Override public String getName() { return ""; } } /** * Utility class to hold user changes about pieces - Updated piece name - Skip * load flag * */ private static class PieceInfo { protected String name; protected boolean skip; public PieceInfo(String name, boolean skip) { this.name = name; this.skip = skip; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isSkip() { return skip; } public void setSkip(boolean b) { skip = b; } } /** * Subclass of Embellishment to allow us to directly manipulate its members */ private static class Emb extends Embellishment { private final List<String> builtImages = new ArrayList<>(); public Emb() { super(); } public Emb(String type, GamePiece p) { super(type, p); } public String[] getImageNames() { return imageName; } public String[] getLevelNames() { return commonName; } @Override public String getDescription() { return Resources.getString("Editor.MassPieceLoader.embellishment_trait_description") + super.getDescription().substring(Resources.getString("Editor.Embellishment.trait_description").length()); } // Return true if the specified file name matches the level // definition of any level in this layer public boolean matchLayer(String s) { for (final String levelName : imageName) { if (match(s.split("\\.")[0], levelName)) { return true; } } return false; } protected boolean match(String s, String levelName) { if (levelName != null && levelName.length() > 1) { // Check 1 to skip // command char if (levelName.charAt(0) == BASE_IMAGE.charAt(0)) { return false; } else if (levelName.charAt(0) == ENDS_WITH.charAt(0)) { return s.endsWith(levelName.substring(1)); } else if (levelName.charAt(0) == INCLUDES.charAt(0)) { return s.contains(levelName.substring(1)); } else if (levelName.charAt(0) == EQUALS.charAt(0)) { return s.equals(levelName.substring(1)); } else { try { return Pattern.matches(levelName.substring(1), s); } catch (Exception ex) { // Invalid pattern } } } return false; } /** * Set the actual layer images based on a base image and the layer image * template specification. * * @param baseImage * base Image name * @param levelImages * List of available level images * @return true if at least one layer built */ public boolean buildLayers(String baseImage, List<String> levelImages) { final String base = baseImage.split("\\.")[0]; int count = 0; builtImages.clear(); for (int i = 0; i < imageName.length; i++) { final String imageTemplate = imageName[i]; String thisImage = null; if (imageTemplate.charAt(0) == BASE_IMAGE.charAt(0)) { thisImage = baseImage; } else { for (final Iterator<String> it = levelImages.iterator(); it.hasNext() && thisImage == null;) { final String checkImage = it.next(); final String checkImageBase = checkImage.split("\\.")[0]; if (imageTemplate.charAt(0) == EQUALS.charAt(0)) { if (match(checkImageBase, imageTemplate)) { thisImage = checkImage; } } else { if (checkImage.startsWith(base)) { if (match(checkImageBase, imageTemplate)) { thisImage = checkImage; } } } } } imageName[i] = thisImage; if (thisImage != null) { count++; builtImages.add(thisImage); } } if (emptyLevelConfig.getValueBoolean()) { int j = 0; int newLength = 0; for (int i = 0; i < imageName.length; i++) { if (imageName[i] != null) { newLength++; } } String[] imageNameTmp = new String[newLength]; String[] commonNameTmp = new String[newLength]; for (int i = 0; i < imageName.length; i++) { if (imageName[i] != null) { imageNameTmp[j] = imageName[i]; commonNameTmp[j] = commonName[i]; j++; } } imageName = imageNameTmp; commonName = commonNameTmp; } return count > 0; } public List<String> getBuiltImageList() { return builtImages; } public static class LoaderEd extends Embellishment.Ed { public LoaderEd(Embellishment e) { super(e); } @Override protected MultiImagePicker getImagePicker() { return new LoaderImagePicker(); } } @Override public PieceEditor getEditor() { return new LoaderEd(this); } } /** * Replacement class for the MultiImagePicker to specify image match strings */ private static class LoaderImagePicker extends MultiImagePicker { private static final long serialVersionUID = 1L; @Override public void addEntry() { final String entry = Resources.getString("Editor.MassPieceLoader.image") + " " + (imageListElements.size() + 1); imageListElements.addElement(entry); final Entry pick = new Entry(); multiPanel.add(entry, pick); imageList.setSelectedIndex(imageListElements.size() - 1); cl.show(multiPanel, imageList.getSelectedValue()); } @Override public List<String> getImageNameList() { final int size = imageListElements.size(); final ArrayList<String> names = new ArrayList<>(size); for (int i = 0; i < size; ++i) { names.add((multiPanel.getComponent(i).toString())); } return names; } @Override public void clear() { multiPanel.removeAll(); imageListElements.removeAllElements(); } @Override public void setImageList(String[] names) { while (names.length > multiPanel.getComponentCount()) { addEntry(); } for (int i = 0; i < names.length; ++i) { if (names[i] != null) { ((Entry) multiPanel.getComponent(i)).setImageName(names[i]); } } } } protected static final String ENDS_WITH = "ends with"; //NON-NLS (really) protected static final String INCLUDES = "includes"; //NON-NLS (really) protected static final String MATCHES = "matches"; //NON-NLS (really) protected static final String EQUALS = "same as"; //NON-NLS (really) protected static final String BASE_IMAGE = "use Base Image"; //NON-NLS (really) private static class Entry extends JPanel { private static final long serialVersionUID = 1L; private final TranslatingStringEnumConfigurer typeConfig; private final StringConfigurer nameConfig; private final JLabel warning = new JLabel(Resources.getString("Editor.MassPieceLoader.warning_suffix")); public Entry() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(new JLabel( Resources.getString("Editor.MassPieceLoader.do_not_suffix"))); final JPanel entry = new JPanel(new MigLayout("ins 0,hidemode 3", "[]rel[]")); // NON-NLS entry.add(new JLabel(Resources.getString("Editor.MassPieceLoader.image_name") + " ")); typeConfig = new TranslatingStringEnumConfigurer(null, "", new String[] { ENDS_WITH, INCLUDES, MATCHES, EQUALS, BASE_IMAGE }, new String[] { "Editor.MassPieceLoader.ends_with", "Editor.MassPieceLoader.includes", "Editor.MassPieceLoader.matches", "Editor.MassPieceLoader.same_as", "Editor.MassPieceLoader.base_image" } ); entry.add(typeConfig.getControls()); nameConfig = new StringConfigurer(null, ""); entry.add(nameConfig.getControls()); add(entry); warning.setVisible(false); add(warning); typeConfig.addPropertyChangeListener(e -> updateVisibility()); nameConfig.addPropertyChangeListener(e -> updateVisibility()); } protected void updateVisibility() { warning .setVisible(ImageUtils.hasImageSuffix(nameConfig.getValueString())); nameConfig.getControls().setVisible( !typeConfig.getValueString().equals(BASE_IMAGE)); } @Override public String toString() { return typeConfig.getValueString().charAt(0) + nameConfig.getValueString(); } public void setImageName(String s) { switch (s.charAt(0)) { case 'e': typeConfig.setValue(ENDS_WITH); break; case 'i': typeConfig.setValue(INCLUDES); break; case 'm': typeConfig.setValue(MATCHES); break; case 's': typeConfig.setValue(EQUALS); break; case 'u': typeConfig.setValue(BASE_IMAGE); break; } nameConfig.setValue(s.substring(1)); } } }
package nl.fifth.postulate.bin; import nl.fifth.postulate.circuit.BaseTrappistData; import nl.fifth.postulate.circuit.PipeAssembly; import nl.fifth.postulate.circuit.TrappistData; import nl.fifth.postulate.circuit.pipe.Average; import nl.fifth.postulate.circuit.pipe.Detrend; import nl.fifth.postulate.circuit.pipe.FFTFilter; import nl.fifth.postulate.circuit.pipe.Smooth; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import static nl.fifth.postulate.circuit.pipe.Average.average; import static nl.fifth.postulate.circuit.pipe.Detrend.detrend; import static nl.fifth.postulate.circuit.pipe.FFTFilter.fftFilter; import static nl.fifth.postulate.circuit.pipe.Smooth.smooth; public class DataCircuit { public static void main(String[] args) throws FileNotFoundException { String filename = args[0]; String pathName = args[1]; TrappistData result = process(BaseTrappistData.from(filename)); PrintStream output = new PrintStream(new FileOutputStream(pathName)); Formatter.format(output, result, "%4d, %10.6f, %10.6f, %10.6f, %10.6f, %10.6f\n", "TIME", Average.COLUMN_NAME, Smooth.COLUMN_NAME, Detrend.COLUMN_NAME, FFTFilter.COLUMN_NAME ); } private static TrappistData process(TrappistData baseData) { PipeAssembly assembly = PipeAssembly .with(average()) .andThen(smooth(0.6f)) .andThen(detrend(Average.COLUMN_NAME, Smooth.COLUMN_NAME)) .andThen(fftFilter(1500)) .build(); return assembly.process(baseData); } } class Formatter { public static void format(PrintStream stream, TrappistData data, String template, String... columnNames) { Map<String, float[]> dataPoints = new HashMap<>(); for (String columnName : columnNames) { if (!columnName.equals("TIME")) { dataPoints.put(columnName, (float[]) data.dataFor(columnName)); } } for (int row = 0, limit = dataPoints.get(columnNames[1]).length; row < limit; row++) { System.out.println(row); Object[] dataPoint = new Object[1 + columnNames.length]; dataPoint[0] = row; for (int index = 0; index < columnNames.length; index++) { String columnName = columnNames[index]; if (columnName.equals("TIME")) { double value = ((double[]) data.dataFor(columnName))[row]; dataPoint[1 + index] = value; } else { float value = (float) dataPoints.get(columnName)[row]; dataPoint[1 + index] = value; } } stream.format(template, dataPoint); } } }
package org.javaz.test.jdbc; import junit.framework.Assert; import org.hsqldb.server.Server; import org.javaz.jdbc.queues.GenericDbUpdater; import org.javaz.jdbc.queues.SqlRecordsFetcher; import org.javaz.jdbc.replicate.ReplicateTables; import org.javaz.jdbc.util.*; import org.javaz.queues.iface.RecordsRotatorI; import org.javaz.queues.impl.RotatorsHolder; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.PrintWriter; import java.util.*; public class JdbcCachedTest { public static JdbcHelperI test = null; public static JdbcHelperI test2 = null; public static String address = null; public static String address2 = null; public static ConnectionProviderI provider = null; public static int testPort = 31234; @BeforeClass public static void testPrepare() throws Exception { new UnsafeSqlHelper(); new JdbcCachedHelper(); address = "jdbc:hsqldb:hsql://localhost:" + testPort + "/mydb1;username=SA"; address2 = "jdbc:hsqldb:hsql://localhost:" + testPort + "/mydb2;username=SA"; // address = "jdbc:hsqldb:mem:test1;username=SA"; test = JdbcCachedHelper.getInstance(address); test2 = JdbcCachedHelper.getInstance(address2); Assert.assertEquals(address, test.getJdbcAddress()); provider = test.getProvider(); test.setProvider(provider); long ttl = test.getListRecordsTtl(); test.setListRecordsTtl(ttl); Server server = new Server(); server.setAddress("localhost"); server.setDatabaseName(0, "mydb1"); server.setDatabaseName(1, "mydb2"); File tempFile1 = File.createTempFile("jdbc-junit-test1", "hsqldb"); tempFile1.deleteOnExit(); server.setDatabasePath(0, tempFile1.getCanonicalPath()); File tempFile2 = File.createTempFile("jdbc-junit-test2", "hsqldb"); tempFile2.deleteOnExit(); server.setDatabasePath(1, tempFile2.getCanonicalPath()); server.setPort(testPort); server.setTrace(true); server.setLogWriter(new PrintWriter(System.out)); server.start(); try { Class.forName("org.hsqldb.jdbc.JDBCDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(System.out); } } @Test public void testCache() throws Exception { test.runUpdate("drop table test", null); test.runUpdate("create table test (id integer, name varchar(250))", null); test.runUpdate("insert into test values (1,'a'),(2,'b'),(3,'c')", null); HashMap params = new HashMap(); UnsafeSqlHelper.addArrayParameters(params, new Object[]{1, 2}); ArrayList id3 = new ArrayList(); id3.add(3); UnsafeSqlHelper.addArrayParameters(params, id3); List list = test.getRecordList("select * from test where id in (" + UnsafeSqlHelper.repeatQuestionMark(params.size()) + ")", params); Assert.assertEquals(list.size(), 3); ArrayList updates = new ArrayList(); updates.add(new Object[]{"insert into test values (101,'a')", null}); updates.add(new Object[]{"insert into test values (102,'b')", null}); updates.add(new Object[]{"insert into test values (103,'c')", null}); test.runMassUpdate(updates); list = test.getRecordList("select * from test", null, false); Assert.assertEquals(list.size(), 6); test.runUpdate("drop table test", null); list = test.getRecordList("select * from test", null, false); Assert.assertEquals(list.size(), 0); List list2 = test.getRecordList("select * from test where id in (" + UnsafeSqlHelper.repeatQuestionMark(params.size()) + ")", params); Assert.assertEquals(list2.size(), 3); } @Test public void testMassUpdate() throws Exception { test.runUpdate("drop table test2", null); test.runUpdate("create table test2 (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, dt timestamp)", null); long millis = System.currentTimeMillis(); HashMap params = new HashMap(); params.clear(); params.put(1, new Date(millis)); ArrayList updates = new ArrayList(); updates.clear(); updates.add(new Object[]{"insert into test2 (dt) values (?)", params}); updates.add(new Object[]{"insert into test2 (dt) values (?)", params}); updates.add(new Object[]{"insert into test2 (dt) values (?)", params}); ArrayList<List> massUpdate = test.runMassUpdate(updates); Assert.assertEquals(massUpdate.size(), 3); Assert.assertEquals(((List) massUpdate.get(0)).size(), 2); ArrayList metadata = UnsafeSqlHelper.runSqlUnsafe(provider, address, "select id from test2", JdbcConstants.ACTION_COMPLEX_LIST_METADATA, null); Assert.assertEquals(metadata.size(), 4); Assert.assertTrue(((List) metadata.get(0)).get(0).getClass().getName().contains("String")); ArrayList nometadata = UnsafeSqlHelper.runSqlUnsafe(provider, address, "select id from test2", JdbcConstants.ACTION_COMPLEX_LIST_NO_METADATA, null); Assert.assertEquals(nometadata.size(), 3); Assert.assertTrue(((List) nometadata.get(0)).get(0) instanceof Number); ArrayList ids = UnsafeSqlHelper.runSqlUnsafe(provider, address, "select id from test2", JdbcConstants.ACTION_LIST_FIRST_OBJECTS, null); Assert.assertTrue(ids.get(0) instanceof Number); test.runUpdate("drop table test2", null); } @Test public void testGenericUpdater() throws Exception { test.runUpdate("drop table test3", null); test.runUpdate("create table test3 (id integer, name varchar(250))", null); test.runUpdate("insert into test3 values (1,'a'),(2,'b'),(3,'c')", null); String query = "update test3 set name='x' where id"; GenericDbUpdater dbUpdater = GenericDbUpdater.getInstance(query, address); Assert.assertEquals(dbUpdater.getQuery(), query); Assert.assertEquals(dbUpdater.getDb(), address); dbUpdater.addToQueue(1); Thread.sleep(GenericDbUpdater.LONG_SEND_PERIOD); List list = test.getRecordList("select * from test3 where name='x'", null, false); Assert.assertEquals(list.size(), 1); ArrayList collection = new ArrayList(); collection.add(2); collection.add(3); dbUpdater.addToQueueAll(collection); int tries = 3; list = test.getRecordList("select * from test3 where name='x'", null, false); while (tries-- > 0 && list.size() != 3) { Thread.sleep(GenericDbUpdater.LONG_SEND_PERIOD); list = test.getRecordList("select * from test3 where name='x'", null, false); } Assert.assertEquals(list.size(), 3); test.runUpdate("drop table test3", null); } @Test public void testSqlFetcher() throws Exception { test.runUpdate("drop table test4", null); test.runUpdate("create table test4 (idx integer, name varchar(250))", null); test.runUpdate("insert into test4 values (1,'a'),(2,'b'),(300000,'c')", null); SqlRecordsFetcher nullFetcher = new SqlRecordsFetcher(null, "idx, name", "test4", "idx > 0"); RecordsRotatorI rotaterNull = RotatorsHolder.getRotater(nullFetcher); SqlRecordsFetcher recordsFetcher = new SqlRecordsFetcher(address, "idx, name", "test4", "idx > 0"); recordsFetcher.setIdColumn("idx"); recordsFetcher.setSelectType(JdbcConstants.ACTION_MAP_RESULTS_SET); System.out.println("recordsFetcher.getDescriptiveName() = " + recordsFetcher.getDescriptiveName()); recordsFetcher.setFieldsClause(recordsFetcher.getFieldsClause()); recordsFetcher.setWhereClause(recordsFetcher.getWhereClause()); recordsFetcher.setProviderI(recordsFetcher.getProviderI()); RecordsRotatorI rotater = RotatorsHolder.getRotater(recordsFetcher); SqlRecordsFetcher recordsFetcher2 = new SqlRecordsFetcher(address, "idx, name", "test4", "idx > 0"); Assert.assertEquals(recordsFetcher2.getIdColumn(), "id"); Assert.assertEquals(recordsFetcher2.getSelectType(), JdbcConstants.ACTION_MAP_RESULTS_SET); recordsFetcher2.setIdColumn("idx"); Assert.assertTrue(recordsFetcher.equals(recordsFetcher2)); recordsFetcher2.setSelectType(JdbcConstants.ACTION_COMPLEX_LIST_NO_METADATA); Assert.assertFalse(recordsFetcher.equals(recordsFetcher2)); RecordsRotatorI rotater2 = RotatorsHolder.getRotater(recordsFetcher2); int totalSteps = 100; int steps = totalSteps; while (rotater.getCurrentQueueSize() < 3 && steps { Thread.sleep(rotater.getFetchDelay() / totalSteps); } //after this sleeps, rotaters MUST fetch all data, since the reported count less than minSize Collection elements = rotater.getManyElements(100); Assert.assertEquals(elements.size(), 3); Collection elements2 = rotater2.getManyElements(100); Assert.assertEquals(elements2.size(), 3); Assert.assertTrue(elements.iterator().next() instanceof Map); Assert.assertTrue(elements2.iterator().next() instanceof List); test.runUpdate("drop table test4", null); } @Test public void testReplicator() throws Exception { test.runUpdate("drop table test5", null); test2.runUpdate("drop table test6", null); test.runUpdate("create table test5 (id integer, name varchar(250), dt timestamp)", null); test2.runUpdate("create table test6 (id integer, name varchar(250), dt timestamp)", null); test.runUpdate("drop table test8", null); test2.runUpdate("drop table test8", null); test.runUpdate("create table test8 (id integer, name varchar(250), dt timestamp)", null); test2.runUpdate("create table test8 (id integer, name varchar(250), dt varchar(45), moreone integer)", null); test.runUpdate("insert into test5 values (0,'X', NULL), (1, 'a', '2013-01-01 00:06:00.101'), (2, NULL, '2011-01-01 00:06:00.103'),(300000,'c', '2011-01-01 00:06:00')", null); test2.runUpdate("insert into test6 values (0,'Y', NULL), (1, 'not A', '2013-01-01 00:06:00.103'), (2, NULL, '2013-01-01 00:06:00.103'),(40,'b', '2013-01-01 00:06:00')", null); List list = test.getRecordList("select * from test5 order by id", null, false); Assert.assertEquals(list.size(), 4); List list2 = test2.getRecordList("select * from test6", null, false); Assert.assertEquals(list2.size(), 4); ReplicateTables replicator = new ReplicateTables(); replicator.init(null); replicator.dbFrom = address; replicator.dbTo = address2; replicator.dbToType = "hsqldb"; HashMap<String, String> tableInfo = new HashMap<String, String>(); tableInfo.put("name", "test5"); tableInfo.put("name2", "test6"); tableInfo.put("where1", " AND id > 0 "); tableInfo.put("where2", " AND id > 0 "); replicator.tables.add(tableInfo); replicator.runReplicate(); list2 = test2.getRecordList("select * from test6 order by id", null, false); Assert.assertEquals(list2.size(), 4); for (int i = 0; i < list.size(); i++) { Map m1 = (Map) list.get(i); Map m2 = (Map) list2.get(i); Object id = m1.get("ID"); if(id == null) { id = m1.get("id"); } if (id.equals(0)) { Assert.assertNotSame(m1, m2); } else { Assert.assertEquals(m1, m2); } } test2.runUpdate("delete from test6", null); replicator.runReplicate(); list2 = test2.getRecordList("select * from test6 order by id", null, false); Assert.assertEquals(list2.size(), 3); test.runUpdate("drop table test5", null); test2.runUpdate("drop table test6", null); tableInfo = new HashMap<String, String>(); tableInfo.put("name", "test8"); tableInfo.put("name2", "test8"); tableInfo.put("where1", ""); tableInfo.put("where2", ""); replicator.tables.clear(); replicator.tables.add(tableInfo); replicator.clearLog(); replicator.runReplicate(); String log = replicator.getLog(); Assert.assertTrue(log.contains("ERROR: Meta data")); test.runUpdate("drop table test8", null); test2.runUpdate("drop table test8", null); } }
// $Id: Cylinder.java 4131 2009-03-19 20:15:28Z blaine.dev $ package com.jme3.scene.shape; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.math.FastMath; import com.jme3.math.Vector3f; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer.Type; import com.jme3.util.BufferUtils; import java.io.IOException; public class Cylinder extends Mesh { private int axisSamples; private int radialSamples; private float radius; private float radius2; private float height; private boolean closed; private boolean inverted; /** * Default constructor for serialization only. Do not use. */ public Cylinder() { } /** * Creates a new Cylinder. By default its center is the origin. Usually, a * higher sample number creates a better looking cylinder, but at the cost * of more vertex information. * * @param axisSamples * Number of triangle samples along the axis. * @param radialSamples * Number of triangle samples along the radial. * @param radius * The radius of the cylinder. * @param height * The cylinder's height. */ public Cylinder(int axisSamples, int radialSamples, float radius, float height) { this(axisSamples, radialSamples, radius, height, false); } /** * Creates a new Cylinder. By default its center is the origin. Usually, a * higher sample number creates a better looking cylinder, but at the cost * of more vertex information. <br> * If the cylinder is closed the texture is split into axisSamples parts: * top most and bottom most part is used for top and bottom of the cylinder, * rest of the texture for the cylinder wall. The middle of the top is * mapped to texture coordinates (0.5, 1), bottom to (0.5, 0). Thus you need * a suited distorted texture. * * @param axisSamples * Number of triangle samples along the axis. * @param radialSamples * Number of triangle samples along the radial. * @param radius * The radius of the cylinder. * @param height * The cylinder's height. * @param closed * true to create a cylinder with top and bottom surface */ public Cylinder(int axisSamples, int radialSamples, float radius, float height, boolean closed) { this(axisSamples, radialSamples, radius, height, closed, false); } /** * Creates a new Cylinder. By default its center is the origin. Usually, a * higher sample number creates a better looking cylinder, but at the cost * of more vertex information. <br> * If the cylinder is closed the texture is split into axisSamples parts: * top most and bottom most part is used for top and bottom of the cylinder, * rest of the texture for the cylinder wall. The middle of the top is * mapped to texture coordinates (0.5, 1), bottom to (0.5, 0). Thus you need * a suited distorted texture. * * @param axisSamples The number of vertices samples along the axis. It is equal to the number of segments + 1; so * that, for instance, 4 samples mean the cylinder will be made of 3 segments. * @param radialSamples The number of triangle samples along the radius. For instance, 4 means that the sides of the * cylinder are made of 4 rectangles, and the top and bottom are made of 4 triangles. * @param radius * The radius of the cylinder. * @param height * The cylinder's height. * @param closed * true to create a cylinder with top and bottom surface * @param inverted * true to create a cylinder that is meant to be viewed from the * interior. */ public Cylinder(int axisSamples, int radialSamples, float radius, float height, boolean closed, boolean inverted) { this(axisSamples, radialSamples, radius, radius, height, closed, inverted); } public Cylinder(int axisSamples, int radialSamples, float radius, float radius2, float height, boolean closed, boolean inverted) { super(); updateGeometry(axisSamples, radialSamples, radius, radius2, height, closed, inverted); } /** * @return the number of samples along the cylinder axis */ public int getAxisSamples() { return axisSamples; } /** * @return Returns the height. */ public float getHeight() { return height; } /** * @return number of samples around cylinder */ public int getRadialSamples() { return radialSamples; } /** * @return Returns the radius. */ public float getRadius() { return radius; } public float getRadius2() { return radius2; } /** * @return true if end caps are used. */ public boolean isClosed() { return closed; } /** * @return true if normals and uvs are created for interior use */ public boolean isInverted() { return inverted; } /** * Rebuilds the cylinder based on a new set of parameters. * * @param axisSamples The number of vertices samples along the axis. It is equal to the number of segments + 1; so * that, for instance, 4 samples mean the cylinder will be made of 3 segments. * @param radialSamples The number of triangle samples along the radius. For instance, 4 means that the sides of the * cylinder are made of 4 rectangles, and the top and bottom are made of 4 triangles. * @param topRadius the radius of the top of the cylinder. * @param bottomRadius the radius of the bottom of the cylinder. * @param height the cylinder's height. * @param closed should the cylinder have top and bottom surfaces. * @param inverted is the cylinder is meant to be viewed from the inside. */ public void updateGeometry(int axisSamples, int radialSamples, float topRadius, float bottomRadius, float height, boolean closed, boolean inverted) { // Ensure there's at least two axis samples and 3 radial samples, and positive geometries. if( axisSamples < 2 || radialSamples < 3 || topRadius <= 0 || bottomRadius <= 0 || height <= 0 ) return; this.axisSamples = axisSamples; this.radialSamples = radialSamples; this.radius = bottomRadius; this.radius2 = topRadius; this.height = height; this.closed = closed; this.inverted = inverted; // Vertices : One per radial sample plus one duplicate for texture closing around the sides. int verticesCount = axisSamples * (radialSamples +1); // Triangles: Two per side rectangle, which is the product of numbers of samples. int trianglesCount = axisSamples * radialSamples * 2 ; if( closed ) { // If there are caps, add two additional rims and two summits. verticesCount += 2 + 2 * (radialSamples +1); // Add one triangle per radial sample, twice, to form the caps. trianglesCount += 2 * radialSamples ; } // Compute the points along a unit circle: float[][] circlePoints = new float[radialSamples+1][2]; for (int circlePoint = 0; circlePoint < radialSamples; circlePoint++) { float angle = FastMath.TWO_PI / radialSamples * circlePoint; circlePoints[circlePoint][0] = FastMath.cos(angle); circlePoints[circlePoint][1] = FastMath.sin(angle); } // Add an additional point for closing the texture around the side of the cylinder. circlePoints[radialSamples][0] = circlePoints[0][0]; circlePoints[radialSamples][1] = circlePoints[0][1]; // Calculate normals. // Let be B and C the top and bottom points of the axis, and A and D the top and bottom edges. // The normal in A and D is simply orthogonal to AD, which means we can get it once per sample. Vector3f[] circleNormals = new Vector3f[radialSamples+1]; for (int circlePoint = 0; circlePoint < radialSamples+1; circlePoint++) { // The normal is the orthogonal to the side, which can be got without trigonometry. // The edge direction is oriented so that it goes up by Height, and out by the radius difference; let's use // those values in reverse order. Vector3f normal = new Vector3f(height * circlePoints[circlePoint][0], height * circlePoints[circlePoint][1], bottomRadius - topRadius ); circleNormals[circlePoint] = normal.normalizeLocal(); } float[] vertices = new float[verticesCount * 3]; float[] normals = new float[verticesCount * 3]; float[] textureCoords = new float[verticesCount * 2]; int currentIndex = 0; // Add a circle of points for each axis sample. for(int axisSample = 0; axisSample < axisSamples; axisSample++ ) { float currentHeight = -height / 2 + height * axisSample / (axisSamples-1); float currentRadius = bottomRadius + (topRadius - bottomRadius) * axisSample / (axisSamples-1); for (int circlePoint = 0; circlePoint < radialSamples + 1; circlePoint++) { // Position, by multipliying the position on a unit circle with the current radius. vertices[currentIndex*3] = circlePoints[circlePoint][0] * currentRadius; vertices[currentIndex*3 +1] = circlePoints[circlePoint][1] * currentRadius; vertices[currentIndex*3 +2] = currentHeight; // Normal Vector3f currentNormal = circleNormals[circlePoint]; normals[currentIndex*3] = currentNormal.x; normals[currentIndex*3+1] = currentNormal.y; normals[currentIndex*3+2] = currentNormal.z; // Texture // The X is the angular position of the point. textureCoords[currentIndex *2] = (float) circlePoint / radialSamples; // Depending on whether there is a cap, the Y is either the height scaled to [0,1], or the radii of // the cap count as well. if (closed) textureCoords[currentIndex *2 +1] = (bottomRadius + height / 2 + currentHeight) / (bottomRadius + height + topRadius); else textureCoords[currentIndex *2 +1] = height / 2 + currentHeight; currentIndex++; } } // If closed, add duplicate rims on top and bottom, with normals facing up and down. if (closed) { // Bottom for (int circlePoint = 0; circlePoint < radialSamples + 1; circlePoint++) { vertices[currentIndex*3] = circlePoints[circlePoint][0] * bottomRadius; vertices[currentIndex*3 +1] = circlePoints[circlePoint][1] * bottomRadius; vertices[currentIndex*3 +2] = -height/2; normals[currentIndex*3] = 0; normals[currentIndex*3+1] = 0; normals[currentIndex*3+2] = -1; textureCoords[currentIndex *2] = (float) circlePoint / radialSamples; textureCoords[currentIndex *2 +1] = bottomRadius / (bottomRadius + height + topRadius); currentIndex++; } // Top for (int circlePoint = 0; circlePoint < radialSamples + 1; circlePoint++) { vertices[currentIndex*3] = circlePoints[circlePoint][0] * topRadius; vertices[currentIndex*3 +1] = circlePoints[circlePoint][1] * topRadius; vertices[currentIndex*3 +2] = height/2; normals[currentIndex*3] = 0; normals[currentIndex*3+1] = 0; normals[currentIndex*3+2] = 1; textureCoords[currentIndex *2] = (float) circlePoint / radialSamples; textureCoords[currentIndex *2 +1] = (bottomRadius + height) / (bottomRadius + height + topRadius); currentIndex++; } // Add the centers of the caps. vertices[currentIndex*3] = 0; vertices[currentIndex*3 +1] = 0; vertices[currentIndex*3 +2] = -height/2; normals[currentIndex*3] = 0; normals[currentIndex*3+1] = 0; normals[currentIndex*3+2] = -1; textureCoords[currentIndex *2] = 0.5f; textureCoords[currentIndex *2+1] = 0f; currentIndex++; vertices[currentIndex*3] = 0; vertices[currentIndex*3 +1] = 0; vertices[currentIndex*3 +2] = height/2; normals[currentIndex*3] = 0; normals[currentIndex*3+1] = 0; normals[currentIndex*3+2] = 1; textureCoords[currentIndex *2] = 0.5f; textureCoords[currentIndex *2+1] = 1f; } // Add the triangles indexes. short[] indices = new short[trianglesCount * 3]; currentIndex = 0; for (short axisSample = 0; axisSample < axisSamples - 1; axisSample++) { for (int circlePoint = 0; circlePoint < radialSamples; circlePoint++) { indices[currentIndex++] = (short) (axisSample * (radialSamples + 1) + circlePoint); indices[currentIndex++] = (short) (axisSample * (radialSamples + 1) + circlePoint + 1); indices[currentIndex++] = (short) ((axisSample + 1) * (radialSamples + 1) + circlePoint); indices[currentIndex++] = (short) ((axisSample + 1) * (radialSamples + 1) + circlePoint); indices[currentIndex++] = (short) (axisSample * (radialSamples + 1) + circlePoint + 1); indices[currentIndex++] = (short) ((axisSample + 1) * (radialSamples + 1) + circlePoint + 1); } } // Add caps if needed. if(closed) { short bottomCapIndex = (short) (verticesCount - 2); short topCapIndex = (short) (verticesCount - 1); int bottomRowOffset = (axisSamples) * (radialSamples +1 ); int topRowOffset = (axisSamples+1) * (radialSamples +1 ); for (int circlePoint = 0; circlePoint < radialSamples; circlePoint++) { indices[currentIndex++] = (short) (bottomRowOffset + circlePoint +1); indices[currentIndex++] = (short) (bottomRowOffset + circlePoint); indices[currentIndex++] = bottomCapIndex; indices[currentIndex++] = (short) (topRowOffset + circlePoint); indices[currentIndex++] = (short) (topRowOffset + circlePoint +1); indices[currentIndex++] = topCapIndex; } } // If inverted, the triangles and normals are all reverted. if (inverted) { for (int i = 0; i < indices.length / 2; i++) { short temp = indices[i]; indices[i] = indices[indices.length - 1 - i]; indices[indices.length - 1 - i] = temp; } for(int i = 0; i< normals.length; i++) { normals[i] = -normals[i]; } } // Fill in the buffers. setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(vertices)); setBuffer(Type.Normal, 3, BufferUtils.createFloatBuffer(normals)); setBuffer(Type.TexCoord, 2, BufferUtils.createFloatBuffer(textureCoords)); setBuffer(Type.Index, 3, BufferUtils.createShortBuffer(indices)); updateBound(); setStatic(); } @Override public void read(JmeImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); axisSamples = capsule.readInt("axisSamples", 0); radialSamples = capsule.readInt("radialSamples", 0); radius = capsule.readFloat("radius", 0); radius2 = capsule.readFloat("radius2", 0); height = capsule.readFloat("height", 0); closed = capsule.readBoolean("closed", false); inverted = capsule.readBoolean("inverted", false); } @Override public void write(JmeExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(axisSamples, "axisSamples", 0); capsule.write(radialSamples, "radialSamples", 0); capsule.write(radius, "radius", 0); capsule.write(radius2, "radius2", 0); capsule.write(height, "height", 0); capsule.write(closed, "closed", false); capsule.write(inverted, "inverted", false); } }
package uk.ac.hw.macs.bisel.phis.iqs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.util.Enumeration; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * Connects client (presumably a GUI) to the SOLR API that wraps the SOLR repository * for image channels * * @author kcm */ public class GetChannel extends HttpServlet { private static final String url = "http://beta.phenoimageshare.org/data/rest/getChannel?"; // stem of every SOLR query private static final Logger logger = Logger.getLogger(System.class.getName()); /** * Enables discovery of channel information for a single channel. * * Handles requests from the PhIS UI by simply forwarding them to the SOLR API and * then returning the result directly to the UI. Provides very basic error handling * (only deals with unknown parameters). * * * This has no need for pagination as only 1 channel can be returned per query * * NOTE: this communicates with SOLR API not the SOLR core directly * * Parameters expected: * <ol> * <li>id = channel ID, e.g., komp2_channel_112003_0</li> * </ol> * * Future versions will: * <ol> * <li>send queries to the SIS, and then integrate the results * with those from SOLR</li> * <li>likely to include sorting the results</li> * <li>include a wider range of query parameters</li> * <li>provide access to the "OLS" functionality from SOLR</li> * </ol> * * * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set response type to JS and allow programs from other servers to send and receive response.setContentType("application/json;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); boolean error = false; // has an error been detected? String solrResult = ""; // JSON doc sent back to UI // create URL for SOLR query String queryURL = url; boolean first = true; Map<String, String[]> params = request.getParameterMap(); // get map of parameters and their values Enumeration<String> allParams = request.getParameterNames(); // get a list of parameter names if (allParams.hasMoreElements()) { String param = allParams.nextElement(); if (param.equalsIgnoreCase("id")) { // ID of channel if (!first) { // at the moment it will always be the first (and only) param queryURL += "&"; } queryURL += "channelId=" + params.get("id")[0]; // extend stem with parameter first = false; // next time you need a separator } else { // parameter was not recognised, send error error = true; // error has been detected logger.log(Level.WARNING, "Client sent invalid parameter: "+param); solrResult = "{\"invalid_paramater\": \"" + param + "\"}"; } } // should write query to log? // run query against SOLR API if (!error) { // if no error detected BufferedReader in = null; try { // connect to SOLR API and run query URL url = new URL(queryURL); in = new BufferedReader(new InputStreamReader(url.openStream())); // read JSON result String inputLine; if ((inputLine = in.readLine()) != null) { // should only be 1 line of result // send result directly to client, should be no need to process (at the moment) solrResult = inputLine; } } catch (IOException e) { logger.log(Level.WARNING, e.getMessage()); solrResult = "{\"server_error\": \""+e.getMessage()+"\"}"; } } // send result to client (UI) PrintWriter out = response.getWriter(); try { out.println(solrResult); // may be error or genuine result } finally { out.close(); } } /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Simple service that wraps the SOLR API to enable searching of channel information"; }// </editor-fold> }
package java.lang; public final class String { /** * The value is used for character storage. */ private char value[]; /** * The offset is the first index of the storage that is used. */ private final int offset; /** * The count is the number of characters in the String. */ private final int count; public String() { this.offset = 0; this.count = 0; this.value = new char[0]; } public String(char value[]) { int size = value.length; this.offset = 0; this.count = size; char[] buf = new char[size]; for (int i = 0; i < value.length; i++) { buf[i] = value[i]; } this.value = buf; } String(int offset, int count, char value[]) { this.offset = offset; this.count = count; this.value = value; } public String concat(String str) { int otherLen = str.count; if (otherLen == 0) { return this; } char buf[] = new char[count + otherLen]; getChars(0, count, buf, 0); str.getChars(0, otherLen, buf, count); return new String(0, count + otherLen, buf); } public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { for (int i = srcBegin; i < srcEnd; i++) { dst[dstBegin + i - srcBegin] = charAt(i); } } public char charAt(int index) { if ((index < 0) || (index >= count)) { throw new StringIndexOutOfBoundsException(index); } return value[index + offset]; } @Override public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String) anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n if (v1[i++] != v2[j++]) return false; } return true; } } return false; } public int length() { return count; } @Override public String toString() { return this; } @Override public int hashCode() { int hash = 0; for(int i = 0; i < count; i++) { hash += charAt(i) * Math.pow(31, count - i - 1); } return hash; } public char[] toCharArray() { char[] arr = new char[count]; for (int i = 0; i < arr.length; ++i) { arr[i] = value[offset + i]; } return arr; } }
package road.movementservice; import aidas.userservice.IUserManager; import aidas.userservice.UserManager; import aidas.userservice.exceptions.UserSystemException; import road.movemententities.entities.Vehicle; import road.movemententities.entities.VehicleOwnership; import road.movemententityaccess.dao.*; import road.movementservice.servers.BillServer; import road.movementservice.servers.CarServer; import road.movementservice.servers.DriverServer; import road.movementservice.servers.PoliceServer; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.GregorianCalendar; public class Server { private LaneDAO laneDAO; private EdgeDAO edgeDAO; private VehicleDAO vehicleDAO; private ConnectionDAO connectionDAO; private InvoiceDAO invoiceDAO; private MovementDAO movementDAO; private DriverServer driverServer; private BillServer billServer; private PoliceServer policeServer; private CarServer carServer; /** * The user manager which is used to process all authentication requests. */ private IUserManager userManager; /** * this method is used to initialize all the different services. */ public void init() { EntityManagerFactory emfUserService = Persistence.createEntityManagerFactory("UserServicePU"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("MovementPU"); this.userManager = new UserManager(emfUserService); // Create a user for debugging. try { this.userManager.register("admin", "aidas123"); } catch (UserSystemException e) { e.printStackTrace(); } this.laneDAO = new LaneDAOImpl(emf); this.edgeDAO = new EdgeDAOImpl(emf); this.vehicleDAO = new VehicleDAOImpl(emf); this.connectionDAO = new ConnectionDAOImpl(emf); this.invoiceDAO = new InvoiceDAOImpl(emf); this.movementDAO = new MovementDAOImpl(emf); this.driverServer = new DriverServer(this.userManager, this.laneDAO, this.connectionDAO, this.edgeDAO, this.vehicleDAO); this.driverServer.init(); this.billServer = new BillServer(this.invoiceDAO, this.userManager, this.movementDAO); this.billServer.init(); this.policeServer = new PoliceServer(); this.policeServer.init(); this.carServer = new CarServer(new EntityDAOImpl(emf)); this.carServer.init(); this.fillDatabase(emf); } /** * Function to fill the database with test data. * @param emf the entity manager factory used for getting the {@link EntityManager}. */ private void fillDatabase(EntityManagerFactory emf) { EntityManager em = emf.createEntityManager(); Vehicle v = new Vehicle("AA-12-BB"); VehicleOwnership vo = new VehicleOwnership(v, 1, new GregorianCalendar(), null); em.persist(v); em.persist(vo); } }
package brooklyn.entity.dns; import java.math.BigDecimal; import java.net.InetAddress; import brooklyn.entity.Entity; import brooklyn.location.Location; import brooklyn.location.MachineLocation; /** * Encapsulates geo-IP information for a given host. */ public class HostGeoInfo { public final String address; public final String displayName; public final double latitude; public final double longitude; public static HostGeoInfo fromLocation(Location l) { InetAddress address = findIpAddress(l); Object latitude = l.findLocationProperty("latitude"); Object longitude = l.findLocationProperty("longitude"); if (address == null || latitude == null || longitude == null) return null; if (latitude instanceof BigDecimal) latitude = ((BigDecimal) latitude).doubleValue(); if (longitude instanceof BigDecimal) longitude = ((BigDecimal) longitude).doubleValue(); if (!(latitude instanceof Double) || !(longitude instanceof Double)) throw new IllegalArgumentException("Passed location specifies invalid type of lat/long"); return new HostGeoInfo(address.toString(), l.getName(), (Double) latitude, (Double) longitude); } public static HostGeoInfo fromEntity(Entity e) { for (Location l : e.getLocations()) { HostGeoInfo hgi = fromLocation(l); if (hgi != null) return hgi; } return null; } public static InetAddress findIpAddress(Location l) { if (l == null) return null; if (l instanceof MachineLocation) return ((MachineLocation) l).getAddress(); return findIpAddress(l.getParentLocation()); } public HostGeoInfo(String address, String displayName, double latitude, double longitude) { this.address = address; this.displayName = displayName; this.latitude = latitude; this.longitude = longitude; } @Override public String toString() { return "ServerGeoInfo["+displayName+": "+address+" at ("+latitude+","+longitude+")]"; } @Override public boolean equals(Object o) { // Slight cheat: only tests the address field. return (o instanceof HostGeoInfo) && address.equals(((HostGeoInfo) o).address); } @Override public int hashCode() { // Slight cheat: only includes the address field. return address.hashCode(); } }
package ezdb.leveldb.util; import java.nio.ByteBuffer; import java.util.Comparator; import java.util.Map.Entry; import org.iq80.leveldb.util.Slice; import ezdb.LazyGetter; import ezdb.RawTableRow; import ezdb.TableRow; import ezdb.serde.Serde; public class Slices { public static ByteBuffer unwrap(final Slice slice) { return ByteBuffer.wrap(slice.getRawArray(), slice.getRawOffset(), slice.length()); } public static ByteBuffer unwrapSlice(final Slice slice, final int index, final int length) { return ByteBuffer.wrap(slice.getRawArray(), slice.getRawOffset() + index, length).slice(); } public static Slice wrap(final ByteBuffer buffer) { return new Slice(buffer.array(), buffer.position(), buffer.remaining()); } public static <H, R, V> TableRow<H, R, V> newRawTableRow(final Entry<Slice, Slice> rawRow, final Serde<H> hashKeySerde, final Serde<R> rangeKeySerde, final Serde<V> valueSerde) { // extract hashKeyBytes/rangeKeyBytes only if needed final LazyGetter<Entry<ByteBuffer, ByteBuffer>> hashKeyBytes_rangeKeyBytes = new LazyGetter<Entry<ByteBuffer, ByteBuffer>>() { @Override protected Entry<ByteBuffer, ByteBuffer> internalGet() { final Slice compoundKeyBytes = rawRow.getKey(); int index = 0; // leveldb stores data in little endian final int hashKeyBytesLength = Integer.reverseBytes(compoundKeyBytes.getInt(index)); index += Integer.BYTES; final ByteBuffer hashKeyBytes = unwrapSlice(compoundKeyBytes, index, hashKeyBytesLength); index += hashKeyBytesLength; final int rangeKeyBytesLength = Integer.reverseBytes(compoundKeyBytes.getInt(index)); index += Integer.BYTES; final ByteBuffer rangeKeyBytes; if (rangeKeyBytesLength > 0) { rangeKeyBytes = unwrapSlice(compoundKeyBytes, index, rangeKeyBytesLength); } else { rangeKeyBytes = null; } return new Entry<ByteBuffer, ByteBuffer>() { @Override public ByteBuffer setValue(final ByteBuffer value) { throw new UnsupportedOperationException(); } @Override public ByteBuffer getValue() { if (rangeKeyBytes != null) { rangeKeyBytes.clear(); } return rangeKeyBytes; } @Override public ByteBuffer getKey() { hashKeyBytes.clear(); return hashKeyBytes; } }; } }; final LazyGetter<H> hashKey = new LazyGetter<H>() { @Override protected H internalGet() { final ByteBuffer hashKeyBytes = hashKeyBytes_rangeKeyBytes.get().getKey(); return hashKeySerde.fromBuffer(hashKeyBytes); } }; final LazyGetter<R> rangeKey = new LazyGetter<R>() { @Override protected R internalGet() { final ByteBuffer rangeKeyBytes = hashKeyBytes_rangeKeyBytes.get().getValue(); if (rangeKeyBytes == null) { return null; } else { return rangeKeySerde.fromBuffer(rangeKeyBytes); } } }; final LazyGetter<V> value = new LazyGetter<V>() { @Override protected V internalGet() { final ByteBuffer valueBytes = unwrap(rawRow.getValue()); return valueSerde.fromBuffer(valueBytes); } }; return new RawTableRow<>(hashKey, rangeKey, value); } public static int compareKeys(final Comparator<ByteBuffer> hashKeyComparator, final Comparator<ByteBuffer> rangeKeyComparator, final Slice k1, final Slice k2) { // First hash key int k1Index = 0; // leveldb stores data in little endian final int k1HashKeyLength = Integer.reverseBytes(k1.getInt(k1Index)); k1Index += Integer.BYTES; final ByteBuffer k1HashKeyBytes = unwrapSlice(k1, k1Index, k1HashKeyLength); // Second hash key int k2Index = 0; final int k2HashKeyLength = Integer.reverseBytes(k2.getInt(k2Index)); k2Index += Integer.BYTES; final ByteBuffer k2HashKeyBytes = unwrapSlice(k2, k2Index, k2HashKeyLength); final int hashComparison = hashKeyComparator.compare(k1HashKeyBytes, k2HashKeyBytes); if (rangeKeyComparator != null && hashComparison == 0) { // First range key k1Index += k1HashKeyLength; final int k1RangeKeyLength = Integer.reverseBytes(k1.getInt(k1Index)); k1Index += Integer.BYTES; final ByteBuffer k1RangeKeyBytes = unwrapSlice(k1, k1Index, k1RangeKeyLength); // Second range key k2Index += k2HashKeyLength; final int k2RangeKeyLength = Integer.reverseBytes(k2.getInt(k2Index)); k2Index += Integer.BYTES; final ByteBuffer k2RangeKeyBytes = unwrapSlice(k2, k2Index, k2RangeKeyLength); return rangeKeyComparator.compare(k1RangeKeyBytes, k2RangeKeyBytes); } return hashComparison; } }
package org.eigenbase.sql.fun; import org.eigenbase.sql.parser.SqlParserPos; import org.eigenbase.sql.test.SqlTester; import org.eigenbase.sql.test.SqlOperatorTests; import org.eigenbase.sql.*; import org.eigenbase.sql.validate.SqlValidatorScope; import org.eigenbase.sql.validate.SqlValidator; import org.eigenbase.util.EnumeratedValues; /** * An operator describing a window specification. * * <p> * Operands are as follows: * * <ul> * <li> * 0: name of referenced window ({@link SqlIdentifier}) * </li> * <li> * 1: partition clause ({@link SqlNodeList}) * </li> * <li> * 2: order clause ({@link SqlNodeList}) * </li> * <li> * 3: isRows ({@link SqlLiteral}) * </li> * <li> * 4: lowerBound ({@link SqlNode}) * </li> * <li> * 5: upperBound ({@link SqlNode}) * </li> * </ul> * * All operands are optional. * </p> * * @author jhyde * @since Oct 19, 2004 * @version $Id$ **/ public class SqlWindowOperator extends SqlOperator { /** * The FOLLOWING operator used exclusively in a window specification. */ private final SqlPostfixOperator followingOperator = new SqlPostfixOperator("FOLLOWING", SqlKind.Other, 10, null, null, null); /** * The PRECEDING operator used exclusively in a window specification. */ private final SqlPostfixOperator precedingOperator = new SqlPostfixOperator("PRECEDING", SqlKind.Other, 10, null, null, null); public SqlWindowOperator() { super("WINDOW", SqlKind.Window, 1, true, null, null, null); } public SqlSyntax getSyntax() { return SqlSyntax.Special; } public SqlCall createCall( SqlNode[] operands, SqlParserPos pos) { return new SqlWindow(this, operands, pos); } public SqlWindow createCall( SqlIdentifier declName, SqlIdentifier refName, SqlNodeList partitionList, SqlNodeList orderList, boolean isRows, SqlNode lowerBound, SqlNode upperBound, SqlParserPos pos) { return (SqlWindow) createCall( new SqlNode[] { declName, refName, partitionList, orderList, SqlLiteral.createBoolean(isRows, pos), lowerBound, upperBound }, pos); } public void unparse( SqlWriter writer, SqlNode[] operands, int leftPrec, int rightPrec) { writer.print("("); SqlIdentifier refName = (SqlIdentifier) operands[SqlWindow.RefName_OPERAND]; int clauseCount = 0; if (refName != null) { refName.unparse(writer, 0, 0); ++clauseCount; } SqlNodeList partitionList = (SqlNodeList) operands[SqlWindow.PartitionList_OPERAND]; if (partitionList != null) { if (clauseCount++ > 0) { writer.println(); } writer.print("PARTITION BY "); partitionList.unparse(writer, 0, 0); } SqlNodeList orderList = (SqlNodeList) operands[SqlWindow.OrderList_OPERAND]; if (orderList != null) { if (clauseCount++ > 0) { writer.println(); } writer.print("ORDER BY "); orderList.unparse(writer, 0, 0); } boolean isRows = SqlLiteral.booleanValue(operands[SqlWindow.IsRows_OPERAND]); SqlNode lowerBound = operands[SqlWindow.LowerBound_OPERAND], upperBound = operands[SqlWindow.UpperBound_OPERAND]; if (lowerBound == null) { // No ROWS or RANGE clause } else if (upperBound == null) { if (clauseCount++ > 0) { writer.println(); } if (isRows) { writer.print("ROWS "); } else { writer.print("RANGE "); } lowerBound.unparse(writer, 0, 0); } else { if (clauseCount++ > 0) { writer.println(); } if (isRows) { writer.print("ROWS BETWEEN "); } else { writer.print("RANGE BETWEEN "); } lowerBound.unparse(writer, 0, 0); writer.print(" AND "); upperBound.unparse(writer, 0, 0); } writer.print(")"); } public void validateCall( SqlCall call, SqlValidator validator, SqlValidatorScope scope, SqlValidatorScope operandScope) { // TODO: validate assert call.operator == this; final SqlNode [] operands = call.operands; SqlIdentifier refName = (SqlIdentifier) operands[SqlWindow.RefName_OPERAND]; SqlNodeList partitionList = (SqlNodeList) operands[SqlWindow.PartitionList_OPERAND]; SqlNodeList orderList = (SqlNodeList) operands[SqlWindow.OrderList_OPERAND]; if (orderList != null) { for (int i = 0; i < orderList.size(); i++) { SqlNode orderItem = orderList.get(i); orderItem.validate(validator, scope); } } boolean isRows = SqlLiteral.booleanValue(operands[SqlWindow.IsRows_OPERAND]); SqlNode lowerBound = operands[SqlWindow.LowerBound_OPERAND], upperBound = operands[SqlWindow.UpperBound_OPERAND]; } public void test(SqlTester tester) { SqlOperatorTests.testWindow(tester); } /** * An enumeration of types of bounds in a window: <code>CURRENT ROW</code>, * <code>UNBOUNDED PRECEDING</code>, and <code>UNBOUNDED FOLLOWING</code>. */ static class Bound extends EnumeratedValues.BasicValue { private Bound(String name, int ordinal) { super(name, ordinal, null); } public static final Bound CurrentRow = new Bound("CURRENT ROW", 0); public static final Bound UnboundedPreceding = new Bound("UNBOUNDED PRECEDING", 1); public static final Bound UnboundedFollowing = new Bound("UNBOUNDED FOLLOWING", 2); } public SqlNode createCurrentRow(SqlParserPos pos) { return SqlLiteral.createSymbol(Bound.CurrentRow, pos); } public SqlNode createUnboundedFollowing(SqlParserPos pos) { return SqlLiteral.createSymbol(Bound.UnboundedFollowing, pos); } public SqlNode createUnboundedPreceding(SqlParserPos pos) { return SqlLiteral.createSymbol(Bound.UnboundedPreceding, pos); } public SqlNode createFollowing(SqlLiteral literal, SqlParserPos pos) { return followingOperator.createCall(literal, pos); } public SqlNode createPreceding(SqlLiteral literal, SqlParserPos pos) { return precedingOperator.createCall(literal, pos); } public SqlNode createBound(SqlLiteral range) { return range; } } // End SqlWindowOperator.java
package edu.umd.cs.findbugs.cloud; import java.awt.GraphicsEnvironment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import javax.swing.JOptionPane; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugRanker; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.I18N; import edu.umd.cs.findbugs.PackageStats; import edu.umd.cs.findbugs.PluginLoader; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.ProjectStats; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.StartTime; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.SourceFile; import edu.umd.cs.findbugs.gui2.MainFrame; import edu.umd.cs.findbugs.gui2.ViewFilter; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.Multiset; import edu.umd.cs.findbugs.util.Util; /** * @author pwilliam */ public class DBCloud extends AbstractCloud { final static long minimumTimestamp = java.util.Date.parse("Oct 1, 2008"); Mode mode = Mode.VOTING; public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } class BugData { final String instanceHash; public BugData(String instanceHash) { this.instanceHash = instanceHash; } int id; boolean inDatabase; long firstSeen; String bugLink = NONE; String filedBy; String bugStatus; String bugAssignedTo; String bugComponentName; long bugFiled = Long.MAX_VALUE; SortedSet<BugDesignation> designations = new TreeSet<BugDesignation>(); Collection<BugInstance> bugs = new LinkedHashSet<BugInstance>(); @CheckForNull BugDesignation getPrimaryDesignation() { for (BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return bd; return null; } @CheckForNull BugDesignation getUserDesignation() { for(BugDesignation d : designations) if (findbugsUser.equals(d.getUser())) return new BugDesignation(d); return null; } Iterable<BugDesignation> getUniqueDesignations() { if (designations.isEmpty()) return Collections.emptyList(); HashSet<String> reviewers = new HashSet<String>(); ArrayList<BugDesignation> result = new ArrayList<BugDesignation>(designations.size()); for(BugDesignation d : designations) if (reviewers.add(d.getUser())) result.add(d); return result; } Set<String> getReviewers() { HashSet<String> reviewers = new HashSet<String>(); for(BugDesignation bd : designations) reviewers.add(bd.getUser()); reviewers.remove(""); reviewers.remove(null); return reviewers; } boolean isClaimed() { for(BugDesignation bd : getUniqueDesignations()) { if (bd.getDesignationKey().equals(UserDesignation.I_WILL_FIX.name())) return true; } return false; } BugDesignation getNonnullUserDesignation() { BugDesignation d = getUserDesignation(); if (d != null) return d; d = new BugDesignation(UserDesignation.UNCLASSIFIED.name(), System.currentTimeMillis(), "", findbugsUser); return d; } public boolean canSeeCommentsByOthers() { switch(mode) { case SECRET: return false; case COMMUNAL : return true; case VOTING : return hasVoted(); } throw new IllegalStateException(); } public boolean hasVoted() { for(BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return true; return false; } } int updatesSentToDatabase; Date lastUpdate = new Date(); Date resync; Date attemptedResync; int resyncCount; Map<String, BugData> instanceMap = new HashMap<String, BugData>(); Map<Integer, BugData> idMap = new HashMap<Integer, BugData>(); IdentityHashMap<BugDesignation, Integer> bugDesignationId = new IdentityHashMap<BugDesignation, Integer>(); BugData getBugData(String instanceHash) { BugData bd = instanceMap.get(instanceHash); if (bd == null) { bd = new BugData(instanceHash); instanceMap.put(instanceHash, bd); } return bd; } BugData getBugData(BugInstance bug) { try { initialSyncDone.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } BugData bugData = getBugData(bug.getInstanceHash()); bugData.bugs.add(bug); return bugData; } void loadDatabaseInfo(String hash, int id, long firstSeen) { BugData bd = instanceMap.get(hash); if (bd == null) return; if (idMap.containsKey(id)) { assert bd == idMap.get(id); assert bd.id == id; assert bd.firstSeen == firstSeen; } else { bd.id = id; bd.firstSeen = firstSeen; bd.inDatabase = true; idMap.put(id, bd); } } DBCloud(BugCollection bugs) { super(bugs); } static final Pattern FORBIDDEN_PACKAGE_PREFIXES = Pattern.compile(SystemProperties.getProperty("findbugs.forbiddenPackagePrefixes", " none ").replace(',','|')); static final boolean PROMPT_FOR_USER_NAME = SystemProperties.getBoolean("findbugs.db.promptForUserName", false); int sessionId = -1; final CountDownLatch initialSyncDone = new CountDownLatch(1); public void bugsPopulated() { queue.add(new PopulateBugs(true)); } long boundDuration(long milliseconds) { if (milliseconds < 0) return 0; if (milliseconds > 1000*1000) return 1000*1000; return milliseconds; } static boolean invocationRecorded; class PopulateBugs implements Update { final boolean performFullLoad; PopulateBugs(boolean performFullLoad) { this.performFullLoad = performFullLoad; } public void execute(DatabaseSyncTask t) throws SQLException { if (startShutdown) return; String commonPrefix = null; int updates = 0; if (performFullLoad) { for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { commonPrefix = Util.commonPrefix(commonPrefix, b.getPrimaryClass().getClassName()); getBugData(b.getInstanceHash()).bugs.add(b); } if (commonPrefix == null) commonPrefix = "<no bugs>"; else if (commonPrefix.length() > 128) commonPrefix = commonPrefix.substring(0, 128); } try { long startTime = System.currentTimeMillis(); Connection c = getConnection(); PreparedStatement ps; ResultSet rs; if (performFullLoad) { ps = c.prepareStatement("SELECT id, hash, firstSeen FROM findbugs_issue"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String hash = rs.getString(col++); Timestamp firstSeen = rs.getTimestamp(col++); loadDatabaseInfo(hash, id, firstSeen.getTime()); } rs.close(); ps.close(); } if (startShutdown) return; ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); BugData data = idMap.get(issueId); if (data != null) { BugDesignation bd = new BugDesignation(designation, when.getTime(), comment, who); if (data.designations.add(bd)) { bugDesignationId.put(bd, id); updates++; } } } rs.close(); ps.close(); if (startShutdown) return; ps = c .prepareStatement("SELECT hash, bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; String hash = rs.getString(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String status = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); BugData data = instanceMap.get(hash); if (data != null) { if (Util.nullSafeEquals(data.bugLink, bugReportId) && Util.nullSafeEquals(data.filedBy, whoFiled) && data.bugFiled == whenFiled.getTime() && Util.nullSafeEquals(data.bugAssignedTo, assignedTo) && Util.nullSafeEquals(data.bugStatus, status) && Util.nullSafeEquals(data.bugComponentName, componentName)) continue; data.bugLink = bugReportId; data.filedBy = whoFiled; data.bugFiled = whenFiled.getTime(); data.bugAssignedTo = assignedTo; data.bugStatus = status; data.bugComponentName = componentName; updates++; } } rs.close(); ps.close(); if (startShutdown) return; if (!invocationRecorded) { long jvmStartTime = StartTime.START_TIME - StartTime.VM_START_TIME; SortedBugCollection sbc = (SortedBugCollection) bugCollection; long findbugsStartTime = sbc.getTimeStartedLoading() - StartTime.START_TIME; URL findbugsURL = PluginLoader.getCoreResource("findbugs.xml"); String loadURL = findbugsURL == null ? "" : findbugsURL.toString(); long initialLoadTime = sbc.getTimeFinishedLoading() - sbc.getTimeStartedLoading(); long lostTime = startTime - sbc.getTimeStartedLoading(); long initialSyncTime = System.currentTimeMillis() - sbc.getTimeFinishedLoading(); String os = SystemProperties.getProperty("os.name", ""); String osVersion = SystemProperties.getProperty("os.version"); String jvmVersion = SystemProperties.getProperty("java.runtime.version"); if (osVersion != null) os = os +" " + osVersion; PreparedStatement insertSession = c .prepareStatement( "INSERT INTO findbugs_invocation (who, entryPoint, dataSource, fbVersion, os, jvmVersion, jvmLoadTime, findbugsLoadTime, analysisLoadTime, initialSyncTime, numIssues, startTime, commonPrefix)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp now = new Timestamp(startTime); int col = 1; insertSession.setString(col++, findbugsUser); insertSession.setString(col++, limitToMaxLength(loadURL, 128)); insertSession.setString(col++, limitToMaxLength(sbc.getDataSource(), 128)); insertSession.setString(col++, Version.RELEASE); insertSession.setString(col++, limitToMaxLength(os,128)); insertSession.setString(col++, limitToMaxLength(jvmVersion,64)); insertSession.setLong(col++, boundDuration(jvmStartTime)); insertSession.setLong(col++, boundDuration(findbugsStartTime)); insertSession.setLong(col++, boundDuration(initialLoadTime)); insertSession.setLong(col++, boundDuration(initialSyncTime)); insertSession.setInt(col++, bugCollection.getCollection().size()); insertSession.setTimestamp(col++, now); insertSession.setString(col++, commonPrefix); int rowCount = insertSession.executeUpdate(); rs = insertSession.getGeneratedKeys(); if (rs.next()) { sessionId = rs.getInt(1); } insertSession.close(); rs.close(); invocationRecorded = true; } c.close(); } catch (Exception e) { e.printStackTrace(); displayMessage("problem bulk loading database", e); } if (startShutdown) return; if (!performFullLoad) { attemptedResync = new Date(); if (updates > 0) { resync = attemptedResync; resyncCount = updates; } } else { for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { BugData bd = getBugData(b.getInstanceHash()); if (!bd.inDatabase) { storeNewBug(b); } else { long firstVersion = b.getFirstVersion(); long firstSeen = bugCollection.getAppVersionFromSequenceNumber(firstVersion).getTimestamp(); if (firstSeen < minimumTimestamp) { firstSeen = System.currentTimeMillis(); // displayMessage("Got timestamp of " + firstSeen + " which is equal to " + new Date(firstSeen)); } else if (firstSeen < bd.firstSeen) { bd.firstSeen = firstSeen; storeFirstSeen(bd); } BugDesignation designation = bd.getPrimaryDesignation(); if (designation != null) b.setUserDesignation(new BugDesignation(designation)); } } initialSyncDone.countDown(); assert !scheduled; if (startShutdown) return; long delay = 10*60*1000; // 10 minutes if (!scheduled) { try { resyncTimer.schedule(new TimerTask() { @Override public void run() { if (attemptedResync == null || lastUpdate.after(attemptedResync) || numSkipped++ > 6) { numSkipped = 0; queue.add(new PopulateBugs(false)); } }}, delay, delay); } catch (Exception e) { AnalysisContext.logError("Error scheduling resync", e); } } scheduled = true; } updatedStatus(); } } boolean scheduled = false; int numSkipped = 0; private static String limitToMaxLength(String s, int maxLength) { if (s.length() <= maxLength) return s; return s.substring(0, maxLength); } private String getProperty(String propertyName) { return SystemProperties.getProperty("findbugs.jdbc." + propertyName); } final static int MAX_DB_RANK = SystemProperties.getInt("findbugs.db.maxrank", 12); String url, dbUser, dbPassword, findbugsUser, dbName; @CheckForNull Pattern sourceFileLinkPattern; String sourceFileLinkFormat; String sourceFileLinkFormatWithLine; String sourceFileLinkToolTip; ProjectPackagePrefixes projectMapping = new ProjectPackagePrefixes(); Map<String,String> prefixBugComponentMapping = new HashMap<String,String>(); Connection getConnection() throws SQLException { return DriverManager.getConnection(url, dbUser, dbPassword); } public boolean initialize() { String sp = SystemProperties.getProperty("findbugs.sourcelink.pattern"); String sf = SystemProperties.getProperty("findbugs.sourcelink.format"); String sfwl = SystemProperties.getProperty("findbugs.sourcelink.formatWithLine"); String stt = SystemProperties.getProperty("findbugs.sourcelink.tooltip"); if (sp != null && sf != null) { try { this.sourceFileLinkPattern = Pattern.compile(sp); this.sourceFileLinkFormat = sf; this.sourceFileLinkToolTip = stt; this.sourceFileLinkFormatWithLine = sfwl; } catch (RuntimeException e) { AnalysisContext.logError("Could not compile pattern " + sp, e); } } String sqlDriver = getProperty("dbDriver"); url = getProperty("dbUrl"); dbName = getProperty("dbName"); dbUser = getProperty("dbUser"); dbPassword = getProperty("dbPassword"); findbugsUser = getProperty("findbugsUser"); if (sqlDriver == null || dbUser == null || url == null || dbPassword == null) return false; if (findbugsUser == null) { if (PROMPT_FOR_USER_NAME) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); findbugsUser = prefs.get("user.name", null); } if (findbugsUser == null) findbugsUser = System.getProperty("user.name", ""); if (PROMPT_FOR_USER_NAME) { findbugsUser = bugCollection.getProject().getGuiCallback().showQuestionDialog( "Your username (to record your comments in database)", "Connect to database as?", findbugsUser == null ? "" : findbugsUser); } if (findbugsUser == null) return false; } loadBugComponents(); try { Class.forName(sqlDriver); Connection c = getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) from findbugs_issue"); boolean result = false; if (rs.next()) { int count = rs.getInt(1); result = findbugsUser != null; } rs.close(); stmt.close(); c.close(); if (result) { runnerThread.setDaemon(true); runnerThread.start(); } return result; } catch (Exception e) { displayMessage("Unable to connect to database", e); return false; } } private String getBugComponent(@SlashedClassName String className) { int longestMatch = -1; String result = null; for(Map.Entry<String,String> e : prefixBugComponentMapping.entrySet()) { String key = e.getKey(); if (className.startsWith(key) && longestMatch < key.length()) { longestMatch = key.length(); result = e.getValue(); } } return result; } private void loadBugComponents(){ try { URL u = PluginLoader.getCoreResource("bugComponents.properties"); if (u != null) { BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream())); while(true) { String s = in.readLine(); if (s == null) break; if (s.trim().length() == 0) continue; int x = s.indexOf(' '); if (x == -1) { if (!prefixBugComponentMapping.containsKey("")) prefixBugComponentMapping.put("", s); } else { String prefix = s.substring(x+1); if (!prefixBugComponentMapping.containsKey(prefix)) prefixBugComponentMapping.put(prefix, s.substring(0,x)); } } in.close(); } } catch (IOException e) { AnalysisContext.logError("Unable to load bug component properties", e); } } final LinkedBlockingQueue<Update> queue = new LinkedBlockingQueue<Update>(); volatile boolean shutdown = false; volatile boolean startShutdown = false; final DatabaseSyncTask runner = new DatabaseSyncTask(); final Thread runnerThread = new Thread(runner, "Database synchronization thread"); final Timer resyncTimer = new Timer("Resync scheduler", true); @Override public void shutdown() { startShutdown = true; resyncTimer.cancel(); queue.add(new ShutdownTask()); try { Connection c = getConnection(); PreparedStatement setEndTime = c.prepareStatement("UPDATE findbugs_invocation SET endTime = ? WHERE id = ?"); Timestamp date = new Timestamp(System.currentTimeMillis()); int col = 1; setEndTime.setTimestamp(col++, date); setEndTime.setInt(col++, sessionId); setEndTime.execute(); } catch (SQLException e) { // we're in shutdown mode, not going to complain assert true; } if (!queue.isEmpty() && runnerThread.isAlive()) { setErrorMsg("waiting for synchronization to complete before shutdown"); for (int i = 0; i < 100; i++) { if (queue.isEmpty() || !runnerThread.isAlive()) break; try { Thread.sleep(30); } catch (InterruptedException e) { break; } } } shutdown = true; runnerThread.interrupt(); } private RuntimeException shutdownException = new RuntimeException("DBCloud shutdown"); private void checkForShutdown() { if (!shutdown) return; IllegalStateException e = new IllegalStateException("DBCloud has already been shutdown"); e.initCause(shutdownException); throw e; } public void storeNewBug(BugInstance bug) { checkForShutdown(); queue.add(new StoreNewBug(bug)); } public void storeFirstSeen(final BugData bd) { checkForShutdown(); queue.add(new Update(){ public void execute(DatabaseSyncTask t) throws SQLException { t.storeFirstSeen(bd); }}); } public void storeUserAnnotation(BugData data, BugDesignation bd) { checkForShutdown(); queue.add(new StoreUserAnnotation(data, bd)); updatedStatus(); if (firstTimeDoing(HAS_CLASSIFIED_ISSUES)) { String msg = "Classification and comments have been sent to database.\n" + "You'll only see this message the first time your classifcations/comments are sent\n" + "to the database."; if (mode == Mode.VOTING) msg += "\nOnce you've classified an issue, you can see how others have classified it."; msg += "\nYour classification and comments are independent from filing a bug using an external\n" + "bug reporting system."; bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } } private static final String HAS_SKIPPED_BUG = "has_skipped_bugs"; private boolean skipBug(BugInstance bug) { boolean result = bug.getBugPattern().getCategory().equals("NOISE") || bug.isDead() || BugRanker.findRank(bug) > MAX_DB_RANK; if (result && firstTimeDoing(HAS_SKIPPED_BUG)) { bugCollection.getProject().getGuiCallback().showMessageDialog( "To limit database load, some issues are not persisted to database.\n" + "For example, issues with rank greater than " + MAX_DB_RANK + " are not stored in the db.\n" + "One of more of the issues you are reviewing will not be persisted,\n" + "and you will not be able to record an evalution of those issues.\n" + "As we scale up the database, we hope to relax these restrictions"); } return result; } public static final String PENDING = "-- pending --"; public static final String NONE = "none"; class DatabaseSyncTask implements Runnable { int handled; Connection c; public void establishConnection() throws SQLException { if (c != null) return; c = getConnection(); } public void closeConnection() throws SQLException { if (c == null) return; c.close(); c = null; } public void run() { try { while (!shutdown) { Update u = queue.poll(10, TimeUnit.SECONDS); if (u == null) { closeConnection(); continue; } establishConnection(); u.execute(this); if ((handled++) % 100 == 0 || queue.isEmpty()) { updatedStatus(); } } } catch (DatabaseSyncShutdownException e) { assert true; } catch (RuntimeException e) { displayMessage("Runtime exception; database connection shutdown", e); } catch (SQLException e) { displayMessage("SQL exception; database connection shutdown", e); } catch (InterruptedException e) { assert true; } try { closeConnection(); } catch (SQLException e) { } } public void newEvaluation(BugData data, BugDesignation bd) { if (!data.inDatabase) return; try { data.designations.add(bd); if (bd.getUser() == null) bd.setUser(findbugsUser); if (bd.getAnnotationText() == null) bd.setAnnotationText(""); PreparedStatement insertEvaluation = c.prepareStatement("INSERT INTO findbugs_evaluation (issueId, who, designation, comment, time) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(bd.getTimestamp()); int col = 1; insertEvaluation.setInt(col++, data.id); insertEvaluation.setString(col++, bd.getUser()); insertEvaluation.setString(col++, bd.getDesignationKey()); insertEvaluation.setString(col++, bd.getAnnotationText()); insertEvaluation.setTimestamp(col++, date); insertEvaluation.executeUpdate(); ResultSet rs = insertEvaluation.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); bugDesignationId.put(bd, id); } rs.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } lastUpdate = new Date(); updatesSentToDatabase++; } public void newBug(BugInstance b, long timestamp) { try { BugData bug = getBugData(b.getInstanceHash()); if (bug.inDatabase) return; PreparedStatement insertBugData = c.prepareStatement("INSERT INTO findbugs_issue (firstSeen, lastSeen, hash, bugPattern, priority, primaryClass) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(timestamp); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setTimestamp(col++, date); insertBugData.setString(col++, bug.instanceHash); insertBugData.setString(col++, b.getBugPattern().getType()); insertBugData.setInt(col++, b.getPriority()); insertBugData.setString(col++, b.getPrimaryClass().getClassName()); insertBugData.executeUpdate(); ResultSet rs = insertBugData.getGeneratedKeys(); if (rs.next()) { bug.id = rs.getInt(1); bug.inDatabase = true; } rs.close(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeFirstSeen(BugData bug) { try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET firstSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(bug.firstSeen); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } /** * @param bd */ public void fileBug(BugData bug) { try { PreparedStatement insert = c .prepareStatement("INSERT INTO findbugs_bugreport (hash, bugReportId, whoFiled, whenFiled)" + " VALUES (?, ?, ?, ?)"); Timestamp date = new Timestamp(bug.bugFiled); int col = 1; insert.setString(col++, bug.instanceHash); insert.setString(col++, PENDING); insert.setString(col++, bug.filedBy); insert.setTimestamp(col++, date); int count = insert.executeUpdate(); insert.close(); if (count == 0) { PreparedStatement updateBug = c.prepareStatement("UPDATE findbugs_bugreport SET whoFiled = ? and whenFiled = ? WHERE hash = ? and bugReportId = ?"); col = 1; updateBug.setString(col++, bug.filedBy); updateBug.setTimestamp(col++, date); updateBug.setString(col++, bug.instanceHash); updateBug.setString(col++, PENDING); count = updateBug.executeUpdate(); updateBug.close(); } } catch (Exception e) { displayMessage("Problem filing bug", e); } lastUpdate = new Date(); updatesSentToDatabase++; } } static interface Update { void execute(DatabaseSyncTask t) throws SQLException; } static class ShutdownTask implements Update { public void execute(DatabaseSyncTask t) { throw new DatabaseSyncShutdownException(); } } static class DatabaseSyncShutdownException extends RuntimeException { } boolean bugAlreadyFiled(BugInstance b) { BugData bd = getBugData(b.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); return bd.bugLink != null && !bd.bugLink.equals(NONE) && !bd.bugLink.equals(PENDING); } class FileBug implements Update { public FileBug(BugInstance bug) { this.bd = getBugData(bug.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); bd.bugFiled = System.currentTimeMillis(); bd.bugLink = PENDING; bd.filedBy = findbugsUser; } final BugData bd; public void execute(DatabaseSyncTask t) throws SQLException { t.fileBug(bd); } } class StoreNewBug implements Update { public StoreNewBug(BugInstance bug) { this.bug = bug; } final BugInstance bug; public void execute(DatabaseSyncTask t) throws SQLException { BugData data = getBugData(bug.getInstanceHash()); if (data.inDatabase) return; long timestamp = bugCollection.getAppVersionFromSequenceNumber(bug.getFirstVersion()).getTimestamp(); t.newBug(bug, timestamp); data.inDatabase = true; } } static class StoreUserAnnotation implements Update { public StoreUserAnnotation(BugData data, BugDesignation designation) { super(); this.data = data; this.designation = designation; } public void execute(DatabaseSyncTask t) throws SQLException { t.newEvaluation(data, new BugDesignation(designation)); } final BugData data; final BugDesignation designation; } private void displayMessage(String msg, Exception e) { AnalysisContext.logError(msg, e); if (bugCollection != null && bugCollection.getProject().isGuiAvaliable()) { StringWriter stackTraceWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stackTraceWriter); e.printStackTrace(printWriter); bugCollection.getProject().getGuiCallback().showMessageDialog( String.format("%s - %s\n%s", msg, e.getMessage(), stackTraceWriter.toString())); } else { System.err.println(msg); e.printStackTrace(System.err); } } private void displayMessage(String msg) { if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } else { System.err.println(msg); } } public String getUser() { return findbugsUser; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getFirstSeen(edu.umd.cs.findbugs.BugInstance) */ public long getFirstSeen(BugInstance b) { return getBugData(b).firstSeen; } @Override public boolean overallClassificationIsNotAProblem(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; int isAProblem = 0; int notAProblem = 0; for(BugDesignation d : bd.getUniqueDesignations() ) switch(UserDesignation.valueOf(d.getDesignationKey())) { case I_WILL_FIX: case MUST_FIX: case SHOULD_FIX: isAProblem++; break; case BAD_ANALYSIS: case NOT_A_BUG: case MOSTLY_HARMLESS: case OBSOLETE_CODE: notAProblem++; break; } return notAProblem > isAProblem; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUser() */ public UserDesignation getUserDesignation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return UserDesignation.UNCLASSIFIED; return UserDesignation.valueOf(bd.getDesignationKey()); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserEvaluation(edu.umd.cs.findbugs.BugInstance) */ public String getUserEvaluation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return ""; return bd.getAnnotationText(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserTimestamp(edu.umd.cs.findbugs.BugInstance) */ public long getUserTimestamp(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return Long.MAX_VALUE; return bd.getTimestamp(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserDesignation(edu.umd.cs.findbugs.BugInstance, edu.umd.cs.findbugs.cloud.UserDesignation, long) */ public void setUserDesignation(BugInstance b, UserDesignation u, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (u == UserDesignation.UNCLASSIFIED) return; bd = data.getNonnullUserDesignation(); } bd.setDesignationKey(u.name()); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserEvaluation(edu.umd.cs.findbugs.BugInstance, java.lang.String, long) */ public void setUserEvaluation(BugInstance b, String e, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (e.length() == 0) return; bd = data.getNonnullUserDesignation(); } bd.setAnnotationText(e); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserTimestamp(edu.umd.cs.findbugs.BugInstance, long) */ public void setUserTimestamp(BugInstance b, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getNonnullUserDesignation(); bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } static final String BUG_NOTE = SystemProperties.getProperty("findbugs.bugnote"); String getBugReportHead(BugInstance b) { StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); out.println("Bug report generated from FindBugs"); out.println(b.getMessageWithoutPrefix()); out.println(); ClassAnnotation primaryClass = b.getPrimaryClass(); for (BugAnnotation a : b.getAnnotations()) { if (a == primaryClass) out.println(a); else out.println(" " + a.toString(primaryClass)); } URL link = getSourceLink(b); if (link != null) { out.println(); out.println(sourceFileLinkToolTip + ": " + link); out.println(); } if (BUG_NOTE != null) { out.println(BUG_NOTE); if (POSTMORTEM_NOTE != null && BugRanker.findRank(b) <= POSTMORTEM_RANK && !overallClassificationIsNotAProblem(b)) out.println(POSTMORTEM_NOTE); out.println(); } Collection<String> projects = projectMapping.getProjects(primaryClass.getClassName()); if (projects != null && !projects.isEmpty()) { String projectList = projects.toString(); projectList = projectList.substring(1, projectList.length() - 1); out.println("Possibly part of: " + projectList); out.println(); } out.close(); return stringWriter.toString(); } String getBugPatternExplanation(BugInstance b) { String detailPlainText = b.getBugPattern().getDetailPlainText(); return "Bug pattern explanation:\n" + detailPlainText + "\n\n"; } String getBugPatternExplanationLink(BugInstance b) { return "Bug pattern explanation: http://findbugs.sourceforge.net/bugDescriptions.html#" + b.getBugPattern().getType() + "\n"; } private String getLineTerminatedUserEvaluation(BugInstance b) { String result = getUserEvaluation(b); if (result.length() == 0) return ""; return result.trim()+"\n"; } String getBugReport(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b) + getBugReportTail(b); } String getBugReportShorter(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportAbridged(BugInstance b) { return getBugReportHead(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportSourceCode(BugInstance b) { if (!MainFrame.isAvailable()) return ""; StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); ClassAnnotation primaryClass = b.getPrimaryClass(); int firstLine = Integer.MAX_VALUE; int lastLine = Integer.MIN_VALUE; for (BugAnnotation a : b.getAnnotations()) if (a instanceof SourceLineAnnotation) { SourceLineAnnotation s = (SourceLineAnnotation) a; if (s.getClassName().equals(primaryClass.getClassName()) && s.getStartLine() > 0) { firstLine = Math.min(firstLine, s.getStartLine()); lastLine = Math.max(lastLine, s.getEndLine()); } } SourceLineAnnotation primarySource = primaryClass.getSourceLines(); if (primarySource.isSourceFileKnown() && firstLine >= 1 && firstLine <= lastLine && lastLine - firstLine < 50) { try { SourceFile sourceFile = MainFrame.getInstance().getSourceFinder().findSourceFile(primarySource); BufferedReader in = new BufferedReader(new InputStreamReader(sourceFile.getInputStream())); int lineNumber = 1; String commonWhiteSpace = null; List<SourceLine> source = new ArrayList<SourceLine>(); while (lineNumber <= lastLine + 4) { String txt = in.readLine(); if (txt == null) break; if (lineNumber >= firstLine - 4) { String trimmed = txt.trim(); if (trimmed.length() == 0) { if (lineNumber > lastLine) break; txt = trimmed; } source.add(new SourceLine(lineNumber, txt)); commonWhiteSpace = commonLeadingWhitespace(commonWhiteSpace, txt); } lineNumber++; } in.close(); out.println("\nRelevant source code:"); for(SourceLine s : source) { if (s.text.length() == 0) out.printf("%5d: \n", s.line); else out.printf("%5d: %s\n", s.line, s.text.substring(commonWhiteSpace.length())); } out.println(); } catch (IOException e) { assert true; } out.close(); String result = stringWriter.toString(); return result; } return ""; } String commonLeadingWhitespace(String soFar, String txt) { if (txt.length() == 0) return soFar; if (soFar == null) return txt; soFar = Util.commonPrefix(soFar, txt); for(int i = 0; i < soFar.length(); i++) { if (!Character.isWhitespace(soFar.charAt(i))) return soFar.substring(0,i); } return soFar; } static class SourceLine { public SourceLine(int line, String text) { this.line = line; this.text = text; } final int line; final String text; } String getBugReportTail(BugInstance b) { return "\nFindBugs issue identifier (do not modify or remove): " + b.getInstanceHash(); } static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { assert false; return "No utf-8 encoding"; } } public Set<String> getReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return Collections.emptySet(); return bd.getReviewers(); } public boolean isClaimed(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; return bd.isClaimed(); } static final int MAX_URL_LENGTH = 1999; private static final String HAS_FILED_BUGS = "has_filed_bugs"; private static final String HAS_CLASSIFIED_ISSUES = "has_classified_issues"; private static boolean firstTimeDoing(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); if (!prefs.getBoolean(activity, false)) { prefs.putBoolean(activity, true); return true; } return false; } private static void alreadyDone(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); prefs.putBoolean(activity, true); } private boolean firstBugRequest = true; static final String POSTMORTEM_NOTE = SystemProperties.getProperty("findbugs.postmortem.note"); static final int POSTMORTEM_RANK = SystemProperties.getInteger("findbugs.postmortem.rank", 4); static final String BUG_LINK_FORMAT = SystemProperties.getProperty("findbugs.filebug.link"); @Override @CheckForNull public URL getBugLink(BugInstance b) { try { BugData bd = getBugData(b); String bugNumber = bd.bugLink; BugFilingStatus status = getBugLinkStatus(b); switch (status) { case VIEW_BUG: { String viewLinkPattern = SystemProperties.getProperty("findbugs.viewbug.link"); if (viewLinkPattern == null) return null; firstBugRequest = false; String u = String.format(viewLinkPattern, bugNumber); return new URL(u); } case FILE_BUG: { URL u = getBugFilingLink(b); if (u != null && firstTimeDoing(HAS_FILED_BUGS)) { String bugFilingNote = String.format(SystemProperties.getProperty("findbugs.filebug.note","")); int response = bugCollection.getProject().getGuiCallback().showConfirmDialog( "This looks like the first time you've filed a bug from this machine. Please:\n" + " * Please check the component the issue is assigned to; we sometimes get it wrong.\n" + " * Try to figure out the right person to assign it to.\n" + " * Provide the information needed to understand the issue.\n" + bugFilingNote + "Note that classifying an issue is distinct from (and lighter weight than) filing a bug.", "Do you want to file a bug report", JOptionPane.YES_NO_OPTION); if (response != JOptionPane.YES_OPTION) return null; } return u; } case FILE_AGAIN: alreadyDone(HAS_FILED_BUGS); return getBugFilingLink(b); } } catch (Exception e) { } return null; } /** * @param b * @return * @throws MalformedURLException */ private URL getBugFilingLink(BugInstance b) throws MalformedURLException { { if (BUG_LINK_FORMAT == null) return null; String report = getBugReport(b); String component = getBugComponent(b.getPrimaryClass().getClassName().replace('.', '/')); String summary = b.getMessageWithoutPrefix() + " in " + b.getPrimaryClass().getSourceFileName(); int maxURLLength = MAX_URL_LENGTH; if (firstBugRequest) maxURLLength = maxURLLength *2/3; firstBugRequest = false; String u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportShorter(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportAbridged(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); String supplemental = "[Can't squeeze this information into the URL used to prepopulate the bug entry\n" +" please cut and paste into the bug report as appropriate]\n\n" + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b); bugCollection.getProject().getGuiCallback().displayNonmodelMessage( "Cut and paste as needed into bug entry", supplemental); } } return new URL(u); } } @Override public boolean supportsCloudReports() { return true; } @Override public boolean supportsBugLinks() { return BUG_LINK_FORMAT != null; } @Override public String getCloudReport(BugInstance b) { SimpleDateFormat format = new SimpleDateFormat("MM/dd"); StringBuilder builder = new StringBuilder(); BugData bd = getBugData(b); long firstSeen = bd.firstSeen; if (firstSeen < Long.MAX_VALUE) { builder.append(String.format("First seen %s\n", format.format(new Timestamp(firstSeen)))); } BugDesignation primaryDesignation = bd.getPrimaryDesignation(); I18N i18n = I18N.instance(); boolean canSeeCommentsByOthers = bd.canSeeCommentsByOthers(); if (canSeeCommentsByOthers) { if (bd.bugStatus != null) { builder.append(bd.bugComponentName); if (bd.bugAssignedTo == null) builder.append("\nBug status is " + bd.bugStatus); else builder.append("\nBug assigned to " + bd.bugAssignedTo + ", status is " + bd.bugStatus); builder.append("\n\n"); } } for(BugDesignation d : bd.getUniqueDesignations()) if (findbugsUser.equals(d.getUser())|| canSeeCommentsByOthers ) { builder.append(String.format("%s @ %s: %s\n", d.getUser(), format.format(new Timestamp(d.getTimestamp())), i18n.getUserDesignation(d.getDesignationKey()))); if (d.getAnnotationText().length() > 0) { builder.append(d.getAnnotationText()); builder.append("\n\n"); } } return builder.toString(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#storeUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ public void storeUserAnnotation(BugInstance bugInstance) { storeUserAnnotation(getBugData(bugInstance), bugInstance.getNonnullUserDesignation()); } @Override public boolean supportsSourceLinks() { return sourceFileLinkPattern != null; } @Override public @CheckForNull URL getSourceLink(BugInstance b) { if (sourceFileLinkPattern == null) return null; SourceLineAnnotation src = b.getPrimarySourceLineAnnotation(); String fileName = src.getSourcePath(); int startLine = src.getStartLine(); java.util.regex.Matcher m = sourceFileLinkPattern.matcher(fileName); boolean isMatch = m.matches(); if (isMatch) try { URL link; if (startLine > 0) link = new URL(String.format(sourceFileLinkFormatWithLine, m.group(1), startLine, startLine - 10)); else link = new URL(String.format(sourceFileLinkFormat, m.group(1))); return link; } catch (MalformedURLException e) { AnalysisContext.logError("Error generating source link for " + src, e); } return null; } @Override public String getSourceLinkToolTip(BugInstance b) { return sourceFileLinkToolTip; } @Override public BugFilingStatus getBugLinkStatus(BugInstance b) { BugData bd = getBugData(b); String link = bd.bugLink; if (link == null || link.length() == 0 || link.equals(NONE)) return BugFilingStatus.FILE_BUG; if (link.equals(PENDING)) { if (findbugsUser.equals(bd.filedBy)) return BugFilingStatus.FILE_AGAIN; else if (System.currentTimeMillis() - bd.bugFiled > 2*60*60*1000L) return BugFilingStatus.FILE_BUG; else return BugFilingStatus.BUG_PENDING; } try { Integer.parseInt(link); return BugFilingStatus.VIEW_BUG; } catch (RuntimeException e) { assert true; } return BugFilingStatus.NA; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#bugFiled(edu.umd.cs.findbugs.BugInstance, java.lang.Object) */ public void bugFiled(BugInstance b, Object bugLink) { checkForShutdown(); if (bugAlreadyFiled(b)) { BugData bd = getBugData(b.getInstanceHash()); return; } queue.add(new FileBug(b)); updatedStatus(); } String errorMsg; long errorTime = 0; void setErrorMsg(String msg) { errorMsg = msg; errorTime = System.currentTimeMillis(); updatedStatus(); } void clearErrorMsg() { errorMsg = null; updatedStatus(); } @Override public String getStatusMsg() { if (errorMsg != null) { if (errorTime + 2 * 60 * 1000 > System.currentTimeMillis()) { errorMsg = null; } else return errorMsg +"; " + getStatusMsg0(); } return getStatusMsg0(); } public String getStatusMsg0() { SimpleDateFormat format = new SimpleDateFormat("h:mm a"); int numToSync = queue.size(); if (numToSync > 0) return String.format("%d remain to be synchronized", numToSync); else if (resync != null && resync.after(lastUpdate)) return String.format("%d updates received from db at %s", resyncCount, format.format(resync)); else if (updatesSentToDatabase == 0) return String.format("%d issues synchronized with database", idMap.size()); else return String.format("%d classifications/bug filings sent to db, last updated at %s", updatesSentToDatabase, format.format(lastUpdate)); } @Override public void printCloudSummary(PrintWriter w, Iterable<BugInstance> bugs, String[] packagePrefixes) { Multiset<String> evaluations = new Multiset<String>(); Multiset<String> designations = new Multiset<String>(); Multiset<String> bugStatus = new Multiset<String>(); int issuesWithThisManyReviews [] = new int[100]; I18N i18n = I18N.instance(); Set<String> hashCodes = new HashSet<String>(); for(BugInstance b : bugs) { hashCodes.add(b.getInstanceHash()); } int packageCount = 0; int classCount = 0; int ncss = 0; ProjectStats projectStats = bugCollection.getProjectStats(); for(PackageStats ps : projectStats.getPackageStats()) if (ViewFilter.matchedPrefixes(packagePrefixes, ps.getPackageName()) && ps.size() > 0 && ps.getNumClasses() > 0) { packageCount++; ncss += ps.size(); classCount += ps.getNumClasses(); } if (packagePrefixes != null && packagePrefixes.length > 0) { String lst = Arrays.asList(packagePrefixes).toString(); w.println("Code analyzed in " + lst.substring(1, lst.length()-1)); } else w.println("Code analyzed"); if (classCount == 0) w.println("No classes were analyzed"); else w.printf("%,7d packages\n%,7d classes\n%,7d thousands of lines of non-commenting source statements\n", packageCount, classCount, (ncss+999)/1000); w.println(); int count = 0; int notInCloud = 0; for(String hash : hashCodes) { BugData bd = instanceMap.get(hash); if (bd == null) { notInCloud++; continue; } count++; HashSet<String> reviewers = new HashSet<String>(); if (bd.bugStatus != null) bugStatus.add(bd.bugStatus); for(BugDesignation d : bd.designations) if (reviewers.add(d.getUser())) { evaluations.add(d.getUser()); designations.add(i18n.getUserDesignation(d.getDesignationKey())); } int numReviews = Math.min( reviewers.size(), issuesWithThisManyReviews.length -1); issuesWithThisManyReviews[numReviews]++; } if (count == 0) { w.printf("None of the %d issues in the current view are in the cloud\n\n", notInCloud); return; } if (notInCloud == 0) { w.printf("Summary for %d issues that are in the current view\n\n", count); }else { w.printf("Summary for %d issues that are in the current view and cloud (%d not in cloud)\n\n", count, notInCloud); } w.println("People who have performed the most reviews"); printLeaderBoard(w, evaluations, 9, findbugsUser, true, "reviewer"); w.println("\nDistribution of evaluations"); printLeaderBoard(w, designations, 100, " --- ", false, "designation"); w.println("\nDistribution of bug status"); printLeaderBoard(w, bugStatus, 100, " --- ", false, "status of filed bug"); w.println("\nDistribution of number of reviews"); for(int i = 0; i < issuesWithThisManyReviews.length; i++) if (issuesWithThisManyReviews[i] > 0) { w.printf("%4d with %3d review", issuesWithThisManyReviews[i], i); if (i != 1) w.print("s"); w.println(); } } /** * @param w * @param evaluations * @param listRank TODO * @param title TODO */ static void printLeaderBoard(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, boolean listRank, String title) { if (listRank) w.printf("%3s %4s %s\n", "rnk", "num", title); else w.printf("%4s %s\n", "num", title); printLeaderBoard2(w, evaluations, maxRows, alwaysPrint, listRank ? "%3d %4d %s\n" : "%2$4d %3$s\n" , title); } static final String LEADERBOARD_BLACKLIST = SystemProperties.getProperty("findbugs.leaderboard.blacklist"); static final Pattern LEADERBOARD_BLACKLIST_PATTERN; static { Pattern p = null; if (LEADERBOARD_BLACKLIST != null) try { p = Pattern.compile(LEADERBOARD_BLACKLIST.replace(',', '|')); } catch (Exception e) { assert true; } LEADERBOARD_BLACKLIST_PATTERN = p; } /** * @param w * @param evaluations * @param maxRows * @param alwaysPrint * @param listRank * @param title */ static void printLeaderBoard2(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, String format, String title) { int row = 1; int position = 0; int previousScore = -1; boolean foundAlwaysPrint = false; for(Map.Entry<String,Integer> e : evaluations.entriesInDecreasingFrequency()) { int num = e.getValue(); if (num != previousScore) { position = row; previousScore = num; } String key = e.getKey(); if (LEADERBOARD_BLACKLIST_PATTERN != null && LEADERBOARD_BLACKLIST_PATTERN.matcher(key).matches()) continue; boolean shouldAlwaysPrint = key.equals(alwaysPrint); if (row <= maxRows || shouldAlwaysPrint) w.printf(format, position, num, key); if (shouldAlwaysPrint) foundAlwaysPrint = true; row++; if (row >= maxRows) { if (alwaysPrint == null) break; if (foundAlwaysPrint) { w.printf("Total of %d %ss\n", evaluations.numKeys(), title); break; } } } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getIWillFix(edu.umd.cs.findbugs.BugInstance) */ @Override public boolean getIWillFix(BugInstance b) { if (super.getIWillFix(b)) return true; BugData bd = getBugData(b); return bd != null && findbugsUser.equals(bd.bugAssignedTo); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#supportsCloudSummaries() */ @Override public boolean supportsCloudSummaries() { return true; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#canStoreUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ @Override public boolean canStoreUserAnnotation(BugInstance bugInstance) { return !skipBug(bugInstance); } @Override public @CheckForNull String claimedBy(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return null; for(BugDesignation designation : bd.getUniqueDesignations()) { if ("I_WILL_FIX".equals(designation.getDesignationKey())) return designation.getUser(); } return null; } }
package edu.umd.cs.findbugs.detect; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Deprecated; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.SignatureParser; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.props.AbstractWarningProperty; import edu.umd.cs.findbugs.props.PriorityAdjustment; import edu.umd.cs.findbugs.props.WarningPropertySet; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; public class Naming extends PreorderVisitor implements Detector { public static class NamingProperty extends AbstractWarningProperty { private NamingProperty(String name, PriorityAdjustment priorityAdjustment) { super(name, priorityAdjustment); } public static final NamingProperty METHOD_IS_CALLED = new NamingProperty("CONFUSING_METHOD_IS_CALLED", PriorityAdjustment.LOWER_PRIORITY); public static final NamingProperty METHOD_IS_DEPRECATED = new NamingProperty("CONFUSING_METHOD_IS_DEPRECATED", PriorityAdjustment.LOWER_PRIORITY); } String baseClassName; boolean classIsPublicOrProtected; public static @CheckForNull XMethod definedIn(JavaClass clazz, XMethod m) { for (Method m2 : clazz.getMethods()) if (m.getName().equals(m2.getName()) && m.getSignature().equals(m2.getSignature()) && m.isStatic() == m2.isStatic()) return XFactory.createXMethod(clazz, m2); return null; } public static boolean confusingMethodNamesWrongCapitalization(XMethod m1, XMethod m2) { if (m1.isStatic() != m2.isStatic()) return false; if (m1.getClassName().equals(m2.getClassName())) return false; if (m1.getName().equals(m2.getName())) return false; if (m1.getName().equalsIgnoreCase(m2.getName()) && removePackageNamesFromSignature(m1.getSignature()).equals(removePackageNamesFromSignature(m2.getSignature()))) return true; return false; } public static boolean confusingMethodNamesWrongPackage(XMethod m1, XMethod m2) { if (m1.isStatic() != m2.isStatic()) return false; if (m1.getClassName().equals(m2.getClassName())) return false; if (!m1.getName().equals(m2.getName())) return false; if (m1.getSignature().equals(m2.getSignature())) return false; if (removePackageNamesFromSignature(m1.getSignature()).equals(removePackageNamesFromSignature(m2.getSignature()))) return true; return false; } // map of canonicalName -> Set<XMethod> HashMap<String, TreeSet<XMethod>> canonicalToXMethod = new HashMap<String, TreeSet<XMethod>>(); HashSet<String> visited = new HashSet<String>(); private BugReporter bugReporter; public Naming(BugReporter bugReporter) { this.bugReporter = bugReporter; } public void visitClassContext(ClassContext classContext) { classContext.getJavaClass().accept(this); } private boolean checkSuper(XMethod m, Set<XMethod> others) { if (m.isStatic()) return false; if (m.getName().equals("<init>") || m.getName().equals("<clinit>")) return false; for (XMethod m2 : others) { try { if ((confusingMethodNamesWrongCapitalization(m, m2) || confusingMethodNamesWrongPackage(m,m2)) && Repository.instanceOf(m.getClassName(), m2.getClassName())) { WarningPropertySet<NamingProperty> propertySet = new WarningPropertySet<NamingProperty>(); int priority = HIGH_PRIORITY; XMethod m3 = null; try { JavaClass clazz = Repository.lookupClass(m.getClassName()); if ((m3 = definedIn(clazz, m2)) == null) { // the method we don't override is also defined in our class priority = NORMAL_PRIORITY; } if (m3 == null) for (JavaClass s : clazz.getSuperClasses()) if ((m3 = definedIn(s, m)) != null) { // the method we define is also defined in our superclass priority = NORMAL_PRIORITY; break; } if (m3 == null) for (JavaClass i : clazz.getAllInterfaces()) if ((m3 = definedIn(i, m)) != null) { priority = NORMAL_PRIORITY; // the method we define is also defined in an interface break; } } catch (ClassNotFoundException e) { priority++; AnalysisContext.reportMissingClass(e); } XFactory xFactory = AnalysisContext.currentXFactory(); if (m3 == null && xFactory.isCalled(m)) propertySet.addProperty(NamingProperty.METHOD_IS_CALLED); else if (m.isDeprecated() || m2.isDeprecated()) propertySet.addProperty(NamingProperty.METHOD_IS_DEPRECATED); if (!m.getName().equals(m2.getName()) && m.getName().equalsIgnoreCase(m2.getName())) { String pattern = m3 != null ? "NM_VERY_CONFUSING_INTENTIONAL" : "NM_VERY_CONFUSING"; BugInstance bug = new BugInstance(this, pattern, priority).addClass(m.getClassName()).addMethod(m) .addClass(m2.getClassName()).addMethod(m2); if (m3 != null) bug.addMethod(m3); propertySet.decorateBugInstance(bug); bugReporter.reportBug(bug); } else if (!m.getSignature().equals(m2.getSignature()) && removePackageNamesFromSignature(m.getSignature()).equals( removePackageNamesFromSignature(m2.getSignature()))) { String pattern = m3 != null ? "NM_WRONG_PACKAGE_INTENTIONAL" : "NM_WRONG_PACKAGE"; Iterator<String> s = new SignatureParser(m.getSignature()).parameterSignatureIterator(); Iterator<String> s2 = new SignatureParser(m2.getSignature()).parameterSignatureIterator(); while (s.hasNext()) { String p = s.next(); String p2 = s2.next(); if (!p.equals(p2)) { BugInstance bug = new BugInstance(this, pattern, priority).addClass(m.getClassName()) .addMethod(m).addClass(m2.getClassName()).addMethod(m2).addFoundAndExpectedType(p, p2); if (m3 != null) bug.addMethod(m3); propertySet.decorateBugInstance(bug); bugReporter.reportBug(bug); } } } return true; } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } } return false; } @SuppressWarnings("unchecked") private boolean checkNonSuper(XMethod m, Set<XMethod> others) { if (m.isStatic()) return false; if (m.getName().startsWith("<init>") || m.getName().startsWith("<clinit>")) return false; for (XMethod m2 : others) { if (confusingMethodNamesWrongCapitalization(m, m2)) { XMethod mm1 = m; XMethod mm2 = m2; if (m.compareTo(m2) < 0) { mm1 = m; mm2 = m2; } else { mm1 = m2; mm2 = m; } bugReporter.reportBug(new BugInstance(this, "NM_CONFUSING", LOW_PRIORITY).addClass(mm1.getClassName()).addMethod( mm1).addClass(mm2.getClassName()).addMethod(mm2)); return true; } } return false; } public void report() { for (Map.Entry<String,TreeSet<XMethod>> e : canonicalToXMethod.entrySet()) { TreeSet<XMethod> conflictingMethods = e.getValue(); HashSet<String> trueNames = new HashSet<String>(); for(XMethod m : conflictingMethods) trueNames.add(m.getName() + m.getSignature()); if (trueNames.size() <= 1) continue; for (Iterator<XMethod> j = conflictingMethods.iterator(); j.hasNext();) { if (checkSuper(j.next(), conflictingMethods)) j.remove(); } for (XMethod conflictingMethod : conflictingMethods) { if (checkNonSuper(conflictingMethod, conflictingMethods)) break; } } } public String stripPackageName(String className) { if (className.indexOf('.') >= 0) return className.substring(className.lastIndexOf('.') + 1); else if (className.indexOf('/') >= 0) return className.substring(className.lastIndexOf('/') + 1); else return className; } public boolean sameSimpleName(String class1, String class2) { return class1 != null && class2 != null && stripPackageName(class1).equals(stripPackageName(class2)); } @Override public void visitJavaClass(JavaClass obj) { if (obj.isSynthetic()) return; String name = obj.getClassName(); if (!visited.add(name)) return; String superClassName = obj.getSuperclassName(); if (!name.equals("java.lang.Object")) { if (sameSimpleName(superClassName, name)) { bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS", HIGH_PRIORITY).addClass(name) .addClass(superClassName)); } for (String interfaceName : obj.getInterfaceNames()) if (sameSimpleName(interfaceName, name)) { bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_INTERFACE", NORMAL_PRIORITY).addClass( name).addClass(interfaceName)); } } if (obj.isInterface()) return; if (superClassName.equals("java.lang.Object") && !visited.contains(superClassName)) try { visitJavaClass(obj.getSuperClass()); } catch (ClassNotFoundException e) { // ignore it } super.visitJavaClass(obj); } /** * Determine whether the class descriptor ultimately inherits from * java.lang.Exception * @param d class descriptor we want to check * @return true iff the descriptor ultimately inherits from Exception */ private static boolean mightInheritFromException(ClassDescriptor d) { while(d != null) { try { if("java.lang.Exception".equals(d.getDottedClassName())) { return true; } XClass classNameAndInfo = Global.getAnalysisCache(). getClassAnalysis(XClass.class, d); d = classNameAndInfo.getSuperclassDescriptor(); } catch (CheckedAnalysisException e) { return true; // don't know } } return false; } boolean hasBadMethodNames; boolean hasBadFieldNames; /** * Eclipse uses reflection to initialize NLS message bundles. Classes which using this * mechanism are usualy extending org.eclipse.osgi.util.NLS class and contains lots * of public static String fields which are used as message constants. Unfortunately * these fields often has bad names which does not follow Java code convention, so FB * reports tons of warnings for such Eclipse message fields. * @see edu.umd.cs.findbugs.detect.MutableStaticFields */ private boolean isEclipseNLS; @Override public void visit(JavaClass obj) { String name = obj.getClassName(); String[] parts = name.split("[$+.]"); baseClassName = parts[parts.length - 1]; for(String p : name.split("[.]")) if (p.length() == 1) return; if (name.indexOf("Proto$") >= 0) return; classIsPublicOrProtected = obj.isPublic() || obj.isProtected(); if (Character.isLetter(baseClassName.charAt(0)) && !Character.isUpperCase(baseClassName.charAt(0)) && baseClassName.indexOf("_") == -1) { int priority = classIsPublicOrProtected ? NORMAL_PRIORITY : LOW_PRIORITY; bugReporter.reportBug(new BugInstance(this, "NM_CLASS_NAMING_CONVENTION", priority).addClass(this)); } if (name.endsWith("Exception")) { // Does it ultimately inherit from Throwable? if(!mightInheritFromException(DescriptorFactory.createClassDescriptor(obj))) { // It doens't, so the name is misleading bugReporter.reportBug(new BugInstance(this, "NM_CLASS_NOT_EXCEPTION", NORMAL_PRIORITY).addClass(this)); } } int badFieldNames = 0; for(Field f : obj.getFields()) if (f.getName().length() >= 2 && badFieldName(f)) badFieldNames++; hasBadFieldNames = badFieldNames > 3 && badFieldNames > obj.getFields().length/3; int badNames = 0; for(Method m : obj.getMethods()) if (badMethodName(m.getName())) badNames++; hasBadMethodNames = badNames > 3 && badNames > obj.getMethods().length/3; isEclipseNLS = "org.eclipse.osgi.util.NLS".equals(obj.getSuperclassName()); super.visit(obj); } @Override public void visit(Field obj) { if (getFieldName().length() == 1) return; if (isEclipseNLS) { int flags = obj.getAccessFlags(); if ((flags & ACC_STATIC) != 0 && ((flags & ACC_PUBLIC) != 0) && getFieldSig().equals("Ljava/lang/String;")) { // ignore "public statis String InstallIUCommandTooltip;" messages from Eclipse NLS bundles return; } } if (badFieldName(obj)) { bugReporter.reportBug(new BugInstance(this, "NM_FIELD_NAMING_CONVENTION", classIsPublicOrProtected && (obj.isPublic() || obj.isProtected()) && !hasBadFieldNames ? NORMAL_PRIORITY : LOW_PRIORITY).addClass(this).addVisitedField( this)); } } /** * @param obj * @return */ private boolean badFieldName(Field obj) { String fieldName = obj.getName(); return !obj.isFinal() && Character.isLetter(fieldName.charAt(0)) && !Character.isLowerCase(fieldName.charAt(0)) && fieldName.indexOf("_") == -1 && Character.isLetter(fieldName.charAt(1)) && Character.isLowerCase(fieldName.charAt(1)); } private final static Pattern sigType = Pattern.compile("L([^;]*/)?([^/]+;)"); private boolean isInnerClass(JavaClass obj) { for (Field f : obj.getFields()) if (f.getName().startsWith("this$")) return true; return false; } private boolean markedAsNotUsable(Method obj) { for (Attribute a : obj.getAttributes()) if (a instanceof Deprecated) return true; Code code = obj.getCode(); if (code == null) return false; byte[] codeBytes = code.getCode(); if (codeBytes.length > 1 && codeBytes.length < 10) { int lastOpcode = codeBytes[codeBytes.length - 1] & 0xff; if (lastOpcode != ATHROW) return false; for (int b : codeBytes) if ((b & 0xff) == RETURN) return false; return true; } return false; } private static @CheckForNull Method findVoidConstructor(JavaClass clazz) { for (Method m : clazz.getMethods()) if (isVoidConstructor(m)) return m; return null; } @Override public void visit(Method obj) { String mName = getMethodName(); if (mName.length() == 1) return; if (mName.equals("isRequestedSessionIdFromURL") || mName.equals("isRequestedSessionIdFromUrl")) return; String sig = getMethodSig(); if (mName.equals(baseClassName) && sig.equals("()V")) { Code code = obj.getCode(); Method realVoidConstructor = findVoidConstructor(getThisClass()); if (code != null && !markedAsNotUsable(obj)) { int priority = NORMAL_PRIORITY; if (codeDoesSomething(code)) priority else if (!obj.isPublic() && getThisClass().isPublic()) priority boolean instanceMembers = false; for(Method m : this.getThisClass().getMethods()) if (!m.isStatic() && m != obj && !isVoidConstructor(m) ) instanceMembers = true; for(Field f : this.getThisClass().getFields()) if (!f.isStatic()) instanceMembers = true; if (!instanceMembers && getSuperclassName().equals("java/lang/Object")) priority+=2; if (realVoidConstructor != null) priority = LOW_PRIORITY; bugReporter.reportBug(new BugInstance(this, "NM_METHOD_CONSTRUCTOR_CONFUSION", priority).addClassAndMethod(this) .lowerPriorityIfDeprecated()); return; } } else if (badMethodName(mName)) bugReporter.reportBug(new BugInstance(this, "NM_METHOD_NAMING_CONVENTION", classIsPublicOrProtected && (obj.isPublic() || obj.isProtected()) && !hasBadMethodNames ? NORMAL_PRIORITY : LOW_PRIORITY).addClassAndMethod(this)); if (obj.isAbstract()) return; if (obj.isPrivate()) return; if (mName.equals("equal") && sig.equals("(Ljava/lang/Object;)Z")) { bugReporter.reportBug(new BugInstance(this, "NM_BAD_EQUAL", HIGH_PRIORITY).addClassAndMethod(this) .lowerPriorityIfDeprecated()); return; } if (mName.equals("hashcode") && sig.equals("()I")) { bugReporter.reportBug(new BugInstance(this, "NM_LCASE_HASHCODE", HIGH_PRIORITY).addClassAndMethod(this) .lowerPriorityIfDeprecated()); return; } if (mName.equals("tostring") && sig.equals("()Ljava/lang/String;")) { bugReporter.reportBug(new BugInstance(this, "NM_LCASE_TOSTRING", HIGH_PRIORITY).addClassAndMethod(this) .lowerPriorityIfDeprecated()); return; } if (obj.isPrivate() || obj.isStatic() || mName.equals("<init>")) return; String sig2 = removePackageNamesFromSignature(sig); String allSmall = mName.toLowerCase() + sig2; XMethod xm = getXMethod(); { TreeSet<XMethod> s = canonicalToXMethod.get(allSmall); if (s == null) { s = new TreeSet<XMethod>(); canonicalToXMethod.put(allSmall, s); } s.add(xm); } } private static boolean isVoidConstructor(Method m) { return m.getName().equals("<init>") && m.getSignature().equals("()V"); } /** * @param mName * @return */ private boolean badMethodName(String mName) { return mName.length() >= 2 && Character.isLetter(mName.charAt(0)) && !Character.isLowerCase(mName.charAt(0)) && Character.isLetter(mName.charAt(1)) && Character.isLowerCase(mName.charAt(1)) && mName.indexOf("_") == -1; } private boolean codeDoesSomething(Code code) { byte[] codeBytes = code.getCode(); return codeBytes.length > 1; } private static String removePackageNamesFromSignature(String sig) { int end = sig.indexOf(")"); Matcher m = sigType.matcher(sig.substring(0, end)); return m.replaceAll("L$2") + sig.substring(end); } }
// Kyle Russell // AUT University 2015 package com.graphi.sim; import com.graphi.util.Edge; import com.graphi.util.GraphUtilities; import com.graphi.util.Node; import edu.uci.ics.jung.algorithms.generators.random.KleinbergSmallWorldGenerator; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.EdgeType; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.PriorityQueue; import java.util.Random; import org.apache.commons.collections15.Factory; public class Network { public static Graph<Node, Edge> generateKleinberg(int latticeSize, int clusterExp, Factory<Node> nodeFactory, Factory<Edge> edgeFactory) { if(nodeFactory == null) nodeFactory = () -> new Node(); if(edgeFactory == null) edgeFactory = () -> new Edge(); Factory<Graph<Node, Edge>> graphFactory = () -> new SparseMultigraph<>(); KleinbergSmallWorldGenerator gen = new KleinbergSmallWorldGenerator(graphFactory, nodeFactory, edgeFactory, latticeSize, clusterExp); return gen.create(); } public static Graph<Node, Edge> generateBerbasiAlbert(Factory<Node> nodeFactory, Factory<Edge> edgeFactory, int n, int m) { if(nodeFactory == null) nodeFactory = () -> new Node(); if(edgeFactory == null) edgeFactory = () -> new Edge(); Graph<Node, Edge> graph = generateConnectedGraph(nodeFactory, edgeFactory, m); for(int i = 0; i < n; i++) { Node current = nodeFactory.create(); PriorityQueue<SimpleEntry<Node, Double>> nextVerticies = new PriorityQueue<> ((SimpleEntry<Node, Double> a1, SimpleEntry<Node, Double> a2) -> Double.compare(a1.getValue(), a2.getValue())); ArrayList<Node> vertices = new ArrayList<>(graph.getVertices()); Random rGen = new Random(); while(!vertices.isEmpty()) { int index = rGen.nextInt(vertices.size()); Node next = vertices.get(index); int degree = graph.degree(next); int degreeSum = GraphUtilities.degreeSum(graph); double p = degree / (degreeSum * 1.0); if(nextVerticies.size() < m) nextVerticies.add(new SimpleEntry<> (next, p)); else if(p > nextVerticies.peek().getValue()) { nextVerticies.poll(); nextVerticies.add(new SimpleEntry<> (next, p)); } vertices.remove(index); } graph.addVertex(current); while(!nextVerticies.isEmpty()) graph.addEdge(edgeFactory.create(), current, nextVerticies.poll().getKey()); } return graph; } public static Graph<Node, Edge> generateConnectedGraph(Factory<Node> nodeFactory, Factory<Edge> edgeFactory, int n) { Graph<Node, Edge> graph = new SparseMultigraph<>(); for(int i = 0; i < n; i++) graph.addVertex(nodeFactory.create()); ArrayList<Node> vertices = new ArrayList<>(graph.getVertices()); for(int i = 1; i < n; i++) graph.addEdge(edgeFactory.create(), vertices.get(i - 1), vertices.get(i)); return graph; } public static Graph<Node, Edge> generateRandomGraph(Factory<Node> nodeFactory, Factory<Edge> edgeFactory, int n, double P, boolean directed) { Graph<Node, Edge> graph = new SparseMultigraph<>(); Random rGen = new Random(); for(int i = 0; i < n; i++) graph.addVertex(nodeFactory.create()); Collection<Node> nodes = graph.getVertices(); for(Node node : nodes) { for(Node other : nodes) { if(!other.equals(node)) { double p = rGen.nextDouble() * 100; if(p >= P) graph.addEdge(edgeFactory.create(), node, other, directed? EdgeType.DIRECTED : EdgeType.UNDIRECTED); } } } return graph; } public static double getITProbability(Graph<Node, Edge> graph, Node from, Node to) { if(!graph.isNeighbor(from, to)) return 0.0; int n = 0; int degree = graph.degree(from); Collection<Node> neighbours = graph.getNeighbors(from); for(Node neighbour : neighbours) { if(!neighbour.equals(to) && graph.isNeighbor(neighbour, to)) n++; } return n / (degree * 1.0); } public static void simulateInterpersonalTies(Graph<Node, Edge> graph, Factory<Edge> edgeFactory, double P) { Collection<Node> nodes = graph.getVertices(); for(Node node: nodes) { Collection<Node> neighbours = graph.getNeighbors(node); for(Node neighbour : neighbours) { double p = getITProbability(graph, node, neighbour); if(p >= P) { Edge edge = edgeFactory.create(); graph.addEdge(edge, node, neighbour, EdgeType.DIRECTED); } } } } }
package com.jme.scene; import java.io.IOException; import java.io.Serializable; import java.nio.FloatBuffer; import java.util.Stack; import com.jme.bounding.BoundingVolume; import com.jme.intersection.PickResults; import com.jme.math.FastMath; import com.jme.math.Ray; import com.jme.math.Vector3f; import com.jme.renderer.CloneCreator; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; import com.jme.system.DisplaySystem; import com.jme.util.geom.BufferUtils; /** * <code>Geometry</code> defines a leaf node of the scene graph. The leaf node * contains the geometric data for rendering objects. It manages all rendering * information such as a collection of states and the data for a model. * Subclasses define what the model data is. * * @author Mark Powell * @author Joshua Slack * @version $Id: Geometry.java,v 1.87 2005-12-08 18:32:13 renanse Exp $ */ public abstract class Geometry extends Spatial implements Serializable { /** The local bounds of this Geometry object. */ protected BoundingVolume bound; /** The number of vertexes in this geometry. */ protected int vertQuantity = 0; /** The geometry's per vertex color information. */ protected transient FloatBuffer colorBuf; /** The geometry's per vertex normal information. */ protected transient FloatBuffer normBuf; /** The geometry's vertex information. */ protected transient FloatBuffer vertBuf; /** The geometry's per Texture per vertex texture coordinate information. */ protected transient FloatBuffer[] texBuf; /** The geometry's VBO information. */ protected VBOInfo vboInfo; /** * The compiled list of renderstates for this geometry, taking into account * ancestors' states - updated with updateRenderStates() */ public RenderState[] states = new RenderState[RenderState.RS_MAX_STATE]; /** Non -1 values signal this geometry is a clone of grouping "cloneID". */ private int cloneID = -1; private ColorRGBA defaultColor = ColorRGBA.white; /** Static computation field */ protected static Vector3f compVect = new Vector3f(); /** * Empty Constructor to be used internally only. */ public Geometry() { texBuf = new FloatBuffer[1]; } /** * Constructor instantiates a new <code>Geometry</code> object. This is * the default object which has an empty vertex array. All other data is * null. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * */ public Geometry(String name) { super(name); reconstruct(null, null, null, null); } /** * Constructor creates a new <code>Geometry</code> object. During * instantiation the geometry is set including vertex, normal, color and * texture information. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * @param vertex * the points that make up the geometry. * @param normal * the normals of the geometry. * @param color * the color of each point of the geometry. * @param texture * the texture coordinates of the geometry (position 0.) */ public Geometry(String name, FloatBuffer vertex, FloatBuffer normal, FloatBuffer color, FloatBuffer texture) { super(name); reconstruct(vertex, normal, color, texture); } /** * <code>reconstruct</code> reinitializes the geometry with new data. This * will reuse the geometry object. * * @param vertices * the new vertices to use. * @param normals * the new normals to use. * @param colors * the new colors to use. * @param textureCoords * the new texture coordinates to use (position 0). */ public void reconstruct(FloatBuffer vertices, FloatBuffer normals, FloatBuffer colors, FloatBuffer textureCoords) { int textureUnits = TextureState.getNumberOfUnits(); if (textureUnits == -1) { DisplaySystem displaySystem = DisplaySystem.getDisplaySystem(); if ( displaySystem != null ) { displaySystem.getRenderer().createTextureState(); textureUnits = TextureState.getNumberOfUnits(); } else { textureUnits = 1; } } texBuf = new FloatBuffer[textureUnits]; if (vertices == null) vertQuantity = 0; else vertQuantity = vertices.capacity() / 3; vertBuf = vertices; normBuf = normals; colorBuf = colors; texBuf[0] = textureCoords; } public void setVBOInfo(VBOInfo info) { this.vboInfo = info; } public VBOInfo getVBOInfo() { return vboInfo; } /** * * <code>setSolidColor</code> sets the color array of this geometry to a * single color. For greater efficiency, try setting the the ColorBuffer * to null and using DefaultColor instead. * * @param color * the color to set. */ public void setSolidColor(ColorRGBA color) { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); colorBuf.rewind(); for (int x = 0, cLength = colorBuf.remaining(); x < cLength; x+=4) { colorBuf.put(color.r); colorBuf.put(color.g); colorBuf.put(color.b); colorBuf.put(color.a); } colorBuf.flip(); } /** * Sets every color of this geometry's color array to a random color. */ public void setRandomColors() { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); for (int x = 0, cLength = colorBuf.capacity(); x < cLength; x+=4) { colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(1); } colorBuf.flip(); } /** * <code>getVertexBuffer</code> returns the float buffer that * contains this geometry's vertex information. * * @return the float buffer that contains this geometry's vertex * information. */ public FloatBuffer getVertexBuffer() { return vertBuf; } /** * <code>setVertexBuffer</code> sets this geometry's vertices via a * float buffer consisting of groups of three floats: x,y and z. * * @param buff * the new vertex buffer. */ public void setVertexBuffer(FloatBuffer buff) { this.vertBuf = buff; if (vertBuf != null) vertQuantity = vertBuf.capacity() / 3; else vertQuantity = 0; } /** * Returns the number of vertices defined in this Geometry object. * * @return The number of vertices in this Geometry object. */ public int getVertQuantity() { return vertQuantity; } /** * * @param quantity * the value to override the quantity with. This is overridden by * setVertexBuffer(). */ public void setVertQuantity(int quantity) { vertQuantity = quantity; } /** * <code>getNormalBuffer</code> retrieves this geometry's normal * information as a float buffer. * * @return the float buffer containing the geometry information. */ public FloatBuffer getNormalBuffer() { return normBuf; } /** * <code>setNormalBuffer</code> sets this geometry's normals via a * float buffer consisting of groups of three floats: x,y and z. * * @param buff * the new normal buffer. */ public void setNormalBuffer(FloatBuffer buff) { this.normBuf = buff; } /** * <code>getColorBuffer</code> retrieves the float buffer that * contains this geometry's color information. * * @return the buffer that contains this geometry's color information. */ public FloatBuffer getColorBuffer() { return colorBuf; } /** * <code>setColorBuffer</code> sets this geometry's colors via a * float buffer consisting of groups of four floats: r,g,b and a. * * @param buff * the new color buffer. */ public void setColorBuffer(FloatBuffer buff) { this.colorBuf = buff; } /** * * <code>copyTextureCoords</code> copys the texture coordinates of a given * texture unit to another location. If the texture unit is not valid, then * the coordinates are ignored. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. */ public void copyTextureCoords(int fromIndex, int toIndex) { copyTextureCoords(fromIndex, toIndex, 1.0f); } /** * * <code>copyTextureCoords</code> copys the texture coordinates of a given * texture unit to another location. If the texture unit is not valid, then * the coordinates are ignored. Coords are multiplied by the given factor. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. * @param factor * a multiple to apply when copying */ public void copyTextureCoords(int fromIndex, int toIndex, float factor) { if (texBuf == null) return; if (fromIndex < 0 || fromIndex >= texBuf.length || texBuf[fromIndex] == null) { return; } if (toIndex < 0 || toIndex >= texBuf.length || toIndex == fromIndex) { return; } FloatBuffer buf = texBuf[toIndex]; if (buf == null || buf.capacity() != texBuf[fromIndex].capacity()) { buf = BufferUtils.createFloatBuffer(texBuf[fromIndex].capacity()); texBuf[toIndex] = buf; } buf.clear(); int oldLimit = texBuf[fromIndex].limit(); texBuf[fromIndex].clear(); for (int i = 0, len = buf.capacity(); i < len; i++) { buf.put(factor * texBuf[fromIndex].get()); } texBuf[fromIndex].limit(oldLimit); buf.limit(oldLimit); } /** * <code>getTextureBuffer</code> retrieves this geometry's texture * information contained within a float buffer. * * @return the float buffer that contains this geometry's texture * information. */ public FloatBuffer getTextureBuffer() { return texBuf[0]; } /** * <code>getTextureBuffers</code> retrieves this geometry's texture * information contained within a float buffer array. * * @return the float buffers that contain this geometry's texture * information. */ public FloatBuffer[] getTextureBuffers() { return texBuf; } /** * * <code>getTextureAsFloatBuffer</code> retrieves the texture buffer of a * given texture unit. * * @param textureUnit * the texture unit to check. * @return the texture coordinates at the given texture unit. */ public FloatBuffer getTextureBuffer(int textureUnit) { if (texBuf == null) return null; return texBuf[textureUnit]; } /** * <code>setTextureBuffer</code> sets this geometry's textures (position * 0) via a float buffer consisting of groups of two floats: x and y. * * @param buff * the new vertex buffer. */ public void setTextureBuffer(FloatBuffer buff) { this.texBuf[0] = buff; } /** * <code>setTextureBuffer</code> sets this geometry's textures st the * position given via a float buffer consisting of groups of two floats: x * and y. * * @param buff * the new vertex buffer. */ public void setTextureBuffer(FloatBuffer buff, int position) { this.texBuf[position] = buff; } /** * * <code>getNumberOfUnits</code> returns the number of texture units this * geometry supports. * * @return the number of texture units supported by the geometry. */ public int getNumberOfUnits() { if (texBuf == null) return 0; return texBuf.length; } public int getType() { return Spatial.GEOMETRY; } /** * Clears all vertex, normal, texture, and color buffers by setting them to * null. */ public void clearBuffers() { reconstruct(null, null, null, null); } /** * <code>updateBound</code> recalculates the bounding object assigned to * the geometry. This resets it parameters to adjust for any changes to the * vertex information. * */ public void updateModelBound() { if (bound != null) { bound.computeFromPoints(vertBuf); updateWorldBound(); } } /** * * <code>getModelBound</code> retrieves the bounding object that contains * the geometry node's vertices. * * @return the bounding object for this geometry. */ public BoundingVolume getModelBound() { return bound; } /** * * <code>setModelBound</code> sets the bounding object for this geometry. * * @param modelBound * the bounding object for this geometry. */ public void setModelBound(BoundingVolume modelBound) { this.worldBound = null; this.bound = modelBound; } /** * * <code>setStates</code> applies all the render states for this * particular geometry. * */ public void applyStates() { RenderState tempState = null; for (int i = 0; i < states.length; i++) { tempState = enforcedStateList[i] != null ? enforcedStateList[i] : states[i]; if (tempState != null) { if (tempState != currentStates[i]) { tempState.apply(); currentStates[i] = tempState; } } else { currentStates[i] = null; } } } /** * <code>draw</code> prepares the geometry for rendering to the display. * The renderstate is set and the subclass is responsible for rendering the * actual data. * * @see com.jme.scene.Spatial#draw(com.jme.renderer.Renderer) * @param r * the renderer that displays to the context. */ public void draw(Renderer r) { applyStates(); } /** * <code>updateWorldBound</code> updates the bounding volume that contains * this geometry. The location of the geometry is based on the location of * all this node's parents. * * @see com.jme.scene.Spatial#updateWorldBound() */ public void updateWorldBound() { if (bound != null) { worldBound = bound.transform(worldRotation, worldTranslation, worldScale, worldBound); } } /** * <code>applyRenderState</code> determines if a particular render state * is set for this Geometry. If not, the default state will be used. */ protected void applyRenderState(Stack[] states) { for (int x = 0; x < states.length; x++) { if (states[x].size() > 0) { this.states[x] = ((RenderState) states[x].peek()).extract( states[x], this); } else { this.states[x] = (RenderState) defaultStateList[x]; } } } /** * <code>randomVertice</code> returns a random vertex from the list of * vertices set to this geometry. If there are no vertices set, null is * returned. * * @param fill * a Vector3f to fill with the results. If null, one is created. * It is more efficient to pass in a nonnull vector. * @return Vector3f a random vertex from the vertex list. Null is returned * if the vertex list is not set. */ public Vector3f randomVertice(Vector3f fill) { if (vertBuf == null) return null; int i = (int) (FastMath.nextRandomFloat() * vertQuantity); if (fill == null) fill = new Vector3f(); BufferUtils.populateFromBuffer(fill, vertBuf, i); worldRotation.multLocal(fill).addLocal(worldTranslation); return fill; } public void findPick(Ray ray, PickResults results) { if (getWorldBound() == null || !isCollidable) { return; } if (getWorldBound().intersects(ray)) { //find the triangle that is being hit. //add this node and the triangle to the PickResults list. results.addPick(ray, this); } } public Spatial putClone(Spatial store, CloneCreator properties) { if (store == null) return null; super.putClone(store, properties); Geometry toStore = (Geometry) store; // This should never throw a class // cast exception if // the clone is written correctly. // Create a CloneID if none exist for this mesh. if (!properties.CloneIDExist(this)) properties.createCloneID(this); toStore.cloneID = properties.getCloneID(this); if (properties.isSet("vertices")) { toStore.setVertexBuffer(vertBuf); } else { if (vertBuf != null) { toStore.setVertexBuffer(BufferUtils.createFloatBuffer(vertBuf.capacity())); vertBuf.rewind(); toStore.vertBuf.put(vertBuf); toStore.setVertexBuffer(toStore.vertBuf); // pick up vertQuantity } else toStore.setVertexBuffer(null); } if (properties.isSet("colors")) { // if I should shallow copy colors toStore.setColorBuffer(colorBuf); } else if (colorBuf != null) { // If I should deep copy colors if (colorBuf != null) { toStore.colorBuf = BufferUtils.createFloatBuffer(colorBuf.capacity()); colorBuf.rewind(); toStore.colorBuf.put(colorBuf); } else toStore.setColorBuffer(null); } if (properties.isSet("normals")) { toStore.setNormalBuffer(normBuf); } else if (normBuf != null) { if (normBuf != null) { toStore.normBuf = BufferUtils.createFloatBuffer(normBuf.capacity()); normBuf.rewind(); toStore.normBuf.put(normBuf); } else toStore.setNormalBuffer(null); } if (properties.isSet("texcoords")) { toStore.texBuf = this.texBuf; // pick up all array positions } else { if (texBuf != null) { for (int i = 0; i < texBuf.length; i++) { if (texBuf[i] != null) { toStore.texBuf[i] = BufferUtils.createFloatBuffer(texBuf[i].capacity()); texBuf[i].rewind(); toStore.texBuf[i].put(texBuf[i]); } else toStore.texBuf[i] = null; } } else toStore.texBuf = null; } if (bound != null) toStore.setModelBound((BoundingVolume) bound.clone(null)); if (properties.isSet("vboinfo")) { toStore.vboInfo = this.vboInfo; } else { if (toStore.vboInfo != null) { toStore.setVBOInfo((VBOInfo)vboInfo.copy()); } else toStore.vboInfo = null; } return toStore; } /** * Returns the ID number that identifies this Geometry's clone ID. * * @return The assigned clone ID of this geometry. Non clones are -1. */ public int getCloneID() { return cloneID; } /** * Used with Serialization. Do not call this directly. * * @param s * @throws IOException * @see java.io.Serializable */ private void writeObject(java.io.ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // vert buffer if (vertBuf == null) s.writeInt(0); else { s.writeInt(vertBuf.capacity()); vertBuf.rewind(); for (int x = 0, len = vertBuf.capacity(); x < len; x++) s.writeFloat(vertBuf.get()); } // norm buffer if (normBuf == null) s.writeInt(0); else { s.writeInt(normBuf.capacity()); normBuf.rewind(); for (int x = 0, len = normBuf.capacity(); x < len; x++) s.writeFloat(normBuf.get()); } // color buffer if (colorBuf == null) s.writeInt(0); else { s.writeInt(colorBuf.capacity()); colorBuf.rewind(); for (int x = 0, len = colorBuf.capacity(); x < len; x++) s.writeFloat(colorBuf.get()); } // tex buffer if (texBuf == null || texBuf.length == 0) s.writeInt(0); else { s.writeInt(texBuf.length); for (int i = 0; i < texBuf.length; i++) { if (texBuf[i] == null) s.writeInt(0); else { s.writeInt(texBuf[i].capacity()); texBuf[i].rewind(); for (int x = 0, len = texBuf[i].capacity(); x < len; x++) s.writeFloat(texBuf[i].get()); } } } } /** * Used with Serialization. Do not call this directly. * * @param s * @throws IOException * @throws ClassNotFoundException * @see java.io.Serializable */ private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // vert buffer int len = s.readInt(); if (len == 0) { setVertexBuffer(null); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setVertexBuffer(buf); } // norm buffer len = s.readInt(); if (len == 0) { setNormalBuffer(null); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setNormalBuffer(buf); } // color buffer len = s.readInt(); if (len == 0) { setColorBuffer(null); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setColorBuffer(buf); } // tex buffers len = s.readInt(); if (len == 0) { texBuf = null; } else { texBuf = new FloatBuffer[len]; for (int i = 0; i < texBuf.length; i++) { len = s.readInt(); if (len == 0) { setTextureBuffer(null, i); } else { FloatBuffer buf = BufferUtils.createFloatBuffer(len); for (int x = 0; x < len; x++) buf.put(s.readFloat()); setTextureBuffer(buf, i); } } } } /** * <code>getDefaultColor</code> returns the color used if no * per vertex colors are specified. * * @return default color */ public ColorRGBA getDefaultColor() { return defaultColor; } /** * <code>setDefaultColor</code> sets the color to be used * if no per vertex color buffer is set. * * @param color */ public void setDefaultColor(ColorRGBA color) { defaultColor = color; } /** * <code>getWorldCoords</code> translates/rotates and scales the * coordinates of this Geometry to world coordinates based on its world * settings. The results are stored in the given FloatBuffer. If given * FloatBuffer is null, one is created. * * @param store * the FloatBuffer to store the results in, or null if you want one created. * @return store or new FloatBuffer if store == null. */ public FloatBuffer getWorldCoords(FloatBuffer store) { if (store == null || store.capacity() != vertBuf.capacity()) store = BufferUtils.clone(vertBuf); for (int v = 0, vSize = store.capacity() / 3; v < vSize; v++) { BufferUtils.populateFromBuffer(compVect, store, v); worldRotation.multLocal(compVect).multLocal(worldScale).addLocal(worldTranslation); BufferUtils.setInBuffer(compVect, store, v); } return store; } }
package com.punchthrough.bean.sdk; import android.util.Log; import com.punchthrough.bean.sdk.message.Acceleration; import com.punchthrough.bean.sdk.message.BatteryLevel; import com.punchthrough.bean.sdk.message.LedColor; import com.punchthrough.bean.sdk.message.ScratchBank; import com.punchthrough.bean.sdk.message.ScratchData; import com.punchthrough.bean.sdk.util.BeanTestCase; import com.punchthrough.bean.sdk.message.Callback; import com.punchthrough.bean.sdk.message.DeviceInfo; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for the Bean. * * Prerequisites: * - Bean within range * - Android device connected over USB */ public class TestBeanSimple extends BeanTestCase { private static final String TAG = "BeanManager"; public void setUp() { super.setUp(); setUpTestBean(); } public void tearDown() { super.tearDown(); tearDownTestBean(); } private boolean validHardwareVersion(String version) { Log.i(TAG, "Validating hardware version: " + version); return ( version.equals("E") || version.startsWith("1") || version.startsWith("2") ); } private boolean validFirmwareVersion(String version) { Log.i(TAG, "Validating firmware version: " + version); return version.length() > 0; } private boolean validSoftwareVersion(String version) { Log.i(TAG, "Validating software version: " + version); return version.length() > 0; } public void testBeanDeviceInfo() throws Exception { /** Read device information from a bean * * Warning: This test requires a nearby Bean */ DeviceInfo info = getDeviceInformation(testBean); if (!validHardwareVersion(info.hardwareVersion())) { fail("Unexpected HW version: " + info.hardwareVersion()); } if (!validFirmwareVersion(info.firmwareVersion())) { fail("Unexpected FW version: " + info.firmwareVersion()); } if (!validSoftwareVersion(info.softwareVersion())) { fail("Unexpected SW version: " + info.softwareVersion()); } Log.i(TAG, "TEST PASSED: Read Device Info"); } public void testReadFirmwareVersion() throws InterruptedException { final CountDownLatch l = new CountDownLatch(1); testBean.readFirmwareVersion(new Callback<String>() { @Override public void onResult(String result) { assertThat(validFirmwareVersion(result)).isTrue(); l.countDown(); Log.i(TAG, "TEST PASSED: Read Firmware Version"); } }); l.await(20, TimeUnit.SECONDS); } public void testReadHardwareVersion() throws InterruptedException { final CountDownLatch l = new CountDownLatch(1); testBean.readHardwareVersion(new Callback<String>() { @Override public void onResult(String result) { assertThat(validHardwareVersion(result)).isTrue(); l.countDown(); Log.i(TAG, "TEST PASSED: Read Hardware Version"); } }); l.await(20, TimeUnit.SECONDS); } public void testBeanReadWriteScratchBank() throws Exception { /** Test Scratch characteristic functionality * * Warning: This test requires a nearby Bean */ // write to BANK_1 and BANK_5 testBean.setScratchData(ScratchBank.BANK_1, new byte[]{11, 12, 13}); testBean.setScratchData(ScratchBank.BANK_5, new byte[]{51, 52, 53}); // read BANK_1 final CountDownLatch scratch1Latch = new CountDownLatch(1); testBean.readScratchData(ScratchBank.BANK_1, new Callback<ScratchData>() { @Override public void onResult(ScratchData result) { assertThat(result.number()).isEqualTo(1); assertThat(result.data()[0]).isEqualTo((byte) 11); assertThat(result.data()[1]).isEqualTo((byte)12); assertThat(result.data()[2]).isEqualTo((byte) 13); scratch1Latch.countDown(); Log.i(TAG, "TEST PASSED: Scratch Bank 1"); } }); scratch1Latch.await(); // read BANK_5 final CountDownLatch scratch5Latch = new CountDownLatch(1); testBean.readScratchData(ScratchBank.BANK_5, new Callback<ScratchData>() { @Override public void onResult(ScratchData result) { assertThat(result.number()).isEqualTo(5); assertThat(result.data()[0]).isEqualTo((byte) 51); assertThat(result.data()[1]).isEqualTo((byte) 52); assertThat(result.data()[2]).isEqualTo((byte) 53); scratch5Latch.countDown(); Log.i(TAG, "TEST PASSED: Scratch Bank 5"); } }); scratch5Latch.await(); } public void testBatteryProfile() throws Exception { final CountDownLatch tlatch = new CountDownLatch(1); testBean.readBatteryLevel(new Callback<BatteryLevel>() { @Override public void onResult(BatteryLevel result) { assertThat(result.getPercentage()).isGreaterThan(0); tlatch.countDown(); Log.i(TAG, "TEST PASSED: Battery Profile"); } }); tlatch.await(20, TimeUnit.SECONDS); } public void testBeanLeds() throws Exception { final CountDownLatch tlatch = new CountDownLatch(1); final LedColor blue = LedColor.create(0, 0, 255); final LedColor off = LedColor.create(0, 0, 0); testBean.setLed(blue); testBean.readLed(new Callback<LedColor>() { @Override public void onResult(LedColor result) { assertThat(result.equals(blue)); tlatch.countDown(); Log.i(TAG, "TEST PASSED: LEDs"); } }); tlatch.await(20, TimeUnit.SECONDS); } public void testBeanAccelerometer() throws Exception { final CountDownLatch tlatch = new CountDownLatch(1); testBean.readAcceleration(new Callback<Acceleration>() { @Override public void onResult(Acceleration result) { tlatch.countDown(); Log.i(TAG, "TEST PASSED: Accelerometer"); } }); tlatch.await(20, TimeUnit.SECONDS); } }
package org.gluu.oxtrust.ldap.service; import java.lang.annotation.Annotation; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.BeforeDestroyed; import javax.enterprise.context.Initialized; import javax.enterprise.event.Observes; import javax.enterprise.inject.Instance; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.ServletContext; import org.gluu.oxtrust.config.ConfigurationFactory; import org.gluu.oxtrust.config.ConfigurationFactory.PersistenceConfiguration; import org.gluu.oxtrust.ldap.cache.service.CacheRefreshTimer; import org.gluu.oxtrust.service.CleanerTimer; import org.gluu.oxtrust.service.MetricService; import org.gluu.oxtrust.service.cdi.event.CentralLdap; import org.gluu.oxtrust.service.custom.LdapCentralConfigurationReload; import org.gluu.oxtrust.service.logger.LoggerService; import org.gluu.oxtrust.service.status.ldap.LdapStatusTimer; import org.gluu.oxtrust.util.BuildVersionService; import org.gluu.persist.PersistenceEntryManager; import org.gluu.persist.ldap.impl.LdapEntryManager; import org.slf4j.Logger; import org.slf4j.bridge.SLF4JBridgeHandler; import org.xdi.exception.OxIntializationException; import org.xdi.model.custom.script.CustomScriptType; import org.xdi.oxauth.client.OpenIdConfigurationClient; import org.xdi.oxauth.client.OpenIdConfigurationResponse; import org.xdi.oxauth.client.OpenIdConnectDiscoveryClient; import org.xdi.oxauth.client.OpenIdConnectDiscoveryResponse; import org.xdi.oxauth.client.uma.UmaClientFactory; import org.xdi.oxauth.client.uma.UmaMetadataService; import org.xdi.oxauth.model.uma.UmaMetadata; import org.xdi.oxauth.model.util.SecurityProviderUtility; import org.xdi.service.JsonService; import org.xdi.service.PythonService; import org.xdi.service.cdi.event.LdapConfigurationReload; import org.xdi.service.cdi.util.CdiUtil; import org.xdi.service.custom.lib.CustomLibrariesLoader; import org.xdi.service.custom.script.CustomScriptManager; import org.xdi.service.metric.inject.ReportMetric; import org.xdi.service.timer.QuartzSchedulerManager; import org.xdi.util.StringHelper; import org.xdi.util.properties.FileConfiguration; import org.xdi.util.security.StringEncrypter; import org.xdi.util.security.StringEncrypter.EncryptionException; /** * Perform startup time initialization * * @author Yuriy Movchan */ @ApplicationScoped @Named public class AppInitializer { @Inject private Logger log; @Inject private BeanManager beanManager; @Inject @Named(ApplicationFactory.PERSISTENCE_ENTRY_MANAGER_NAME) private Instance<PersistenceEntryManager> persistenceEntryManagerInstance; @Inject @Named(ApplicationFactory.PERSISTENCE_METRIC_ENTRY_MANAGER_NAME) @ReportMetric private Instance<PersistenceEntryManager> persistenceMetricEntryManagerInstance; @Inject @Named(ApplicationFactory.PERSISTENCE_CENTRAL_ENTRY_MANAGER_NAME) @CentralLdap private Instance<PersistenceEntryManager> persistenceCentralEntryManagerInstance; @Inject private Instance<EncryptionService> encryptionServiceInstance; @Inject private ApplicationFactory applicationFactory; @Inject private SvnSyncTimer svnSyncTimer; @Inject private MetadataValidationTimer metadataValidationTimer; @Inject private EntityIDMonitoringService entityIDMonitoringService; @Inject private LogFileSizeChecker logFileSizeChecker; @Inject private ConfigurationFactory configurationFactory; @Inject private CacheRefreshTimer cacheRefreshTimer; @Inject private StatusCheckerDaily statusCheckerDaily; @Inject private StatusCheckerTimer statusCheckerTimer; @Inject private PythonService pythonService; @Inject private MetricService metricService; @Inject private CustomScriptManager customScriptManager; @Inject private LdapStatusTimer ldapStatusTimer; @Inject private ShibbolethInitializer shibbolethInitializer; @Inject private JsonService jsonService; @Inject private TemplateService templateService; @Inject private SubversionService subversionService; @Inject private CustomLibrariesLoader customLibrariesLoader; @Inject private QuartzSchedulerManager quartzSchedulerManager; @Inject private LdifArchiver ldifArchiver; @Inject private BuildVersionService buildVersionService; @Inject private LoggerService loggerService; @Inject private CleanerTimer cleanerTimer; private AtomicBoolean isActive; private long lastFinishedTime; @PostConstruct public void createApplicationComponents() { SecurityProviderUtility.installBCProvider(); // Remove JUL console logger SLF4JBridgeHandler.removeHandlersForRootLogger(); // Add SLF4JBridgeHandler to JUL root logger SLF4JBridgeHandler.install(); } /** * Initialize components and schedule DS connection time checker */ public void applicationInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) { log.debug("Initializing application services"); showBuildInfo(); customLibrariesLoader.init(); configurationFactory.create(); PersistenceEntryManager localLdapEntryManager = persistenceEntryManagerInstance.get(); initializeLdifArchiver(localLdapEntryManager); // Initialize template engine templateService.initTemplateEngine(); // Initialize SubversionService subversionService.initSubversionService(); // Initialize python interpreter pythonService.initPythonInterpreter(configurationFactory.getPersistenceConfiguration().getConfiguration() .getString("pythonModulesDir", null)); // Initialize Shibboleth shibbolethInitializer.createShibbolethConfiguration(); // Initialize script manager List<CustomScriptType> supportedCustomScriptTypes = Arrays.asList(CustomScriptType.CACHE_REFRESH, CustomScriptType.UPDATE_USER, CustomScriptType.USER_REGISTRATION, CustomScriptType.ID_GENERATOR, CustomScriptType.SCIM); // Start timer initSchedulerService(); // Schedule timer tasks metricService.initTimer(); configurationFactory.initTimer(); loggerService.initTimer(); ldapStatusTimer.initTimer(); metadataValidationTimer.initTimer(); entityIDMonitoringService.initTimer(); cacheRefreshTimer.initTimer(); customScriptManager.initTimer(supportedCustomScriptTypes); cleanerTimer.initTimer(); statusCheckerDaily.initTimer(); statusCheckerTimer.initTimer(); svnSyncTimer.initTimer(); logFileSizeChecker.initTimer(); } protected void initSchedulerService() { quartzSchedulerManager.start(); String disableScheduler = System.getProperties().getProperty("gluu.disable.scheduler"); if ((disableScheduler != null) && Boolean.valueOf(disableScheduler)) { this.log.warn("Suspending Quartz Scheduler Service..."); quartzSchedulerManager.standby(); return; } } @Produces @ApplicationScoped public StringEncrypter getStringEncrypter() throws OxIntializationException { String encodeSalt = configurationFactory.getCryptoConfigurationSalt(); if (StringHelper.isEmpty(encodeSalt)) { throw new OxIntializationException("Encode salt isn't defined"); } try { StringEncrypter stringEncrypter = StringEncrypter.instance(encodeSalt); return stringEncrypter; } catch (EncryptionException ex) { throw new OxIntializationException("Failed to create StringEncrypter instance"); } } private void showBuildInfo() { log.info("Build date {}. Code revision {} on {}. Build {}", getGluuBuildDate(), getGluuRevisionVersion(), getGluuRevisionDate(), getGluuBuildNumber()); } protected Properties preparePersistanceProperties() { PersistenceConfiguration persistenceConfiguration = this.configurationFactory.getPersistenceConfiguration(); FileConfiguration persistenceConfig = persistenceConfiguration.getConfiguration(); Properties connectionProperties = (Properties) persistenceConfig.getProperties(); EncryptionService securityService = encryptionServiceInstance.get(); Properties decryptedConnectionProperties = securityService.decryptAllProperties(connectionProperties); return decryptedConnectionProperties; } protected Properties prepareCustomPersistanceProperties(String configId) { Properties connectionProperties = preparePersistanceProperties(); if (StringHelper.isNotEmpty(configId)) { // Replace properties names 'configId.xyz' to 'configId.xyz' in order to // override default values connectionProperties = (Properties) connectionProperties.clone(); String baseGroup = configId + "."; for (Object key : connectionProperties.keySet()) { String propertyName = (String) key; if (propertyName.startsWith(baseGroup)) { propertyName = propertyName.substring(baseGroup.length()); Object value = connectionProperties.get(key); connectionProperties.put(propertyName, value); } } } return connectionProperties; } @Produces @ApplicationScoped @Named(ApplicationFactory.PERSISTENCE_ENTRY_MANAGER_NAME) public PersistenceEntryManager createPersistenceEntryManager() { Properties connectionProperties = preparePersistanceProperties(); PersistenceEntryManager persistenceEntryManager = applicationFactory.getPersistenceEntryManagerFactory() .createEntryManager(connectionProperties); log.info("Created {}: {} with operation service: {}", new Object[] { ApplicationFactory.PERSISTENCE_ENTRY_MANAGER_NAME, persistenceEntryManager, persistenceEntryManager.getOperationService() }); return persistenceEntryManager; } @Produces @ApplicationScoped @Named(ApplicationFactory.PERSISTENCE_METRIC_ENTRY_MANAGER_NAME) @ReportMetric public PersistenceEntryManager createMetricPersistenceEntryManager() { Properties connectionProperties = prepareCustomPersistanceProperties(ApplicationFactory.PERSISTENCE_METRIC_CONFIG_GROUP_NAME); PersistenceEntryManager persistenceEntryManager = applicationFactory.getPersistenceEntryManagerFactory() .createEntryManager(connectionProperties); log.info("Created {}: {} with operation service: {}", new Object[] { ApplicationFactory.PERSISTENCE_METRIC_ENTRY_MANAGER_NAME, persistenceEntryManager, persistenceEntryManager.getOperationService() }); return persistenceEntryManager; } @Produces @ApplicationScoped @Named(ApplicationFactory.PERSISTENCE_CENTRAL_ENTRY_MANAGER_NAME) @CentralLdap public PersistenceEntryManager createCentralLdapEntryManager() { if (!((configurationFactory.getLdapCentralConfiguration() != null) && configurationFactory.getAppConfiguration().isUpdateApplianceStatus())) { return new LdapEntryManager(); } FileConfiguration ldapCentralConfig = configurationFactory.getLdapCentralConfiguration(); Properties centralConnectionProperties = (Properties) ldapCentralConfig.getProperties(); EncryptionService securityService = encryptionServiceInstance.get(); Properties decryptedCentralConnectionProperties = securityService .decryptProperties(centralConnectionProperties); // TODO: Review if it works well with couchbase PersistenceEntryManager centralLdapEntryManager = applicationFactory.getPersistenceEntryManagerFactory() .createEntryManager(decryptedCentralConnectionProperties); log.info("Created {}: {}", new Object[] { ApplicationFactory.PERSISTENCE_CENTRAL_ENTRY_MANAGER_NAME, centralLdapEntryManager.getOperationService() }); return centralLdapEntryManager; } public void recreatePersistanceEntryManager(@Observes @LdapConfigurationReload String event) { recreatePersistanceEntryManagerImpl(persistenceEntryManagerInstance, ApplicationFactory.PERSISTENCE_ENTRY_MANAGER_NAME); recreatePersistanceEntryManagerImpl(persistenceEntryManagerInstance, ApplicationFactory.PERSISTENCE_METRIC_ENTRY_MANAGER_NAME, ReportMetric.Literal.INSTANCE); } protected void recreatePersistanceEntryManagerImpl(Instance<PersistenceEntryManager> instance, String persistenceEntryManagerName, Annotation... qualifiers) { // Get existing application scoped instance PersistenceEntryManager oldLdapEntryManager = CdiUtil.getContextBean(beanManager, PersistenceEntryManager.class, persistenceEntryManagerName, qualifiers); // Close existing connections closePersistenceEntryManager(oldLdapEntryManager, persistenceEntryManagerName); // Force to create new bean PersistenceEntryManager ldapEntryManager = instance.get(); instance.destroy(ldapEntryManager); log.info("Recreated instance {}: {} with operation service: {}", persistenceEntryManagerName, ldapEntryManager, ldapEntryManager.getOperationService()); } public void recreateCentralPersistanceEntryManager(@Observes @LdapCentralConfigurationReload String event) { // Get existing application scoped instance PersistenceEntryManager oldCentralLdapEntryManager = CdiUtil.getContextBean(beanManager, PersistenceEntryManager.class, ApplicationFactory.PERSISTENCE_CENTRAL_ENTRY_MANAGER_NAME); // Close existing connections closePersistenceEntryManager(oldCentralLdapEntryManager, ApplicationFactory.PERSISTENCE_CENTRAL_ENTRY_MANAGER_NAME); // Force to create new bean PersistenceEntryManager ldapCentralEntryManager = persistenceCentralEntryManagerInstance.get(); persistenceEntryManagerInstance.destroy(ldapCentralEntryManager); log.info("Recreated instance {}: {}", ApplicationFactory.PERSISTENCE_CENTRAL_ENTRY_MANAGER_NAME, ldapCentralEntryManager); } private void closePersistenceEntryManager(PersistenceEntryManager oldPersistenceEntryManager, String persistenceEntryManagerName) { // Close existing connections if ((oldPersistenceEntryManager != null) && (oldPersistenceEntryManager.getOperationService() != null)) { log.debug("Attempting to destroy {}:{} with operation service: {}", persistenceEntryManagerName, oldPersistenceEntryManager, oldPersistenceEntryManager.getOperationService()); oldPersistenceEntryManager.destroy(); log.debug("Destroyed {}:{} with operation service: {}", persistenceEntryManagerName, oldPersistenceEntryManager, oldPersistenceEntryManager.getOperationService()); } } private void initializeLdifArchiver(PersistenceEntryManager ldapEntryManager) { ldifArchiver.init(); ldapEntryManager.addDeleteSubscriber(ldifArchiver); } @Produces @ApplicationScoped @Named("openIdConfiguration") public OpenIdConfigurationResponse initOpenIdConfiguration() throws OxIntializationException { String oxAuthIssuer = this.configurationFactory.getAppConfiguration().getOxAuthIssuer(); if (StringHelper.isEmpty(oxAuthIssuer)) { log.info("oxAuth issuer isn't specified"); return null; } log.debug("Attempting to determine configuration endpoint URL"); OpenIdConnectDiscoveryClient openIdConnectDiscoveryClient; try { openIdConnectDiscoveryClient = new OpenIdConnectDiscoveryClient(oxAuthIssuer); } catch (URISyntaxException ex) { throw new OxIntializationException("OpenId discovery response is invalid!", ex); } OpenIdConnectDiscoveryResponse openIdConnectDiscoveryResponse = openIdConnectDiscoveryClient.exec(); if ((openIdConnectDiscoveryResponse.getStatus() != 200) || (openIdConnectDiscoveryResponse.getSubject() == null) || (openIdConnectDiscoveryResponse.getLinks().size() == 0)) { throw new OxIntializationException("OpenId discovery response is invalid!"); } log.debug("Attempting to load OpenID configuration"); String configurationEndpoint = openIdConnectDiscoveryResponse.getLinks().get(0).getHref() + "/.well-known/openid-configuration"; OpenIdConfigurationClient client = new OpenIdConfigurationClient(configurationEndpoint); OpenIdConfigurationResponse openIdConfiguration; try { openIdConfiguration = client.execOpenIdConfiguration(); } catch (Exception e) { log.error("Failed to load OpenId configuration!", e); throw new OxIntializationException("Failed to load OpenId configuration!"); } if (openIdConfiguration.getStatus() != 200) { throw new OxIntializationException("OpenId configuration response is invalid!"); } return openIdConfiguration; } @Produces @ApplicationScoped @Named("umaMetadataConfiguration") public UmaMetadata initUmaMetadataConfiguration() throws OxIntializationException { String umaConfigurationEndpoint = getUmaConfigurationEndpoint(); if (StringHelper.isEmpty(umaConfigurationEndpoint)) { return null; } UmaMetadataService metaDataConfigurationService = UmaClientFactory.instance() .createMetadataService(umaConfigurationEndpoint); UmaMetadata metadataConfiguration = metaDataConfigurationService.getMetadata(); if (metadataConfiguration == null) { throw new OxIntializationException("UMA meta data configuration is invalid!"); } return metadataConfiguration; } public String getUmaConfigurationEndpoint() { String umaIssuer = this.configurationFactory.getAppConfiguration().getUmaIssuer(); if (StringHelper.isEmpty(umaIssuer)) { log.trace("oxAuth UMA issuer isn't specified"); return null; } String umaConfigurationEndpoint = umaIssuer; if (!umaConfigurationEndpoint.endsWith("uma2-configuration")) { umaConfigurationEndpoint += "/.well-known/uma2-configuration"; } return umaConfigurationEndpoint; } public void destroy(@Observes @BeforeDestroyed(ApplicationScoped.class) ServletContext init) { log.info("Closing LDAP connection at server shutdown..."); PersistenceEntryManager persistanceEntryManager = persistenceEntryManagerInstance.get(); closePersistenceEntryManager(persistanceEntryManager, ApplicationFactory.PERSISTENCE_ENTRY_MANAGER_NAME); PersistenceEntryManager persistanceMetricEntryManager = persistenceMetricEntryManagerInstance.get(); closePersistenceEntryManager(persistanceMetricEntryManager, ApplicationFactory.PERSISTENCE_METRIC_ENTRY_MANAGER_NAME); PersistenceEntryManager persistanceCentralEntryManager = persistenceCentralEntryManagerInstance.get(); if (persistanceCentralEntryManager != null) { closePersistenceEntryManager(persistanceCentralEntryManager, ApplicationFactory.PERSISTENCE_CENTRAL_ENTRY_MANAGER_NAME); } } public String getGluuRevisionVersion() { return buildVersionService.getRevisionVersion(); } public String getGluuRevisionDate() { return buildVersionService.getRevisionDate(); } public String getGluuBuildDate() { return buildVersionService.getBuildDate(); } public String getGluuBuildNumber() { return buildVersionService.getBuildNumber(); } }
package com.oracle.poco.bbhelper.log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; import com.oracle.poco.bbhelper.Constants; import com.oracle.poco.bbhelper.exception.BbhelperException; import com.oracle.poco.bbhelper.exception.ErrorDescription; /** * * * * * * * @author hhayakaw * */ @Component public class BbhelperLogger { private static final String FILE_PATH_LOGGING_PROPERTIES = "logging.properties"; private static final String LOGGER_NAME_SYSTEM = "com.oracle.bbhelper.log.system"; private static final String LOGGER_NAME_ACCESS = "com.oracle.bbhelper.log.access"; private static final String LOGGER_NAME_DEBUG = "com.oracle.bbhelper.log.debug"; private Logger SystemLogger; private Logger AccessLogger; private Logger DebugLogger; // uninstanciable private BbhelperLogger() { initInternal(); } private void initInternal() { File logdir = new File("logs"); if (!logdir.exists() || !logdir.isDirectory()) { if (!logdir.mkdir()) { System.out.println("ERROR! : Can't make log directory."); System.exit(1); } } final InputStream in = this.getClass().getClassLoader(). getResourceAsStream(FILE_PATH_LOGGING_PROPERTIES); if (in == null) { throw new IllegalStateException("Failed to load logging.properties."); } try { LogManager.getLogManager().readConfiguration(in); SystemLogger = Logger.getLogger(LOGGER_NAME_SYSTEM); SystemLogger.addHandler(new ConsoleHandler()); SystemLogger.addHandler(new SystemLogFileHandler()); AccessLogger = Logger.getLogger(LOGGER_NAME_ACCESS); AccessLogger.addHandler(new ConsoleHandler()); AccessLogger.addHandler(new AccessLogFileHandler()); DebugLogger = Logger.getLogger(LOGGER_NAME_DEBUG); DebugLogger.addHandler(new ConsoleHandler()); DebugLogger.addHandler(new DebugLogFileHandler()); } catch (SecurityException | IOException e) { throw new IllegalStateException(e); } } /** * @param request */ public void request(HttpServletRequest request) { if (request == null) { throw new NullPointerException("request is null."); } AccessLogger.info("REQUEST: " + (String)request.getAttribute( Constants.REQUEST_ATTR_KEY_REQUEST_ID)); } /** * @param message */ public void response(HttpServletRequest request) { if (request == null) { throw new NullPointerException("request is null."); } AccessLogger.info("RESPONSE: " + (String)request.getAttribute( Constants.REQUEST_ATTR_KEY_REQUEST_ID)); } /** * @param message */ public void info(String message) { if (message == null || message.length() == 0) { // do nothing. return; } SystemLogger.info(message); } /** * @param request * @param description */ public void severe(HttpServletRequest request, ErrorDescription description) { if (description == null) { // do nothing. return; } String message = getBaseMessage( request, description.getFullDescription()).toString(); SystemLogger.severe(message); } /** * @param description */ public void severe(ErrorDescription description) { if (description == null) { // do nothing. return; } SystemLogger.severe(description.getFullDescription()); } /** * @param reqest * @param e */ public void logBbhelperException( HttpServletRequest request, BbhelperException e) { if (e == null) { return; } logThrowable(request, e.getErrorDescription().getFullDescription(), e); } /** * @param t */ private void logThrowable( HttpServletRequest request, String message, Throwable t) { if (t == null) { // do nothing. return; } String logMessage = getBaseMessage(request, message).toString(); SystemLogger.severe(logMessage); DebugLogger.log(Level.SEVERE, logMessage, t); } /** * @param message */ public void debug(String message) { if (message == null || message.length() == 0) { // do nothing. return; } DebugLogger.fine(message); } private StringBuilder getBaseMessage( HttpServletRequest request, String message) { String request_id; if (request == null) { request_id = "N/A"; } request_id = (String)request.getAttribute( Constants.REQUEST_ATTR_KEY_REQUEST_ID); StringBuilder builder = new StringBuilder(); // TODO requestNull builder.append("REQUEST_ID: ").append(request_id).append(","); builder.append("REQUEST_URL: ").append(request.getRequestURL()).append(","); builder.append("MESSAGE: ").append(message); return builder; } }
package de.hpi.bpmn2execpn.converter; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import de.hpi.bpmn.BPMNDiagram; import de.hpi.bpmn.DataObject; import de.hpi.bpmn.Edge; import de.hpi.bpmn.ExecDataObject; import de.hpi.bpmn.IntermediateEvent; import de.hpi.bpmn.SubProcess; import de.hpi.bpmn.Task; import de.hpi.bpmn2execpn.model.ExecTask; import de.hpi.bpmn2pn.converter.Converter; import de.hpi.bpmn2pn.model.ConversionContext; import de.hpi.bpmn2pn.model.SubProcessPlaces; import de.hpi.execpn.AutomaticTransition; import de.hpi.execpn.ExecFlowRelationship; import de.hpi.execpn.ExecPetriNet; import de.hpi.execpn.FormTransition; import de.hpi.execpn.TransformationTransition; import de.hpi.execpn.impl.ExecPNFactoryImpl; import de.hpi.execpn.pnml.Locator; import de.hpi.petrinet.ExecPlace; import de.hpi.petrinet.FlowRelationship; import de.hpi.petrinet.PetriNet; import de.hpi.petrinet.Place; import de.hpi.petrinet.Transition; public class ExecConverter extends Converter { private static final String baseXsltURL = "http://localhost:3000/examples/contextPlace/"; private static final String copyXsltURL = baseXsltURL + "copy_xslt.xsl"; private static final String extractDataURL = baseXsltURL + "extract_processdata.xsl"; // TODO: Resolve this by using pnengine.properties - Engine does not have to be local! private static final String enginePostURL = "http://localhost:3000/documents/"; private static String contextPath; protected String standardModel; protected String baseFileName; private List<ExecTask> taskList; public ExecConverter(BPMNDiagram diagram, String modelURL, String contextPath) { super(diagram, new ExecPNFactoryImpl(modelURL)); this.standardModel = modelURL; this.taskList = new ArrayList<ExecTask>(); this.contextPath = contextPath; } public void setBaseFileName(String basefilename) { this.baseFileName = basefilename; } @Override protected void handleDiagram(PetriNet net, ConversionContext c) { ((ExecPetriNet) net).setName(diagram.getTitle()); } @Override protected void createStartPlaces(PetriNet net, ConversionContext c) { // do nothing...: we want start transitions instead of start places } /* @Override public PetriNet convert () { // !! no start place for petrinet // but create a start transition ExecPetriNet pn = (ExecPetriNet) super.convert(); AutomaticTransition startTransition = addAutomaticTransition(pn, "tr_initProcess", "", "initProcess", copyXsltURL, false); pn.setStartTransition(startTransition); Vector <Place> dataPlaces = ExecTask.pl_dataPlaces; for (Place place : dataPlaces) addFlowRelationship(pn, startTransition, place); return pn; } // connect startTransition with contextplaces */ // TODO this is a dirty hack... @Override protected void handleTask(PetriNet net, Task task, ConversionContext c) { ExecTask exTask = new ExecTask(); exTask.setId(task.getId()); exTask.setLabel(task.getLabel()); exTask.setResourceId(task.getResourceId()); String taskDesignation = exTask.getTaskDesignation(); // create proper model, form and bindings String model = null; String form = null; String bindings = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ; try { DocumentBuilder parser = factory.newDocumentBuilder ( ) ; Document modelDoc = parser.newDocument(); Element dataEl = modelDoc.createElement("data"); Node data = modelDoc.appendChild(dataEl); Node metaData = data.appendChild(modelDoc.createElement("metadata")); Node processData = data.appendChild(modelDoc.createElement("processdata")); //TODO: use metadata_model.xml instead of building it by hand // create MetaData Layout for Task model // (take attention to the fact, that the attributes are again defined in the engine) /*Node startTime =*/ metaData.appendChild(modelDoc.createElement("startTime")); /*Node endTime =*/ metaData.appendChild(modelDoc.createElement("endTime")); /*Node status =*/ metaData.appendChild(modelDoc.createElement("status")); /*Node owner =*/ metaData.appendChild(modelDoc.createElement("owner")); /*Node isDelegated =*/ metaData.appendChild(modelDoc.createElement("isDelegated")); /*Node reviewRequested =*/ metaData.appendChild(modelDoc.createElement("reviewRequested")); /*Node firstOwner =*/ metaData.appendChild(modelDoc.createElement("firstOwner")); /*Node actions =*/ metaData.appendChild(modelDoc.createElement("actions")); // create MetaData Layout Actions, that will be logged --> here not regarded // interrogate all incoming data objects for task, create DataPlaces for them and create Task model List<Edge> edges_in = task.getIncomingEdges(); for (Edge edge : edges_in) { if (edge.getSource() instanceof ExecDataObject) { ExecDataObject dataObject = (ExecDataObject)edge.getSource(); // for incoming data objects of task: create read dependencies addReadOnlyExecFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_enable, null); // create XML Structure for Task String modelXML = dataObject.getModel(); try { Document doc = parser.parse(new InputSource(new StringReader(modelXML))); Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId())); Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild(); Node child = dataTagOfDataModel.getNextSibling(); while (child != null) { Node attributeToAttach = modelDoc.importNode(child.cloneNode(true), true); dataObjectId.appendChild(attributeToAttach); child = child.getNextSibling(); }; } catch (Exception io) { io.printStackTrace(); } } } // interrogate all outgoing data objects for task and create flow relationships for them List<Edge> edges_out = task.getOutgoingEdges(); for (Edge edge : edges_out) { if (edge.getTarget() instanceof ExecDataObject) { ExecDataObject dataObject = (ExecDataObject)edge.getTarget(); // for outgoing data objects of task: create read/write dependencies NodeList list = processData.getChildNodes(); String modelXML = dataObject.getModel(); if (!isContainedIn(dataObject, list)) { // if object is already read, then not neccessary Document doc = parser.parse(new InputSource(new StringReader(modelXML))); Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId())); Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild(); Node child = dataTagOfDataModel.getNextSibling(); while (child != null) { Node attributeToAttach = modelDoc.importNode(child.cloneNode(true), true); dataObjectId.appendChild(attributeToAttach); child = child.getNextSibling(); }; addReadOnlyExecFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_enable, null); } addFlowRelationship(net, exTask.tr_finish, ExecTask.getDataPlace(dataObject.getId())); addFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_finish); } } // build form Document template without attributes Document formDoc = buildFormTemplate(parser); // adds form fields of necessary attributes formDoc = addFormFields(formDoc, processData); // build bindings Document for attributes Document bindDoc = buildBindingsDocument(parser); // adds binding attributes for tags bindDoc = addBindings(bindDoc, processData); // append metadata for internal tokenmodel of transitions Element message = modelDoc.createElement("message"); Element deadline = modelDoc.createElement("deadline"); Element wantToReview = modelDoc.createElement("wantToReview"); processData.appendChild(message); processData.appendChild(deadline); processData.appendChild(wantToReview); message.setAttribute("readonly", "true"); deadline.setAttribute("readonly", "true"); wantToReview.setTextContent("false"); // persist form and bindings and save URL model = this.postDataToURL(domToString(modelDoc),enginePostURL); form = this.postDataToURL(domToString(formDoc),enginePostURL); String bindingsString = domToString(bindDoc); bindings = this.postDataToURL( bindingsString.replace("<bindings>", "").replace("</bindings>", ""), enginePostURL); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } catch (SAXException sax) { sax.printStackTrace(); } exTask.pl_inited = addPlace(net, "pl_inited_" + task.getId(), ExecPlace.Type.flow); exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId(), ExecPlace.Type.flow); exTask.pl_running = addPlace(net, "pl_running_" + task.getId(), ExecPlace.Type.flow); exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId(), ExecPlace.Type.flow); exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId(), ExecPlace.Type.flow); exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId(), ExecPlace.Type.flow); exTask.pl_context = addPlace(net, "pl_context_" + task.getId(), ExecPlace.Type.context); // add role dependencies String rolename = task.getRolename(); // integrate context place exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime")); exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime")); exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status")); exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner")); exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isDelegated")); exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isReviewed")); exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested")); exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner")); exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions")); //init transition exTask.tr_init = addAutomaticTransition(net, "tr_init_" + task.getId(), taskDesignation); addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_init); addFlowRelationship(net, exTask.tr_init, exTask.pl_inited); //enable transition //note: structure of context place must be initialized by engine AutomaticTransition enable = addAutomaticTransition(net, "tr_enable_" + task.getId(), taskDesignation); exTask.tr_enable = enable; //addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable); addFlowRelationship(net, exTask.pl_inited, exTask.tr_enable); addExecFlowRelationship(net, exTask.tr_enable, exTask.pl_ready, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_enable); addExecFlowRelationship(net, exTask.tr_enable, exTask.pl_context, baseXsltURL + "context_enable.xsl"); enable.setModelURL(model); // allocate Transition exTask.tr_allocate = addTransformationTransition(net, "tr_allocate_" + task.getId(), taskDesignation,"allocate", copyXsltURL); addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl"); exTask.tr_allocate.setRolename(rolename); if (task.isSkippable()) { // skip Transition exTask.setSkippable(true); exTask.tr_skip = addTransformationTransition(net, "tr_skip_" + task.getId(), taskDesignation, "skip", copyXsltURL); addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl"); } // submit Transition FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings); submit.setAction("submit"); exTask.tr_submit = submit; addFlowRelationship(net, exTask.pl_running, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl"); exTask.tr_submit.setRolename(rolename); submit.setFormURL(form); submit.setBindingsURL(bindings); // delegate Transition FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), taskDesignation, model, form, bindings); delegate.setAction("delegate"); delegate.setGuard(exTask.pl_context.getId() + ".isDelegated == 'true'"); exTask.tr_delegate = delegate; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl"); exTask.tr_delegate.setRolename(rolename); delegate.setFormURL(form); delegate.setBindingsURL(bindings); // review Transition FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), taskDesignation,model,form,bindings); review.setAction("review"); review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".reviewRequested == 'true'"); exTask.tr_review = review; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl"); exTask.tr_review.setRolename(rolename); review.setFormURL(form); review.setBindingsURL(bindings); // done Transition exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), taskDesignation); addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done); addFlowRelationship(net, exTask.tr_done, exTask.pl_complete); addFlowRelationship(net, exTask.pl_context, exTask.tr_done); addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl"); exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".reviewRequested != 'true'"); // suspend exTask.tr_suspend = addTransformationTransition(net, "tr_suspend_" + task.getId(), taskDesignation, "suspend", copyXsltURL); addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl"); exTask.tr_suspend.setRolename(rolename); // resume exTask.tr_resume = addTransformationTransition(net, "tr_resume_" + task.getId(), taskDesignation, "resume", copyXsltURL); addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl"); exTask.tr_resume.setRolename(rolename); // finish transition exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), taskDesignation); addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl"); taskList.add(exTask); handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c); if (c.ancestorHasExcpH) handleExceptions(net, task, exTask.tr_submit, c); for (IntermediateEvent event : task.getAttachedEvents()) handleAttachedIntermediateEventForTask(net, event, c); } @Override protected void handleSubProcess(PetriNet net, SubProcess process, ConversionContext c) { super.handleSubProcess(net, process, c); if (process.isAdhoc()) { handleSubProcessAdHoc(net, process, c); } } private String getCompletionConditionString(SubProcess adHocSubprocess){ assert (adHocSubprocess.isAdhoc()); // TODO (see below) return "place_pl_context_resource2.status == 'completed'"; } /* TODO: There are a number of tasks that remain to be done here: * * - Integrating data dependencies as guards * - Transforming an Pseudo Code CC into an Ruby String (Friday, 30th May) * - Adding second parallel mode * - Connecting auto skip with context places */ protected void handleSubProcessAdHoc(PetriNet net, SubProcess process, ConversionContext c) { SubProcessPlaces pl = c.getSubprocessPlaces(process); boolean isParallel = process.isParallelOrdering(); // start and end transitions Transition startT = addTauTransition(net, "ad-hoc_start_" + process.getId()); Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId()); Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_" + process.getId()); addFlowRelationship(net, pl.startP, startT); addFlowRelationship(net, defaultEndT, pl.endP); addFlowRelationship(net, endT, pl.endP); // standard completion condition check Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId()); String completionConditionString = getCompletionConditionString(process); Transition finalize = addTauTransition(net, "ad-hoc_finalize_" + process.getId()); finalize.setGuard(completionConditionString); Transition resume = addTauTransition(net, "ad-hoc_resume_" + process.getId()); resume.setGuard("!("+completionConditionString+")" ); // synchronization and completionCondition checks(synch, corresponds to enableStarting) Place synch = addPlace(net, "ad-hoc_synch_" + process.getId()); addFlowRelationship(net, startT, synch); addFlowRelationship(net, synch, defaultEndT); addFlowRelationship(net, updatedState, resume); addFlowRelationship(net, updatedState, finalize); if (isParallel){ addFlowRelationship(net, synch, finalize); } else { addFlowRelationship(net, resume, synch); } // task specific constructs for (ExecTask exTask : taskList) { Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId()); Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId()); addFlowRelationship(net, startT, enabled); addFlowRelationship(net, enabled, exTask.tr_init); if (isParallel){ addReadOnlyFlowRelationship(net, synch, exTask.tr_allocate); } else { addFlowRelationship(net, synch, exTask.tr_allocate); } addFlowRelationship(net, exTask.tr_finish, executed); addFlowRelationship(net, exTask.tr_finish, updatedState); addFlowRelationship(net, executed, defaultEndT); if (exTask.isSkippable()) { addFlowRelationship(net, synch, exTask.tr_skip); } // let completioncondition cheks access the context place addReadOnlyFlowRelationship(net, exTask.pl_context, resume); addReadOnlyFlowRelationship(net, exTask.pl_context, finalize); // finishing construct(finalize with skip, finish and abort) Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId()); Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId()); Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId()); Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId()); addFlowRelationship(net, finalize, enableFinalize); addFlowRelationship(net, enableFinalize, skip); addFlowRelationship(net, exTask.pl_ready, skip); addFlowRelationship(net, skip, taskFinalized); addFlowRelationship(net, enableFinalize, finish); addFlowRelationship(net, executed, finish); addFlowRelationship(net, finish, taskFinalized); addFlowRelationship(net, taskFinalized, endT); } } @Override protected void handleDataObject(PetriNet net, DataObject object, ConversionContext c){ try { if (object instanceof ExecDataObject) { ExecDataObject dataobject = (ExecDataObject) object; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ; DocumentBuilder parser = factory.newDocumentBuilder ( ) ; //create data place for Task ExecPlace dataPlace = addPlace(net,"pl_data_"+dataobject.getId(), ExecPlace.Type.data); ExecTask.addDataPlace(dataPlace); // for data place add locators String modelXML = dataobject.getModel(); dataPlace.setModel(modelXML); Document doc = parser.parse(new InputSource(new StringReader(modelXML))); Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild(); Node child = dataTagOfDataModel.getFirstChild(); while (child != null) { dataPlace.addLocator(new Locator( child.getNodeName(), "xsd:string", "/data/processdata/"+dataobject.getId()+"/"+child.getNodeName())); child = child.getNextSibling(); }; } } catch (Exception io) { io.printStackTrace(); } } public TransformationTransition addTransformationTransition(PetriNet net, String id, String task, String action, String xsltURL) { TransformationTransition t =((ExecPNFactoryImpl) pnfactory).createTransformationTransition(); t.setId(id); t.setLabel(id); // TODO: why is this uncommended? // t.setTask(task); t.setAction(action); t.setXsltURL(xsltURL); net.getTransitions().add(t); return t; } public ExecFlowRelationship addExecFlowRelationship(PetriNet net, de.hpi.petrinet.Node source, de.hpi.petrinet.Node target, String xsltURL) { if (source == null || target == null) return null; ExecFlowRelationship rel = ((ExecPNFactoryImpl) pnfactory).createExecFlowRelationship(); rel.setSource(source); rel.setTarget(target); rel.setTransformationURL(xsltURL); net.getFlowRelationships().add(rel); return rel; } public ExecFlowRelationship addReadOnlyExecFlowRelationship(PetriNet net, de.hpi.petrinet.Place source, de.hpi.petrinet.Transition target, String xsltURL) { ExecFlowRelationship rel = addExecFlowRelationship(net, source, target, xsltURL); if (rel == null){ return null; } rel.setMode(FlowRelationship.RELATION_MODE_READTOKEN); return rel; } public FormTransition addFormTransition(PetriNet net, String id, String task, String model, String form, String bindings) { FormTransition t = ((ExecPNFactoryImpl)pnfactory).createFormTransition(); t.setId(id); t.setLabel(id); // TODO: why is this uncommended? // t.setTask(task); t.setFormURL(form); t.setBindingsURL(bindings); t.setModelURL(model); net.getTransitions().add(t); return t; } public AutomaticTransition addAutomaticTransition(PetriNet net, String id, String task) { AutomaticTransition t = ((ExecPNFactoryImpl)pnfactory).createAutomaticTransition(); t.setId(id); t.setLabel(id); t.setTask(task); t.setXsltURL(copyXsltURL); net.getTransitions().add(t); return t; } public ExecPlace addPlace(PetriNet net, String id, ExecPlace.Type type) { ExecPlace p = ((ExecPNFactoryImpl)pnfactory).createPlace(); p.setId(id); if (type != null) p.setType(type); net.getPlaces().add(p); return p; } Document buildFormTemplate(DocumentBuilder parser) throws IOException, SAXException{ Document template = parser.parse(new File(contextPath+"execution/form.xml")); return template; } // build Structure for forms Document addFormFields(Document doc, Node processData) { NodeList list = processData.getChildNodes(); Node root = doc.getFirstChild(); for (int i = 0; i<list.getLength(); i++) { String attributeName = list.item(i).getNodeName(); // for template watch in engine folder "/public/examples/delegation/formulartemplate" Element div = doc.createElement("div"); div.setAttribute("class", "formatted"); root.appendChild(div); div.appendChild(doc.createElement("br")); Element div2 = doc.createElement("div"); div2.setAttribute("id", attributeName + "_grp"); div.appendChild(div2); Element input = doc.createElement("x:input"); input.setAttribute("ref", "instance('ui_settings')/"+ attributeName +"/@futurereadonly"); input.setAttribute("class", "leftcheckbox"); div.appendChild(input); Element input2 = doc.createElement("x:input"); input2.setAttribute("ref", "instance('ui_settings')/"+ attributeName +"/@futurevisible"); input2.setAttribute("class", "leftcheckbox"); div.appendChild(input2); Element group = doc.createElement("x:group"); group.setAttribute("bind", "fade."+ attributeName); group.setAttribute("class", "fieldgroup"); div.appendChild(group); Element label = doc.createElement("x:label"); Element nameinput = doc.createElement("x:input"); label.setTextContent(attributeName+": "); nameinput.setAttribute("ref", "instance('output-token')/data/processdata/" + attributeName); nameinput.setAttribute("class", "inputclass"); group.appendChild(label); div.appendChild(doc.createElement("br")); div.appendChild(doc.createElement("br")); } { Element group = doc.createElement("x:group"); group.setAttribute("bind", "delegationstate"); root.appendChild(group); //delegateButton Element deltrigger = doc.createElement("x:trigger"); deltrigger.setAttribute("ref", "instance('ui_settings')/delegatebutton"); group.appendChild(deltrigger); Element dellabel = doc.createElement("x:label"); dellabel.setNodeValue("Delegate"); deltrigger.appendChild(dellabel); Element delaction = doc.createElement("x:action"); delaction.setAttribute("ev:event", "DOMActivate"); deltrigger.appendChild(delaction); Element delaction2 = doc.createElement("x:action"); delaction2.setAttribute("ev:event", "DOMActivate"); deltrigger.appendChild(delaction2); Element send = doc.createElement("x:send"); send.setAttribute("submission", "form1"); delaction2.appendChild(send); //values Element value1 = doc.createElement("x:setvalue"); value1.setAttribute("bind", "isDelegated"); value1.setNodeValue("false"); delaction.appendChild(value1); Element value2 = doc.createElement("x:setvalue"); value2.setAttribute("bind", "isReviewed"); value2.setNodeValue("false"); delaction.appendChild(value2); Element value3 = doc.createElement("x:setvalue"); value3.setAttribute("bind", "delegatedFrom"); value3.setAttribute("value", "instance('output-token')/data/metadata/owner"); delaction.appendChild(value3); Element value4 = doc.createElement("x:setvalue"); value4.setAttribute("bind", "firstOwner"); value4.setAttribute("value", "instance('output-token')/data/metadata/owner"); delaction.appendChild(value4); Element value5 = doc.createElement("x:setvalue"); value5.setAttribute("bind", "owner.readonly"); value5.setNodeValue("true"); delaction.appendChild(value5); Element value6 = doc.createElement("x:setvalue"); value6.setAttribute("bind", "owner"); value6.setAttribute("value", "instance('output-token')/data/metadata/delegate"); delaction.appendChild(value6); for (int i = 0; i<list.getLength(); i++) { String attributeName = list.item(i).getNodeName(); Element valuereadonly = doc.createElement("x:setvalue"); valuereadonly.setAttribute("bind", attributeName + ".readonly"); valuereadonly.setAttribute("value", "instance('ui_settings')/"+attributeName+"/@futurereadonly = 'true'"); delaction.appendChild(valuereadonly); Element valuevisible = doc.createElement("x:setvalue"); valuevisible.setAttribute("bind", attributeName + ".visible"); valuevisible.setAttribute("value", "instance('ui_settings')/"+attributeName+"/@futurevisible = 'true'"); delaction.appendChild(valuevisible); } //cancelButton Element canceltrigger = doc.createElement("x:trigger"); canceltrigger.setAttribute("ref", "instance('ui_settings')/cancelbutton"); group.appendChild(canceltrigger); Element cancellabel = doc.createElement("x:label"); cancellabel.setNodeValue("Cancel"); canceltrigger.appendChild(cancellabel); Element cancelaction = doc.createElement("x:action"); cancelaction.setAttribute("ev:event", "DOMActivate"); canceltrigger.appendChild(cancelaction); Element cancelaction2 = doc.createElement("x:action"); cancelaction2.setAttribute("ev:event", "DOMActivate"); canceltrigger.appendChild(cancelaction2); Element cancelsend = doc.createElement("x:send"); cancelsend.setAttribute("submission", "form1"); cancelaction2.appendChild(cancelsend); //values Element cancelvalue1 = doc.createElement("x:setvalue"); cancelvalue1.setAttribute("bind", "isDelegated"); cancelvalue1.setNodeValue("false"); cancelaction.appendChild(cancelvalue1); Element cancelvalue2 = doc.createElement("x:setvalue"); cancelvalue2.setAttribute("bind", "isReviewed"); cancelvalue2.setNodeValue("false"); cancelaction.appendChild(cancelvalue2); } { Element group = doc.createElement("x:group"); group.setAttribute("bind", "reviewstate"); root.appendChild(group); //reviewsubmitbutton Element reviewtrigger = doc.createElement("x:trigger"); reviewtrigger.setAttribute("ref", "instance('ui_settings')/reviewsubmitbutton"); group.appendChild(reviewtrigger); Element reviewlabel = doc.createElement("x:label"); reviewlabel.setNodeValue("Review"); reviewtrigger.appendChild(reviewlabel); Element reviewaction = doc.createElement("x:action"); reviewaction.setAttribute("ev:event", "DOMActivate"); reviewtrigger.appendChild(reviewaction); Element reviewaction2 = doc.createElement("x:action"); reviewaction2.setAttribute("ev:event", "DOMActivate"); reviewtrigger.appendChild(reviewaction2); Element reviewsend = doc.createElement("x:send"); reviewsend.setAttribute("submission", "form1"); reviewaction2.appendChild(reviewsend); //values Element reviewvalue1 = doc.createElement("x:setvalue"); reviewvalue1.setAttribute("bind", "wantToReview"); reviewvalue1.setNodeValue("false"); reviewaction.appendChild(reviewvalue1); Element reviewvalue2 = doc.createElement("x:setvalue"); reviewvalue2.setAttribute("bind", "isReviewed"); reviewvalue2.setNodeValue("false"); reviewaction.appendChild(reviewvalue2); } { Element group = doc.createElement("x:group"); group.setAttribute("bind", "executionstate"); root.appendChild(group); //submitButton Element submittrigger = doc.createElement("x:trigger"); submittrigger.setAttribute("ref", "instance('ui_settings')/submitbutton"); group.appendChild(submittrigger); Element submitlabel = doc.createElement("x:label"); submitlabel.setNodeValue("Submit"); submittrigger.appendChild(submitlabel); Element submitaction = doc.createElement("x:action"); submitaction.setAttribute("ev:event", "DOMActivate"); submittrigger.appendChild(submitaction); Element submitaction2 = doc.createElement("x:action"); submitaction2.setAttribute("ev:event", "DOMActivate"); submittrigger.appendChild(submitaction2); Element send = doc.createElement("x:send"); send.setAttribute("submission", "form1"); submitaction2.appendChild(send); //values Element value1 = doc.createElement("x:setvalue"); value1.setAttribute("bind", "delegatedFrom"); value1.setNodeValue(""); submitaction.appendChild(value1); Element value2 = doc.createElement("x:setvalue"); value2.setAttribute("bind", "isDelegated"); value2.setNodeValue("false"); submitaction.appendChild(value2); Element value3 = doc.createElement("x:setvalue"); value3.setAttribute("bind", "isReviewed"); value3.setNodeValue("true"); submitaction.appendChild(value3); Element value4 = doc.createElement("x:setvalue"); value4.setAttribute("bind", "owner"); value4.setAttribute("value", "instance('output-token')/data/metadata/firstOwner"); submitaction.appendChild(value4); for (int i = 0; i<list.getLength(); i++) { String attributeName = list.item(i).getNodeName(); Element valuereadonly = doc.createElement("x:setvalue"); valuereadonly.setAttribute("bind", attributeName + ".readonly"); valuereadonly.setNodeValue("false"); submitaction.appendChild(valuereadonly); Element valuevisible = doc.createElement("x:setvalue"); valuevisible.setAttribute("bind", attributeName + ".visible"); valuevisible.setNodeValue("true"); submitaction.appendChild(valuevisible); } // cancelButton Element canceltrigger = doc.createElement("x:trigger"); canceltrigger.setAttribute("ref", "instance('ui_settings')/cancelbutton"); group.appendChild(canceltrigger); Element cancellabel = doc.createElement("x:label"); cancellabel.setNodeValue("Cancel"); canceltrigger.appendChild(cancellabel); Element cancelaction = doc.createElement("x:action"); cancelaction.setAttribute("ev:event", "DOMActivate"); canceltrigger.appendChild(cancelaction); Element cancelaction2 = doc.createElement("x:action"); cancelaction2.setAttribute("ev:event", "DOMActivate"); canceltrigger.appendChild(cancelaction2); Element cancelsend = doc.createElement("x:send"); cancelsend.setAttribute("submission", "form1"); cancelaction2.appendChild(cancelsend); //values Element cancelvalue1 = doc.createElement("x:setvalue"); cancelvalue1.setAttribute("bind", "isDelegated"); cancelvalue1.setNodeValue("true"); cancelaction.appendChild(cancelvalue1); Element cancelvalue2 = doc.createElement("x:setvalue"); cancelvalue2.setAttribute("bind", "isReviewed"); cancelvalue2.setNodeValue("false"); cancelaction.appendChild(cancelvalue2); } return doc; } Document buildBindingsDocument(DocumentBuilder parser) throws IOException, SAXException{ Document bindDoc = parser.parse(new File(contextPath+"execution/bindings.xml")); return bindDoc; } // build structure for bindings Document addBindings(Document doc, Node processData) { NodeList list = processData.getChildNodes(); Node root = doc.getFirstChild(); for (int i = 0; i<list.getLength(); i++) { String attributeName = list.item(i).getNodeName(); Element bind1 = doc.createElement("x:bind"); bind1.setAttribute("id", attributeName); bind1.setAttribute("nodeset", "instance('output-token')/data/" + attributeName); root.appendChild(bind1); Element bind2 = doc.createElement("x:bind"); bind2.setAttribute("id", attributeName+".readonly"); bind2.setAttribute("nodeset", "instance('output-token')/data/" + attributeName + "/@readonly"); root.appendChild(bind2); Element bind3 = doc.createElement("x:bind"); bind3.setAttribute("id", attributeName+".visible"); bind3.setAttribute("nodeset", "instance('output-token')/data/" + attributeName +"/@visible"); root.appendChild(bind3); Element bind4 = doc.createElement("x:bind"); bind4.setAttribute("type", "xsd:boolean"); bind4.setAttribute("nodeset", "instance('output-token')/data/" + attributeName +"/@readonly"); root.appendChild(bind4); Element bind5 = doc.createElement("x:bind"); bind5.setAttribute("type", "xsd:boolean"); bind5.setAttribute("nodeset", "instance('output-token')/data/" + attributeName +"/@visible"); root.appendChild(bind5); Element bind6 = doc.createElement("x:bind"); bind6.setAttribute("type", "xsd:boolean"); bind6.setAttribute("nodeset", "instance('ui_settings')/" + attributeName +"/@futurereadonly"); root.appendChild(bind6); Element bind7 = doc.createElement("x:bind"); bind7.setAttribute("type", "xsd:boolean"); bind7.setAttribute("nodeset", "instance('ui_settings')/" + attributeName +"/@futurevisible"); root.appendChild(bind7); Element bind8 = doc.createElement("x:bind"); bind8.setAttribute("nodeset", "instance('ui_settings')/" + attributeName +"/@futurevisible"); bind8.setAttribute("relevant", "instance('output-token')/data/metadata/isDelegated = 'true' and instance('output-token')/data/processdata/" + attributeName +"/@visible = 'true'"); root.appendChild(bind8); Element bind9 = doc.createElement("x:bind"); bind9.setAttribute("nodeset", "instance('ui_settings')/" + attributeName +"/@futurereadonly"); bind9.setAttribute("relevant", "instance('output-token')/data/metadata/isDelegated = 'true' and ((instance('output-token')/data/processdata/" + attributeName +"/@readonly = 'true' and instance('output-token')/data/processdata/" + attributeName +"/@visible != 'true') or instance('output-token')/data/processdata/" + attributeName +"/@visible = 'true')"); root.appendChild(bind9); Element bind10 = doc.createElement("x:bind"); bind10.setAttribute("nodeset", "instance('output-token')/data/processdata/" + attributeName); bind10.setAttribute("readonly", "instance('output-token')/data/processdata/" + attributeName +"/@readonly = 'true'"); root.appendChild(bind10); Element bind11 = doc.createElement("x:bind"); bind11.setAttribute("nodeset", "instance('ui_settings')/" + attributeName); bind11.setAttribute("relevant", "not(instance('output-token')/data/processdata/" + attributeName +"/@visible != 'true' and instance('output-token')/data/processdata/" + attributeName +"/@readonly != 'true')"); bind11.setAttribute("id", "fade." + attributeName); root.appendChild(bind11); Element bind12 = doc.createElement("x:bind"); bind12.setAttribute("nodeset", "instance('ui_settings')/" + attributeName +"/@futurevisible"); bind12.setAttribute("readonly", "instance('ui_settings')/" + attributeName +"/@futurereadonly = 'true'"); root.appendChild(bind12); Element bind13 = doc.createElement("x:bind"); bind13.setAttribute("nodeset", "instance('ui_settings')/" + attributeName +"/@futurereadonly"); bind13.setAttribute("readonly", "instance('ui_settings')/" + attributeName +"/@futurevisible = 'true'"); root.appendChild(bind13); } return doc; } /** * Writes *requestData* to url *targetURL* as form-data * This is the same as pressing submit on a POST type HTML form * Throws: * MalformedURLException for bad URL String * IOException when connection can not be made, or error when * reading response * TODO: HOW DOES IT WORK KAI?? * * @param requestData string to POST to the URL. * empty for no post data * @param targetURL string of url to post to * and read response. * @return string response from url. */ private String postDataToURL(String requestData, String targetURL) throws MalformedURLException, IOException { String URLResponse = ""; // open the connection and prepare it to POST URL url = new URL(targetURL); HttpURLConnection URLconn = (HttpURLConnection) url.openConnection(); URLconn.setDoOutput(true); URLconn.setDoInput(true); URLconn.setAllowUserInteraction(false); URLconn.setUseCaches (false); URLconn.setRequestMethod("POST"); URLconn.setRequestProperty("Content-Length", "" + requestData.length()); URLconn.setRequestProperty("Content-Language", "en-US"); URLconn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); URLconn.setRequestProperty("Authorization", "Basic a2Fp0g=="); DataOutputStream dataOutStream = new DataOutputStream(URLconn.getOutputStream()); // Send the data dataOutStream.writeBytes(requestData); dataOutStream.flush(); dataOutStream.close(); // Read the response int resp = URLconn.getResponseCode(); if (URLconn.getResponseCode() == HttpURLConnection.HTTP_OK) URLResponse = URLconn.getURL().toString(); else throw new IOException("ResponseCode for post to engine was not OK!"); // while((nextLine = reader.readLine()) != null) { // URLResponse += nextLine; // reader.close(); return URLResponse; } private boolean isContainedIn(ExecDataObject dataObject, NodeList list){ for (int i = 0; i<list.getLength(); i++) { if (list.item(i).getNodeName().equals(dataObject.getId())) return true; } return false; } private String domToString(Document document) { // Normalizing the DOM document.getDocumentElement().normalize(); StringWriter domAsString = new StringWriter(); try { // Prepare the DOM document for writing Source source = new DOMSource(document); // Prepare the output file Result result = new StreamResult(domAsString); // Write the DOM document to the file // Get Transformer Transformer transformer = TransformerFactory.newInstance() .newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // Write to a String transformer.transform(source, result); } catch (TransformerConfigurationException e) { System.out.println("TransformerConfigurationException: " + e); } catch (TransformerException e) { System.out.println("TransformerException: " + e); } return domAsString.toString(); } }
package com.missionbit.game.states; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.missionbit.game.GameTutorial; import com.missionbit.game.sprites.Farmer; import com.missionbit.game.sprites.Sheep; public class Instruction extends State { private Sheep sheep; private Sheep theOneThatDies; private Farmer farmer; private Texture background; public Instruction(GameStateManager gsm) { super(gsm); background = new Texture("INST.png"); sheep = new Sheep (50,280); theOneThatDies = new Sheep(650, 280); farmer = new Farmer (400, 280); farmer.getPosition().x = 400; farmer.setBoundsFarmer(180, 180); cam.setToOrtho(false, GameTutorial.WIDTH, GameTutorial.HEIGHT); sheep = new Sheep (150,280); farmer = new Farmer (400, 280); cam.setToOrtho(false, GameTutorial.WIDTH, GameTutorial.HEIGHT); } @Override protected void handleInput() { if (Gdx.input.justTouched()){ gsm.set(new MenuState(gsm)); } } @Override public void create() { } @Override public void update(float dt) { handleInput(); sheep.update(dt); theOneThatDies.update(dt); farmer.update(dt); collisionCheck(); //ifs and butts if (sheep.getPosition().x > 150) { sheep.jump(); } if (sheep.getPosition().x > 250) { sheep.getPosition().x = 50; } if (farmer.getPosition().x > 650){ farmer.getPosition().x = 400; } } public void collisionCheck() { if (farmer.collides(theOneThatDies.getBounds1())){ theOneThatDies.getSheepDead(); } else { theOneThatDies.setDead(false); } } @Override public void render(final SpriteBatch sb) { sb.begin(); sb.draw(background, 0, 0, GameTutorial.WIDTH, GameTutorial.HEIGHT); sb.draw(sheep.getSheep(), sheep.getPosition().x, 220, 140, 90); if (farmer.collides(theOneThatDies.getBounds1())) { sb.draw(theOneThatDies.getSheepDead(), theOneThatDies.getPosition().x, 220, 140, 90); theOneThatDies.noSpd(); } else { sb.draw(theOneThatDies.getSheep(), theOneThatDies.getPosition().x, 220, 140,90); theOneThatDies.noSpd(); } sb.draw(farmer.getFarmer(), farmer. getPosition().x, 220, 180, 180); sb.draw(sheep.getSheep(), 100, 220, 140, 90); sb.draw(farmer.getFarmer(), 400, 220, 180, 180); sb.end(); } @Override public void dispose() { sheep.dispose(); farmer.dispose(); theOneThatDies.dispose(); background.dispose(); } }
package org.labkey.googledrive; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONObject; import org.labkey.api.action.MutatingApiAction; import org.labkey.api.action.SimpleApiJsonForm; import org.labkey.api.action.SimpleViewAction; import org.labkey.api.action.SpringActionController; import org.labkey.api.module.Module; import org.labkey.api.module.ModuleLoader; import org.labkey.api.security.ActionNames; import org.labkey.api.security.RequiresPermission; import org.labkey.api.security.RequiresSiteAdmin; import org.labkey.api.security.permissions.ReadPermission; import org.labkey.api.view.JspView; import org.labkey.api.view.NavTree; import org.labkey.googledrive.api.GoogleDriveService; import org.labkey.googledrive.api.ServiceAccountForm; import org.labkey.webutils.api.action.SimpleJspPageAction; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; public class GoogleDriveController extends SpringActionController { private static final DefaultActionResolver _actionResolver = new DefaultActionResolver(GoogleDriveController.class); public static final String NAME = "googledrive"; public GoogleDriveController() { setActionResolver(_actionResolver); } @RequiresPermission(ReadPermission.class) public class BeginAction extends SimpleViewAction { public ModelAndView getView(Object o, BindException errors) throws Exception { return new JspView("/org/labkey/googledrive/view/begin.jsp"); } public NavTree appendNavTrail(NavTree root) { return root; } } public abstract class GoogleDrivePageAction extends SimpleJspPageAction { @Override public Module getModule() { return ModuleLoader.getInstance().getModule(GoogleDriveModule.class); } } @RequiresSiteAdmin() @ActionNames("RegisterAccountPage") public class AddAcountPage extends GoogleDrivePageAction { @Override public String getPathToJsp() { return "view/RegisterServiceAccount.jsp"; } @Override public String getTitle() { return "Add Account"; } } public static class RegisterServiceAccountForm extends ServiceAccountForm { public String displayName; public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } } @RequiresSiteAdmin() @ActionNames("registerAccount") public class AddAccount extends MutatingApiAction<SimpleApiJsonForm> { @Override public Object execute(SimpleApiJsonForm form, BindException errors) throws Exception { ObjectMapper mapper = new ObjectMapper(); JSONObject object = (form.getJsonObject() == null) ? new JSONObject() : form.getJsonObject(); RegisterServiceAccountForm registerForm = mapper.readValue(object.toString(), RegisterServiceAccountForm.class); String id = GoogleDriveService.get().registerServiceAccount(registerForm.getDisplayName(), registerForm, getUser()); JSONObject json = new JSONObject(); json.put("id", id); return json; } } public static class AccountForm { public String id; public String getId() { return id; } public void setId(String id) { this.id = id; } } public static class UpdateDisplayNameForm extends AccountForm { public String displayName; public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } } @RequiresSiteAdmin() @ActionNames("updateAccountDisplayName") public class UpdateAccountDisplayName extends MutatingApiAction<UpdateDisplayNameForm> { @Override public Object execute(UpdateDisplayNameForm form, BindException errors) throws Exception { GoogleDriveService.get().updateDisplayNameForAccount(form.getId(), form.getDisplayName(), getUser()); return new JSONObject(); } } @RequiresSiteAdmin() @ActionNames("deleteAccount") public class DeleteAccount extends MutatingApiAction<AccountForm> { @Override public Object execute(AccountForm form, BindException errors) throws Exception { GoogleDriveService.get().deleteAccount(form.getId(), getUser()); return new JSONObject(); } } }
package org.subethamail.smtp.command; import java.io.IOException; import org.apache.mina.filter.SSLFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subethamail.smtp.server.BaseCommand; import org.subethamail.smtp.server.ConnectionContext; import org.subethamail.smtp.server.io.DummySSLSocketFactory; /** * @author De Oliveira Edouard &lt;doe_wanted@yahoo.fr&gt; */ public class StartTLSCommand extends BaseCommand { private static Logger log = LoggerFactory.getLogger(StartTLSCommand.class); private static SSLFilter sslFilter; static { try { DummySSLSocketFactory socketFactory = new DummySSLSocketFactory(); sslFilter = new SSLFilter(socketFactory.getSSLContext()); } catch (Exception e) { e.printStackTrace(); } } public StartTLSCommand() { super("STARTTLS", "The starttls command"); } /** * Ability to override the SSLFilter * @param filter */ public static void setSSLFilter(SSLFilter filter) { if (filter == null) throw new IllegalArgumentException("filter argument can't be null"); sslFilter = filter; } @Override public void execute(String commandString, ConnectionContext context) throws IOException { if (!commandString.trim().toUpperCase().equals(this.getName())) { context.sendResponse("501 Syntax error (no parameters allowed)"); return; } try { if (sslFilter.isSSLStarted(context.getIOSession())) { context.sendResponse("454 TLS not available due to temporary reason: TLS already active"); return; } // Insert SSLFilter to get ready for handshaking context.getIOSession().getFilterChain().addFirst("SSLfilter", sslFilter); // Disable encryption temporarilly. // This attribute will be removed by SSLFilter // inside the Session.write() call below. context.getIOSession().setAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE); // Write StartTLSResponse which won't be encrypted. context.sendResponse("220 Ready to start TLS"); // Now DISABLE_ENCRYPTION_ONCE attribute is cleared. assert context.getIOSession().getAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE) == null; context.getSession().reset(); // clean state } catch (Exception e) { log.warn("startTLS() failed: " + e.getMessage(), e); } } }
package fr.ece.pfe_project.panel; import fr.ece.pfe_project.algo.Algorithm; import fr.ece.pfe_project.database.DatabaseHelper; import fr.ece.pfe_project.model.JourFerie; import fr.ece.pfe_project.tablemodel.JourFerieTableModel; import fr.ece.pfe_project.utils.ExcelUtils; import fr.ece.pfe_project.utils.ParametersUtils; import fr.ece.pfe_project.widget.ProgressDialog; import java.awt.Component; import java.awt.Font; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import javax.swing.DefaultCellEditor; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFormattedTextField; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; /** * * @author pierreghazal */ public class ParametersDialog extends javax.swing.JDialog { private final Integer DEFAULT_SEUIL_JOUR = 4000; private final Integer DEFAULT_SEUIL_CAMERA = 70; private static JDialog dialog; SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy"); public class DateRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); if (value instanceof Date) { String strDate = f.format((Date) value); this.setText(strDate); } return this; } } public class DateEditor extends DefaultCellEditor { private final JFormattedTextField textField; public DateEditor() { super(new JFormattedTextField(f)); textField = (JFormattedTextField) super.getComponent(); textField.setFont(new Font(textField.getFont().getName(), Font.PLAIN, 11)); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (value instanceof Date) { String strDate = f.format((Date) value); this.textField.setText(strDate); } return this.textField; } @Override public Object getCellEditorValue() { try { if (textField.getText().trim().length() == 0) { throw new ParseException("", 0); } java.util.Date utilDate = f.parse(textField.getText().trim()); return utilDate; } catch (ParseException e) { msgbox("Format date invalide. Format accepté : jj/mm/aaaa"); return textField.getText(); } } } /** * Creates new form ParametersDialog * * @param parent * @param modal */ public ParametersDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer(); rightRenderer.setHorizontalAlignment(SwingConstants.CENTER); this.tableFeries.getColumnModel().getColumn(0).setCellRenderer(rightRenderer); this.tableFeries.getColumnModel().getColumn(0).setMaxWidth(50); this.tableFeries.getColumnModel().getColumn(0).setMinWidth(20); this.tableFeries.getColumnModel().getColumn(2). setCellRenderer(new DateRenderer()); this.tableFeries.getColumnModel().getColumn(2). setCellEditor(new DateEditor()); initParameters(); dialog = this; } private void initParameters() { // String paramPathExcel = (String) ParametersUtils.get(ParametersUtils.PARAM_PATH_EXCEL); // if (paramPathExcel != null) { // this.textFieldPathExcel.setText(paramPathExcel); Integer seuilJour = (Integer) ParametersUtils.get(ParametersUtils.PARAM_SUEIL_JOUR); Integer seuilCamera = (Integer) ParametersUtils.get(ParametersUtils.PARAM_SUEIL_CAMERA); if (seuilJour != null) { this.spinnerSeuilJour.setValue(seuilJour); } else { this.spinnerSeuilJour.setValue(DEFAULT_SEUIL_JOUR); } if (seuilCamera != null) { this.spinnerSeuilCamera.setValue(seuilCamera); } else { this.spinnerSeuilCamera.setValue(DEFAULT_SEUIL_CAMERA); } ArrayList<JourFerie> jours = (ArrayList<JourFerie>) ParametersUtils.get(ParametersUtils.PARAM_JOURS_FERIES); if (jours != null && jours.size() > 0) { Collections.sort(jours, new Comparator<JourFerie>() { @Override public int compare(JourFerie o1, JourFerie o2) { return o1.getDate().compareTo(o2.getDate()); } }); ((JourFerieTableModel) this.tableFeries.getModel()).setData(jours, true); } } //Poppup Message public static void msgbox(String s) { JOptionPane.showMessageDialog(dialog, s, "Warning", JOptionPane.WARNING_MESSAGE); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonValider = new javax.swing.JButton(); buttonCancel = new javax.swing.JButton(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); spinnerSeuilJour = new javax.swing.JSpinner(); jLabel3 = new javax.swing.JLabel(); spinnerSeuilCamera = new javax.swing.JSpinner(); jPanel4 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tableFeries = new javax.swing.JTable(); addJourFerieButton = new javax.swing.JButton(); deleteJourFerieButton = new javax.swing.JButton(); loadJourFerie = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); textFieldPathExcel = new javax.swing.JTextField(); buttonBrowserExcel = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); exportExcelButton = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); buttonReset = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Paramètres"); setAlwaysOnTop(true); setModal(true); buttonValider.setText("OK"); buttonValider.setMaximumSize(new java.awt.Dimension(93, 29)); buttonValider.setMinimumSize(new java.awt.Dimension(93, 29)); buttonValider.setPreferredSize(new java.awt.Dimension(93, 29)); buttonValider.setSize(new java.awt.Dimension(93, 29)); buttonValider.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonValiderActionPerformed(evt); } }); buttonCancel.setText("Annuler"); buttonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonCancelActionPerformed(evt); } }); jLabel2.setText("Seuil d'alerte journalier :"); spinnerSeuilJour.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(4000), Integer.valueOf(0), null, Integer.valueOf(100))); jLabel3.setText("Seuil d'alerte par caméras :"); spinnerSeuilCamera.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(70), Integer.valueOf(0), null, Integer.valueOf(10))); jScrollPane1.setBorder(null); tableFeries.setAutoCreateRowSorter(true); tableFeries.setModel(new JourFerieTableModel()); tableFeries.setFillsViewportHeight(true); tableFeries.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); tableFeries.setShowGrid(false); tableFeries.setShowVerticalLines(true); tableFeries.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(tableFeries); addJourFerieButton.setText("+"); addJourFerieButton.setFocusable(false); addJourFerieButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addJourFerieButtonActionPerformed(evt); } }); deleteJourFerieButton.setText("-"); deleteJourFerieButton.setFocusable(false); deleteJourFerieButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteJourFerieButtonActionPerformed(evt); } }); loadJourFerie.setIcon(new javax.swing.ImageIcon(getClass().getResource("/nomoreline/img/france_icon.png"))); // NOI18N loadJourFerie.setText(" Jours Fériés"); loadJourFerie.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadJourFerieActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(addJourFerieButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deleteJourFerieButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 124, Short.MAX_VALUE) .addComponent(loadJourFerie, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(0, 98, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(addJourFerieButton) .addComponent(deleteJourFerieButton) .addComponent(loadJourFerie))) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(33, Short.MAX_VALUE))) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(spinnerSeuilJour, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE) .addComponent(spinnerSeuilCamera)))) .addContainerGap(184, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(spinnerSeuilJour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(spinnerSeuilCamera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane1.addTab("Général", jPanel1); jLabel1.setText("Chemin d'accès Excel (xls, xlsx)"); textFieldPathExcel.setFocusable(false); buttonBrowserExcel.setText("Parcourir"); buttonBrowserExcel.setFocusable(false); buttonBrowserExcel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonBrowserExcelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(textFieldPathExcel, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buttonBrowserExcel))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textFieldPathExcel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonBrowserExcel)) .addContainerGap(149, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Importation", jPanel2); exportExcelButton.setText("Exporter"); exportExcelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportExcelButtonActionPerformed(evt); } }); jLabel4.setText("Exportation des données de fréquentation :"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(exportExcelButton) .addContainerGap(137, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(exportExcelButton)) .addContainerGap(172, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Exportation", jPanel3); buttonReset.setText("Reset"); buttonReset.setMaximumSize(new java.awt.Dimension(93, 29)); buttonReset.setMinimumSize(new java.awt.Dimension(93, 29)); buttonReset.setPreferredSize(new java.awt.Dimension(93, 29)); buttonReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonResetActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(buttonReset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buttonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonValider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(buttonValider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonCancel) .addComponent(buttonReset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void buttonBrowserExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowserExcelActionPerformed final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.addChoosableFileFilter(new ExcelUtils().new ExcelFilter()); fc.setAcceptAllFileFilterUsed(false); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); if (file.exists()) { String path = file.getPath(); this.textFieldPathExcel.setText(path); } } else { } }//GEN-LAST:event_buttonBrowserExcelActionPerformed private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed this.dispose(); }//GEN-LAST:event_buttonCancelActionPerformed private void buttonValiderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonValiderActionPerformed Runnable r = new Runnable() { @Override public void run() { Boolean isSuccess = false; // Saving parameters in memory if (textFieldPathExcel.getText() != null && textFieldPathExcel.getText().length() > 0) { isSuccess = ExcelUtils.loadExcel(textFieldPathExcel.getText()); } if ((int) spinnerSeuilJour.getValue() >= 0 && (int) spinnerSeuilCamera.getValue() >= 0) { ParametersUtils.set(ParametersUtils.PARAM_SUEIL_JOUR, (int) spinnerSeuilJour.getValue()); ParametersUtils.set(ParametersUtils.PARAM_SUEIL_CAMERA, (int) spinnerSeuilCamera.getValue()); isSuccess = true; } JourFerieTableModel model = (JourFerieTableModel) tableFeries.getModel(); ParametersUtils.set(ParametersUtils.PARAM_JOURS_FERIES, (ArrayList<JourFerie>) model.getDatas()); if (isSuccess) { // Reinit textFieldPathExcel.setText(""); // Saving parameters in file parameter ParametersUtils.saveParameters(); // Dispose the parameter window dispose(); } } }; ProgressDialog progressDialog = new ProgressDialog(this, r, "Veuillez patienter..."); progressDialog.setVisible(true); }//GEN-LAST:event_buttonValiderActionPerformed private void buttonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonResetActionPerformed // REMETTRE PARAMETRE PAR DEFAUT JourFerieTableModel model = (JourFerieTableModel) this.tableFeries.getModel(); model.setData(null, true); ParametersUtils.set(ParametersUtils.PARAM_JOURS_FERIES, (ArrayList<JourFerie>) model.getDatas()); // Afficher pop-up ? this.spinnerSeuilJour.setValue(DEFAULT_SEUIL_JOUR); this.spinnerSeuilCamera.setValue(DEFAULT_SEUIL_CAMERA); ParametersUtils.set(ParametersUtils.PARAM_SUEIL_JOUR, (int) spinnerSeuilJour.getValue()); ParametersUtils.set(ParametersUtils.PARAM_SUEIL_CAMERA, (int) spinnerSeuilCamera.getValue()); // Saving parameters in file parameter ParametersUtils.saveParameters(); }//GEN-LAST:event_buttonResetActionPerformed private void addJourFerieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addJourFerieButtonActionPerformed JourFerieTableModel model = (JourFerieTableModel) this.tableFeries.getModel(); if (tableFeries.isEditing()) { tableFeries.getCellEditor().stopCellEditing(); } model.add(new JourFerie()); }//GEN-LAST:event_addJourFerieButtonActionPerformed private void deleteJourFerieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteJourFerieButtonActionPerformed JourFerieTableModel model = (JourFerieTableModel) this.tableFeries.getModel(); int index = this.tableFeries.getSelectedRow(); // Si une ligne est selectionnee if (index != -1) { if (tableFeries.isEditing()) { tableFeries.getCellEditor().stopCellEditing(); } model.removeDataAtRow(index); } }//GEN-LAST:event_deleteJourFerieButtonActionPerformed private void loadJourFerieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadJourFerieActionPerformed ArrayList<JourFerie> jours = new ArrayList<JourFerie>(); Calendar cal = Calendar.getInstance(); JourFerie paques = Algorithm.paques(cal.get(Calendar.YEAR)); jours.add(paques); jours.add(Algorithm.ascension(paques)); jours.add(Algorithm.pentecote(paques)); jours.add(Algorithm.vendrediSaint(paques)); cal.set(Calendar.MILLISECOND, 0); cal.set(cal.get(Calendar.YEAR), 7, 14, 0, 0, 0); jours.add(new JourFerie("Fête Nationale", cal.getTime())); cal.set(cal.get(Calendar.YEAR), 10, 11, 0, 0, 0); jours.add(new JourFerie("Armistice", cal.getTime())); cal.set(cal.get(Calendar.YEAR), 4, 8, 0, 0, 0); jours.add(new JourFerie("8 Mai", cal.getTime())); cal.set(cal.get(Calendar.YEAR), 7, 15, 0, 0, 0); jours.add(new JourFerie("Assomption", cal.getTime())); cal.set(cal.get(Calendar.YEAR), 10, 1, 0, 0, 0); jours.add(new JourFerie("Toussaint", cal.getTime())); cal.set(cal.get(Calendar.YEAR), 11, 25, 0, 0, 0); jours.add(new JourFerie("Noël", cal.getTime())); cal.set(cal.get(Calendar.YEAR), 11, 26, 0, 0, 0); jours.add(new JourFerie("26 Décembre", cal.getTime())); JourFerieTableModel model = (JourFerieTableModel) this.tableFeries.getModel(); if (tableFeries.isEditing()) { tableFeries.getCellEditor().stopCellEditing(); } model.setData(jours, true); }//GEN-LAST:event_loadJourFerieActionPerformed private void exportExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportExcelButtonActionPerformed final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setSelectedFile(new File("export_frequentation")); //fc.addChoosableFileFilter(new ExcelUtils().new ExcelFilter()); //fc.setAcceptAllFileFilterUsed(false); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); Runnable r = new Runnable() { @Override public void run() { if (ExcelUtils.exportExcel(file.getPath(), DatabaseHelper.getAllFrequentationJournaliere())) { } else { } dispose(); } }; ProgressDialog progressDialog = new ProgressDialog(this, r, "Exportation en cours..."); progressDialog.setVisible(true); } else { } }//GEN-LAST:event_exportExcelButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addJourFerieButton; private javax.swing.JButton buttonBrowserExcel; private javax.swing.JButton buttonCancel; private javax.swing.JButton buttonReset; private javax.swing.JButton buttonValider; private javax.swing.JButton deleteJourFerieButton; private javax.swing.JButton exportExcelButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JButton loadJourFerie; private javax.swing.JSpinner spinnerSeuilCamera; private javax.swing.JSpinner spinnerSeuilJour; private javax.swing.JTable tableFeries; private javax.swing.JTextField textFieldPathExcel; // End of variables declaration//GEN-END:variables }
package ui.graphical.window; import java.io.File; import java.awt.BorderLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import javax.swing.Timer; import ui.graphical.dialog.DialogHandler; import ui.graphical.menuItem.MenuItemActionListener; import ui.graphical.menuItem.MenuItemDelegate; import ui.graphical.menuItem.MenuItemType; import ui.graphical.tree.TreePanel; import logic.BinaryTree; /** * Class that represents the main window of the application * @author Benny Lach * */ public class MainWindow extends JFrame implements MenuItemDelegate { private static final long serialVersionUID = 2061144514357325585L; private final int WIDTH = 1440; private final int HEIGHT = 900; private BottomBar statusBar; private TreePanel treePanel; private BinaryTree tree; private Timer timer; /** * Constructor to create a main window */ public MainWindow() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Binary Tree Visualizer"); // center the frame on screen setLocationRelativeTo(null); setResizable(false); setSize(WIDTH, HEIGHT); addMenuBar(); addStatusBar(); addTreePanel(); } /** * Delegate Method called from the JMenuItem's ActionListener */ @Override public void performAction(MenuItemType type) { switch (type) { case New: newAction(); break; case NewFromFile: newFromFileAction(); break; case Save: saveAction(); break; case SaveTo: saveToAction(); break; case Quit: quitAction(); break; case AddNode: addNodeAction(); break; case DeleteNode: deleteNodeAction(); break; case DeleteAll: deleteAllAction(); break; case CheatSheet: cheatSheetAction(); break; case Documentation: documentationAction(); break; default: System.out.println("Type " + type + " is not implemented"); break; } } /** * Method to add the menu bar to the frame */ private void addMenuBar() { JMenuBar bar = new JMenuBar(); bar.add(getFileMenu()); bar.add(getEditMenu()); bar.add(getHelpMenu()); setJMenuBar(bar); } /** * Method to add a status bar on the bottom of the frame */ private void addStatusBar() { statusBar = new BottomBar(this); add(statusBar, BorderLayout.SOUTH); } /** * Method to add the tree panel to the frame */ private void addTreePanel() { treePanel = new TreePanel(getWidth(), getHeight() - 16); add(treePanel); } /** * Method to get the file sub menu for the menu bar * @return The file menu */ private JMenu getFileMenu() { // On macOS we are using CMD, on Windows people are using CTRL // Instead of InputEvent.SHIFT_MASK what always is CTRL we are using // ShortcutKeyMask to respect the different keys on macOS and Windows int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuItem newItem = new JMenuItem("New"); newItem.addActionListener(new MenuItemActionListener(MenuItemType.New, this)); // CTRL+N shortcut newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ctrl)); JMenuItem newFromFileItem = new JMenuItem("Open..."); newFromFileItem.addActionListener(new MenuItemActionListener(MenuItemType.NewFromFile, this)); // CTRL+O shortcut newFromFileItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ctrl)); JMenuItem saveItem = new JMenuItem("Save"); saveItem.addActionListener(new MenuItemActionListener(MenuItemType.Save, this)); // CTRL+S saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ctrl)); saveItem.setEnabled(false); JMenuItem saveToItem = new JMenuItem("Save to..."); saveToItem.addActionListener(new MenuItemActionListener(MenuItemType.SaveTo, this)); // SHIFT+CTRL+S saveToItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ctrl | InputEvent.SHIFT_MASK)); JMenuItem quitItem = new JMenuItem("Quit"); quitItem.addActionListener(new MenuItemActionListener(MenuItemType.Quit, this)); JMenu fileMenu = new JMenu("File"); fileMenu.add(newItem); fileMenu.add(newFromFileItem); fileMenu.addSeparator(); fileMenu.add(saveItem); fileMenu.add(saveToItem); fileMenu.addSeparator(); fileMenu.add(quitItem); return fileMenu; } /** * Method to get the edit sub menu for the menu bar * @return The edit menu */ private JMenu getEditMenu() { // On macOS we are using CMD, on Windows people are using CTRL // Instead of InputEvent.SHIFT_MASK what always is CTRL we are using // ShortcutKeyMask to respect the different keys on macOS and Windows int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuItem addItem = new JMenuItem("Add node"); addItem.addActionListener(new MenuItemActionListener(MenuItemType.AddNode, this)); // CTRL+A shortcut addItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ctrl)); JMenuItem deleteItem = new JMenuItem("Delete node"); deleteItem.addActionListener(new MenuItemActionListener(MenuItemType.DeleteNode, this)); // CTRL+D shortcut deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ctrl)); JMenuItem deleteAllItem = new JMenuItem("Delete all"); deleteAllItem.addActionListener(new MenuItemActionListener(MenuItemType.DeleteAll, this)); // SHIFT+CTRL+D shortcut deleteAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ctrl | InputEvent.SHIFT_MASK)); JMenu editMenu = new JMenu("Edit"); editMenu.add(addItem); editMenu.addSeparator(); editMenu.add(deleteItem); editMenu.add(deleteAllItem); return editMenu; } /** * Method to get the help sub menu for the menu bar * @return The help menu */ private JMenu getHelpMenu() { JMenuItem cheatSheetItem = new JMenuItem("Cheat Sheet"); cheatSheetItem.addActionListener(new MenuItemActionListener(MenuItemType.CheatSheet, this)); JMenuItem documentationItem = new JMenuItem("Documentation"); documentationItem.addActionListener(new MenuItemActionListener(MenuItemType.Documentation, this)); JMenu helpMenu = new JMenu("Help"); helpMenu.add(cheatSheetItem); helpMenu.add(documentationItem); return helpMenu; } /** * Method to handle the new action of the JMenuItem */ private void newAction() { tree = new BinaryTree(); treePanel.drawTree(tree); } /** * Method to handle the new from file action of the JMenuItem */ private void newFromFileAction() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); int result = fileChooser.showOpenDialog(this); System.out.println("File Chooser result: " + result); // TODO implement logic to init tree from file } /** * Method to handle the save action of the JMenuItem */ private void saveAction() { System.out.println("Perform Save action"); } /** * Method to handle the save to action of the JMenuItem */ private void saveToAction() { if (tree != null && tree.getRootNode() != null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { String path = fileChooser.getSelectedFile().getAbsolutePath(); if (tree.saveTreeToFile(path)) { updateStatus("Tree saved sucessfully"); } else { updateStatus("Wasn't able to save"); } } } else { updateStatus("There is nothing to save"); } } /** * Method to handle the quit action of the JMenuItem */ private void quitAction() { System.exit(0); } /** * Method to handle the add node action of the JMenuItem */ private void addNodeAction() { String nodeName = DialogHandler.showInputDialog("Enter the string you want to add"); if (nodeName != null) { if (nodeName.isEmpty() || nodeName.length() > 3) { updateStatus("The given String is not valid"); } else { if (tree == null) { tree = new BinaryTree(); } if (tree.addNode(nodeName)) { treePanel.drawTree(tree); } else { updateStatus("Node with string <" + nodeName + "> is already part of the tree"); } } } } /** * Method to handle the delete node action of the JMenuItem */ private void deleteNodeAction() { String nodeName = DialogHandler.showInputDialog("Enter the string of the node you want to delete"); if (nodeName != null) { if (nodeName.isEmpty() || nodeName.length() > 3) { updateStatus("The given String is not valid"); } else { if (tree != null) { if (tree.deleteNode(nodeName)) { treePanel.drawTree(tree); } else { updateStatus("Node with string <" + nodeName + "> not found"); } } } } else { System.out.println("User did cancel"); } } /** * Method to handle the delete all action of the JMenuItem */ private void deleteAllAction() { Boolean delete = DialogHandler.showConfirmDialog("Do you really want to delete the tree?", "Delete All"); if (delete) { // TODO Call binary tree function to delete all } } /** * Method to update the status message of the message bar * @param status The status to show */ private void updateStatus(String status) { statusBar.updateStatus(status); // remove the status after three seconds clearStatusAfterTime(3000); } /** * Method to clear the current status label of the bottom bar after a specific time * @param time The given delay in milliseconds after the status label should be cleared. */ private void clearStatusAfterTime(int time) { if (timer != null) { timer.stop(); } timer = new Timer(time, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { statusBar.updateStatus(""); } }); timer.setRepeats(false); timer.start(); } /** * Method to handle the cheat sheet action of the JMenuItem */ private void cheatSheetAction() { System.out.println("Perform Cheat Sheet action"); // TODO Add implementation } /** * Method to handle the documentation action of the JMenuItem */ private void documentationAction() { System.out.println("Perform Documentation action"); // TODO Add implementation } }
/* * $Log: IfsaFacade.java,v $ * Revision 1.45 2007-08-10 11:11:16 europe\L190409 * removed attribute 'transacted' * automatic determination of transaction state and capabilities * * Revision 1.44 2007/02/12 13:47:55 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * * Revision 1.43 2007/02/05 14:56:29 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * make isJmsTransacted() protected * * Revision 1.42 2006/11/06 08:15:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modifications for dynamic serviceId * * Revision 1.41 2006/10/13 08:08:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modify comments * * Revision 1.40 2006/08/21 15:08:03 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected javadoc * * Revision 1.39 2006/07/17 08:54:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * documented custom property ifsa.provider.useSelectors * * Revision 1.38 2006/02/09 07:59:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * restored compatibility with IFSA releases without provider selection mechanism * * Revision 1.37 2006/01/23 08:55:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * use providerSelector (when available in ifsajms) * * Revision 1.36 2005/12/28 08:47:34 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved logging * * Revision 1.35 2005/12/20 16:59:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * implemented support for connection-pooling * * Revision 1.34 2005/11/02 09:08:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * ifsa-mode connection not for single dynamic reply queue * * Revision 1.33 2005/10/26 08:23:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved logging * * Revision 1.32 2005/10/24 15:10:13 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made sessionsArePooled configurable via appConstant 'jms.sessionsArePooled' * * Revision 1.31 2005/10/18 07:04:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * better handling of dynamic reply queues * * Revision 1.30 2005/09/26 11:44:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Jms-commit only if not XA-transacted * * Revision 1.29 2005/09/13 15:48:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * changed acknowledge mode back to AutoAcknowledge * * Revision 1.28 2005/08/31 16:32:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected code for static reply queues * * Revision 1.27 2005/07/28 07:31:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * change default acknowledge mode to CLIENT * * Revision 1.26 2005/07/19 12:33:56 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * implements IXAEnabled * polishing of serviceIds, to work around problems with ':' and '/' * * Revision 1.25 2005/06/20 09:12:47 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * set sessionsArePooled false by default * * Revision 1.24 2005/06/13 15:07:58 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * avoid excessive logging in debug mode * * Revision 1.23 2005/06/13 11:59:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected version-string * * Revision 1.22 2005/06/13 11:57:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added support for pooled sessions and for XA-support * * Revision 1.21 2005/05/03 15:58:49 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * rework of shared connection code * * Revision 1.20 2005/04/26 15:17:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * rework, using IfsaApplicationConnection resulting in shared usage of connection objects * * Revision 1.19 2005/01/13 08:15:08 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made queue type IfsaQueue * * Revision 1.18 2004/08/23 13:12:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated JavaDoc * * Revision 1.17 2004/08/09 08:46:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * small changes * * Revision 1.16 2004/08/03 13:07:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved closing * * Revision 1.15 2004/07/22 13:19:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * let requestor receive IFSATimeOutMessages * * Revision 1.14 2004/07/22 11:01:04 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added configurable timeOut * * Revision 1.13 2004/07/20 16:37:47 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * toch maar niet IFSA-mode timeout * * Revision 1.12 2004/07/20 13:28:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * implemented IFSA timeout mode * * Revision 1.11 2004/07/19 13:20:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * increased logging + close connection on 'close' * * Revision 1.10 2004/07/15 07:35:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * cosmetic changes * * Revision 1.9 2004/07/08 12:55:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * logging refinements * * Revision 1.8 2004/07/08 08:56:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * show physical destination after configure * * Revision 1.7 2004/07/06 14:50:06 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * included PhysicalDestination * * Revision 1.6 2004/07/05 14:29:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * restructuring to align with IFSA naming scheme * */ package nl.nn.adapterframework.extensions.ifsa; import java.util.Map; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueReceiver; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.TextMessage; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.HasPhysicalDestination; import nl.nn.adapterframework.core.INamedObject; import nl.nn.adapterframework.core.IbisException; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.LogUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import com.ing.ifsa.IFSAConstants; import com.ing.ifsa.IFSAMessage; import com.ing.ifsa.IFSAQueue; import com.ing.ifsa.IFSAQueueSender; import com.ing.ifsa.IFSAServerQueueSender; /** * Base class for IFSA 2.0/2.2 functions. * <br/> * <p>Descenderclasses must set either Requester or Provider behaviour in their constructor.</p> * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>classname</td><td>nl.nn.adapterframework.extensions.ifsa.IfsaFacade</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the object</td><td>&nbsp;</td></tr> * <tr><td>{@link #setApplicationId(String) applicationId}</td><td>the ApplicationID, in the form of "IFSA://<i>AppId</i>"</td><td>&nbsp;</td></tr> * <tr><td>{@link #setServiceId(String) serviceId}</td><td>only for Requesters: the ServiceID, in the form of "IFSA://<i>ServiceID</i>"</td><td>&nbsp;</td></tr> * <tr><td>{@link #setMessageProtocol(String) messageProtocol}</td><td>protocol of IFSA-Service to be called. Possible values * <ul> * <li>"FF": Fire & Forget protocol</li> * <li>"RR": Request-Reply protocol</li> * </ul></td><td>&nbsp;</td></tr> * <tr><td>{@link #setTransacted(boolean) transacted}</td><td>must be set <code>true</true> for FF senders/listeners in transacted mode</td><td>false</td></tr> * <tr><td>{@link #setTimeOut(long) timeOut}</td><td>receiver timeout, in milliseconds</td><td>defined by IFSA expiry</td></tr> * </table> * * N.B. * Starting from IFSA-jms version 2.2.10.055(beta) a feature was created to have separate service-queues for Request/Reply * and for Fire & Forget services. This allows applications to provide both types of services, each in its own transaction * mode. This options is not compatible with earlier versions of IFSA-jms. If an earlier version of IFSA-jms is deployed on * the server, this behaviour must be disabled by the following setting in DeploymentSpecifics.properties: * * <code> ifsa.provider.useSelectors=false</code> * * @author Johan Verrips / Gerrit van Brakel * @since 4.2 */ public class IfsaFacade implements INamedObject, HasPhysicalDestination { public static final String version = "$RCSfile: IfsaFacade.java,v $ $Revision: 1.45 $ $Date: 2007-08-10 11:11:16 $"; protected Logger log = LogUtil.getLogger(this); private static int BASIC_ACK_MODE = Session.AUTO_ACKNOWLEDGE; private final static String USE_SELECTOR_FOR_PROVIDER_KEY="ifsa.provider.useSelectors"; private static Boolean useSelectorsStore=null; private String name; private String applicationId; private String serviceId; private String polishedServiceId=null;; private IfsaMessageProtocolEnum messageProtocol; private long timeOut = -1; // when set (>=0), overrides IFSA-expiry private IFSAQueue queue; private IfsaConnection connection=null; private boolean requestor=false; private boolean provider=false; private String providerSelector=null; private boolean notXaEnabledForSure=false; private boolean xaEnabledForSure=false; public IfsaFacade(boolean asProvider) { super(); if (asProvider) { provider=true; } else requestor=true; } protected String getLogPrefix() { String objectType; String serviceInfo=""; try { if (isRequestor()) { objectType = "IfsaRequester"; serviceInfo = "of Application ["+getApplicationId()+"] "; } else { objectType = "IfsaProvider"; serviceInfo = "for Application ["+getApplicationId()+"] "; } } catch (IfsaException e) { log.debug("Exception determining objectType in getLogPrefix",e); objectType="Object"; serviceInfo = "of Application ["+getApplicationId()+"]"; } return objectType + "["+ getName()+ "] " + serviceInfo; } /** * Checks if messageProtocol and serviceId (only for Requestors) are specified */ public void configure() throws ConfigurationException { // perform some basic checks if (StringUtils.isEmpty(getApplicationId())) throw new ConfigurationException(getLogPrefix()+"applicationId is not specified"); if (getMessageProtocolEnum() == null) throw new ConfigurationException(getLogPrefix()+ "invalid messageProtocol specified [" + getMessageProtocolEnum() + "], should be one of the following " + IfsaMessageProtocolEnum.getNames()); // TODO: check if serviceId is specified, either as attribute or as parameter try { log.debug(getLogPrefix()+"opening connection for service, to obtain info about XA awareness"); getConnection(); // obtain and cache connection, then start it. closeService(); } catch (IfsaException e) { cleanUpAfterException(); throw new ConfigurationException(e); } } protected void cleanUpAfterException() { try { closeService(); } catch (IfsaException e) { log.warn("exception closing ifsaConnection after previous exception, current:",e); } } /** * Prepares object for communication on the IFSA bus. * Obtains a connection and a serviceQueue. */ public void openService() throws IfsaException { try { log.debug(getLogPrefix()+"opening connection for service"); getConnection(); // obtain and cache connection, then start it. getServiceQueue(); // obtain and cache service queue } catch (IfsaException e) { cleanUpAfterException(); throw e; } } /** * Stops communication on the IFSA bus. * Releases references to serviceQueue and connection. */ public void closeService() throws IfsaException { try { if (connection != null) { try { connection.close(); } catch (IbisException e) { if (e instanceof IfsaException) { throw (IfsaException)e; } throw new IfsaException(e); } log.debug(getLogPrefix()+"closed connection for service"); } } finally { // make sure all objects are reset, to be able to restart after IFSA parameters have changed (e.g. at iterative installation time) queue = null; connection = null; } } /** * Looks up the <code>serviceId</code> in the <code>IFSAContext</code>.<br/> * <p>The method is knowledgable of Provider versus Requester processing. * When the request concerns a Provider <code>lookupProviderInput</code> is used, * when it concerns a Requester <code>lookupService(serviceId)</code> is used. * This method distinguishes a server-input queue and a client-input queue */ protected IFSAQueue getServiceQueue() throws IfsaException { if (queue == null) { if (isRequestor()) { if (getServiceId() != null) { queue = getConnection().lookupService(getServiceId()); if (log.isDebugEnabled()) { log.info(getLogPrefix()+ "got Queue to send messages on "+getPhysicalDestinationName()); } } } else { queue = getConnection().lookupProviderInput(); if (log.isDebugEnabled()) { log.info(getLogPrefix()+ "got Queue to receive messages from "+getPhysicalDestinationName()); } } } return queue; } protected IfsaConnection getConnection() throws IfsaException { if (connection == null) { synchronized (this) { if (connection == null) { log.debug(getLogPrefix()+"instantiating IfsaConnectionFactory"); IfsaConnectionFactory ifsaConnectionFactory = new IfsaConnectionFactory(); try { log.debug(getLogPrefix()+"creating IfsaConnection"); connection = (IfsaConnection)ifsaConnectionFactory.getConnection(getApplicationId()); if (ifsaConnectionFactory.xaCapabilityCanBeDetermined()) { if (ifsaConnectionFactory.isXaEnabled()) { xaEnabledForSure=true; notXaEnabledForSure=false; } else { xaEnabledForSure=false; notXaEnabledForSure=true; } } } catch (IbisException e) { if (e instanceof IfsaException) { throw (IfsaException)e; } throw new IfsaException(e); } } } } return connection; } /** * Create a session on the connection to the service */ protected QueueSession createSession() throws IfsaException { try { int mode = BASIC_ACK_MODE; if (isRequestor() && connection.canUseIfsaModeSessions()) { mode += IFSAConstants.QueueSession.IFSA_MODE; // let requestor receive IFSATimeOutMessages } return (QueueSession) connection.createSession(isJmsTransacted(), mode); } catch (IbisException e) { if (e instanceof IfsaException) { throw (IfsaException)e; } throw new IfsaException(e); } } protected void closeSession(Session session) { try { getConnection().releaseSession(session); } catch (IfsaException e) { log.warn("Exception releasing session", e); } } protected QueueSender createSender(QueueSession session, Queue queue) throws IfsaException { try { QueueSender queueSender = session.createSender(queue); if (log.isDebugEnabled()) { log.debug(getLogPrefix()+ "got queueSender [" + ToStringBuilder.reflectionToString((IFSAQueueSender) queueSender)+ "]"); } return queueSender; } catch (Exception e) { throw new IfsaException(e); } } protected synchronized String getProviderSelector() { if (providerSelector==null && useSelectorsForProviders()) { try { providerSelector=""; // set default, also to avoid re-evaluation time and time again for lower ifsa-versions. if (messageProtocol.equals(IfsaMessageProtocolEnum.REQUEST_REPLY)) { providerSelector=IFSAConstants.QueueReceiver.SELECTOR_RR; } if (messageProtocol.equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET)) { providerSelector=IFSAConstants.QueueReceiver.SELECTOR_FF; } } catch (Throwable t) { log.debug(getLogPrefix()+"exception determining selector, probably lower ifsa version, ignoring"); } } return providerSelector; } /** * Gets the queueReceiver, by utilizing the <code>getInputQueue()</code> method.<br/> * For serverside getQueueReceiver() the creating of the QueueReceiver is done * without the <code>selector</code> information, as this is not allowed * by IFSA.<br/> * For a clientconnection, the receiver is done with the <code>getClientReplyQueue</code> * @see javax.jms.QueueReceiver */ protected QueueReceiver getServiceReceiver( QueueSession session) throws IfsaException { try { QueueReceiver queueReceiver; if (isProvider()) { String selector = getProviderSelector(); if (StringUtils.isEmpty(selector)) { queueReceiver = session.createReceiver(getServiceQueue()); } else { //log.debug(getLogPrefix()+"using selector ["+selector+"]"); try { queueReceiver = session.createReceiver(getServiceQueue(), selector); } catch (JMSException e) { log.warn("caught exception, probably due to use of selector ["+selector+"], falling back to non-selected mode",e); queueReceiver = session.createReceiver(getServiceQueue()); } } } else { throw new IfsaException("cannot obtain ServiceReceiver: Requestor cannot act as Provider"); } if (log.isDebugEnabled() && !isSessionsArePooled()) { log.debug(getLogPrefix()+ "got receiver for queue [" + queueReceiver.getQueue().getQueueName() + "] "+ ToStringBuilder.reflectionToString(queueReceiver)); } return queueReceiver; } catch (JMSException e) { throw new IfsaException(e); } } public long getExpiry() throws IfsaException { return getExpiry((IFSAQueue) getServiceQueue()); } public long getExpiry(IFSAQueue queue) throws IfsaException { long expiry = getTimeOut(); if (expiry>=0) { return expiry; } try { return queue.getExpiry(); } catch (JMSException e) { throw new IfsaException("error retrieving timeOut value", e); } } public String getMessageProtocol() { return messageProtocol.getName(); } public IfsaMessageProtocolEnum getMessageProtocolEnum() { return messageProtocol; } /** * Gets the queueReceiver, by utilizing the <code>getInputQueue()</code> method.<br/> * For serverside getQueueReceiver() the creating of the QueueReceiver is done * without the <code>selector</code> information, as this is not allowed * by IFSA.<br/> * For a clientconnection, the receiver is done with the <code>getClientReplyQueue</code> */ public QueueReceiver getReplyReceiver(QueueSession session, Message sentMessage) throws IfsaException { if (isProvider()) { throw new IfsaException("cannot get ReplyReceiver: Provider cannot act as Requestor"); } return getConnection().getReplyReceiver(session, sentMessage); } public void closeReplyReceiver(QueueReceiver receiver) throws IfsaException { log.debug(getLogPrefix()+"closing replyreceiver"); getConnection().closeReplyReceiver(receiver); } /** * Indicates whether the object at hand represents a Client (returns <code>True</code>) or * a Server (returns <code>False</code>). */ public boolean isRequestor() throws IfsaException { if (requestor && provider) { throw new IfsaException("cannot be both Requestor and Provider"); } if (!requestor && !provider) { throw new IfsaException("not configured as Requestor or Provider"); } return requestor; } /** * Indicates whether the object at hand represents a Client (returns <code>False</code>) or * a Server (returns <code>True</code>). * * @see #isRequestor() */ public boolean isProvider() throws IfsaException { return ! isRequestor(); } /** * Sends a message,and if transacted, the queueSession is committed. * <p>This method is intended for <b>clients</b>, as <b>server</b>s * will use the <code>sendReply</code>. * @return the correlationID of the sent message */ public TextMessage sendMessage(QueueSession session, QueueSender sender, String message, Map udzMap) throws IfsaException { try { if (!isRequestor()) { throw new IfsaException(getLogPrefix()+ "Provider cannot use sendMessage, should use sendReply"); } TextMessage msg = session.createTextMessage(); msg.setText(message); if (udzMap != null && msg instanceof IFSAMessage) { // Handle UDZs log.debug(getLogPrefix()+"add UDZ map to IFSAMessage"); // process the udzMap Map udzObject = (Map)((IFSAMessage) msg).getOutgoingUDZObject(); udzObject.putAll(udzMap); } String replyToQueueName="-"; //Client side if (messageProtocol.equals(IfsaMessageProtocolEnum.REQUEST_REPLY)) { // set reply-to address Queue replyTo=getConnection().getClientReplyQueue(session); msg.setJMSReplyTo(replyTo); replyToQueueName=replyTo.getQueueName(); } if (messageProtocol.equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET)) { // not applicable } log.info(getLogPrefix() + " messageProtocol [" + messageProtocol + "] replyToQueueName [" + replyToQueueName + "] sending message [" + message + "]"); // send the message sender.send(msg); // perform commit if (isJmsTransacted() && !isXaEnabledForSure()) { session.commit(); log.debug(getLogPrefix()+ "committing (send) transaction"); } return msg; } catch (JMSException e) { throw new IfsaException(e); } } /** * Intended for server-side reponse sending and implies that the received * message *always* contains a reply-to address. */ public void sendReply(QueueSession session, Message received_message, String response) throws IfsaException { try { TextMessage answer = session.createTextMessage(); answer.setText(response); Queue replyQueue = (Queue)received_message.getJMSReplyTo(); if (log.isDebugEnabled()) { log.debug(getLogPrefix()+"obtained replyQueue ["+replyQueue.getQueueName()+"]"); } QueueSender tqs = session.createSender(replyQueue ); if (log.isDebugEnabled()) { log.debug(getLogPrefix()+ "sending reply to ["+ received_message.getJMSReplyTo()+ "]"); } ((IFSAServerQueueSender) tqs).sendReply(received_message, answer); tqs.close(); } catch (JMSException e) { throw new IfsaException(e); } } public void setMessageProtocol(String newMessageProtocol) { if (null==IfsaMessageProtocolEnum.getEnum(newMessageProtocol)) { throw new IllegalArgumentException(getLogPrefix()+ "illegal messageProtocol [" + newMessageProtocol + "] specified, it should be one of the values " + IfsaMessageProtocolEnum.getNames()); } messageProtocol = IfsaMessageProtocolEnum.getEnum(newMessageProtocol); log.debug(getLogPrefix()+"message protocol set to "+messageProtocol.getName()); } public boolean isSessionsArePooled() { try { return getConnection().sessionsArePooled(); } catch (IfsaException e) { log.error(getLogPrefix()+"could not get session",e); return false; } } protected boolean isJmsTransacted() { return getMessageProtocolEnum().equals(IfsaMessageProtocolEnum.FIRE_AND_FORGET); } public String toString() { String result = super.toString(); ToStringBuilder ts = new ToStringBuilder(this); ts.append("applicationId", applicationId); ts.append("serviceId", serviceId); if (messageProtocol != null) { ts.append("messageProtocol", messageProtocol.getName()); // ts.append("transacted", isTransacted()); ts.append("jmsTransacted", isJmsTransacted()); } else ts.append("messageProtocol", "null!"); result += ts.toString(); return result; } public String getPhysicalDestinationName() { String result = null; try { if (isRequestor()) { result = getServiceId(); } else { result = getApplicationId(); } log.debug("obtaining connection and servicequeue for "+result); if (getConnection()!=null && getServiceQueue() != null) { result += " ["+ getServiceQueue().getQueueName()+"]"; } } catch (Throwable t) { log.warn(getLogPrefix()+"got exception in getPhysicalDestinationName", t); } return result; } /** * set the IFSA service Id, for requesters only * @param newServiceId the name of the service, e.g. IFSA://SERVICE/CLAIMINFORMATIONMANAGEMENT/NLDFLT/FINDCLAIM:01 */ public void setServiceId(String newServiceId) { serviceId = newServiceId; } public String getServiceId() { if (polishedServiceId==null && serviceId!=null) { try { IfsaConnection conn = getConnection(); polishedServiceId = conn.polishServiceId(serviceId); } catch (IfsaException e) { log.warn("could not obtain connection, no polishing of serviceId",e); polishedServiceId = serviceId; } } return polishedServiceId; } public void setApplicationId(String newApplicationId) { applicationId = newApplicationId; } public String getApplicationId() { return applicationId; } protected synchronized boolean useSelectorsForProviders() { if (useSelectorsStore==null) { boolean pooled=AppConstants.getInstance().getBoolean(USE_SELECTOR_FOR_PROVIDER_KEY, true); useSelectorsStore = new Boolean(pooled); } return useSelectorsStore.booleanValue(); } public boolean isNotXaEnabledForSure() { return notXaEnabledForSure; } public boolean isXaEnabledForSure() { return xaEnabledForSure; } public void setName(String newName) { name = newName; } public String getName() { return name; } public long getTimeOut() { return timeOut; } public void setTimeOut(long timeOut) { this.timeOut = timeOut; } }
package com.essiembre.eclipse.rbe.ui.editor.i18n; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.texteditor.ITextEditor; import com.essiembre.eclipse.rbe.model.bundle.BundleEntry; import com.essiembre.eclipse.rbe.model.bundle.BundleGroup; import com.essiembre.eclipse.rbe.ui.RBEPlugin; import com.essiembre.eclipse.rbe.ui.UIUtils; import com.essiembre.eclipse.rbe.ui.editor.ResourceBundleEditor; import com.essiembre.eclipse.rbe.ui.editor.resources.ResourceManager; import com.essiembre.eclipse.rbe.ui.editor.resources.SourceEditor; import com.essiembre.eclipse.rbe.ui.preferences.RBEPreferences; /** * Represents a data entry section for a bundle entry. * @author Pascal Essiembre (essiembre@users.sourceforge.net) * @version $Author$ $Revision$ $Date$ */ public class BundleEntryComposite extends Composite { private final ResourceManager resourceManager; private final Locale locale; private final Font boldFont; private final Font smallFont; private Map imageCache = new HashMap(11); private Text textBox; private Button commentedCheckbox; private Button gotoButton; private String activeKey; private String textBeforeUpdate; /** * Constructor. */ public BundleEntryComposite( final Composite parent, final ResourceManager resourceManager, final Locale locale) { super(parent, SWT.NONE); this.resourceManager = resourceManager; this.locale = locale; this.boldFont = UIUtils.createFont(this, SWT.BOLD, 0); this.smallFont = UIUtils.createFont(SWT.NONE, -1); GridLayout gridLayout = new GridLayout(1, false); gridLayout.horizontalSpacing = 0; gridLayout.verticalSpacing = 2; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; setLayout(gridLayout); setLayoutData(new GridData(GridData.FILL_BOTH)); createLabelRow(); createTextRow(); } /** * Update bundles if the value of the active key changed. */ public void updateBundleOnChanges(){ if (activeKey != null) { BundleGroup bundleGroup = resourceManager.getBundleGroup(); BundleEntry entry = bundleGroup.getBundleEntry(locale, activeKey); boolean commentedSelected = commentedCheckbox.getSelection(); if (entry == null || !textBox.getText().equals(entry.getValue()) || entry.isCommented() != commentedSelected) { String comment = null; if (entry != null) { comment = entry.getComment(); } bundleGroup.addBundleEntry(locale, new BundleEntry( activeKey, textBox.getText(), comment, commentedSelected)); } } } /** * @see org.eclipse.swt.widgets.Widget#dispose() */ public void dispose() { super.dispose(); for (Iterator i = imageCache.values().iterator(); i.hasNext();) { ((Image) i.next()).dispose(); } imageCache.clear(); boldFont.dispose(); smallFont.dispose(); } /** * Refreshes the text field value with value matching given key. * @param key key used to grab value */ public void refresh(String key) { activeKey = key; BundleGroup bundleGroup = resourceManager.getBundleGroup(); if (key != null && bundleGroup.isKey(key)) { BundleEntry bundleEntry = bundleGroup.getBundleEntry(locale, key); SourceEditor sourceEditor = resourceManager.getSourceEditor(locale); if (bundleEntry == null) { textBox.setText(""); } else { commentedCheckbox.setSelection(bundleEntry.isCommented()); textBox.setText(bundleEntry.getValue()); } commentedCheckbox.setEnabled(!sourceEditor.isReadOnly()); textBox.setEnabled(!sourceEditor.isReadOnly()); gotoButton.setEnabled(true); } else { commentedCheckbox.setSelection(false); commentedCheckbox.setEnabled(false); textBox.setText(""); textBox.setEnabled(false); gotoButton.setEnabled(false); } resetCommented(); } /** * Creates the text field label, icon, and commented check box. */ private void createLabelRow() { Composite labelComposite = new Composite(this, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 4; gridLayout.horizontalSpacing = 0; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; labelComposite.setLayout(gridLayout); labelComposite.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); gotoButton = new Button( labelComposite, SWT.ARROW | SWT.RIGHT); gotoButton.setToolTipText( "Click to go to corresponding properties file"); gotoButton.setEnabled(false); gotoButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); Object activeEditor = editor.getSite().getPage().getActiveEditor(); if (activeEditor instanceof ResourceBundleEditor) { ((ResourceBundleEditor) activeEditor).setActivePage(locale); } } }); Label txtLabel = new Label(labelComposite, SWT.NONE); txtLabel.setText(" " + UIUtils.getDisplayName(locale) + " "); txtLabel.setFont(boldFont); GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gridData.grabExcessHorizontalSpace = true; commentedCheckbox = new Button( labelComposite, SWT.CHECK); commentedCheckbox.setText("# commented" + " ");//TODO translate commentedCheckbox.setFont(smallFont); commentedCheckbox.setLayoutData(gridData); commentedCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { resetCommented(); updateBundleOnChanges(); } }); commentedCheckbox.setEnabled(false); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; //gridData.grabExcessHorizontalSpace = true; Label imgLabel = new Label(labelComposite, SWT.NONE); imgLabel.setLayoutData(gridData); imgLabel.setImage(loadCountryIcon(locale)); } /** * Creates the text row. */ private void createTextRow() { textBox = new Text(this, SWT.MULTI | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); textBox.setEnabled(false); GridData gridData = new GridData(); gridData.verticalAlignment = GridData.FILL; gridData.grabExcessVerticalSpace = true; gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; textBox.setLayoutData(gridData); textBox.addFocusListener(new FocusListener() { public void focusGained(FocusEvent event) { textBeforeUpdate = textBox.getText(); } public void focusLost(FocusEvent event) { updateBundleOnChanges(); } }); //TODO add a preference property listener and add/remove this listener textBox.addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent event) { if (!RBEPreferences.getFieldTabInserts() && event.character == SWT.TAB) { event.doit = true; } } }); textBox.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { Text textBox = (Text) event.widget; final ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); // Text field has changed: make editor dirty if not already if (textBeforeUpdate != null && !textBeforeUpdate.equals(textBox.getText())) { // Make the editor dirty if not already. If it is, // we wait until field focus lost (or save) to // update it completely. if (!editor.isDirty()) { updateBundleOnChanges(); } // Text field is the same as original (make non-dirty) } else { if (editor.isDirty()) { getShell().getDisplay().asyncExec(new Runnable() { public void run() { editor.doRevertToSaved(); } }); } } } }); } /** * Loads country icon based on locale country. * @param locale the locale on which to grab the country * @return an image, or <code>null</code> if no match could be made */ private Image loadCountryIcon(Locale locale) { ImageDescriptor descriptor = null; String countryCode = null; if (locale != null && locale.getCountry() != null) { countryCode = locale.getCountry().toLowerCase(); } if (countryCode != null && countryCode.length() > 0) { descriptor = RBEPlugin.getImageDescriptor( "countries/" + countryCode + ".gif"); } descriptor = RBEPlugin.getImageDescriptor( "countries/blank.gif"); Image image = (Image) imageCache.get(descriptor); if (image == null) { image = descriptor.createImage(); imageCache.put(descriptor, image); } return image; } private void resetCommented() { if (commentedCheckbox.getSelection()) { commentedCheckbox.setToolTipText( "Uncheck to uncomment this entry."); textBox.setForeground( getDisplay().getSystemColor(SWT.COLOR_GRAY)); } else { commentedCheckbox.setToolTipText( "Check to comment this entry."); textBox.setForeground(null); } } }
package de.guj.ems.mobile.sdk.controllers.adserver; import java.security.MessageDigest; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import android.content.Context; import android.content.res.TypedArray; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.AttributeSet; import com.google.android.gms.ads.doubleclick.PublisherAdRequest; import com.google.android.gms.ads.doubleclick.PublisherAdRequest.Builder; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import de.guj.ems.mobile.sdk.R; import de.guj.ems.mobile.sdk.util.SdkGlobals; import de.guj.ems.mobile.sdk.util.SdkLog; import de.guj.ems.mobile.sdk.util.SdkUtil; /** * New ad view settings adapter connecting the app to * Google Doubleclick for Publishers by invoking the * Google SDK's Request Builder and defining custom criteria * * @author stein16 * */ public class DFPSettingsAdapter extends AdServerSettingsAdapter { private final static String TAG = "DFPSettingsAdapter"; private final static char STATUS_3G_ON = '3'; private final static char STATUS_4G_ON = '4'; private final static char STATUS_GPS_ON = 'g'; private final static char STATUS_PORTRAIT_MODE = 'p'; private final static char STATUS_HEADSET_CONNECTED = 'h'; private final static char STATUS_CHARGER_CONNECTED = 'c'; private final static char STATUS_WIFI_ON = 'w'; private final static char STATUS_LANDSCAPE_MODE = 'l'; private static AsyncTask<Context, Void, String> androidAdIdtask = null; private static String androidAdId = ""; private String zone; private boolean useLocation = false; private boolean noRectangle = false; private boolean noBillboard = false; private boolean noDesktopBillboard = false; private boolean noLeaderboard = false; private boolean noTwoToOne = false; public DFPSettingsAdapter() { super(); } private Map<String, String> addBatteryStatus(Map<String, String> params) { params.put(SdkGlobals.EMS_CV_BATT_LEVEL, String.valueOf(SdkUtil.getBatteryLevel())); return params; } private Map<String, String> addPhoneStatus(Map<String, String> params) { String pVals = ""; if (SdkUtil.is3G()) { pVals += STATUS_3G_ON + ","; } if (SdkUtil.is4G()) { pVals += STATUS_4G_ON + ","; } if (SdkUtil.isGPSActive()) { pVals += STATUS_GPS_ON + ","; } if (SdkUtil.isPortrait()) { pVals += STATUS_PORTRAIT_MODE + ","; } else { pVals += STATUS_LANDSCAPE_MODE + ","; } if (SdkUtil.isHeadsetConnected()) { pVals += STATUS_HEADSET_CONNECTED + ","; } if (SdkUtil.isChargerConnected()) { pVals += STATUS_CHARGER_CONNECTED + ","; } if (SdkUtil.isWifi()) { pVals += STATUS_WIFI_ON; } params.put(SdkGlobals.EMS_CV_PHONE_STAT, pVals); return params; } private Map<String, String> getCustomValues() { return addPhoneStatus(addBatteryStatus(getParams())); } /** * Acquire the preinitialized request builder for Google Ads with all custom * values that were available. Use builder.build() to finalize * * @return the Google Publisher Ad Request builder */ public Builder getGoogleRequestBuilder(int pos) { Map<String, String> customValues = getCustomValues(); Iterator<String> cvI = customValues.keySet().iterator(); Builder adRequestBuilder = new PublisherAdRequest.Builder(); while (cvI.hasNext()) { String key = cvI.next(); String val = customValues.get(key); if (!"as".equals(key) && val.indexOf(",") >= 0) { adRequestBuilder = adRequestBuilder.addCustomTargeting(key, Arrays.asList(val.split(","))); } else { adRequestBuilder = adRequestBuilder .addCustomTargeting(key, val); } SdkLog.d(TAG, hashCode() + " adding custom key value [" + key + ", " + val + "]"); } if (useLocation) { try { Location locObj = SdkUtil.getLocationObj(); adRequestBuilder = adRequestBuilder.setLocation(locObj); SdkLog.d(TAG, this + " added location [" + locObj + "]"); } catch (Exception e) { SdkLog.e(TAG, hashCode() + " problem setting request location", e); } } String adunit = SdkUtil.mapToDfp(this.zone); if (adunit != null) { String[] adc = adunit.split(","); if (pos <= 0 && adc.length > 1) { SdkLog.d(TAG, hashCode() + " adding custom key value [pos, " + adunit.split(",")[1] + "]"); adRequestBuilder = adRequestBuilder.addCustomTargeting("pos", adc[1]); } else if (pos > 0) { SdkLog.d(TAG, hashCode() + " adding custom key value [pos, " + pos + "]"); adRequestBuilder = adRequestBuilder.addCustomTargeting("pos", String.valueOf(pos)); } else { SdkLog.w(TAG, "No position value provided. The SDK cannot where in your view the ad view i.!"); } if (adc.length > 2 && adc[2].length() > 1) { SdkLog.d(TAG, hashCode() + " adding custom key value [ind, " + adc[2] + "]"); adRequestBuilder = adRequestBuilder.addCustomTargeting("ind", adc[2]); } } if (this.androidAdId != "") { adRequestBuilder = adRequestBuilder.addCustomTargeting("idfa", this.androidAdId); } return adRequestBuilder.addCustomTargeting(SdkGlobals.EMS_CV_SDV_VER, SdkUtil.VERSION_STR); } /** * Maps old adserver placement ids to Google compliant adunits * @return a comma separated string with the adunit (without network), the ad position and the index value (index page yes/no) */ public String mapToDfpAdUnit() { String adunit = SdkUtil.mapToDfp(this.zone); SdkLog.i(TAG, hashCode() + " zone " + this.zone + " maps to adUnit " + adunit); if (adunit != null && adunit.indexOf(",") >= 0) { return adunit.split(",")[0]; } return adunit; } /** * Constructor with all attributes stored in an AttributeSet * * @param context * android application context * @param set * attribute set with configuration */ @Override public void setup(Context context, AttributeSet set) { super.setup(context, set); this.getGoogleAdId(context); TypedArray tVals = context.obtainStyledAttributes(set, R.styleable.GuJEMSAdView); if (getAttrsToParams().get(SdkGlobals.EMS_ZONEID) != null) { this.zone = tVals.getString(R.styleable.GuJEMSAdView_ems_zoneId); } if (getAttrsToParams().get(SdkGlobals.EMS_GEO) != null) { if (tVals.getBoolean(R.styleable.GuJEMSAdView_ems_geo, false)) { double[] loc = SdkUtil.getLocation(); if (loc != null && 0.0 != loc[0]) { useLocation = true; putAttrToParam(SdkGlobals.EMS_CV_GPS_VELO, SdkGlobals.EMS_CV_GPS_VELO); putAttrValue(SdkGlobals.EMS_CV_GPS_VELO, String.valueOf((int) loc[2])); putAttrToParam(SdkGlobals.EMS_CV_GPS_ALT, SdkGlobals.EMS_CV_GPS_ALT); putAttrValue(SdkGlobals.EMS_CV_GPS_ALT, String.valueOf((int) loc[3])); } else { SdkLog.i(TAG, hashCode() + " location too old or not fetchable."); } } else { SdkLog.d(TAG, hashCode() + " location fetching not allowed by adspace."); } } this.noBillboard = getAttrsToParams().get(SdkGlobals.EMS_NO_BILLBOARD) != null && tVals.getBoolean(R.styleable.GuJEMSAdView_ems_noBillboard, false); this.noDesktopBillboard = getAttrsToParams().get( SdkGlobals.EMS_NO_DESKTOP_BILLBOARD) != null && tVals.getBoolean( R.styleable.GuJEMSAdView_ems_noDesktopBillboard, false); this.noTwoToOne = getAttrsToParams().get(SdkGlobals.EMS_NO_TWO_TO_ONE) != null && tVals.getBoolean(R.styleable.GuJEMSAdView_ems_noTwoToOne, false); this.noLeaderboard = getAttrsToParams().get( SdkGlobals.EMS_NO_LEADERBOARD) != null && tVals.getBoolean(R.styleable.GuJEMSAdView_ems_noLeaderboard, false); this.noRectangle = getAttrsToParams().get(SdkGlobals.EMS_NO_RECTANGLE) != null && tVals.getBoolean(R.styleable.GuJEMSAdView_ems_noRectangle, false); tVals.recycle(); } /** * Constructor with configuration in bundle * * @param context * android application context * @param savedInstance * bundle with configuration */ @Override public void setup(Context context, Bundle savedInstance) { super.setup(context, savedInstance); this.getGoogleAdId(context); if (getAttrsToParams().get(SdkGlobals.EMS_ZONEID) != null) { this.zone = savedInstance.getString(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_ZONEID); } if (getAttrsToParams().get(SdkGlobals.EMS_GEO) != null) { if (savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_GEO, false)) { double[] loc = SdkUtil.getLocation(); if (loc != null && 0.0 != loc[0]) { putAttrToParam(SdkGlobals.EMS_CV_GPS_VELO, SdkGlobals.EMS_CV_GPS_VELO); putAttrValue(SdkGlobals.EMS_CV_GPS_VELO, String.valueOf((int) loc[2])); putAttrToParam(SdkGlobals.EMS_CV_GPS_ALT, SdkGlobals.EMS_CV_GPS_ALT); putAttrValue(SdkGlobals.EMS_CV_GPS_ALT, String.valueOf((int) loc[3])); SdkLog.i(TAG, hashCode() + " using " + loc[0] + "x" + loc[1] + " as location."); } else { SdkLog.i(TAG, hashCode() + " location too old or not fetchable."); } } else { SdkLog.d(TAG, hashCode() + " location fetching not allowed by adspace."); } } this.noBillboard = getAttrsToParams().get(SdkGlobals.EMS_NO_BILLBOARD) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_BILLBOARD, false); this.noDesktopBillboard = getAttrsToParams().get( SdkGlobals.EMS_NO_DESKTOP_BILLBOARD) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_DESKTOP_BILLBOARD, false); this.noTwoToOne = getAttrsToParams().get(SdkGlobals.EMS_NO_TWO_TO_ONE) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_TWO_TO_ONE, false); this.noLeaderboard = getAttrsToParams().get( SdkGlobals.EMS_NO_LEADERBOARD) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_LEADERBOARD, false); this.noRectangle = getAttrsToParams().get(SdkGlobals.EMS_NO_RECTANGLE) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_RECTANGLE, false); } public void setEmsZoneId(String zone) { this.zone = zone; } @Override public void setup(Context context, Bundle savedInstance, String[] keywords) { super.setup(context, savedInstance); this.getGoogleAdId(context); if (getAttrsToParams().get(SdkGlobals.EMS_ZONEID) != null) { this.zone = savedInstance.getString(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_ZONEID); } if (getAttrsToParams().get(SdkGlobals.EMS_GEO) != null) { if (savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_GEO, false)) { double[] loc = SdkUtil.getLocation(); if (loc != null && 0.0 != loc[0]) { putAttrToParam(SdkGlobals.EMS_CV_GPS_VELO, SdkGlobals.EMS_CV_GPS_VELO); putAttrValue(SdkGlobals.EMS_CV_GPS_VELO, String.valueOf((int) loc[2])); putAttrToParam(SdkGlobals.EMS_CV_GPS_ALT, SdkGlobals.EMS_CV_GPS_ALT); putAttrValue(SdkGlobals.EMS_CV_GPS_ALT, String.valueOf((int) loc[3])); SdkLog.i(TAG, hashCode() + " using " + loc[0] + "x" + loc[1] + " as location."); } else { SdkLog.i(TAG, hashCode() + " location too old or not fetchable."); } } else { SdkLog.d(TAG, hashCode() + " location fetching not allowed by adspace."); } } this.noBillboard = getAttrsToParams().get(SdkGlobals.EMS_NO_BILLBOARD) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_BILLBOARD, false); this.noDesktopBillboard = getAttrsToParams().get( SdkGlobals.EMS_NO_DESKTOP_BILLBOARD) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_DESKTOP_BILLBOARD, false); this.noTwoToOne = getAttrsToParams().get(SdkGlobals.EMS_NO_TWO_TO_ONE) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_TWO_TO_ONE, false); this.noLeaderboard = getAttrsToParams().get( SdkGlobals.EMS_NO_LEADERBOARD) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_LEADERBOARD, false); this.noRectangle = getAttrsToParams().get(SdkGlobals.EMS_NO_RECTANGLE) != null && savedInstance.getBoolean(SdkGlobals.EMS_ATTRIBUTE_PREFIX + SdkGlobals.EMS_NO_RECTANGLE, false); } /** * Check whether 300x250 ads are blocked for the view with these settings * @return true if 300x250 ads are blocked */ public boolean isNoRectangle() { return noRectangle; } /** * Set whether 300x250 ads are blocked for the view with these settings * @param noRectangle set to true if 300x250 ads are blocked */ public void setNoRectangle(boolean noRectangle) { this.noRectangle = noRectangle; } /** * Check whether 1024x220 (landscape) and 768x300 (portrait) ads are blocked for the view with these settings * @return true if 1024x220 (landscape) and 768x300 (portrait) ads are blocked */ public boolean isNoBillboard() { return noBillboard; } /** * Set whether 1024x220 (landscape) and 768x300 (portrait)ads are blocked for the view with these settings * @param noBillboard set true if 1024x220 (landscape) and 768x300 (portrait) ads are blocked */ public void setNoBillboard(boolean noBillboard) { this.noBillboard = noBillboard; } /** * Check whether 800x250 ads are blocked for the view with these settings * @return true if 800x250 ads are blocked */ public boolean isNoDesktopBillboard() { return noDesktopBillboard; } /** * Set whether 800x250 ads are blocked for the view with these settings * @param noDesktopBillboard set true if 800x250 ads are blocked */ public void setNoDesktopBillboard(boolean noDesktopBillboard) { this.noDesktopBillboard = noDesktopBillboard; } /** * Check whether 728x90 and 768x90 ads are blocked for the view with these settings * @return true if 728x90 and 768x90 ads are blocked */ public boolean isNoLeaderboard() { return noLeaderboard; } /** * Set whether 728x90 and 768x90 ads are blocked for the view with these settings * @param noLeaderboard set true if 728x90 and 768x90 ads are blocked */ public void setNoLeaderboard(boolean noLeaderboard) { this.noLeaderboard = noLeaderboard; } /** * Check whether 300x150 ads are blocked for the view with these settings * @return true if 300x150 ads are blocked */ public boolean isNoTwoToOne() { return noTwoToOne; } /** * Set whether 300x150 ads are blocked for the view with these settings * @param noTwoToOne set true if 300x150 ads are blocked */ public void setNoTwoToOne(boolean noTwoToOne) { this.noTwoToOne = noTwoToOne; } private void getGoogleAdId(Context context) { if (androidAdIdtask == null) { androidAdIdtask = new AsyncTask<Context, Void, String>() { @Override protected String doInBackground(Context... params) { AdvertisingIdClient.Info idInfo = null; String advertId = null; try { idInfo = AdvertisingIdClient.getAdvertisingIdInfo(params[0]); advertId = idInfo.getId(); } catch (Exception e) { e.printStackTrace(); } return advertId; } @Override protected void onPostExecute(String advertId) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(advertId.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); for (int i=0; i<messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); androidAdId = hexString.toString(); } catch (Exception e) { e.printStackTrace(); } } }; androidAdIdtask.execute(context); } } }
package org.herac.tuxguitar.io.ptb; import java.util.Iterator; import org.herac.tuxguitar.io.ptb.base.PTBar; import org.herac.tuxguitar.io.ptb.base.PTBeat; import org.herac.tuxguitar.io.ptb.base.PTComponent; import org.herac.tuxguitar.io.ptb.base.PTGuitarIn; import org.herac.tuxguitar.io.ptb.base.PTNote; import org.herac.tuxguitar.io.ptb.base.PTPosition; import org.herac.tuxguitar.io.ptb.base.PTSection; import org.herac.tuxguitar.io.ptb.base.PTSong; import org.herac.tuxguitar.io.ptb.base.PTSongInfo; import org.herac.tuxguitar.io.ptb.base.PTTempo; import org.herac.tuxguitar.io.ptb.base.PTTrack; import org.herac.tuxguitar.io.ptb.base.PTTrackInfo; import org.herac.tuxguitar.io.ptb.helper.TrackHelper; import org.herac.tuxguitar.song.factory.TGFactory; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGBeat; import org.herac.tuxguitar.song.models.TGDuration; import org.herac.tuxguitar.song.models.TGMeasure; import org.herac.tuxguitar.song.models.TGNote; import org.herac.tuxguitar.song.models.TGSong; import org.herac.tuxguitar.song.models.TGString; import org.herac.tuxguitar.song.models.TGStroke; import org.herac.tuxguitar.song.models.TGTrack; import org.herac.tuxguitar.song.models.TGVoice; import org.herac.tuxguitar.song.models.effects.TGEffectBend; public class PTSongParser { private TGSongManager manager; private TrackHelper helper; public PTSongParser(TGFactory factory){ this.manager = new TGSongManager(factory); this.helper = new TrackHelper(); } public TGSong parseSong(PTSong src){ PTSong song = new PTSong(); PTSongSynchronizerUtil.synchronizeTracks(src, song); this.manager.setSong(this.manager.getFactory().newSong()); this.parseTrack(song.getTrack1()); this.parseTrack(song.getTrack2()); this.parseProperties(song.getInfo()); this.manager.orderBeats(); return this.manager.getSong(); } private void parseProperties(PTSongInfo info){ if( info.getName() != null ){ this.manager.getSong().setName( info.getName() ); } if( info.getAlbum() != null ){ this.manager.getSong().setAlbum( info.getAlbum() ); } if( info.getAuthor() != null ){ this.manager.getSong().setAuthor( info.getAuthor() ); } if( info.getCopyright() != null ){ this.manager.getSong().setCopyright( info.getCopyright() ); } if( info.getArrenger() != null ){ this.manager.getSong().setWriter( info.getArrenger() ); } if( info.getGuitarTranscriber() != null || info.getBassTranscriber() != null ){ String transcriber = new String(); if(info.getGuitarTranscriber() != null ){ transcriber += info.getGuitarTranscriber(); } if(info.getBassTranscriber() != null ){ if( transcriber.length() > 0 ){ transcriber += (" - "); } transcriber += info.getBassTranscriber(); } this.manager.getSong().setTranscriber( transcriber ); } if( info.getGuitarInstructions() != null || info.getBassInstructions() != null ){ String comments = new String(); if(info.getGuitarInstructions() != null ){ comments += info.getGuitarInstructions(); } if(info.getBassInstructions() != null ){ comments += info.getBassInstructions(); } this.manager.getSong().setComments( comments ); } } private void parseTrack(PTTrack track){ this.helper.reset( track.getDefaultInfo() ); long start = TGDuration.QUARTER_TIME; for( int sIndex = 0; sIndex < track.getSections().size(); sIndex ++){ PTSection section = (PTSection) track.getSections().get(sIndex); section.sort(); //calculo el siguiente start del compas this.helper.getStartHelper().init(section.getNumber(),section.getStaffs()); this.helper.getStartHelper().initVoices(start); //parseo las posiciones for( int pIndex = 0; pIndex < section.getPositions().size(); pIndex ++){ PTPosition position = (PTPosition)section.getPositions().get(pIndex); parsePosition(track,position/*,number*/); } //Calculo el start para la proxima seccion start = this.helper.getStartHelper().getMaxStart(); } } private void parsePosition(PTTrack track,PTPosition position/*,int fromTrack*/){ for(int i = 0; i < position.getComponents().size(); i ++){ PTComponent component = (PTComponent)position.getComponents().get(i); if(component instanceof PTBar){ parseBar((PTBar)component); } else if(component instanceof PTGuitarIn){ parseGuitarIn(track,(PTGuitarIn)component); } else if(component instanceof PTTempo){ parseTempo((PTTempo)component); } else if(component instanceof PTBeat){ parseBeat((PTBeat)component); } } } private void parseBar(PTBar bar){ this.helper.getStartHelper().initVoices( this.helper.getStartHelper().getMaxStart() ); if(bar.getNumerator() > 0 && bar.getDenominator() > 0 ){ this.helper.getStartHelper().setBarStart( this.helper.getStartHelper().getMaxStart() ); this.helper.getStartHelper().setBarLength((long)(bar.getNumerator() *( TGDuration.QUARTER_TIME * ( 4.0f / bar.getDenominator())))); } } private void parseGuitarIn(PTTrack track,PTGuitarIn guitarIn){ PTTrackInfo info = track.getInfo(guitarIn.getTrackInfo()); if(info != null){ // Remove used tracks after guitarIn staff. while( this.helper.getInfoHelper().countStaffTracks() > guitarIn.getStaff() ){ this.helper.getInfoHelper().removeStaffTrack( this.helper.getInfoHelper().countStaffTracks() - 1 ); } // If track was already created, but it's not in use Iterator it = this.manager.getSong().getTracks(); while( it.hasNext() ){ TGTrack tgTrack = (TGTrack )it.next(); if( hasSameInfo( tgTrack , info)){ boolean exists = false; for( int i = 0 ; i < this.helper.getInfoHelper().countStaffTracks() ; i ++ ){ TGTrack existent = this.helper.getInfoHelper().getStaffTrack(i); if(existent != null && existent.getNumber() == tgTrack.getNumber() ){ exists = true; } } if(!exists){ this.helper.getInfoHelper().addStaffTrack( tgTrack ); return; } } } // Create track if not exists. this.createTrack(info); } } private void parseTempo(PTTempo tempo){ TGMeasure measure = getMeasure(1,this.helper.getStartHelper().getMaxStart()); measure.getTempo().setValue( tempo.getTempo() ); measure.getHeader().setTripletFeel(tempo.getTripletFeel()); } private void parseBeat(PTBeat beat){ if(beat.isGrace()){ //TODO: agrear el efecto a las notas del siguiente beat return; } if( beat.getMultiBarRest() > 1){ // Multibar Rests, must allways have measure duration. long start = this.helper.getStartHelper().getBarStart(); long duration = (beat.getMultiBarRest() * this.helper.getStartHelper().getBarLength()); this.helper.getStartHelper().setVoiceStart(beat.getStaff(),beat.getVoice(),(start + duration)); return ; } long start = this.helper.getStartHelper().getVoiceStart(beat.getStaff(),beat.getVoice()); TGMeasure measure = getMeasure( getStaffTrack(beat.getStaff()) , start ); TGBeat tgBeat = getBeat(measure, start); TGVoice tgVoice = tgBeat.getVoice(beat.getVoice()); tgVoice.setEmpty(false); tgVoice.getDuration().setValue(beat.getDuration()); tgVoice.getDuration().setDotted(beat.isDotted()); tgVoice.getDuration().setDoubleDotted(beat.isDoubleDotted()); tgVoice.getDuration().getDivision().setTimes(beat.getTimes()); tgVoice.getDuration().getDivision().setEnters(beat.getEnters()); Iterator it = beat.getNotes().iterator(); while(it.hasNext()){ PTNote ptNote = (PTNote)it.next(); if( ptNote.getString() <= measure.getTrack().stringCount() && ptNote.getValue() >= 0 ){ TGNote note = this.manager.getFactory().newNote(); note.setString(ptNote.getString()); note.setValue(ptNote.getValue()); note.setTiedNote( ptNote.isTied() ); note.getEffect().setVibrato( beat.isVibrato() ); note.getEffect().setDeadNote( ptNote.isDead() ); note.getEffect().setHammer( ptNote.isHammer() ); note.getEffect().setSlide( ptNote.isSlide() ); note.getEffect().setBend( makeBend(ptNote.getBend())); tgVoice.addNote(note); } } if( beat.isArpeggioUp() ){ tgBeat.getStroke().setDirection( TGStroke.STROKE_DOWN ); tgBeat.getStroke().setValue( TGDuration.SIXTEENTH ); }else if( beat.isArpeggioDown() ){ tgBeat.getStroke().setDirection( TGStroke.STROKE_UP ); tgBeat.getStroke().setValue( TGDuration.SIXTEENTH ); } this.helper.getStartHelper().checkBeat( tgVoice.isRestVoice() ); // If it's a rest measure, duration must fill the measure. long duration = tgVoice.getDuration().getTime(); if(tgVoice.isRestVoice() && tgBeat.getStart() == this.helper.getStartHelper().getBarStart() && duration > this.helper.getStartHelper().getBarLength()){ duration = this.helper.getStartHelper().getBarLength(); } this.helper.getStartHelper().setVoiceStart(beat.getStaff(),beat.getVoice(),(tgBeat.getStart() + duration)); } private TGEffectBend makeBend(int value){ if(value >= 1 && value <= 8){ TGEffectBend bend = this.manager.getFactory().newEffectBend(); if(value == 1){ bend.addPoint(0,0); bend.addPoint(6,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(12,(TGEffectBend.SEMITONE_LENGTH * 4)); } else if(value == 2){ bend.addPoint(0,0); bend.addPoint(3,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(6,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(9,0); bend.addPoint(12,0); } else if(value == 3){ bend.addPoint(0,0); bend.addPoint(6,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(12,(TGEffectBend.SEMITONE_LENGTH * 4)); } else if(value == 4){ bend.addPoint(0,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(12,(TGEffectBend.SEMITONE_LENGTH * 4)); } else if(value == 5){ bend.addPoint(0,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(4,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(8,0); bend.addPoint(12,0); } else if(value == 6){ bend.addPoint(0,8); bend.addPoint(12,8); } else if(value == 7){ bend.addPoint(0,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(4,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(8,0); bend.addPoint(12,0); } else if(value == 8){ bend.addPoint(0,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(4,(TGEffectBend.SEMITONE_LENGTH * 4)); bend.addPoint(8,0); bend.addPoint(12,0); } return bend; } return null; } private TGMeasure getMeasure(int trackNumber,long start){ return getMeasure( getTrack(trackNumber) , start); } private TGMeasure getMeasure(TGTrack track,long start){ TGMeasure measure = null; while( (measure = this.manager.getTrackManager().getMeasureAt(track, start)) == null){ this.manager.addNewMeasureBeforeEnd(); } return measure; } private TGTrack getTrack(int number){ TGTrack track = null; while( (track = this.manager.getTrack(number)) == null){ track = createTrack(); } return track; } public TGTrack getStaffTrack(int staff){ TGTrack track = this.helper.getInfoHelper().getStaffTrack( staff ); return ( track != null ? track : createTrack() ); } private TGTrack createTrack(){ return createTrack(this.helper.getInfoHelper().getDefaultInfo()); } private TGTrack createTrack(PTTrackInfo info){ TGTrack track = this.manager.createTrack(); this.helper.getInfoHelper().addStaffTrack( track ); this.setTrackInfo(track, info ); return track; } private void setTrackInfo(TGTrack tgTrack , PTTrackInfo info){ tgTrack.setName( info.getName() ); tgTrack.getChannel().setInstrument((short) info.getInstrument() ); tgTrack.getChannel().setVolume((short) info.getVolume() ); tgTrack.getChannel().setBalance((short) info.getBalance() ); tgTrack.getStrings().clear(); for(int i = 0; i < info.getStrings().length; i ++){ TGString string = this.manager.getFactory().newString(); string.setNumber( (i + 1) ); string.setValue( info.getStrings()[i] ); tgTrack.getStrings().add(string); } } private boolean hasSameInfo(TGTrack track , PTTrackInfo info){ if( !info.getName().equals( track.getName() ) ){ return false; } if( info.getInstrument() != track.getChannel().getInstrument() ){ return false; } if( info.getVolume() != track.getChannel().getVolume() ){ return false; } if( info.getBalance() != track.getChannel().getBalance() ){ return false; } if( info.getStrings().length != track.stringCount() ){ return false; } for(int i = 0; i < info.getStrings().length; i ++){ if( info.getStrings()[i] != track.getString( (i + 1) ).getValue() ){ return false; } } return true; } private TGBeat getBeat(TGMeasure measure, long start){ int count = measure.countBeats(); for(int i = 0 ; i < count ; i ++ ){ TGBeat beat = measure.getBeat( i ); if( beat.getStart() == start ){ return beat; } } TGBeat beat = this.manager.getFactory().newBeat(); beat.setStart(start); measure.addBeat(beat); return beat; } } /* class TGSongAdjuster{ protected TGSongManager manager; public TGSongAdjuster(TGSongManager manager){ this.manager = manager; } public TGSong process(){ Iterator tracks = this.manager.getSong().getTracks(); while(tracks.hasNext()){ TGTrack track = (TGTrack)tracks.next(); Iterator measures = track.getMeasures(); while(measures.hasNext()){ TGMeasure measure = (TGMeasure)measures.next(); this.process(measure); } } return this.manager.getSong(); } public void process(TGMeasure measure){ this.manager.getMeasureManager().orderBeats(measure); joinBeats(measure); } public void joinBeats(TGMeasure measure){ TGBeat previous = null; boolean finish = true; long measureStart = measure.getStart(); long measureEnd = (measureStart + measure.getLength()); for(int i = 0;i < measure.countBeats();i++){ TGBeat beat = measure.getBeat( i ); long beatStart = beat.getStart(); long beatLength = beat.getDuration().getTime(); if(previous != null){ long previousStart = previous.getStart(); long previousLength = previous.getDuration().getTime(); if(previousStart == beatStart){ // add beat notes to previous for(int n = 0;n < beat.countNotes();n++){ TGNote note = beat.getNote( n ); previous.addNote( note ); } // add beat chord to previous if(!previous.isChordBeat() && beat.isChordBeat()){ previous.setChord( beat.getChord() ); } // add beat text to previous if(!previous.isTextBeat() && beat.isTextBeat()){ previous.setText( beat.getText() ); } // set the best duration if(beatLength > previousLength && (beatStart + beatLength) <= measureEnd){ beat.getDuration().copy(previous.getDuration()); } measure.removeBeat(beat); finish = false; break; } else if(previousStart < beatStart && (previousStart + previousLength) > beatStart){ if(beat.isRestBeat()){ measure.removeBeat(beat); finish = false; break; } TGDuration duration = TGDuration.fromTime(this.manager.getFactory(), (beatStart - previousStart) ); duration.copy( previous.getDuration() ); } } if( (beatStart + beatLength) > measureEnd ){ if(beat.isRestBeat()){ measure.removeBeat(beat); finish = false; break; } TGDuration duration = TGDuration.fromTime(this.manager.getFactory(), (measureEnd - beatStart) ); duration.copy( beat.getDuration() ); } previous = beat; } if(!finish){ joinBeats(measure); } } } */
package alma.acs.util; /** * Normalizes XML data by escaping special characters such as '&' or ' <'. * * @author hsommer created Jul 25, 2003 10:14:34 AM */ public class XmlNormalizer { /** * Normalizes a string to not conflict with XML markup characters. * Only allocates memory if the string <code>s</code> does contain such markup. * Otherwise <code>s</code> is returned. */ private static String normalize(String s, boolean normalizeXMLEmbeddedTextOnly) { if (s == null) return s; StringBuffer str = null; int begin = 0; boolean currentlyInsideText = false; boolean currentlyInsideCharacterContent = false; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); String trans = null; if (normalizeXMLEmbeddedTextOnly && !currentlyInsideText) { if (ch == '<') { currentlyInsideCharacterContent = false; continue; } else if (ch == '>') { currentlyInsideCharacterContent = true; continue; } } if (ch == '\"') { currentlyInsideText = !currentlyInsideText; // don't translate the quote char if we expect entire XML including valid markup if (!normalizeXMLEmbeddedTextOnly) { trans = translate(ch); } } else if (!normalizeXMLEmbeddedTextOnly || currentlyInsideText || currentlyInsideCharacterContent) { trans = translate(ch); } if (trans != null) { // we found a special char if (str == null) { // memory allocation only if character escapes are necessary str = new StringBuffer(s.length() + 16); } // copy all chars from the last special char to the current special char at once -- // hopefully with slightly better performance than 1 char at a time str.append(s.substring(begin, i)).append(trans); begin = i + 1; } } if (str != null) { str.append(s.substring(begin)); return str.toString(); } // nothing had to be translated return s; } /** * Normalizes a string to not conflict with XML markup characters. * Only allocates memory if the string <code>s</code> does contain such markup. * Otherwise <code>s</code> is returned. */ public static String normalize(String s) { return normalize(s, false); } public static String normalizeXMLEmbeddedTextOnly(String xmlString) { return normalize(xmlString, true); } /** * Translates the given character <code>ch</code> to its masked XML representation * if this character is one of { &lt;, &gt;, &amp;, ", ' }. * Otherwise returns <code>null</code>. * @param ch * @return The corresponding XML representation such as "&amp;lt;" for a '&lt;'. */ public static String translate(char ch) { switch (ch) { case '<': return "&lt;"; case '>': return "&gt;"; case '&': return "&amp;"; case '"': return "&quot;"; case '\'': return "&apos;"; default: return null; } } }
package dr.evomodel.treedatalikelihood.discrete; import dr.inference.hmc.GradientWrtParameterProvider; import dr.inference.model.Likelihood; import dr.inference.model.Parameter; import dr.math.MultivariateFunction; import dr.math.NumericalDerivative; import dr.math.matrixAlgebra.WrappedVector; import dr.util.Transform; import dr.xml.Reportable; import com.github.lbfgs4j.liblbfgs.Lbfgs; import com.github.lbfgs4j.LbfgsMinimizer; import com.github.lbfgs4j.liblbfgs.Function; import com.github.lbfgs4j.liblbfgs.LbfgsConstant.LBFGS_Param; import static dr.math.matrixAlgebra.ReadableVector.Utils.setParameter; /** * @author Marc A. Suchard * @author Xiang Ji */ public class MaximizerWrtParameter implements Reportable { private final GradientWrtParameterProvider gradient; private final GradientType gradientType; private final Parameter parameter; private final Likelihood likelihood; private final Transform transform; private final Function function; private final Settings settings; private long time = 0; private long count = 0; private double minimumValue = Double.NaN; private double[] minimumPoint = null; public static class Settings { int numberIterations; boolean startAtCurrentState; boolean printToScreen; public Settings(int numberIterations, boolean startAtCurrentState, boolean printToScreen) { this.numberIterations = numberIterations; this.startAtCurrentState = startAtCurrentState; this.printToScreen = printToScreen; } } public MaximizerWrtParameter(Likelihood likelihood, Parameter parameter, GradientWrtParameterProvider gradient, Transform transform, Settings settings) { this.likelihood = likelihood; this.parameter = parameter; this.transform = transform; if (gradient == null) { this.gradient = constructGradient(); this.gradientType = GradientType.NUMERICAL; } else { this.gradient = gradient; this.gradientType = GradientType.ANALYTIC; } this.function = constructFunction(); this.settings = settings; } public void maximize() { LBFGS_Param paramsBFGS = Lbfgs.defaultParams(); if (settings.numberIterations > 0) { paramsBFGS.max_iterations = settings.numberIterations; } LbfgsMinimizer minimizer = new LbfgsMinimizer(paramsBFGS, settings.printToScreen); double[] x0 = null; if (settings.startAtCurrentState) { x0 = parameter.getParameterValues(); if (transform != null) { x0 = transform.transform(x0, 0, x0.length); } // PB: I don't think that this is needed. XJ: bug fixed, should be transform instead of inverse, sorry. // if (transform != null) { // x0 = transform.inverse(x0, 0, x0.length); } long startTime = System.currentTimeMillis(); minimumPoint = minimizer.minimize(function, x0); long endTime = System.currentTimeMillis(); time += endTime - startTime; minimumValue = function.valueAt(minimumPoint); setParameter(new WrappedVector.Raw(minimumPoint), parameter); } @Override public String getReport() { StringBuilder sb = new StringBuilder(); if (function == null) { sb.append("Not yet executed."); } else { if (transform != null) { sb.append("Gradient is taken with respect to the transformed paramter values.\n"); sb.append("Untransformed X: ").append(new dr.math.matrixAlgebra.Vector(transform.inverse(minimumPoint, 0, minimumPoint.length))).append("\n"); } sb.append("X: ").append(new dr.math.matrixAlgebra.Vector(minimumPoint)).append("\n"); sb.append("Gradient: ").append(new dr.math.matrixAlgebra.Vector(function.gradientAt(minimumPoint))).append("\n"); sb.append("Gradient type: ").append(gradientType).append("\n"); sb.append("Fx: ").append(minimumValue).append("\n"); sb.append("Time: ").append(time).append("\n"); sb.append("Count: ").append(count).append("\n"); } return sb.toString(); } private double evaluateLogLikelihood() { ++count; return likelihood.getLogLikelihood(); } private Function constructFunction() { return new Function() { @Override public int getDimension() { return gradient.getDimension(); } @Override public double valueAt(double[] argument) { if (transform != null) { argument = transform.inverse(argument, 0, argument.length); } setParameter(new WrappedVector.Raw(argument), parameter); return -evaluateLogLikelihood(); } @Override public double[] gradientAt(double[] argument) { if (transform != null) { argument = transform.inverse(argument, 0, argument.length); } setParameter(new WrappedVector.Raw(argument), parameter); double[] result = gradient.getGradientLogDensity(); if (transform != null) { result = transform.updateGradientUnWeightedLogDensity(result, argument, 0, argument.length); } for (int i = 0; i < result.length; ++i) { result[i] = -result[i]; } return result; } }; } private GradientWrtParameterProvider constructGradient() { final MultivariateFunction function = new MultivariateFunction() { @Override public double evaluate(double[] argument) { setParameter(new WrappedVector.Raw(argument), parameter); return evaluateLogLikelihood(); } @Override public int getNumArguments() { return parameter.getDimension(); } @Override public double getLowerBound(int n) { return Double.NEGATIVE_INFINITY; } @Override public double getUpperBound(int n) { return Double.POSITIVE_INFINITY; } }; return new GradientWrtParameterProvider() { @Override public Likelihood getLikelihood() { return likelihood; } @Override public Parameter getParameter() { return parameter; } @Override public int getDimension() { return parameter.getDimension(); } @Override public double[] getGradientLogDensity() { return NumericalDerivative.gradient(function, parameter.getParameterValues()); } }; } private enum GradientType { ANALYTIC("analytic"), NUMERICAL("numerical"); private String type; GradientType(String type) { this.type = type; } public String toString() { return type; } } }
package org.jivesoftware.smackx; import java.util.Iterator; /** * * A listener that is fired anytime a roster exchange is received. * * @author Gaston Dombiak */ public interface RosterExchangeListener { /** * Called when roster entries are received as part of a roster exchange. * * @param from the user that sent the entries. * @param remoteRosterEntries the entries sent by the user. The entries are instances of * RemoteRosterEntry. */ public void entriesReceived(String from, Iterator remoteRosterEntries); }
package edu.wustl.catissuecore.action; import java.io.IOException; import java.sql.Connection; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dhtmlx.connector.ConnectorServlet; import com.dhtmlx.connector.DBType; import com.dhtmlx.connector.GridConnector; import edu.wustl.catissuecore.gridImpl.AbstractGridImpl; import edu.wustl.catissuecore.gridImpl.GridSpecimenImpl; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.util.global.CommonServiceLocator; import edu.wustl.dao.daofactory.DAOConfigFactory; import edu.wustl.dao.daofactory.IDAOFactory; import edu.wustl.dao.exception.DAOException; public class LoadGridServlet extends ConnectorServlet { private String pageOf; private String aliasName; private SessionDataBean sessionDataBean; public String getPageOf() { return pageOf; } public void setPageOf(String pageOf) { this.pageOf = pageOf; } public String getAliasName() { return aliasName; } public void setAliasName(String aliasName) { this.aliasName = aliasName; } public SessionDataBean getSessionDataBean() { return sessionDataBean; } public void setSessionDataBean(SessionDataBean sessionDataBean) { this.sessionDataBean = sessionDataBean; } @Override protected void configure() { AbstractGridImpl gridImplObj = null; Connection conn = null; String appName = CommonServiceLocator.getInstance().getAppName(); IDAOFactory daoFactory = DAOConfigFactory.getInstance().getDAOFactory(appName); try { gridImplObj =(AbstractGridImpl) Class.forName(GridSpecimenImpl.class.getName()).newInstance(); conn = daoFactory.getConnection(); GridConnector connector = null; if (Constants.ORACLE_DATABASE.equals(DAOConfigFactory.getInstance().getDAOFactory( Constants.APPLICATION_NAME).getDataBaseType())){ connector = new GridConnector(conn, DBType.Oracle); }else if(Constants.MYSQL_DATABASE.equals(DAOConfigFactory.getInstance() .getDAOFactory(Constants.APPLICATION_NAME).getDataBaseType())){ connector = new GridConnector(conn, DBType.MySQL); } connector.event.attach(gridImplObj); String sql = gridImplObj.getGridQuery(aliasName,getSessionDataBean()); String tableColString =gridImplObj.getTableColumnString(); connector.dynamic_loading(true); connector.dynamic_loading(Integer.MAX_VALUE); connector.render_sql(sql, gridImplObj.getTableColumnString(), tableColString); } catch (Exception e) { e.printStackTrace(); } finally { try { if(conn != null) { daoFactory.closeConnection(conn); } } catch (DAOException e) { // Logger.getLogger(LoadGridServlet.class).error(e.getMessage(), e); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { setAliasName(req.getParameter("reqParam")); setPageOf(req.getParameter("pageOf")); setSessionDataBean((SessionDataBean)req.getSession().getAttribute(Constants.SESSION_DATA)); super.doGet(req, res); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doGet(req, res); } }
package org.bonej.plugins; import java.awt.AWTEvent; import java.awt.Checkbox; import java.awt.Choice; import java.awt.Color; import java.awt.TextField; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bonej.geometry.Ellipsoid; import org.bonej.geometry.FitEllipsoid; import org.bonej.geometry.Vectors; import org.bonej.menuWrappers.LocalThickness; import org.bonej.util.DialogModifier; import org.bonej.util.ImageCheck; import org.scijava.vecmath.Color3f; import org.scijava.vecmath.Point3f; import Jama.EigenvalueDecomposition; import Jama.Matrix; import customnode.CustomPointMesh; import customnode.CustomTriangleMesh; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.gui.DialogListener; import ij.gui.GenericDialog; import ij.measure.Calibration; import ij.measure.ResultsTable; import ij.plugin.PlugIn; import ij.process.ByteProcessor; import ij.process.ImageProcessor; import ij3d.Image3DUniverse; import marchingcubes.MCTriangulator; public class ParticleCounter implements PlugIn, DialogListener { /** Foreground value */ static final int FORE = -1; /** Background value */ static final int BACK = 0; /** Surface colour style */ private static final int GRADIENT = 0; private static final int SPLIT = 1; private static final int ORIENTATION = 2; private String sPhase = ""; private String chunkString = ""; private JOINING labelMethod = JOINING.MAPPED; @Override public boolean dialogItemChanged(final GenericDialog gd, final AWTEvent e) { if (DialogModifier.hasInvalidNumber(gd.getNumericFields())) return false; final List<?> choices = gd.getChoices(); final List<?> checkboxes = gd.getCheckboxes(); final List<?> numbers = gd.getNumericFields(); // link algorithm choice to chunk size field final Choice choice = (Choice) choices.get(1); final TextField num = (TextField) numbers.get(5); num.setEnabled(choice.getSelectedItem().contentEquals("Multithreaded")); // link moments and ellipsoid choice to unit vector choice final Checkbox momBox = (Checkbox) checkboxes.get(4); final Checkbox elBox = (Checkbox) checkboxes.get(8); final Checkbox vvvBox = (Checkbox) checkboxes.get(9); vvvBox.setEnabled(elBox.getState() || momBox.getState()); // link show stack 3d to volume resampling final Checkbox box = (Checkbox) checkboxes.get(17); final TextField numb = (TextField) numbers.get(4); numb.setEnabled(box.getState()); // link show surfaces, gradient choice and split value final Checkbox surfbox = (Checkbox) checkboxes.get(13); final Choice col = (Choice) choices.get(0); final TextField split = (TextField) numbers.get(3); col.setEnabled(surfbox.getState()); split.setEnabled(surfbox.getState() && col.getSelectedIndex() == 1); DialogModifier.registerMacroValues(gd, gd.getComponents()); return true; } @Override public void run(final String arg) { final ImagePlus imp = IJ.getImage(); if (null == imp) { IJ.noImage(); return; } if (!ImageCheck.isBinary(imp)) { IJ.error("Binary image required"); return; } final Calibration cal = imp.getCalibration(); final String units = cal.getUnits(); final GenericDialog gd = new GenericDialog("Setup"); final String[] headers = { "Measurement Options", " " }; final String[] labels = new String[10]; final boolean[] defaultValues = new boolean[10]; labels[0] = "Exclude on sides"; defaultValues[0] = false; labels[1] = "Surface_area"; defaultValues[1] = true; labels[2] = "Feret diameter"; defaultValues[2] = false; labels[3] = "Enclosed_volume"; defaultValues[3] = true; labels[4] = "Moments of inertia"; defaultValues[4] = true; labels[5] = "Euler characteristic"; defaultValues[5] = true; labels[6] = "Thickness"; defaultValues[6] = true; labels[7] = "Mask thickness map"; defaultValues[7] = false; labels[8] = "Ellipsoids"; defaultValues[8] = true; labels[9] = "Record unit vectors"; defaultValues[9] = false; gd.addCheckboxGroup(5, 2, labels, defaultValues, headers); gd.addNumericField("Min Volume", 0, 3, 7, units + "³"); gd.addNumericField("Max Volume", Double.POSITIVE_INFINITY, 3, 7, units + "³"); gd.addNumericField("Surface_resampling", 2, 0); final String[] headers2 = { "Graphical Results", " " }; final String[] labels2 = new String[9]; final boolean[] defaultValues2 = new boolean[9]; labels2[0] = "Show_particle stack"; defaultValues2[0] = true; labels2[1] = "Show_size stack"; defaultValues2[1] = false; labels2[2] = "Show_thickness stack"; defaultValues2[2] = false; labels2[3] = "Show_surfaces (3D)"; defaultValues2[3] = true; labels2[4] = "Show_centroids (3D)"; defaultValues2[4] = true; labels2[5] = "Show_axes (3D)"; defaultValues2[5] = true; labels2[6] = "Show_ellipsoids (3D)"; defaultValues2[6] = true; labels2[7] = "Show_stack (3D)"; defaultValues2[7] = true; labels2[8] = "Draw_ellipsoids"; defaultValues2[8] = false; gd.addCheckboxGroup(5, 2, labels2, defaultValues2, headers2); final String[] items = { "Gradient", "Split", "Orientation"}; gd.addChoice("Surface colours", items, items[0]); gd.addNumericField("Split value", 0, 3, 7, units + "³"); gd.addNumericField("Volume_resampling", 2, 0); final String[] items2 = { "Multithreaded", "Linear", "Mapped" }; gd.addChoice("Labelling algorithm", items2, items2[2]); gd.addNumericField("Slices per chunk", 2, 0); gd.addDialogListener(this); gd.showDialog(); if (gd.wasCanceled()) { return; } final double minVol = gd.getNextNumber(); final double maxVol = gd.getNextNumber(); final boolean doExclude = gd.getNextBoolean(); final boolean doSurfaceArea = gd.getNextBoolean(); final boolean doFeret = gd.getNextBoolean(); final boolean doSurfaceVolume = gd.getNextBoolean(); final int resampling = (int) Math.floor(gd.getNextNumber()); final boolean doMoments = gd.getNextBoolean(); final boolean doEulerCharacters = gd.getNextBoolean(); final boolean doThickness = gd.getNextBoolean(); final boolean doMask = gd.getNextBoolean(); final boolean doEllipsoids = gd.getNextBoolean(); final boolean doVerboseUnitVectors = gd.getNextBoolean(); final boolean doParticleImage = gd.getNextBoolean(); final boolean doParticleSizeImage = gd.getNextBoolean(); final boolean doThickImage = gd.getNextBoolean(); final boolean doSurfaceImage = gd.getNextBoolean(); final int colourMode = gd.getNextChoiceIndex(); final double splitValue = gd.getNextNumber(); final boolean doCentroidImage = gd.getNextBoolean(); final boolean doAxesImage = gd.getNextBoolean(); final boolean doEllipsoidImage = gd.getNextBoolean(); final boolean do3DOriginal = gd.getNextBoolean(); final boolean doEllipsoidStack = gd.getNextBoolean(); final int origResampling = (int) Math.floor(gd.getNextNumber()); final String choice = gd.getNextChoice(); if (choice.equals(items2[0])) labelMethod = JOINING.MULTI; else if (choice.equals(items2[1])) labelMethod = JOINING.LINEAR; else labelMethod = JOINING.MAPPED; final int slicesPerChunk = (int) Math.floor(gd.getNextNumber()); // get the particles and do the analysis final long start = System.nanoTime(); final Object[] result = getParticles(imp, slicesPerChunk, minVol, maxVol, FORE, doExclude); // calculate particle labelling time in ms final long time = (System.nanoTime() - start) / 1000000; IJ.log("Particle labelling finished in " + time + " ms"); final int[][] particleLabels = (int[][]) result[1]; final long[] particleSizes = getParticleSizes(particleLabels); final int nParticles = particleSizes.length; final double[] volumes = getVolumes(imp, particleSizes); final double[][] centroids = getCentroids(imp, particleLabels, particleSizes); final int[][] limits = getParticleLimits(imp, particleLabels, nParticles); // set up resources for analysis ArrayList<List<Point3f>> surfacePoints = new ArrayList<>(); if (doSurfaceArea || doSurfaceVolume || doSurfaceImage || doEllipsoids || doFeret || doEllipsoidStack) { surfacePoints = getSurfacePoints(imp, particleLabels, limits, resampling, nParticles); } EigenvalueDecomposition[] eigens = new EigenvalueDecomposition[nParticles]; if (doMoments || doAxesImage || colourMode == ORIENTATION) { eigens = getEigens(imp, particleLabels, centroids); } // calculate dimensions double[] surfaceAreas = new double[nParticles]; if (doSurfaceArea) { surfaceAreas = getSurfaceAreas(surfacePoints); } double[] ferets = new double[nParticles]; if (doFeret) { ferets = getFerets(surfacePoints); } double[] surfaceVolumes = new double[nParticles]; if (doSurfaceVolume) { surfaceVolumes = getSurfaceVolume(surfacePoints); } double[][] eulerCharacters = new double[nParticles][3]; if (doEulerCharacters) { eulerCharacters = getEulerCharacter(imp, particleLabels, limits, nParticles); } double[][] thick = new double[nParticles][2]; if (doThickness) { final LocalThickness th = new LocalThickness(); final ImagePlus thickImp = th.getLocalThickness(imp, false, doMask); thick = getMeanStdDev(thickImp, particleLabels, particleSizes); if (doThickImage) { double max = 0; for (int i = 1; i < nParticles; i++) { max = Math.max(max, thick[i][2]); } thickImp.getProcessor().setMinAndMax(0, max); thickImp.setTitle(imp.getShortTitle() + "_thickness"); thickImp.show(); thickImp.setSlice(1); IJ.run("Fire"); } } Object[][] ellipsoids = new Object[nParticles][10]; if (doEllipsoids || doEllipsoidImage || doEllipsoidStack) { ellipsoids = getEllipsoids(surfacePoints); } // Show numerical results final ResultsTable rt = new ResultsTable(); for (int i = 1; i < volumes.length; i++) { if (volumes[i] > 0) { rt.incrementCounter(); rt.addLabel(imp.getTitle()); rt.addValue("ID", i); rt.addValue("Vol. (" + units + "³)", volumes[i]); rt.addValue("x Cent (" + units + ")", centroids[i][0]); rt.addValue("y Cent (" + units + ")", centroids[i][1]); rt.addValue("z Cent (" + units + ")", centroids[i][2]); if (doSurfaceArea) { rt.addValue("SA (" + units + "²)", surfaceAreas[i]); } if (doFeret) { rt.addValue("Feret (" + units + ")", ferets[i]); } if (doSurfaceVolume) { rt.addValue("Encl. Vol. (" + units + "³)", surfaceVolumes[i]); } if (doMoments) { final EigenvalueDecomposition E = eigens[i]; rt.addValue("I1", E.getD().get(2, 2)); rt.addValue("I2", E.getD().get(1, 1)); rt.addValue("I3", E.getD().get(0, 0)); rt.addValue("vX", E.getV().get(0, 0)); rt.addValue("vY", E.getV().get(1, 0)); rt.addValue("vZ", E.getV().get(2, 0)); if (doVerboseUnitVectors) { rt.addValue("vX1", E.getV().get(0, 1)); rt.addValue("vY1", E.getV().get(1, 1)); rt.addValue("vZ1", E.getV().get(2, 1)); rt.addValue("vX2", E.getV().get(0, 2)); rt.addValue("vY2", E.getV().get(1, 2)); rt.addValue("vZ2", E.getV().get(2, 2)); } } if (doEulerCharacters) { rt.addValue("Euler (χ)", eulerCharacters[i][0]); rt.addValue("Holes (β1)", eulerCharacters[i][1]); rt.addValue("Cavities (β2)", eulerCharacters[i][2]); } if (doThickness) { rt.addValue("Thickness (" + units + ")", thick[i][0]); rt.addValue("SD Thickness (" + units + ")", thick[i][1]); rt.addValue("Max Thickness (" + units + ")", thick[i][2]); } if (doEllipsoids) { final double[] rad; final double[][] unitV; if (ellipsoids[i] == null) { rad = new double[] { Double.NaN, Double.NaN, Double.NaN }; unitV = new double[][] { { Double.NaN, Double.NaN, Double.NaN }, { Double.NaN, Double.NaN, Double.NaN }, { Double.NaN, Double.NaN, Double.NaN } }; } else { final Object[] el = ellipsoids[i]; rad = (double[]) el[1]; unitV = (double[][]) el[2]; } rt.addValue("Major radius (" + units + ")", rad[0]); rt.addValue("Int. radius (" + units + ")", rad[1]); rt.addValue("Minor radius (" + units + ")", rad[2]); if (doVerboseUnitVectors) { rt.addValue("V00", unitV[0][0]); rt.addValue("V01", unitV[0][1]); rt.addValue("V02", unitV[0][2]); rt.addValue("V10", unitV[1][0]); rt.addValue("V11", unitV[1][1]); rt.addValue("V12", unitV[1][2]); rt.addValue("V20", unitV[2][0]); rt.addValue("V21", unitV[2][1]); rt.addValue("V22", unitV[2][2]); } } rt.updateResults(); } } rt.show("Results"); // Show resulting image stacks if (doParticleImage) { displayParticleLabels(particleLabels, imp).show(); IJ.run("Fire"); } if (doParticleSizeImage) { displayParticleValues(imp, particleLabels, volumes).show(); IJ.run("Fire"); } if (doEllipsoidStack) { displayParticleEllipsoids(imp, ellipsoids, "Ellipsoids").show(); } // show 3D renderings if (doSurfaceImage || doCentroidImage || doAxesImage || do3DOriginal || doEllipsoidImage) { final Image3DUniverse univ = new Image3DUniverse(); if (doSurfaceImage) { displayParticleSurfaces(univ, surfacePoints, colourMode, volumes, splitValue, eigens); } if (doCentroidImage) { displayCentroids(centroids, univ); } if (doAxesImage) { displayPrincipalAxes(univ, eigens, centroids, particleSizes); } if (doEllipsoidImage) { displayEllipsoids(ellipsoids, univ); } if (do3DOriginal) { display3DOriginal(imp, origResampling, univ); } univ.show(); } IJ.showProgress(1.0); IJ.showStatus("Particle Analysis Complete"); UsageReporter.reportEvent(this).send(); } /** * Add all the neighbouring labels of a pixel to the map, except 0 * (background) and the pixel's own label, which is already in the map. The * LUT gets updated with the minimum neighbour found, but this is only within * the first neighbours and not the minimum label in the pixel's neighbour * network * * @param map a map of LUT values. * @param nbh a neighbourhood in the image. * @param centre current pixel's label */ private static void addNeighboursToMap(final List<HashSet<Integer>> map, final int[] nbh, final int centre) { final HashSet<Integer> set = map.get(centre); Arrays.stream(nbh).filter(n -> n > 0).forEach(set::add); } private static void applyLUT(final int[][] particleLabels, final int[] lut, final int w, final int h, final int d) { for (int z = 0; z < d; z++) { IJ.showStatus("Applying LUT..."); IJ.showProgress(z, d - 1); final int[] slice = particleLabels[z]; for (int y = 0; y < h; y++) { final int yw = y * w; for (int x = 0; x < w; x++) { final int i = yw + x; final int label = slice[i]; if (label == 0) continue; slice[i] = lut[label]; } } } } private static boolean checkConsistence(final int[] lut, final List<HashSet<Integer>> map) { final int l = lut.length; for (int i = 1; i < l; i++) { if (!map.get(lut[i]).contains(i)) return false; } return true; } /** * Connect structures = minimisation of IDs * * @param imp an image. * @param workArray work array. * @param particleLabels particles in the image. * @param phase foreground or background * @param scanRanges int[][] listgetPixel(particleLabels, x, y, z, w, h, * d);ing ranges to run connectStructures on */ private void connectStructures(final ImagePlus imp, final byte[][] workArray, final int[][] particleLabels, final int phase, final int[][] scanRanges) { IJ.showStatus("Connecting " + sPhase + " structures" + chunkString); final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); for (int c = 0; c < scanRanges[0].length; c++) { final int sR0 = scanRanges[0][c]; final int sR1 = scanRanges[1][c]; final int sR2 = scanRanges[2][c]; final int sR3 = scanRanges[3][c]; for (int z = sR0; z < sR1; z++) { for (int y = 0; y < h; y++) { final int rowIndex = y * w; for (int x = 0; x < w; x++) { final int arrayIndex = rowIndex + x; final List<int[]> coordinates; if (workArray[z][arrayIndex] == BACK) { coordinates = get26NeighbourhoodCoordinates(x, y, z, w, h, d); } else if (workArray[z][arrayIndex] == FORE && particleLabels[z][arrayIndex] > 1) { coordinates = get6NeighbourhoodCoordinates(x, y, z, w, h, d); } else { continue; } replaceLabelsWithMinimum(coordinates, workArray, particleLabels, w, phase, sR2, sR3); } } if (phase == FORE) { IJ.showStatus("Connecting foreground structures" + chunkString); IJ.showProgress(z, d); } else { IJ.showStatus("Connecting background structures" + chunkString); IJ.showProgress(z, d + 1); } } } } /** * Find duplicated values and update the LUT * * @param counter counts of LUT values. * @param map map of LUT values. * @param lut a look-up table. * @return total number of duplicate values found. */ private static int countDuplicates(int[] counter, final ArrayList<HashSet<Integer>> map, final int[] lut) { //reset to 0 the counter array final int l = counter.length; counter = new int[l]; HashSet<Integer> set = null; for (int i = 1; i < map.size(); i++) { set = map.get(i); for (final Integer val : set) { final int v = val.intValue(); // every time a value is seen, log it counter[v]++; // update its LUT value if value was // found in a set with lower than current // lut value if (lut[v] > i) lut[v] = i; } } minimiseLutArray(lut); // all values should be seen only once, // count how many >1s there are. int count = 0; for (int i = 1; i < l; i++) { if (counter[i] > 1) count++; } return count; } /** * Calculate the cross product of 3 Point3f's, which describe two vectors * joined at the tails. Can be used to find the plane / surface normal of a * triangle. Half of its magnitude is the area of the triangle. * * @param point0 both vectors' tails * @param point1 vector 1's head * @param point2 vector 2's head * @return cross product vector */ private static Point3f crossProduct(final Point3f point0, final Point3f point1, final Point3f point2) { final double x1 = point1.x - point0.x; final double y1 = point1.y - point0.y; final double z1 = point1.z - point0.z; final double x2 = point2.x - point0.x; final double y2 = point2.y - point0.y; final double z2 = point2.z - point0.z; final Point3f crossVector = new Point3f(); crossVector.x = (float) (y1 * z2 - z1 * y2); crossVector.y = (float) (z1 * x2 - x1 * z2); crossVector.z = (float) (x1 * y2 - y1 * x2); return crossVector; } private static void display3DOriginal(final ImagePlus imp, final int resampling, final Image3DUniverse univ) { final Color3f colour = new Color3f(1.0f, 1.0f, 1.0f); final boolean[] channels = { true, true, true }; try { univ.addVoltex(imp, colour, imp.getTitle(), 0, channels, resampling) .setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); } } /** * Draws 3 orthogonal axes defined by the centroid, unitvector and axis * length. * * @param univ the universe where axes are drawn. * @param centroid centroid of a particle. * @param unitVector orientation of the particle. * @param lengths lengths of the axes. * @param green green component of the axes' color. * @param title text shown by the axes. */ private static void displayAxes(final Image3DUniverse univ, final double[] centroid, final double[][] unitVector, final double[] lengths, final float green, final String title) { final double cX = centroid[0]; final double cY = centroid[1]; final double cZ = centroid[2]; final double eVec1x = unitVector[0][0]; final double eVec1y = unitVector[1][0]; final double eVec1z = unitVector[2][0]; final double eVec2x = unitVector[0][1]; final double eVec2y = unitVector[1][1]; final double eVec2z = unitVector[2][1]; final double eVec3x = unitVector[0][2]; final double eVec3y = unitVector[1][2]; final double eVec3z = unitVector[2][2]; final double l1 = lengths[0]; final double l2 = lengths[1]; final double l3 = lengths[2]; final List<Point3f> mesh = new ArrayList<>(); final Point3f start1 = new Point3f(); start1.x = (float) (cX - eVec1x * l1); start1.y = (float) (cY - eVec1y * l1); start1.z = (float) (cZ - eVec1z * l1); mesh.add(start1); final Point3f end1 = new Point3f(); end1.x = (float) (cX + eVec1x * l1); end1.y = (float) (cY + eVec1y * l1); end1.z = (float) (cZ + eVec1z * l1); mesh.add(end1); final Point3f start2 = new Point3f(); start2.x = (float) (cX - eVec2x * l2); start2.y = (float) (cY - eVec2y * l2); start2.z = (float) (cZ - eVec2z * l2); mesh.add(start2); final Point3f end2 = new Point3f(); end2.x = (float) (cX + eVec2x * l2); end2.y = (float) (cY + eVec2y * l2); end2.z = (float) (cZ + eVec2z * l2); mesh.add(end2); final Point3f start3 = new Point3f(); start3.x = (float) (cX - eVec3x * l3); start3.y = (float) (cY - eVec3y * l3); start3.z = (float) (cZ - eVec3z * l3); mesh.add(start3); final Point3f end3 = new Point3f(); end3.x = (float) (cX + eVec3x * l3); end3.y = (float) (cY + eVec3y * l3); end3.z = (float) (cZ + eVec3z * l3); mesh.add(end3); final Color3f aColour = new Color3f(1.0f, green, 0.0f); try { univ.addLineMesh(mesh, aColour, title, false).setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); } } /** * Draw the particle centroids in a 3D viewer * * @param centroids [n][3] centroids of particles. * @param univ universe where the centroids are displayed. */ private static void displayCentroids(final double[][] centroids, final Image3DUniverse univ) { final int nCentroids = centroids.length; for (int p = 1; p < nCentroids; p++) { IJ.showStatus("Rendering centroids..."); IJ.showProgress(p, nCentroids); final Point3f centroid = new Point3f(); centroid.x = (float) centroids[p][0]; centroid.y = (float) centroids[p][1]; centroid.z = (float) centroids[p][2]; final List<Point3f> point = new ArrayList<>(); point.add(centroid); final CustomPointMesh mesh = new CustomPointMesh(point); mesh.setPointSize(5.0f); final float red = 0.0f; final float green = 0.5f * p / nCentroids; final float blue = 1.0f; final Color3f cColour = new Color3f(red, green, blue); mesh.setColor(cColour); try { univ.addCustomMesh(mesh, "Centroid " + p).setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); return; } } } private static void displayEllipsoids(final Object[][] ellipsoids, final Image3DUniverse univ) { final int nEllipsoids = ellipsoids.length; for (int el = 1; el < nEllipsoids; el++) { IJ.showStatus("Rendering ellipsoids..."); IJ.showProgress(el, nEllipsoids); if (ellipsoids[el] == null) { continue; } final double[] radii = (double[]) ellipsoids[el][1]; if (!isRadiiValid(radii)) { continue; } final double[] centre = (double[]) ellipsoids[el][0]; final double[][] eV = (double[][]) ellipsoids[el][2]; final double a = radii[0]; // longest final double b = radii[1]; // middle final double c = radii[2]; // shortest if (a < b || b < c || a < c) { IJ.log("Error: Bad ellipsoid radius ordering! Surface: " + el); } final double[][] ellipsoid = FitEllipsoid.testEllipsoid(a, b, c, 0, 0, 0, 0, 0, 1000, false); final int nPoints = ellipsoid.length; // rotate points by eigenvector matrix // and add transformation for centre for (int p = 0; p < nPoints; p++) { final double x = ellipsoid[p][0]; final double y = ellipsoid[p][1]; final double z = ellipsoid[p][2]; ellipsoid[p][0] = x * eV[0][0] + y * eV[0][1] + z * eV[0][2] + centre[0]; ellipsoid[p][1] = x * eV[1][0] + y * eV[1][1] + z * eV[1][2] + centre[1]; ellipsoid[p][2] = x * eV[2][0] + y * eV[2][1] + z * eV[2][2] + centre[2]; } final List<Point3f> points = new ArrayList<>(); for (final double[] anEllipsoid : ellipsoid) { final Point3f e = new Point3f(); e.x = (float) anEllipsoid[0]; e.y = (float) anEllipsoid[1]; e.z = (float) anEllipsoid[2]; points.add(e); } final CustomPointMesh mesh = new CustomPointMesh(points); mesh.setPointSize(1.0f); final float red = 0.0f; final float green = 0.5f; final float blue = 1.0f; final Color3f cColour = new Color3f(red, green, blue); mesh.setColor(cColour); try { univ.addCustomMesh(mesh, "Ellipsoid " + el).setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); return; } // Add some axes displayAxes(univ, centre, eV, radii, 1.0f, "Ellipsoid Axes " + el); } } /** * Display the particle labels as an ImagePlus * * @param particleLabels particles labelled in the original image. * @param imp original image, used for image dimensions, calibration and * titles * @return an image of the particles. */ private static ImagePlus displayParticleLabels(final int[][] particleLabels, final ImagePlus imp) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int wh = w * h; final ImageStack stack = new ImageStack(w, h); double max = 0; for (int z = 0; z < d; z++) { final float[] slicePixels = new float[wh]; for (int i = 0; i < wh; i++) { slicePixels[i] = particleLabels[z][i]; max = Math.max(max, slicePixels[i]); } stack.addSlice(imp.getImageStack().getSliceLabel(z + 1), slicePixels); } final ImagePlus impParticles = new ImagePlus(imp.getShortTitle() + "_parts", stack); impParticles.setCalibration(imp.getCalibration()); impParticles.getProcessor().setMinAndMax(0, max); if (max > Math.pow(2, 24)) IJ.error("Warning", "More than 16777216 (2^24) particles./n/n" + "Particle image labels are inaccurate above this number."); return impParticles; } /** * Draw the particle surfaces in a 3D viewer * * @param univ universe where the centroids are displayed. * @param surfacePoints points of each particle. */ private static void displayParticleSurfaces(final Image3DUniverse univ, final Collection<List<Point3f>> surfacePoints, final int colourMode, final double[] volumes, final double splitValue, final EigenvalueDecomposition[] eigens) { int p = 0; final int nParticles = surfacePoints.size(); for (final List<Point3f> surfacePoint : surfacePoints) { IJ.showStatus("Rendering surfaces..."); IJ.showProgress(p, nParticles); if (p > 0 && !surfacePoint.isEmpty()) { Color3f pColour = new Color3f(0, 0, 0); if (colourMode == GRADIENT) { final float red = 1.0f - p / (float) nParticles; final float green = 1.0f - red; final float blue = p / (2.0f * nParticles); pColour = new Color3f(red, green, blue); } else if (colourMode == SPLIT) { if (volumes[p] > splitValue) { // red if over pColour = new Color3f(1.0f, 0.0f, 0.0f); } else { // yellow if under pColour = new Color3f(1.0f, 1.0f, 0.0f); } } else if (colourMode == ORIENTATION) { pColour = colourFromEigenVector(eigens[p]); } // Add the mesh try { univ.addTriangleMesh(surfacePoint, pColour, "Surface " + p).setLocked( true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); return; } } p++; } } /** * Generate a colour based on the inertia tensor's eigenvector * * Colour is from the HSB colour wheel scaled by 0.5 to fit * into pi radians (rather than the 2 pi it normally occupies), * so that red is at 0, pi and 2pi radians. * * Colour is mapped to the axis-angle representation of the tensor * so hue varies as a function of second axis rotation around the * first. * * @param eigen Eigenvalue decomposition of the particle * @return Colour scaling in red for axis and green for angle */ private static Color3f colourFromEigenVector(EigenvalueDecomposition eigen) { final Matrix rotation = eigen.getV(); //deflection of long axis from image z axis, 0 - pi radians final double angle = Math.acos(-Math.abs(rotation.get(2, 0))); final float hue = (float)(angle / Math.PI); final float saturation = 1.0f; final float brightness = 1.0f; final int rgb = Color.HSBtoRGB(hue, saturation, brightness); final Color color = new Color(rgb); float red = (float)(color.getRed()/255d); float green = (float)(color.getGreen()/255d); float blue = (float)(color.getBlue()/255d); return new Color3f(red, green, blue); } /** * Create an image showing some particle measurement * * @param imp an image. * @param particleLabels the particles in the image. * @param values list of values whose array indices correspond to * particlelabels * @return ImagePlus with particle labels substituted with some value */ private static ImagePlus displayParticleValues(final ImagePlus imp, final int[][] particleLabels, final double[] values) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int wh = w * h; final float[][] pL = new float[d][wh]; values[0] = 0; // don't colour the background final ImageStack stack = new ImageStack(w, h); for (int z = 0; z < d; z++) { for (int i = 0; i < wh; i++) { final int p = particleLabels[z][i]; pL[z][i] = (float) values[p]; } stack.addSlice(imp.getImageStack().getSliceLabel(z + 1), pL[z]); } final double max = Arrays.stream(values).max().orElse(0.0); final ImagePlus impOut = new ImagePlus(imp.getShortTitle() + "_" + "volume", stack); impOut.setCalibration(imp.getCalibration()); impOut.getProcessor().setMinAndMax(0, max); return impOut; } /** * * @param imp * @param ellipsoids * @param title * @return ImagePlus containing particles drawn as best-fit solid ellipsoids */ private ImagePlus displayParticleEllipsoids(final ImagePlus imp, final Object[][] ellipsoids, final String title) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); Calibration cal = imp.getCalibration(); final double pW = cal.pixelWidth; final double pH = cal.pixelHeight; final double pD = cal.pixelDepth; //set up a work array final ByteProcessor[] bps = new ByteProcessor[d]; for (int z = 0; z < d; z++) { bps[z] = new ByteProcessor(w, h); } final int n = ellipsoids.length; for (int i = 0; i < n; i++) { IJ.showStatus("Drawing ellipsoid stack..."); IJ.showProgress(i, n); Ellipsoid ellipsoid; try { ellipsoid = new Ellipsoid(ellipsoids[i]); } catch (Exception e) { continue; } //ellipsoid is in calibrated real-world units final double[] box = ellipsoid.getAxisAlignedBoundingBox(); //decalibrate to pixels final int xMin = clamp((int) Math.floor(box[0] / pW), 0, w-1); final int xMax = clamp((int) Math.floor(box[1] / pW), 0, w-1); final int yMin = clamp((int) Math.floor(box[2] / pH), 0, h-1); final int yMax = clamp((int) Math.floor(box[3] / pH), 0, h-1); final int zMin = clamp((int) Math.floor(box[4] / pD), 0, d-1); final int zMax = clamp((int) Math.floor(box[5] / pD), 0, d-1); //set the ellipsoid-contained pixels to foreground for (int z = zMin; z <= zMax; z++) { for (int y = yMin; y <= yMax; y++) { for (int x = xMin; x <= xMax; x++ ) { if (ellipsoid.contains(x * pW, y * pH, z * pD)){ bps[z].set(x, y, 255); } } } } } ImageStack stack = new ImageStack(w, h); for (ByteProcessor bp : bps) stack.addSlice(bp); final ImagePlus impOut = new ImagePlus(imp.getShortTitle() + "_" + title, stack); impOut.setCalibration(cal); return impOut; } private int clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } private static void displayPrincipalAxes(final Image3DUniverse univ, final EigenvalueDecomposition[] eigens, final double[][] centroids, long[] particleSizes) { final int nEigens = eigens.length; for (int p = 1; p < nEigens; p++) { IJ.showStatus("Rendering principal axes..."); IJ.showProgress(p, nEigens); final long size = particleSizes[p]; final Matrix eVec = eigens[p].getV(); final Matrix eVal = eigens[p].getD(); double[] lengths = new double[3]; for (int i = 0; i < 3; i++) { lengths[i] = 2 * Math.sqrt(eVal.get(2 - i, 2 - i) / size); } displayAxes(univ, centroids[p], eVec.getArray(), lengths, 0.0f, "Principal Axes " + p); } } /** * Scans edge voxels and set all touching particles to background * * @param imp an image. * @param particleLabels particles in the image. */ private void excludeOnEdges(final ImagePlus imp, final int[][] particleLabels, final byte[][] workArray) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final long[] particleSizes = getParticleSizes(particleLabels); final int nLabels = particleSizes.length; final int[] newLabel = new int[nLabels]; for (int i = 0; i < nLabels; i++) newLabel[i] = i; // scan faces // top and bottom faces for (int y = 0; y < h; y++) { final int index = y * w; for (int x = 0; x < w; x++) { final int pt = particleLabels[0][index + x]; if (pt > 0) newLabel[pt] = 0; final int pb = particleLabels[d - 1][index + x]; if (pb > 0) newLabel[pb] = 0; } } // west and east faces for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int pw = particleLabels[z][y * w]; final int pe = particleLabels[z][y * w + w - 1]; if (pw > 0) newLabel[pw] = 0; if (pe > 0) newLabel[pe] = 0; } } // north and south faces final int lastRow = w * (h - 1); for (int z = 0; z < d; z++) { for (int x = 0; x < w; x++) { final int pn = particleLabels[z][x]; final int ps = particleLabels[z][lastRow + x]; if (pn > 0) newLabel[pn] = 0; if (ps > 0) newLabel[ps] = 0; } } // replace labels final int wh = w * h; for (int z = 0; z < d; z++) { for (int i = 0; i < wh; i++) { final int p = particleLabels[z][i]; final int nL = newLabel[p]; if (nL == 0) { particleLabels[z][i] = 0; workArray[z][i] = 0; } } } } /** * Remove particles outside user-specified volume thresholds * * @param imp ImagePlus, used for calibration * @param workArray binary foreground and background information * @param particleLabels Packed 3D array of particle labels * @param minVol minimum (inclusive) particle volume * @param maxVol maximum (inclusive) particle volume * @param phase phase we are interested in */ private void filterParticles(final ImagePlus imp, final byte[][] workArray, final int[][] particleLabels, final double minVol, final double maxVol, final int phase) { if (minVol == 0 && maxVol == Double.POSITIVE_INFINITY) return; final int d = imp.getImageStackSize(); final int wh = workArray[0].length; final long[] particleSizes = getParticleSizes(particleLabels); final double[] particleVolumes = getVolumes(imp, particleSizes); final byte flip; if (phase == FORE) { flip = 0; } else { flip = (byte) 255; } for (int z = 0; z < d; z++) { for (int i = 0; i < wh; i++) { final int p = particleLabels[z][i]; final double v = particleVolumes[p]; if (v < minVol || v > maxVol) { workArray[z][i] = flip; particleLabels[z][i] = 0; } } } } private static boolean findFirstAppearance(final int[] lut, final List<HashSet<Integer>> map) { final int l = map.size(); boolean changed = false; for (int i = 0; i < l; i++) { final HashSet<Integer> set = map.get(i); for (final Integer val : set) { // if the current lut value is greater // than the current position // update lut with current position if (lut[val] > i) { lut[val] = i; changed = true; } } } return changed; } private static int findMinimumLabel(final Iterable<int[]> coordinates, final byte[][] workArray, final int[][] particleLabels, final int w, final int phase, final int minStart) { int minLabel = minStart; for (final int[] coordinate : coordinates) { final int z = coordinate[2]; final int index = getOffset(coordinate[0], coordinate[1], w); if (workArray[z][index] == phase) { final int label = particleLabels[z][index]; if (label != 0 && label < minLabel) { minLabel = label; } } } return minLabel; } /** * Go through all pixels and assign initial particle label * * @param imp an image. * @param workArray byte[] array containing pixel values * @param phase FORE or BACK for foreground of background respectively * @return particleLabels int[] array containing label associating every pixel * with a particle */ private int[][] firstIDAttribution(final ImagePlus imp, final byte[][] workArray, final int phase) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int[] bounds = { w, h, d }; final int wh = w * h; IJ.showStatus("Finding " + sPhase + " structures"); final int[][] particleLabels = new int[d][wh]; int ID = 1; final BiFunction<int[], int[], List<int[]>> neighbourhoodFinder; if (phase == BACK) { neighbourhoodFinder = ParticleCounter::get6NeighbourhoodCoordinates; } else { neighbourhoodFinder = ParticleCounter::get26NeighbourhoodCoordinates; } for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int rowIndex = y * w; for (int x = 0; x < w; x++) { final int arrayIndex = rowIndex + x; if (workArray[z][arrayIndex] != phase) { continue; } particleLabels[z][arrayIndex] = ID; final List<int[]> coordinates = neighbourhoodFinder.apply(new int[] { x, y, z }, bounds); coordinates.add(new int[] { x, y, z }); final int minTag = findMinimumLabel(coordinates, workArray, particleLabels, w, phase, ID); particleLabels[z][arrayIndex] = minTag; if (minTag == ID) { ID++; } } } IJ.showProgress(z, d); } return particleLabels; } /** * Get neighborhood of a pixel in a 3D image (0 border conditions) * Longhand, hard-coded for speed * * @param neighborhood a neighbourhood in the image. * @param image 3D image (int[][]) * @param x x- coordinate * @param y y- coordinate * @param z z- coordinate (in image stacks the indexes start at 1) * @param w width of the image. * @param h height of the image. * @param d depth of the image. */ private static void get26Neighborhood(final int[] neighborhood, final int[][] image, final int x, final int y, final int z, final int w, final int h, final int d) { final int xm1 = x - 1; final int xp1 = x + 1; final int ym1 = y - 1; final int yp1 = y + 1; final int zm1 = z - 1; final int zp1 = z + 1; neighborhood[0] = getPixel(image, xm1, ym1, zm1, w, h, d); neighborhood[1] = getPixel(image, x, ym1, zm1, w, h, d); neighborhood[2] = getPixel(image, xp1, ym1, zm1, w, h, d); neighborhood[3] = getPixel(image, xm1, y, zm1, w, h, d); neighborhood[4] = getPixel(image, x, y, zm1, w, h, d); neighborhood[5] = getPixel(image, xp1, y, zm1, w, h, d); neighborhood[6] = getPixel(image, xm1, yp1, zm1, w, h, d); neighborhood[7] = getPixel(image, x, yp1, zm1, w, h, d); neighborhood[8] = getPixel(image, xp1, yp1, zm1, w, h, d); neighborhood[9] = getPixel(image, xm1, ym1, z, w, h, d); neighborhood[10] = getPixel(image, x, ym1, z, w, h, d); neighborhood[11] = getPixel(image, xp1, ym1, z, w, h, d); neighborhood[12] = getPixel(image, xm1, y, z, w, h, d); neighborhood[13] = getPixel(image, xp1, y, z, w, h, d); neighborhood[14] = getPixel(image, xm1, yp1, z, w, h, d); neighborhood[15] = getPixel(image, x, yp1, z, w, h, d); neighborhood[16] = getPixel(image, xp1, yp1, z, w, h, d); neighborhood[17] = getPixel(image, xm1, ym1, zp1, w, h, d); neighborhood[18] = getPixel(image, x, ym1, zp1, w, h, d); neighborhood[19] = getPixel(image, xp1, ym1, zp1, w, h, d); neighborhood[20] = getPixel(image, xm1, y, zp1, w, h, d); neighborhood[21] = getPixel(image, x, y, zp1, w, h, d); neighborhood[22] = getPixel(image, xp1, y, zp1, w, h, d); neighborhood[23] = getPixel(image, xm1, yp1, zp1, w, h, d); neighborhood[24] = getPixel(image, x, yp1, zp1, w, h, d); neighborhood[25] = getPixel(image, xp1, yp1, zp1, w, h, d); } private static List<int[]> get26NeighbourhoodCoordinates(final int[] voxel, final int[] bounds) { return get26NeighbourhoodCoordinates(voxel[0], voxel[1], voxel[2], bounds[0], bounds[1], bounds[2]); } private static List<int[]> get26NeighbourhoodCoordinates(final int x0, final int y0, final int z0, final int w, final int h, final int d) { final List<int[]> coordinates = new ArrayList<>(); for (int z = z0 - 1; z <= z0 + 1; z++) { for (int y = y0 - 1; y <= y0 + 1; y++) { for (int x = x0 - 1; x <= x0 + 1; x++) { if (z == z0 && y == y0 && x == x0) { continue; } if (withinBounds(x, y, z, w, h, d)) { coordinates.add(new int[] { x, y, z }); } } } } return coordinates; } private static void get6Neighborhood(final int[] neighborhood, final int[][] image, final int x, final int y, final int z, final int w, final int h, final int d) { neighborhood[0] = getPixel(image, x - 1, y, z, w, h, d); neighborhood[1] = getPixel(image, x, y - 1, z, w, h, d); neighborhood[2] = getPixel(image, x, y, z - 1, w, h, d); neighborhood[3] = getPixel(image, x + 1, y, z, w, h, d); neighborhood[4] = getPixel(image, x, y + 1, z, w, h, d); neighborhood[5] = getPixel(image, x, y, z + 1, w, h, d); } private static List<int[]> get6NeighbourhoodCoordinates(final int[] voxel, final int[] bounds) { return get26NeighbourhoodCoordinates(voxel[0], voxel[1], voxel[2], bounds[0], bounds[1], bounds[2]); } private static List<int[]> get6NeighbourhoodCoordinates(final int x0, final int y0, final int z0, final int w, final int h, final int d) { return Stream.of(new int[] { x0 - 1, y0, z0 }, new int[] { x0 + 1, y0, z0 }, new int[] { x0, y0 - 1, z0 }, new int[] { x0, y0 + 1, z0 }, new int[] { x0, y0, z0 - 1 }, new int[] { x0, y0, z0 + 1 }).filter( a -> withinBounds(a[0], a[1], a[2], w, h, d)).collect(Collectors .toList()); } /** * create a binary ImagePlus containing a single particle and which 'just * fits' the particle * * @param p The particle ID to get * @param imp original image, used for calibration * @param particleLabels work array of particle labels * @param limits x,y and z limits of each particle * @param padding amount of empty space to pad around each particle * @return a cropped single particle image. */ private static ImagePlus getBinaryParticle(final int p, final ImagePlus imp, final int[][] particleLabels, final int[][] limits, final int padding) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int xMin = Math.max(0, limits[p][0] - padding); final int xMax = Math.min(w - 1, limits[p][1] + padding); final int yMin = Math.max(0, limits[p][2] - padding); final int yMax = Math.min(h - 1, limits[p][3] + padding); final int zMin = Math.max(0, limits[p][4] - padding); final int zMax = Math.min(d - 1, limits[p][5] + padding); final int stackWidth = xMax - xMin + 1; final int stackHeight = yMax - yMin + 1; final int stackSize = stackWidth * stackHeight; final ImageStack stack = new ImageStack(stackWidth, stackHeight); for (int z = zMin; z <= zMax; z++) { final byte[] slice = new byte[stackSize]; int i = 0; for (int y = yMin; y <= yMax; y++) { final int sourceIndex = y * w; for (int x = xMin; x <= xMax; x++) { if (particleLabels[z][sourceIndex + x] == p) { slice[i] = (byte) 0xFF; } i++; } } stack.addSlice(imp.getStack().getSliceLabel(z + 1), slice); } final ImagePlus binaryImp = new ImagePlus("Particle_" + p, stack); final Calibration cal = imp.getCalibration(); binaryImp.setCalibration(cal); return binaryImp; } /** * Get the centroids of all the particles in real units * * @param imp an image. * @param particleLabels particles in the image. * @param particleSizes sizes of the particles * @return double[][] containing all the particles' centroids */ private static double[][] getCentroids(final ImagePlus imp, final int[][] particleLabels, final long[] particleSizes) { final int nParticles = particleSizes.length; final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final double[][] sums = new double[nParticles][3]; for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int index = y * w; for (int x = 0; x < w; x++) { final int particle = particleLabels[z][index + x]; sums[particle][0] += x; sums[particle][1] += y; sums[particle][2] += z; } } } final Calibration cal = imp.getCalibration(); final double[][] centroids = new double[nParticles][3]; for (int p = 0; p < nParticles; p++) { centroids[p][0] = cal.pixelWidth * sums[p][0] / particleSizes[p]; centroids[p][1] = cal.pixelHeight * sums[p][1] / particleSizes[p]; centroids[p][2] = cal.pixelDepth * sums[p][2] / particleSizes[p]; } return centroids; } private static EigenvalueDecomposition[] getEigens(final ImagePlus imp, final int[][] particleLabels, final double[][] centroids) { final Calibration cal = imp.getCalibration(); final double vW = cal.pixelWidth; final double vH = cal.pixelHeight; final double vD = cal.pixelDepth; final double voxVhVd = (vH * vH + vD * vD) / 12; final double voxVwVd = (vW * vW + vD * vD) / 12; final double voxVhVw = (vH * vH + vW * vW) / 12; final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int nParticles = centroids.length; final EigenvalueDecomposition[] eigens = new EigenvalueDecomposition[nParticles]; final double[][] momentTensors = new double[nParticles][6]; for (int z = 0; z < d; z++) { IJ.showStatus("Calculating particle moments..."); IJ.showProgress(z, d); final double zVd = z * vD; for (int y = 0; y < h; y++) { final double yVh = y * vH; final int index = y * w; for (int x = 0; x < w; x++) { final int p = particleLabels[z][index + x]; if (p > 0) { final double xVw = x * vW; final double dx = xVw - centroids[p][0]; final double dy = yVh - centroids[p][1]; final double dz = zVd - centroids[p][2]; momentTensors[p][0] += dy * dy + dz * dz + voxVhVd; // Ixx momentTensors[p][1] += dx * dx + dz * dz + voxVwVd; // Iyy momentTensors[p][2] += dy * dy + dx * dx + voxVhVw; // Izz momentTensors[p][3] += dx * dy; // Ixy momentTensors[p][4] += dx * dz; // Ixz momentTensors[p][5] += dy * dz; // Iyz } } } for (int p = 1; p < nParticles; p++) { final double[][] inertiaTensor = new double[3][3]; inertiaTensor[0][0] = momentTensors[p][0]; inertiaTensor[1][1] = momentTensors[p][1]; inertiaTensor[2][2] = momentTensors[p][2]; inertiaTensor[0][1] = -momentTensors[p][3]; inertiaTensor[0][2] = -momentTensors[p][4]; inertiaTensor[1][0] = -momentTensors[p][3]; inertiaTensor[1][2] = -momentTensors[p][5]; inertiaTensor[2][0] = -momentTensors[p][4]; inertiaTensor[2][1] = -momentTensors[p][5]; final Matrix inertiaTensorMatrix = new Matrix(inertiaTensor); final EigenvalueDecomposition E = new EigenvalueDecomposition( inertiaTensorMatrix); eigens[p] = E; } } return eigens; } private static Object[][] getEllipsoids( final Collection<List<Point3f>> surfacePoints) { final Object[][] ellipsoids = new Object[surfacePoints.size()][]; int p = 0; for (final List<Point3f> points : surfacePoints) { if (points == null) { p++; continue; } final Iterator<Point3f> pointIter = points.iterator(); final double[][] coOrdinates = new double[points.size()][3]; int i = 0; while (pointIter.hasNext()) { final Point3f point = pointIter.next(); coOrdinates[i][0] = point.x; coOrdinates[i][1] = point.y; coOrdinates[i][2] = point.z; i++; } try { ellipsoids[p] = FitEllipsoid.yuryPetrov(coOrdinates); } catch (final RuntimeException re) { IJ.log("Could not fit ellipsoid to surface " + p); } p++; } return ellipsoids; } /** * Get the Euler characteristic of each particle * * @param imp an image. * @param particleLabels particles of the image. * @param limits limits of the particles. * @param nParticles number particles. * @return euler characteristic of each image. */ private double[][] getEulerCharacter(final ImagePlus imp, final int[][] particleLabels, final int[][] limits, final int nParticles) { final Connectivity con = new Connectivity(); final double[][] eulerCharacters = new double[nParticles][3]; for (int p = 1; p < nParticles; p++) { final ImagePlus particleImp = getBinaryParticle(p, imp, particleLabels, limits, 1); final double euler = con.getSumEuler(particleImp); final double cavities = getNCavities(particleImp); // Calculate number of holes and cavities using // Euler = particles - holes + cavities // where particles = 1 final double holes = cavities - euler + 1; final double[] bettis = { euler, holes, cavities }; eulerCharacters[p] = bettis; } return eulerCharacters; } /** * Get the Feret diameter of a surface. Uses an inefficient brute-force * algorithm. * * @param particleSurfaces points of all the particles. * @return Feret diameters of the surfaces. */ private static double[] getFerets( final List<List<Point3f>> particleSurfaces) { final int nParticles = particleSurfaces.size(); final double[] ferets = new double[nParticles]; final ListIterator<List<Point3f>> it = particleSurfaces.listIterator(); int i = 0; Point3f a; Point3f b; List<Point3f> surface; ListIterator<Point3f> ita; ListIterator<Point3f> itb; while (it.hasNext()) { IJ.showStatus("Finding Feret diameter..."); IJ.showProgress(it.nextIndex(), nParticles); surface = it.next(); if (surface == null) { ferets[i] = Double.NaN; i++; continue; } ita = surface.listIterator(); while (ita.hasNext()) { a = ita.next(); itb = surface.listIterator(ita.nextIndex()); while (itb.hasNext()) { b = itb.next(); ferets[i] = Math.max(ferets[i], a.distance(b)); } } i++; } return ferets; } /** * Get the mean and standard deviation of pixel values &gt;0 for each particle * in a particle label work array * * @param imp Input image containing pixel values * @param particleLabels workArray containing particle labels * @param particleSizes array of particle sizes as pixel counts * @return array containing mean, std dev and max pixel values for each * particle */ private static double[][] getMeanStdDev(final ImagePlus imp, final int[][] particleLabels, final long[] particleSizes) { final int nParticles = particleSizes.length; final int d = imp.getImageStackSize(); final int wh = imp.getWidth() * imp.getHeight(); final ImageStack stack = imp.getImageStack(); final double[] sums = new double[nParticles]; for (int z = 0; z < d; z++) { final float[] pixels = (float[]) stack.getPixels(z + 1); final int[] labelPixels = particleLabels[z]; for (int i = 0; i < wh; i++) { final double value = pixels[i]; if (value > 0) { sums[labelPixels[i]] += value; } } } final double[][] meanStdDev = new double[nParticles][3]; for (int p = 1; p < nParticles; p++) { meanStdDev[p][0] = sums[p] / particleSizes[p]; } final double[] sumSquares = new double[nParticles]; for (int z = 0; z < d; z++) { final float[] pixels = (float[]) stack.getPixels(z + 1); final int[] labelPixels = particleLabels[z]; for (int i = 0; i < wh; i++) { final double value = pixels[i]; if (value > 0) { final int p = labelPixels[i]; final double residual = value - meanStdDev[p][0]; sumSquares[p] += residual * residual; meanStdDev[p][2] = Math.max(meanStdDev[p][2], value); } } } for (int p = 1; p < nParticles; p++) { meanStdDev[p][1] = Math.sqrt(sumSquares[p] / particleSizes[p]); } return meanStdDev; } private int getNCavities(final ImagePlus imp) { final Object[] result = getParticles(imp, BACK); final long[] particleSizes = (long[]) result[2]; final int nParticles = particleSizes.length; return nParticles - 2; } /** * Find the offset within a 1D array given 2 (x, y) offset values * * @param m x difference * @param n y difference * @param w width of the stack. * @return Integer offset for looking up pixel in work array */ private static int getOffset(final int m, final int n, final int w) { return m + n * w; } /** * Get the minimum and maximum x, y and z coordinates of each particle * * @param imp ImagePlus (used for stack size) * @param particleLabels work array containing labelled particles * @param nParticles number of particles in the stack * @return int[][] containing x, y and z minima and maxima. */ private static int[][] getParticleLimits(final ImagePlus imp, final int[][] particleLabels, final int nParticles) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int[][] limits = new int[nParticles][6]; for (int i = 0; i < nParticles; i++) { limits[i][0] = Integer.MAX_VALUE; // x min limits[i][1] = 0; // x max limits[i][2] = Integer.MAX_VALUE; // y min limits[i][3] = 0; // y max limits[i][4] = Integer.MAX_VALUE; // z min limits[i][5] = 0; // z max } for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int index = y * w; for (int x = 0; x < w; x++) { final int i = particleLabels[z][index + x]; limits[i][0] = Math.min(limits[i][0], x); limits[i][1] = Math.max(limits[i][1], x); limits[i][2] = Math.min(limits[i][2], y); limits[i][3] = Math.max(limits[i][3], y); limits[i][4] = Math.min(limits[i][4], z); limits[i][5] = Math.max(limits[i][5], z); } } } return limits; } private ArrayList<ArrayList<short[]>> getParticleLists( final int[][] particleLabels, final int nBlobs, final int w, final int h, final int d) { final ArrayList<ArrayList<short[]>> pL = new ArrayList<>(nBlobs); pL.add(new ArrayList<>()); final long[] particleSizes = getParticleSizes(particleLabels); for (int b = 1; b < nBlobs; b++) { pL.add(new ArrayList<>((int) particleSizes[b])); } // add all the particle coordinates to the appropriate list for (short z = 0; z < d; z++) { IJ.showStatus("Listing substructures..."); IJ.showProgress(z, d); final int[] sliceLabels = particleLabels[z]; for (short y = 0; y < h; y++) { final int i = y * w; for (short x = 0; x < w; x++) { final int p = sliceLabels[i + x]; if (p > 0) { // ignore background final short[] voxel = { x, y, z }; pL.get(p).add(voxel); } } } } return pL; } /** * Get particles, particle labels and particle sizes from a 3D ImagePlus * * @param imp Binary input image * @param slicesPerChunk number of slices per chunk. 2 is generally good. * @param minVol minimum volume particle to include * @param maxVol maximum volume particle to include * @param phase foreground or background (FORE or BACK) * @param doExclude if true, remove particles touching sides of the stack * @return Object[] {byte[][], int[][]} containing a binary workArray and * particle labels. */ private Object[] getParticles(final ImagePlus imp, final int slicesPerChunk, final double minVol, final double maxVol, final int phase, final boolean doExclude) { final byte[][] workArray = makeWorkArray(imp); return getParticles(imp, workArray, slicesPerChunk, minVol, maxVol, phase, doExclude); } private Object[] getParticles(final ImagePlus imp, final int phase) { final byte[][] workArray = makeWorkArray(imp); final double minVol = 0; final double maxVol = Double.POSITIVE_INFINITY; return getParticles(imp, workArray, 4, minVol, maxVol, phase, false); } /** * Get particles, particle labels and sizes from a workArray using an * ImagePlus for scale information * * @param imp input binary image * @param workArray work array * @param slicesPerChunk number of slices to use for each chunk * @param minVol minimum volume particle to include * @param maxVol maximum volume particle to include * @param phase FORE or BACK for foreground or background respectively * @param doExclude exclude particles touching the edges. * @return Object[] array containing a binary workArray, particle labels and * particle sizes */ private Object[] getParticles(final ImagePlus imp, final byte[][] workArray, final int slicesPerChunk, final double minVol, final double maxVol, final int phase, final boolean doExclude) { if (phase == FORE) { sPhase = "foreground"; } else if (phase == BACK) { sPhase = "background"; } else { throw new IllegalArgumentException(); } if (slicesPerChunk < 1) { throw new IllegalArgumentException(); } // Set up the chunks final int[][] particleLabels = firstIDAttribution(imp, workArray, phase); if (labelMethod == JOINING.MULTI) { // connect particles within chunks final int nChunks = getNChunks(imp, slicesPerChunk); final int nThreads = Runtime.getRuntime().availableProcessors(); final ConnectStructuresThread[] cptf = new ConnectStructuresThread[nThreads]; final int[][] chunkRanges = getChunkRanges(imp, nChunks, slicesPerChunk); for (int thread = 0; thread < nThreads; thread++) { cptf[thread] = new ConnectStructuresThread(thread, nThreads, imp, workArray, particleLabels, phase, nChunks, chunkRanges); cptf[thread].start(); } try { for (int thread = 0; thread < nThreads; thread++) { cptf[thread].join(); } } catch (final InterruptedException ie) { IJ.error("A thread was interrupted."); } // connect particles between chunks if (nChunks > 1) { chunkString = ": stitching..."; final int[][] stitchRanges = getStitchRanges(imp, nChunks, slicesPerChunk); connectStructures(imp, workArray, particleLabels, phase, stitchRanges); } } else if (labelMethod == JOINING.LINEAR) { joinStructures(imp, particleLabels, phase); } else if (labelMethod == JOINING.MAPPED) { final int nParticles = getParticleSizes(particleLabels).length; joinMappedStructures(imp, particleLabels, nParticles, phase); } filterParticles(imp, workArray, particleLabels, minVol, maxVol, phase); if (doExclude) excludeOnEdges(imp, particleLabels, workArray); minimiseLabels(particleLabels); final long[] particleSizes = getParticleSizes(particleLabels); return new Object[] { workArray, particleLabels, particleSizes }; } /** * Get pixel in 3D image (0 border conditions) * * @param image 3D image * @param x x- coordinate * @param y y- coordinate * @param z z- coordinate (in image stacks the indexes start at 1) * @param w width of the image. * @param h height of the image. * @param d depth of the image. * @return corresponding pixel (0 if out of image) */ private static int getPixel(final int[][] image, final int x, final int y, final int z, final int w, final int h, final int d) { if (withinBounds(x, y, z, w, h, d)) return image[z][x + y * w]; return 0; } /** * Return scan ranges for stitching. The first 2 values for each chunk are the * first slice of the next chunk and the last 2 values are the range through * which to replaceLabels() Running replace labels over incrementally * increasing volumes as chunks are added is OK (for 1st interface connect * chunks 0 & 1, for 2nd connect chunks 0, 1, 2, etc.) * * @param imp an image. * @param nC number of chunks * @param slicesPerChunk number of slices chunks process. * @return scanRanges list of scan limits for connectStructures() to stitch * chunks back together */ private static int[][] getStitchRanges(final ImagePlus imp, final int nC, final int slicesPerChunk) { final int nSlices = imp.getImageStackSize(); if (nC < 2) { return null; } final int[][] scanRanges = new int[4][3 * (nC - 1)]; // there are nC - 1 // interfaces for (int c = 0; c < nC - 1; c++) { scanRanges[0][c] = (c + 1) * slicesPerChunk; scanRanges[1][c] = (c + 1) * slicesPerChunk + 1; scanRanges[2][c] = c * slicesPerChunk; // forward and reverse // algorithm // hard scanRanges[3][c] = (c + 2) * slicesPerChunk; } // stitch back for (int c = nC - 1; c < 2 * (nC - 1); c++) { scanRanges[0][c] = (2 * nC - c - 2) * slicesPerChunk - 1; scanRanges[1][c] = (2 * nC - c - 2) * slicesPerChunk; scanRanges[2][c] = (2 * nC - c - 3) * slicesPerChunk; scanRanges[3][c] = (2 * nC - c - 1) * slicesPerChunk; } // stitch forwards (paranoid third pass) for (int c = 2 * (nC - 1); c < 3 * (nC - 1); c++) { scanRanges[0][c] = (-2 * nC + c + 3) * slicesPerChunk; scanRanges[1][c] = (-2 * nC + c + 3) * slicesPerChunk + 1; scanRanges[2][c] = (-2 * nC + c + 2) * slicesPerChunk; scanRanges[3][c] = (-2 * nC + c + 4) * slicesPerChunk; } for (int i = 0; i < scanRanges.length; i++) { for (int c = 0; c < scanRanges[i].length; c++) { if (scanRanges[i][c] > nSlices) { scanRanges[i][c] = nSlices; } } } scanRanges[3][nC - 2] = nSlices; return scanRanges; } /** * Calculate surface area of the isosurface * * @param points in 3D triangle mesh * @return surface area */ private static double getSurfaceArea(final List<Point3f> points) { if (points == null) { return 0; } double sumArea = 0; final int nPoints = points.size(); final Point3f origin = new Point3f(0.0f, 0.0f, 0.0f); for (int n = 0; n < nPoints; n += 3) { IJ.showStatus("Calculating surface area..."); final Point3f cp = crossProduct(points.get(n), points.get(n + 1), points .get(n + 2)); final double deltaArea = 0.5 * cp.distance(origin); sumArea += deltaArea; } return sumArea; } private static double[] getSurfaceAreas( final Collection<List<Point3f>> surfacePoints) { return surfacePoints.stream().mapToDouble(ParticleCounter::getSurfaceArea) .toArray(); } private static ArrayList<List<Point3f>> getSurfacePoints(final ImagePlus imp, final int[][] particleLabels, final int[][] limits, final int resampling, final int nParticles) { final Calibration cal = imp.getCalibration(); final ArrayList<List<Point3f>> surfacePoints = new ArrayList<>(); final boolean[] channels = { true, false, false }; for (int p = 0; p < nParticles; p++) { IJ.showStatus("Getting surface meshes..."); IJ.showProgress(p, nParticles); if (p > 0) { final ImagePlus binaryImp = getBinaryParticle(p, imp, particleLabels, limits, resampling); // noinspection TypeMayBeWeakened final MCTriangulator mct = new MCTriangulator(); @SuppressWarnings("unchecked") final List<Point3f> points = mct.getTriangles(binaryImp, 128, channels, resampling); final double xOffset = (limits[p][0] - 1) * cal.pixelWidth; final double yOffset = (limits[p][2] - 1) * cal.pixelHeight; final double zOffset = (limits[p][4] - 1) * cal.pixelDepth; for (final Point3f point : points) { point.x += xOffset; point.y += yOffset; point.z += zOffset; } surfacePoints.add(points); if (points.isEmpty()) { IJ.log("Particle " + p + " resulted in 0 surface points"); } } else { surfacePoints.add(null); } } return surfacePoints; } private static double[] getSurfaceVolume( final Collection<List<Point3f>> surfacePoints) { return surfacePoints.stream().mapToDouble(p -> { if (p == null) { return 0; } final CustomTriangleMesh mesh = new CustomTriangleMesh(p); return Math.abs(mesh.getVolume()); }).toArray(); } private static double[] getVolumes(final ImagePlus imp, final long[] particleSizes) { final Calibration cal = imp.getCalibration(); final double voxelVolume = cal.pixelWidth * cal.pixelHeight * cal.pixelDepth; final int nLabels = particleSizes.length; final double[] particleVolumes = new double[nLabels]; for (int i = 0; i < nLabels; i++) { particleVolumes[i] = voxelVolume * particleSizes[i]; } return particleVolumes; } private static boolean isRadiiValid(final double[] radii) { for (int r = 0; r < 3; r++) { if (Double.isNaN(radii[r])) { return false; } } return true; } /** * Join particle p to particle b, relabelling p with b. * * @param b a particle label. * @param p another particle label. * @param particleLabels array of particle labels * @param particleLists list of particle voxel coordinates * @param w stack width */ private static void joinBlobs(final int b, final int p, final int[][] particleLabels, final List<ArrayList<short[]>> particleLists, final int w) { for (final short[] voxelB : particleLists.get(p)) { particleLists.get(b).add(voxelB); final int iB = voxelB[1] * w + voxelB[0]; particleLabels[voxelB[2]][iB] = b; } particleLists.get(p).clear(); } private static void joinMappedStructures(final ImagePlus imp, final int[][] particleLabels, final int nParticles, final int phase) { IJ.showStatus("Mapping structures and joining..."); final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final ArrayList<HashSet<Integer>> map = new ArrayList<>(nParticles + 1); final int[] lut = new int[nParticles + 1]; // set each label to be its own root final int initialCapacity = 1; for (int i = 0; i < nParticles + 1; i++) { lut[i] = i; final HashSet<Integer> set = new HashSet<>(initialCapacity); set.add(i); map.add(set); } // populate the first list with neighbourhoods int[] nbh = null; if (phase == FORE) nbh = new int[26]; else if (phase == BACK) nbh = new int[6]; for (int z = 0; z < d; z++) { IJ.showStatus("Building neighbourhood list"); IJ.showProgress(z, d - 1); final int[] slice = particleLabels[z]; for (int y = 0; y < h; y++) { final int yw = y * w; for (int x = 0; x < w; x++) { final int centre = slice[yw + x]; // ignore background if (centre == 0) continue; if (phase == FORE) get26Neighborhood(nbh, particleLabels, x, y, z, w, h, d); else if (phase == BACK) get6Neighborhood(nbh, particleLabels, x, y, z, w, h, d); addNeighboursToMap(map, nbh, centre); } } } // map now contains for every value the set of first degree neighbours IJ.showStatus("Minimising list and generating LUT..."); // place to store counts of each label final int[] counter = new int[lut.length]; // place to map lut values and targets // lutList lists the indexes which point to each transformed lutvalue // for quick updating final ArrayList<HashSet<Integer>> lutList = new ArrayList<>(nParticles); // initialise the lutList for (int i = 0; i <= nParticles; i++) { lutList.add(new HashSet<>(2)); } // set it up. ArrayList index is now the transformed value // list contains the lut indices that have the transformed value for (int i = 1; i < nParticles; i++) { final HashSet<Integer> list = lutList.get(lut[i]); list.add(i); } // initialise LUT with minimal label in set updateLUTwithMinPosition(lut, map, lutList); // find the minimal position of each value findFirstAppearance(lut, map); // de-chain the lut array minimiseLutArray(lut); int duplicates = Integer.MAX_VALUE; boolean snowball = true; boolean merge = true; boolean update = true; boolean find = true; boolean minimise = true; boolean inconsistent = true; while ((duplicates > 0) && snowball && merge && update && find && minimise && inconsistent) { snowball = snowballLUT(lut, map, lutList); duplicates = countDuplicates(counter, map, lut); // merge duplicates merge = mergeDuplicates(map, counter, duplicates, lut, lutList); // update the LUT update = updateLUTwithMinPosition(lut, map, lutList); find = findFirstAppearance(lut, map); // minimise the LUT minimise = minimiseLutArray(lut); inconsistent = !checkConsistence(lut, map); } // replace all labels with LUT values applyLUT(particleLabels, lut, w, h, d); IJ.showStatus("LUT applied"); } /** * Joins semi-labelled particles using a non-recursive algorithm * * @param imp an image. * @param particleLabels particles in the image. * @param phase foreground or background */ private void joinStructures(final ImagePlus imp, final int[][] particleLabels, final int phase) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final long[] particleSizes = getParticleSizes(particleLabels); final int nBlobs = particleSizes.length; final ArrayList<ArrayList<short[]>> particleLists = getParticleLists( particleLabels, nBlobs, w, h, d); switch (phase) { case FORE: { for (int b = 1; b < nBlobs; b++) { IJ.showStatus("Joining substructures..."); IJ.showProgress(b, nBlobs); if (particleLists.get(b).isEmpty()) { continue; } for (int l = 0; l < particleLists.get(b).size(); l++) { final short[] voxel = particleLists.get(b).get(l); final int x = voxel[0]; final int y = voxel[1]; final int z = voxel[2]; // find any neighbours with bigger labels for (int zN = z - 1; zN <= z + 1; zN++) { for (int yN = y - 1; yN <= y + 1; yN++) { final int index = yN * w; for (int xN = x - 1; xN <= x + 1; xN++) { if (!withinBounds(xN, yN, zN, w, h, d)) continue; final int iN = index + xN; final int p = particleLabels[zN][iN]; if (p > b) { joinBlobs(b, p, particleLabels, particleLists, w); } } } } } } break; } case BACK: { for (int b = 1; b < nBlobs; b++) { IJ.showStatus("Joining substructures..."); IJ.showProgress(b, nBlobs); if (particleLists.get(b).isEmpty()) { continue; } for (int l = 0; l < particleLists.get(b).size(); l++) { final short[] voxel = particleLists.get(b).get(l); final int x = voxel[0]; final int y = voxel[1]; final int z = voxel[2]; // find any neighbours with bigger labels int xN = x; int yN = y; int zN = z; for (int n = 1; n < 7; n++) { switch (n) { case 1: xN = x - 1; break; case 2: xN = x + 1; break; case 3: yN = y - 1; xN = x; break; case 4: yN = y + 1; break; case 5: zN = z - 1; yN = y; break; case 6: zN = z + 1; break; } if (!withinBounds(xN, yN, zN, w, h, d)) continue; final int iN = yN * w + xN; final int p = particleLabels[zN][iN]; if (p > b) { joinBlobs(b, p, particleLabels, particleLists, w); } } } } } } } /** * Create a work array * * @param imp an image. * @return byte[][] work array */ private static byte[][] makeWorkArray(final ImagePlus imp) { final int s = imp.getStackSize(); final int p = imp.getWidth() * imp.getHeight(); final byte[][] workArray = new byte[s][p]; final ImageStack stack = imp.getStack(); for (int z = 0; z < s; z++) { final ImageProcessor ip = stack.getProcessor(z + 1); for (int i = 0; i < p; i++) { workArray[z][i] = (byte) ip.get(i); } } return workArray; } private static boolean mergeDuplicates(final List<HashSet<Integer>> map, final int[] counter, final int duplicates, final int[] lut, final List<HashSet<Integer>> lutList) { boolean changed = false; // create a list of duplicate values to check for final int[] dupList = new int[duplicates]; final int l = counter.length; int dup = 0; for (int i = 1; i < l; i++) { if (counter[i] > 1) dupList[dup] = i; dup++; } // find duplicates hiding in sets which are greater than the lut for (int i = 1; i < l; i++) { final HashSet<Integer> set = map.get(i); if (set.isEmpty()) continue; for (final int d : dupList) { // if we are in the lut key of this value, continue final int lutValue = lut[d]; if (lutValue == i) continue; // otherwise check to see if the non-lut set contains our dup if (set.contains(d)) { // we found a dup, merge whole set back to lut changed = true; final Iterator<Integer> iter = set.iterator(); final HashSet<Integer> target = map.get(lutValue); while (iter.hasNext()) { final Integer val = iter.next(); target.add(val); lut[val] = lutValue; } // empty the set set.clear(); updateLUT(i, lutValue, lut, lutList); // move to the next set break; } } } return changed; } /** * Gets rid of redundant particle labels * * @param particleLabels particles in the image. */ private void minimiseLabels(final int[][] particleLabels) { IJ.showStatus("Minimising labels..."); final int d = particleLabels.length; final long[] particleSizes = getParticleSizes(particleLabels); final int nLabels = particleSizes.length; final int[] newLabel = new int[nLabels]; int minLabel = 0; // find the minimised labels for (int i = 0; i < nLabels; i++) { if (particleSizes[i] > 0) { if (i == minLabel) { newLabel[i] = i; minLabel++; continue; } newLabel[i] = minLabel; particleSizes[minLabel] = particleSizes[i]; particleSizes[i] = 0; minLabel++; } } // now replace labels final int wh = particleLabels[0].length; for (int z = 0; z < d; z++) { IJ.showStatus("Replacing with minimised labels..."); IJ.showProgress(z, d); final int[] slice = particleLabels[z]; for (int i = 0; i < wh; i++) { final int p = slice[i]; if (p > 0) { slice[i] = newLabel[p]; } } } } private static boolean minimiseLutArray(final int[] lutArray) { final int l = lutArray.length; boolean changed = false; for (int key = 1; key < l; key++) { final int value = lutArray[key]; // this is a root if (value == key) continue; // otherwise update the current key with the // value from the referred key final int minValue = lutArray[value]; lutArray[key] = minValue; changed = true; } return changed; } /** * Check whole array replacing m with n * * @param particleLabels particles labelled in the image. * @param m value to be replaced * @param n new value * @param startZ first z coordinate to check * @param endZ last+1 z coordinate to check */ private static void replaceLabel(final int[][] particleLabels, final int m, final int n, final int startZ, final int endZ) { final int s = particleLabels[0].length; for (int z = startZ; z < endZ; z++) { for (int i = 0; i < s; i++) if (particleLabels[z][i] == m) { particleLabels[z][i] = n; } } } private static void replaceLabelsWithMinimum( final Iterable<int[]> coordinates, final byte[][] workArray, final int[][] particleLabels, final int w, final int phase, final int minZ, final int maxZ) { final int minimumLabel = findMinimumLabel(coordinates, workArray, particleLabels, w, phase, 0); for (final int[] coordinate : coordinates) { final int vX = coordinate[0]; final int vY = coordinate[1]; final int vZ = coordinate[2]; final int offset = getOffset(vX, vY, w); if (workArray[vZ][offset] == phase) { final int label = particleLabels[vZ][offset]; if (label != 0 && label != minimumLabel) { replaceLabel(particleLabels, label, minimumLabel, minZ, maxZ); } } } } /** * Iterate backwards over map entries, moving set values to their new lut * positions in the map. Updates LUT value of shifted values * * @param lut a color look-up table. * @param map a map of LUT values. * @return false if nothing changed, true if something changed */ private static boolean snowballLUT(final int[] lut, final List<HashSet<Integer>> map, final List<HashSet<Integer>> lutList) { boolean changed = false; for (int i = lut.length - 1; i > 0; i IJ.showStatus("Snowballing labels..."); IJ.showProgress(lut.length - i + 1, lut.length); final int lutValue = lut[i]; if (lutValue < i) { changed = true; final HashSet<Integer> set = map.get(i); final HashSet<Integer> target = map.get(lutValue); for (final Integer n : set) { target.add(n); lut[n] = lutValue; } // set is made empty // if later tests come across empty sets, then // must look up the lut to find the new location of the // neighbour network set.clear(); // update lut so that anything pointing // to cleared set points to the new set updateLUT(i, lutValue, lut, lutList); } } return changed; } /** * Replace old value with new value in LUT using map * * @param oldValue a LUT value to be replaced. * @param newValue new value of the LUT value. * @param lut a look-up table. * @param lutlist hash of LUT values. */ private static void updateLUT(final int oldValue, final int newValue, final int[] lut, final List<HashSet<Integer>> lutlist) { final HashSet<Integer> list = lutlist.get(oldValue); final HashSet<Integer> newList = lutlist.get(newValue); for (final Integer in : list) { lut[in] = newValue; newList.add(in); } list.clear(); } private static boolean updateLUTwithMinPosition(final int[] lut, final List<HashSet<Integer>> map, final List<HashSet<Integer>> lutList) { final int l = lut.length; final boolean changed = false; for (int i = 1; i < l; i++) { final HashSet<Integer> set = map.get(i); if (set.isEmpty()) continue; // find minimal value or lut value in the set int min = Integer.MAX_VALUE; int minLut = Integer.MAX_VALUE; for (final Integer val : set) { min = Math.min(min, val); minLut = Math.min(minLut, lut[val]); } // min now contains the smaller of the neighbours or their LUT // values min = Math.min(min, minLut); // add minimal value to lut final HashSet<Integer> target = map.get(min); for (final Integer val : set) { target.add(val); if (lut[val] > min) lut[val] = min; } set.clear(); updateLUT(i, min, lut, lutList); } return changed; } private static boolean withinBounds(final int m, final int n, final int o, final int w, final int h, final int d) { return (m >= 0 && m < w && n >= 0 && n < h && o >= 0 && o < d); } /** Particle joining method */ public enum JOINING { MULTI, LINEAR, MAPPED } private final class ConnectStructuresThread extends Thread { private final ImagePlus imp; private final int thread; private final int nThreads; private final int nChunks; private final int phase; private final byte[][] workArray; private final int[][] particleLabels; private final int[][] chunkRanges; private ConnectStructuresThread(final int thread, final int nThreads, final ImagePlus imp, final byte[][] workArray, final int[][] particleLabels, final int phase, final int nChunks, final int[][] chunkRanges) { this.imp = imp; this.thread = thread; this.nThreads = nThreads; this.workArray = workArray; this.particleLabels = particleLabels; this.phase = phase; this.nChunks = nChunks; this.chunkRanges = chunkRanges; } @Override public void run() { for (int k = thread; k < nChunks; k += nThreads) { // assign singleChunkRange for chunk k from chunkRanges final int[][] singleChunkRange = new int[4][1]; for (int i = 0; i < 4; i++) { singleChunkRange[i][0] = chunkRanges[i][k]; } chunkString = ": chunk " + (k + 1) + "/" + nChunks; connectStructures(imp, workArray, particleLabels, phase, singleChunkRange); } } } Object[] getParticles(final ImagePlus imp, final int slicesPerChunk, final int phase) { final byte[][] workArray = makeWorkArray(imp); return getParticles(imp, workArray, slicesPerChunk, 0.0, Double.POSITIVE_INFINITY, phase, false); } Object[] getParticles(final ImagePlus imp, final byte[][] workArray, final int slicesPerChunk, final int phase) { return getParticles(imp, workArray, slicesPerChunk, 0.0, Double.POSITIVE_INFINITY, phase, false); } /** * Gets number of chunks needed to divide a stack into evenly-sized sets of * slices. * * @param imp input image * @param slicesPerChunk number of slices per chunk * @return number of chunks */ static int getNChunks(final ImagePlus imp, final int slicesPerChunk) { final double d = imp.getImageStackSize(); return (int) Math.ceil(d / slicesPerChunk); } /** * Get a 2 d array that defines the z-slices to scan within while connecting * particles within chunkified stacks. * * @param imp an image. * @param nC number of chunks * @param slicesPerChunk number of slices chunks process. * @return scanRanges int[][] containing 4 limits: int[0][] - start of outer * for; int[1][] end of outer for; int[3][] start of inner for; int[4] * end of inner 4. Second dimension is chunk number. */ static int[][] getChunkRanges(final ImagePlus imp, final int nC, final int slicesPerChunk) { final int nSlices = imp.getImageStackSize(); final int[][] scanRanges = new int[4][nC]; scanRanges[0][0] = 0; // the first chunk starts at the first (zeroth) // slice scanRanges[2][0] = 0; // and that is what replaceLabel() will work on // first if (nC == 1) { scanRanges[1][0] = nSlices; scanRanges[3][0] = nSlices; } else if (nC > 1) { scanRanges[1][0] = slicesPerChunk; scanRanges[3][0] = slicesPerChunk; for (int c = 1; c < nC; c++) { for (int i = 0; i < 4; i++) { scanRanges[i][c] = scanRanges[i][c - 1] + slicesPerChunk; } } // reduce the last chunk to nSlices scanRanges[1][nC - 1] = nSlices; scanRanges[3][nC - 1] = nSlices; } return scanRanges; } /** * Get the sizes of all the particles as a voxel count * * @param particleLabels particles in the image. * @return particleSizes sizes of the particles. */ long[] getParticleSizes(final int[][] particleLabels) { IJ.showStatus("Getting " + sPhase + " particle sizes"); final int d = particleLabels.length; final int wh = particleLabels[0].length; // find the highest value particleLabel int maxParticle = 0; for (final int[] slice : particleLabels) { for (int i = 0; i < wh; i++) { maxParticle = Math.max(maxParticle, slice[i]); } } final long[] particleSizes = new long[maxParticle + 1]; for (int z = 0; z < d; z++) { final int[] slice = particleLabels[z]; for (int i = 0; i < wh; i++) { particleSizes[slice[i]]++; } IJ.showProgress(z, d); } return particleSizes; } /** * Set the value of this instance's labelMethod field * * @param label one of ParticleCounter.MULTI or .LINEAR */ void setLabelMethod(final JOINING label) { labelMethod = label; } }
package org.rstudio.studio.client.rmarkdown.ui; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.LoadHandler; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.dom.WindowEx; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.core.client.widget.AnchorableFrame; import org.rstudio.core.client.widget.SatelliteFramePanel; import org.rstudio.core.client.widget.Toolbar; import org.rstudio.core.client.widget.ToolbarButton; import org.rstudio.core.client.widget.ToolbarLabel; import org.rstudio.studio.client.rmarkdown.model.RMarkdownServerOperations; import org.rstudio.studio.client.rmarkdown.model.RmdPreviewParams; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.common.presentation.SlideNavigationMenu; import org.rstudio.studio.client.common.presentation.SlideNavigationToolbarMenu; import org.rstudio.studio.client.common.presentation.events.SlideIndexChangedEvent; import org.rstudio.studio.client.common.presentation.events.SlideNavigationChangedEvent; import org.rstudio.studio.client.common.presentation.events.SlideNavigationChangedEvent.Handler; import org.rstudio.studio.client.common.presentation.model.SlideNavigation; import org.rstudio.studio.client.common.presentation.model.SlideNavigationItem; public class RmdOutputPanel extends SatelliteFramePanel<AnchorableFrame> implements RmdOutputPresenter.Display { @Inject public RmdOutputPanel(Commands commands, RMarkdownServerOperations server) { super(commands); server_ = server; } @Override public void showOutput(RmdPreviewParams params, boolean enablePublish, boolean refresh) { fileLabel_.setText(FileSystemItem.createFile( params.getOutputFile()).getName()); // we can only publish self-contained HTML to RPubs boolean showPublish = enablePublish && params.getResult().isHtml() && params.getResult().isSelfContained(); publishButton_.setText(params.getResult().getRpubsPublished() ? "Republish" : "Publish"); publishButton_.setVisible(showPublish); publishButtonSeparator_.setVisible(showPublish); // when refreshing, reapply the current scroll position and anchor scrollPosition_ = refresh ? getScrollPosition() : params.getScrollPosition(); String url; if (refresh) { url = getCurrentUrl(); } else { url = server_.getApplicationURL(params.getOutputUrl()); if (params.getAnchor().length() > 0) { url += "#" + params.getAnchor(); } } showUrl(url); } @Override protected void initToolbar (Toolbar toolbar, Commands commands) { AppCommand presHome = commands.presentationHome(); ToolbarButton homeButton = new ToolbarButton( presHome.getImageResource(), new ClickHandler() { @Override public void onClick(ClickEvent event) { navigate(0); } }); homeButton.setTitle(presHome.getTooltip()); slideNavigationMenu_ = new SlideNavigationToolbarMenu(toolbar, homeButton, 400, 100, true); fileLabel_ = new ToolbarLabel(); fileLabel_.addStyleName(ThemeStyles.INSTANCE.subtitle()); fileLabel_.getElement().getStyle().setMarginRight(7, Unit.PX); toolbar.addLeftWidget(fileLabel_); toolbar.addLeftSeparator(); ToolbarButton popoutButton = commands.viewerPopout().createToolbarButton(); popoutButton.setText("Open in Browser"); toolbar.addLeftWidget(popoutButton); publishButtonSeparator_ = toolbar.addLeftSeparator(); publishButton_ = commands.publishHTML().createToolbarButton(false); toolbar.addLeftWidget(publishButton_); toolbar.addRightWidget(commands.viewerRefresh().createToolbarButton()); } @Override protected AnchorableFrame createFrame(String url) { AnchorableFrame frame = new AnchorableFrame(); frame.navigate(url); frame.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { Document doc = getFrame().getIFrame().getContentDocument(); if (scrollPosition_ > 0) doc.setScrollTop(scrollPosition_); String title = doc.getTitle(); if (title != null && !title.isEmpty()) { Window.setTitle(title); title_ = title; } // see if we can do ioslides navigation SlideNavigation slideNavigation = getIoslidesNavigationList(doc); handlerManager_.fireEvent(new SlideNavigationChangedEvent( slideNavigation)); // slide change monitoring slideChangeMonitor_.cancel(); if (slideNavigation != null) { fireSlideIndexChanged(); slideChangeMonitor_.scheduleRepeating(250); } } }); return frame; } private Timer slideChangeMonitor_ = new Timer() { @Override public void run() { String url = getCurrentUrl(); if (!url.equals(lastUrl_)) { lastUrl_ = url; fireSlideIndexChanged(); } } private String lastUrl_ = null; }; @Override public void refresh() { // cache the scroll position, so we can re-apply it when the page loads scrollPosition_ = getScrollPosition(); showUrl(getCurrentUrl()); } @Override public int getScrollPosition() { return getFrame().getIFrame().getContentDocument().getScrollTop(); } @Override public String getTitle() { return title_; } @Override public String getAnchor() { String url = getCurrentUrl(); int anchorPos = url.lastIndexOf(" return anchorPos > 0 ? url.substring(anchorPos + 1) : ""; } @Override public void navigate(int index) { getFrame().getIFrame().focus(); String url = getCurrentUrl(); int anchorPos = url.lastIndexOf(" if (anchorPos > 0) url = url.substring(0, anchorPos); showUrl(url + "#" + (index + 1)); } @Override public SlideNavigationMenu getNavigationMenu() { return slideNavigationMenu_; } @Override public HandlerRegistration addSlideNavigationChangedHandler(Handler handler) { return handlerManager_.addHandler(SlideNavigationChangedEvent.TYPE, handler); } @Override public HandlerRegistration addSlideIndexChangedHandler( SlideIndexChangedEvent.Handler handler) { return handlerManager_.addHandler(SlideIndexChangedEvent.TYPE, handler); } // the current URL is the one currently showing in the frame, which may // reflect navigation occurring after initial load (e.g. anchor changes) private String getCurrentUrl() { return getFrame().getIFrame().getContentDocument().getURL(); } private SlideNavigation getIoslidesNavigationList(Document doc) { // look for ioslides JsArray<SlideNavigationItem> navItems = JsArray.createArray().cast(); NodeList<Element> slides = doc.getElementsByTagName("slide"); if (slides.getLength() <= 2) // just the title slide + the background return null; for (int i = 0; i<slides.getLength(); i++) { Element slide = slides.getItem(i); boolean segue = slide.getClassName().contains("segue"); NodeList<Element> hgroups = slide.getElementsByTagName("hgroup"); if (hgroups.getLength() != 0) { // get the slide Element header = hgroups.getItem(0).getFirstChildElement(); String h = header.getTagName(); if (h.equalsIgnoreCase("h1") || h.equalsIgnoreCase("h2")) { String title = header.getInnerText(); if (!StringUtil.isNullOrEmpty(title)) { SlideNavigationItem navItem = SlideNavigationItem.create( title, segue ? 0 : 1, i, -1); navItems.push(navItem); } } } } if (navItems.length() > 0) return SlideNavigation.create(slides.getLength() - 1, navItems); else return null; } private void fireSlideIndexChanged() { try { String anchor = getAnchor(); if (anchor.length() == 0) anchor = "1"; int index = Integer.parseInt(anchor); handlerManager_.fireEvent(new SlideIndexChangedEvent(index-1)); } catch(NumberFormatException e) { } } private SlideNavigationToolbarMenu slideNavigationMenu_; private Label fileLabel_; private ToolbarButton publishButton_; private Widget publishButtonSeparator_; private String title_; private RMarkdownServerOperations server_; private int scrollPosition_ = 0; private HandlerManager handlerManager_ = new HandlerManager(this); }
package com.elmakers.mine.bukkit.block; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.bukkit.Art; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Rotation; import org.bukkit.block.BlockFace; import org.bukkit.inventory.ItemStack; import org.bukkit.util.BlockVector; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.entity.EntityData; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.NMSUtils; public class Schematic implements com.elmakers.mine.bukkit.api.block.Schematic { private volatile boolean loaded = false; private Vector size; private Vector center; private MaterialAndData[][][] blocks; private Collection<EntityData> entities; public Schematic() { } public void load(short width, short height, short length, short[] blockTypes, byte[] data, Collection<Object> tileEntityData, Collection<Object> entityData, Vector origin, Vector offset) { size = new Vector(width, height, length); center = new Vector(Math.floor(size.getBlockX() / 2), 0, Math.floor(size.getBlockZ() / 2)); blocks = new MaterialAndData[width][height][length]; entities = new ArrayList<>(); // Load entities for (Object entity : entityData) { String type = NMSUtils.getMetaString(entity, "id"); Vector position = NMSUtils.getPosition(entity, "Pos"); if (position == null) continue; position = position.subtract(origin).subtract(center); if (type == null) continue; // Only doing paintings and item frames for now. if (type.equals("Painting")) { String motive = NMSUtils.getMetaString(entity, "Motive"); motive = motive.toLowerCase(); Art art = Art.ALBAN; for (Art test : Art.values()) { if (test.name().toLowerCase().replace("_", "").equals(motive)) { art = test; break; } } byte facing = NMSUtils.getMetaByte(entity, "Facing"); EntityData painting = com.elmakers.mine.bukkit.entity.EntityData.loadPainting(position, art, getFacing(facing)); entities.add(painting); } else if (type.equals("ItemFrame")) { byte facing = NMSUtils.getMetaByte(entity, "Facing"); byte rotation = NMSUtils.getMetaByte(entity, "ItemRotation"); Rotation rot = Rotation.NONE; if (rotation < Rotation.values().length) { rot = Rotation.values()[rotation]; } ItemStack item = NMSUtils.getItem(NMSUtils.getNode(entity, "Item")); EntityData itemFrame = com.elmakers.mine.bukkit.entity.EntityData.loadItemFrame(position, item, getFacing(facing), rot); entities.add(itemFrame); } } // Map tile entity data Map<BlockVector, Object> tileEntityMap = new HashMap<>(); for (Object tileEntity : tileEntityData) { try { Integer x = NMSUtils.getMetaInt(tileEntity, "x"); Integer y = NMSUtils.getMetaInt(tileEntity, "y"); Integer z = NMSUtils.getMetaInt(tileEntity, "z"); if (x == null || y == null || z == null) continue; BlockVector location = new BlockVector(x, y, z); tileEntityMap.put(location, tileEntity); } catch (Exception ex) { ex.printStackTrace(); } } for (int y = 0; y < height; y++) { for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++) { int index = x + (y * length + z) * width; Material material = CompatibilityUtils.getMaterial(blockTypes[index], data[index]); if (material != null) { MaterialAndData block = null; // For 1.13 we're going to use BlockData here. String blockData = CompatibilityUtils.getBlockData(material, data[index]); if (blockData != null) { block = new MaterialAndData(material, blockData); } else { block = new MaterialAndData(material, data[index]); } // Check for tile entity data BlockVector blockLocation = new BlockVector(x, y, z); Object tileEntity = tileEntityMap.get(blockLocation); if (tileEntity != null) { try { if (DefaultMaterials.isCommand(material)) { String customName = NMSUtils.getMetaString(tileEntity, "CustomName"); if (!customName.isEmpty()) { block.setCustomName(customName); } block.setCommandLine(NMSUtils.getMetaString(tileEntity, "Command")); } else { block.setRawData(tileEntity); } } catch (Exception ex) { ex.printStackTrace(); } } blocks[x][y][z] = block; } } } } loaded = true; } protected BlockFace getFacing(byte dir) { switch (dir) { case 0: return BlockFace.SOUTH; case 1: return BlockFace.WEST; case 2: return BlockFace.NORTH; case 3: return BlockFace.EAST; } return BlockFace.UP; } @Override public boolean contains(Vector v) { int x = v.getBlockX() + center.getBlockX(); int y = v.getBlockY() + center.getBlockY(); int z = v.getBlockZ() + center.getBlockZ(); return (x >= 0 && x <= size.getBlockX() && y >= 0 && y <= size.getBlockY() && z >= 0 && z <= size.getBlockZ()); } @Nullable @Override public MaterialAndData getBlock(Vector v) { int x = v.getBlockX() + center.getBlockX(); int y = v.getBlockY() + center.getBlockY(); int z = v.getBlockZ() + center.getBlockZ(); if (x < 0 || x >= blocks.length || y < 0 || y >= blocks[x].length || z < 0 || z >= blocks[x][y].length) { return null; } return blocks[x][y][z]; } @Override public Collection<EntityData> getEntities(Location center) { List<EntityData> translated = new ArrayList<>(); for (EntityData data : entities) { EntityData relative = data == null ? null : data.getRelativeTo(center); if (relative != null) { translated.add(relative); } } return translated; } @Override public Vector getSize() { return size; } @Override public boolean isLoaded() { return loaded; } }
package org.opencms.ade.containerpage.client; import org.opencms.gwt.client.util.CmsMessages; /** * Convenience class to access the localized messages of this OpenCms package.<p> * * @since 8.0.0 */ public final class Messages { /** Message constant for key in the resource bundle. */ public static final String ERR_LOCK_RESOURCE_CHANGED_BY_1 = "ERR_LOCK_RESOURCE_CHANGED_BY_1"; /** Message constant for key in the resource bundle. */ public static final String ERR_LOCK_RESOURCE_LOCKED_BY_1 = "ERR_LOCK_RESOURCE_LOCKED_BY_1"; /** Message constant for key in the resource bundle. */ public static final String ERR_LOCK_TITLE_RESOURCE_CHANGED_0 = "ERR_LOCK_TITLE_RESOURCE_CHANGED_0"; /** Message constant for key in the resource bundle. */ public static final String ERR_LOCK_TITLE_RESOURCE_LOCKED_0 = "ERR_LOCK_TITLE_RESOURCE_LOCKED_0"; /** Message constant for key in the resource bundle. */ public static final String ERR_READING_CONTAINER_PAGE_DATA_0 = "ERR_READING_CONTAINER_PAGE_DATA_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_ASK_DELETE_REMOVED_ELEMENT_0 = "GUI_ASK_DELETE_REMOVED_ELEMENT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_ASK_DELETE_REMOVED_ELEMENT_TITLE_0 = "GUI_ASK_DELETE_REMOVED_ELEMENT_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_BREAK_UP_TEXT_0 = "GUI_BUTTON_BREAK_UP_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_CANCEL_TEXT_0 = "GUI_BUTTON_CANCEL_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_CHANGE_ORDER_TEXT_0 = "GUI_BUTTON_CHANGE_ORDER_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_DISCARD_TEXT_0 = "GUI_BUTTON_DISCARD_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_EDITFAVORITES_TEXT_0 = "GUI_BUTTON_EDITFAVORITES_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_REMOVE_TEXT_0 = "GUI_BUTTON_REMOVE_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_RESET_DISABLED_0 = "GUI_BUTTON_RESET_DISABLED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_RESET_TEXT_0 = "GUI_BUTTON_RESET_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_RETURN_TEXT_0 = "GUI_BUTTON_RETURN_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_SAVE_DISABLED_0 = "GUI_BUTTON_SAVE_DISABLED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_BUTTON_SAVE_TEXT_0 = "GUI_BUTTON_SAVE_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_CLIPBOARD_ITEM_CAN_NOT_BE_EDITED_0 = "GUI_CLIPBOARD_ITEM_CAN_NOT_BE_EDITED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_LEAVE_NOT_SAVED_0 = "GUI_DIALOG_LEAVE_NOT_SAVED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_NOT_SAVED_TITLE_0 = "GUI_DIALOG_NOT_SAVED_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_PAGE_RESET_0 = "GUI_DIALOG_PAGE_RESET_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_PUBLISH_NOT_SAVED_0 = "GUI_DIALOG_PUBLISH_NOT_SAVED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_RELOAD_TEXT_0 = "GUI_DIALOG_RELOAD_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_RELOAD_TITLE_0 = "GUI_DIALOG_RELOAD_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_RESET_TITLE_0 = "GUI_DIALOG_RESET_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_SAVE_BEFORE_LEAVING_0 = "GUI_DIALOG_SAVE_BEFORE_LEAVING_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_DIALOG_SAVE_QUESTION_0 = "GUI_DIALOG_SAVE_QUESTION_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_EDIT_SMALL_ELEMENTS_0 = "GUI_EDIT_SMALL_ELEMENTS_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_GROUPCONTAINER_CAPTION_0 = "GUI_GROUPCONTAINER_CAPTION_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_GROUPCONTAINER_LABEL_DESCRIPTION_0 = "GUI_GROUPCONTAINER_LABEL_DESCRIPTION_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_GROUPCONTAINER_LABEL_TITLE_0 = "GUI_GROUPCONTAINER_LABEL_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_GROUPCONTAINER_LOADING_DATA_0 = "GUI_GROUPCONTAINER_LOADING_DATA_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_INHERITANCECONTAINER_CAPTION_0 = "GUI_INHERITANCECONTAINER_CAPTION_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_INHERITANCECONTAINER_CONFIG_NAME_0 = "GUI_INHERITANCECONTAINER_CONFIG_NAME_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_INHERITANCECONTAINER_HIDE_ELEMENTS_0 = "GUI_INHERITANCECONTAINER_HIDE_ELEMENTS_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_INHERITANCECONTAINER_NO_HIDDEN_ELEMENTS_0 = "GUI_INHERITANCECONTAINER_NO_HIDDEN_ELEMENTS_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_INHERITANCECONTAINER_SHOW_HIDDEN_0 = "GUI_INHERITANCECONTAINER_SHOW_HIDDEN_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_KEEP_ELEMENT_0 = "GUI_KEEP_ELEMENT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_LOCK_FAIL_0 = "GUI_LOCK_FAIL_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NO_SETTINGS_0 = "GUI_NO_SETTINGS_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NO_SETTINGS_TITLE_0 = "GUI_NO_SETTINGS_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NOTIFICATION_ADD_TO_FAVORITES_0 = "GUI_NOTIFICATION_ADD_TO_FAVORITES_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NOTIFICATION_FAVORITES_SAVED_0 = "GUI_NOTIFICATION_FAVORITES_SAVED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NOTIFICATION_GROUP_CONTAINER_SAVED_0 = "GUI_NOTIFICATION_GROUP_CONTAINER_SAVED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0 = "GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NOTIFICATION_PAGE_SAVED_0 = "GUI_NOTIFICATION_PAGE_SAVED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NOTIFICATION_PAGE_UNLOCKED_0 = "GUI_NOTIFICATION_PAGE_UNLOCKED_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_NOTIFICATION_UNABLE_TO_LOCK_0 = "GUI_NOTIFICATION_UNABLE_TO_LOCK_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_PROPERTY_DIALOG_TEXT_0 = "GUI_PROPERTY_DIALOG_TEXT_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_PROPERTY_DIALOG_TITLE_0 = "GUI_PROPERTY_DIALOG_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_SETTINGS_LEGEND_0 = "GUI_SETTINGS_LEGEND_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_TAB_FAVORITES_DESCRIPTION_0 = "GUI_TAB_FAVORITES_DESCRIPTION_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_TAB_FAVORITES_NO_ELEMENTS_0 = "GUI_TAB_FAVORITES_NO_ELEMENTS_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_TAB_FAVORITES_TITLE_0 = "GUI_TAB_FAVORITES_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_TAB_RECENT_DESCRIPTION_0 = "GUI_TAB_RECENT_DESCRIPTION_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_TAB_RECENT_TITLE_0 = "GUI_TAB_RECENT_TITLE_0"; /** Message constant for key in the resource bundle. */ public static final String GUI_TITLE_INHERITED_FROM_1 = "GUI_TITLE_INHERITED_FROM_1"; /** Name of the used resource bundle. */ private static final String BUNDLE_NAME = "org.opencms.ade.containerpage.clientmessages"; /** Static instance member. */ private static CmsMessages INSTANCE; /** * Hides the public constructor for this utility class.<p> */ private Messages() { // hide the constructor } /** * Returns an instance of this localized message accessor.<p> * * @return an instance of this localized message accessor */ public static CmsMessages get() { if (INSTANCE == null) { INSTANCE = new CmsMessages(BUNDLE_NAME); } return INSTANCE; } /** * Returns the bundle name for this OpenCms package.<p> * * @return the bundle name for this OpenCms package */ public String getBundleName() { return BUNDLE_NAME; } }
package org.jivesoftware.openfire.streammanagement; import java.math.BigInteger; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import org.dom4j.Element; import org.dom4j.QName; import org.dom4j.dom.DOMElement; import org.jivesoftware.openfire.Connection; import org.jivesoftware.openfire.PacketRouter; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.auth.AuthToken; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.LocalClientSession; import org.jivesoftware.openfire.session.LocalSession; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.StringUtils; import org.jivesoftware.util.XMPPDateTimeFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmpp.packet.*; /** * XEP-0198 Stream Manager. * Handles client/server messages acknowledgement. * * @author jonnyheavey */ public class StreamManager { private final Logger Log; private boolean resume = false; public static class UnackedPacket { public final long x; public final Date timestamp = new Date(); public final Packet packet; public UnackedPacket(long x, Packet p) { this.x = x; packet = p; } } public static boolean isStreamManagementActive() { return JiveGlobals.getBooleanProperty("stream.management.active", true); } /** * Stanza namespaces */ public static final String NAMESPACE_V2 = "urn:xmpp:sm:2"; public static final String NAMESPACE_V3 = "urn:xmpp:sm:3"; /** * Session (stream) to client. */ private final LocalSession session; /** * Namespace to be used in stanzas sent to client (depending on XEP-0198 version used by client) */ private String namespace; /** * Count of how many stanzas/packets * sent from the client that the server has processed */ private AtomicLong serverProcessedStanzas = new AtomicLong( 0 ); /** * Count of how many stanzas/packets * sent from the server that the client has processed */ private AtomicLong clientProcessedStanzas = new AtomicLong( 0 ); /** * The value (2^32)-1, used to emulate roll-over */ private static final long MASK = new BigInteger( "2" ).pow( 32 ).longValue() - 1; /** * Collection of stanzas/packets sent to client that haven't been acknowledged. */ private Deque<UnackedPacket> unacknowledgedServerStanzas = new LinkedList<>(); public StreamManager(LocalSession session) { String address; try { address = session.getConnection().getHostAddress(); } catch ( UnknownHostException e ) { address = null; } this.Log = LoggerFactory.getLogger(StreamManager.class + "["+ (address == null ? "(unknown address)" : address) +"]" ); this.session = session; } /** * Returns true if a stream is resumable. * * @return True if a stream is resumable. */ public boolean getResume() { return resume; } /** * Processes a stream management element. * * @param element The stream management element to be processed. */ public void process( Element element ) { switch(element.getName()) { case "enable": String resumeString = element.attributeValue("resume"); boolean resume = false; if (resumeString != null) { if (resumeString.equalsIgnoreCase("true") || resumeString.equalsIgnoreCase("yes") || resumeString.equals("1")) { resume = true; } } enable( element.getNamespace().getStringValue(), resume ); break; case "resume": long h = new Long(element.attributeValue("h")); String previd = element.attributeValue("previd"); startResume( element.getNamespaceURI(), previd, h); break; case "r": sendServerAcknowledgement(); break; case "a": processClientAcknowledgement( element); break; default: sendUnexpectedError(); } } /** * Should this session be allowed to resume? * This is used while processed <enable/> and <resume/> * * @return True if the session is allowed to resume. */ private boolean allowResume() { boolean allow = false; // Ensure that resource binding has occurred. if (session instanceof ClientSession) { AuthToken authToken = ((LocalClientSession)session).getAuthToken(); if (authToken != null) { if (!authToken.isAnonymous()) { allow = true; } } } return allow; } /** * Attempts to enable Stream Management for the entity identified by the provided JID. * * @param namespace The namespace that defines what version of SM is to be enabled. * @param resume Whether the client is requesting a resumable session. */ private void enable( String namespace, boolean resume ) { boolean offerResume = allowResume(); // Ensure that resource binding has occurred. if (session.getStatus() != Session.STATUS_AUTHENTICATED) { this.namespace = namespace; sendUnexpectedError(); return; } String smId = null; synchronized ( this ) { // Do nothing if already enabled if ( isEnabled() ) { sendUnexpectedError(); return; } this.namespace = namespace; this.resume = resume && offerResume; if ( this.resume ) { // Create SM-ID. smId = StringUtils.encodeBase64( session.getAddress().getResource() + "\0" + session.getStreamID().getID()); } } // Send confirmation to the requestee. Element enabled = new DOMElement(QName.get("enabled", namespace)); if (this.resume) { enabled.addAttribute("resume", "true"); enabled.addAttribute( "id", smId); } session.deliverRawText(enabled.asXML()); } private void startResume(String namespace, String previd, long h) { Log.debug("Attempting resumption for {}, h={}", previd, h); this.namespace = namespace; // Ensure that resource binding has NOT occurred. if (!allowResume() ) { sendUnexpectedError(); return; } if (session.getStatus() == Session.STATUS_AUTHENTICATED) { sendUnexpectedError(); return; } AuthToken authToken = null; // Ensure that resource binding has occurred. if (session instanceof ClientSession) { authToken = ((LocalClientSession) session).getAuthToken(); } if (authToken == null) { sendUnexpectedError(); return; } // Decode previd. String resource; String streamId; try { StringTokenizer toks = new StringTokenizer(new String(StringUtils.decodeBase64(previd), StandardCharsets.UTF_8), "\0"); resource = toks.nextToken(); streamId = toks.nextToken(); } catch (Exception e) { Log.debug("Exception from previd decode:", e); sendUnexpectedError(); return; } final JID fullJid; if ( authToken.isAnonymous() ){ fullJid = new JID(resource, authToken.getDomain(), resource, true); } else { fullJid = new JID(authToken.getUsername(), authToken.getDomain(), resource, true); } Log.debug("Resuming session {}", fullJid); // Locate existing session. LocalClientSession otherSession = (LocalClientSession)XMPPServer.getInstance().getRoutingTable().getClientRoute(fullJid); if (otherSession == null) { sendError(new PacketError(PacketError.Condition.item_not_found)); return; } if (!otherSession.getStreamID().getID().equals(streamId)) { sendError(new PacketError(PacketError.Condition.item_not_found)); return; } Log.debug("Found existing session, checking status"); // Previd identifies proper session. Now check SM status if (!otherSession.getStreamManager().resume) { Log.debug("Not allowing a client to resume a session, the session to be resumed does not have the stream management resumption feature enabled." ); sendError(new PacketError(PacketError.Condition.unexpected_request)); return; } if (!otherSession.getStreamManager().namespace.equals(namespace)) { Log.debug("Not allowing a client to resume a session, the session to be resumed used a different version ({}) of the session management resumption feature as compared to the version that's requested now: {}.", otherSession.getStreamManager().namespace, namespace); sendError(new PacketError(PacketError.Condition.unexpected_request)); return; } if (!otherSession.getStreamManager().validateClientAcknowledgement(h)) { Log.debug("Not allowing a client to resume a session, as it reports it received more stanzas from us than that we've send it." ); sendError(new PacketError(PacketError.Condition.unexpected_request)); return; } if (!otherSession.isDetached()) { Log.debug("Existing session is not detached; detaching."); Connection oldConnection = otherSession.getConnection(); otherSession.setDetached(); oldConnection.close(); } Log.debug("Attaching to other session."); // If we're all happy, disconnect this session. Connection conn = session.getConnection(); session.setDetached(); // Connect new session. otherSession.reattach(conn, h); Log.debug( "Perform resumption on session {}. Closing session {}", otherSession, session ); session.close(); } /** * Called when a session receives a closing stream tag, this prevents the * session from being detached. */ public void formalClose() { this.resume = false; } /** * Sends XEP-0198 acknowledgement &lt;a /&gt; to client from server */ public void sendServerAcknowledgement() { if(isEnabled()) { if (session.isDetached()) { Log.debug("Session is detached, won't request an ack."); return; } String ack = String.format("<a xmlns='%s' h='%s' />", namespace, serverProcessedStanzas.get() & MASK ); session.deliverRawText( ack ); } } /** * Sends XEP-0198 request <r /> to client from server */ private void sendServerRequest() { if(isEnabled()) { if (session.isDetached()) { Log.debug("Session is detached, won't request an ack."); return; } String request = String.format("<r xmlns='%s' />", namespace); session.deliverRawText( request ); } } /** * Send an error if a XEP-0198 stanza is received at an unexpected time. * e.g. before resource-binding has completed. */ private void sendUnexpectedError() { sendError(new PacketError( PacketError.Condition.unexpected_request )); } /** * Send a generic failed error. * * @param error PacketError describing the failure. */ private void sendError(PacketError error) { session.deliverRawText( String.format("<failed xmlns='%s'>", namespace) + String.format("<%s xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>", error.getCondition().toXMPP()) + "</failed>" ); this.namespace = null; // isEnabled() is testing this. } /** * Checks if the amount of stanzas that the client acknowledges is equal to or less than the amount of stanzas that * we've sent to the client. * * @param h Then number of stanzas that the client acknowledges it has received from us. * @return false if we sent less stanzas to the client than the number it is acknowledging. */ private synchronized boolean validateClientAcknowledgement(long h) { return h <= ( unacknowledgedServerStanzas.isEmpty() ? clientProcessedStanzas.get() : unacknowledgedServerStanzas.getLast().x ); } /** * Process client acknowledgements for a given value of h. * * @param h Last handled stanza to be acknowledged. */ private void processClientAcknowledgement(long h) { synchronized (this) { if ( !validateClientAcknowledgement(h) ) { // All paths leading up to here should have checked for this. Race condition? throw new IllegalStateException( "Client acknowledges stanzas that we didn't send! Client Ack h: "+h+", our last stanza: " + unacknowledgedServerStanzas.getLast().x ); } clientProcessedStanzas.set( h ); // Remove stanzas from temporary storage as now acknowledged Log.trace( "Before processing client Ack (h={}): {} unacknowledged stanzas.", h, unacknowledgedServerStanzas.size() ); // Pop all acknowledged stanzas. while( !unacknowledgedServerStanzas.isEmpty() && unacknowledgedServerStanzas.getFirst().x <= h ) { unacknowledgedServerStanzas.removeFirst(); } // Ensure that unacknowledged stanzas are purged after the client rolled over 'h' which occurs at h= (2^32)-1 final int maxUnacked = getMaximumUnacknowledgedStanzas(); final boolean clientHadRollOver = h < maxUnacked && !unacknowledgedServerStanzas.isEmpty() && unacknowledgedServerStanzas.getLast().x > MASK - maxUnacked; if ( clientHadRollOver ) { Log.info( "Client rolled over 'h'. Purging high-numbered unacknowledged stanzas." ); while ( !unacknowledgedServerStanzas.isEmpty() && unacknowledgedServerStanzas.getLast().x > MASK - maxUnacked) { unacknowledgedServerStanzas.removeLast(); } } Log.trace( "After processing client Ack (h={}): {} unacknowledged stanzas.", h, unacknowledgedServerStanzas.size()); } } /** * Receive and process acknowledgement packet from client * @param ack XEP-0198 acknowledgement <a /> stanza to process */ private void processClientAcknowledgement(Element ack) { if(isEnabled()) { if (ack.attribute("h") != null) { final long h = Long.valueOf(ack.attributeValue("h")); Log.debug( "Received acknowledgement from client: h={}", h ); if (!validateClientAcknowledgement(h)) { Log.warn( "Closing client session. Client acknowledges stanzas that we didn't send! Client Ack h: {}, our last stanza: {}, affected session: {}", h, unacknowledgedServerStanzas.getLast().x, session ); final StreamError error = new StreamError( StreamError.Condition.undefined_condition, "You acknowledged stanzas that we didn't send. Your Ack h: " + h + ", our last stanza: " + unacknowledgedServerStanzas.getLast().x ); session.deliverRawText( error.toXML() ); session.close(); return; } processClientAcknowledgement(h); } } } /** * Registers that Openfire sends a stanza to the client (which is expected to be acknowledged later). * @param packet The stanza that is sent. */ public void sentStanza(Packet packet) { if(isEnabled()) { final long requestFrequency = JiveGlobals.getLongProperty( "stream.management.requestFrequency", 5 ); final int size; synchronized (this) { // The next ID is one higher than the last stanza that was sent (which might be unacknowledged!) final long x = 1 + ( unacknowledgedServerStanzas.isEmpty() ? clientProcessedStanzas.get() : unacknowledgedServerStanzas.getLast().x ); unacknowledgedServerStanzas.addLast( new StreamManager.UnackedPacket( x, packet.createCopy() ) ); size = unacknowledgedServerStanzas.size(); Log.trace( "Added stanza of type '{}' to collection of unacknowledged stanzas (x={}). Collection size is now {}.", packet.getElement().getName(), x, size ); // Prevent keeping to many stanzas in memory. if ( size > getMaximumUnacknowledgedStanzas() ) { Log.warn( "To many stanzas go unacknowledged for this connection. Clearing queue and disabling functionality." ); namespace = null; unacknowledgedServerStanzas.clear(); return; } } // When we have a sizable amount of unacknowledged stanzas, request acknowledgement. if ( size % requestFrequency == 0 ) { Log.debug( "Requesting acknowledgement from peer, as we have {} or more unacknowledged stanzas.", requestFrequency ); sendServerRequest(); } } } public void onClose(PacketRouter router, JID serverAddress) { // Re-deliver unacknowledged stanzas from broken stream (XEP-0198) synchronized (this) { if(isEnabled()) { namespace = null; // disable stream management. for (StreamManager.UnackedPacket unacked : unacknowledgedServerStanzas) { if (unacked.packet instanceof Message) { Message m = (Message) unacked.packet; if (m.getExtension("delay", "urn:xmpp:delay") == null) { Element delayInformation = m.addChildElement("delay", "urn:xmpp:delay"); delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(unacked.timestamp)); delayInformation.addAttribute("from", serverAddress.toBareJID()); } router.route(unacked.packet); } } } } } public void onResume(JID serverAddress, long h) { Log.debug("Agreeing to resume"); Element resumed = new DOMElement(QName.get("resumed", namespace)); resumed.addAttribute("previd", StringUtils.encodeBase64( session.getAddress().getResource() + "\0" + session.getStreamID().getID())); resumed.addAttribute("h", Long.toString(serverProcessedStanzas.get())); session.getConnection().deliverRawText(resumed.asXML()); Log.debug("Resuming session: Ack for {}", h); processClientAcknowledgement(h); Log.debug("Processing remaining unacked stanzas"); // Re-deliver unacknowledged stanzas from broken stream (XEP-0198) synchronized (this) { if(isEnabled()) { for (StreamManager.UnackedPacket unacked : unacknowledgedServerStanzas) { try { if (unacked.packet instanceof Message) { Message m = (Message) unacked.packet; if (m.getExtension("delay", "urn:xmpp:delay") == null) { Element delayInformation = m.addChildElement("delay", "urn:xmpp:delay"); delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(unacked.timestamp)); delayInformation.addAttribute("from", serverAddress.toBareJID()); } session.getConnection().deliver(m); } else if (unacked.packet instanceof Presence) { Presence p = (Presence) unacked.packet; if (p.getExtension("delay", "urn:xmpp:delay") == null) { Element delayInformation = p.addChildElement("delay", "urn:xmpp:delay"); delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(unacked.timestamp)); delayInformation.addAttribute("from", serverAddress.toBareJID()); } session.getConnection().deliver(p); } else { session.getConnection().deliver(unacked.packet); } } catch (UnauthorizedException e) { Log.warn("Caught unauthorized exception, which seems worrying: ", e); } } sendServerRequest(); } } } /** * Determines whether Stream Management enabled for session this * manager belongs to. * @return true when stream management is enabled, otherwise false. */ public boolean isEnabled() { return namespace != null; } /** * Increments the count of stanzas processed by the server since * Stream Management was enabled. */ public void incrementServerProcessedStanzas() { if(isEnabled()) { this.serverProcessedStanzas.incrementAndGet(); } } /** * The maximum amount of stanzas we keep, waiting for ack. * @return The maximum number of stanzas. */ private int getMaximumUnacknowledgedStanzas() { return JiveGlobals.getIntProperty( "stream.management.max-unacked", 10000 ); } }
package WeatherAPI.Providers.WorldWeatherOnline; import WeatherAPI.Direction; import WeatherAPI.IWeather; import WeatherAPI.Providers.LocationSource; import WeatherAPI.Providers.WeatherProvider; import WeatherAPI.WeatherCondition; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.EnumSet; public class WWOProvider extends WeatherProvider implements IWeather { private static final String WWO_API_FORMAT = "xml"; private static final String WWO_API_URL = "http://free.worldweatheronline.com/feed/weather.ashx?q=%s&format=%s&num_of_days=1&key=%s"; private static final String WWO_XPATH_HEADER = "//data/current_condition/%s"; private XMLReader _reader; private String _wwo_api_key; public WWOProvider () { if (IsAvailable()) { _wwo_api_key = PROPERTIES.getProperty("WORLD_WEATHER_ONLINE_API_KEY"); _reader = new XMLReader(); } } public boolean IsAvailable() { return PROPERTIES.containsKey("WORLD_WEATHER_ONLINE_API_KEY") && (PROPERTIES.getProperty("WORLD_WEATHER_ONLINE_API_KEY") != null && !PROPERTIES.getProperty("WORLD_WEATHER_ONLINE_API_KEY").equals("")); } public void Update() { URL url; HttpURLConnection conn = null; InputStream stream = null; try { url = new URL(String.format(WWO_API_URL, getLocation(), WWO_API_FORMAT, _wwo_api_key)); conn = (HttpURLConnection)url.openConnection(); stream = conn.getInputStream(); StringBuilder sb = new StringBuilder(); int data = stream.read(); while (data != -1) { sb.append((char)data); data = stream.read(); } _reader.load(sb.toString()); _lastUpdate = System.currentTimeMillis(); } catch (Exception e) { e.printStackTrace(System.err); } finally { try { if (stream != null) stream.close(); } catch (IOException e) { e.printStackTrace(System.err); } finally { if (conn != null ) conn.disconnect(); } } } public boolean Supports(LocationSource source) { return true; } public double getDegreesCelcius() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "temp_C/text()"); Object val = _reader.read(xpath); return Double.parseDouble(val.toString()); } public double getDegressFahrienhiet() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "temp_F/text()"); Object val = _reader.read(xpath); return Double.parseDouble(val.toString()); } public double getWindSpeedMPH() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "windspeedMiles/text()"); Object val = _reader.read(xpath); return Double.parseDouble(val.toString()); } public double getWindSpeedKPH() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "windspeedKmph/text()"); Object val = _reader.read(xpath); return Double.parseDouble(val.toString()); } public Direction getWindDirection() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "winddir16Point/text()"); Object val = _reader.read(xpath); return Direction.valueOf(val.toString()); } public double getCloudCover() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "cloudcover/text()"); Object val = _reader.read(xpath); return Double.parseDouble(val.toString()); } public double getPercipitation() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "precipMM/text()"); Object val = _reader.read(xpath); return Double.parseDouble(val.toString()); } public double getHumidity() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "humidity/text()"); Object val = _reader.read(xpath); return Double.parseDouble(val.toString()); } public EnumSet<WeatherCondition> getConditions() { if (!isFresh()) { Update(); } String xpath = String.format(WWO_XPATH_HEADER, "weatherCode/text()"); Object val = _reader.read(xpath); WWOWeatherCode code = WWOWeatherCode.findByCode(Integer.parseInt(val.toString())); EnumSet<WeatherCondition> currentCondition = translateConditions(code); return currentCondition; } protected EnumSet<WeatherCondition> translateConditions(WWOWeatherCode code) { switch (code) { case Blizzard: return EnumSet.of(WeatherCondition.Blizzard, WeatherCondition.Snow); case BlowingSnow: return EnumSet.of(WeatherCondition.Blowing, WeatherCondition.Snow); case ClearSunny: return EnumSet.of(WeatherCondition.Clear); case Cloudy: return EnumSet.of(WeatherCondition.Cloudy); case Fog: return EnumSet.of(WeatherCondition.Fog); case FreezingDrizzle: return EnumSet.of(WeatherCondition.Freezing, WeatherCondition.Drizzle); case FreezingFog: return EnumSet.of(WeatherCondition.Freezing, WeatherCondition.Fog); case HeavyFreezingDrizzle: return EnumSet.of(WeatherCondition.Heavy, WeatherCondition.Freezing, WeatherCondition.Drizzle); case HeavyRain: return EnumSet.of(WeatherCondition.Heavy, WeatherCondition.Rain); case HeavySnow: return EnumSet.of(WeatherCondition.Heavy, WeatherCondition.Snow); case IcePellets: return EnumSet.of(WeatherCondition.Ice, WeatherCondition.Pellets); case LightDrizzle: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Drizzle); case LightFreezingRain: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Freezing, WeatherCondition.Rain); case LightIcePellets: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Ice, WeatherCondition.Pellets); case LightRain: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Rain); case LightRainShower: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Rain, WeatherCondition.Showers); case LightSleet: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Sleet); case LightSleetShowers: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Sleet, WeatherCondition.Showers); case LightSnow: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Snow); case LightSnowShowers: return EnumSet.of(WeatherCondition.Light, WeatherCondition.Snow, WeatherCondition.Showers); case Mist: return EnumSet.of(WeatherCondition.Mist); case ModerateOrHeavyFreezingRain: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Freezing, WeatherCondition.Rain); case ModerateOrHeavyIcePellets: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Ice, WeatherCondition.Pellets); case ModerateOrHeavyRainAndThunder: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Rain, WeatherCondition.Thunder); case ModerateOrHeavyRainShowers: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Rain, WeatherCondition.Showers); case ModerateOrHeavySleet: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Sleet); case ModerateOrHeavySleetshowers: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Sleet, WeatherCondition.Showers); case ModerateOrHeavySnowShowers: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Snow, WeatherCondition.Showers); case ModerateOrHeavySnowWithThunder: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Heavy, WeatherCondition.Snow, WeatherCondition.Thunder); case ModerateRain: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Rain); case ModerateSnow: return EnumSet.of(WeatherCondition.Moderate, WeatherCondition.Snow); case Overcast: return EnumSet.of(WeatherCondition.Overcast); case PartlyCloudy: return EnumSet.of(WeatherCondition.PartlyCloudy); case PatchyFreezingDrizzleNearby: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Freezing, WeatherCondition.Drizzle); case PatchyHeavyRain: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Heavy, WeatherCondition.Rain); case PatchyHeavySnow: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Heavy, WeatherCondition.Snow); case PatchyLightDrizzle: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Light, WeatherCondition.Drizzle); case PatchyLightRain: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Light, WeatherCondition.Rain); case PatchyLightRainAndThunder: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Light, WeatherCondition.Rain, WeatherCondition.Thunder); case PatchyLightSnow: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Light, WeatherCondition.Snow); case PatchyLightSnowWithThunder: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Light, WeatherCondition.Snow, WeatherCondition.Thunder); case PatchyModerateRain: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Moderate, WeatherCondition.Rain); case PatchyModerateSnow: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Moderate, WeatherCondition.Snow); case PatchyRainNearby: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Rain); case PatchySleetNearby: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Sleet); case PatchySnowNearby: return EnumSet.of(WeatherCondition.Patchy, WeatherCondition.Snow); case ThunderyOutbreaksInNearby: return EnumSet.of(WeatherCondition.Thunder); case TorrentialRainShowers: return EnumSet.of(WeatherCondition.Torrential, WeatherCondition.Rain, WeatherCondition.Showers); default: return EnumSet.of(WeatherCondition.Clear); } } }
package br.com.caelum.vraptor.ioc.cdi; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.enterprise.inject.Default; import javax.servlet.ServletContext; import br.com.caelum.vraptor.ioc.ComponentFactory; @ApplicationScoped public class ServletContextFactory implements ComponentFactory<ServletContext>{ private ServletContext context; public void observesContext(@Observes ServletContext context){ this.context = context; } @ApplicationScoped @Default @VraptorPreference public ServletContext getInstance(){ return this.context; } }
package com.mgnt.lifecycle.management.httpclient; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import com.mgnt.utils.TextUtils; import com.mgnt.utils.WebUtils; import com.mgnt.utils.entities.TimeInterval; /** * This class is meant to be a parent class to any class that wants to implement an http access to a particular * cite. In this case the extending class may inherit from this class, set a predefined {@link #connectionUrl} property * and then simply add some methods that would be used to contact some different sub-urls with the same url base. Those * methods may receive some parameters that would enable to build final url based on pre-set base url. However this * class may be used on its own as well. All you will need to do is to set a value for content type using method * {@link #setContentType(String)} if needed, or/and any other request header using method * {@link #setRequestHeader(String, String)} and then just call method {@link #sendHttpRequest(String, HttpMethod)} * or {@link #sendHttpRequest(String, HttpMethod, String)} (or if the reply is expected to be binary such as image then * call the methods {@link #sendHttpRequestForBinaryResponse(String, HttpMethod)} or * {@link #sendHttpRequestForBinaryResponse(String, HttpMethod, String)}) */ public class HttpClient { private static final String CONTENT_TYPE_HEADER_KEY = "Content-Type"; private Map<String, String> requestPropertiesMap = new HashMap<>(); private String connectionUrl; private int lastResponseCode = -1; private String lastResponseMessage = null; private Map<String, List<String>> lastResponseHeaders = null; private TimeInterval connectTimeout = new TimeInterval(0, TimeUnit.MILLISECONDS); private TimeInterval readTimeout = new TimeInterval(0, TimeUnit.MILLISECONDS); /** * This method is a getter for connectionUrl property which only makes sense if that property was set. Setting * this property is intended for extending classes if such class provides several methods contacting urls based on * the same base url. In this case building the final url for each such method can use base url that is common for * them * @return String that holds common URL prefix */ public String getConnectionUrl() { return connectionUrl; } /** * Setter for connectionUrl property. This method is intended for use by extending classes if they provide methods * that contact URLs that have common prefix * @param connectionUrl */ public void setConnectionUrl(String connectionUrl) { this.connectionUrl = connectionUrl; } /** * This method sends HTTP request to pre-set URL. It uses method {@link #getConnectionUrl()} to get the URL and uses * specified HTTP method. Obviously it is expected that user should set connectionUrl property by invoking method * {@link #setConnectionUrl(String)} beforehand. It returns response * that is expected to be textual such as a String. This method does not send any info through request body. * It may send parameters through URL. So this method fits perfectly for using HTTP GET method. If HTTP request * uses method POST, PUT or any other methods that allow passing info in the request body and there is some info * to be sent then use method {@link #sendHttpRequest(HttpMethod, String)} * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @return String that holds response from the URL * @throws IOException */ public String sendHttpRequest(HttpMethod callMethod) throws IOException { return sendHttpRequest(getConnectionUrl(), callMethod, (String)null); } /** * This method sends HTTP request to specified URL and uses specified HTTP method. It returns response * that is expected to be textual such as a String. This method does not send any info through request body. * It may send parameters through URL. So this method fits perfectly for using HTTP GET method. If HTTP request * uses method POST, PUT or any other methods that allow passing info in the request body and there is some info * to be sent then use method {@link #sendHttpRequest(String, HttpMethod, String)} * @param requestUrl URL to which request is to be sent * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @return String that holds response from the URL * @throws IOException */ public String sendHttpRequest(String requestUrl, HttpMethod callMethod) throws IOException { return sendHttpRequest(requestUrl, callMethod, (String)null); } /** * This method sends HTTP request to pre-set URL. It uses method {@link #getConnectionUrl()} to get the URL and uses * specified HTTP method and sends data through request body. Obviously it is expected that user should set connectionUrl * property by invoking method {@link #setConnectionUrl(String)} beforehand. * It returns response that is expected to be textual such as a String. This method fits for using HTTP methods * POST, PUT or any other methods that allow passing info in the request body and there is some info to be sent. * If you don't need to send any info as request body, consider using method * {@link #sendHttpRequest(HttpMethod)} * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data String that holds the data to be sent as request body * @return String that holds response from the URL * @throws IOException */ public String sendHttpRequest(HttpMethod callMethod, String data) throws IOException { return sendHttpRequest(getConnectionUrl(), callMethod, data); } /** * This method sends HTTP request to pre-set URL. It uses method {@link #getConnectionUrl()} to get the URL and uses * specified HTTP method and sends binary data through request body. Obviously it is expected that user should set connectionUrl * property by invoking method {@link #setConnectionUrl(String)} beforehand. * It returns response that is expected to be textual such as a String. This method fits for using HTTP methods * POST, PUT or any other methods that allow passing info in the request body and there is some binary info to be sent. * This method is useful for uploading files or any other binary info * If you don't need to send any info as request body, consider using method * {@link #sendHttpRequest(HttpMethod)} * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data ByteBuffer that holds the binary data to be sent as request body * @return String that holds response from the URL * @throws IOException */ public String sendHttpRequest(HttpMethod callMethod, ByteBuffer data) throws IOException { return sendHttpRequest(getConnectionUrl(), callMethod, data); } /** * This method sends HTTP request to specified URL, uses specified HTTP method and sends data through request body. * It returns response that is expected to be textual such as a String. This method fits for using HTTP methods * POST, PUT or any other methods that allow passing info in the request body and there is some info to be sent. * If you don't need to send any info as request body, consider using method * {@link #sendHttpRequest(String, HttpMethod)} * @param requestUrl URL to which request is to be sent * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data String that holds the data to be sent as request body * @return String that holds response from the URL * @throws IOException */ public String sendHttpRequest(String requestUrl, HttpMethod callMethod, String data) throws IOException { String response; HttpURLConnection connection = sendRequest(requestUrl, callMethod, data); setLastResponseCode(connection.getResponseCode()); setLastResponseMessage(connection.getResponseMessage()); setLastResponseHeaders(connection.getHeaderFields()); try { response = readResponse(connection); } catch (IOException ioe) { throw new IOException("HTTP " + getLastResponseCode() + " " + getLastResponseMessage() + " (" + ioe.getMessage() + ")", ioe); } finally { connection.disconnect(); } return response; } /** * This method sends HTTP request to specified URL, uses specified HTTP method and sends binary data through request body. * It returns response that is expected to be textual such as a String. This method fits for using HTTP methods * POST, PUT or any other methods that allow passing info in the request body and there is some binary info to be sent. * This method is useful for uploading files Image, Video, Audio or any other binary info * If you don't need to send any info as request body, consider using method * {@link #sendHttpRequest(String, HttpMethod)} * @param requestUrl URL to which request is to be sent * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data String that holds the data to be sent as request body * @return String that holds response from the URL * @throws IOException */ public String sendHttpRequest(String requestUrl, HttpMethod callMethod, ByteBuffer data) throws IOException { String response; HttpURLConnection connection = sendRequest(requestUrl, callMethod, data); setLastResponseCode(connection.getResponseCode()); setLastResponseMessage(connection.getResponseMessage()); setLastResponseHeaders(connection.getHeaderFields()); try { response = readResponse(connection); } catch (IOException ioe) { throw new IOException("HTTP " + getLastResponseCode() + " " + getLastResponseMessage() + " (" + ioe.getMessage() + ")", ioe); } finally { connection.disconnect(); } return response; } /** * This method sends HTTP request to pre-set URL. It uses method {@link #getConnectionUrl()} to get the URL and uses * specified HTTP method. Obviously it is expected that user should set connectionUrl property by invoking method * {@link #setConnectionUrl(String)} beforehand. * This method is the same as {@link #sendHttpRequest(HttpMethod)} except that it returns {@link ByteBuffer} * that holds binary info. So this methods fits for retrieving binary response such as Image, Video, Audio or any * other info in binary format. * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @return {@link ByteBuffer} that holds response from URL * @throws IOException */ public ByteBuffer sendHttpRequestForBinaryResponse(HttpMethod callMethod) throws IOException { return sendHttpRequestForBinaryResponse(getConnectionUrl(), callMethod, (String)null); } /** * This method is the same as {@link #sendHttpRequest(String, HttpMethod)} except that it returns {@link ByteBuffer} * that holds binary info. So this methods fits for retrieving binary response such as Image, Video, Audio or any * other info in binary format. * @param requestUrl URL to which request is to be sent * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @return {@link ByteBuffer} that holds response from URL * @throws IOException */ public ByteBuffer sendHttpRequestForBinaryResponse(String requestUrl, HttpMethod callMethod) throws IOException { return sendHttpRequestForBinaryResponse(requestUrl, callMethod, (String)null); } /** * This method sends HTTP request to pre-set URL. It uses method {@link #getConnectionUrl()} to get the URL and uses * specified HTTP method. Obviously it is expected that user should set connectionUrl property by invoking method * {@link #setConnectionUrl(String)} beforehand. * This method is the same as {@link #sendHttpRequest(HttpMethod, String)} except that it returns * {@link ByteBuffer} that holds binary info. So this methods fits for retrieving binary response such as Image, * Video, Audio or any other info in binary format. * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data String that holds the data to be sent as request body * @return {@link ByteBuffer} that holds response from URL * @throws IOException */ public ByteBuffer sendHttpRequestForBinaryResponse(HttpMethod callMethod, String data) throws IOException { return sendHttpRequestForBinaryResponse(getConnectionUrl(),callMethod, data); } /** * This method sends HTTP request to pre-set URL. It uses method {@link #getConnectionUrl()} to get the URL and uses * specified HTTP method. Obviously it is expected that user should set connectionUrl property by invoking method * {@link #setConnectionUrl(String)} beforehand. * This method is the same as {@link #sendHttpRequest(HttpMethod, ByteBuffer)} except that it returns * {@link ByteBuffer} that holds binary info. So this method fits for sending binary info such as Image, * Video, Audio or any other info in binary format. and then retrieving binary response as well. So this method * might be a good fit for consuming API that receives and returns binary info possibly for modifying images or * binary files such as adding a watermark to an Image for example * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data ByteArray that holds some binary data to be sent as request body * @return {@link ByteBuffer} that holds response from URL * @throws IOException */ public ByteBuffer sendHttpRequestForBinaryResponse(HttpMethod callMethod, ByteBuffer data) throws IOException { return sendHttpRequestForBinaryResponse(getConnectionUrl(),callMethod, data); } /** * This method is the same as {@link #sendHttpRequest(String, HttpMethod, String)} except that it returns * {@link ByteBuffer} that holds binary info. So this methods fits for retrieving binary response such as Image, * Video, Audio or any other info in binary format. * @param requestUrl URL to which request is to be sent * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data String that holds the data to be sent as request body * @return {@link ByteBuffer} that holds response from URL * @throws IOException */ public ByteBuffer sendHttpRequestForBinaryResponse(String requestUrl, HttpMethod callMethod, String data) throws IOException { ByteBuffer response; HttpURLConnection connection = sendRequest(requestUrl, callMethod, data); setLastResponseCode(connection.getResponseCode()); setLastResponseMessage(connection.getResponseMessage()); setLastResponseHeaders(connection.getHeaderFields()); try { response = readBinaryResponse(connection); } catch (IOException ioe) { throw new IOException("HTTP " + getLastResponseCode() + " " + getLastResponseMessage() + " (" + ioe.getMessage() + ")", ioe); } finally { connection.disconnect(); } return response; } /** * This method is the same as {@link #sendHttpRequest(String, HttpMethod, ByteBuffer)} except that it returns * {@link ByteBuffer} that holds binary info. So this method fits for sending binary info such as Image, * Video, Audio or any other info in binary format. and then retrieving binary response as well. So this method * might be a good fit for consuming API that receives and returns binary info possibly for modifying images or * binary files such as adding a watermark to an Image for example * @param requestUrl URL to which request is to be sent * @param callMethod {@link HttpMethod} that specifies which HTTP method is to be used * @param data ByteBuffer that holds the data to be sent as request body * @return {@link ByteBuffer} that holds response from URL * @throws IOException */ public ByteBuffer sendHttpRequestForBinaryResponse(String requestUrl, HttpMethod callMethod, ByteBuffer data) throws IOException { ByteBuffer response; HttpURLConnection connection = sendRequest(requestUrl, callMethod, data); setLastResponseCode(connection.getResponseCode()); setLastResponseMessage(connection.getResponseMessage()); setLastResponseHeaders(connection.getHeaderFields()); try { response = readBinaryResponse(connection); } catch (IOException ioe) { throw new IOException("HTTP " + getLastResponseCode() + " " + getLastResponseMessage() + " (" + ioe.getMessage() + ")", ioe); } finally { connection.disconnect(); } return response; } /** * This is getter method for content type property. Returns default value if the property was not set. This * method intended for use in extending classes * @return content type property value or default value if the property was not set */ public String getContentType() { String contentType = requestPropertiesMap.get(CONTENT_TYPE_HEADER_KEY); if(StringUtils.isBlank(contentType)) { contentType = getDefaultContentType(); if(StringUtils.isNotBlank(contentType)) { requestPropertiesMap.put(CONTENT_TYPE_HEADER_KEY, contentType); } } return contentType; } /** * This method is a general request header setter. This method is deprecated due to wrong name. * Use method {@link #setRequestHeader(String, String)} instead * @param headerName if the value of header name is blank or null this method does nothing * @param headerValue Holds the value for the header * @See #setRequestHeader(String, String) */ @Deprecated public void setRequestProperty(String headerName, String headerValue) { setRequestHeader(headerName, headerValue); } /** * This method is a general request header setter. * @param headerName if the value of header name is blank or null this method does nothing * @param headerValue headerValue Holds the value for the header */ public void setRequestHeader(String headerName, String headerValue) { if(StringUtils.isNotBlank(headerName)) { requestPropertiesMap.put(headerName, headerValue); } } /** * This method removes request property * @param propertyName if the value of propertyName is blank or null this method does nothing and returns null * @return the value that has been removed or null if the propertyName key was not present in the properties */ public String removeRequestProperty(String propertyName) { String result = null; if(StringUtils.isNotBlank(propertyName)) { result = requestPropertiesMap.remove(propertyName); } return result; } /** * This method clears all request properties. */ public void clearAllRequestProperties() { requestPropertiesMap.clear(); } /** * This is setter method for content type property. This method intended for use in extending classes * @param contentType holds content type value */ public void setContentType(String contentType) { requestPropertiesMap.put(CONTENT_TYPE_HEADER_KEY, contentType); } /** * This method returns the status code from the last HTTP response message. If two or more separate requests * where executed this method returns the status code from the last response. The codes from previous responses are lost if they * were not read after the respective request was executed and before the next one is executed. This method returns -1 if no * request was executed yet by this instance of the class or response was't received. * @return the HTTP Status-Code, or -1 */ public int getLastResponseCode() { return lastResponseCode; } /** * This method returns the last HTTP response message. If two or more separate requests * where executed this method returns the HTTP response message from the last response. The messages from previous responses * are lost if they were not read after the respective request was executed and before the next one is executed. This method * returns null if no request was executed yet by this instance of the class or response was't received. * @return the HTTP response message, or null */ public String getLastResponseMessage() { return lastResponseMessage; } /** * This method returns header fields from last executed http request as unmodifiable map. If two or more separate requests * where executed this method returns header fields from the last response. The headers from previous responses * are lost if they were not read after the respective request was executed and before the next one is executed. This method * returns null if no request was executed yet by this instance of the class or response was't received. * @return An unmodifiable Map of Header fields of last response */ public Map<String, List<String>> getLastResponseHeaders() { return lastResponseHeaders; } /** * This method returns header fields names from last executed http request as unmodifiable set. If two or more separate requests * where executed this method returns header field names from the last response. The header names from previous responses * are lost if they were not read after the respective request was executed and before the next one is executed. This method * returns null if no request was executed yet by this instance of the class or response was't received. * @return An unmodifiable Set of Header field names of last response */ public Set<String> getLastResponseHeaderNames() { return (lastResponseHeaders != null) ? Collections.unmodifiableSet(lastResponseHeaders.keySet()) : null; } /** * This method returns the values of the header field by field name from last executed http request as unmodifiable list. * If two or more separate requests where executed this method returns header field value from the last response. The header * values from previous responses are lost if they were not read after the respective request was executed and before the * next one is executed. This method returns null if no request was executed yet by this instance of the class or response * was't received. * @param fieldName - the name of the header field to be retrieved * @return An unmodifiable list of values of the requested header field */ public List<String> getLastResponseHeader(String fieldName) { return (lastResponseHeaders != null && StringUtils.isNotBlank(fieldName)) ? Collections.unmodifiableList(lastResponseHeaders.get(fieldName)) : null; } /** * This method returns connection timeout currently in effect. The default value (if timeout was never set) is 0 which means * that the option is disabled (i.e., timeout of infinity). The timeout value remains in effect for all the following * connection requests until changed * @return returns current timeout value in {@link TimeInterval} */ public TimeInterval getConnectTimeout() { return connectTimeout; } /** * This method sets the connection timeout that will remain in effect for all subsequent connection requests until it is * changed by invocation of this or other connection timeout setter methods: {@link #setConnectTimeout(String)}, * {@link #setConnectTimeout(long, TimeUnit)} * @param connectTimeout */ public void setConnectTimeout(TimeInterval connectTimeout) { this.connectTimeout = connectTimeout; } public void setConnectTimeout(String timeIntervalStr) throws IllegalArgumentException { setConnectTimeout(TextUtils.parseStringToTimeInterval(timeIntervalStr)); } public void setConnectTimeout(long timeValue, TimeUnit timeUnit) throws IllegalArgumentException { if(timeValue < 0) { throw new IllegalArgumentException("Negative value for timeout"); } if(timeUnit == null) { throw new IllegalArgumentException("Null Time Unit value for timeout"); } setConnectTimeout(new TimeInterval(timeValue, timeUnit)); } /** * This method returns read timeout currently in effect. The default value (if timeout was never set) is 0 which means * that the option is disabled (i.e., timeout of infinity). The timeout value remains in effect for all the following * connection requests until changed * @return returns current timeout value in {@link TimeInterval} */ public TimeInterval getReadTimeout() { return readTimeout; } /** * This method sets the read timeout that will remain in effect for all subsequent connection requests until it is * changed by invocation of this or other read timeout setter methods: {@link #setReadTimeout(String)}, * {@link #setReadTimeout(long, TimeUnit)} * @param readTimeout */ public void setReadTimeout(TimeInterval readTimeout) { this.readTimeout = readTimeout; } public void setReadTimeout(String timeIntervalStr) throws IllegalArgumentException { setReadTimeout(TextUtils.parseStringToTimeInterval(timeIntervalStr)); } public void setReadTimeout(long timeValue, TimeUnit timeUnit) throws IllegalArgumentException { if(timeValue < 0) { throw new IllegalArgumentException("Negative value for timeout"); } if(timeUnit == null) { throw new IllegalArgumentException("Null Time Unit value for timeout"); } setReadTimeout(new TimeInterval(timeValue, timeUnit)); } /** * This method creates and opens {@link HttpURLConnection} to specified URL The connection's property * doOutput is set to false * @param url Url to be connected to * @param method {@link HttpMethod} that specifies which HTTP Method to use * @return opened {@link HttpURLConnection} * @throws IOException */ protected HttpURLConnection openHttpUrlConnection(String url, HttpMethod method) throws IOException { return openHttpUrlConnection(url, method, false); } /** * This method creates and opens {@link HttpURLConnection} to specified URL. * @param url Url to be connected to * @param method {@link HttpMethod} that specifies which HTTP Method to use * @param doOutput boolean value that specifies how to set connection's doOutput property * @return opened {@link HttpURLConnection} * @throws IOException */ protected HttpURLConnection openHttpUrlConnection(String url, HttpMethod method, boolean doOutput) throws IOException { URL requestUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection(); setConnectionTimeout(connection); setReadTimeout(connection); connection.setDoOutput(doOutput); connection.setRequestMethod(method.toString()); for(String requestProperty : requestPropertiesMap.keySet()) { connection.setRequestProperty(requestProperty, requestPropertiesMap.get(requestProperty)); } return connection; } /** * This method is intended to be overridden by extending classes if those classes provide methods that send * requests with the same content type * @return default content type (See {@link #getContentType()}) */ protected String getDefaultContentType() { return null; } private void setLastResponseCode(int lastResponseCode) { this.lastResponseCode = lastResponseCode; } private void setLastResponseMessage(String lastResponseMessage) { this.lastResponseMessage = lastResponseMessage; } private void setLastResponseHeaders(Map<String, List<String>> lastResponseHeaders) { this.lastResponseHeaders = lastResponseHeaders; } /** * This method reads response from {@link HttpURLConnection} expecting response to be in Textual format * @param connection {@link HttpURLConnection} from which to read the response * @return String that holds the response * @throws IOException */ private String readResponse(HttpURLConnection connection) throws IOException { String response = ""; try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { response = doReadResponse(br); } catch(IOException ioe) { InputStream errorInputStream = connection.getErrorStream(); if(errorInputStream == null) { throw ioe; } else { BufferedReader br = new BufferedReader(new InputStreamReader(errorInputStream, StandardCharsets.UTF_8)); response = doReadResponse(br); } } return response; } /** * This method reads response from {@link BufferedReader} that wraps an {@link InputStream} obtained from the server. * @param br {@link BufferedReader} that wraps an {@link InputStream} obtained from the server * @return read content as a {@link String} * @throws IOException */ private String doReadResponse(BufferedReader br) throws IOException { String response; StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } response = sb.toString(); return response; } /** * This method reads response from {@link HttpURLConnection} and returns it in raw binary format * @param connection {@link HttpURLConnection} from which to read the response * @return {@link ByteBuffer} that contains the response * @throws IOException */ private ByteBuffer readBinaryResponse(HttpURLConnection connection) throws IOException { List<ByteBuffer> content = new LinkedList<>(); int totalLength = 0; try (InputStream is = connection.getInputStream()) { while(true) { byte[] buff = new byte[WebUtils.DEFAULT_BUFFER_SIZE]; int length = is.read(buff); if(length >= 0) { content.add(ByteBuffer.wrap(buff, 0, length)); totalLength += length; } else { break; } } } ByteBuffer result = ByteBuffer.allocate(totalLength); for(ByteBuffer byteBuffer : content) { result.put(byteBuffer); } return result; } /** * This method sends the HTTP request and returns opened {@link HttpURLConnection}. If <b><i>data</i></b> * parameter is not null or empty it sends it as request body content * @param url URL to which request is sent * @param method {@link HttpMethod} that specifies which HTTP Method to use * @param data request body content. May be <b>NULL</b> if no request body needs to be sent * @return open {@link HttpURLConnection} * @throws IOException */ private HttpURLConnection sendRequest(String url, HttpMethod method, String data) throws IOException { ByteBuffer dataBuffer = (StringUtils.isNotBlank(data)) ? StandardCharsets.UTF_8.encode(data) : null; return sendRequest(url, method, dataBuffer); } private HttpURLConnection sendRequest(String url, HttpMethod method, ByteBuffer data) throws IOException { boolean doOutput = (data != null && data.hasArray()); HttpURLConnection httpURLConnection = openHttpUrlConnection(url, method, doOutput); if (doOutput) { try (DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream())) { dataOutputStream.write(data.array()); dataOutputStream.flush(); } } return httpURLConnection; } private HttpURLConnection setConnectionTimeout(HttpURLConnection connection) { int connectionTimeoutMs = Long.valueOf((getConnectTimeout().toMillis())).intValue(); if(connectionTimeoutMs >= 0L) { connection.setConnectTimeout(connectionTimeoutMs); } return connection; } private HttpURLConnection setReadTimeout(HttpURLConnection connection) { int readTimeoutMs = Long.valueOf((getReadTimeout().toMillis())).intValue(); if(readTimeoutMs >= 0L) { connection.setReadTimeout(readTimeoutMs); } return connection; } public static enum HttpMethod { GET, PUT, POST, DELETE, HEAD, OPTIONS, TRACE } }
package com.midori.confluence.plugin.mail2news; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Address; import javax.mail.AuthenticationFailedException; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.FolderNotFoundException; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import com.atlassian.confluence.pages.Attachment; import com.atlassian.confluence.pages.AttachmentManager; import com.atlassian.confluence.pages.BlogPost; import com.atlassian.confluence.pages.PageManager; import com.atlassian.confluence.spaces.Space; import com.atlassian.confluence.spaces.SpaceManager; import com.atlassian.confluence.user.AuthenticatedUserThreadLocal; import com.atlassian.confluence.user.UserAccessor; import com.atlassian.mail.MailFactory; import com.atlassian.mail.server.SMTPMailServer; import com.atlassian.quartz.jobs.AbstractJob; import com.atlassian.spring.container.ContainerManager; import com.atlassian.user.User; import com.atlassian.user.search.SearchResult; import com.atlassian.user.search.page.Pager; public class Mail2NewsJob extends AbstractJob { /** * The log to which we will be logging infos and errors. */ protected final Logger log = Logger.getLogger(this.getClass()); /** * The page manager of this Confluence instance */ private PageManager pageManager; /** * The space manager of this Confluence instance */ private SpaceManager spaceManager; /** * The attachment manager of this Confluence instance */ private AttachmentManager attachmentManager; /** * The user accessor of this Confluence instance, used to find * users. */ private UserAccessor userAccessor; /** * The configuration manager of this plugin which contains * the settings of this plugin (e.g. login credentials for * the email account which is monitored). */ private ConfigurationManager configurationManager; /** * The content of a message, this will be the content of the * news entry */ private String blogEntryContent; /** * A list of attachments, used when examining a new message */ private LinkedList attachments; /** * A list of input streams for the attachments. */ private LinkedList attachmentsInputStreams; /** * A flag indicating whether the current post contains an image */ private boolean containsImage; /** * The default constructor. Autowires this component and creates a * new configuration manager. */ public Mail2NewsJob() { /* autowire this component (this means that the space and * page manager are automatically set by confluence */ ContainerManager.autowireComponent(this); /* create the configuration manager */ this.configurationManager = new ConfigurationManager(); } /** * The main method of this job. Called by confluence every time the mail2news trigger * fires. * * @see com.atlassian.quartz.jobs.AbstractJob#doExecute(org.quartz.JobExecutionContext) */ public void doExecute(JobExecutionContext arg0) throws JobExecutionException { /* The mailstore object used to connect to the server */ Store store = null; try { this.log.info("Executing mail2news plugin."); /* check if we have all necessary components */ if (pageManager == null) { throw new Exception("Null PageManager instance."); } if (spaceManager == null) { throw new Exception("Null SpaceManager instance."); } if (configurationManager == null) { throw new Exception("Null ConfigurationManager instance."); } /* get the mail configuration from the manager */ MailConfiguration config = configurationManager.getMailConfiguration(); if (config == null) { throw new Exception("Null MailConfiguration instance."); } /* create the properties for the session */ Properties prop = new Properties(); /* get the protocol to use */ if (config.getProtocol() == null) { throw new Exception("Cannot get protocol."); } String protocol = config.getProtocol().toLowerCase().concat(config.getSecure() ? "s" : ""); /* assemble the property prefix for this protocol */ String propertyPrefix = "mail."; propertyPrefix = propertyPrefix.concat(protocol).concat("."); /* get the server port from the configuration and add it to the properties, * but only if it is actually set. If port = 0 this means we use the standard * port for the chosen protocol */ int port = config.getPort(); if (port != 0) { prop.setProperty(propertyPrefix.concat("port"), "" + port); } /* set connection timeout (10 seconds) */ prop.setProperty(propertyPrefix.concat("connectiontimeout"), "10000"); /* get the session for connecting to the mail server */ Session session = Session.getInstance(prop, null); /* get the mail store, using the desired protocol */ if (config.getSecure()) { store = session.getStore(protocol); } else { store = session.getStore(protocol); } /* get the host and credentials for the mail server from the configuration */ String host = config.getServer(); String username = config.getUsername(); String password = config.getPassword(); /* sanity check */ if (host == null || username == null || password == null) { throw new Exception("Incomplete mail configuration settings (at least one setting is null)."); } /* connect to the mailstore */ try { store.connect(host, username, password); } catch (AuthenticationFailedException afe) { throw new Exception("Authentication for mail store failed: " + afe.getMessage(), afe); } catch (MessagingException me) { throw new Exception("Connecting to mail store failed: " + me.getMessage(), me); } catch (IllegalStateException ise) { throw new Exception("Connecting to mail store failed, already connected: " + ise.getMessage(), ise); } catch (Exception e) { throw new Exception("Connecting to mail store failed, general exception: " + e.getMessage(), e); } /* get the INBOX folder */ Folder folderInbox = store.getFolder("INBOX"); /* we need to open it READ_WRITE, because we want to move messages we already handled */ try { folderInbox.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find INBOX folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open INBOX folder: " + e.getMessage(), e); } /* here we have to split, because IMAP will be handled differently from POP3 */ if (config.getProtocol().toLowerCase().equals("imap")) { Folder folderDefault = null; try { folderDefault = store.getDefaultFolder(); } catch (MessagingException me) { throw new Exception("Could not get default folder: " + me.getMessage(), me); } /* sanity check */ try { if (!folderDefault.exists()) { throw new Exception("Default folder does not exist. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author."); } } catch (MessagingException me) { throw new Exception("Could not test existence of the default folder: " + me.getMessage(), me); } /** * This is kind of a fallback mechanism. For some reasons it can happen that * the default folder has an empty name and exists() returns true, but when * trying to create a subfolder it generates an error message. * So what we do here is if the name of the default folder is empty, we * look for the "INBOX" folder, which has to exist and then create the * subfolders under this folder. */ if (folderDefault.getName().equals("")) { this.log.warn("Default folder has empty name. Looking for 'INBOX' folder as root folder."); folderDefault = store.getFolder("INBOX"); if (!folderDefault.exists()) { throw new Exception("Could not find default folder and could not find 'INBOX' folder. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author."); } } /* get the folder where we store processed messages */ Folder folderProcessed = folderDefault.getFolder("Processed"); /* check if it exists */ if (!folderProcessed.exists()) { /* does not exist, create it */ try { if (!folderProcessed.create(Folder.HOLDS_MESSAGES)) { throw new Exception("Creating 'processed' folder failed."); } } catch (MessagingException me) { throw new Exception("Could not create 'processed' folder: " + me.getMessage(), me); } } /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */ try { folderProcessed.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find 'processed' folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open 'processed' folder: " + e.getMessage(), e); } /* get the folder where we store invalid messages */ Folder folderInvalid = folderDefault.getFolder("Invalid"); /* check if it exists */ if (!folderInvalid.exists()) { /* does not exist, create it */ try { if (!folderInvalid.create(Folder.HOLDS_MESSAGES)) { throw new Exception("Creating 'invalid' folder failed."); } } catch (MessagingException me) { throw new Exception("Could not create 'invalid' folder: " + me.getMessage(), me); } } /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */ try { folderInvalid.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find 'invalid' folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open 'invalid' folder: " + e.getMessage(), e); } /* get all messages in the INBOX */ Message message[] = folderInbox.getMessages(); /* go through all messages and get the unseen ones (all should be unseen, * as the seen ones get moved to a different folder */ for (int i = 0; i < message.length; i++) { if (message[i].isSet(Flags.Flag.SEEN)) { /* this message has been seen, should not happen */ /* send email to the sender */ sendErrorMessage(message[i], "This message has already been flagged as seen before being handled and was thus ignored."); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } Space space = null; try { space = getSpaceFromAddress(message[i]); } catch (Exception e) { this.log.error("Could not get space from message: " + e.getMessage()); /* send email to the sender */ sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } /* initialise content and attachments */ blogEntryContent = null; attachments = new LinkedList(); attachmentsInputStreams = new LinkedList(); containsImage = false; /* get the content of this message */ try { Object content = message[i].getContent(); if (content instanceof Multipart) { handleMultipart((Multipart)content); } else { handlePart(message[i]); } } catch (Exception e) { this.log.error("Error while getting content of message: " + e.getMessage(), e); /* send email to the sender */ sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } try { createBlogPost(space, message[i]); } catch (MessagingException me) { this.log.error("Error while creating blog post: " + me.getMessage(), me); /* send email to sender */ sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } /* move the message to the processed folder */ moveMessage(message[i], folderInbox, folderProcessed); } /* close the folders, expunging deleted messages in the process */ folderInbox.close(true); folderProcessed.close(true); folderInvalid.close(true); /* close the store */ store.close(); } else if (config.getProtocol().toLowerCase().equals("pop3")) { /* get all messages in this POP3 account */ Message message[] = folderInbox.getMessages(); /* go through all messages */ for (int i = 0; i < message.length; i++) { Space space = null; try { space = getSpaceFromAddress(message[i]); } catch (Exception e) { this.log.error("Could not get space from message: " + e.getMessage()); /* send email to the sender */ sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } /* initialise content and attachments */ blogEntryContent = null; attachments = new LinkedList(); attachmentsInputStreams = new LinkedList(); containsImage = false; /* get the content of this message */ try { Object content = message[i].getContent(); if (content instanceof Multipart) { handleMultipart((Multipart)content); } else { handlePart(message[i]); } } catch (Exception e) { this.log.error("Error while getting content of message: " + e.getMessage(), e); /* send email to the sender */ sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } try { createBlogPost(space, message[i]); } catch (MessagingException me) { this.log.error("Error while creating blog post: " + me.getMessage(), me); /* send email to the sender */ sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } /* finished processing this message, delete it */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ } /* close the pop3 folder, deleting all messages flagged as DELETED */ folderInbox.close(true); /* close the mail store */ store.close(); } else { throw new Exception("Unknown protocol: " + config.getProtocol()); } } catch (Exception e) { /* catch any exception which was not handled so far */ this.log.error("Error while executing mail2news job: " + e.getMessage(), e); JobExecutionException jee = new JobExecutionException("Error while executing mail2news job: " + e.getMessage(), e, false); throw jee; } finally { /* try to do some cleanup */ try { store.close(); } catch (Exception e) {} } } /** * Send an mail containing the error message back to the * user which sent the given message. * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception // FIXME this method should use the higher level email sending facilities in confluence instead of this low level approach { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if(smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } if(smtpMailServer.getHostname() == null) { log.warn("Failed to send error message as JNDI bound SMTP servers are not supported (JNDI location:<" + smtpMailServer.getJndiLocation() + ">)"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if(StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); } /** * Move a given message from one IMAP folder to another. It will be flagged as DELETED * in the originating folder and thus be deleted the next time EXPUNGE is called. * * @param m The message to be moved. * @param from The folder from which the message has to be moved. * @param to The folder to where to move the message. */ private void moveMessage(Message m, Folder from, Folder to) { try { /* copy the message to the destination folder */ from.copyMessages(new Message[] {m}, to); /* delete the message from the originating folder */ /* this sets the DELETED flag, the message will be deleted * when expunging the folder */ m.setFlag(Flags.Flag.DELETED, true); } catch (Exception e) { this.log.error("Could not copy message: " + e.getMessage(), e); try { /* cannot move the message. mark it read so we will not look at it again */ m.setFlag(Flags.Flag.SEEN, true); } catch (MessagingException me) { /* could not set SEEN on the message */ this.log.error("Could not set SEEN on message.", me); } } } /** * Handle a multipart of a email message. May recursively call handleMultipart or * handlePart. * * @param multipart The multipart to handle. * @throws MessagingException * @throws IOException */ private void handleMultipart(Multipart multipart) throws MessagingException, IOException { for (int i = 0, n = multipart.getCount(); i < n; i++) { Part p = multipart.getBodyPart(i); if (p instanceof Multipart) { handleMultipart((Multipart)p); } else { handlePart(multipart.getBodyPart(i)); } } } /** * Handle a part of a email message. This is either displayable text or some MIME * attachment. * * @param part The part to handle. * @throws MessagingException * @throws IOException */ private void handlePart(Part part) throws MessagingException, IOException { /* get the content type of this part */ String contentType = part.getContentType(); if (part.getContent() instanceof Multipart) { handleMultipart((Multipart)part.getContent()); return; } log.debug("Content-Type: " + contentType); /* check if the content is printable */ if (contentType.toLowerCase().startsWith("text/plain") && blogEntryContent == null) { /* get the charset */ Charset charset = getCharsetFromHeader(contentType); /* set the blog entry content to this content */ blogEntryContent = ""; InputStream is = part.getInputStream(); BufferedReader br = null; if (charset != null) { br = new BufferedReader(new InputStreamReader(is, charset)); } else { br = new BufferedReader(new InputStreamReader(is)); } String currentLine = null; while ((currentLine = br.readLine()) != null) { blogEntryContent = blogEntryContent.concat(currentLine).concat("\r\n"); } } else { /* the content is not text, so we assume it is some sort of MIME attachment */ try { /* get the filename */ String fileName = part.getFileName(); /* no filename, ignore this part */ if (fileName == null) { this.log.warn("Attachment with no filename. Ignoring."); return; } /* retrieve an input stream to the attachment */ InputStream is = part.getInputStream(); /* clean-up the content type (only the part before the first ';' is relevant) */ if (contentType.indexOf(';') != -1) { contentType = contentType.substring(0, contentType.indexOf(';')); } if (contentType.toLowerCase().indexOf("image") != -1) { /* this post contains an image as attachment, add the gallery macro to the blog post */ containsImage = true; } ByteArrayInputStream bais = null; byte[] attachment = null; /* put the attachment into a byte array */ try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int numBytes; while(true) { numBytes = is.read(buf); if (numBytes > 0) { baos.write(buf, 0, numBytes); } else { /* end of stream reached */ break; } } /* create a new input stream */ attachment = baos.toByteArray(); bais = new ByteArrayInputStream(attachment); //this.log.info("Attachment size: " + attachment.length); } catch (Exception e) { this.log.error("Could not load attachment:" + e.getMessage(), e); /* skip this attachment */ throw e; } /* create a new attachment */ Attachment a = new Attachment(fileName, contentType, attachment.length, "Attachment added by mail2news"); Date d = new Date(); a.setCreationDate(d); a.setLastModificationDate(d); /* add the attachment and the input stream to the attachment to the list * of attachments of the current blog entry */ attachments.addLast(a); attachmentsInputStreams.addLast(bais); } catch (Exception e) { this.log.error("Error while saving attachment: " + e.getMessage(), e); } } } /** * Get the charset listed in a "Content-Type" header. * @param contentType The "Content-Type" header. * @return Returns the used charset or null if no information is found. */ private Charset getCharsetFromHeader(String contentType) { StringTokenizer tok = new StringTokenizer(contentType, ";"); while (tok.hasMoreTokens()) { String token = tok.nextToken().trim(); if (token.toLowerCase().startsWith("charset")) { if (token.indexOf('=') != -1) { String charsetString = token.substring(token.indexOf('=')+1); try { Charset characterSet = Charset.forName(charsetString); return characterSet; } catch (Exception e) { log.warn("Unsupported charset in email content (" + charsetString + "). Some characters may be wrong."); return null; } } } } return null; } /** * Get the space key and subsequently the space from the recipient * email address. * The space key is extracted in the form "email+spacekey@domain.net". If the email * address does not contain a "+spacekey", then the application tests if it can * find a spacekey which is equivalent to the local part of the email address. * * @param message The mail message from which to extract the space key. * @return Returns the space * @throws Exception Throws an exception if the space key cannot be extracted or the space cannot be found. */ private Space getSpaceFromAddress(Message message) throws Exception { /* list for deferred space keys (see below) */ List<Space> deferredSpaceKeys = new LinkedList<Space>(); /* get the To: email addresses */ Address[] recipientTo = message.getRecipients(Message.RecipientType.TO); /* get the CC: email addresses */ Address[] recipientCc = message.getRecipients(Message.RecipientType.CC); /* merge To and CC addresses into one array */ if (recipientTo == null) // FIXME this should be seriously rewritten { recipientTo = new Address[0]; } if (recipientCc == null) { recipientCc = new Address[0]; } Address[] recipient = new Address[recipientTo.length + recipientCc.length]; System.arraycopy(recipientTo, 0, recipient, 0, recipientTo.length); System.arraycopy(recipientCc, 0, recipient, recipientTo.length, recipientCc.length); /* check if we have any address */ if (recipient.length == 0) { /* no recipient */ this.log.error("No recipient found in email."); /* throw an error */ throw new Exception("No recipient found in email."); } /* loop through all addresses until we found one where we can extract * a space key */ for (int i = 0; i < recipient.length; i++) { /* retrieve the email address */ String emailAddress; if (recipient[i] instanceof InternetAddress) { emailAddress = ((InternetAddress)recipient[i]).getAddress(); } else { emailAddress = recipient[i].toString(); } /* extract the wiki space name */ Pattern pattern = Pattern.compile("(.+?)([a-zA-Z0-9]+\\+[a-zA-Z0-9]+)@(.+?)"); Matcher matcher = pattern.matcher(emailAddress); String spaceKey = ""; boolean defer = false; if (matcher.matches()) { String tmp = matcher.group(2); spaceKey = tmp.substring(tmp.indexOf('+')+1); } else { /* fallback: test if there exists a space with a spacekey equal to the * local part of the email address. */ spaceKey = emailAddress.substring(0, emailAddress.indexOf('@')); defer = true; } /* check if the space exists */ Space space = spaceManager.getSpace(spaceKey); if(space == null) { // fall back to look up a personal space space = spaceManager.getPersonalSpace(spaceKey); } if (space == null) { /* could not find the space specified in the email address */ this.log.info("Unknown space key: " + spaceKey); /* try the next address if possible. */ continue; } /* check if it is a fallback space key */ if (defer) { /* add to the list of fallback spaces. if we don't find another * space in the form addr+spacekey@..., then we take the first one * of the fallback spaces */ deferredSpaceKeys.add(space); } else { return space; } } /* we did not find a space in the form addr+spacekey@domain.net. * check for a fallback space */ if (deferredSpaceKeys.size() > 0) { /* take the first fallback space */ Space s = deferredSpaceKeys.get(0); return s; } /* did not find any space, not even a fallback key */ /* Concat the to headers into one string for the error message */ String[] toHeaders = message.getHeader("To"); String toString = ""; for (int j = 0; j < toHeaders.length; j++) { toString = toString.concat(toHeaders[j]); if (j < (toHeaders.length - 1)) { toString = toString.concat(" / "); } } throw new Exception("Could not extract space key from any of the To: addresses: " + toString); } /** * Create a blog post from the content and the attachments retrieved from a * mail message. * There are only two parameters, the other necessary parameters are global * variables. * * @param space The space where to publish the blog post. * @param m The message which to publish as a blog post. * @throws MessagingException Throws a MessagingException if something goes wrong when getting attributes from the message. */ private void createBlogPost(Space space, Message m) throws MessagingException { /* create the blogPost and add values */ BlogPost blogPost = new BlogPost(); /* set the creation date of the blog post to the current date */ blogPost.setCreationDate(new Date()); /* set the space where to save the blog post */ blogPost.setSpace(space); /* if the gallery macro is set and the post contains an image add the macro */ MailConfiguration config = configurationManager.getMailConfiguration(); if (config.getGallerymacro()) { /* gallery macro is set */ if (containsImage) { /* post contains an image */ /* add the macro */ blogEntryContent = blogEntryContent.concat("{gallery}"); } } /* set the blog post content */ if (blogEntryContent != null) { blogPost.setContent(blogEntryContent); } else { blogPost.setContent(""); } /* set the title of the blog post */ String title = m.getSubject(); /* could be replaced with a regex */ char[] illegalCharacters = {':', '@', '/', '%', '\\', '&', '!', '|', ' for (int i = 0; i < illegalCharacters.length; i++) { if (title.indexOf(illegalCharacters[i]) != -1) { title = title.replace(illegalCharacters[i], ' '); } } blogPost.setTitle(title); /* set creating user */ String creatorEmail = getEmailAddressFromMessage(m); String creatorName = "Anonymous"; User creator = null; if (creatorEmail != "") { SearchResult sr = userAccessor.getUsersByEmail(creatorEmail); Pager p = sr.pager(); List l = p.getCurrentPage(); if (l.size() == 1) { /* found a matching user for the email address of the sender */ creator = (User)l.get(0); creatorName = creator.getFullName(); } } //this.log.info("creatorName: " + creatorName); //this.log.info("creator: " + creator); blogPost.setCreatorName(creatorName); if (creator != null) { AuthenticatedUserThreadLocal.setUser(creator); } else { //this.log.info("Resetting authenticated user."); AuthenticatedUserThreadLocal.setUser(null); } /* save the blog post */ pageManager.saveContentEntity(blogPost, null); /* set attachments of this blog post */ /* we have to save the blog post before we can add the * attachments, because attachments need to be attached to * a content. */ Attachment[] a = new Attachment[attachments.size()]; a = (Attachment[])attachments.toArray(a); for (int j = 0; j < a.length; j++) { InputStream is = (InputStream)attachmentsInputStreams.get(j); /* save the attachment */ try { /* set the creator of the attachment */ a[j].setCreatorName(creatorName); /* set the content of this attachment to the newly saved blog post */ a[j].setContent(blogPost); attachmentManager.saveAttachment(a[j], null, is); } catch (Exception e) { this.log.error("Could not save attachment: " + e.getMessage(), e); /* skip this attachment */ continue; } /* add the attachment to the blog post */ blogPost.addAttachment(a[j]); } } private String getEmailAddressFromMessage(Message m) throws MessagingException { Address[] sender = m.getFrom(); String creatorEmail = ""; if (sender.length > 0) { if (sender[0] instanceof InternetAddress) { creatorEmail = ((InternetAddress) sender[0]).getAddress(); } else { try { InternetAddress ia[] = InternetAddress.parse(sender[0].toString()); if (ia.length > 0) { creatorEmail = ia[0].getAddress(); } } catch (AddressException ae) { } } } return creatorEmail; } /** * Override the method which indicates whether this job can * be run several times simultaneously. We do not allow this * job to be run several times at once, because this would * generate all sorts of problems with the access to the mailbox. * * @return Returns whether concurrent execution is allowed. */ protected boolean allowConcurrentExecution() { return false; } /** * This method is automatically called by Confluence to pass the * PageManager of this Confluence instance. * * @param pageManager The PageManager of this Confluence instance */ public void setPageManager(PageManager pageManager) { this.pageManager = pageManager; } /** * This method is automatically called by Confluence to pass the * SpaceManager of this Confluence instance. * * @param pageManager The PageManager of this Confluence instance */ public void setSpaceManager(SpaceManager spaceManager) { this.spaceManager = spaceManager; } /** * This method is automatically called by Confluence to pass the * AttachmentManager of this Confluence instance. * * @param attachmentManager The AttachmentManager of this Confluence instance */ public void setAttachmentManager(AttachmentManager attachmentManager) { this.attachmentManager = attachmentManager; } /** * This method is automatically called by Confluence to pass the * UserAccessor of this Confluence instance. * * @param userAccessor The UserAccessor of this Confluence instance */ public void setUserAccessor(UserAccessor userAccessor) { this.userAccessor = userAccessor; } }
package com.springsource.greenhouse.events; import java.util.List; import javax.inject.Inject; import org.joda.time.LocalDate; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.social.core.ForbiddenSocialOperationException; import org.springframework.social.core.SocialException; import org.springframework.social.core.SocialSecurityException; import org.springframework.social.twitter.SearchResults; import org.springframework.social.twitter.TwitterOperations; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.springsource.greenhouse.account.Account; import com.springsource.greenhouse.action.Location; @Controller @RequestMapping("/events") public class EventsController { private EventRepository eventRepository; private TwitterOperations twitter; @Inject public EventsController(EventRepository eventRepository, TwitterOperations twitter) { this.eventRepository = eventRepository; this.twitter = twitter; } // for web service (JSON) clients @RequestMapping(method=RequestMethod.GET, headers="Accept=application/json") public @ResponseBody List<Event> upcomingEvents() { return eventRepository.findUpcomingEvents(); } @RequestMapping(value="/{id}/favorites", method=RequestMethod.GET, headers="Accept=application/json") public @ResponseBody List<EventSession> favorites(@PathVariable Long id, Account account) { return eventRepository.findFavorites(id, account.getId()); } @RequestMapping(value="/{id}/tweets", method=RequestMethod.GET, headers="Accept=application/json") public @ResponseBody SearchResults tweets(@PathVariable Long id, @RequestParam(defaultValue="1") Integer page, @RequestParam(defaultValue="10") Integer pageSize) { return twitter.search(eventRepository.findEventSearchString(id), page, pageSize); } @RequestMapping(value = "/{id}/tweets", method = RequestMethod.POST) public ResponseEntity<String> postTweet(@PathVariable Long id, @RequestParam String status, Location currentLocation) { return postTweet(status); } @RequestMapping(value="/{id}/retweet", method=RequestMethod.POST) @ResponseBody public ResponseEntity<String> postRetweet(@PathVariable Long id, @RequestParam Long tweetId) { return postRetweet(tweetId); } @RequestMapping(value="/{id}/sessions/favorites", method=RequestMethod.GET, headers="Accept=application/json") public @ResponseBody List<EventSession> favoriteSessions(@PathVariable Long id, Account account) { return eventRepository.findAttendeeFavorites(id, account.getId()); } @RequestMapping(value="/{id}/sessions/today", method=RequestMethod.GET, headers="Accept=application/json") public @ResponseBody List<EventSession> sessionsToday(@PathVariable Long id, Account account) { return eventRepository.findTodaysSessions(id, account.getId()); } @RequestMapping(value="/{id}/sessions/{day}", method=RequestMethod.GET, headers="Accept=application/json") public @ResponseBody List<EventSession> sessionsOnDay(@PathVariable Long id, @PathVariable @DateTimeFormat(iso=ISO.DATE) LocalDate day, Account account) { return eventRepository.findSessionsOnDay(id, day, account.getId()); } @RequestMapping(value="/{id}/sessions/{number}/favorite", method=RequestMethod.PUT) public @ResponseBody Boolean toggleFavorite(@PathVariable Long id, @PathVariable Short number, Account account) { return eventRepository.toggleFavorite(id, number, account.getId()); } @RequestMapping(value="/{id}/sessions/{number}/rating", method=RequestMethod.POST) public @ResponseBody void updateRating(@PathVariable Long id, @PathVariable Short number, Account account, @RequestParam Short value, @RequestParam String comment) { eventRepository.rate(id, number, account.getId(), value, comment); } @RequestMapping(value="/{id}/sessions/{number}/tweets", method=RequestMethod.GET, headers="Accept=application/json") public @ResponseBody SearchResults sessionTweets(@PathVariable Long id, @PathVariable Short number, @RequestParam(defaultValue="1") Integer page, @RequestParam(defaultValue="10") Integer pageSize) { return twitter.search(eventRepository.findSessionSearchString(id, number), page, pageSize); } @RequestMapping(value="/{id}/sessions/{number}/tweets", method=RequestMethod.POST) public ResponseEntity<String> postSessionTweet(@PathVariable Long id, @PathVariable Short number, @RequestParam String status, Location currentLocation) { return postTweet(status); } @RequestMapping(value="/{id}/sessions/{number}/retweet", method=RequestMethod.POST) @ResponseBody public ResponseEntity<String> postSessionRetweet(@PathVariable Long id, @RequestParam Long tweetId) { return postRetweet(tweetId); } // for web browser (HTML) clients @RequestMapping(method=RequestMethod.GET, headers="Accept=text/html") public String upcomingEventsView(Model model) { model.addAttribute(eventRepository.findUpcomingEvents()); return "events/list"; } // Common tweet/reweet methods private ResponseEntity<String> postTweet(String status) { try { twitter.tweet(status); return new ResponseEntity<String>((String) null, HttpStatus.OK); } catch (ForbiddenSocialOperationException e) { return new ResponseEntity<String>((String) null, HttpStatus.FORBIDDEN); } catch (SocialSecurityException e) { return new ResponseEntity<String>((String) null, HttpStatus.PRECONDITION_FAILED); } catch (SocialException e) { return new ResponseEntity<String>((String) null, HttpStatus.INTERNAL_SERVER_ERROR); } } private ResponseEntity<String> postRetweet(Long tweetId) { try { twitter.retweet(tweetId); } catch (ForbiddenSocialOperationException e) { return new ResponseEntity<String>((String) null, HttpStatus.FORBIDDEN); } catch (SocialSecurityException e) { return new ResponseEntity<String>((String) null, HttpStatus.PRECONDITION_FAILED); } catch (SocialException e) { return new ResponseEntity<String>((String) null, HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<String>((String) null, HttpStatus.OK); } }
package info.schnatterer.songbird2itunes; import info.schnatterer.songbird2itunes.Songbird2itunes.Statistics; import java.io.InputStream; import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.ParameterException; /** * Entry point for the songbird2Itunes Command Line Application */ public class Songbird2itunesApp { static final int EXIT_SUCCESS = 0; static final int EXIT_INVALID_PARAMS = 1; static final int EXIT_ERROR_CONVERSION = 2; /** SLF4J-Logger. */ private final Logger log = LoggerFactory.getLogger(getClass()); public static void main(String[] args) { System.exit(new Songbird2itunesApp().run(args)); } /** * @param args * @return 0 on success; 1 on command line parameters error; 2 on error on * songbird 2 iTunes conversion. */ int run(String[] args) { /* Parse command line arguments/parameter (command line interface) */ int ret = 0; // Presume success Songbird2itunesCli cliParams = null; try { cliParams = Songbird2itunesCli.readParams(args, "songbird2itunes"); if (cliParams != null) { if (cliParams.isDateAddedWorkaround() && !confirmedWorkaround()) { return EXIT_SUCCESS; } // Successfully read command line params. Do conversion printStats(createSongbird2itunes().convert(cliParams.getPath(), cliParams.getRetries(), cliParams.isDateAddedWorkaround())); return EXIT_SUCCESS; } } catch (ParameterException e) { log.error("Error parsing command line arguments."); ret = EXIT_INVALID_PARAMS; } catch (Exception e) { // Outmost "catch all" block for logging any // exception exiting application with error log.error("Conversion failed with error \"" + e.getMessage() + "\". Please see log file.", e); ret = EXIT_ERROR_CONVERSION; } return ret; } /** * Writes statistics to log. * * @param stats * statistics to write */ private void printStats(Statistics stats) { log.info("Finished converting."); log.info("Processed " + stats.getTracksProcessed() + " tracks (total) of which " + stats.getTracksFailed() + " failed."); log.info("Processed " + stats.getPlaylistsProcessed() + " playlists of which " + stats.getPlaylistsFailed() + " failed."); log.info("Processed " + stats.getPlaylistTracksProcessed() + " tracks (playlist members) of which " + stats.getPlaylistTracksFailed() + " failed."); log.info("See log file for more info"); } /** * Make user confirm to use the "date added workaround" * * @return <code>true</code> if the user confirmed, <code>false</code> * otherwise */ private boolean confirmedWorkaround() { Scanner scanner = null; try { scanner = new Scanner(createSystemIn()); log.info("You used the option for using the workaround to set the date added in iTunes. As setting the date added in iTunes is not possible, this workaround sets the system clock to the desired date and then adds the song to iTunes. Make sure to"); log.info(" - start songbird2itunes with administration rights,"); log.info(" - either close iTunes or start iTunes as administrator, "); log.info(" - deactivate the automatic sync of windows with a time server for the progress of conversion to iTunes."); log.info("If you REALLY want to do this, type \"yes\". If not just press enter and restart without this option!"); if ("yes".equals(scanner.nextLine())) { return true; } } finally { if (scanner != null) { scanner.close(); } } return false; } /** * @return a new instance of System.in. Useful for testing. */ InputStream createSystemIn() { return System.in; } /** * @return a new instance of {@link Songbird2itunes}. Useful for testing. */ Songbird2itunes createSongbird2itunes() { return new Songbird2itunes(); } }
package no.vegvesen.nvdbapi.client.clients; import com.google.common.base.Joiner; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import no.vegvesen.nvdbapi.client.clients.util.JerseyHelper; import no.vegvesen.nvdbapi.client.gson.ChangesParser; import no.vegvesen.nvdbapi.client.gson.RoadObjectParser; import no.vegvesen.nvdbapi.client.model.Change; import no.vegvesen.nvdbapi.client.model.Page; import no.vegvesen.nvdbapi.client.model.datakatalog.DataType; import no.vegvesen.nvdbapi.client.model.datakatalog.Datakatalog; import no.vegvesen.nvdbapi.client.model.roadobjects.Attribute; import no.vegvesen.nvdbapi.client.model.roadobjects.RoadObject; import no.vegvesen.nvdbapi.client.model.roadobjects.Statistics; import no.vegvesen.nvdbapi.client.util.ArgUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class RoadObjectClient extends AbstractJerseyClient { private static final Logger logger = LoggerFactory.getLogger(RoadObjectClient.class); private final Datakatalog datakatalog; protected RoadObjectClient(String baseUrl, Client client, Datakatalog datakatalog) { super(baseUrl, client); this.datakatalog = datakatalog; } public Datakatalog getDatakatalog() { return datakatalog; } public Attribute getAttribute(int featureTypeId, long featureId, int attributeTypeId) { UriBuilder path = start() .path(String.format("/vegobjekter/%d/%d/egenskaper/%d", featureTypeId, featureId, attributeTypeId)); logger.debug("Invoking {}", path); WebTarget target = getClient().target(path); JsonElement e = JerseyHelper.execute(target); return RoadObjectParser.parseAttribute(datakatalog.getDataTypeMap(), e.getAsJsonObject()); } public Stream<Attribute> getAttributes(int featureTypeId, Stream<Long> featureIds, int attributeTypeId) { return featureIds.map(id -> getAttribute(featureTypeId, id, attributeTypeId)); } public Statistics getStats(int featureTypeId, RoadObjectRequest request) { UriBuilder path = start() .path(String.format("/vegobjekter/%d/statistikk", featureTypeId)); applyRequestParameters(path, convert(request)); logger.debug("Invoking {}", path); WebTarget target = getClient().target(path); JsonElement e = JerseyHelper.execute(target); return RoadObjectParser.parseStatistics(e.getAsJsonObject()); } public RoadObjectsResult getRoadObjects(int featureTypeId) { return getRoadObjects(featureTypeId, RoadObjectRequest.DEFAULT); } /** * This method can be used when you desire complete control of which query parameters is sent to the API * @param featureTypeId * @param queryParameters * @return */ public RoadObjectsResult getRoadObjects(int featureTypeId, MultivaluedMap<String, String> queryParameters) { UriBuilder path = start() .path(String.format("/vegobjekter/%d", featureTypeId)); applyRequestParameters(path, queryParameters); WebTarget target = getClient().target(path); return new RoadObjectsResult(target, extractPage(queryParameters), datakatalog); } public RoadObjectsResult getRoadObjects(int featureTypeId, RoadObjectRequest request) { UriBuilder path = start() .path(String.format("/vegobjekter/%d", featureTypeId)); applyRequestParameters(path, convert(request)); WebTarget target = getClient().target(path); return new RoadObjectsResult(target, Optional.ofNullable(request.getPage()), datakatalog); } private Optional<Page> extractPage(MultivaluedMap<String, String> params) { if (params.containsKey("antall")) { return Optional.of(Page.count(Integer.parseInt(params.getFirst("antall")))); } return Optional.empty(); } public RoadObject getRoadObject(int featureTypeId, long featureId) { return getRoadObject(featureTypeId, featureId, RoadObjectRequest.DEFAULT); } public RoadObject getRoadObject(int featureTypeId, long featureId, RoadObjectRequest request) { UriBuilder path = start() .path(String.format("/vegobjekter/%d/%d", featureTypeId, featureId)); logger.debug("Invoking {}", path); applyRequestParameters(path, convert(request)); WebTarget target = getClient().target(path); JsonObject obj = JerseyHelper.execute(target).getAsJsonObject(); return RoadObjectParser.parse(datakatalog.getDataTypeMap(), obj); } public ChangesResult getChanges(int typeId, LocalDate from, Page page, Change.Type type) { return getChanges(typeId, from.atStartOfDay(), page, type); } public ChangesResult getChanges(int typeId, LocalDateTime from, Page page, Change.Type type) { Objects.requireNonNull(from, "Missing from argument!"); UriBuilder path = start() .path(String.format("/vegobjekter/%d/endringer", typeId)) .queryParam("etter", ArgUtil.date(from)) .queryParam("type", type.getArgValue()); WebTarget target = getClient().target(path); return new ChangesResult(datakatalog.getDataTypeMap(), typeId, target, Optional.ofNullable(page)); } private static void applyRequestParameters(UriBuilder path, MultivaluedMap<String, String> params) { params.forEach((k, values) -> { path.queryParam(k, values.toArray(new String[0])); }); } private static MultivaluedMap<String, String> convert(RoadObjectRequest request) { MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); // Single parameters request.getSegmented().ifPresent(v -> map.putSingle("segmentering", Boolean.toString(v))); request.getProjection().ifPresent(v -> map.putSingle("srid", Integer.toString(v.getSrid()))); request.getDistanceTolerance().ifPresent(v -> map.putSingle("geometritoleranse", Integer.toString(v))); request.getDepth().ifPresent(v -> map.putSingle("dybde", v)); getIncludeArgument(request.getIncludes()).ifPresent(v -> map.putSingle("inkluder", v)); request.getAttributeFilter().ifPresent(v -> map.putSingle("egenskap", v)); request.getBbox().ifPresent(v -> map.putSingle("kartutsnitt", v)); request.getRoadRefFilter().ifPresent(v -> map.putSingle("vegreferanse", v)); request.getRefLinkFilter().ifPresent(v -> map.putSingle("veglenke", v)); flatten(request.getMunicipalities()).ifPresent(v -> map.putSingle("kommune", v)); flatten(request.getCounties()).ifPresent(v -> map.putSingle("fylke", v)); flatten(request.getRegions()).ifPresent(v -> map.putSingle("region", v)); flatten(request.getRoadDepartments()).ifPresent(v -> map.putSingle("vegavdeling", v)); flattenString(request.getContractAreas()).ifPresent(v -> map.putSingle("kontraktsomrade", v)); flattenString(request.getNationalRoutes()).ifPresent(v -> map.putSingle("riksvegrute", v)); // Multiple parameters request.getOverlapFilters().forEach(f -> map.add("overlapp", f.toString())); return map; } private static Optional<String> flatten(List<Integer> set) { if (set.isEmpty()) { return Optional.empty(); } return Optional.of(set.stream().map(i -> i.toString()).collect(Collectors.joining(","))); } private static Optional<String> flattenString(List<String> set) { if (set.isEmpty()) { return Optional.empty(); } return Optional.of(Joiner.on(",").join(set)); } public List<Attribute> getAttributes(int featureTypeId, long featureId) { UriBuilder path = start() .path(String.format("/vegobjekter/%d/%d/egenskaper", featureTypeId, featureId)); logger.debug("Invoking {}", path); WebTarget target = getClient().target(path); JsonArray array = JerseyHelper.execute(target).getAsJsonArray(); return StreamSupport.stream(array.spliterator(), false) .map(e -> e.getAsJsonObject()) .map(o -> RoadObjectParser.parseAttribute(datakatalog.getDataTypeMap(), o)) .collect(Collectors.toList()); } private static Optional<String> getIncludeArgument(Include... informationToInclude) { Set<Include> values = informationToInclude != null && informationToInclude.length > 0 ? new HashSet<>(Arrays.asList(informationToInclude)) : Collections.emptySet(); return getIncludeArgument(values); } private static Optional<String> getIncludeArgument(Set<Include> values) { // Defaults if (values == null || values.isEmpty()) { return Optional.empty(); } // "All" trumps any other values if (values.contains(Include.ALL)) { return Optional.of(Include.ALL.value); } // "minimum" is redundant except when alone if (values.size() == 1 && values.contains(Include.MINIMUM)) { return Optional.of(Include.MINIMUM.value); } String val = values.stream().filter(i -> i != Include.MINIMUM).map(i -> i.value).collect(Collectors.joining(",")); return Optional.of(val); } public enum Include { MINIMUM("minimum"), METADATA("metadata"), ATTRIBUTES("egenskaper"), ASSOCIATIONS("relasjoner"), LOCATION("lokasjon"), ROAD_SEGMENTS("vegsegmenter"), GEOMETRI("geometri"), ALL("alle"); private final String value; Include(String value) { this.value = value; } public static Set<Include> all() { return EnumSet.complementOf(EnumSet.of(Include.MINIMUM, Include.ALL)); } public static Set<Include> not(Include... without) { return all().stream().filter(v -> !Arrays.asList(without).contains(v)).collect(Collectors.toSet()); } public String stringValue() { return value; } } public static class RoadObjectsResult extends GenericResultSet<RoadObject> { public RoadObjectsResult(WebTarget baseTarget, Optional<Page> currentPage, Datakatalog datakatalog) { super(baseTarget, currentPage, o -> RoadObjectParser.parse(datakatalog.getDataTypeMap(), o)); } } public static class ChangesResult extends GenericResultSet<Change> { public ChangesResult(Map<Integer, DataType> dataTypes, int typeId, WebTarget baseTarget, Optional<Page> currentPage) { super(baseTarget, currentPage, obj -> ChangesParser.parse(dataTypes, obj, typeId)); } } }