answer
stringlengths
17
10.2M
package com.novoda.downloadmanager; import java.util.Collections; import java.util.List; class Migration { private final Batch batch; private final List<FileMetadata> fileMetadata; Migration(Batch batch, List<FileMetadata> fileMetadata) { this.batch = batch; this.fileMetadata = Collections.unmodifiableList(fileMetadata); } Batch batch() { return batch; } List<FileMetadata> getFileMetadata() { return fileMetadata; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Migration migration = (Migration) o; if (batch != null ? !batch.equals(migration.batch) : migration.batch != null) { return false; } return fileMetadata != null ? fileMetadata.equals(migration.fileMetadata) : migration.fileMetadata == null; } @Override public int hashCode() { int result = batch != null ? batch.hashCode() : 0; result = 31 * result + (fileMetadata != null ? fileMetadata.hashCode() : 0); return result; } static class FileMetadata { private final String originalFileLocation; private final FileSize fileSize; private final String uri; FileMetadata(String originalFileLocation, FileSize fileSize, String uri) { this.originalFileLocation = originalFileLocation; this.fileSize = fileSize; this.uri = uri; } String originalFileLocation() { return originalFileLocation; } FileSize fileSize() { return fileSize; } public String uri() { return uri; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FileMetadata that = (FileMetadata) o; if (originalFileLocation != null ? !originalFileLocation.equals(that.originalFileLocation) : that.originalFileLocation != null) { return false; } if (fileSize != null ? !fileSize.equals(that.fileSize) : that.fileSize != null) { return false; } return uri != null ? uri.equals(that.uri) : that.uri == null; } @Override public int hashCode() { int result = originalFileLocation != null ? originalFileLocation.hashCode() : 0; result = 31 * result + (fileSize != null ? fileSize.hashCode() : 0); result = 31 * result + (uri != null ? uri.hashCode() : 0); return result; } } }
package io.nlopez.smartadapters; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.support.v7.widget.RecyclerView; import android.widget.AbsListView; import java.util.ArrayList; import java.util.List; import io.nlopez.smartadapters.adapters.MultiAdapter; import io.nlopez.smartadapters.adapters.RecyclerMultiAdapter; import io.nlopez.smartadapters.builders.BindableLayoutBuilder; import io.nlopez.smartadapters.utils.Mapper; import io.nlopez.smartadapters.utils.ViewEventListener; import io.nlopez.smartadapters.views.BindableLayout; /** * Managing class for SmartAdapters library. */ public class SmartAdapter { private SmartAdapter() { } /** * Include the object list that is going to be represented in our collection view. * * @param items model list to be displayed in the listing * @return fluid interface for more settings */ public static MultiAdaptersCreator items(@NonNull List<?> items) { return new MultiAdaptersCreator(items); } /** * Initiates the fluid chain without any models to be represented. You should include them in * further calls to the adapter with the addItems method. * * @return fluid interface for more settings */ public static MultiAdaptersCreator empty() { return new MultiAdaptersCreator(new ArrayList<>()); } public static class MultiAdaptersCreator { private Mapper mapper; private List elements; private BindableLayoutBuilder builder; private ViewEventListener listener; public MultiAdaptersCreator(List<?> elements) { this.mapper = new Mapper(); this.elements = elements; } /** * Binds the models to their views. The views should inherit from BindableLayout, so their * bind methods assign the values from the model to the view widgets. * * @param objectClass Class of the object (model) class * @param viewClass Class of the view (layout) class * @return fluid interface for more settings */ public MultiAdaptersCreator map(@NonNull Class objectClass, @NonNull Class<? extends BindableLayout> viewClass) { mapper.add(objectClass, viewClass); return this; } /** * Changes the internal Mapper instance to a new one. The mapper is an object with all the * mappings between objects and views. This will overwrite all the @see #map(Class, Class) * calls done so far, so beware of that. * * @param mapper mappings for objects to views * @return fluid interface for more settings */ @VisibleForTesting MultiAdaptersCreator mapper(@NonNull Mapper mapper) { this.mapper = mapper; return this; } /** * Sets a new builder different from the default one @see io.nlopez.smartadapters.builders.DefaultBindableLayoutBuilder * so the views can be created based on the models with your own actions. * * @param builder new builder instance * @return fluid interface for more settings */ public MultiAdaptersCreator builder(BindableLayoutBuilder builder) { this.builder = builder; return this; } /** * Sets a new listener for all the collection related events. All the events fired within * the views with the proper notifyItemAction calls will get to this listener. * * @param listener callback for actions control * @return fluid interface for more settings */ public MultiAdaptersCreator listener(@NonNull ViewEventListener listener) { this.listener = listener; return this; } /** * Returns the instantiated adapter for AbsListView inherited widgets (ListView, GridView) * created with all the parameters already set. It is based on BaseAdapter adapters. * * @return adapter for {@code AbsListView} based on {@code BaseAdapter} */ public MultiAdapter adapter() { MultiAdapter response = new MultiAdapter(mapper, elements, builder); response.setViewEventListener(listener); return response; } /** * Returns the instantiated adapter for RecyclerView * * @return adapter based on {@code RecyclerView.Adapter} */ public RecyclerMultiAdapter recyclerAdapter() { RecyclerMultiAdapter response = new RecyclerMultiAdapter(mapper, elements, builder); response.setViewEventListener(listener); return response; } /** * Assigns the created adapter to the given {@code AbsListView} inherited widget (ListView, GridView). * * @param widget ListView, GridView, ie any widget inheriting from {@code AbsListView} * @return assigned adapter */ public MultiAdapter into(@NonNull AbsListView widget) { MultiAdapter adapter = adapter(); widget.setAdapter(adapter); return adapter; } /** * Assigns the created adapter to the given {@code RecyclerView}. * * @param recyclerView instance of RecyclerView * @return assigned adapter */ public RecyclerMultiAdapter into(@NonNull RecyclerView recyclerView) { RecyclerMultiAdapter adapter = recyclerAdapter(); recyclerView.setAdapter(adapter); return adapter; } } }
package sk.coplas.sqliteddlhelper; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; public class DDLBuilder { private String tableName; private LinkedHashMap<String, ColumnType> columns; private String primaryKey; private String autoincrement; private String columnNameCache; private List<String> notNullcolumns; private boolean isAlter; private DDLBuilder(){ columns = new LinkedHashMap<String, ColumnType>(); notNullcolumns = new ArrayList<String>(); } public static DDLBuilder createTable(String tableName) { DDLBuilder builder = new DDLBuilder(); builder.tableName = tableName; builder.isAlter = false; return builder; } public static DDLBuilder alterTable(String tableName) { DDLBuilder builder = new DDLBuilder(); builder.tableName = tableName; builder.isAlter = true; return builder; } public String build(){ StringBuilder sb = new StringBuilder(); if (tableName == null || tableName.length() < 0) { throw new IllegalArgumentException("Table name is required"); } if (isAlter) { if (columns.size() != 1) { throw new IllegalArgumentException("One column is required in SQLite ALTER"); } else { //get first column String columnName = columns.keySet().iterator().next(); ColumnType columnType = columns.get( columnName); sb.append("ALTER TABLE "); sb.append(tableName); sb.append(" ADD COLUMN "); sb.append(columnName); sb.append(" "); sb.append(columnType.toString()); createColumnParams(sb, columnName); } } else { if (columns.size() < 1) { throw new IllegalArgumentException("At least one column is required in SQLite CREATE"); } else { sb.append("CREATE TABLE "); sb.append(tableName); sb.append(" ( "); final Iterator<String> columnsIterator = columns.keySet().iterator(); while (columnsIterator.hasNext()) { String columnName = columnsIterator.next(); ColumnType columnType = columns.get( columnName); sb.append(columnName); sb.append(" "); sb.append(columnType.toString()); createColumnParams(sb, columnName); if (columnsIterator.hasNext()) { sb.append(", "); } } sb.append(")"); } } return sb.toString(); } private void createColumnParams(StringBuilder sb, String columnName) { if (columnName.equals( primaryKey)) { sb.append(" PRIMARY KEY"); } if (columnName.equals( autoincrement)) { sb.append(" AUTOINCREMENT"); } if (notNullcolumns.contains( columnName)) { sb.append(" NOT NULL"); } } public static enum ColumnType { TEXT,NUMERIC,INTEGER,REAL,BOOLEAN, NONE } private class SingleColumnBuilder{ private String name; private ColumnType type; private boolean pk; private boolean autoIncrement; private boolean notNull; public DDLBuilder pk(String columnName) { this.primaryKey = columnName; return this; } public DDLBuilder autoIncrement(String columnName) { this.primaryKey = columnName; return this; } public DDLBuilder pk() { this.primaryKey = columnNameCache; return this; } public DDLBuilder autoIncrement() { this.autoincrement = columnNameCache; return this; } public DDLBuilder notNull() { this.notNullcolumns.add( columnNameCache); return this; } public DDLBuilder text(String columnName) { return column(columnName, ColumnType.TEXT); } public DDLBuilder numeric(String columnName) { return column(columnName, ColumnType.NUMERIC); } public DDLBuilder integer(String columnName) { return column(columnName, ColumnType.INTEGER); } public DDLBuilder real(String columnName) { return column(columnName, ColumnType.REAL); } public DDLBuilder bool(String columnName) { return column(columnName, ColumnType.BOOLEAN); } public DDLBuilder none(String columnName) { return column(columnName, ColumnType.NONE); } public DDLBuilder column(String columnName, ColumnType columnType) { if (isAlter && columns.size() > 0) { throw new IllegalArgumentException("Only one column is allowed in SQLite ALTER"); } if (!columns.containsKey(columnName)) { columns.put(columnName, columnType); } columnNameCache = columnName; return this; } } private class MultiColumnBuilder extends SingleColumnBuilder{ private List<SingleColumnBuilder> columns; private SingleColumnBuilder column; private MultiColumnBuilder() { columns = new ArrayList<SingleColumnBuilder>(); } public MultiColumnBuilder column() { if (column != null) { columns.add( column); } column = new SingleColumnBuilder(); return this; } } }
package liquibase.changelog; import liquibase.ContextExpression; import liquibase.LabelExpression; import liquibase.Labels; import liquibase.change.Change; import liquibase.change.ChangeFactory; import liquibase.change.CheckSum; import liquibase.change.DbmsTargetedChange; import liquibase.change.core.EmptyChange; import liquibase.change.core.RawSQLChange; import liquibase.changelog.visitor.ChangeExecListener; import liquibase.database.Database; import liquibase.database.DatabaseList; import liquibase.database.ObjectQuotingStrategy; import liquibase.exception.*; import liquibase.executor.Executor; import liquibase.executor.ExecutorService; import liquibase.executor.LoggingExecutor; import liquibase.logging.LogService; import liquibase.logging.LogType; import liquibase.logging.Logger; import liquibase.parser.core.ParsedNode; import liquibase.parser.core.ParsedNodeException; import liquibase.precondition.Conditional; import liquibase.precondition.ErrorPrecondition; import liquibase.precondition.FailedPrecondition; import liquibase.precondition.core.PreconditionContainer; import liquibase.resource.ResourceAccessor; import liquibase.sql.visitor.SqlVisitor; import liquibase.sql.visitor.SqlVisitorFactory; import liquibase.statement.SqlStatement; import liquibase.util.StreamUtil; import liquibase.util.StringUtils; import java.util.*; /** * Encapsulates a changeSet and all its associated changes. */ public class ChangeSet implements Conditional, ChangeLogChild { protected CheckSum checkSum; /** * storedChecksum is used to make the checksum of a changeset that has already been run * on a database available to liquibase extensions. This value might differ from the checkSum value that * is calculated at run time when ValidatorVisitor is being called */ private CheckSum storedCheckSum; public enum RunStatus { NOT_RAN, ALREADY_RAN, RUN_AGAIN, MARK_RAN, INVALID_MD5SUM } public enum ExecType { EXECUTED("EXECUTED", false, true), FAILED("FAILED", false, false), SKIPPED("SKIPPED", false, false), RERAN("RERAN", true, true), MARK_RAN("MARK_RAN", false, true); ExecType(String value, boolean ranBefore, boolean ran) { this.value = value; this.ranBefore = ranBefore; this.ran = ran; } public final String value; public final boolean ranBefore; public final boolean ran; } public enum ValidationFailOption { HALT("HALT"), MARK_RAN("MARK_RAN"); String key; ValidationFailOption(String key) { this.key = key; } @Override public String toString() { return key; } } protected String key; private ChangeLogParameters changeLogParameters; /** * List of change objects defined in this changeset */ private List<Change> changes; /** * "id" specified in changeLog file. Combination of id+author+filePath must be unique */ private String id; /** * "author" defined in changeLog file. Having each developer use a unique author tag allows duplicates of "id" attributes between developers. */ private String author; /** * File changeSet is defined in. May be a logical/non-physical string. It is included in the unique identifier to allow duplicate id+author combinations in different files */ private String filePath = "UNKNOWN CHANGE LOG"; private Logger log; /** * If set to true, the changeSet will be executed on every update. Defaults to false */ private boolean alwaysRun; /** * If set to true, the changeSet will be executed when the checksum changes. Defaults to false. */ private boolean runOnChange; /** * Runtime contexts in which the changeSet will be executed. If null or empty, will execute regardless of contexts set */ private ContextExpression contexts; /** * "Labels" associated with this changeSet. If null or empty, will execute regardless of contexts set */ private Labels labels; /** * * If set to true, the changeSet will be ignored (skipped) * */ private boolean ignore; /** * Databases for which this changeset should run. The string values should match the value returned from Database.getShortName() */ private Set<String> dbmsSet; /** * If false, do not stop liquibase update execution if an error is thrown executing the changeSet. Defaults to true */ private Boolean failOnError; /** * List of checksums that are assumed to be valid besides the one stored in the database. Can include the string "any" */ private Set<CheckSum> validCheckSums = new HashSet<>(); /** * If true, the changeSet will run in a database transaction. Defaults to true */ private boolean runInTransaction; /** * Behavior if the validation of any of the changeSet changes fails. Does not include checksum validation */ private ValidationFailOption onValidationFail = ValidationFailOption.HALT; /** * Stores if validation failed on this ChangeSet */ private boolean validationFailed; /** * Changes defined to roll back this changeSet */ private RollbackContainer rollback = new RollbackContainer(); /** * ChangeSet comments defined in changeLog file */ private String comments; /** * ChangeSet level precondtions defined for this changeSet */ private PreconditionContainer preconditions; /** * ChangeSet level attribute to specify an Executor */ private String runWith; /** * SqlVisitors defined for this changeset. * SqlVisitors will modify the SQL generated by the changes before sending it to the database. */ private List<SqlVisitor> sqlVisitors = new ArrayList<>(); private ObjectQuotingStrategy objectQuotingStrategy; private DatabaseChangeLog changeLog; private String created; /** * Allow changeSet to be ran "first" or "last". Multiple changeSets with the same runOrder will preserve their order relative to each other. */ private String runOrder; private Map<String, Object> attributes = new HashMap<>(); public boolean shouldAlwaysRun() { return alwaysRun; } public boolean shouldRunOnChange() { return runOnChange; } public ChangeSet(DatabaseChangeLog databaseChangeLog) { this.changes = new ArrayList<>(); log = LogService.getLog(getClass()); this.changeLog = databaseChangeLog; } public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextList, String dbmsList, DatabaseChangeLog databaseChangeLog) { this(id, author, alwaysRun, runOnChange, filePath, contextList, dbmsList, null, true, ObjectQuotingStrategy.LEGACY, databaseChangeLog); } public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextList, String dbmsList, boolean runInTransaction, DatabaseChangeLog databaseChangeLog) { this(id, author, alwaysRun, runOnChange, filePath, contextList, dbmsList, null, runInTransaction, ObjectQuotingStrategy.LEGACY, databaseChangeLog); } public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextList, String dbmsList, ObjectQuotingStrategy quotingStrategy, DatabaseChangeLog databaseChangeLog) { this(id, author, alwaysRun, runOnChange, filePath, contextList, dbmsList, null, true, quotingStrategy, databaseChangeLog); } public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextList, String dbmsList, boolean runInTransaction, ObjectQuotingStrategy quotingStrategy, DatabaseChangeLog databaseChangeLog) { this(id, author, alwaysRun, runOnChange, filePath, contextList, dbmsList, null, runInTransaction, quotingStrategy, databaseChangeLog); } public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextList, String dbmsList, String runWith, boolean runInTransaction, ObjectQuotingStrategy quotingStrategy, DatabaseChangeLog databaseChangeLog) { this(databaseChangeLog); this.id = id; this.author = author; this.filePath = filePath; this.alwaysRun = alwaysRun; this.runOnChange = runOnChange; this.runInTransaction = runInTransaction; this.objectQuotingStrategy = quotingStrategy; this.contexts = new ContextExpression(contextList); setDbms(dbmsList); this.runWith = runWith; } protected void setDbms(String dbmsList) { this.dbmsSet = DatabaseList.toDbmsSet(dbmsList); } public String getFilePath() { return filePath; } public String getRunWith() { return runWith; } public void clearCheckSum() { this.checkSum = null; } public CheckSum generateCheckSum() { if (checkSum == null) { StringBuffer stringToMD5 = new StringBuffer(); for (Change change : getChanges()) { stringToMD5.append(change.generateCheckSum()).append(":"); } for (SqlVisitor visitor : this.getSqlVisitors()) { stringToMD5.append(visitor.generateCheckSum()).append(";"); } checkSum = CheckSum.compute(stringToMD5.toString()); } return checkSum; } @Override public void load(ParsedNode node, ResourceAccessor resourceAccessor) throws ParsedNodeException { this.id = node.getChildValue(null, "id", String.class); this.author = node.getChildValue(null, "author", String.class); this.alwaysRun = node.getChildValue(null, "runAlways", node.getChildValue(null, "alwaysRun", false)); this.runOnChange = node.getChildValue(null, "runOnChange", false); this.runWith = node.getChildValue(null, "runWith", String.class); this.contexts = new ContextExpression(node.getChildValue(null, "context", String.class)); this.labels = new Labels(StringUtils.trimToNull(node.getChildValue(null, "labels", String.class))); setDbms(node.getChildValue(null, "dbms", String.class)); this.runInTransaction = node.getChildValue(null, "runInTransaction", true); this.created = node.getChildValue(null, "created", String.class); this.runOrder = node.getChildValue(null, "runOrder", String.class); this.ignore = node.getChildValue(null, "ignore", false); this.comments = StringUtils.join(node.getChildren(null, "comment"), "\n", new StringUtils.StringUtilsFormatter() { @Override public String toString(Object obj) { if (((ParsedNode) obj).getValue() == null) { return ""; } else { return ((ParsedNode) obj).getValue().toString(); } } }); this.comments = StringUtils.trimToNull(this.comments); String objectQuotingStrategyString = StringUtils.trimToNull(node.getChildValue(null, "objectQuotingStrategy", String.class)); if (changeLog != null) { this.objectQuotingStrategy = changeLog.getObjectQuotingStrategy(); } if (objectQuotingStrategyString != null) { this.objectQuotingStrategy = ObjectQuotingStrategy.valueOf(objectQuotingStrategyString); } if (this.objectQuotingStrategy == null) { this.objectQuotingStrategy = ObjectQuotingStrategy.LEGACY; } this.filePath = StringUtils.trimToNull(node.getChildValue(null, "logicalFilePath", String.class)); if (filePath == null) { filePath = changeLog.getFilePath(); } this.setFailOnError(node.getChildValue(null, "failOnError", Boolean.class)); String onValidationFailString = node.getChildValue(null, "onValidationFail", "HALT"); this.setOnValidationFail(ValidationFailOption.valueOf(onValidationFailString)); for (ParsedNode child : node.getChildren()) { handleChildNode(child, resourceAccessor); } } protected void handleChildNode(ParsedNode child, ResourceAccessor resourceAccessor) throws ParsedNodeException { switch (child.getName()) { case "rollback": handleRollbackNode(child, resourceAccessor); break; case "validCheckSum": case "validCheckSums": if (child.getValue() == null) { return; } if (child.getValue() instanceof Collection) { for (Object checksum : (Collection) child.getValue()) { addValidCheckSum((String) checksum); } } else { addValidCheckSum(child.getValue(String.class)); } break; case "modifySql": String dbmsString = StringUtils.trimToNull(child.getChildValue(null, "dbms", String.class)); String contextString = StringUtils.trimToNull(child.getChildValue(null, "context", String.class)); String labelsString = StringUtils.trimToNull(child.getChildValue(null, "labels", String.class)); boolean applyToRollback = child.getChildValue(null, "applyToRollback", false); Set<String> dbms = new HashSet<>(); if (dbmsString != null) { dbms.addAll(StringUtils.splitAndTrim(dbmsString, ",")); } ContextExpression context = null; if (contextString != null) { context = new ContextExpression(contextString); } Labels labels = null; if (labelsString != null) { labels = new Labels(labelsString); } List<ParsedNode> potentialVisitors = child.getChildren(); for (ParsedNode node : potentialVisitors) { SqlVisitor sqlVisitor = SqlVisitorFactory.getInstance().create(node.getName()); if (sqlVisitor != null) { sqlVisitor.setApplyToRollback(applyToRollback); if (!dbms.isEmpty()) { sqlVisitor.setApplicableDbms(dbms); } sqlVisitor.setContexts(context); sqlVisitor.setLabels(labels); sqlVisitor.load(node, resourceAccessor); addSqlVisitor(sqlVisitor); } } break; case "preConditions": this.preconditions = new PreconditionContainer(); try { this.preconditions.load(child, resourceAccessor); } catch (ParsedNodeException e) { e.printStackTrace(); } break; case "changes": for (ParsedNode changeNode : child.getChildren()) { handleChildNode(changeNode, resourceAccessor); } break; default: Change change = toChange(child, resourceAccessor); if ((change == null) && (child.getValue() instanceof String)) { this.setAttribute(child.getName(), child.getValue()); } else { addChange(change); } break; } } protected void handleRollbackNode(ParsedNode rollbackNode, ResourceAccessor resourceAccessor) throws ParsedNodeException { String changeSetId = rollbackNode.getChildValue(null, "changeSetId", String.class); if (changeSetId != null) { String changeSetAuthor = rollbackNode.getChildValue(null, "changeSetAuthor", String.class); String changeSetPath = rollbackNode.getChildValue(null, "changeSetPath", getFilePath()); DatabaseChangeLog changeLog = this.getChangeLog(); ChangeSet changeSet = changeLog.getChangeSet(changeSetPath, changeSetAuthor, changeSetId); while ((changeSet == null) && (changeLog != null)) { changeLog = changeLog.getParentChangeLog(); if (changeLog != null) { changeSet = changeLog.getChangeSet(changeSetPath, changeSetAuthor, changeSetId); } } if (changeSet == null) { throw new ParsedNodeException("Change set " + new ChangeSet(changeSetId, changeSetAuthor, false, false, changeSetPath, null, null, null).toString(false) + " does not exist"); } for (Change change : changeSet.getChanges()) { rollback.getChanges().add(change); } return; } boolean foundValue = false; for (ParsedNode childNode : rollbackNode.getChildren()) { Change rollbackChange = toChange(childNode, resourceAccessor); if (rollbackChange != null) { addRollbackChange(rollbackChange); foundValue = true; } } Object value = rollbackNode.getValue(); if (value != null) { if (value instanceof String) { String finalValue = StringUtils.trimToNull((String) value); if (finalValue != null) { String[] strings = StringUtils.processMutliLineSQL(finalValue, true, true, ";"); for (String string : strings) { addRollbackChange(new RawSQLChange(string)); foundValue = true; } } } else { throw new ParsedNodeException("Unexpected object: "+value.getClass().getName()+" '"+value.toString()+"'"); } } if (!foundValue) { addRollbackChange(new EmptyChange()); } } protected Change toChange(ParsedNode value, ResourceAccessor resourceAccessor) throws ParsedNodeException { Change change = ChangeFactory.getInstance().create(value.getName()); if (change == null) { return null; } else { change.load(value, resourceAccessor); return change; } } @Override public ParsedNode serialize() { throw new RuntimeException("TODO"); } public ExecType execute(DatabaseChangeLog databaseChangeLog, Database database) throws MigrationFailedException { return execute(databaseChangeLog, null, database); } /** * This method will actually execute each of the changes in the list against the * specified database. * * @return should change set be marked as ran */ public ExecType execute(DatabaseChangeLog databaseChangeLog, ChangeExecListener listener, Database database) throws MigrationFailedException { if (validationFailed) { return ExecType.MARK_RAN; } long startTime = new Date().getTime(); ExecType execType = null; boolean skipChange = false; Executor originalExecutor = switchExecutorIfNecessary(database); try { Executor executor = ExecutorService.getInstance().getExecutor("jdbc", database); // set object quoting strategy database.setObjectQuotingStrategy(objectQuotingStrategy); if (database.supportsDDLInTransaction()) { database.setAutoCommit(!runInTransaction); } executor.comment("Changeset " + toString(false)); if (StringUtils.trimToNull(getComments()) != null) { String comments = getComments(); String[] lines = comments.split("\\n"); for (int i = 0; i < lines.length; i++) { if (i > 0) { lines[i] = database.getLineComment() + " " + lines[i]; } } executor.comment(StringUtils.join(Arrays.asList(lines), "\n")); } try { if (preconditions != null) { preconditions.check(database, databaseChangeLog, this, listener); } } catch (PreconditionFailedException e) { if (listener != null) { listener.preconditionFailed(e, preconditions.getOnFail()); } StringBuffer message = new StringBuffer(); message.append(StreamUtil.getLineSeparator()); for (FailedPrecondition invalid : e.getFailedPreconditions()) { message.append(" ").append(invalid.toString()); message.append(StreamUtil.getLineSeparator()); } if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.HALT)) { throw new MigrationFailedException(this, message.toString(), e); } else if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.CONTINUE)) { skipChange = true; execType = ExecType.SKIPPED; LogService.getLog(getClass()).info(LogType.LOG, "Continuing past: " + toString() + " despite precondition failure due to onFail='CONTINUE': " + message); } else if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.MARK_RAN)) { execType = ExecType.MARK_RAN; skipChange = true; log.info(LogType.LOG, "Marking ChangeSet: " + toString() + " ran despite precondition failure due to onFail='MARK_RAN': " + message); } else if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.WARN)) { execType = null; //already warned } else { throw new UnexpectedLiquibaseException("Unexpected precondition onFail attribute: " + preconditions.getOnFail(), e); } } catch (PreconditionErrorException e) { if (listener != null) { listener.preconditionErrored(e, preconditions.getOnError()); } StringBuffer message = new StringBuffer(); message.append(StreamUtil.getLineSeparator()); for (ErrorPrecondition invalid : e.getErrorPreconditions()) { message.append(" ").append(invalid.toString()); message.append(StreamUtil.getLineSeparator()); } if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.HALT)) { throw new MigrationFailedException(this, message.toString(), e); } else if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.CONTINUE)) { skipChange = true; execType = ExecType.SKIPPED; } else if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.MARK_RAN)) { execType = ExecType.MARK_RAN; skipChange = true; log.info(LogType.LOG, "Marking ChangeSet: " + toString() + " ran despite precondition error: " + message); } else if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.WARN)) { execType = null; //already logged } else { throw new UnexpectedLiquibaseException("Unexpected precondition onError attribute: " + preconditions.getOnError(), e); } database.rollback(); } finally { database.rollback(); } if (!skipChange) { for (Change change : changes) { try { change.finishInitialization(); } catch (SetupException se) { throw new MigrationFailedException(this, se); } } log.debug(LogType.LOG, "Reading ChangeSet: " + toString()); for (Change change : getChanges()) { if ((!(change instanceof DbmsTargetedChange)) || DatabaseList.definitionMatches(((DbmsTargetedChange) change).getDbms(), database, true)) { if (listener != null) { listener.willRun(change, this, changeLog, database); } if (change.generateStatementsVolatile(database)) { executor.comment("WARNING The following SQL may change each run and therefore is possibly incorrect and/or invalid:"); } database.executeStatements(change, databaseChangeLog, sqlVisitors); log.info(LogType.LOG, change.getConfirmationMessage()); if (listener != null) { listener.ran(change, this, changeLog, database); } } else { log.debug(LogType.LOG, "Change " + change.getSerializedObjectName() + " not included for database " + database.getShortName()); } } if (runInTransaction) { database.commit(); } log.info(LogType.LOG, "ChangeSet " + toString(false) + " ran successfully in " + (new Date().getTime() - startTime + "ms")); if (execType == null) { execType = ExecType.EXECUTED; } } else { log.debug(LogType.LOG, "Skipping ChangeSet: " + toString()); } } catch (Exception e) { try { database.rollback(); } catch (Exception e1) { throw new MigrationFailedException(this, e); } if ((getFailOnError() != null) && !getFailOnError()) { log.info(LogType.LOG, "Change set " + toString(false) + " failed, but failOnError was false. Error: " + e.getMessage()); log.debug(LogType.LOG, "Failure Stacktrace", e); execType = ExecType.FAILED; } else { // just log the message, dont log the stacktrace by appending exception. Its logged anyway to stdout log.severe(LogType.LOG, "Change Set " + toString(false) + " failed. Error: " + e.getMessage()); if (e instanceof MigrationFailedException) { throw ((MigrationFailedException) e); } else { throw new MigrationFailedException(this, e); } } } finally { ExecutorService.getInstance().setExecutor("jdbc", database, originalExecutor); // restore auto-commit to false if this ChangeSet was not run in a transaction, // but only if the database supports DDL in transactions if (!runInTransaction && database.supportsDDLInTransaction()) { try { database.setAutoCommit(false); } catch (DatabaseException e) { throw new MigrationFailedException(this, "Could not resetInternalState autocommit", e); } } } return execType; } // Switch the Executor for a custom one if specified and we do not // have a LoggingExecutor private Executor switchExecutorIfNecessary(Database database) { Executor originalExecutor = ExecutorService.getInstance().getExecutor("jdbc", database); if (getRunWith() != null && !(originalExecutor instanceof LoggingExecutor)) { Executor customExecutor = ExecutorService.getInstance().getExecutor(getRunWith(), database); ExecutorService.getInstance().setExecutor("jdbc", database, customExecutor); } return originalExecutor; } public void rollback(Database database) throws RollbackFailedException { rollback(database, null); } public void rollback(Database database, ChangeExecListener listener) throws RollbackFailedException { try { Executor executor = ExecutorService.getInstance().getExecutor("jdbc", database); executor.comment("Rolling Back ChangeSet: " + toString()); database.setObjectQuotingStrategy(objectQuotingStrategy); // set auto-commit based on runInTransaction if database supports DDL in transactions if (database.supportsDDLInTransaction()) { database.setAutoCommit(!runInTransaction); } if (hasCustomRollbackChanges()) { final List<SqlStatement> statements = new LinkedList<>(); for (Change change : rollback.getChanges()) { if (((change instanceof DbmsTargetedChange)) && !DatabaseList.definitionMatches(((DbmsTargetedChange) change).getDbms(), database, true)) { continue; } if (listener != null) { listener.willRun(change, this, changeLog, database); } ValidationErrors errors = change.validate(database); if (errors.hasErrors()) { throw new RollbackFailedException("Rollback statement failed validation: "+errors.toString()); } SqlStatement[] changeStatements = change.generateStatements(database); if (changeStatements != null) { statements.addAll(Arrays.asList(changeStatements)); } if (listener != null) { listener.ran(change, this, changeLog, database); } } if (!statements.isEmpty()) { database.executeRollbackStatements(statements.toArray(new SqlStatement[]{}), sqlVisitors); } } else { List<Change> changes = getChanges(); for (int i = changes.size() - 1; i >= 0; i Change change = changes.get(i); database.executeRollbackStatements(change, sqlVisitors); } } if (runInTransaction) { database.commit(); } log.debug(LogType.LOG, "ChangeSet " + toString() + " has been successfully rolled back."); } catch (Exception e) { try { database.rollback(); } catch (DatabaseException e1) { } throw new RollbackFailedException(e); } finally { // restore auto-commit to false if this ChangeSet was not run in a transaction, // but only if the database supports DDL in transactions if (!runInTransaction && database.supportsDDLInTransaction()) { try { database.setAutoCommit(false); } catch (DatabaseException e) { throw new RollbackFailedException("Could not resetInternalState autocommit", e); } } } } /** * Returns whether custom rollback steps are specified for this changeSet, or whether auto-generated ones should be used */ protected boolean hasCustomRollbackChanges() { return (rollback != null) && (rollback.getChanges() != null) && !rollback.getChanges().isEmpty(); } /** * Returns an unmodifiable list of changes. To add one, use the addRefactoing method. */ public List<Change> getChanges() { return Collections.unmodifiableList(changes); } public void addChange(Change change) { if (change == null) { return; } changes.add(change); change.setChangeSet(this); } public String getId() { return id; } public String getAuthor() { return author; } public ContextExpression getContexts() { return contexts; } public Labels getLabels() { return labels; } public void setLabels(Labels labels) { this.labels = labels; } public Set<String> getDbmsSet() { return dbmsSet; } public boolean isIgnore() { return ignore; } public void setIgnore(boolean ignore) { this.ignore = ignore; } public boolean isInheritableIgnore() { DatabaseChangeLog changeLog = getChangeLog(); return changeLog.isIncludeIgnore(); } public Collection<ContextExpression> getInheritableContexts() { Collection<ContextExpression> expressions = new ArrayList<>(); DatabaseChangeLog changeLog = getChangeLog(); while (changeLog != null) { ContextExpression expression = changeLog.getContexts(); if ((expression != null) && !expression.isEmpty()) { expressions.add(expression); } ContextExpression includeExpression = changeLog.getIncludeContexts(); if ((includeExpression != null) && !includeExpression.isEmpty()) { expressions.add(includeExpression); } changeLog = changeLog.getParentChangeLog(); } return Collections.unmodifiableCollection(expressions); } public Collection<LabelExpression> getInheritableLabels() { Collection<LabelExpression> expressions = new ArrayList<LabelExpression>(); DatabaseChangeLog changeLog = getChangeLog(); while (changeLog != null) { LabelExpression expression = changeLog.getIncludeLabels(); if (expression != null && !expression.isEmpty()) { expressions.add(expression); } changeLog = changeLog.getParentChangeLog(); } return Collections.unmodifiableCollection(expressions); } public DatabaseChangeLog getChangeLog() { return changeLog; } public String toString(boolean includeMD5Sum) { return filePath + "::" + getId() + "::" + getAuthor() + (includeMD5Sum ? ("::(Checksum: " + generateCheckSum() + ")") : ""); } @Override public String toString() { return toString(false); } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public boolean isAlwaysRun() { return alwaysRun; } public boolean isRunOnChange() { return runOnChange; } public boolean isRunInTransaction() { return runInTransaction; } public RollbackContainer getRollback() { return rollback; } public void addRollBackSQL(String sql) { if (StringUtils.trimToNull(sql) == null) { if (rollback.getChanges().isEmpty()) { rollback.getChanges().add(new EmptyChange()); } return; } for (String statment : StringUtils.splitSQL(sql, null)) { rollback.getChanges().add(new RawSQLChange(statment.trim())); } } public void addRollbackChange(Change change) { if (change == null) { return; } rollback.getChanges().add(change); change.setChangeSet(this); } public boolean supportsRollback(Database database) { if ((rollback != null) && (rollback.getChanges() != null) && !rollback.getChanges().isEmpty()) { return true; } for (Change change : getChanges()) { if (!change.supportsRollback(database)) { return false; } } return true; } public String getDescription() { List<Change> changes = getChanges(); if (changes.isEmpty()) { return "empty"; } List<String> messages = new ArrayList<>(); for (Change change : changes) { messages.add(change.getDescription()); } return StringUtils.limitSize(StringUtils.join(messages, "; "), 255); } public Boolean getFailOnError() { return failOnError; } public void setFailOnError(Boolean failOnError) { this.failOnError = failOnError; } public ValidationFailOption getOnValidationFail() { return onValidationFail; } public void setOnValidationFail(ValidationFailOption onValidationFail) { this.onValidationFail = onValidationFail; } public void setValidationFailed(boolean validationFailed) { this.validationFailed = validationFailed; } public void addValidCheckSum(String text) { validCheckSums.add(CheckSum.parse(text)); } public Set<CheckSum> getValidCheckSums() { return Collections.unmodifiableSet(validCheckSums); } public boolean isCheckSumValid(CheckSum storedCheckSum) { // no need to generate the checksum if any has been set as the valid checksum for (CheckSum validCheckSum : validCheckSums) { if ("1:any".equalsIgnoreCase(validCheckSum.toString()) || "1:all".equalsIgnoreCase(validCheckSum.toString()) || "1:*".equalsIgnoreCase(validCheckSum.toString())) { return true; } } CheckSum currentMd5Sum = generateCheckSum(); if (currentMd5Sum == null) { return true; } if (storedCheckSum == null) { return true; } if (currentMd5Sum.equals(storedCheckSum)) { return true; } for (CheckSum validCheckSum : validCheckSums) { if (currentMd5Sum.equals(validCheckSum) || storedCheckSum.equals(validCheckSum)) { return true; } } return false; } @Override public PreconditionContainer getPreconditions() { return preconditions; } @Override public void setPreconditions(PreconditionContainer preconditionContainer) { this.preconditions = preconditionContainer; } public void addSqlVisitor(SqlVisitor sqlVisitor) { sqlVisitors.add(sqlVisitor); } public List<SqlVisitor> getSqlVisitors() { return sqlVisitors; } public ChangeLogParameters getChangeLogParameters() { return changeLogParameters; } /** * Called by the changelog parsing process to pass the {@link ChangeLogParameters}. */ public void setChangeLogParameters(ChangeLogParameters changeLogParameters) { this.changeLogParameters = changeLogParameters; } /** * Called to update file path from database entry when rolling back and ignoreClasspathPrefix is true. */ public void setFilePath(String filePath) { this.filePath = filePath; } public ObjectQuotingStrategy getObjectQuotingStrategy() { return objectQuotingStrategy; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public String getRunOrder() { return runOrder; } public void setRunOrder(String runOrder) { if (runOrder != null) { runOrder = runOrder.toLowerCase(); if (!"first".equals(runOrder) && !"last".equals(runOrder)) { throw new UnexpectedLiquibaseException("runOrder must be 'first' or 'last'"); } } this.runOrder = runOrder; } @Override public String getSerializedObjectName() { return "changeSet"; } @Override public Set<String> getSerializableFields() { return new LinkedHashSet<>( Arrays.asList( "id", "author", "runAlways", "runOnChange", "failOnError", "context", "labels", "dbms", "objectQuotingStrategy", "comment", "preconditions", "changes", "rollback", "labels", "objectQuotingStrategy", "created" ) ); } @Override public Object getSerializableFieldValue(String field) { if ("id".equals(field)) { return this.getId(); } if ("author".equals(field)) { return this.getAuthor(); } if ("runAlways".equals(field)) { if (this.isAlwaysRun()) { return true; } else { return null; } } if ("runOnChange".equals(field)) { if (this.isRunOnChange()) { return true; } else { return null; } } if ("failOnError".equals(field)) { return this.getFailOnError(); } if ("context".equals(field)) { if (!this.getContexts().isEmpty()) { return this.getContexts().toString().replaceFirst("^\\(", "").replaceFirst("\\)$", ""); } else { return null; } } if ("labels".equals(field)) { if ((this.getLabels() != null) && !this.getLabels().isEmpty()) { return StringUtils.join(this.getLabels().getLabels(), ", "); } else { return null; } } if ("dbms".equals(field)) { if ((this.getDbmsSet() != null) && !this.getDbmsSet().isEmpty()) { StringBuffer dbmsString = new StringBuffer(); for (String dbms : this.getDbmsSet()) { dbmsString.append(dbms).append(","); } return dbmsString.toString().replaceFirst(",$", ""); } else { return null; } } if ("comment".equals(field)) { return StringUtils.trimToNull(this.getComments()); } if ("objectQuotingStrategy".equals(field)) { if (this.getObjectQuotingStrategy() == null) { return null; } return this.getObjectQuotingStrategy().toString(); } if ("preconditions".equals(field)) { if ((this.getPreconditions() != null) && !this.getPreconditions().getNestedPreconditions().isEmpty()) { return this.getPreconditions(); } else { return null; } } if ("changes".equals(field)) { return getChanges(); } if ("created".equals(field)) { return getCreated(); } if ("rollback".equals(field)) { if ((rollback != null) && (rollback.getChanges() != null) && !rollback.getChanges().isEmpty()) { return rollback; } else { return null; } } throw new UnexpectedLiquibaseException("Unexpected field request on changeSet: "+field); } @Override public SerializationType getSerializableFieldType(String field) { if ("comment".equals(field) || "preconditions".equals(field) || "changes".equals(field) || "rollback".equals (field)) { return SerializationType.NESTED_OBJECT; } else { return SerializationType.NAMED_FIELD; } } @Override public String getSerializedObjectNamespace() { return STANDARD_CHANGELOG_NAMESPACE; } @Override public String getSerializableFieldNamespace(String field) { return getSerializedObjectNamespace(); } @Override public boolean equals(Object obj) { if (!(obj instanceof ChangeSet)) { return false; } return this.toString(false).equals(((ChangeSet) obj).toString(false)); } @Override public int hashCode() { return toString(false).hashCode(); } public Object getAttribute(String attribute) { return attributes.get(attribute); } public ChangeSet setAttribute(String attribute, Object value) { this.attributes.put(attribute, value); return this; } /** * Gets storedCheckSum * @return storedCheckSum if it was executed otherwise null */ public CheckSum getStoredCheckSum() { return storedCheckSum; } /** * Sets storedCheckSum in ValidatingVisitor in case when changeset was executed * @param storedCheckSum */ public void setStoredCheckSum(CheckSum storedCheckSum) { this.storedCheckSum = storedCheckSum; } }
package com.bafomdad.realfilingcabinet.crafting; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.ShapelessRecipes; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import com.bafomdad.realfilingcabinet.api.IEmptyFolder; import com.bafomdad.realfilingcabinet.api.IFolder; import com.bafomdad.realfilingcabinet.init.RFCBlocks; import com.bafomdad.realfilingcabinet.init.RFCItems; import com.bafomdad.realfilingcabinet.items.ItemFolder; public class FolderStorageRecipe extends ShapelessRecipes implements IRecipe { private List<ItemStack> inputs; public FolderStorageRecipe(ItemStack output, List<ItemStack> inputs) { super(output, inputs); this.inputs = inputs; } @Override public boolean matches(InventoryCrafting ic, World world) { ArrayList list = new ArrayList(this.inputs); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { ItemStack stack = ic.getStackInRowAndColumn(j, i); if (!stack.isEmpty()) { if (allowableIngredient(stack)) list.add(stack); boolean flag = false; Iterator iter = list.iterator(); while (iter.hasNext()) { ItemStack stack1 = (ItemStack)iter.next(); if (stack.getItem() == stack1.getItem() && (stack1.getItemDamage() == 32767 || stack.getItemDamage() == stack1.getItemDamage())) { flag = true; list.remove(stack1); break; } } if (!flag) return false; } } } return list.isEmpty(); } @Override public ItemStack getCraftingResult(InventoryCrafting ic) { int emptyFolder = -1; int recipestack = -1; for (int i = 0; i < ic.getSizeInventory(); i++) { ItemStack stack = ic.getStackInSlot(i); if (!stack.isEmpty()) { if (stack.getItem() instanceof IEmptyFolder) emptyFolder = i; else recipestack = i; } } if (emptyFolder >= 0 && recipestack >= 0) { ItemStack stack1 = ic.getStackInSlot(recipestack); ItemStack folder = ic.getStackInSlot(emptyFolder); if ((folder.getItemDamage() == 0 && !stack1.getItem().isRepairable()) || (folder.getItemDamage() == 1 && stack1.getItem().isRepairable())) { int damage = 0; if (folder.getItemDamage() == 1) damage = 2; ItemStack newFolder = new ItemStack(RFCItems.folder, 1, damage); ItemFolder.setObject(newFolder, stack1); return newFolder; } } return ItemStack.EMPTY; // return new ItemStack(RFCItems.emptyFolder, 1, Math.max(recipeOutput.getItemDamage() - 1, 0)); } private boolean allowableIngredient(ItemStack stack) { if (stack.getItem() instanceof IFolder || stack.getItem() instanceof IEmptyFolder || stack.getItem() == Item.getItemFromBlock(RFCBlocks.blockRFC)) return false; if (stack.hasTagCompound()) return false; return true; } }
package liquibase.change; import org.junit.Test; import java.io.ByteArrayInputStream; import static org.junit.Assert.*; public class CheckSumTest { @Test public void parse() { String checksumString = "3:asdf"; CheckSum checkSum = CheckSum.parse(checksumString); assertEquals(3, checkSum.getVersion()); assertEquals(checksumString, checkSum.toString()); } @Test public void parse_null() { assertNull(CheckSum.parse(null)); } @Test public void parse_v1() { String checksumString = "asdf"; CheckSum checkSum = CheckSum.parse(checksumString); assertEquals(1, checkSum.getVersion()); assertEquals("1:asdf", checkSum.toString()); } @Test public void getCurrentVersion() { assertEquals(8, CheckSum.getCurrentVersion()); } @Test public void compute_String() { String valueToHash = "asdf"; CheckSum checkSum = CheckSum.compute(valueToHash); assertEquals(CheckSum.getCurrentVersion(), checkSum.getVersion()); assertNotEquals(checkSum.toString(), valueToHash); } @Test public void compute_String_shouldIgnoreUnknownUnicodeChar() { CheckSum checkSum1 = CheckSum.compute("asdfa"); CheckSum checkSum2 = CheckSum.compute("as\uFFFDdf\uFFFDa"); assertEquals(checkSum2, checkSum1); } @Test public void compute_Stream() { String valueToHash = "asdf"; CheckSum checkSum = CheckSum.compute(new ByteArrayInputStream(valueToHash.getBytes()), false); assertEquals(CheckSum.getCurrentVersion(), checkSum.getVersion()); assertNotEquals(checkSum.toString(), valueToHash); assertEquals(CheckSum.compute(valueToHash).toString(), checkSum.toString()); } @Test public void toString_test() { assertTrue(CheckSum.parse("9:asdf").toString().startsWith("9:")); } @Test public void equals() { assertEquals(CheckSum.parse("9:asdf"), CheckSum.parse("9:asdf")); assertNotEquals(CheckSum.parse("9:asdf"), CheckSum.parse("8:asdf")); assertNotEquals(CheckSum.parse("9:asdf"), CheckSum.parse("9:qwert")); assertNotEquals(12, CheckSum.parse("9:asdf")); assertFalse(CheckSum.parse("9:asdf").equals(null)); } @Test public void compute_lineEndingsDontMatter() { String checkSum = CheckSum.compute("a string\nwith\nlines").toString(); // assertEquals(checkSum, CheckSum.compute("a string\rwith\rlines").toString()); assertEquals(checkSum, CheckSum.compute("a string\r\nwith\r\nlines").toString()); assertEquals(checkSum, CheckSum.compute("a string\rwith\nlines").toString()); assertNotEquals(checkSum, CheckSum.compute("a string\n\nwith\n\nlines").toString()); assertEquals(checkSum, CheckSum.compute(new ByteArrayInputStream("a string\nwith\nlines".getBytes()), true).toString()); // assertEquals(checkSum, CheckSum.compute(new ByteArrayInputStream("a string\rwith\rlines".getBytes()), true).toString()); assertEquals(checkSum, CheckSum.compute(new ByteArrayInputStream("a string\r\nwith\r\nlines".getBytes()), true).toString()); // assertEquals(checkSum, CheckSum.compute(new ByteArrayInputStream("a string\rwith\r\nlines".getBytes()), true).toString()); } @Test public void compute_lineEndingsDontMatter_multiline() { String checkSum = CheckSum.compute("a string\n\nwith\n\nlines").toString(); assertEquals(checkSum, CheckSum.compute("a string\r\rwith\r\rlines").toString()); assertEquals(checkSum, CheckSum.compute("a string\r\n\r\nwith\r\n\r\nlines").toString()); assertEquals(checkSum, CheckSum.compute(new ByteArrayInputStream("a string\n\nwith\n\nlines".getBytes()), true).toString()); // assertEquals(checkSum, CheckSum.compute(new ByteArrayInputStream("a string\r\rwith\r\rlines".getBytes()), true).toString()); assertEquals(checkSum, CheckSum.compute(new ByteArrayInputStream("a string\r\n\r\nwith\r\n\r\nlines".getBytes()), true).toString()); } }
package ru.ilb.common.jpa.bitset; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.BitSet; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Store Sets as bit field * * To use, need to define class, extending BitSet: public class CreateOptionsSet * extends BitSet&lt;CreateOptions> { public CreateOptionsSet() { } public CreateOptionsSet(Long bitSet) { super(bitSet); } public CreateOptionsSet(Collection&lt;CreateOptions> items) { super(items); } * } define AttributeConverter and include in persistance.xml: * <pre> * {@code * @Converter(autoApply = true) * public class ApplicationFactConverter implements AttributeConverter<ApplicationFactSet, byte[]> { * * @Override * public byte[] convertToDatabaseColumn(ApplicationFactSet attribute) { * return attribute == null ? null : attribute.toByteArray(); * } * * @Override * public ApplicationFactSet convertToEntityAttribute(byte[] dbData) { * return dbData == null ? null : new ApplicationFactSet(dbData); * } * * } * } * </pre> * * @author slavb * @param <T> stored object type */ public class BigBitSet<T> implements Serializable { // protected int MAX_BIT_LENGTH = 128; protected BitSet bitSet; private final BitAccessor accessor; @Override public int hashCode() { int hash = 3; hash = 29 * hash + Objects.hashCode(this.bitSet); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BigBitSet<?> other = (BigBitSet<?>) obj; if (!Objects.equals(this.bitSet, other.bitSet)) { return false; } return true; } public BigBitSet() { Class<T> clazz = getParamClass(0); accessor = clazz.isEnum() ? new EnumBitAccessor() : new EntityBitAccessor(clazz); } public BigBitSet(BitSet bitSet) { this(); this.bitSet = bitSet; } public BigBitSet(byte[] value) { this(); this.bitSet = BitSet.valueOf(value); } public BigBitSet(Collection<T> items) { this(); addAll(items); } private Class<T> getParamClass(int pos) { return (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()) .getActualTypeArguments()[pos]; } public BitSet getBitSet() { return this.bitSet; } public byte[] toByteArray() { return bitSet!=null ? bitSet.toByteArray() : null; } public void setBitSet(BitSet bitSet) { this.bitSet = bitSet; } public boolean contains(T item) { return bitSet != null && bitSet.get(accessor.getBitNum(item)); } public boolean containsAll(Collection<T> items) { Boolean res = items.stream().map(this::contains).reduce((c1, c2) -> c1 && c2).orElse(Boolean.FALSE); return res; } public boolean containsAll(T... items) { //optimize this return Stream.of(items).map(this::contains).reduce((c1, c2) -> c1 && c2).orElse(Boolean.FALSE); } public boolean containsAny(Collection<T> items) { //optimize this return items.stream().map(this::contains).reduce((c1, c2) -> c1 || c2).orElse(Boolean.FALSE); } public boolean containsAny(T... items) { //optimize this return Stream.of(items).map(this::contains).reduce((c1, c2) -> c1 || c2).orElse(Boolean.FALSE); } public boolean remove(T item) { boolean res = false; if (bitSet != null) { int bitNum = accessor.getBitNum(item); res = bitSet.get(bitNum); bitSet.clear(bitNum); } return res; } public void add(T item) { if (bitSet == null) { bitSet = new BitSet(); } int bitNum = accessor.getBitNum(item); bitSet.set(bitNum); } public void set(T item, boolean value) { if (bitSet == null) { bitSet = new BitSet(); } int bitNum = accessor.getBitNum(item); bitSet.set(bitNum, value); } final public void addAll(Collection<T> items) { items.forEach(this::add); } public void removeAll(Collection<T> items) { items.forEach(this::remove); } public List<Integer> getSetBits() { //List<Integer> res = new ArrayList<>(); List<Integer> res = bitSet!=null ? bitSet.stream().boxed().collect(Collectors.toList()): new ArrayList<>(); return res; //return res; } }
package com.airbnb.lottie; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.View; import androidx.annotation.AttrRes; import androidx.annotation.DrawableRes; import androidx.annotation.FloatRange; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RawRes; import androidx.annotation.RequiresApi; import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.AppCompatImageView; import androidx.core.view.ViewCompat; import com.airbnb.lottie.model.KeyPath; import com.airbnb.lottie.utils.Logger; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.LottieFrameInfo; import com.airbnb.lottie.value.LottieValueCallback; import com.airbnb.lottie.value.SimpleLottieValueCallback; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import static com.airbnb.lottie.RenderMode.HARDWARE; @SuppressWarnings({"WeakerAccess"}) public class LottieAnimationView extends AppCompatImageView { private static final String TAG = LottieAnimationView.class.getSimpleName(); private static final LottieListener<Throwable> DEFAULT_FAILURE_LISTENER = new LottieListener<Throwable>() { @Override public void onResult(Throwable throwable) { // By default, fail silently for network errors. if (Utils.isNetworkException(throwable)) { Logger.warning("Unable to load composition.", throwable); return; } throw new IllegalStateException("Unable to parse composition", throwable); } }; private final LottieListener<LottieComposition> loadedListener = new LottieListener<LottieComposition>() { @Override public void onResult(LottieComposition composition) { setComposition(composition); } }; private final LottieListener<Throwable> wrappedFailureListener = new LottieListener<Throwable>() { @Override public void onResult(Throwable result) { if (fallbackResource != 0) { setImageResource(fallbackResource); } LottieListener<Throwable> l = failureListener == null ? DEFAULT_FAILURE_LISTENER : failureListener; l.onResult(result); } }; @Nullable private LottieListener<Throwable> failureListener; @DrawableRes private int fallbackResource = 0; private final LottieDrawable lottieDrawable = new LottieDrawable(); private boolean isInitialized; private String animationName; private @RawRes int animationResId; private boolean playAnimationWhenShown = false; private boolean wasAnimatingWhenNotShown = false; private boolean wasAnimatingWhenDetached = false; /** * When we set a new composition, we set LottieDrawable to null then back again so that ImageView re-checks its bounds. * However, this causes the drawable to get unscheduled briefly. Normally, we would pause the animation but in this case, we don't want to. */ private boolean ignoreUnschedule = false; private boolean autoPlay = false; private boolean cacheComposition = true; private RenderMode renderMode = RenderMode.AUTOMATIC; private final Set<LottieOnCompositionLoadedListener> lottieOnCompositionLoadedListeners = new HashSet<>(); /** * Prevents a StackOverflowException on 4.4 in which getDrawingCache() calls buildDrawingCache(). * This isn't a great solution but it works and has very little performance overhead. * At some point in the future, the original goal of falling back to hardware rendering when * the animation is set to software rendering but it is too large to fit in a software bitmap * should be reevaluated. */ private int buildDrawingCacheDepth = 0; @Nullable private LottieTask<LottieComposition> compositionTask; /** Can be null because it is created async */ @Nullable private LottieComposition composition; public LottieAnimationView(Context context) { super(context); init(null, R.attr.lottieAnimationViewStyle); } public LottieAnimationView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, R.attr.lottieAnimationViewStyle); } public LottieAnimationView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } private void init(@Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.LottieAnimationView, defStyleAttr, 0); cacheComposition = ta.getBoolean(R.styleable.LottieAnimationView_lottie_cacheComposition, true); boolean hasRawRes = ta.hasValue(R.styleable.LottieAnimationView_lottie_rawRes); boolean hasFileName = ta.hasValue(R.styleable.LottieAnimationView_lottie_fileName); boolean hasUrl = ta.hasValue(R.styleable.LottieAnimationView_lottie_url); if (hasRawRes && hasFileName) { throw new IllegalArgumentException("lottie_rawRes and lottie_fileName cannot be used at " + "the same time. Please use only one at once."); } else if (hasRawRes) { int rawResId = ta.getResourceId(R.styleable.LottieAnimationView_lottie_rawRes, 0); if (rawResId != 0) { setAnimation(rawResId); } } else if (hasFileName) { String fileName = ta.getString(R.styleable.LottieAnimationView_lottie_fileName); if (fileName != null) { setAnimation(fileName); } } else if (hasUrl) { String url = ta.getString(R.styleable.LottieAnimationView_lottie_url); if (url != null) { setAnimationFromUrl(url); } } setFallbackResource(ta.getResourceId(R.styleable.LottieAnimationView_lottie_fallbackRes, 0)); if (ta.getBoolean(R.styleable.LottieAnimationView_lottie_autoPlay, false)) { wasAnimatingWhenDetached = true; autoPlay = true; } if (ta.getBoolean(R.styleable.LottieAnimationView_lottie_loop, false)) { lottieDrawable.setRepeatCount(LottieDrawable.INFINITE); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_repeatMode)) { setRepeatMode(ta.getInt(R.styleable.LottieAnimationView_lottie_repeatMode, LottieDrawable.RESTART)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_repeatCount)) { setRepeatCount(ta.getInt(R.styleable.LottieAnimationView_lottie_repeatCount, LottieDrawable.INFINITE)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_speed)) { setSpeed(ta.getFloat(R.styleable.LottieAnimationView_lottie_speed, 1f)); } setImageAssetsFolder(ta.getString(R.styleable.LottieAnimationView_lottie_imageAssetsFolder)); setProgress(ta.getFloat(R.styleable.LottieAnimationView_lottie_progress, 0)); enableMergePathsForKitKatAndAbove(ta.getBoolean( R.styleable.LottieAnimationView_lottie_enableMergePathsForKitKatAndAbove, false)); if (ta.hasValue(R.styleable.LottieAnimationView_lottie_colorFilter)) { int colorRes = ta.getResourceId(R.styleable.LottieAnimationView_lottie_colorFilter, -1); ColorStateList csl = AppCompatResources.getColorStateList(getContext(), colorRes); SimpleColorFilter filter = new SimpleColorFilter(csl.getDefaultColor()); KeyPath keyPath = new KeyPath("**"); LottieValueCallback<ColorFilter> callback = new LottieValueCallback<ColorFilter>(filter); addValueCallback(keyPath, LottieProperty.COLOR_FILTER, callback); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_scale)) { lottieDrawable.setScale(ta.getFloat(R.styleable.LottieAnimationView_lottie_scale, 1f)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_renderMode)) { int renderModeOrdinal = ta.getInt(R.styleable.LottieAnimationView_lottie_renderMode, RenderMode.AUTOMATIC.ordinal()); if (renderModeOrdinal >= RenderMode.values().length) { renderModeOrdinal = RenderMode.AUTOMATIC.ordinal(); } setRenderMode(RenderMode.values()[renderModeOrdinal]); } ta.recycle(); lottieDrawable.setSystemAnimationsAreEnabled(Utils.getAnimationScale(getContext()) != 0f); enableOrDisableHardwareLayer(); isInitialized = true; } @Override public void setImageResource(int resId) { cancelLoaderTask(); super.setImageResource(resId); } @Override public void setImageDrawable(Drawable drawable) { cancelLoaderTask(); super.setImageDrawable(drawable); } @Override public void setImageBitmap(Bitmap bm) { cancelLoaderTask(); super.setImageBitmap(bm); } @Override public void unscheduleDrawable(Drawable who) { if (!ignoreUnschedule && who == lottieDrawable && lottieDrawable.isAnimating()) { pauseAnimation(); } else if (!ignoreUnschedule && who instanceof LottieDrawable && ((LottieDrawable) who).isAnimating()) { ((LottieDrawable) who).pauseAnimation(); } super.unscheduleDrawable(who); } @Override public void invalidateDrawable(@NonNull Drawable dr) { if (getDrawable() == lottieDrawable) { // We always want to invalidate the root drawable so it redraws the whole drawable. // Eventually it would be great to be able to invalidate just the changed region. super.invalidateDrawable(lottieDrawable); } else { // Otherwise work as regular ImageView super.invalidateDrawable(dr); } } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.animationName = animationName; ss.animationResId = animationResId; ss.progress = lottieDrawable.getProgress(); ss.isAnimating = lottieDrawable.isAnimating() || (!ViewCompat.isAttachedToWindow(this) && wasAnimatingWhenDetached); ss.imageAssetsFolder = lottieDrawable.getImageAssetsFolder(); ss.repeatMode = lottieDrawable.getRepeatMode(); ss.repeatCount = lottieDrawable.getRepeatCount(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); animationName = ss.animationName; if (!TextUtils.isEmpty(animationName)) { setAnimation(animationName); } animationResId = ss.animationResId; if (animationResId != 0) { setAnimation(animationResId); } setProgress(ss.progress); if (ss.isAnimating) { playAnimation(); } lottieDrawable.setImagesAssetsFolder(ss.imageAssetsFolder); setRepeatMode(ss.repeatMode); setRepeatCount(ss.repeatCount); } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { // This can happen on older versions of Android because onVisibilityChanged gets called from the // constructor of View so this will get called before lottieDrawable gets initialized. // A simple null check on lottieDrawable would not work because when using Proguard optimization, a // null check on a final field gets removed. As "usually" final fields cannot be null. // However because this is called by super (View) before the initializer of the LottieAnimationView // is called, it actually can be null here. // Working around this by using a non final boolean that is set to true after the class initializer // has run. if (!isInitialized) { return; } if (isShown()) { if (wasAnimatingWhenNotShown) { resumeAnimation(); } else if (playAnimationWhenShown) { playAnimation(); } wasAnimatingWhenNotShown = false; playAnimationWhenShown = false; } else { if (isAnimating()) { pauseAnimation(); wasAnimatingWhenNotShown = true; } } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (!isInEditMode() && (autoPlay || wasAnimatingWhenDetached)) { playAnimation(); // Autoplay from xml should only apply once. autoPlay = false; wasAnimatingWhenDetached = false; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // This is needed to mimic newer platform behavior. onVisibilityChanged(this, getVisibility()); } } @Override protected void onDetachedFromWindow() { if (isAnimating()) { cancelAnimation(); wasAnimatingWhenDetached = true; } super.onDetachedFromWindow(); } /** * Enable this to get merge path support for devices running KitKat (19) and above. * * Merge paths currently don't work if the the operand shape is entirely contained within the * first shape. If you need to cut out one shape from another shape, use an even-odd fill type * instead of using merge paths. */ public void enableMergePathsForKitKatAndAbove(boolean enable) { lottieDrawable.enableMergePathsForKitKatAndAbove(enable); } /** * Returns whether merge paths are enabled for KitKat and above. */ public boolean isMergePathsEnabledForKitKatAndAbove() { return lottieDrawable.isMergePathsEnabledForKitKatAndAbove(); } /** * If set to true, all future compositions that are set will be cached so that they don't need to be parsed * next time they are loaded. This won't apply to compositions that have already been loaded. * * Defaults to true. * * {@link R.attr#lottie_cacheComposition} */ public void setCacheComposition(boolean cacheComposition) { this.cacheComposition = cacheComposition; } /** * Enable this to debug slow animations by outlining masks and mattes. The performance overhead of the masks and mattes will * be proportional to the surface area of all of the masks/mattes combined. * * DO NOT leave this enabled in production. */ public void setOutlineMasksAndMattes(boolean outline) { lottieDrawable.setOutlineMasksAndMattes(outline); } /** * Sets the animation from a file in the raw directory. * This will load and deserialize the file asynchronously. */ public void setAnimation(@RawRes final int rawRes) { this.animationResId = rawRes; animationName = null; setCompositionTask(fromRawRes(rawRes)); } private LottieTask<LottieComposition> fromRawRes(@RawRes final int rawRes) { if (isInEditMode()) { return new LottieTask<>(new Callable<LottieResult<LottieComposition>>() { @Override public LottieResult<LottieComposition> call() { return cacheComposition ? LottieCompositionFactory.fromRawResSync(getContext(), rawRes) : LottieCompositionFactory.fromRawResSync(getContext(), rawRes, null); } }, true); } else { return cacheComposition ? LottieCompositionFactory.fromRawRes(getContext(), rawRes) : LottieCompositionFactory.fromRawRes(getContext(), rawRes, null); } } public void setAnimation(final String assetName) { this.animationName = assetName; animationResId = 0; setCompositionTask(fromAssets(assetName)); } private LottieTask<LottieComposition> fromAssets(final String assetName) { if (isInEditMode()) { return new LottieTask<>(new Callable<LottieResult<LottieComposition>>() { @Override public LottieResult<LottieComposition> call() { return cacheComposition ? LottieCompositionFactory.fromAssetSync(getContext(), assetName) : LottieCompositionFactory.fromAssetSync(getContext(), assetName, null); } }, true); } else { return cacheComposition ? LottieCompositionFactory.fromAsset(getContext(), assetName) : LottieCompositionFactory.fromAsset(getContext(), assetName, null); } } /** * @see #setAnimationFromJson(String, String) */ @Deprecated public void setAnimationFromJson(String jsonString) { setAnimationFromJson(jsonString, null); } /** * Sets the animation from json string. This is the ideal API to use when loading an animation * over the network because you can use the raw response body here and a conversion to a * JSONObject never has to be done. */ public void setAnimationFromJson(String jsonString, @Nullable String cacheKey) { setAnimation(new ByteArrayInputStream(jsonString.getBytes()), cacheKey); } /** * Sets the animation from an arbitrary InputStream. * This will load and deserialize the file asynchronously. * <p> * This is particularly useful for animations loaded from the network. You can fetch the * bodymovin json from the network and pass it directly here. */ public void setAnimation(InputStream stream, @Nullable String cacheKey) { setCompositionTask(LottieCompositionFactory.fromJsonInputStream(stream, cacheKey)); } /** * Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together and lottie * will unzip and link the images automatically. * * Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the file * to the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one that * can be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted. * * You can replace the default network stack or cache handling with a global {@link LottieConfig} * * @see LottieConfig.Builder * @see Lottie#initialize(LottieConfig) */ public void setAnimationFromUrl(String url) { LottieTask<LottieComposition> task = cacheComposition ? LottieCompositionFactory.fromUrl(getContext(), url) : LottieCompositionFactory.fromUrl(getContext(), url, null); setCompositionTask(task); } /** * Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together and lottie * will unzip and link the images automatically. * * Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the file * to the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one that * can be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted. * * You can replace the default network stack or cache handling with a global {@link LottieConfig} * * @see LottieConfig.Builder * @see Lottie#initialize(LottieConfig) */ public void setAnimationFromUrl(String url, @Nullable String cacheKey) { LottieTask<LottieComposition> task = LottieCompositionFactory.fromUrl(getContext(), url, cacheKey); setCompositionTask(task); } /** * Set a default failure listener that will be called if any of the setAnimation APIs fail for any reason. * This can be used to replace the default behavior. * * The default behavior will log any network errors and rethrow all other exceptions. * * If you are loading an animation from the network, errors may occur if your user has no internet. * You can use this listener to retry the download or you can have it default to an error drawable * with {@link #setFallbackResource(int)}. * * Unless you are using {@link #setAnimationFromUrl(String)}, errors are unexpected. * * Set the listener to null to revert to the default behavior. */ public void setFailureListener(@Nullable LottieListener<Throwable> failureListener) { this.failureListener = failureListener; } /** * Set a drawable that will be rendered if the LottieComposition fails to load for any reason. * Unless you are using {@link #setAnimationFromUrl(String)}, this is an unexpected error and * you should handle it with {@link #setFailureListener(LottieListener)}. * * If this is a network animation, you may use this to show an error to the user or * you can use a failure listener to retry the download. */ public void setFallbackResource(@DrawableRes int fallbackResource) { this.fallbackResource = fallbackResource; } private void setCompositionTask(LottieTask<LottieComposition> compositionTask) { clearComposition(); cancelLoaderTask(); this.compositionTask = compositionTask .addListener(loadedListener) .addFailureListener(wrappedFailureListener); } private void cancelLoaderTask() { if (compositionTask != null) { compositionTask.removeListener(loadedListener); compositionTask.removeFailureListener(wrappedFailureListener); } } /** * Sets a composition. * You can set a default cache strategy if this view was inflated with xml by * using {@link R.attr#lottie_cacheComposition}. */ public void setComposition(@NonNull LottieComposition composition) { if (L.DBG) { Log.v(TAG, "Set Composition \n" + composition); } lottieDrawable.setCallback(this); this.composition = composition; ignoreUnschedule = true; boolean isNewComposition = lottieDrawable.setComposition(composition); ignoreUnschedule = false; enableOrDisableHardwareLayer(); if (getDrawable() == lottieDrawable && !isNewComposition) { // We can avoid re-setting the drawable, and invalidating the view, since the composition // hasn't changed. return; } else if (!isNewComposition) { // The current drawable isn't lottieDrawable but the drawable already has the right composition. setLottieDrawable(); } // This is needed to makes sure that the animation is properly played/paused for the current visibility state. // It is possible that the drawable had a lazy composition task to play the animation but this view subsequently // became invisible. Comment this out and run the espresso tests to see a failing test. onVisibilityChanged(this, getVisibility()); requestLayout(); for (LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener : lottieOnCompositionLoadedListeners) { lottieOnCompositionLoadedListener.onCompositionLoaded(composition); } } @Nullable public LottieComposition getComposition() { return composition; } /** * Returns whether or not any layers in this composition has masks. */ public boolean hasMasks() { return lottieDrawable.hasMasks(); } /** * Returns whether or not any layers in this composition has a matte layer. */ public boolean hasMatte() { return lottieDrawable.hasMatte(); } /** * Plays the animation from the beginning. If speed is {@literal <} 0, it will start at the end * and play towards the beginning */ @MainThread public void playAnimation() { if (isShown()) { lottieDrawable.playAnimation(); enableOrDisableHardwareLayer(); } else { playAnimationWhenShown = true; } } /** * Continues playing the animation from its current position. If speed {@literal <} 0, it will play backwards * from the current position. */ @MainThread public void resumeAnimation() { if (isShown()) { lottieDrawable.resumeAnimation(); enableOrDisableHardwareLayer(); } else { playAnimationWhenShown = false; wasAnimatingWhenNotShown = true; } } /** * Sets the minimum frame that the animation will start from when playing or looping. */ public void setMinFrame(int startFrame) { lottieDrawable.setMinFrame(startFrame); } /** * Returns the minimum frame set by {@link #setMinFrame(int)} or {@link #setMinProgress(float)} */ public float getMinFrame() { return lottieDrawable.getMinFrame(); } /** * Sets the minimum progress that the animation will start from when playing or looping. */ public void setMinProgress(float startProgress) { lottieDrawable.setMinProgress(startProgress); } /** * Sets the maximum frame that the animation will end at when playing or looping. * * The value will be clamped to the composition bounds. For example, setting Integer.MAX_VALUE would result in the same * thing as composition.endFrame. */ public void setMaxFrame(int endFrame) { lottieDrawable.setMaxFrame(endFrame); } /** * Returns the maximum frame set by {@link #setMaxFrame(int)} or {@link #setMaxProgress(float)} */ public float getMaxFrame() { return lottieDrawable.getMaxFrame(); } /** * Sets the maximum progress that the animation will end at when playing or looping. */ public void setMaxProgress(@FloatRange(from = 0f, to = 1f) float endProgress) { lottieDrawable.setMaxProgress(endProgress); } public void setMinFrame(String markerName) { lottieDrawable.setMinFrame(markerName); } public void setMaxFrame(String markerName) { lottieDrawable.setMaxFrame(markerName); } public void setMinAndMaxFrame(String markerName) { lottieDrawable.setMinAndMaxFrame(markerName); } public void setMinAndMaxFrame(final String startMarkerName, final String endMarkerName, final boolean playEndMarkerStartFrame) { lottieDrawable.setMinAndMaxFrame(startMarkerName, endMarkerName, playEndMarkerStartFrame); } /** * @see #setMinFrame(int) * @see #setMaxFrame(int) */ public void setMinAndMaxFrame(int minFrame, int maxFrame) { lottieDrawable.setMinAndMaxFrame(minFrame, maxFrame); } /** * @see #setMinProgress(float) * @see #setMaxProgress(float) */ public void setMinAndMaxProgress( @FloatRange(from = 0f, to = 1f) float minProgress, @FloatRange(from = 0f, to = 1f) float maxProgress) { lottieDrawable.setMinAndMaxProgress(minProgress, maxProgress); } /** * Reverses the current animation speed. This does NOT play the animation. * @see #setSpeed(float) * @see #playAnimation() * @see #resumeAnimation() */ public void reverseAnimationSpeed() { lottieDrawable.reverseAnimationSpeed(); } /** * Sets the playback speed. If speed {@literal <} 0, the animation will play backwards. */ public void setSpeed(float speed) { lottieDrawable.setSpeed(speed); } /** * Returns the current playback speed. This will be {@literal <} 0 if the animation is playing backwards. */ public float getSpeed() { return lottieDrawable.getSpeed(); } public void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { lottieDrawable.addAnimatorUpdateListener(updateListener); } public void removeUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { lottieDrawable.removeAnimatorUpdateListener(updateListener); } public void removeAllUpdateListeners() { lottieDrawable.removeAllUpdateListeners(); } public void addAnimatorListener(Animator.AnimatorListener listener) { lottieDrawable.addAnimatorListener(listener); } public void removeAnimatorListener(Animator.AnimatorListener listener) { lottieDrawable.removeAnimatorListener(listener); } public void removeAllAnimatorListeners() { lottieDrawable.removeAllAnimatorListeners(); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void addAnimatorPauseListener(Animator.AnimatorPauseListener listener) { lottieDrawable.addAnimatorPauseListener(listener); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void removeAnimatorPauseListener(Animator.AnimatorPauseListener listener) { lottieDrawable.removeAnimatorPauseListener(listener); } /** * @see #setRepeatCount(int) */ @Deprecated public void loop(boolean loop) { lottieDrawable.setRepeatCount(loop ? ValueAnimator.INFINITE : 0); } /** * Defines what this animation should do when it reaches the end. This * setting is applied only when the repeat count is either greater than * 0 or {@link LottieDrawable#INFINITE}. Defaults to {@link LottieDrawable#RESTART}. * * @param mode {@link LottieDrawable#RESTART} or {@link LottieDrawable#REVERSE} */ public void setRepeatMode(@LottieDrawable.RepeatMode int mode) { lottieDrawable.setRepeatMode(mode); } /** * Defines what this animation should do when it reaches the end. * * @return either one of {@link LottieDrawable#REVERSE} or {@link LottieDrawable#RESTART} */ @LottieDrawable.RepeatMode public int getRepeatMode() { return lottieDrawable.getRepeatMode(); } /** * Sets how many times the animation should be repeated. If the repeat * count is 0, the animation is never repeated. If the repeat count is * greater than 0 or {@link LottieDrawable#INFINITE}, the repeat mode will be taken * into account. The repeat count is 0 by default. * * @param count the number of times the animation should be repeated */ public void setRepeatCount(int count) { lottieDrawable.setRepeatCount(count); } /** * Defines how many times the animation should repeat. The default value * is 0. * * @return the number of times the animation should repeat, or {@link LottieDrawable#INFINITE} */ public int getRepeatCount() { return lottieDrawable.getRepeatCount(); } public boolean isAnimating() { return lottieDrawable.isAnimating(); } public void setImageAssetsFolder(String imageAssetsFolder) { lottieDrawable.setImagesAssetsFolder(imageAssetsFolder); } @Nullable public String getImageAssetsFolder() { return lottieDrawable.getImageAssetsFolder(); } /** * Allows you to modify or clear a bitmap that was loaded for an image either automatically * through {@link #setImageAssetsFolder(String)} or with an {@link ImageAssetDelegate}. * * @return the previous Bitmap or null. */ @Nullable public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) { return lottieDrawable.updateBitmap(id, bitmap); } public void setImageAssetDelegate(ImageAssetDelegate assetDelegate) { lottieDrawable.setImageAssetDelegate(assetDelegate); } /** * Use this to manually set fonts. */ public void setFontAssetDelegate(FontAssetDelegate assetDelegate) { lottieDrawable.setFontAssetDelegate(assetDelegate); } /** * Set this to replace animation text with custom text at runtime */ public void setTextDelegate(TextDelegate textDelegate) { lottieDrawable.setTextDelegate(textDelegate); } /** * Takes a {@link KeyPath}, potentially with wildcards or globstars and resolve it to a list of * zero or more actual {@link KeyPath Keypaths} that exist in the current animation. * * If you want to set value callbacks for any of these values, it is recommended to use the * returned {@link KeyPath} objects because they will be internally resolved to their content * and won't trigger a tree walk of the animation contents when applied. */ public List<KeyPath> resolveKeyPath(KeyPath keyPath) { return lottieDrawable.resolveKeyPath(keyPath); } /** * Add a property callback for the specified {@link KeyPath}. This {@link KeyPath} can resolve * to multiple contents. In that case, the callback's value will apply to all of them. * * Internally, this will check if the {@link KeyPath} has already been resolved with * {@link #resolveKeyPath(KeyPath)} and will resolve it if it hasn't. */ public <T> void addValueCallback(KeyPath keyPath, T property, LottieValueCallback<T> callback) { lottieDrawable.addValueCallback(keyPath, property, callback); } /** * Overload of {@link #addValueCallback(KeyPath, Object, LottieValueCallback)} that takes an interface. This allows you to use a single abstract * method code block in Kotlin such as: * animationView.addValueCallback(yourKeyPath, LottieProperty.COLOR) { yourColor } */ public <T> void addValueCallback(KeyPath keyPath, T property, final SimpleLottieValueCallback<T> callback) { lottieDrawable.addValueCallback(keyPath, property, new LottieValueCallback<T>() { @Override public T getValue(LottieFrameInfo<T> frameInfo) { return callback.getValue(frameInfo); } }); } /** * Set the scale on the current composition. The only cost of this function is re-rendering the * current frame so you may call it frequent to scale something up or down. * * The smaller the animation is, the better the performance will be. You may find that scaling an * animation down then rendering it in a larger ImageView and letting ImageView scale it back up * with a scaleType such as centerInside will yield better performance with little perceivable * quality loss. * * You can also use a fixed view width/height in conjunction with the normal ImageView * scaleTypes centerCrop and centerInside. */ public void setScale(float scale) { lottieDrawable.setScale(scale); if (getDrawable() == lottieDrawable) { setLottieDrawable(); } } public float getScale() { return lottieDrawable.getScale(); } @MainThread public void cancelAnimation() { wasAnimatingWhenDetached = false; wasAnimatingWhenNotShown = false; playAnimationWhenShown = false; lottieDrawable.cancelAnimation(); enableOrDisableHardwareLayer(); } @MainThread public void pauseAnimation() { autoPlay = false; wasAnimatingWhenDetached = false; wasAnimatingWhenNotShown = false; playAnimationWhenShown = false; lottieDrawable.pauseAnimation(); enableOrDisableHardwareLayer(); } /** * Sets the progress to the specified frame. * If the composition isn't set yet, the progress will be set to the frame when * it is. */ public void setFrame(int frame) { lottieDrawable.setFrame(frame); } /** * Get the currently rendered frame. */ public int getFrame() { return lottieDrawable.getFrame(); } public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) { lottieDrawable.setProgress(progress); } @FloatRange(from = 0.0f, to = 1.0f) public float getProgress() { return lottieDrawable.getProgress(); } public long getDuration() { return composition != null ? (long) composition.getDuration() : 0; } public void setPerformanceTrackingEnabled(boolean enabled) { lottieDrawable.setPerformanceTrackingEnabled(enabled); } @Nullable public PerformanceTracker getPerformanceTracker() { return lottieDrawable.getPerformanceTracker(); } private void clearComposition() { composition = null; lottieDrawable.clearComposition(); } /** * If you are experiencing a device specific crash that happens during drawing, you can set this to true * for those devices. If set to true, draw will be wrapped with a try/catch which will cause Lottie to * render an empty frame rather than crash your app. * * Ideally, you will never need this and the vast majority of apps and animations won't. However, you may use * this for very specific cases if absolutely necessary. * * There is no XML attr for this because it should be set programmatically and only for specific devices that * are known to be problematic. */ public void setSafeMode(boolean safeMode) { lottieDrawable.setSafeMode(safeMode); } /** * If rendering via software, Android will fail to generate a bitmap if the view is too large. Rather than displaying * nothing, fallback on hardware acceleration which may incur a performance hit. * * @see #setRenderMode(RenderMode) * @see com.airbnb.lottie.LottieDrawable#draw(android.graphics.Canvas) */ @Override public void buildDrawingCache(boolean autoScale) { L.beginSection("buildDrawingCache"); buildDrawingCacheDepth++; super.buildDrawingCache(autoScale); if (buildDrawingCacheDepth == 1 && getWidth() > 0 && getHeight() > 0 && getLayerType() == LAYER_TYPE_SOFTWARE && getDrawingCache(autoScale) == null) { setRenderMode(HARDWARE); } buildDrawingCacheDepth L.endSection("buildDrawingCache"); } /** * Call this to set whether or not to render with hardware or software acceleration. * Lottie defaults to Automatic which will use hardware acceleration unless: * 1) There are dash paths and the device is pre-Pie. * 2) There are more than 4 masks and mattes and the device is pre-Pie. * Hardware acceleration is generally faster for those devices unless * there are many large mattes and masks in which case there is a ton * of GPU uploadTexture thrashing which makes it much slower. * * In most cases, hardware rendering will be faster, even if you have mattes and masks. * However, if you have multiple mattes and masks (especially large ones) then you * should test both render modes. You should also test on pre-Pie and Pie+ devices * because the underlying rendering enginge changed significantly. */ public void setRenderMode(RenderMode renderMode) { this.renderMode = renderMode; enableOrDisableHardwareLayer(); } /** * Sets whether to apply opacity to the each layer instead of shape. * <p> * Opacity is normally applied directly to a shape. In cases where translucent shapes overlap, applying opacity to a layer will be more accurate * at the expense of performance. * <p> * The default value is false. * <p> * Note: This process is very expensive. The performance impact will be reduced when hardware acceleration is enabled. * * @see #setRenderMode(RenderMode) */ public void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled) { lottieDrawable.setApplyingOpacityToLayersEnabled(isApplyingOpacityToLayersEnabled); } /** * Disable the extraScale mode in {@link #draw(Canvas)} function when scaleType is FitXY. It doesn't affect the rendering with other scaleTypes. * * <p>When there are 2 animation layout side by side, the default extra scale mode might leave 1 pixel not drawn between 2 animation, and * disabling the extraScale mode can fix this problem</p> * * <b>Attention:</b> Disable the extra scale mode can downgrade the performance and may lead to larger memory footprint. Please only disable this * mode when using animation with a reasonable dimension (smaller than screen size). */ public void disableExtraScaleModeInFitXY() { lottieDrawable.disableExtraScaleModeInFitXY(); } private void enableOrDisableHardwareLayer() { int layerType = LAYER_TYPE_SOFTWARE; switch (renderMode) { case HARDWARE: layerType = LAYER_TYPE_HARDWARE; break; case SOFTWARE: layerType = LAYER_TYPE_SOFTWARE; break; case AUTOMATIC: boolean useHardwareLayer = true; if (composition != null && composition.hasDashPattern() && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { useHardwareLayer = false; } else if (composition != null && composition.getMaskAndMatteCount() > 4) { useHardwareLayer = false; } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { useHardwareLayer = false; } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N || Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) { useHardwareLayer = false; } layerType = useHardwareLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_SOFTWARE; break; } if (layerType != getLayerType()) { setLayerType(layerType, null); } } public boolean addLottieOnCompositionLoadedListener(@NonNull LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener) { LottieComposition composition = this.composition; if (composition != null) { lottieOnCompositionLoadedListener.onCompositionLoaded(composition); } return lottieOnCompositionLoadedListeners.add(lottieOnCompositionLoadedListener); } public boolean removeLottieOnCompositionLoadedListener(@NonNull LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener) { return lottieOnCompositionLoadedListeners.remove(lottieOnCompositionLoadedListener); } public void removeAllLottieOnCompositionLoadedListener() { lottieOnCompositionLoadedListeners.clear(); } private void setLottieDrawable() { boolean wasAnimating = isAnimating(); // Set the drawable to null first because the underlying LottieDrawable's intrinsic bounds can change // if the composition changes. setImageDrawable(null); setImageDrawable(lottieDrawable); if (wasAnimating) { // This is necessary because lottieDrawable will get unscheduled and canceled when the drawable is set to null. lottieDrawable.resumeAnimation(); } } private static class SavedState extends BaseSavedState { String animationName; int animationResId; float progress; boolean isAnimating; String imageAssetsFolder; int repeatMode; int repeatCount; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); animationName = in.readString(); progress = in.readFloat(); isAnimating = in.readInt() == 1; imageAssetsFolder = in.readString(); repeatMode = in.readInt(); repeatCount = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(animationName); out.writeFloat(progress); out.writeInt(isAnimating ? 1 : 0); out.writeString(imageAssetsFolder); out.writeInt(repeatMode); out.writeInt(repeatCount); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package com.continuuity.common.queue; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.io.File; import java.net.URI; import java.util.List; /** * An abstraction over URI of a queue. */ public final class QueueName { /** * URI of the queue. */ private final URI uri; /** * End point name. */ private final String simpleName; /** * The components of the URI. */ private final String[] components; /** * Represents the queue as byte[]. */ private final byte[] byteName; /** * Represents the queue name as a string. */ private final String stringName; /** * Constructs this class from an URI. * * @param uri of the queue * @return An instance of {@link QueueName} */ public static QueueName from(URI uri) { Preconditions.checkNotNull(uri, "URI cannot be null."); return new QueueName(uri); } /** * Constructs this class from byte array of queue URI. * * @param bytes respresenting URI * @return An instance of {@link QueueName} */ public static QueueName from(byte[] bytes) { return new QueueName(URI.create(new String(bytes, Charsets.US_ASCII))); } public static QueueName fromFlowlet(String app, String flow, String flowlet, String output) { URI uri = URI.create(Joiner.on("/").join("queue:", "", app, flow, flowlet, output)); return new QueueName(uri); } /** * Generates an QueueName for the stream. * * @param accountId The stream belongs to * @param stream connected to flow * @return An {@link QueueName} with schema as stream */ public static QueueName fromStream(String accountId, String stream) { URI uri = URI.create(Joiner.on("/").join("stream:", "", accountId, stream)); return new QueueName(uri); } /** * Called from static method {@code QueueName#from(URI)} and {@code QueueName#from(bytes[])}. * * @param uri of the queue. */ private QueueName(URI uri) { this.uri = uri; this.simpleName = new File(uri.getPath()).getName(); this.stringName = uri.toASCIIString(); this.byteName = stringName.getBytes(Charsets.US_ASCII); List<String> comps = Lists.asList(uri.getHost(), uri.getPath().split("/")); this.components = comps.toArray(new String[comps.size()]); } public boolean isStream() { return "stream".equals(uri.getScheme()); } public boolean isQueue() { return "queue".equals(uri.getScheme()); } private String getNthComponent(int n) { return n < components.length ? components[n] : null; } /** * @return the first component of the URI (the app for a queue, the account for a stream). */ public String getFirstComponent() { return getNthComponent(0); } /** * @return the second component of the URI (the flow for a queue, the stream name for a stream). */ public String getSecondComponent() { return getNthComponent(2); // (1) would return "" (path starts with /) } /** * @return the third component of the URI (the flowlet for a queue, null for a stream). */ public String getThirdComponent() { return getNthComponent(3); } /** * @return Simple name which is the last part of queue URI path and endpoint. */ public String getSimpleName() { return simpleName; } /** * Gets the bytes representation of the queue uri. Note that mutating the returned array will mutate the underlying * byte array as well. If mutation is needed, one has to copy to a separate array. * * @return bytes representation of queue uri. */ public byte[] toBytes() { return byteName; } /** * @return A {@link URI} representation of the queue name. */ public URI toURI() { return uri; } /** * @return converts to ascii string. */ @Override public String toString() { return stringName; } /** * @return whether the given string represents a queue. */ public static boolean isQueue(String name) { return name.startsWith("queue"); } /** * @return whether the given string represents a queue. */ public static boolean isStream(String name) { return name.startsWith("stream"); } /** * Compares this {@link QueueName} with another {@link QueueName}. * * @param o Other instance of {@link QueueName} * @return true if equal; false otherwise. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return uri.equals(((QueueName) o).uri); } /** * @return hash code of this QueueName. */ @Override public int hashCode() { return uri.hashCode(); } }
package com.esotericsoftware.kryo.serialize; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import junit.framework.TestCase; import org.junit.Assert; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.NotNull; import com.esotericsoftware.kryo.Serializer; // TODO - Write tests for all serializers. // TODO - Break this monolithic test into smaller tests. public class SerializerTest extends TestCase { private ByteBuffer buffer = ByteBuffer.allocateDirect(500); private int intValues[] = { 0, 1, 2, 3, -1, -2, -3, 32, -32, 127, 128, 129, -125, -126, -127, -128, 252, 253, 254, 255, 256, -252, -253, -254, -255, -256, 32767, 32768, 32769, -32767, -32768, -32769, 65535, 65536, 65537, Integer.MAX_VALUE, Integer.MIN_VALUE, }; public void testStrings () { roundTrip(new StringSerializer(), 21, "abcdef\u00E1\u00E9\u00ED\u00F3\u00FA\u1234"); } public void testCollection () { Kryo kryo = new Kryo(); CollectionSerializer serializer = new CollectionSerializer(kryo); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); roundTrip(serializer, 13, new ArrayList(Arrays.asList("1", "2", null, 1, 2))); roundTrip(serializer, 15, new ArrayList(Arrays.asList("1", "2", null, 1, 2, 5))); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); serializer.setElementClass(String.class); roundTrip(serializer, 11, new ArrayList(Arrays.asList("1", "2", "3"))); serializer.setElementsCanBeNull(false); roundTrip(serializer, 8, new ArrayList(Arrays.asList("1", "2", "3"))); } public void testArray () { Kryo kryo = new Kryo(); ArraySerializer serializer = new ArraySerializer(kryo); roundTrip(serializer, 7, new int[] {1, 2, 3, 4}); roundTrip(serializer, 11, new int[] {1, 2, -100, 4}); roundTrip(serializer, 13, new int[] {1, 2, -100, 40000}); roundTrip(serializer, 10, new int[][] { {1, 2}, {100, 4}}); roundTrip(serializer, 12, new int[][] { {1}, {2}, {100}, {4}}); roundTrip(serializer, 15, new int[][][] { { {1}, {2}}, { {100}, {4}}}); roundTrip(serializer, 19, new String[] {"11", "2222", "3", "4"}); roundTrip(serializer, 17, new String[] {"11", "2222", null, "4"}); serializer.setDimensionCount(1); serializer.setElementsAreSameType(true); roundTrip(serializer, 16, new String[] {"11", "2222", null, "4"}); serializer.setElementsAreSameType(false); roundTrip(serializer, 16, new String[] {"11", "2222", null, "4"}); roundTrip(new ArraySerializer(kryo), 6, new String[] {null, null, null}); roundTrip(new ArraySerializer(kryo), 3, new String[] {}); serializer.setElementsCanBeNull(true); serializer.setElementsAreSameType(true); roundTrip(serializer, 18, new String[] {"11", "2222", "3", "4"}); serializer.setElementsCanBeNull(false); roundTrip(serializer, 14, new String[] {"11", "2222", "3", "4"}); serializer.setLength(4); roundTrip(serializer, 13, new String[] {"11", "2222", "3", "4"}); } public void testMap () { Kryo kryo = new Kryo(); HashMap map = new HashMap(); map.put("123", "456"); map.put("789", "abc"); MapSerializer serializer = new MapSerializer(kryo); roundTrip(serializer, 22, map); serializer.setKeyClass(String.class); serializer.setKeysCanBeNull(false); serializer.setValueClass(String.class); roundTrip(serializer, 20, map); serializer.setValuesCanBeNull(false); roundTrip(serializer, 18, map); } public void testShort () { roundTrip(new ShortSerializer(true), 2, (short)123); roundTrip(new ShortSerializer(false), 2, (short)123); buffer.clear(); ShortSerializer.put(buffer, (short)250, false); buffer.flip(); assertEquals(3, buffer.limit()); assertEquals((short)250, ShortSerializer.get(buffer, false)); buffer.clear(); ShortSerializer.put(buffer, (short)250, true); buffer.flip(); assertEquals(1, buffer.limit()); assertEquals((short)250, ShortSerializer.get(buffer, true)); buffer.clear(); ShortSerializer.put(buffer, (short)123, true); buffer.flip(); assertEquals(1, buffer.limit()); assertEquals((short)123, ShortSerializer.get(buffer, true)); } public void testNumbers () { for (int value : intValues) { roundTrip(value, false); roundTrip(value, true); } // now go through powers of 2 for (long value = 65536; value > 0; value /= 2) { System.out.println(value); roundTrip(value, false); roundTrip(value, true); roundTrip(value + 1, false); roundTrip(value + 1, true); roundTrip(value - 1, false); roundTrip(value - 1, true); roundTrip(-value, false); roundTrip(-value, true); roundTrip(-value + 1, false); roundTrip(-value + 1, true); roundTrip(-value - 1, false); roundTrip(-value - 1, true); } } private void roundTrip (long value, boolean optimizePositive) { buffer.clear(); LongSerializer.put(buffer, value, optimizePositive); buffer.flip(); long result = LongSerializer.get(buffer, optimizePositive); System.out.println(value + " long bytes, " + optimizePositive + ": " + buffer.limit()); assertEquals(result, value); int intValue = (int)value; buffer.clear(); IntSerializer.put(buffer, intValue, optimizePositive); buffer.flip(); result = IntSerializer.get(buffer, optimizePositive); System.out.println(intValue + " int bytes, " + optimizePositive + ": " + buffer.limit()); assertEquals(result, intValue); short shortValue = (short)value; buffer.clear(); ShortSerializer.put(buffer, shortValue, optimizePositive); buffer.flip(); short shortResult = ShortSerializer.get(buffer, optimizePositive); System.out.println(shortValue + " short bytes, " + optimizePositive + ": " + buffer.limit()); assertEquals(shortResult, shortValue); } private <T> T roundTrip (Serializer serializer, int length, T object1) { buffer.clear(); serializer.writeObject(buffer, object1); buffer.flip(); System.out.println(object1 + " bytes: " + buffer.remaining()); assertEquals("Incorrect length.", length, buffer.remaining()); Object object2 = serializer.readObject(buffer, object1.getClass()); if (object1.getClass().isArray()) { if (object1 instanceof int[]) Assert.assertArrayEquals((int[])object1, (int[])object2); else if (object1 instanceof int[][]) Assert.assertArrayEquals((int[][])object1, (int[][])object2); else if (object1 instanceof int[][][]) Assert.assertArrayEquals((int[][][])object1, (int[][][])object2); else if (object1 instanceof String[]) Assert.assertArrayEquals((String[])object1, (String[])object2); else fail(); } else assertEquals(object1, object2); return (T)object2; } private <T> T roundTrip (Kryo kryo, int length, T object1) { buffer.clear(); kryo.writeClassAndObject(buffer, object1); buffer.flip(); System.out.println(object1 + " bytes: " + buffer.remaining()); assertEquals("Incorrect length.", length, buffer.remaining()); Object object2 = kryo.readClassAndObject(buffer); assertEquals(object1, object2); return (T)object2; } public void testNonNull () { Kryo kryo = new Kryo(); StringTestClass value = new StringTestClass(); value.text = "moo"; buffer.clear(); FieldSerializer fieldSerializer = new FieldSerializer(kryo, StringTestClass.class); fieldSerializer.writeObjectData(buffer, value); buffer.flip(); assertEquals("Incorrect length.", 5, buffer.remaining()); NonNullTestClass nonNullValue = new NonNullTestClass(); nonNullValue.nonNullText = "moo"; buffer.clear(); fieldSerializer = new FieldSerializer(kryo, NonNullTestClass.class); fieldSerializer.writeObjectData(buffer, nonNullValue); buffer.flip(); assertEquals("Incorrect length.", 4, buffer.remaining()); } public void testDateSerializer () { Kryo kryo = new Kryo(); kryo.register(Date.class, new DateSerializer()); buffer.clear(); Date date = new Date(0); kryo.writeClassAndObject(buffer, date); buffer.flip(); assertEquals(date, kryo.readClassAndObject(buffer)); buffer.clear(); date = new Date(1234567); kryo.writeClassAndObject(buffer, date); buffer.flip(); assertEquals(date, kryo.readClassAndObject(buffer)); } public void testFieldSerializer () { TestClass value = new TestClass(); value.child = new TestClass(); Kryo kryo = new Kryo(); FieldSerializer serializer = new FieldSerializer(kryo, TestClass.class); serializer.removeField("optional"); value.optional = 123; kryo.register(TestClass.class, serializer); TestClass value2 = roundTrip(serializer, 35, value); assertEquals(0, value2.optional); serializer = new FieldSerializer(kryo, TestClass.class); value.optional = 123; value2 = roundTrip(serializer, 36, value); assertEquals(123, value2.optional); } public void testFieldSerializerRegistrationOrder () { A a = new A(); a.value = 100; a.b = new B(); a.b.value = 200; a.b.a = new A(); a.b.a.value = 300; Kryo kryo = new Kryo(); kryo.register(A.class); kryo.register(B.class); roundTrip(kryo, 9, a); kryo = new Kryo(); kryo.register(B.class); kryo.register(A.class); roundTrip(kryo, 9, a); } public void testNoDefaultConstructor () { SimpleNoDefaultConstructor object1 = new SimpleNoDefaultConstructor(2); roundTrip(new SimpleSerializer<SimpleNoDefaultConstructor>() { public SimpleNoDefaultConstructor read (ByteBuffer buffer) { return new SimpleNoDefaultConstructor(IntSerializer.get(buffer, true)); } public void write (ByteBuffer buffer, SimpleNoDefaultConstructor object) { IntSerializer.put(buffer, object.constructorValue, true); } }, 2, object1); Kryo kryo = new Kryo(); FieldSerializer complexSerializer = new FieldSerializer(kryo, ComplexNoDefaultConstructor.class) { public ComplexNoDefaultConstructor readObjectData (ByteBuffer buffer, Class type) { String name = StringSerializer.get(buffer); ComplexNoDefaultConstructor object = new ComplexNoDefaultConstructor(name); readObjectData(object, buffer, type); return object; } public void writeObjectData (ByteBuffer buffer, Object object) { ComplexNoDefaultConstructor complexObject = (ComplexNoDefaultConstructor)object; StringSerializer.put(buffer, complexObject.name); super.writeObjectData(buffer, complexObject); } }; ComplexNoDefaultConstructor object2 = new ComplexNoDefaultConstructor("has no zero arg constructor!"); object2.anotherField1 = 1234; object2.anotherField2 = "abcd"; roundTrip(complexSerializer, 38, object2); } public void testArrayList () { Kryo kryo = new Kryo(); kryo.register(ArrayList.class); ArrayList list = new ArrayList(Arrays.asList("1", "2", "3")); ByteBuffer buffer = ByteBuffer.allocate(1024); kryo.writeObject(buffer, list); buffer.flip(); kryo.readObject(buffer, ArrayList.class); } public void testNulls () { Kryo kryo = new Kryo(); kryo.register(ArrayList.class); ByteBuffer buffer = ByteBuffer.allocate(1024); kryo.writeObject(buffer, null); buffer.flip(); Object object = kryo.readObject(buffer, ArrayList.class); assertNull(object); buffer.clear(); kryo.writeClassAndObject(buffer, null); buffer.flip(); object = kryo.readClassAndObject(buffer); assertNull(object); buffer.clear(); kryo.writeClass(buffer, null); buffer.flip(); object = kryo.readClass(buffer); assertNull(object); } public void testUnregisteredClassNames () { TestClass value = new TestClass(); value.child = new TestClass(); value.optional = 123; Kryo kryo = new Kryo(); kryo.setAllowUnregisteredClasses(true); buffer.clear(); kryo.writeClassAndObject(buffer, value); buffer.flip(); TestClass value2 = (TestClass)kryo.readClassAndObject(buffer); assertEquals(value, value2); } static public class SimpleNoDefaultConstructor { int constructorValue; public SimpleNoDefaultConstructor (int constructorValue) { this.constructorValue = constructorValue; } public int getConstructorValue () { return constructorValue; } public int hashCode () { final int prime = 31; int result = 1; result = prime * result + constructorValue; return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SimpleNoDefaultConstructor other = (SimpleNoDefaultConstructor)obj; if (constructorValue != other.constructorValue) return false; return true; } } static public class ComplexNoDefaultConstructor { public transient String name; public int anotherField1; public String anotherField2; public ComplexNoDefaultConstructor (String name) { this.name = name; } public int hashCode () { final int prime = 31; int result = 1; result = prime * result + anotherField1; result = prime * result + ((anotherField2 == null) ? 0 : anotherField2.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComplexNoDefaultConstructor other = (ComplexNoDefaultConstructor)obj; if (anotherField1 != other.anotherField1) return false; if (anotherField2 == null) { if (other.anotherField2 != null) return false; } else if (!anotherField2.equals(other.anotherField2)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } static public class NonNullTestClass { @NotNull public String nonNullText; } static public class StringTestClass { public String text = "something"; } static public class TestClass { public String text = "something"; public String nullField; TestClass child; private float abc = 1.2f; public int optional; public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestClass other = (TestClass)obj; if (Float.floatToIntBits(abc) != Float.floatToIntBits(other.abc)) return false; if (child == null) { if (other.child != null) return false; } else if (!child.equals(other.child)) return false; if (nullField == null) { if (other.nullField != null) return false; } else if (!nullField.equals(other.nullField)) return false; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } } static public final class A { public int value; public B b; public int hashCode () { final int prime = 31; int result = 1; result = prime * result + ((b == null) ? 0 : b.hashCode()); result = prime * result + value; return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; A other = (A)obj; if (b == null) { if (other.b != null) return false; } else if (!b.equals(other.b)) return false; if (value != other.value) return false; return true; } } static public final class B { public int value; public A a; public int hashCode () { final int prime = 31; int result = 1; result = prime * result + ((a == null) ? 0 : a.hashCode()); result = prime * result + value; return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; B other = (B)obj; if (a == null) { if (other.a != null) return false; } else if (!a.equals(other.a)) return false; if (value != other.value) return false; return true; } } }
package org.neo4j.kernel.ha.zookeeper; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.neo4j.helpers.Pair; import org.neo4j.kernel.impl.ha.ResponseReceiver; public class ZooClient implements Watcher { private ZooKeeper zooKeeper; private final long storeCreationTime; private final long storeId; private final int machineId; private String sequenceNr; private long committedTx; private final String servers; private volatile KeeperState keeperState = KeeperState.Disconnected; private volatile boolean shutdown = false; private final ResponseReceiver receiver; public ZooClient( String servers, int machineId, long storeCreationTime, long storeId, long committedTx, ResponseReceiver receiver ) { this.servers = servers; this.receiver = receiver; instantiateZooKeeper(); this.machineId = machineId; this.storeCreationTime = storeCreationTime; this.storeId = storeId; this.committedTx = committedTx; this.sequenceNr = "not initialized yet"; } public void process( WatchedEvent event ) { String path = event.getPath(); System.out.println( this + ", " + new Date() + " Got event: " + event + "(path=" + path + ")" ); if ( path == null ) { if ( event.getState() == Watcher.Event.KeeperState.Expired ) { keeperState = KeeperState.Expired; instantiateZooKeeper(); } else if ( event.getState() == Watcher.Event.KeeperState.SyncConnected ) { sequenceNr = setup(); keeperState = KeeperState.SyncConnected; receiver.somethingIsWrong( new Exception() ); } else if ( event.getState() == Watcher.Event.KeeperState.Disconnected ) { keeperState = KeeperState.Disconnected; } } else { if ( event.getType() == Watcher.Event.EventType.NodeChildrenChanged ) { // Assert path = rootPath? // Here either a new machine came into the cluster // or a machine (or its network) went down. receiver.somethingIsWrong( new Exception() ); // Add the watch again getRoot( true ); } } } private final long TIME_OUT = 5000; private void waitForSyncConnected() { if ( keeperState == KeeperState.SyncConnected ) { return; } if ( shutdown == true ) { throw new ZooKeeperException( "ZooKeeper client has been shutdwon" ); } long startTime = System.currentTimeMillis(); long currentTime = startTime; synchronized ( keeperState ) { do { try { keeperState.wait( 250 ); } catch ( InterruptedException e ) { Thread.interrupted(); } if ( keeperState == KeeperState.SyncConnected ) { return; } if ( shutdown == true ) { throw new ZooKeeperException( "ZooKeeper client has been shutdwon" ); } currentTime = System.currentTimeMillis(); } while ( (currentTime - startTime) < TIME_OUT ); if ( keeperState != KeeperState.SyncConnected ) { throw new ZooKeeperTimedOutException( "Connection to ZooKeeper server timed out, keeper state=" + keeperState ); } } } private void instantiateZooKeeper() { try { this.zooKeeper = new ZooKeeper( servers, 5000, this ); } catch ( IOException e ) { throw new ZooKeeperException( "Unable to create zoo keeper client", e ); } } private String setOrCreate( String path, boolean pathIsRelative, byte[] data, boolean addWatch ) { String created = null; try { path = pathIsRelative ? getRoot( addWatch ) + "/" + path : path; boolean exists = false; byte[] existingData = null; try { existingData = zooKeeper.getData( path, addWatch, null ); exists = true; if ( Arrays.equals( data, existingData ) ) { return null; } } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NONODE ) { throw new ZooKeeperException( "Couldn't get master notify node", e ); } } // Didn't exist or value differs try { if ( !exists ) { created = zooKeeper.create( path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); } zooKeeper.setData( path, data, -1 ); // Add a watch for it if ( addWatch ) { zooKeeper.getData( path, true, null ); } return created; } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NODEEXISTS ) { throw new ZooKeeperException( "Couldn't set master notify node", e ); } } } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted", e ); } return created; } private String getRoot( boolean addWatch ) { String rootPath = "/" + storeCreationTime + "_" + storeId; setOrCreate( rootPath, false, new byte[] { 0 }, addWatch ); return rootPath; } private void cleanupChildren() { try { String root = getRoot( false ); List<String> children = zooKeeper.getChildren( root, false ); for ( String child : children ) { System.out.println( child ); int index = child.indexOf( '_' ); int id = Integer.parseInt( child.substring( 0, index ) ); if ( id == machineId ) { zooKeeper.delete( root + "/" + child, -1 ); } } } catch ( KeeperException e ) { throw new ZooKeeperException( "Unable to clean up old child", e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted.", e ); } } private String setup() { try { cleanupChildren(); String root = getRoot( true ); String path = root + "/" + machineId + "_"; byte[] data = new byte[8]; ByteBuffer buf = ByteBuffer.wrap( data ); buf.putLong( committedTx ); String created = zooKeeper.create( path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL ); System.out.println( this + " wrote " + committedTx + " to zookeeper" ); // Need to add watch here? getRoot( true ); return created.substring( created.lastIndexOf( "_" ) + 1 ); } catch ( KeeperException e ) { throw new ZooKeeperException( "Unable to setup", e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Setup got interrupted", e ); } catch ( Throwable t ) { t.printStackTrace(); throw new ZooKeeperException( "Unknown setup error", t ); } } public synchronized int getMaster() { waitForSyncConnected(); try { Map<Integer, Pair<Integer, Long>> rawData = new HashMap<Integer, Pair<Integer,Long>>(); String root = getRoot( true ); List<String> children = zooKeeper.getChildren( root, false ); int currentMasterId = -1; int lowestSeq = Integer.MAX_VALUE; long highestTxId = -1; for ( String child : children ) { int index = child.indexOf( '_' ); int id = Integer.parseInt( child.substring( 0, index ) ); int seq = Integer.parseInt( child.substring( index + 1 ) ); try { byte[] data = zooKeeper.getData( root + "/" + child, false, null ); ByteBuffer buf = ByteBuffer.wrap( data ); long tx = buf.getLong(); if ( rawData.put( id, new Pair<Integer, Long>( seq, tx ) ) != null ) { System.out.println( "warning: " + id + " found more than once" ); } if ( tx >= highestTxId ) { if ( tx > highestTxId || seq < lowestSeq ) { currentMasterId = id; lowestSeq = seq; } highestTxId = tx; } } catch ( KeeperException inner ) { if ( inner.code() != KeeperException.Code.NONODE ) { throw new ZooKeeperException( "Unabe to get master.", inner ); } } } System.out.println( "getMaster: " + currentMasterId + " based on " + rawData ); return currentMasterId; } catch ( KeeperException e ) { throw new ZooKeeperException( "Unable to get master", e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted.", e ); } } public synchronized void setCommittedTx( long tx ) { System.out.println( "Setting txId=" + tx + " for machine=" + machineId ); waitForSyncConnected(); if ( tx <= committedTx ) { throw new IllegalArgumentException( "tx=" + tx + " but committedTx is " + committedTx ); } this.committedTx = tx; String root = getRoot( true ); String path = root + "/" + machineId + "_" + sequenceNr; byte[] data = new byte[8]; ByteBuffer buf = ByteBuffer.wrap( data ); buf.putLong( tx ); try { zooKeeper.setData( path, data, -1 ); } catch ( KeeperException e ) { throw new ZooKeeperException( "Unable to set current tx", e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted...", e ); } } public void shutdown() { try { shutdown = true; zooKeeper.close(); } catch ( InterruptedException e ) { throw new ZooKeeperException( "Error closing zookeeper connection", e ); } } }
package org.walterweight.rightclicktorch; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerInteractEvent; @Mod(modid = RightClickTorch.MODID, name = RightClickTorch.MODID) public class RightClickTorch { public static final String MODID = "RightClickTorch"; private static final int NOTORCHESFOUND = -1; private boolean processingEvent = false; @Mod.Instance(MODID) public static RightClickTorch instance; public RightClickTorch() { MinecraftForge.EVENT_BUS.register(this); } @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { } @SubscribeEvent public void playerInteractEventHandler(PlayerInteractEvent event) { if (processingEvent | eventNotRelevant(event)) return; ItemStack itemInHand = event.entityPlayer.inventory.getCurrentItem(); if (notHoldingTool(itemInHand)) return; InventoryPlayer inventory = event.entityPlayer.inventory; int mainInventoryTorchSlotIndex = getTorchSlotIndex(inventory.mainInventory); if (mainInventoryTorchSlotIndex == NOTORCHESFOUND) return; if (!targetBlockAcceptsTorches(event)) return; processingEvent = true; ItemStack torchStack = inventory.mainInventory[mainInventoryTorchSlotIndex]; useItem(event, torchStack); if (torchStack.stackSize == 0) inventory.mainInventory[mainInventoryTorchSlotIndex] = null; event.entityPlayer.openContainer.detectAndSendChanges(); processingEvent = false; event.setCanceled(true); } private void useItem(PlayerInteractEvent event, ItemStack torchStack) { ((EntityPlayerMP) event.entityPlayer).theItemInWorldManager .activateBlockOrUseItem(event.entityPlayer, event.world, torchStack, event.x, event.y, event.z, event.face, 0.5f, 0.5f, 0.5f); } private boolean targetBlockAcceptsTorches(PlayerInteractEvent event) { // Unless I'm having a serious brain fart, it seems that .canPlaceTorchOnTop() should be a static method from the Block class Block block = event.world.getBlock(event.x, event.y, event.z); return block.canPlaceTorchOnTop(event.world, event.x, event.y, event.z); } private boolean eventNotRelevant(PlayerInteractEvent event) { return event .isCanceled() || event.world.isRemote || event.action != PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK; } private boolean notHoldingTool(ItemStack itemInHand) { return itemInHand == null || !(itemInHand.getItem() instanceof ItemTool); } private int getTorchSlotIndex(ItemStack[] itemStacks) { for (int index = 0; index < itemStacks.length; index++) { if (itemStacks[index] != null && itemStacks[index].getItem() == net.minecraft.item.Item .getItemFromBlock(Blocks.torch)) return index; } return NOTORCHESFOUND; } }
package de.unisb.cs.depend.ccs_sem.parser; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import de.unisb.cs.depend.ccs_sem.exceptions.ArithmeticError; import de.unisb.cs.depend.ccs_sem.exceptions.LexException; import de.unisb.cs.depend.ccs_sem.exceptions.ParseException; import de.unisb.cs.depend.ccs_sem.lexer.CCSLexer; import de.unisb.cs.depend.ccs_sem.lexer.tokens.*; import de.unisb.cs.depend.ccs_sem.lexer.tokens.categories.Token; import de.unisb.cs.depend.ccs_sem.semantics.expressions.*; import de.unisb.cs.depend.ccs_sem.semantics.expressions.adapters.TopMostExpression; import de.unisb.cs.depend.ccs_sem.semantics.types.ChannelSet; import de.unisb.cs.depend.ccs_sem.semantics.types.Parameter; import de.unisb.cs.depend.ccs_sem.semantics.types.ParameterList; import de.unisb.cs.depend.ccs_sem.semantics.types.ProcessVariable; import de.unisb.cs.depend.ccs_sem.semantics.types.Program; import de.unisb.cs.depend.ccs_sem.semantics.types.ValueList; import de.unisb.cs.depend.ccs_sem.semantics.types.ValueSet; import de.unisb.cs.depend.ccs_sem.semantics.types.actions.Action; import de.unisb.cs.depend.ccs_sem.semantics.types.actions.InputAction; import de.unisb.cs.depend.ccs_sem.semantics.types.actions.OutputAction; import de.unisb.cs.depend.ccs_sem.semantics.types.actions.SimpleAction; import de.unisb.cs.depend.ccs_sem.semantics.types.actions.TauAction; import de.unisb.cs.depend.ccs_sem.semantics.types.ranges.IntervalRange; import de.unisb.cs.depend.ccs_sem.semantics.types.ranges.Range; import de.unisb.cs.depend.ccs_sem.semantics.types.ranges.SetRange; import de.unisb.cs.depend.ccs_sem.semantics.types.values.*; import de.unisb.cs.depend.ccs_sem.utils.Pair; /** * This Parser parses the following grammar: * * program --> (constDecl | rangeDecl | recursiveDecl)* expression * constDecl --> "const" identifier ":=" arithExpression ";" * rangeDecl --> "range" identifier ":=" range ";" * recursiveDecl --> recursionVariable := expression ";" * recursionVariable --> ucIdentifier ( "[" ( ( parameter "," )* parameter)? "]" )? * * expression --> restrictExpression * restrictExpression --> parallelExpression * | restrictExpression "\" "{" ( ( channel "," )* channel )? "}" * parallelExpression --> choiceExpression * | parallelExpression "|" choiceExpression * choiceExpression --> prefixExpression * | choiceExpression "+" prefixExpression * prefixExpression --> whenExpression * | action "." prefixExpression * whenExpression --> baseExpression | "when" arithExpression prefixExpression * baseExpression --> "0" * | "ERROR" * | "(" expression ")" * | recursionVariable * | action * * action --> channel ( "?" inputValue | "!" outputValue )? * channel --> lcIdentifier * identifier --> character ( digit | character ) * * lcIdentifier --> lcCharacter ( digit | character ) * * ucIdentifier --> ucCharacter ( digit | character ) * * character --> "a" | ... | "z" | "A" | ... | "Z" | "_" * ucCharacter --> "A" | ... | "Z" | "_" * lcCharacter --> "a" | ... | "z" | "_" * digit --> "0" | ... | "9" * inputValue --> inputParameter | "" | arithBase * outputValue --> arithBase | "" * parameter --> identifier ( ":" rangeDef) * inputParameter --> identifier ( ":" range) * * range --> rangeAdd * rangeAdd --> rangeDef | rangeAdd ( "+" | "-" ) rangeDef * rangeDef --> Identifier | arithBase ".." arithBase * | "{" ( ( arithExpression "," )* arithExpression)? "}" * rangeBase --> Identifier * rangeElem --> integer | Identifier * * integer --> ( "+" | "-" )? digit+ * * arithExpression --> arithCond * arithCond --> arithOr | arithOr "?" arithCond ":" arithCond * arithOr --> arithAnd | arithOr "||" arithAnd * arithAnd --> arithEq | arithAnd "&&" arithEq * arithEq --> arithComp | arithEq ("==" | "!=" ) arithComp * arithComp --> arithShift | arithShift ("<" | "<=" | ">" | ">=") arithShift * arithShift --> arithAdd | arithShift (">>" | "<<") arithAdd * arithAdd --> arithMult | arithAdd ("+" | "-") arithMult * arithMult --> arithNot | arithMult ("*" | "/" | "%" | "mod") arithUnary * arithUnary --> arithBase | "!" arithUnary | "+" arithUnary | "-" arithUnary * arithBase --> integer | "true" | "false" | "(" arithExpression ")" | identifier * * * @author Clemens Hammacher */ public class CCSParser implements Parser { private final List<IParsingProblemListener> listeners = new ArrayList<IParsingProblemListener>(); // "Stack" of the currently read parameters, it's increased and decreased by // the read... methods. When a string is read, we try to match it with one // of these parameters *from left to right*. // i.e. we can "overwrite" parameters by just adding them on the left to this list. private LinkedList<Parameter> parameters; // a Map of all constants that are defined in the current program private Map<String, ConstantValue> constants; // a Map of all ranges that are defined in the current program private Map<String, Range> ranges; /** * Parses a CCS program from an input reader. * * @param input the Reader that provides the input * @return the parsed CCS program, or <code>null</code> if there was an error * (use {@link #addProblemListener(IParsingProblemListener)} to fetch the error) */ public Program parse(Reader input) { try { return parse(getDefaultLexer().lex(input)); } catch (final LexException e) { reportProblem(new ParsingProblem(ParsingProblem.ERROR, "Error lexing: " + e.getMessage(), e.getPosition(), e.getPosition())); return null; } } protected CCSLexer getDefaultLexer() { return new CCSLexer(); } /** * Parses a CCS program from an input string. * * @param input the input source code * @return the parsed CCS program, or <code>null</code> if there was an error * (use {@link #addProblemListener(IParsingProblemListener)} to fetch the error) */ public Program parse(String input) { try { return parse(getDefaultLexer().lex(input)); } catch (final LexException e) { reportProblem(new ParsingProblem(ParsingProblem.ERROR, "Error lexing: " + e.getMessage(), e.getPosition(), e.getPosition())); return null; } } /** * Parses a CCS program from a token list. * * @param tokens the token list to parse * @return the parsed CCS program, or <code>null</code> if there was an error * (use {@link #addProblemListener(IParsingProblemListener)} to fetch the error) */ public synchronized Program parse(List<Token> tokens) { final ArrayList<ProcessVariable> processVariables = new ArrayList<ProcessVariable>(); parameters = new LinkedList<Parameter>(); constants = new HashMap<String, ConstantValue>(); ranges = new HashMap<String, Range>(); final ExtendedListIterator<Token> it = new ExtendedListIterator<Token>(tokens); readDeclarations(it, processVariables); // then, read the ccs expression Expression mainExpr; try { mainExpr = readMainExpression(it); } catch (final ParseException e) { reportProblem(new ParsingProblem(e)); return null; } // now make it a "top most expression" mainExpr = ExpressionRepository.getExpression(new TopMostExpression(mainExpr)); final Token eof = it.next(); if (!(eof instanceof EOFToken)) { reportProblem(new ParsingProblem(ParsingProblem.ERROR, "Unexpected token", eof)); } Program program = null; try { program = new Program(processVariables, mainExpr); } catch (final ParseException e) { reportProblem(new ParsingProblem(e)); } if (program != null) { // search if the alphabet contains parameterized input actions final Set<Action> alphabet = program.getAlphabet(); for (final Action act: alphabet) { if (!(act instanceof InputAction)) continue; final Parameter param = ((InputAction)act).getParameter(); if (param == null) continue; final Range range = param.getRange(); if (range != null && range.isRangeRestricted()) continue; // ok, we have an unrestricted and not range restricted action. reportUnboundInputParameter(act); } } return program; } private void readDeclarations(final ExtendedListIterator<Token> tokens, final ArrayList<ProcessVariable> processVariables) { while (tokens.hasNext() && !(tokens.peek() instanceof EOFToken)) { final int oldPosition = tokens.nextIndex(); try { if (tokens.peek() instanceof ConstToken) { tokens.next(); Token nextToken = tokens.next(); if (!(nextToken instanceof Identifier)) throw new ParseException("Expected an identifier after 'const' keyword.", nextToken); final String constName = ((Identifier)nextToken).getName(); // check for double constant name if (constants.get(constName) != null) throw new ParseException("Constant name \"" + constName + "\" already used.", nextToken); if (!tokens.hasNext() || !(tokens.next() instanceof Assign)) throw new ParseException("Expected ':=' after const identifier.", tokens.peekPrevious()); final Token startToken = tokens.peek(); final Value constValue = readArithmeticExpression(tokens); identifierParsed((Identifier)nextToken, constValue); nextToken = tokens.next(); // TODO remove this ambiguousness if (!(nextToken instanceof Semicolon) && !(nextToken instanceof Comma)) throw new ParseException("Expected ';' after constant declaration.", tokens.peekPrevious()); if (!(constValue instanceof ConstantValue)) throw new ParseException("Expected constant value.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); constants.put(constName, (ConstantValue)constValue); } else if (tokens.peek() instanceof RangeToken) { tokens.next(); Token nextToken = tokens.next(); if (!(nextToken instanceof Identifier)) throw new ParseException("Expected an identifier after 'range' keyword.", nextToken); final String rangeName = ((Identifier)nextToken).getName(); // check for double range name if (ranges.get(rangeName) != null) throw new ParseException("Range name \"" + rangeName + "\" already used.", nextToken); if (!tokens.hasNext() || !(tokens.next() instanceof Assign)) throw new ParseException("Expected ':=' after range identifier.", tokens.peekPrevious()); final Range range = readRange(tokens); identifierParsed((Identifier)nextToken, range); nextToken = tokens.next(); // TODO remove this ambiguousness if (!(nextToken instanceof Semicolon) && !(nextToken instanceof Comma)) throw new ParseException("Expected ';' after constant declaration.", tokens.peekPrevious()); ranges.put(rangeName, range); } else { final Token nextToken = tokens.peek(); final ProcessVariable nextProcessVariable = readProcessDeclaration(tokens); if (nextProcessVariable == null) { tokens.setPosition(oldPosition); break; } // check if a process variable with the same name and number of parameters is already known for (final ProcessVariable proc: processVariables) if (proc.getName().equals(nextProcessVariable.getName()) && proc.getParamCount() == nextProcessVariable.getParamCount()) { reportProblem(new ParsingProblem(ParsingProblem.ERROR, "Duplicate process variable definition (" + nextProcessVariable.getName() + "[" + nextProcessVariable.getParamCount() + "]", nextToken)); break; } processVariables.add(nextProcessVariable); } } catch (final ParseException e) { reportProblem(new ParsingProblem(e)); // ... but continue parsing (readProcessDeclaration moved // forward to the next semicolon) } } processVariables.trimToSize(); } /** * @return <code>null</code>, if there are no more declarations */ protected ProcessVariable readProcessDeclaration(ExtendedListIterator<Token> tokens) { final Token token1 = tokens.hasNext() ? tokens.next() : null; final Token token2 = tokens.hasNext() ? tokens.next() : null; if (token1 == null || token2 == null) // there is no declaration return null; if (!(token1 instanceof Identifier)) return null; final Identifier identifier = (Identifier) token1; if (identifier.isQuoted() || !identifier.isUpperCase()) return null; ParameterList myParameters = null; Expression expr = null; try { if (token2 instanceof Assign) { myParameters = new ParameterList(0); expr = readExpression(tokens); } else if (token2 instanceof LBracket) { final List<Pair<Parameter, Pair<Token, Token>>> readParameters = readProcessParameters(tokens); if (readParameters == null || !(tokens.next() instanceof Assign)) return null; myParameters = new ParameterList(readParameters.size()); for (final Pair<Parameter, Pair<Token, Token>> param: readParameters) myParameters.add(param.getFirst()); // now that we know that we have a process declaration, check the // parameters (may throw a ParseException) checkProcessParameters(readParameters); // save old parameters final LinkedList<Parameter> oldParameters = parameters; try { // set new parameters parameters = new LinkedList<Parameter>(myParameters); expr = readExpression(tokens); } finally { // restore old parameters parameters = oldParameters; } } else return null; } catch (final ParseException e) { if (myParameters == null) myParameters = new ParameterList(0); reportProblem(new ParsingProblem(e)); } final Token nextToken = tokens.next(); // TODO remove this ambiguousness if (!(nextToken instanceof Semicolon) && !(nextToken instanceof Comma)) { // only report the error if the expression was read correctly if (expr != null) reportProblem(new ParsingProblem(ParsingProblem.ERROR, "Expected ';' after the declaration", tokens.peekPrevious())); // move forward to the next semicolon while (tokens.hasNext()) if (tokens.next() instanceof Semicolon) break; // we don't want to read the EOFToken if (tokens.peekPrevious() instanceof EOFToken) tokens.previous(); // ... and continue parsing } if (expr == null) expr = StopExpression.get(); final ProcessVariable proc = new ProcessVariable(identifier.getName(), myParameters, expr); // hook for logging: identifierParsed(identifier, proc); return proc; } /** * Read a Range definition. * * @param tokens * @return a {@link Range} read from the tokens * @throws ParseException on syntax errors */ private Range readRange(ExtendedListIterator<Token> tokens) throws ParseException { return readRangeAdd(tokens); } private Range readRangeAdd(ExtendedListIterator<Token> tokens) throws ParseException { Range range = readRangeDef(tokens); while (tokens.peek() instanceof Plus || tokens.peek() instanceof Minus) { final boolean isSub = tokens.next() instanceof Minus; final Range secondRange = readRangeDef(tokens); range = isSub ? range.subtract(secondRange) : range.add(secondRange); } return range; } private Range readRangeDef(ExtendedListIterator<Token> tokens) throws ParseException { final Token nextToken = tokens.peek(); // just a range definition in parenthesis? if (nextToken instanceof LParenthesis) { tokens.next(); final Range range = readRange(tokens); if (!tokens.hasNext() || !(tokens.next() instanceof RParenthesis)) throw new ParseException("Expected ')'.", tokens.peekPrevious()); return range; } // or a set of independant values if (nextToken instanceof LBrace) { tokens.next(); final ValueSet rangeValues = readRangeValues(tokens); return new SetRange(rangeValues); } // or a range of integer values int posStart = nextToken.getStartPosition(); final Value startValue = readArithmeticBaseExpression(tokens, false); // are there '..'? if (tokens.peek() instanceof IntervalDots) { ensureInteger(startValue, "Expected constant integer expression before '..'.", posStart, tokens.peekPrevious().getEndPosition()); tokens.next(); posStart = tokens.peek().getStartPosition(); final Value endValue = readArithmeticBaseExpression(tokens, false); ensureInteger(endValue, "Expected constant integer expression after '..'.", posStart, tokens.peekPrevious().getEndPosition()); return new IntervalRange(startValue, endValue); } // or another range (if the value was a string value) if (startValue instanceof ConstString) { final Range referencedRange = ranges.get(((ConstString)startValue).getStringValue()); if (referencedRange != null) { // hook for logging: changedIdentifierMeaning((ConstString)startValue, referencedRange); return referencedRange; } } // otherwise, there is an error throw new ParseException("No valid range definition.", nextToken); } private ValueSet readRangeValues(ExtendedListIterator<Token> it) throws ParseException { final ValueSet values = new ValueSet(); while (true) { final Value value = readArithmeticExpression(it); values.add(value); final Token nextToken = it.next(); if (nextToken instanceof RBrace) return values; if (!(nextToken instanceof Comma)) throw new ParseException("Expected ',' or '}'", nextToken); } } /** * Read all parameters up to the next RBracket (this token is read too). * * @return a List containing read parameters and the Token range where they * occured, or <code>null</code> if there was no declaration * @throws ParseException if there was definitly a declaration, but it had * syntactical errors */ private List<Pair<Parameter, Pair<Token, Token>>> readProcessParameters(ExtendedListIterator<Token> tokens) throws ParseException { final ArrayList<Pair<Parameter, Pair<Token, Token>>> parameters = new ArrayList<Pair<Parameter,Pair<Token,Token>>>(); if (tokens.peek() instanceof RBracket) { tokens.next(); return Collections.emptyList(); } while (true) { // read one parameter Token nextToken = tokens.next(); if (nextToken instanceof Identifier) { final Identifier identifier = (Identifier)nextToken; if (identifier.isQuoted()) return null; final String name = identifier.getName(); // range? Range range = null; if (tokens.hasNext() && tokens.peek() instanceof Colon) { tokens.next(); range = readRange(tokens); } final Parameter nextParameter = new Parameter(name, range); // hook for logging: identifierParsed(identifier, nextParameter); parameters.add(new Pair<Parameter, Pair<Token,Token>>(nextParameter, new Pair<Token, Token>(identifier, tokens.peekPrevious()))); } else return null; if (!tokens.hasNext()) return null; nextToken = tokens.next(); if (nextToken instanceof RBracket) { parameters.trimToSize(); return parameters; } if (!(nextToken instanceof Comma)) return null; } } private void checkProcessParameters(List<Pair<Parameter, Pair<Token, Token>>> readParameters) throws ParseException { final Set<String> names = new HashSet<String>(readParameters.size()*4/3+1); for (final Pair<Parameter, Pair<Token, Token>> param: readParameters) { final String name = param.getFirst().getName(); if ("i".equals(name)) throw new ParseException("\"i\" cannot be used as parameter identifier", param.getSecond().getFirst().getStartPosition(), param.getSecond().getSecond().getStartPosition()); if (!names.add(name)) throw new ParseException("Duplicate parameter identifier \"" + name + "\"", param.getSecond().getFirst().getStartPosition(), param.getSecond().getSecond().getStartPosition()); } } /** * Read all parameter values up to the next RBracket (this token is read too). */ private ValueList readParameterValues(ExtendedListIterator<Token> tokens) throws ParseException { final ValueList readParameters = new ValueList(); while (true) { if (tokens.peek() instanceof RBracket) { tokens.next(); readParameters.trimToSize(); return readParameters; } final Value nextValue = readArithmeticExpression(tokens); readParameters.add(nextValue); final Token nextToken = tokens.next(); if (nextToken instanceof RBracket) { readParameters.trimToSize(); return readParameters; } if (!(nextToken instanceof Comma)) throw new ParseException("Expected ',' or ']'", nextToken); } } /** * Read one Expression. */ private Expression readExpression(ExtendedListIterator<Token> tokens) throws ParseException { // the topmost operator is restriction: return readRestrictExpression(tokens); } /** * Read the "main expression". */ protected Expression readMainExpression(ExtendedListIterator<Token> tokens) throws ParseException { if (!tokens.hasNext() || tokens.peek() instanceof EOFToken) throw new ParseException("Missing main expression", tokens.hasNext() ? tokens.next() : tokens.peekPrevious()); return readExpression(tokens); } /** * Read one restriction expression. */ private Expression readRestrictExpression(ExtendedListIterator<Token> tokens) throws ParseException { Expression expr = readParallelExpression(tokens); while (tokens.peek() instanceof Restrict) { tokens.next(); if (!(tokens.next() instanceof LBrace)) throw new ParseException("Expected '{'", tokens.peekPrevious()); final ChannelSet restricted = readRestrictionChannelSet(tokens); expr = ExpressionRepository.getExpression(new RestrictExpression(expr, restricted)); } return expr; } /** * Read all actions up to the next RBrace (this token is read too). */ private ChannelSet readRestrictionChannelSet(ExtendedListIterator<Token> tokens) throws ParseException { final ChannelSet channels = new ChannelSet(); while (true) { final Token startToken = tokens.peek(); final Channel newChannel = readChannel(tokens); if (newChannel == null) throw new ParseException("Expected a channel here", startToken); if (newChannel instanceof TauChannel) throw new ParseException("Tau channel cannot be restricted", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); channels.add(newChannel); final Token nextToken = tokens.next(); if (nextToken instanceof RBrace) return channels; if (!(nextToken instanceof Comma)) throw new ParseException("Expected ',' or '}'", nextToken); } } /** * Read an Action. * * @param tokens * @return the read Action, or <code>null</code> if there is no action in the tokens. * In this case, the iterator is not changed. * @throws ParseException */ protected Action readAction(ExtendedListIterator<Token> tokens) throws ParseException { final Channel channel = readChannel(tokens); if (channel == null) return null; if (channel instanceof TauChannel) { if (tokens.peek() instanceof QuestionMark) throw new ParseException("Tau cannot be used as input channel", tokens.peek()); if (tokens.peek() instanceof Exclamation) throw new ParseException("Tau cannot be used as output channel", tokens.peek()); return TauAction.get(); } if (tokens.peek() instanceof QuestionMark) { tokens.next(); // read the input value // either a parameter if (tokens.peek() instanceof Identifier) { final Identifier identifier = (Identifier)tokens.next(); if (identifier.isQuoted()) tokens.previous(); else { Range range = null; if (tokens.peek() instanceof Colon) { tokens.next(); range = readRangeDef(tokens); } final Parameter parameter = new Parameter(identifier.getName(), range); // hook for logging: identifierParsed(identifier, parameter); return new InputAction(channel, parameter); } } // ELSE: // an arithmetic expression (if it is more complex, // it must have parenthesis around it) final int posStart = tokens.peek().getStartPosition(); final Value value = readArithmeticBaseExpression(tokens, true); // may return null if (value instanceof ParameterReference) try { ((ParameterReference) value).getParam().setType(Parameter.Type.VALUE); } catch (final ParseException e) { throw new ParseException(e.getMessage(), posStart, tokens.peekPrevious().getEndPosition()); } return new InputAction(channel, value); } else if (tokens.peek() instanceof Exclamation) { tokens.next(); // we have an output value (may be null) final Value value = readOutputValue(tokens); return new OutputAction(channel, value); } // no tau, no input, no output ==> it's a simple action return new SimpleAction(channel); } // returns null if there is no output value private Value readOutputValue(ExtendedListIterator<Token> tokens) throws ParseException { final int posStart = tokens.peek().getStartPosition(); final Value value = readArithmeticBaseExpression(tokens, true); // may return null if (value instanceof ParameterReference) try { ((ParameterReference)value).getParam().setType(Parameter.Type.VALUE); } catch (final ParseException e) { throw new ParseException(e.getMessage(), posStart, tokens.peekPrevious().getEndPosition()); } return value; } private Channel readChannel(ExtendedListIterator<Token> tokens) throws ParseException { if (!(tokens.peek() instanceof Identifier)) return null; final Identifier identifier = (Identifier)tokens.next(); Channel channel = null; if ("i".equals(identifier.getName())) { channel = TauChannel.get(); } else { if (!identifier.isQuoted()) { for (final Parameter param: parameters) { if (param.getName().equals(identifier.getName())) { try { param.setType(Parameter.Type.CHANNEL); } catch (final ParseException e) { throw new ParseException(e.getMessage(), identifier); } channel = new ParameterRefChannel(param); break; } } if (channel == null) { final ConstantValue val = constants.get(identifier.getName()); if (val != null) { if (val instanceof ConstStringChannel) { channel = (Channel) val; } else if (val instanceof ConstString) { final ConstString str = (ConstString) val; channel = new ConstStringChannel(str.getStringValue(), str.isQuoted()); } else { throw new ParseException("This constant cannot be used as channel identifier", identifier); } } if (channel != null) { // check if we have to quote the value if (channel instanceof ConstStringChannel) { final ConstStringChannel csc = (ConstStringChannel) channel; boolean needsQuotes = false; for (final Parameter param: parameters) needsQuotes |= param.getName().equals(csc.getStringValue()); if (needsQuotes && !csc.isQuoted()) channel = new ConstStringChannel(csc.getStringValue(), true); } } } } if (channel == null && identifier.isLowerCase()) channel = new ConstStringChannel(identifier.getName(), identifier.isQuoted()); } if (channel == null) { tokens.previous(); return null; } // hook for logging: identifierParsed(identifier, channel); return channel; } /** * Read one parallel expression. */ private Expression readParallelExpression(ExtendedListIterator<Token> tokens) throws ParseException { Expression expr = readChoiceExpression(tokens); while (tokens.peek() instanceof Parallel) { tokens.next(); final Expression newExpr = readChoiceExpression(tokens); expr = ParallelExpression.create(expr, newExpr); } return expr; } /** * Read one choice expression. */ private Expression readChoiceExpression(ExtendedListIterator<Token> tokens) throws ParseException { Expression expr = readPrefixExpression(tokens); while (tokens.peek() instanceof Plus) { tokens.next(); final Expression newExpr = readPrefixExpression(tokens); expr = ChoiceExpression.create(expr, newExpr); } return expr; } /** * Read one prefix expression. */ private Expression readPrefixExpression(ExtendedListIterator<Token> tokens) throws ParseException { final Action action = readAction(tokens); if (action == null) return readWhenExpression(tokens); if (tokens.peek() instanceof Dot) { tokens.next(); // if the read action is an InputAction with a parameter, we // have to add this parameter to the list of parameters Parameter newParam = null; if (action instanceof InputAction) { newParam = ((InputAction)action).getParameter(); if (newParam != null) { // add the new parameter in front of the list parameters.addFirst(newParam); } } final Expression target = readPrefixExpression(tokens); if (newParam != null) { final Parameter removedParam = parameters.removeFirst(); assert removedParam == newParam; } return ExpressionRepository.getExpression(new PrefixExpression(action, target)); } // otherwise, we append ".0" (i.e. we make a PrefixExpression with target = STOP return ExpressionRepository.getExpression(new PrefixExpression(action, StopExpression.get())); } private Expression readWhenExpression(ExtendedListIterator<Token> tokens) throws ParseException { if (tokens.peek() instanceof When) { tokens.next(); final int startPos = tokens.peek().getStartPosition(); final Value condition = readArithmeticExpression(tokens); ensureBoolean(condition, "Expected boolean expression after 'when'.", startPos, tokens.peekPrevious().getEndPosition()); // if there is a "then" now, ignore it if (tokens.hasNext() && tokens.peek() instanceof Then) tokens.next(); final Expression consequence = readPrefixExpression(tokens); Expression condExpr = ConditionalExpression.create(condition, consequence); // we allow an "else" here to declare an alternative, but internally, // it is mapped to a "(when (x) <consequence>) + (when (!x) <alternative>)" if (tokens.hasNext() && tokens.peek() instanceof Else) { tokens.next(); Expression alternative = readPrefixExpression(tokens); // build negated condition final Value negatedCondition = condition instanceof NotValue ? ((NotValue)condition).getNegatedValue() : NotValue.create(condition); alternative = ConditionalExpression.create(negatedCondition, alternative); condExpr = ChoiceExpression.create(condExpr, alternative); } return condExpr; } return readBaseExpression(tokens); } /** * Read one base expression (stop, error, expression in parentheses, or recursion variable). */ private Expression readBaseExpression(ExtendedListIterator<Token> tokens) throws ParseException { final Token nextToken = tokens.next(); if (nextToken instanceof Stop) return ExpressionRepository.getExpression(StopExpression.get()); if (nextToken instanceof ErrorToken) return ExpressionRepository.getExpression(ErrorExpression.get()); if (nextToken instanceof LParenthesis) { final Expression expr = readExpression(tokens); if (!tokens.hasNext() || !(tokens.next() instanceof RParenthesis)) throw new ParseException("Expected ')'", tokens.peekPrevious()); return expr; } if (nextToken instanceof Identifier) { final Identifier id = (Identifier) nextToken; if (id.isUpperCase()) { final ValueList myParameters; if (tokens.hasNext() && tokens.peek() instanceof LBracket) { tokens.next(); myParameters = readParameterValues(tokens); } else myParameters = new ValueList(0); final Expression expression = ExpressionRepository.getExpression(new UnknownRecursiveExpression(id.getName(), myParameters, id.getStartPosition(), tokens.peekPrevious().getEndPosition())); // hook for logging: identifierParsed(id, expression); return expression; } } tokens.previous(); throw new ParseException(nextToken instanceof EOFToken ? "Unexpected end of file" : "Syntax error (unexpected token)", nextToken); } private Value readArithmeticExpression(ExtendedListIterator<Token> tokens) throws ParseException { return readArithmeticConditionalExpression(tokens); } private Value readArithmeticConditionalExpression(ExtendedListIterator<Token> tokens) throws ParseException { final Token startToken = tokens.peek(); final Value orValue = readArithmeticOrExpression(tokens); if (tokens.peek() instanceof QuestionMark) { tokens.next(); ensureBoolean(orValue, "Boolean expression required before '?:' construct.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); final Value thenValue = readArithmeticConditionalExpression(tokens); if (!(tokens.next() instanceof Colon)) throw new ParseException("Expected ':'", tokens.previous()); final Value elseValue = readArithmeticConditionalExpression(tokens); ensureEqualTypes(thenValue, elseValue, "Expression in '?:' construct must have the same type.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); return ConditionalValue.create(orValue, thenValue, elseValue); } return orValue; } private Value readArithmeticOrExpression(ExtendedListIterator<Token> tokens) throws ParseException { Token startToken = tokens.peek(); Value value = readArithmeticAndExpression(tokens); while (tokens.peek() instanceof Or) { tokens.next(); ensureBoolean(value, "Boolean expression required before '||'.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); startToken = tokens.peek(); final Value secondValue = readArithmeticAndExpression(tokens); ensureBoolean(secondValue, "Boolean expression required after '||'.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); value = OrValue.create(value, secondValue); } return value; } private Value readArithmeticAndExpression(ExtendedListIterator<Token> tokens) throws ParseException { Token startToken = tokens.peek(); Value value = readArithmeticEqExpression(tokens); while (tokens.peek() instanceof And) { tokens.next(); ensureBoolean(value, "Boolean expression required before '&&'.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); startToken = tokens.peek(); final Value secondValue = readArithmeticEqExpression(tokens); ensureBoolean(secondValue, "Boolean expression required after '&&'.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); value = AndValue.create(value, secondValue); } return value; } private Value readArithmeticEqExpression(ExtendedListIterator<Token> tokens) throws ParseException { final Token startToken = tokens.peek(); Value value = readArithmeticCompExpression(tokens); while (tokens.peek() instanceof Equals || tokens.peek() instanceof Neq) { final boolean isNeq = tokens.next() instanceof Neq; final Value secondValue = readArithmeticCompExpression(tokens); final int posAfter = tokens.peekPrevious().getEndPosition(); ensureEqualTypes(value, secondValue, "Values to compare must have the same type.", startToken.getStartPosition(), posAfter); value = EqValue.create(value, secondValue, isNeq); } return value; } private Value readArithmeticCompExpression(ExtendedListIterator<Token> tokens) throws ParseException { Token startToken = tokens.peek(); final Value value = readArithmeticShiftExpression(tokens); final Token nextToken = tokens.peek(); CompValue.Type type = null; if (nextToken instanceof Less) type = CompValue.Type.LESS; else if (nextToken instanceof Leq) type = CompValue.Type.LEQ; else if (nextToken instanceof Geq) type = CompValue.Type.GEQ; else if (nextToken instanceof Greater) type = CompValue.Type.GREATER; if (type != null) { Token endToken = tokens.peekPrevious(); tokens.next(); ensureInteger(value, "Only integer values can be compared.", startToken.getStartPosition(), endToken.getEndPosition()); startToken = tokens.peek(); final Value secondValue = readArithmeticShiftExpression(tokens); endToken = tokens.peekPrevious(); ensureInteger(secondValue, "Only integer values can be compared.", startToken.getStartPosition(), endToken.getEndPosition()); return CompValue.create(value, secondValue, type); } return value; } private Value readArithmeticShiftExpression(ExtendedListIterator<Token> tokens) throws ParseException { Token startToken = tokens.peek(); Value value = readArithmeticAddExpression(tokens); while (tokens.peek() instanceof LeftShift || tokens.peek() instanceof RightShift) { ensureInteger(value, "Only integer values can be shifted.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); final boolean shiftRight = tokens.next() instanceof RightShift; startToken = tokens.peek(); final Value secondValue = readArithmeticAddExpression(tokens); ensureInteger(secondValue, "Shifting width must be an integer.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); value = ShiftValue.create(value, secondValue, shiftRight); } return value; } private Value readArithmeticAddExpression(ExtendedListIterator<Token> tokens) throws ParseException { Token startToken = tokens.peek(); Value value = readArithmeticMultExpression(tokens); while (tokens.peek() instanceof Plus || tokens.peek() instanceof Minus) { ensureInteger(value, "Both sides of an addition must be integers.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); final boolean isSubtraction = tokens.next() instanceof Minus; startToken = tokens.peek(); final Value secondValue = readArithmeticMultExpression(tokens); ensureInteger(secondValue, "Both sides of an addition must be integers.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); value = AddValue.create(value, secondValue, isSubtraction); } return value; } private Value readArithmeticMultExpression(ExtendedListIterator<Token> tokens) throws ParseException { Token startToken = tokens.peek(); Value value = readArithmeticUnaryExpression(tokens); while (true) { final Token nextToken = tokens.peek(); MultValue.Type type = null; if (nextToken instanceof Multiplication) type = MultValue.Type.MULT; else if (nextToken instanceof Division) type = MultValue.Type.DIV; else if (nextToken instanceof Modulo) type = MultValue.Type.MOD; if (type == null) break; ensureInteger(value, "Both sides of a multiplication/division must be integer expressions.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); tokens.next(); startToken = tokens.peek(); final Value secondValue = readArithmeticUnaryExpression(tokens); ensureInteger(secondValue, "Both sides of a multiplication/division must be integer expressions.", startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); try { value = MultValue.create(value, secondValue, type); } catch (final ArithmeticError e) { throw new ParseException("Arithmetic error: " + e.getMessage(), startToken.getStartPosition(), tokens.peekPrevious().getEndPosition()); } } return value; } private Value readArithmeticUnaryExpression(ExtendedListIterator<Token> tokens) throws ParseException { final Token nextToken = tokens.peek(); if (nextToken instanceof Exclamation) { tokens.next(); final int posStart = tokens.peek().getStartPosition(); final Value negatedValue = readArithmeticUnaryExpression(tokens); ensureBoolean(negatedValue, "The negated value must be a boolean expression.", posStart, tokens.peekPrevious().getEndPosition()); return NotValue.create(negatedValue); } else if (nextToken instanceof Plus) { tokens.next(); return readArithmeticUnaryExpression(tokens); } else if (nextToken instanceof Minus) { tokens.next(); final int posStart = tokens.peek().getStartPosition(); final Value negativeValue = readArithmeticUnaryExpression(tokens); ensureInteger(negativeValue, "The negated value must be an integer expression.", posStart, tokens.peekPrevious().getEndPosition()); return NegativeValue.create(negativeValue); } // else: return readArithmeticBaseExpression(tokens, false); } private Value readArithmeticBaseExpression(ExtendedListIterator<Token> tokens, boolean allowNull) throws ParseException { final Token nextToken = tokens.next(); if (nextToken instanceof IntegerToken) return new ConstIntegerValue(((IntegerToken)nextToken).getValue()); // a stop is the integer "0" here... if (nextToken instanceof Stop) { // change the token in the token list (for highlighting etc.) tokens.set(tokens.previousIndex(), new IntegerToken(nextToken.getStartPosition(), nextToken.getEndPosition(), 0)); return new ConstIntegerValue(0); } if (nextToken instanceof True) return ConstBooleanValue.get(true); if (nextToken instanceof False) return ConstBooleanValue.get(false); if (nextToken instanceof Identifier) { final Identifier id = (Identifier)nextToken; final String name = id.getName(); if (!id.isQuoted()) { // search if this identifier is a parameter for (final Parameter param: parameters) if (param.getName().equals(name)) { final ParameterReference parameterReference = new ParameterReference(param); // hook for logging: identifierParsed(id, parameterReference); return parameterReference; } // search if it is a constant final ConstantValue constant = constants.get(name); if (constant != null) { // hook for logging: identifierParsed(id, constant); return constant; } } final ConstString constString = new ConstString(name, id.isQuoted()); // hook for logging: identifierParsed(id, constString); return constString; } if (nextToken instanceof LParenthesis) { final Value value = readArithmeticExpression(tokens); if (!(tokens.next() instanceof RParenthesis)) throw new ParseException("Expected ')'.", tokens.peekPrevious()); return value; } tokens.previous(); if (!allowNull) throw new ParseException("Expected arithmetic expression", nextToken); return null; } private void ensureEqualTypes(Value value1, Value value2, String message, int startPos, int endPos) throws ParseException { if (value1 instanceof IntegerValue && value2 instanceof IntegerValue) return; if (value1 instanceof BooleanValue && value2 instanceof BooleanValue) return; if (value1 instanceof ConstString && value2 instanceof ConstString) return; try { if (value1 instanceof ParameterReference || value1 instanceof ParameterRefChannel) { ((ParameterReference)value1).getParam().match(value2); return; } if (value2 instanceof ParameterReference || value2 instanceof ParameterRefChannel) { ((ParameterReference)value2).getParam().match(value1); return; } } catch (final ParseException e) { throw new ParseException(e.getMessage(), startPos, endPos); } if (value1 instanceof ConditionalValue) { ensureEqualTypes(((ConditionalValue)value1).getThenValue(), value2, message, startPos, endPos); ensureEqualTypes(((ConditionalValue)value1).getElseValue(), value2, message, startPos, endPos); } else if (value2 instanceof ConditionalValue) { ensureEqualTypes(value1, ((ConditionalValue)value2).getThenValue(), message, startPos, endPos); ensureEqualTypes(value1, ((ConditionalValue)value2).getElseValue(), message, startPos, endPos); } throw new ParseException(message + " The values \"" + value1 + "\" and \"" + value2 + "\" have different types.", startPos, endPos); } private void ensureBoolean(Value value, String message, int startPos, int endPos) throws ParseException { if (value instanceof BooleanValue) return; if (value instanceof IntegerValue) throw new ParseException(message + " The value \"" + value + "\" has type integer.", startPos, endPos); if (value instanceof ConstString) throw new ParseException(message + " The value \"" + value + "\" has type string.", startPos, endPos); if (value instanceof ParameterReference) { try { ((ParameterReference)value).getParam().setType(Parameter.Type.BOOLEANVALUE); } catch (final ParseException e) { throw new ParseException(message + e.getMessage(), startPos, endPos); } return; } if (value instanceof ConditionalValue) { ensureBoolean(((ConditionalValue)value).getThenValue(), message, startPos, endPos); ensureBoolean(((ConditionalValue)value).getElseValue(), message, startPos, endPos); } assert false; throw new ParseException(message, startPos, endPos); } private void ensureInteger(Value value, String message, int startPos, int endPos) throws ParseException { if (value instanceof IntegerValue) return; if (value instanceof BooleanValue) throw new ParseException(message + " The value \"" + value + "\" has type boolean.", startPos, endPos); if (value instanceof ConstString) throw new ParseException(message + " The value \"" + value + "\" has type string.", startPos, endPos); if (value instanceof ParameterReference) { try { ((ParameterReference)value).getParam().setType(Parameter.Type.INTEGERVALUE); } catch (final ParseException e) { throw new ParseException(message + e.getMessage(), startPos, endPos); } return; } if (value instanceof ConditionalValue) { ensureInteger(((ConditionalValue)value).getThenValue(), message, startPos, endPos); ensureInteger(((ConditionalValue)value).getElseValue(), message, startPos, endPos); } assert false; throw new ParseException(message, startPos, endPos); } protected void identifierParsed(Identifier identifier, Object semantic) { // ignore in this implementation } protected void changedIdentifierMeaning(ConstString constString, Range range) { // ignore in this implementation } public void addProblemListener(IParsingProblemListener listener) { listeners.add(listener); } public void removeProblemListener(IParsingProblemListener listener) { listeners.remove(listener); } public void reportProblem(ParsingProblem problem) { for (final IParsingProblemListener listener: listeners) listener.reportParsingProblem(problem); } protected void reportUnboundInputParameter(Action act) { reportProblem(new ParsingProblem(ParsingProblem.ERROR, "The action \"" + act + "\" is not restricted and without a range. " + "This would leed to infinitely many transitions.", -1, -1)); } }
package cgeo.geocaching.downloader; import cgeo.geocaching.R; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.models.OfflineMap; import cgeo.geocaching.storage.ContentStorage; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.AsyncTaskWithProgressText; import cgeo.geocaching.utils.FileNameCreator; import cgeo.geocaching.utils.FileUtils; import cgeo.geocaching.utils.Log; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; /** * Receives a map file via intent, moves it to the currently set map directory and sets it as current map source. * If no map directory is set currently, default map directory is used, created if needed, and saved as map directory in preferences. * If the map file already exists under that name in the map directory, you have the option to either overwrite it or save it under a randomly generated name. */ public class ReceiveMapFileActivity extends AbstractActivity { public static final String EXTRA_FILENAME = "filename"; private Uri uri = null; private String filename = null; private String sourceURL = ""; private long sourceDate = 0; private int offlineMapTypeId = OfflineMap.OfflineMapType.DEFAULT; private AbstractDownloader downloader; protected enum CopyStates { SUCCESS, CANCELLED, IO_EXCEPTION, FILENOTFOUND_EXCEPTION, UNKNOWN_STATE } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(); final Intent intent = getIntent(); uri = intent.getData(); final String preset = intent.getStringExtra(EXTRA_FILENAME); sourceURL = intent.getStringExtra(MapDownloaderUtils.RESULT_CHOSEN_URL); sourceDate = intent.getLongExtra(MapDownloaderUtils.RESULT_DATE, 0); offlineMapTypeId = intent.getIntExtra(MapDownloaderUtils.RESULT_TYPEID, OfflineMap.OfflineMapType.DEFAULT); downloader = OfflineMap.OfflineMapType.getInstance(offlineMapTypeId); MapDownloaderUtils.checkMapDirectory(this, false, (folder, isWritable) -> { if (isWritable) { boolean foundMapInZip = false; // test if ZIP file received try (BufferedInputStream bis = new BufferedInputStream(getContentResolver().openInputStream(uri)); ZipInputStream zis = new ZipInputStream(bis)) { ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { String filename = ze.getName(); final int posExt = filename.lastIndexOf('.'); if (posExt != -1 && (StringUtils.equalsIgnoreCase(FileUtils.MAP_FILE_EXTENSION, filename.substring(posExt)))) { filename = downloader.toVisibleFilename(filename); // found map file within zip if (guessFilename(filename)) { handleMapFile(this, true, ze.getName()); foundMapInZip = true; } } } } catch (IOException | SecurityException e) { // ignore ZIP errors } // if no ZIP file: continue with copying the file if (!foundMapInZip && guessFilename(preset)) { handleMapFile(this, false, null); } } else { finish(); } }); } // try to guess a filename, otherwise chose randomized filename private boolean guessFilename(final String preset) { filename = StringUtils.isNotBlank(preset) ? preset : uri.getPath(); // uri.getLastPathSegment doesn't help here, if path is encoded if (filename != null) { filename = FileUtils.getFilenameFromPath(filename); if (StringUtils.isNotBlank(downloader.forceExtension)) { final int posExt = filename.lastIndexOf('.'); if (posExt == -1 || !(StringUtils.equalsIgnoreCase(downloader.forceExtension, filename.substring(posExt)))) { filename += downloader.forceExtension; } } } if (filename == null) { filename = FileNameCreator.OFFLINE_MAPS.createName(); } return true; } private void handleMapFile(final Activity activity, final boolean isZipFile, final String nameWithinZip) { // check whether the target file or its companion file already exist final List<ContentStorage.FileInformation> files = ContentStorage.get().list(downloader.targetFolder.getFolder(), false, false); Uri companionFileExists = CompanionFileUtils.companionFileExists(files, filename); Uri downloadFileExists = null; for (ContentStorage.FileInformation fi : files) { if (fi.name.equals(filename)) { downloadFileExists = fi.uri; break; } } // a companion file without original file does not make sense => delete if (downloadFileExists == null && companionFileExists != null) { ContentStorage.get().delete(companionFileExists); companionFileExists = null; } final Uri df = downloadFileExists; final Uri cf = companionFileExists; if (df != null) { final AlertDialog.Builder builder = Dialogs.newBuilder(activity); final AlertDialog dialog = builder.setTitle(R.string.receivemapfile_intenttitle) .setCancelable(true) .setMessage(R.string.receivemapfile_alreadyexists) .setPositiveButton(R.string.receivemapfile_option_overwrite, (dialog3, button3) -> { // for overwrite: delete existing files ContentStorage.get().delete(df); if (cf != null) { ContentStorage.get().delete(cf); } new CopyTask(this, isZipFile, nameWithinZip).execute(); }) .setNeutralButton(R.string.receivemapfile_option_differentname, (dialog2, button2) -> { // when overwriting generate new filename internally and check for collisions with companion file (would be a lone companion file, so delete silently) final List<String> existingFiles = new ArrayList<>(); for (ContentStorage.FileInformation fi : files) { existingFiles.add(fi.name); } filename = FileUtils.createUniqueFilename(filename, existingFiles); final Uri newCompanionFile = CompanionFileUtils.companionFileExists(files, filename); if (newCompanionFile != null) { ContentStorage.get().delete(newCompanionFile); } new CopyTask(this, isZipFile, nameWithinZip).execute(); }) .setNegativeButton(android.R.string.cancel, (dialog4, which4) -> activity.finish()) .create(); dialog.setOwnerActivity(activity); dialog.show(); } else { new CopyTask(this, isZipFile, nameWithinZip).execute(); } } protected class CopyTask extends AsyncTaskWithProgressText<String, CopyStates> { private long bytesCopied = 0; private final String progressFormat = getString(R.string.receivemapfile_kb_copied); private final AtomicBoolean cancelled = new AtomicBoolean(false); private final Activity context; private final boolean isZipFile; private final String nameWithinZip; CopyTask(final Activity activity, final boolean isZipFile, final String nameWithinZip) { super(activity, activity.getString(R.string.receivemapfile_intenttitle), ""); setOnCancelListener((dialog, which) -> cancelled.set(true)); context = activity; this.isZipFile = isZipFile; this.nameWithinZip = nameWithinZip; } @Override protected CopyStates doInBackgroundInternal(final String[] logTexts) { CopyStates status = CopyStates.UNKNOWN_STATE; Log.d("start receiving map file: " + filename); InputStream inputStream = null; final Uri outputUri = ContentStorage.get().create(downloader.targetFolder, filename); try { inputStream = new BufferedInputStream(getContentResolver().openInputStream(uri)); if (isZipFile) { try (ZipInputStream zis = new ZipInputStream(inputStream)) { ZipEntry ze; boolean stillSearching = true; while (stillSearching && (ze = zis.getNextEntry()) != null) { if (ze.getName().equals(nameWithinZip)) { status = doCopy(zis, outputUri); stillSearching = false; // don't continue here, as doCopy also closes the input stream, so further reads would lead to IOException } } } catch (IOException e) { Log.e("IOException on receiving map file: " + e.getMessage()); status = CopyStates.IO_EXCEPTION; } } else { status = doCopy(inputStream, outputUri); } } catch (SecurityException e) { Log.e("SecurityException on receiving map file: " + e.getMessage()); return CopyStates.FILENOTFOUND_EXCEPTION; } catch (FileNotFoundException e) { return CopyStates.FILENOTFOUND_EXCEPTION; } finally { IOUtils.closeQuietly(inputStream); } // clean up and refresh available map list if (!cancelled.get()) { try { getContentResolver().delete(uri, null, null); } catch (IllegalArgumentException iae) { Log.w("Deleting Uri '" + uri + "' failed, will be ignored", iae); } // finalization AFTER deleting source file. This handles the very special case when Map Folder = Download Folder downloader.onSuccessfulReceive(outputUri); } else { ContentStorage.get().delete(outputUri); status = CopyStates.CANCELLED; } return status; } private CopyStates doCopy(final InputStream inputStream, final Uri outputUri) { OutputStream outputStream = null; try { outputStream = ContentStorage.get().openForWrite(outputUri); final byte[] buffer = new byte[64 << 10]; int length = 0; while (!cancelled.get() && (length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); bytesCopied += length; publishProgress(String.format(progressFormat, bytesCopied >> 10)); } return CopyStates.SUCCESS; } catch (IOException e) { Log.e("IOException on receiving map file: " + e.getMessage()); return CopyStates.IO_EXCEPTION; } finally { IOUtils.closeQuietly(inputStream, outputStream); } } @Override protected void onPostExecuteInternal(final CopyStates status) { final String result; String fileinfo = filename; if (fileinfo != null) { fileinfo = fileinfo.substring(0, fileinfo.length() - downloader.forceExtension.length()); } switch (status) { case SUCCESS: result = String.format(getString(R.string.receivemapfile_success), fileinfo); if (StringUtils.isNotBlank(sourceURL)) { CompanionFileUtils.writeInfo(sourceURL, filename, CompanionFileUtils.getDisplayName(fileinfo), sourceDate, offlineMapTypeId); } break; case CANCELLED: result = getString(R.string.receivemapfile_cancelled); break; case IO_EXCEPTION: result = String.format(getString(R.string.receivemapfile_error_io_exception), downloader.targetFolder.toUserDisplayableValue()); break; case FILENOTFOUND_EXCEPTION: result = getString(R.string.receivemapfile_error_filenotfound_exception); break; default: result = getString(R.string.receivemapfile_error); break; } Dialogs.message(context, getString(R.string.receivemapfile_intenttitle), result, getString(android.R.string.ok), (dialog, button) -> downloader.onFollowup(activity, ReceiveMapFileActivity.this::doFinish)); } } private void doFinish() { finish(); } }
package arez.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import javax.annotation.Nonnull; /** * Marks a template method that returns the {@link arez.ComputedValue} instance for * the {@link Computed} annotated property. Each property marked with the {@link Computed} annotation is backed * by an {@link arez.ComputedValue} instance and some frameworks make use of this value to implement * advanced functionality. * * <p>The method that is annotated with this annotation must also comply with the following constraints:</p> * <ul> * <li>Must not be annotated with any other arez annotation</li> * <li>Must not be private</li> * <li>Must not be static</li> * <li>Must not be final</li> * <li>Must be abstract</li> * <li>Must not throw any exceptions</li> * <li>Must return an instance of {@link arez.ComputedValue}.</li> * </ul> */ @Documented @Target( ElementType.METHOD ) public @interface ComputedValueRef { /** * Return the name of the associated Computed property that this ref relates to. * This value will be derived if the method name matches the pattern "get[Name]ComputedValue", * otherwise it must be specified. * * @return the name of the associated ComputedValue. */ @Nonnull String name() default "<default>"; }
package com.bloatit.rest.resources; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import com.bloatit.framework.restprocessor.RestElement; import com.bloatit.framework.restprocessor.RestServer.RequestMethod; import com.bloatit.framework.restprocessor.annotations.REST; import com.bloatit.model.FileMetadata; import com.bloatit.model.Software; import com.bloatit.model.managers.SoftwareManager; import com.bloatit.rest.list.RestFeatureList; import com.bloatit.rest.list.RestSoftwareList; /** * <p> * Representation of a Software for the ReST RPC calls * </p> * <p> * This class should implement any methods from Software that needs to be called * through the ReST RPC. Every such method needs to be mapped with the * {@code @REST} interface. * <p> * ReST uses the four HTTP request methods <code>GET</code>, <code>POST</code>, * <code>PUT</code>, <code>DELETE</code> each with their own meaning. Please * only bind the according to the following: * <li>GET list: List the URIs and perhaps other details of the collection's * members.</li> * <li>GET list/id: Retrieve a representation of the addressed member of the * collection, expressed in an appropriate Internet media type.</li> * <li>POST list: Create a new entry in the collection. The new entry's URL is * assigned automatically and is usually returned by the operation.</li> * <li>POST list/id: Treat the addressed member as a collection in its own right * and create a new entry in it.</li> * <li>PUT list: Replace the entire collection with another collection.</li> * <li>PUT list/id: Replace the addressed member of the collection, or if it * doesn't exist, create it.</li> * <li>DELETE list: Delete the entire collection.</li> * <li>DELETE list/id: Delete the addressed member of the collection.</li> * </p> * </p> * <p> * This class will be serialized as XML (or maybe JSON who knows) to be sent * over to the client RPC. Hence this class needs to be annotated to indicate * which methods (and/or fields) are to be matched in the XML data. For this * use: * <li>@XmlRootElement at the root of the class</li> * <li>@XmlElement on each method/attribute that will yield <i>complex</i> data</li> * <li>@XmlAttribute on each method/attribute that will yield <i>simple</i> data * </li> * <li>Methods that return a list need to be annotated with @XmlElement and to * return a RestSoftwareList</li> * </p> */ @XmlRootElement(name = "software") @XmlAccessorType(XmlAccessType.NONE) public class RestSoftware extends RestElement<Software> { private Software model; // -- Constructors /** * Provided for JAXB */ @SuppressWarnings("unused") private RestSoftware() { super(); } protected RestSoftware(final Software model) { this.model = model; } // -- Static methods /** * <p> * Finds the RestSoftware matching the <code>id</code> * </p> * * @param id the id of the RestSoftware */ @REST(name = "softwares", method = RequestMethod.GET) public static RestSoftware getById(final int id) { final RestSoftware restSoftware = new RestSoftware(SoftwareManager.getById(id)); if (restSoftware.isNull()) { return null; } return restSoftware; } /** * <p> * Finds the list of all (valid) RestSoftware * </p> */ @REST(name = "softwares", method = RequestMethod.GET) public static RestSoftwareList getAll() { return new RestSoftwareList(SoftwareManager.getAll()); } // -- XML Getters @XmlAttribute @XmlID public String getId() { return model.getId().toString(); } /** * @see com.bloatit.model.Software#getName() */ @XmlAttribute public String getName() { return model.getName(); } /** * @see com.bloatit.model.Software#getDescription() */ @XmlElement public RestDescription getDescription() { return new RestDescription(model.getDescription()); } /** * @see com.bloatit.model.Software#getFeatures() */ @XmlElement public RestFeatureList getFeatures() { return new RestFeatureList(model.getFeatures()); } /** * @see com.bloatit.model.Software#getImage() */ @XmlElement public RestFileMetadata getImage() { FileMetadata image = model.getImage(); if (image != null) { return new RestFileMetadata(image); } return null; } // -- Utils /** * Provided for JAXB */ void setModel(final Software model) { this.model = model; } /** * Package method to find the model */ Software getModel() { return model; } @Override public boolean isNull() { return (model == null); } }
package bisq.core.btc.wallet; import bisq.common.config.Config; import org.bitcoinj.core.Coin; public class Restrictions { private static Coin MIN_TRADE_AMOUNT; private static Coin MIN_BUYER_SECURITY_DEPOSIT; // For the seller we use a fixed one as there is no way the seller can cancel the trade // To make it editable would just increase complexity. private static Coin SELLER_SECURITY_DEPOSIT; // At mediation we require a min. payout to the losing party to keep incentive for the trader to accept the // mediated payout. For Refund agent cases we do not have that restriction. private static Coin MIN_REFUND_AT_MEDIATED_DISPUTE; public static Coin getMinNonDustOutput() { if (minNonDustOutput == null) minNonDustOutput = Config.baseCurrencyNetwork().getParameters().getMinNonDustOutput(); return minNonDustOutput; } private static Coin minNonDustOutput; public static boolean isAboveDust(Coin amount) { return amount.compareTo(getMinNonDustOutput()) >= 0; } public static boolean isDust(Coin amount) { return !isAboveDust(amount); } public static Coin getMinTradeAmount() { if (MIN_TRADE_AMOUNT == null) MIN_TRADE_AMOUNT = Coin.valueOf(10_000); // 0,7 USD @ 7000 USD/BTC return MIN_TRADE_AMOUNT; } public static double getDefaultBuyerSecurityDepositAsPercent() { return 0.15; // 15% of trade amount. } public static double getMinBuyerSecurityDepositAsPercent() { return 0.15; // 15% of trade amount. } public static double getMaxBuyerSecurityDepositAsPercent() { return 0.5; // 50% of trade amount. For a 1 BTC trade it is about 3500 USD @ 7000 USD/BTC } // We use MIN_BUYER_SECURITY_DEPOSIT as well as lower bound in case of small trade amounts. // So 0.0005 BTC is the min. buyer security deposit even with amount of 0.0001 BTC and 0.05% percentage value. public static Coin getMinBuyerSecurityDepositAsCoin() { if (MIN_BUYER_SECURITY_DEPOSIT == null) MIN_BUYER_SECURITY_DEPOSIT = Coin.parseCoin("0.006"); // 0.006 BTC about 42 USD @ 7000 USD/BTC return MIN_BUYER_SECURITY_DEPOSIT; } public static double getSellerSecurityDepositAsPercent() { return 0.15; // 15% of trade amount. } public static Coin getMinSellerSecurityDepositAsCoin() { if (SELLER_SECURITY_DEPOSIT == null) SELLER_SECURITY_DEPOSIT = Coin.parseCoin("0.006"); // 0.006 BTC about 42 USD @ 7000 USD/BTC return SELLER_SECURITY_DEPOSIT; } // This value must be lower than MIN_BUYER_SECURITY_DEPOSIT and SELLER_SECURITY_DEPOSIT public static Coin getMinRefundAtMediatedDispute() { if (MIN_REFUND_AT_MEDIATED_DISPUTE == null) MIN_REFUND_AT_MEDIATED_DISPUTE = Coin.parseCoin("0.003"); // 0.003 BTC about 21 USD @ 7000 USD/BTC return MIN_REFUND_AT_MEDIATED_DISPUTE; } public static int getLockTime(boolean isAsset) { // 10 days for altcoins, 20 days for other payment methods return isAsset ? 144 * 10 : 144 * 20; } }
package hudson.matrix; import hudson.FilePath; import hudson.model.DependencyGraph; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.JDK; import hudson.model.Label; import hudson.model.Node; import hudson.model.Project; import hudson.model.SCMedItem; import hudson.scm.SCM; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.LogRotator; import hudson.tasks.Publisher; import java.io.IOException; import java.util.Map; /** * One configuration of {@link MatrixProject}. * * @author Kohsuke Kawaguchi */ public class MatrixConfiguration extends Project<MatrixConfiguration,MatrixRun> implements SCMedItem { /** * The actual value combination. */ private transient /*final*/ Combination combination; public MatrixConfiguration(MatrixProject parent, Combination c) { super(parent,c.toString()); this.combination = c; } public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { super.onLoad(parent, combination.toString()); } /** * Used during loading to set the combination back. */ /*package*/ void setCombination(Combination c) { this.combination = c; } /** * Build numbers are always synchronized with the parent. */ @Override public int getNextBuildNumber() { MatrixBuild lb = getParent().getLastBuild(); return lb!=null ? lb.getNumber() : 0; } public int assignBuildNumber() throws IOException { int nb = getNextBuildNumber(); MatrixRun r = getLastBuild(); if(r!=null && r.getNumber()>=nb) // make sure we don't schedule the same build twice throw new IllegalStateException("Build #"+nb+" is already completed"); return nb; } @Override public String getDisplayName() { return combination.toCompactString(getParent().getAxes()); } public MatrixProject getParent() { return (MatrixProject)super.getParent(); } /** * Get the actual combination of the axes values for this {@link MatrixConfiguration} */ public Combination getCombination() { return combination; } @Override public FilePath getWorkspace() { Node node = getLastBuiltOn(); if(node==null) node = Hudson.getInstance(); FilePath ws = node.getWorkspaceFor(getParent()); if(ws==null) return null; return ws.child(getCombination().toString('/','/')); } @Override public boolean isConfigurable() { return false; } @Override protected Class<MatrixRun> getBuildClass() { return MatrixRun.class; } @Override protected MatrixRun newBuild() throws IOException { // for every MatrixRun there should be a parent MatrixBuild MatrixBuild lb = getParent().getLastBuild(); MatrixRun lastBuild = new MatrixRun(this, lb.getTimestamp()); lastBuild.number = lb.getNumber(); builds.put(lastBuild); return lastBuild; } @Override public boolean isFingerprintConfigured() { // TODO return false; } @Override protected void buildDependencyGraph(DependencyGraph graph) { } public MatrixConfiguration asProject() { return this; } @Override public Label getAssignedLabel() { return Hudson.getInstance().getLabel(combination.get("label")); } @Override public String getPronoun() { return "Configuration"; } @Override public JDK getJDK() { return Hudson.getInstance().getJDK(combination.get("jdk")); } // inherit build setting from the parent project @Override public Map<Descriptor<Builder>, Builder> getBuilders() { return getParent().getBuilders(); } @Override public Map<Descriptor<Publisher>, Publisher> getPublishers() { return getParent().getPublishers(); } @Override public Map<Descriptor<BuildWrapper>, BuildWrapper> getBuildWrappers() { return getParent().getBuildWrappers(); } @Override public Publisher getPublisher(Descriptor<Publisher> descriptor) { return getParent().getPublisher(descriptor); } @Override public LogRotator getLogRotator() { return new LinkedLogRotator(); } @Override public SCM getScm() { return getParent().getScm(); } /** * JDK cannot be set on {@link MatrixConfiguration} because * it's controlled by {@link MatrixProject}. * @deprecated * Not supported. */ public void setJDK(JDK jdk) throws IOException { throw new UnsupportedOperationException(); } /** * @deprecated * Value is controlled by {@link MatrixProject}. */ public void setLogRotator(LogRotator logRotator) { throw new UnsupportedOperationException(); } /** * Returns true if this configuration is a configuration * currently in use today (as opposed to the ones that are * there only to keep the past record.) * * @see MatrixProject#getActiveConfigurations() */ public boolean isActiveConfiguration() { return getParent().getActiveConfigurations().contains(this); } }
package lucee.runtime.osgi; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.Bundle; import org.osgi.framework.BundleReference; import lucee.commons.io.IOUtil; import lucee.commons.io.SystemUtil; import lucee.commons.io.log.Log; import lucee.commons.lang.StringUtil; import lucee.loader.engine.CFMLEngineFactory; import lucee.runtime.config.Config; import lucee.runtime.config.ConfigPro; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.text.xml.XMLUtil; public class EnvClassLoader extends URLClassLoader { private static float FROM_SYSTEM = 1; private static float FROM_BOOTDELEGATION = 2; private static float FROM_CALLER = 3; private static SoftReference<String> EMPTY = new SoftReference<String>(null); private static Map<SoftReference<String>, SoftReference<String>> notFound = new java.util.concurrent.ConcurrentHashMap<>(); private Config config; private Map<String, SoftReference<Object[]>> callerCache = new ConcurrentHashMap<String, SoftReference<Object[]>>(); private Log trace; private static final short CLASS = 1; private static final short URL = 2; private static final short STREAM = 3; private static ThreadLocal<Set<String>> checking = new ThreadLocal<Set<String>>() { @Override protected Set<String> initialValue() { return new HashSet<>(); } }; private static ThreadLocal<Boolean> inside = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; private static final EnvClassLoader NULL_INSTANCE = new EnvClassLoader(null); public static EnvClassLoader getInstance(ConfigPro config) { config = (ConfigPro) ThreadLocalPageContext.getConfig(config); if (config != null) return (EnvClassLoader) config.getClassLoaderEnv(); return NULL_INSTANCE; } public EnvClassLoader(ConfigPro config) { super(new URL[0], config != null ? config.getClassLoaderCore() : new lucee.commons.lang.ClassLoaderHelper().getClass().getClassLoader()); this.config = config; this.trace = log(Log.LEVEL_TRACE); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } @Override public URL getResource(String name) { if (trace == null) { return (java.net.URL) load(name, URL, true, null, true); } double start = SystemUtil.millis(); try { return (java.net.URL) load(name, URL, true, null, true); } finally { trace.trace("EnvClassLoader", "EnvClassLoader.getResource(" + name + "):" + (SystemUtil.millis() - start)); } } @Override public InputStream getResourceAsStream(String name) { if (trace == null) { return (InputStream) load(name, STREAM, true, null, true); } double start = SystemUtil.millis(); try { return (InputStream) load(name, STREAM, true, null, true); } finally { trace.trace("EnvClassLoader", "EnvClassLoader.getResourceAsStream(" + name + "):" + (SystemUtil.millis() - start)); } } @Override public Enumeration<URL> getResources(String name) throws IOException { if (trace == null) { List<URL> list = new ArrayList<URL>(); URL url = (URL) load(name, URL, false, null, true); if (url != null) list.add(url); return new E<URL>(list.iterator()); } double start = SystemUtil.millis(); try { List<URL> list = new ArrayList<URL>(); URL url = (URL) load(name, URL, false, null, true); if (url != null) list.add(url); return new E<URL>(list.iterator()); } finally { trace.trace("EnvClassLoader", "EnvClassLoader.getResources(" + name + "):" + (SystemUtil.millis() - start)); } } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (trace == null) { Class<?> c = findLoadedClass(name); if (c == null) c = (Class<?>) load(name, CLASS, true, null, true); if (c == null) c = findClass(name); if (resolve) resolveClass(c); return c; } double start = SystemUtil.millis(); try { Class<?> c = findLoadedClass(name); if (c == null) c = (Class<?>) load(name, CLASS, true, null, true); if (c == null) c = findClass(name); if (resolve) resolveClass(c); return c; } finally { trace.trace("EnvClassLoader", "EnvClassLoader.loadClass(" + name + "):" + (SystemUtil.millis() - start)); } } private synchronized Object load(String name, short type, boolean doLog, List<ClassLoader> listContext, boolean useCache) { double start = SystemUtil.millis(); StringBuilder id = new StringBuilder(name).append(';').append(type).append(';'); String _id = id.toString(); Set<String> cache = checking.get(); if (useCache && cache.contains(_id)) { callerCache.put(id.toString(), new SoftReference<Object[]>(new Object[] { null })); return null; } try { cache.add(_id); if (listContext == null) { listContext = SystemUtil.getClassLoaderContext(true, id); } // PATCH XML if ((name + "").startsWith("META-INF/services") && !inside.get()) { inside.set(Boolean.TRUE); try { if (name.equalsIgnoreCase("META-INF/services/javax.xml.parsers.DocumentBuilderFactory")) { if (patchNeeded(name, doLog, listContext)) { if (type == URL) return XMLUtil.getDocumentBuilderFactoryResource(); else if (type == STREAM) return new ByteArrayInputStream(XMLUtil.getDocumentBuilderFactoryName().getBytes()); } } else if (name.equalsIgnoreCase("META-INF/services/javax.xml.parsers.SAXParserFactory")) { if (patchNeeded(name, doLog, listContext)) { if (type == URL) return XMLUtil.getSAXParserFactoryResource(); else if (type == STREAM) return new ByteArrayInputStream(XMLUtil.getSAXParserFactoryName().getBytes()); } } else if (name.equalsIgnoreCase("META-INF/services/javax.xml.transform.TransformerFactory")) { if (patchNeeded(name, doLog, listContext)) { if (type == URL) return XMLUtil.getTransformerFactoryResource(); else if (type == STREAM) return new ByteArrayInputStream(XMLUtil.getTransformerFactoryName().getBytes()); } } else if (name.equalsIgnoreCase("META-INF/services/org.apache.xerces.xni.parser.XMLParserConfiguration")) { if (patchNeeded(name, doLog, listContext)) { if (type == STREAM) return new ByteArrayInputStream(XMLUtil.getXMLParserConfigurationName().getBytes()); } } } catch (IOException e) { } finally { inside.set(Boolean.FALSE); } } // PATCH for com.sun if ((name + "").startsWith("com.sun.")) { Object obj; ClassLoader loader = CFMLEngineFactory.class.getClassLoader(); obj = _load(loader, name, type); if (obj != null) { if (trace != null) trace.trace("EnvClassLoader", "found [" + name + "] in loader ClassLoader"); return obj; } } SoftReference<Object[]> sr = callerCache.get(id.toString()); if (sr != null && sr.get() != null) { // print.e(name + " - from cache " + callerCache.size()); return sr.get()[0]; } // callers classloader context Object obj; for (ClassLoader cl: listContext) { obj = _load(cl, name, type); if (obj != null) { if (cl instanceof BundleReference) { if (trace != null) trace.trace("EnvClassLoader", "found [" + name + "] in bundle [" + (((BundleReference) cl).getBundle().getSymbolicName()) + ":" + (((BundleReference) cl).getBundle().getVersion()) + "]"); } else { if (trace != null) trace.trace("EnvClassLoader", "found [" + name + "] in System ClassLoader " + cl); } if (useCache) callerCache.put(id.toString(), new SoftReference<Object[]>(new Object[] { obj })); return obj; } else { if (cl instanceof BundleReference) { if (trace != null) trace.trace("EnvClassLoader", "not found [" + name + "] in bundle [" + (((BundleReference) cl).getBundle().getSymbolicName()) + ":" + (((BundleReference) cl).getBundle().getVersion()) + "]"); } else { if (trace != null) trace.trace("EnvClassLoader", "not found [" + name + "] in System ClassLoader " + cl); } } } // print.ds("4:" + (SystemUtil.millis() - start) + ":" + name); if (trace != null) trace.trace("EnvClassLoader", "not found [" + name + "] "); if (useCache) callerCache.put(id.toString(), new SoftReference<Object[]>(new Object[] { null })); return null; } finally { cache.remove(_id); } } private boolean patchNeeded(String name, boolean doLog, List<ClassLoader> listContext) throws IOException { Object o = load(name, STREAM, doLog, listContext, false); boolean patchIt = true; if (o instanceof InputStream) { String className = IOUtil.toString((InputStream) o, (Charset) null); o = StringUtil.isEmpty(className) ? null : load(className.trim(), CLASS, doLog, listContext, false); if (o != null) patchIt = false; } return patchIt; } private Object _load(ClassLoader cl, String name, short type) { Object obj = null; Bundle b = null; if (cl != null) { try { if (type == CLASS) { if (cl instanceof BundleReference) { b = ((BundleReference) cl).getBundle(); if (notFound.containsKey( new SoftReference<String>(new StringBuilder(b.getSymbolicName()).append(':').append(b.getVersion()).append(':').append(name).toString()))) return null; else obj = cl.loadClass(name); } else obj = cl.loadClass(name); } else if (type == URL) obj = cl.getResource(name); else obj = cl.getResourceAsStream(name); } catch (ClassNotFoundException cnfe) { if (b != null) notFound.put(new SoftReference<String>(new StringBuilder(b.getSymbolicName()).append(':').append(b.getVersion()).append(':').append(name).toString()), EMPTY); } catch (Exception e) { } } return obj; } private String toType(short type) { if (CLASS == type) return "class"; if (STREAM == type) return "stream"; return "url"; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { throw new ClassNotFoundException("class " + name + " not found in the core, the loader and all the extension bundles"); } private static class E<T> implements Enumeration<T> { private Iterator<T> it; private E(Iterator<T> it) { this.it = it; } @Override public boolean hasMoreElements() { return it.hasNext(); } @Override public T nextElement() { return it.next(); } } // URLClassloader methods, need to be supressed // @Override public URL findResource(String name) { return getResource(name); } @Override public Enumeration<URL> findResources(String name) throws IOException { return getResources(name); } private Log log(int logLevel) { if (config == null) return null; Log log = config.getLog("application"); if (log == null || log.getLogLevel() > logLevel) return null; return log; } }
package org.jetbrains.idea.svn; import com.intellij.diagnostic.ThreadDumper; import com.intellij.execution.process.ProcessOutput; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TestDialog; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl; import com.intellij.openapi.vcs.rollback.RollbackProgressListener; import com.intellij.openapi.vcs.update.CommonUpdateProjectAction; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.ApplicationRule; import com.intellij.testFramework.RunAll; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.testFramework.fixtures.TempDirTestFixture; import com.intellij.testFramework.vcs.AbstractJunitVcsTestCase; import com.intellij.testFramework.vcs.MockChangeListManagerGate; import com.intellij.testFramework.vcs.MockChangelistBuilder; import com.intellij.testFramework.vcs.TestClientRunner; import com.intellij.util.Processor; import com.intellij.util.ThrowableRunnable; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.io.ZipUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.actions.CreateExternalAction; import org.jetbrains.idea.svn.api.Url; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.rules.ExternalResource; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.intellij.openapi.actionSystem.impl.SimpleDataContext.getProjectContext; import static com.intellij.openapi.application.PluginPathManager.getPluginHomePath; import static com.intellij.openapi.util.io.FileUtil.*; import static com.intellij.openapi.util.text.StringUtil.isEmptyOrSpaces; import static com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile; import static com.intellij.testFramework.EdtTestUtil.runInEdtAndWait; import static com.intellij.testFramework.UsefulTestCase.assertDoesntExist; import static com.intellij.testFramework.UsefulTestCase.assertExists; import static com.intellij.util.ObjectUtils.notNull; import static com.intellij.util.containers.ContainerUtil.map2Array; import static com.intellij.util.lang.CompoundRuntimeException.throwIfNotEmpty; import static java.util.Collections.singletonMap; import static org.jetbrains.idea.svn.SvnUtil.parseUrl; import static org.junit.Assert.*; public abstract class SvnTestCase extends AbstractJunitVcsTestCase { @ClassRule public static final ApplicationRule appRule = new ApplicationRule(); @ClassRule public static final ExternalResource ideaTempDirectoryRule = new ExternalResource() { @Override protected void before() throws Throwable { ensureExists(new File(PathManager.getTempPath())); } }; private static final String ORIGINAL_TEMP_DIRECTORY = getTempDirectory(); protected TempDirTestFixture myTempDirFixture; protected Url myRepositoryUrl; protected String myRepoUrl; protected TestClientRunner myRunner; protected String myWcRootName; private final String myTestDataDir; private File myRepoRoot; private File myWcRoot; private ChangeListManagerGate myGate; protected String myAnotherRepoUrl; protected File myPluginRoot; protected ProjectLevelVcsManagerImpl vcsManager; protected ChangeListManagerImpl changeListManager; protected VcsDirtyScopeManager dirtyScopeManager; protected SvnVcs vcs; protected SvnTestCase() { this("testData"); } protected SvnTestCase(@NotNull String testDataDir) { myTestDataDir = testDataDir; myWcRootName = "wcroot"; } @NotNull public static String getPluginHome() { return getPluginHomePath("svn4idea"); } @Before public void setUp() throws Exception { myTempDirFixture = IdeaTestFixtureFactory.getFixtureFactory().createTempDirTestFixture(); myTempDirFixture.setUp(); resetCanonicalTempPathCache(myTempDirFixture.getTempDirPath()); myPluginRoot = new File(getPluginHome()); myClientBinaryPath = getSvnClientDirectory(); myRunner = SystemInfo.isMac ? createClientRunner(singletonMap("DYLD_LIBRARY_PATH", myClientBinaryPath.getPath())) : createClientRunner(); myRepoRoot = virtualToIoFile(myTempDirFixture.findOrCreateDir("svnroot")); ZipUtil.extract(new File(myPluginRoot, getTestDataDir() + "/svn/newrepo.zip"), myRepoRoot, null); myWcRoot = virtualToIoFile(myTempDirFixture.findOrCreateDir(myWcRootName)); myRepoUrl = (SystemInfo.isWindows ? "file:///" : "file://") + toSystemIndependentName(myRepoRoot.getPath()); myRepositoryUrl = parseUrl(myRepoUrl); verify(runSvn("co", myRepoUrl, myWcRoot.getPath())); initProject(myWcRoot, this.getTestName()); activateVCS(SvnVcs.VCS_NAME); vcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject); changeListManager = ChangeListManagerImpl.getInstanceImpl(myProject); dirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); vcs = SvnVcs.getInstance(myProject); myGate = new MockChangeListManagerGate(changeListManager); ((StartupManagerImpl)StartupManager.getInstance(myProject)).runPostStartupActivitiesRegisteredDynamically(); refreshSvnMappingsSynchronously(); refreshChanges(); } @NotNull private File getSvnClientDirectory() { File svnBinDir = new File(myPluginRoot, getTestDataDir() + "/svn/bin"); String executablePath = SystemInfo.isWindows ? "windows/svn.exe" : SystemInfo.isLinux ? "linux/svn" : SystemInfo.isMac ? "mac/svn" : null; assertNotNull("No Subversion executable was found " + SystemInfo.OS_NAME, executablePath); File svnExecutable = new File(svnBinDir, executablePath); assertTrue(svnExecutable + " is not executable", svnExecutable.canExecute()); return svnExecutable.getParentFile(); } protected void refreshSvnMappingsSynchronously() { final Semaphore semaphore = new Semaphore(); semaphore.down(); ((SvnFileUrlMappingImpl) vcs.getSvnFileUrlMapping()).realRefresh(() -> semaphore.up()); if (ApplicationManager.getApplication().isDispatchThread()) { long start = System.currentTimeMillis(); while (true) { UIUtil.dispatchAllInvocationEvents(); if (semaphore.waitFor(50)) break; if (System.currentTimeMillis() - start > 60_000) { throw new AssertionError("Couldn't await SVN mapping refresh\n" + ThreadDumper.dumpThreadsToString()); } } } else { semaphore.waitFor(); } } protected void refreshChanges() { dirtyScopeManager.markEverythingDirty(); changeListManager.ensureUpToDate(); } protected void waitChangesAndAnnotations() { changeListManager.ensureUpToDate(); ((VcsAnnotationLocalChangesListenerImpl)vcsManager.getAnnotationLocalChangesListener()).calmDown(); } @NotNull protected Set<String> commit(@NotNull List<Change> changes, @NotNull String message) { Set<String> feedback = new HashSet<>(); throwIfNotEmpty(vcs.getCheckinEnvironment().commit(changes, message, new CommitContext(), feedback)); return feedback; } protected void rollback(@NotNull List<Change> changes) { List<VcsException> exceptions = new ArrayList<>(); vcs.createRollbackEnvironment().rollbackChanges(changes, exceptions, RollbackProgressListener.EMPTY); throwIfNotEmpty(exceptions); } @Override protected void projectCreated() { SvnApplicationSettings.getInstance().setCommandLinePath(myClientBinaryPath + File.separator + "svn"); } @After public void tearDown() throws Exception { new RunAll( this::waitChangeListManager, () -> runInEdtAndWait(this::tearDownProject), this::tearDownTempDirectoryFixture, () -> resetCanonicalTempPathCache(ORIGINAL_TEMP_DIRECTORY) ).run(); } private void waitChangeListManager() { if (changeListManager != null) { changeListManager.forceStopInTestMode(); changeListManager.waitEverythingDoneInTestMode(); } } private void tearDownTempDirectoryFixture() throws Exception { if (myTempDirFixture != null) { myTempDirFixture.tearDown(); myTempDirFixture = null; } } protected ProcessOutput runSvn(String... commandLine) throws IOException { return myRunner.runClient("svn", null, myWcRoot, commandLine); } protected void enableSilentOperation(final VcsConfiguration.StandardConfirmation op) { setStandardConfirmation(SvnVcs.VCS_NAME, op, VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY); } protected void disableSilentOperation(final VcsConfiguration.StandardConfirmation op) { setStandardConfirmation(SvnVcs.VCS_NAME, op, VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY); } protected void checkin() throws IOException { runInAndVerifyIgnoreOutput("ci", "-m", "test"); } protected void update() throws IOException { runInAndVerifyIgnoreOutput("up"); } protected List<Change> getChangesInScope(final VcsDirtyScope dirtyScope) throws VcsException { MockChangelistBuilder builder = new MockChangelistBuilder(); vcs.getChangeProvider().getChanges(dirtyScope, builder, new EmptyProgressIndicator(), myGate); return builder.getChanges(); } protected void undo() { runInEdtAndWait(() -> { final TestDialog oldTestDialog = Messages.setTestDialog(TestDialog.OK); try { UndoManager.getInstance(myProject).undo(null); } finally { Messages.setTestDialog(oldTestDialog); } }); } protected void prepareInnerCopy(final boolean anotherRepository) throws Exception { if (anotherRepository) { createAnotherRepo(); } final String mainUrl = myRepoUrl + "/root/source"; final String externalURL = (anotherRepository ? myAnotherRepoUrl : myRepoUrl) + "/root/target"; final SubTree subTree = new SubTree(myWorkingCopyDir); checkin(); withDisabledChangeListManager(() -> { final File rootFile = virtualToIoFile(subTree.myRootDir); delete(rootFile); delete(new File(myWorkingCopyDir.getPath() + File.separator + ".svn")); assertDoesntExist(rootFile); refreshVfs(); runInAndVerifyIgnoreOutput("co", mainUrl); final File sourceDir = new File(myWorkingCopyDir.getPath(), "source"); final File innerDir = new File(sourceDir, "inner1/inner2/inner"); runInAndVerifyIgnoreOutput("co", externalURL, innerDir.getPath()); refreshVfs(); }); } public String getTestDataDir() { return myTestDataDir; } protected class SubTree { public final VirtualFile myBase; public VirtualFile myRootDir; public VirtualFile mySourceDir; public VirtualFile myTargetDir; public VirtualFile myS1File; public VirtualFile myS2File; public final List<VirtualFile> myTargetFiles = new ArrayList<>(); public static final String ourS1Contents = "123"; public static final String ourS2Contents = "abc"; private VirtualFile findChild(final VirtualFile parent, final String name, final String content, boolean create) { final VirtualFile result = parent.findChild(name); if (result != null || !create) return result; return content == null ? createDirInCommand(parent, name) : createFileInCommand(parent, name, content); } public SubTree(@NotNull VirtualFile base) { myBase = base; refresh(true); } public void refresh(boolean create) { myRootDir = findChild(myBase, "root", null, create); mySourceDir = findChild(myRootDir, "source", null, create); myS1File = findChild(mySourceDir, "s1.txt", ourS1Contents, create); myS2File = findChild(mySourceDir, "s2.txt", ourS2Contents, create); myTargetDir = findChild(myRootDir, "target", null, create); myTargetFiles.clear(); for (int i = 0; i < 3; i++) { myTargetFiles.add(findChild(myTargetDir, "t" + (i + 10) + ".txt", ourS1Contents, create)); } } } public String prepareBranchesStructure() throws Exception { final String mainUrl = myRepoUrl + "/trunk"; runInAndVerifyIgnoreOutput("mkdir", "-m", "mkdir", mainUrl); runInAndVerifyIgnoreOutput("mkdir", "-m", "mkdir", myRepoUrl + "/branches"); runInAndVerifyIgnoreOutput("mkdir", "-m", "mkdir", myRepoUrl + "/tags"); String branchUrl = myRepoUrl + "/branches/b1"; withDisabledChangeListManager(() -> { assertTrue(delete(new File(myWorkingCopyDir.getPath() + File.separator + ".svn"))); refreshVfs(); runInAndVerifyIgnoreOutput("co", mainUrl, myWorkingCopyDir.getPath()); enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); new SubTree(myWorkingCopyDir); checkin(); runInAndVerifyIgnoreOutput("copy", "-q", "-m", "coppy", mainUrl, branchUrl); }); return branchUrl; } public void prepareExternal() throws Exception { prepareExternal(true, true, false); } public void prepareExternal(boolean commitExternalDefinition, boolean updateExternal, boolean anotherRepository) throws Exception { if (anotherRepository) { createAnotherRepo(); } final String mainUrl = myRepoUrl + "/root/source"; final String externalURL = (anotherRepository ? myAnotherRepoUrl : myRepoUrl) + "/root/target"; final SubTree subTree = new SubTree(myWorkingCopyDir); checkin(); withDisabledChangeListManager(() -> { final File rootFile = virtualToIoFile(subTree.myRootDir); delete(rootFile); delete(new File(myWorkingCopyDir.getPath() + File.separator + ".svn")); assertDoesntExist(rootFile); refreshVfs(); final File sourceDir = new File(myWorkingCopyDir.getPath(), "source"); runInAndVerifyIgnoreOutput("co", mainUrl, sourceDir.getPath()); CreateExternalAction.addToExternalProperty(vcs, sourceDir, "external", externalURL); if (updateExternal) { runInAndVerifyIgnoreOutput("up", sourceDir.getPath()); } if (commitExternalDefinition) { runInAndVerifyIgnoreOutput("ci", "-m", "test", sourceDir.getPath()); } refreshVfs(); setNewDirectoryMappings(sourceDir); if (updateExternal) { assertExists(new File(sourceDir, "external")); } }); } protected void withDisabledChangeListManager(@NotNull ThrowableRunnable<? extends Exception> action) throws Exception { changeListManager.waitUntilRefreshed(); changeListManager.forceStopInTestMode(); action.run(); changeListManager.forceGoInTestMode(); refreshSvnMappingsSynchronously(); } private void setNewDirectoryMappings(@NotNull File directory) { setVcsMappings(new VcsDirectoryMapping(toSystemIndependentName(directory.getPath()), vcs.getName())); } protected void createAnotherRepo() throws Exception { File repo = virtualToIoFile(myTempDirFixture.findOrCreateDir("anotherRepo")); copyDir(myRepoRoot, repo); myAnotherRepoUrl = (SystemInfo.isWindows ? "file:///" : "file://") + toSystemIndependentName(repo.getPath()); VirtualFile tmpWcVf = myTempDirFixture.findOrCreateDir("anotherRepoWc"); File tmpWc = virtualToIoFile(tmpWcVf); runInAndVerifyIgnoreOutput("co", myAnotherRepoUrl, tmpWc.getPath()); new SubTree(tmpWcVf); runInAndVerifyIgnoreOutput(tmpWc, "add", "root"); runInAndVerifyIgnoreOutput(tmpWc, "ci", "-m", "fff"); delete(tmpWc); } protected void imitUpdate() { vcsManager.getOptions(VcsConfiguration.StandardOption.UPDATE).setValue(false); final CommonUpdateProjectAction action = new CommonUpdateProjectAction(); action.getTemplatePresentation().setText("1"); action .actionPerformed(new AnActionEvent(null, getProjectContext(myProject), "test", new Presentation(), ActionManager.getInstance(), 0)); waitChangesAndAnnotations(); } protected void runAndVerifyStatusSorted(final String... stdoutLines) throws IOException { runStatusAcrossLocks(myWcRoot, true, map2Array(stdoutLines, String.class, it -> toSystemDependentName(it))); } protected void runAndVerifyStatus(final String... stdoutLines) throws IOException { runStatusAcrossLocks(myWcRoot, false, map2Array(stdoutLines, String.class, it -> toSystemDependentName(it))); } private void runStatusAcrossLocks(@Nullable File workingDir, final boolean sorted, final String... stdoutLines) throws IOException { final Processor<ProcessOutput> primitiveVerifier = output -> { if (sorted) { verifySorted(output, stdoutLines); } else { verify(output, stdoutLines); } return false; }; runAndVerifyAcrossLocks(workingDir, new String[]{"status"}, output -> { final List<String> lines = output.getStdoutLines(); for (String line : lines) { if (line.trim().startsWith("L")) { return true; // i.e. continue tries } } primitiveVerifier.process(output); return false; }, primitiveVerifier); } protected void runInAndVerifyIgnoreOutput(final String... inLines) throws IOException { final Processor<ProcessOutput> verifier = createPrimitiveExitCodeVerifier(); runAndVerifyAcrossLocks(myWcRoot, myRunner, inLines, verifier, verifier); } private static Processor<ProcessOutput> createPrimitiveExitCodeVerifier() { return output -> { assertEquals(output.getStderr(), 0, output.getExitCode()); return false; }; } public static void runInAndVerifyIgnoreOutput(File workingDir, final TestClientRunner runner, final String[] input) throws IOException { final Processor<ProcessOutput> verifier = createPrimitiveExitCodeVerifier(); runAndVerifyAcrossLocks(workingDir, runner, input, verifier, verifier); } protected void runInAndVerifyIgnoreOutput(final File root, final String... inLines) throws IOException { final Processor<ProcessOutput> verifier = createPrimitiveExitCodeVerifier(); runAndVerifyAcrossLocks(root, myRunner, inLines, verifier, verifier); } private void runAndVerifyAcrossLocks(@Nullable File workingDir, final String[] input, final Processor<ProcessOutput> verifier, final Processor<ProcessOutput> primitiveVerifier) throws IOException { workingDir = notNull(workingDir, myWcRoot); runAndVerifyAcrossLocks(workingDir, myRunner, input, verifier, primitiveVerifier); } public static void runAndVerifyAcrossLocks(File workingDir, final TestClientRunner runner, final String[] input, final Processor<ProcessOutput> verifier, final Processor<ProcessOutput> primitiveVerifier) throws IOException { for (int i = 0; i < 5; i++) { final ProcessOutput output = runner.runClient("svn", null, workingDir, input); if (output.getExitCode() != 0 && !isEmptyOrSpaces(output.getStderr())) { final String stderr = output.getStderr(); if (stderr.contains("E155004") && stderr.contains("is already locked")) continue; } if (verifier.process(output)) continue; return; } primitiveVerifier.process(runner.runClient("svn", null, workingDir, input)); } }
package org.jpmml.evaluator; import java.util.*; import org.jpmml.manager.*; import org.dmg.pmml.*; public class ParameterUtil { private ParameterUtil(){ } static public Object getValue(Map<FieldName, ?> parameters, FieldName name){ return getValue(parameters, name, false); } static public Object getValue(Map<FieldName, ?> parameters, FieldName name, boolean nullable){ Object value = parameters.get(name); if(value == null && !nullable){ throw new EvaluationException("Missing parameter " + name.getValue()); } return value; } static public Object parse(DictionaryField field, String string){ DataType dataType = field.getDataType(); switch(dataType){ case STRING: return string; case INTEGER: return new Integer(string); case FLOAT: return new Float(string); case DOUBLE: return new Double(string); default: throw new UnsupportedFeatureException(dataType); } } }
package org.realityforge.arez; import java.util.concurrent.Callable; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.TestOnly; /** * The ArezContext defines the top level container of interconnected observables and observers. * The context also provides the mechanism for creating transactions to read and write state * within the system. */ public final class ArezContext { /** * All changes in a context must occur within the scope of a transaction. * This references the current transaction. */ @Nullable private Transaction _transaction; /** * Id of next node to be created. * * This needs to start at 1 as {@link Observable#NOT_IN_CURRENT_TRACKING} is used * to optimize dependency tracking in transactions. */ private int _nextNodeId = 1; /** * Reaction Scheduler. * Currently hard-coded, in the future potentially configurable. */ private final ReactionScheduler _scheduler = new ReactionScheduler( this ); /** * Support infrastructure for propagating observer errors. */ @Nonnull private final ObserverErrorHandlerSupport _observerErrorHandlerSupport = new ObserverErrorHandlerSupport(); /** * Pass the supplied observer to the scheduler. * The observer should NOT be already pending execution. * * @param observer the reaction to schedule. */ void scheduleReaction( @Nonnull final Observer observer ) { _scheduler.scheduleReaction( observer ); } /** * Create a new transaction. * * @param name the name of the transaction. Should be non-null if {@link ArezConfig#enableNames()} is true, false otherwise. * @param mode the transaciton mode. * @param tracker the observer that is tracking transaction if any. * @return the new transaction. */ private Transaction beginTransaction( @Nullable final String name, @Nonnull final TransactionMode mode, @Nullable final Observer tracker ) { _transaction = new Transaction( this, _transaction, name, mode, tracker ); _transaction.begin(); return _transaction; } /** * Commit the supplied transaction. * * This method verifies that the transaction active is the supplied transaction before committing * the transaction and restoring the prior transaction if any. * * @param transaction the transaction. */ private void commitTransaction( @Nonnull final Transaction transaction ) { Guards.invariant( () -> null != _transaction, () -> String.format( "Attempting to commit transaction named '%s' but no transaction is active.", transaction.getName() ) ); assert null != _transaction; Guards.invariant( () -> _transaction == transaction, () -> String.format( "Attempting to commit transaction named '%s' but this does not match existing transaction named '%s'.", transaction.getName(), _transaction.getName() ) ); _transaction.commit(); _transaction = _transaction.getPrevious(); if ( null == _transaction ) { _scheduler.runPendingObservers(); } } /** * Execute the supplied action in a transaction. * The transaction is tracking if tracker is supplied and is named with specified name. * * @param <T> the type of return value. * @param name the name of the transaction. Should be non-null if {@link ArezConfig#enableNames()} is true, false otherwise. * @param mode the transaciton mode. * @param tracker the observer that is tracking transaction if any. * @param action the action to execute. * @return the value returned from the action. * @throws Exception if the action throws an an exception. */ public <T> T transaction( @Nullable final String name, @Nonnull final TransactionMode mode, @Nullable final Observer tracker, @Nonnull final Callable<T> action ) throws Exception { final Transaction transaction = beginTransaction( name, mode, tracker ); try { return action.call(); } finally { commitTransaction( transaction ); } } /** * Execute the supplied action in a transaction. * The transaction is tracking if tracker is supplied and is named with specified name. * * @param name the name of the transaction. Should be non-null if {@link ArezConfig#enableNames()} is true, false otherwise. * @param mode the transaciton mode. * @param tracker the observer that is tracking transaction if any. * @param action the action to execute. * @throws Exception if the action throws an an exception. */ public void transaction( @Nullable final String name, @Nonnull final TransactionMode mode, @Nullable final Observer tracker, @Nonnull final Action action ) throws Exception { final Transaction transaction = beginTransaction( name, mode, tracker ); try { action.call(); } finally { commitTransaction( transaction ); } } /** * Return true if there is a transaction in progress. * * @return true if there is a transaction in progress. */ public boolean isTransactionActive() { return null != _transaction; } /** * Return the current transaction. * This method should not be invoked unless a transaction active and will throw an * exception if invariant checks are enabled. * * @return the current transaction. */ @Nonnull Transaction getTransaction() { Guards.invariant( this::isTransactionActive, () -> "Attempting to get current transaction but no transaction is active." ); assert null != _transaction; return _transaction; } /** * Return next node id and increment internal counter. * The id is a monotonically increasing number starting at 1. * * @return the next node id. */ int nextNodeId() { return _nextNodeId++; } /** * Add error handler to the list of error handlers called. * The handler should not already be in the list. * * @param handler the error handler. */ public void addObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { getObserverErrorHandlerSupport().addObserverErrorHandler( handler ); } /** * Remove error handler from list of existing error handlers. * The handler should already be in the list. * * @param handler the error handler. */ public void removeObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { getObserverErrorHandlerSupport().removeObserverErrorHandler( handler ); } @Nonnull ObserverErrorHandler getObserverErrorHandler() { return _observerErrorHandlerSupport; } @Nonnull ObserverErrorHandlerSupport getObserverErrorHandlerSupport() { return _observerErrorHandlerSupport; } @TestOnly int currentNextNodeId() { return _nextNodeId; } @TestOnly @Nonnull ReactionScheduler getScheduler() { return _scheduler; } @TestOnly void setTransaction( @Nullable final Transaction transaction ) { _transaction = transaction; } }
package org.realityforge.arez; import java.util.ArrayList; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.TestOnly; final class Transaction extends Node { /** * Determines which write operations are permitted within the scope of the transaction if any. */ @Nonnull private final TransactionMode _mode; /** * A list of observables that have reached zero observers within the scope of the root transaction. * When the root transaction completes, these observers are deactivated if they still have no observers. * It should be noted that this list is owned by the root transaction and a reference is copied to all * non-root transactions that attempt to deactivate an observable. */ @Nullable private ArrayList<Observable> _pendingDeactivations; /** * Reference to the transaction that was active when this transaction began. When this * transaction commits, the previous transaction will be restored. */ @Nullable private final Transaction _previous; /** * The tracking observer if the transaction is trackable. */ @Nullable private final Observer _tracker; /** * the list of observables that have been observed during tracking. * This list may contain duplicates but the duplicates will be eliminated when converting the list * of observables to dependencies to pass to the tracking observer. * * This should be null unless the _tracker is non null. */ @Nullable private ArrayList<Observable> _observables; Transaction( @Nonnull final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, @Nonnull final TransactionMode mode, @Nullable final Observer tracker ) { super( context, name ); _previous = previous; _mode = Objects.requireNonNull( mode ); _tracker = tracker; Guards.invariant( () -> TransactionMode.READ_WRITE_OWNED != mode || null != tracker, () -> String.format( "Attempted to create transaction named '%s' with mode READ_WRITE_OWNED but no tracker specified.", getName() ) ); } @Nonnull TransactionMode getMode() { return _mode; } void begin() { beginTracking(); } void beginTracking() { if ( null != _tracker ) { _tracker.invariantDependenciesBackLink( "Pre beginTracking" ); // Mark the tracker as up to date at the start of the transaction. // If it is made stale during the transaction then completeTracking() will fix the // state of the _tracker. _tracker.setState( ObserverState.UP_TO_DATE ); // Ensure dependencies "LeastStaleObserverState" state is kept up to date. _tracker.markDependenciesLeastStaleObserverAsUpToDate(); } } @Nullable Transaction getPrevious() { return _previous; } void commit() { completeTracking(); if ( isRootTransaction() ) { // Only the root transactions performs deactivations. processPendingDeactivations(); } } int processPendingDeactivations() { Guards.invariant( this::isRootTransaction, () -> String.format( "Invoked processPendingDeactivations on transaction named '%s' which is not the root transaction.", getName() ) ); int count = 0; if ( null != _pendingDeactivations ) { // WARNING: Deactivationss can be enqueued during the deactivation process // so we always need to call _pendingDeactivations.size() through each iteration // of the loop to ensure that new pending deactivations are deactivated. //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < _pendingDeactivations.size(); i++ ) { final Observable observable = _pendingDeactivations.get( i ); observable.resetPendingDeactivation(); if ( !observable.hasObservers() ) { observable.deactivate(); count++; } } } return count; } void queueForDeactivation( @Nonnull final Observable observable ) { Guards.invariant( observable::canDeactivate, () -> String.format( "Invoked queueForDeactivation on transaction named '%s' for observable named '%s' when observable can not be deactivated.", getName(), observable.getName() ) ); if ( null == _pendingDeactivations ) { final Transaction rootTransaction = getRootTransaction(); if ( null == rootTransaction._pendingDeactivations ) { rootTransaction._pendingDeactivations = new ArrayList<>(); } _pendingDeactivations = rootTransaction._pendingDeactivations; } else { Guards.invariant( () -> !_pendingDeactivations.contains( observable ), () -> String.format( "Invoked queueForDeactivation on transaction named '%s' for observable named '%s' when pending deactivation already exists for observable.", getName(), observable.getName() ) ); } _pendingDeactivations.add( Objects.requireNonNull( observable ) ); } void observe( @Nonnull final Observable observable ) { if ( null != _tracker ) { /* * This invariant is in place as owned observables are generated by the tracker and thus should not be * observed during own generation process. */ Guards.invariant( () -> _tracker != observable.getOwner(), () -> String.format( "Invoked observe on transaction named '%s' for observable named '%s' where the observable is owned by the tracker.", getName(), observable.getName() ) ); observable.invariantOwner(); /* * This optimization attempts to stop the same observable being added multiple * times to the observables list by caching the transaction id on the observable. * This is optimization may be defeated if the same observable is observed in a * nested tracking transaction in which case the same observable may appear multiple. * times in the _observables list. However completeTracking will eliminate duplicates. */ final int id = getId(); if ( observable.getLastTrackerTransactionId() != id ) { observable.setLastTrackerTransactionId( id ); safeGetObservables().add( observable ); } } } /** * Called to report that this observable has changed. * This is called when the observable has definitely changed and should * not be called for derived values that may have changed. */ void reportChanged( @Nonnull final Observable observable ) { verifyWriteAllowed( observable ); observable.invariantLeastStaleObserverState(); if ( observable.hasObservers() && ObserverState.STALE != observable.getLeastStaleObserverState() ) { observable.setLeastStaleObserverState( ObserverState.STALE ); final ArrayList<Observer> observers = observable.getObservers(); for ( final Observer observer : observers ) { final ObserverState state = observer.getState(); if ( ObserverState.UP_TO_DATE == state ) { observer.setState( ObserverState.STALE ); } else { Guards.invariant( () -> ObserverState.POSSIBLY_STALE != state, () -> String.format( "Transaction named '%s' has attempted to explicitly change observable " + "named '%s' but observable is in state POSSIBLY_STALE indicating it is " + "derived and thus can not be explicitly changed.", getName(), observable.getName() ) ); Guards.invariant( () -> ObserverState.STALE == state, () -> String.format( "Transaction named '%s' has attempted to explicitly change observable " + "named '%s' and observable is in unexpected state %s.", getName(), observable.getName(), state.name() ) ); } } } observable.invariantLeastStaleObserverState(); } /** * Invoked with a derived observable when a dependency of the observable has * changed. The observable may or may not have changed but the framework will * recalculate the value during normal reaction cycle or when accessed within * transaction scope and will update the state of the observable at that time. */ void reportPossiblyChanged( @Nonnull final Observable observable ) { Guards.invariant( () -> null != observable.getOwner(), () -> String.format( "Transaction named '%s' has attempted to mark observable " + "named '%s' as potentially changed but observable is not a derived value.", getName(), observable.getName() ) ); verifyWriteAllowed( observable ); observable.invariantLeastStaleObserverState(); if ( observable.hasObservers() && ObserverState.UP_TO_DATE == observable.getLeastStaleObserverState() ) { observable.setLeastStaleObserverState( ObserverState.POSSIBLY_STALE ); for ( final Observer observer : observable.getObservers() ) { final ObserverState state = observer.getState(); if ( ObserverState.UP_TO_DATE == state ) { observer.setState( ObserverState.POSSIBLY_STALE ); } else { assert ObserverState.STALE == state || ObserverState.POSSIBLY_STALE == state; } } } observable.invariantLeastStaleObserverState(); } /** * Invoked with a derived observable when the derived observable is actually * changed. This is determined after the value is recalculated and converts * a UPTODATE or POSSIBLY_STALE state to STALE. */ void reportChangeConfirmed( @Nonnull final Observable observable ) { Guards.invariant( () -> null != observable.getOwner(), () -> String.format( "Transaction named '%s' has attempted to mark observable " + "named '%s' as potentially changed but observable is not a derived value.", getName(), observable.getName() ) ); verifyWriteAllowed( observable ); observable.invariantLeastStaleObserverState(); if ( observable.hasObservers() && ObserverState.STALE != observable.getLeastStaleObserverState() ) { observable.setLeastStaleObserverState( ObserverState.STALE ); for ( final Observer observer : observable.getObservers() ) { if ( ObserverState.POSSIBLY_STALE == observer.getState() ) { observer.setState( ObserverState.STALE ); } else if ( ObserverState.UP_TO_DATE == observer.getState() ) { /* * This happens when the observer is reacting to the change and this * has a ComputedValue dependency has recalculated as part of the reaction. * So make sure we keep _leastStaleObserverState up to date. */ invariantObserverIsTracker( observable, observer ); observable.setLeastStaleObserverState( ObserverState.UP_TO_DATE ); } } } observable.invariantLeastStaleObserverState(); } /** * Verifies that the specified observer is a tracker for the current * transaction or one of the parent transactions. * * @param observable the observable which the observer is observing. Used when constructing invariant message. * @param observer the observer. */ void invariantObserverIsTracker( @Nonnull final Observable observable, @Nonnull final Observer observer ) { // The ArezConfig.checkInvariants() is not needed as the optimizing compilers will eventually // eliminate this as dead code but this top level check short-cuts this and ensures that GWT compiler // eliminates it in first pass. if ( ArezConfig.checkInvariants() ) { boolean found = false; Transaction t = this; final ArrayList<String> names = new ArrayList<>(); while ( null != t ) { if ( t.getTracker() == observer ) { found = true; break; } names.add( ArezConfig.enableNames() ? t.getName() : String.valueOf( t.getId() ) ); t = t.getPrevious(); } final boolean check = found; Guards.invariant( () -> check, () -> String.format( "Transaction named '%s' attempted to call reportChangeConfirmed for observable " + "named '%s' and found a dependency named '%s' that is UP_TO_DATE but is not the " + "tracker of any transactions in the hierarchy: %s.", getName(), observable.getName(), observer.getName(), String.valueOf( names ) ) ); } } void verifyWriteAllowed( @Nonnull final Observable observable ) { if ( ArezConfig.enforceTransactionType() ) { if ( TransactionMode.READ_ONLY == _mode ) { Guards.fail( () -> String.format( "Transaction named '%s' attempted to change observable named '%s' but transaction is READ_ONLY.", getName(), observable.getName() ) ); } else if ( TransactionMode.READ_WRITE_OWNED == _mode ) { Guards.invariant( () -> !observable.hasObservers() || observable.getOwner() == _tracker, () -> String.format( "Transaction named '%s' attempted to change observable named '%s' and transaction is " + "READ_WRITE_OWNED but the observable has not been created by the transaction.", getName(), observable.getName() ) ); } } } /** * Completes the tracking by updating the dependencies on the observer to match the * observables that were observed during tracking. The _tracker is added or removed * as an observer on an observable if the observer is a new dependency or previously * was a dependency but no longer is, respectively. */ void completeTracking() { if ( null == _tracker ) { Guards.invariant( () -> null == _observables, () -> String.format( "Transaction named '%s' has no associated tracker so _observables should be null but are not.", getName() ) ); return; } _tracker.invariantDependenciesUnique( "Pre completeTracking" ); Guards.invariant( () -> _tracker.getState() != ObserverState.INACTIVE, () -> String.format( "Transaction named '%s' called completeTracking but _tracker state of INACTIVE is unexpected.", getName() ) ); ObserverState newDerivationState = ObserverState.UP_TO_DATE; boolean dependenciesChanged = false; int currentIndex = 0; if ( null != _observables ) { /* * Iterate through the list of observables, flagging observables and "removing" duplicates. */ final int size = _observables.size(); for ( int i = 0; i < size; i++ ) { final Observable observable = _observables.get( i ); if ( !observable.isInCurrentTracking() ) { observable.putInCurrentTracking(); if ( i != currentIndex ) { _observables.set( currentIndex, observable ); } currentIndex++; final Observer owner = observable.getOwner(); if ( null != owner ) { final ObserverState dependenciesState = owner.getState(); if ( dependenciesState.ordinal() > newDerivationState.ordinal() ) { newDerivationState = dependenciesState; } } } } } // Look through the old dependencies and any that are no longer tracked // should no longer be observed. final ArrayList<Observable> dependencies = _tracker.getDependencies(); for ( int i = dependencies.size() - 1; i >= 0; i { final Observable observable = dependencies.get( i ); if ( !observable.isInCurrentTracking() ) { // Old dependency was not part of current tracking and needs to be unobserved observable.removeObserver( _tracker ); dependenciesChanged = true; } else { observable.removeFromCurrentTracking(); } } if ( null != _observables ) { // Look through the new observables and any that are still flagged must be // new dependencies and need to be observed by the observer for ( int i = currentIndex - 1; i >= 0; i { final Observable observable = _observables.get( i ); if ( observable.isInCurrentTracking() ) { observable.removeFromCurrentTracking(); //Observable was not a dependency so it needs to be observed observable.addObserver( _tracker ); dependenciesChanged = true; final ObserverState leastStaleObserverState = observable.getLeastStaleObserverState(); if ( leastStaleObserverState == ObserverState.INACTIVE || leastStaleObserverState.ordinal() > newDerivationState.ordinal() ) { observable.setLeastStaleObserverState( newDerivationState ); } } } } // Some newly observed derivation owned observables may have become stale during // tracking operation but they have had no chance to propagate staleness to this // observer so rectify this. if ( ObserverState.UP_TO_DATE != newDerivationState ) { _tracker.setState( newDerivationState ); } // Ugly hack to remove the elements from the end of the list that are no longer // required. We start from end of list and work back to avoid array copies. // We should replace _observables with a structure that works under both JS and Java // that avoids this by just allowing us to change current size if ( null != _observables ) { for ( int i = _observables.size() - 1; i >= currentIndex; i { _observables.remove( i ); } if ( dependenciesChanged ) { _tracker.replaceDependencies( _observables ); } } else { if ( dependenciesChanged ) { _tracker.replaceDependencies( new ArrayList<>() ); } } /* * Check invariants. In both java and non-java code this will be compiled out. */ if ( ArezConfig.checkInvariants() ) { if ( null != _observables ) { for ( final Observable observable : _observables ) { observable.invariantLeastStaleObserverState(); observable.invariantObserversLinked(); } } _tracker.invariantDependenciesUnique( "Post completeTracking" ); _tracker.invariantDependenciesBackLink( "Post completeTracking" ); } } boolean isRootTransaction() { return null == _previous; } @Nonnull Transaction getRootTransaction() { if ( isRootTransaction() ) { return this; } else { assert null != _previous; return _previous.getRootTransaction(); } } /** * Return the observables, initializing the array if necessary. */ @Nonnull ArrayList<Observable> safeGetObservables() { if ( null == _observables ) { _observables = new ArrayList<>(); } return _observables; } @TestOnly @Nullable Observer getTracker() { return _tracker; } @TestOnly @Nullable ArrayList<Observable> getPendingDeactivations() { return _pendingDeactivations; } @TestOnly @Nullable ArrayList<Observable> getObservables() { return _observables; } }
package org.sql2o.reflection; import org.sql2o.Sql2oException; import org.sql2o.tools.AbstractCache; import org.sql2o.tools.FeatureDetector; import org.sql2o.tools.UnderscoreToCamelCase; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Stores metadata for a POJO. */ public class PojoMetadata { private static final Cache caseSensitiveFalse = new Cache(); private static final Cache caseSensitiveTrue = new Cache(); private final PropertyAndFieldInfo propertyInfo; private final Map<String, String> columnMappings; private final FactoryFacade factoryFacade = FactoryFacade.getInstance(); public boolean isCaseSensitive() { return caseSensitive; } public boolean isAutoDeriveColumnNames() { return autoDeriveColumnNames; } private boolean caseSensitive; private boolean autoDeriveColumnNames; private Class clazz; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PojoMetadata that = (PojoMetadata) o; return autoDeriveColumnNames == that.autoDeriveColumnNames && caseSensitive == that.caseSensitive && clazz.equals(that.clazz) && columnMappings.equals(that.columnMappings) && propertyInfo.equals(that.propertyInfo); } @Override public int hashCode() { int result = (caseSensitive ? 1 : 0); result = 31 * result + clazz.hashCode(); return result; } public PojoMetadata(Class clazz, boolean caseSensitive, boolean autoDeriveColumnNames, Map<String, String> columnMappings) { this.caseSensitive = caseSensitive; this.autoDeriveColumnNames = autoDeriveColumnNames; this.clazz = clazz; this.columnMappings = columnMappings == null ? Collections.<String,String>emptyMap() : columnMappings; this.propertyInfo = getPropertyInfoThroughCache(); } public ObjectConstructor getObjectConstructor() { return propertyInfo.objectConstructor; } private PropertyAndFieldInfo getPropertyInfoThroughCache() { return (caseSensitive ? caseSensitiveTrue : caseSensitiveFalse) .get(clazz, this); } private PropertyAndFieldInfo initializePropertyInfo() { HashMap<String, Setter> propertySetters = new HashMap<String, Setter>(); HashMap<String, Field> fields = new HashMap<String, Field>(); Class theClass = clazz; ObjectConstructor objectConstructor = factoryFacade.newConstructor(theClass); do { for (Field f : theClass.getDeclaredFields()) { String propertyName = f.getName(); propertyName = caseSensitive ? propertyName : propertyName.toLowerCase(); propertySetters.put(propertyName, factoryFacade.newSetter(f)); fields.put(propertyName, f); } // prepare methods. Methods will override fields, if both exists. for (Method m : theClass.getDeclaredMethods()) { if (m.getParameterTypes().length!=1) continue; if (m.getName().startsWith("set")) { String propertyName = m.getName().substring(3); if (caseSensitive) { propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); } else { propertyName = propertyName.toLowerCase(); } propertySetters.put(propertyName, factoryFacade.newSetter(m)); } } theClass = theClass.getSuperclass(); } while (!theClass.equals(Object.class)); return new PropertyAndFieldInfo(propertySetters, fields, objectConstructor); } public Map<String, String> getColumnMappings() { return columnMappings; } public Setter getPropertySetter(String propertyName) { Setter setter = getPropertySetterIfExists(propertyName); if (setter != null) { return setter; } else { String errorMsg = "Property with name '" + propertyName + "' not found on class " + this.clazz.toString(); if (this.caseSensitive) { errorMsg += " (You have turned on case sensitive property search. Is this intentional?)"; } throw new Sql2oException(errorMsg); } } public Setter getPropertySetterIfExists(String propertyName) { String name = this.caseSensitive ? propertyName : propertyName.toLowerCase(); if (this.columnMappings.containsKey(name)) { name = this.columnMappings.get(name); } if (autoDeriveColumnNames) { name = UnderscoreToCamelCase.convert(name); if (!this.caseSensitive) name = name.toLowerCase(); } return propertyInfo.propertySetters.get(name); } public Class getType() { return this.clazz; } public Object getValueOfProperty(String propertyName, Object object) { String name = this.caseSensitive ? propertyName : propertyName.toLowerCase(); Field field = this.propertyInfo.fields.get(name); try { return field.get(object); } catch (IllegalAccessException e) { throw new Sql2oException("could not read value of field " + field.getName() + " on class " + object.getClass().toString(), e); } } private static class Cache extends AbstractCache<Class, PropertyAndFieldInfo, PojoMetadata> { @Override protected PropertyAndFieldInfo evaluate(Class key, PojoMetadata param) { return param.initializePropertyInfo(); } } private static class PropertyAndFieldInfo { // since this class is private we can just use field access // to make HotSpot a little less work for inlining public final Map<String, Setter> propertySetters; public final Map<String, Field> fields; public final ObjectConstructor objectConstructor; private PropertyAndFieldInfo(Map<String, Setter> propertySetters, Map<String, Field> fields, ObjectConstructor objectConstructor) { this.propertySetters = propertySetters; this.fields = fields; this.objectConstructor = objectConstructor; } } }
package org.xins.client; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.net.URL; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.http.HTTPRequester; /** * Accessor for a remote XINS API. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @deprecated * Deprecated since XINS 0.41. Use {@link ActualFunctionCaller} instead. */ public class RemoteAPI extends ActualFunctionCaller { // Class fields // Class functions // Constructors public RemoteAPI(URL url) throws IllegalArgumentException, SecurityException, UnknownHostException, MultipleIPAddressesException { super(url); } // Fields // Methods }
package com.jmex.bui.headlessWindows; import com.jmex.bui.BContainer; import com.jmex.bui.BStatusBar; import com.jmex.bui.BStyleSheet; import com.jmex.bui.BTitleBar; import com.jmex.bui.event.ComponentListener; import com.jmex.bui.event.MouseEvent; import com.jmex.bui.layout.BorderLayout; import com.jmex.bui.layout.GroupLayout; import com.jmex.bui.listener.CollapsesTitledWindow; import com.jmex.bui.util.Dimension; import com.jmex.bui.util.Rectangle; /** * @author timo * @since 27Apr07 */ public class BTitledWindow extends BDraggableWindow { public static final String WINDOW_MINIMIZE_ACTION = "minimize window"; public static final String WINDOW_MAXIMIZE_ACTION = "maximize window"; public static final String WINDOW_CLOSE_ACTION = "close window"; /** * The current state of the window. * * @author Lucian Cristian Beskid */ public enum WindowState { NORMAL, MAXIMIZED, MINIMIZED } private WindowState windowState = WindowState.NORMAL; protected WindowState previousState = WindowState.NORMAL; private String maximizedStyle = "window"; private String minimizedStyle = "window"; // the window's size before maximizing protected Rectangle originalBounds = new Rectangle(0, 0, 0, 0); protected Rectangle maximizedBounds = new Rectangle(0, 0, 0, 0); protected Dimension maximizedSize = new Dimension(-1, -1); protected Dimension minimizedSize = new Dimension(-1, -1); protected BTitleBar titleBar; protected BStatusBar statusBar; private BContainer componentArea; public BTitledWindow(final String name, final BTitleBar titleBar, final BStatusBar statusBar, final BStyleSheet style) { super(name, style, new BorderLayout()); this.titleBar = titleBar; this.statusBar = statusBar; init(); } @Override public void addListener(final ComponentListener listener) { if (listener instanceof CollapsesTitledWindow) { titleBar.removeAllListeners(); titleBar.addListener(listener); } super.addListener(listener); } private void init() { // setLayoutManager(new BorderLayout()); if (titleBar != null) { add(titleBar, BorderLayout.NORTH); } else { throw new RuntimeException("The title bar cannot be null."); } if (statusBar != null) { add(statusBar, BorderLayout.SOUTH); } componentArea = new BContainer(GroupLayout.makeVStretch()); add(componentArea, BorderLayout.CENTER); } public Dimension getMinimizedSize() { return minimizedSize; } public void setMinimizedSize(final Dimension _minimizedSize) { minimizedSize = _minimizedSize; } public void setMinimizedSize(final int width, final int height) { minimizedSize.width = width; minimizedSize.height = height; } public void setMaximizedSize(final int width, final int height) { maximizedSize.width = width; maximizedSize.height = height; } public Dimension getMaximizedSize() { return maximizedSize; } /** * The component area of a window is the part of the window underneath the title bar. * It is analogue to the Swing window's content pane. * * @return The container representing the window's component area. */ public BContainer getComponentArea() { return componentArea; } public void setComponentArea(final BContainer componentArea) { remove(this.componentArea); this.componentArea.removeAll(); this.componentArea = componentArea; invalidate(); } public WindowState getWindowState() { return windowState; } public void setWindowState(final WindowState _windowState) { windowState = _windowState; } public void maximize(final Dimension size) { if (windowState != WindowState.MAXIMIZED) { if (size != null) { // save the current state if (windowState != WindowState.MINIMIZED) { originalBounds = getBounds(); } // if there are defaults, take them into account if (maximizedSize.width > 0 && maximizedSize.height > 0) { setSize(Math.min(maximizedSize.width, size.width), Math .min(maximizedSize.height, size.height)); } // else just use the provided size else { setSize(size.width, size.height); } previousState = windowState; windowState = WindowState.MAXIMIZED; componentArea.setVisible(true); center(); maximizedBounds.x = _x; maximizedBounds.y = _y; maximizedBounds.width = _width; maximizedBounds.height = _height; } // attempt to use our own settings if any else if (maximizedSize.width > 0 && maximizedSize.height > 0) { setSize(maximizedSize.width, maximizedSize.height); if (windowState != WindowState.MINIMIZED) { originalBounds = getBounds(); } previousState = windowState; windowState = WindowState.MAXIMIZED; componentArea.setVisible(true); center(); maximizedBounds.x = _x; maximizedBounds.y = _y; maximizedBounds.width = _width; maximizedBounds.height = _height; } } } public void minimize() { if (windowState != WindowState.MINIMIZED) { // save the bounds if necessary if (windowState == WindowState.NORMAL) { originalBounds = getBounds(); } else if (windowState == WindowState.MAXIMIZED) { maximizedBounds = getBounds(); } // adjust the new y position setLocation(_x, _y + _height - titleBar.getHeight()); componentArea.setVisible(false); setSize(getWidth(), titleBar.getHeight()); previousState = windowState; windowState = WindowState.MINIMIZED; } } /** * Restores the size of the BTitledWindow if it is maximized or minimized. */ public void restoreSize() { // restore from maximized to normal if (windowState == WindowState.MAXIMIZED) { setSize(originalBounds.width, originalBounds.height); setLocation(originalBounds.x, originalBounds.y); componentArea.setVisible(true); previousState = windowState; windowState = WindowState.NORMAL; } // restore from minimized to previous else if (windowState == WindowState.MINIMIZED) { if (previousState == WindowState.NORMAL) { setSize(originalBounds.width, originalBounds.height); setLocation(originalBounds.x, originalBounds.y); previousState = windowState; windowState = WindowState.NORMAL; componentArea.setVisible(true); } else if (previousState == WindowState.MAXIMIZED) { setSize(maximizedBounds.width, maximizedBounds.height); setLocation(maximizedBounds.x, maximizedBounds.y); previousState = windowState; windowState = WindowState.MAXIMIZED; componentArea.setVisible(true); } } } @Override protected void windowReleased(final MouseEvent event) { // we'll need to update the saved bounds if the window // was dragged in a minimized state if (windowState == WindowState.MINIMIZED) { originalBounds.x = _x - originalBounds.width + titleBar.getWidth(); originalBounds.y = _y - originalBounds.height + titleBar.getHeight(); } } public String getMaximizedStyleClass() { return maximizedStyle; } public void setMaximizedStyleClass(final String maximizedStyleClass) { this.maximizedStyle = maximizedStyleClass; } public String getMinimizedStyleClass() { return minimizedStyle; } public void setMinimizedStyleClass(final String minimizedStyleClass) { this.minimizedStyle = minimizedStyleClass; } }
package com.sun.facelets.compiler; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import com.sun.facelets.tag.AbstractTagLibrary; import com.sun.facelets.tag.TagHandler; import com.sun.facelets.tag.TagLibrary; import com.sun.facelets.util.ParameterCheck; import com.sun.facelets.util.Classpath; import com.sun.facelets.util.ReflectionUtil; /** * Handles creating a {@link com.sun.facelets.tag.TagLibrary TagLibrary} from a * {@link java.net.URL URL} source. * * @author Jacob Hookom * @version $Id: TagLibraryConfig.java,v 1.11 2007-06-14 21:59:50 rlubke Exp $ */ public final class TagLibraryConfig { private final static String SUFFIX = ".taglib.xml"; protected final static Logger log = Logger.getLogger("facelets.compiler"); private static class TagLibraryImpl extends AbstractTagLibrary { public TagLibraryImpl(String namespace) { super(namespace); } public void putConverter(String name, String id) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("id", id); this.addConverter(name, id); } public void putConverter(String name, String id, Class handlerClass) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("id", id); ParameterCheck.notNull("handlerClass", handlerClass); this.addConverter(name, id, handlerClass); } public void putValidator(String name, String id) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("id", id); this.addValidator(name, id); } public void putValidator(String name, String id, Class handlerClass) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("id", id); ParameterCheck.notNull("handlerClass", handlerClass); this.addValidator(name, id, handlerClass); } public void putTagHandler(String name, Class type) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("type", type); this.addTagHandler(name, type); } public void putComponent(String name, String componentType, String rendererType) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("componentType", componentType); this.addComponent(name, componentType, rendererType); } public void putComponent(String name, String componentType, String rendererType, Class handlerClass) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("componentType", componentType); ParameterCheck.notNull("handlerClass", handlerClass); this.addComponent(name, componentType, rendererType, handlerClass); } public void putUserTag(String name, URL source) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("source", source); this.addUserTag(name, source); } public void putFunction(String name, Method method) { ParameterCheck.notNull("name", name); ParameterCheck.notNull("method", method); this.addFunction(name, method); } } private static class LibraryHandler extends DefaultHandler { private final String file; private final URL source; private TagLibrary library; private final StringBuffer buffer; private Locator locator; private String tagName; private String converterId; private String validatorId; private String componentClassName; private String componentType; private String rendererType; private String functionName; private Class handlerClass; private Class functionClass; private String functionSignature; public LibraryHandler(URL source) { this.file = source.getFile(); this.source = source; this.buffer = new StringBuffer(64); } public TagLibrary getLibrary() { return this.library; } public void endElement(String uri, String localName, String qName) throws SAXException { try { if ("facelet-taglib".equals(qName)) { ; // Nothing to do } else if ("library-class".equals(qName)) { this.processLibraryClass(); } else if ("namespace".equals(qName)) { this.library = new TagLibraryImpl(this.captureBuffer()); } else if ("component-type".equals(qName)) { this.componentType = this.captureBuffer(); } else if ("renderer-type".equals(qName)) { this.rendererType = this.captureBuffer(); } else if ("tag-name".equals(qName)) { this.tagName = this.captureBuffer(); } else if ("function-name".equals(qName)) { this.functionName = this.captureBuffer(); } else if ("function-class".equals(qName)) { String className = this.captureBuffer(); this.functionClass = this.createClass(Object.class, className); } else { // Make sure there we've seen a namespace element // before trying any of the following elements to avoid // obscure NPEs if (this.library == null) { throw new IllegalStateException("No <namespace> element"); } TagLibraryImpl impl = (TagLibraryImpl) this.library; if ("tag".equals(qName)) { if (this.handlerClass != null) { impl.putTagHandler(this.tagName, this.handlerClass); } } else if ("handler-class".equals(qName)) { String cName = this.captureBuffer(); this.handlerClass = this.createClass( TagHandler.class, cName); } else if ("component".equals(qName)) { if (this.handlerClass != null) { impl.putComponent(this.tagName, this.componentType, this.rendererType, this.handlerClass); this.handlerClass = null; } else { impl.putComponent(this.tagName, this.componentType, this.rendererType); } } else if ("converter-id".equals(qName)) { this.converterId = this.captureBuffer(); } else if ("converter".equals(qName)) { if (this.handlerClass != null) { impl.putConverter(this.tagName, this.converterId, handlerClass); this.handlerClass = null; } else { impl.putConverter(this.tagName, this.converterId); } this.converterId = null; } else if ("validator-id".equals(qName)) { this.validatorId = this.captureBuffer(); } else if ("validator".equals(qName)) { if (this.handlerClass != null) { impl.putValidator(this.tagName, this.validatorId, handlerClass); this.handlerClass = null; } else { impl.putValidator(this.tagName, this.validatorId); } this.validatorId = null; } else if ("source".equals(qName)) { String path = this.captureBuffer(); URL url = new URL(this.source, path); impl.putUserTag(this.tagName, url); } else if ("function-signature".equals(qName)) { this.functionSignature = this.captureBuffer(); Method m = this.createMethod(this.functionClass, this.functionSignature); impl.putFunction(this.functionName, m); } } } catch (Exception e) { SAXException saxe = new SAXException("Error Handling [" + this.source + "@" + this.locator.getLineNumber() + "," + this.locator.getColumnNumber() + "] <" + qName + ">"); saxe.initCause(e); throw saxe; } } private String captureBuffer() throws Exception { String s = this.buffer.toString().trim(); if (s.length() == 0) { throw new Exception("Value Cannot be Empty"); } this.buffer.setLength(0); return s; } private static Class createClass(Class type, String name) throws Exception { Class factory = ReflectionUtil.forName(name); if (!type.isAssignableFrom(factory)) { throw new Exception(name + " must be an instance of " + type.getName()); } return factory; } private static Method createMethod(Class type, String s) throws Exception { Method m = null; int pos = s.indexOf(' '); if (pos == -1) { throw new Exception("Must Provide Return Type: "+s); } else { String rt = s.substring(0, pos).trim(); int pos2 = s.indexOf('(', pos+1); if (pos2 == -1) { throw new Exception("Must provide a method name, followed by '(': "+s); } else { String mn = s.substring(pos+1, pos2).trim(); pos = s.indexOf(')', pos2 + 1); if (pos == -1) { throw new Exception("Must close parentheses, ')' missing: "+s); } else { String[] ps = s.substring(pos2 + 1, pos).trim().split(","); Class[] pc; if (ps.length == 1 && "".equals(ps[0])) { pc = new Class[0]; } else { pc = new Class[ps.length]; for (int i = 0; i < pc.length; i ++) { pc[i] = ReflectionUtil.forName(ps[i].trim()); } } try { return type.getMethod(mn, pc); } catch (NoSuchMethodException e) { throw new Exception("No Function Found on type: "+type.getName()+" with signature: "+s); } } } } } private void processLibraryClass() throws Exception { String name = this.captureBuffer(); Class type = this.createClass(TagLibrary.class, name); this.library = (TagLibrary) type.newInstance(); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if ("-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" .equals(publicId)) { URL url = Thread.currentThread().getContextClassLoader() .getResource("facelet-taglib_1_0.dtd"); return new InputSource(url.toExternalForm()); } return null; } public void characters(char[] ch, int start, int length) throws SAXException { this.buffer.append(ch, start, length); } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.buffer.setLength(0); if ("tag".equals(qName)) { this.componentClassName = null; this.handlerClass = null; this.componentType = null; this.rendererType = null; this.tagName = null; } else if ("function".equals(qName)) { this.functionName = null; this.functionClass = null; this.functionSignature = null; } } public void error(SAXParseException e) throws SAXException { SAXException saxe = new SAXException("Error Handling [" + this.source + "@" + e.getLineNumber() + "," + e.getColumnNumber() + "]"); saxe.initCause(e); throw saxe; } public void setDocumentLocator(Locator locator) { this.locator = locator; } public void fatalError(SAXParseException e) throws SAXException { throw e; } public void warning(SAXParseException e) throws SAXException { throw e; } } public TagLibraryConfig() { super(); } public static TagLibrary create(URL url) throws IOException { InputStream is = null; TagLibrary t = null; try { is = url.openStream(); LibraryHandler handler = new LibraryHandler(url); SAXParser parser = createSAXParser(handler); parser.parse(is, handler); t = handler.getLibrary(); } catch (SAXException e) { IOException ioe = new IOException("Error parsing [" + url + "]: "); ioe.initCause(e); throw ioe; } catch (ParserConfigurationException e) { IOException ioe = new IOException("Error parsing [" + url + "]: "); ioe.initCause(e); throw ioe; } finally { if (is != null) is.close(); } return t; } public void loadImplicit(Compiler compiler) throws IOException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL[] urls = Classpath.search(cl, "META-INF/", SUFFIX); for (int i = 0; i < urls.length; i++) { try { compiler.addTagLibrary(create(urls[i])); log.info("Added Library from: " + urls[i]); } catch (Exception e) { log.log(Level.SEVERE, "Error Loading Library: " + urls[i], e); } } } private static final SAXParser createSAXParser(LibraryHandler handler) throws SAXException, ParserConfigurationException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setFeature("http://xml.org/sax/features/validation", true); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(handler); reader.setEntityResolver(handler); return parser; } }
/* @java.file.header */ package org.apache.ignite; import org.apache.ignite.cluster.*; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.lang.*; import org.apache.ignite.managed.*; import org.apache.ignite.resources.*; import org.jetbrains.annotations.*; import java.util.*; /** * Defines functionality necessary to deploy distributed services on the grid. Instance of * {@code GridServices} is obtained from grid projection as follows: * <pre name="code" class="java"> * GridServices svcs = GridGain.grid().services(); * </pre> * With distributed services you can do the following: * <ul> * <li>Automatically deploy any number of service instances on the grid.</li> * <li> * Automatically deploy singletons, including <b>cluster-singleton</b>, * <b>node-singleton</b>, or <b>key-affinity-singleton</b>. * </li> * <li>Automatically deploy services on node start-up by specifying them in grid configuration.</li> * <li>Undeploy any of the deployed services.</li> * <li>Get information about service deployment topology within the grid.</li> * </ul> * <h1 class="header">Deployment From Configuration</h1> * In addition to deploying managed services by calling any of the provided {@code deploy(...)} methods, * you can also automatically deploy services on startup by specifying them in {@link IgniteConfiguration} * like so: * <pre name="code" class="java"> * GridConfiguration gridCfg = new GridConfiguration(); * * GridServiceConfiguration svcCfg1 = new GridServiceConfiguration(); * * // Cluster-wide singleton configuration. * svcCfg1.setName("myClusterSingletonService"); * svcCfg1.setMaxPerNodeCount(1); * svcCfg1.setTotalCount(1); * svcCfg1.setService(new MyClusterSingletonService()); * * GridServiceConfiguration svcCfg2 = new GridServiceConfiguration(); * * // Per-node singleton configuration. * svcCfg2.setName("myNodeSingletonService"); * svcCfg2.setMaxPerNodeCount(1); * svcCfg2.setService(new MyNodeSingletonService()); * * gridCfg.setServiceConfiguration(svcCfg1, svcCfg2); * ... * GridGain.start(gridCfg); * </pre> * <h1 class="header">Load Balancing</h1> * In all cases, other than singleton service deployment, GridGain will automatically make sure that * an about equal number of services are deployed on each node within the grid. Whenever cluster topology * changes, GridGain will re-evaluate service deployments and may re-deploy an already deployed service * on another node for better load balancing. * <h1 class="header">Fault Tolerance</h1> * GridGain guarantees that services are deployed according to specified configuration regardless * of any topology changes, including node crashes. * <h1 class="header">Resource Injection</h1> * All distributed services can be injected with * grid resources. Both, field and method based injections are supported. The following grid * resources can be injected: * <ul> * <li>{@link IgniteInstanceResource}</li> * <li>{@link IgniteLoggerResource}</li> * <li>{@link IgniteHomeResource}</li> * <li>{@link IgniteExecutorServiceResource}</li> * <li>{@link IgniteLocalNodeIdResource}</li> * <li>{@link IgniteMBeanServerResource}</li> * <li>{@link IgniteMarshallerResource}</li> * <li>{@link IgniteSpringApplicationContextResource}</li> * <li>{@link IgniteSpringResource}</li> * </ul> * Refer to corresponding resource documentation for more information. * <h1 class="header">Service Example</h1> * Here is an example of how an distributed service may be implemented and deployed: * <pre name="code" class="java"> * // Simple service implementation. * public class MyGridService implements GridService { * ... * // Example of grid resource injection. All resources are optional. * // You should inject resources only as needed. * &#64;GridInstanceResource * private Grid grid; * ... * &#64;Override public void cancel(GridServiceContext ctx) { * // No-op. * } * * &#64;Override public void execute(GridServiceContext ctx) { * // Loop until service is cancelled. * while (!ctx.isCancelled()) { * // Do something. * ... * } * } * } * ... * GridServices svcs = grid.services(); * * GridFuture&lt;?&gt; fut = svcs.deployClusterSingleton("mySingleton", new MyGridService()); * * // Wait for deployment to complete. * fut.get(); * </pre> */ public interface IgniteManaged extends IgniteAsyncSupport { /** * Gets grid projection to which this {@code GridServices} instance belongs. * * @return Grid projection to which this {@code GridServices} instance belongs. */ public ClusterGroup clusterGroup(); /** * Deploys a cluster-wide singleton service. GridGain will guarantee that there is always * one instance of the service in the cluster. In case if grid node on which the service * was deployed crashes or stops, GridGain will automatically redeploy it on another node. * However, if the node on which the service is deployed remains in topology, then the * service will always be deployed on that node only, regardless of topology changes. * <p> * Note that in case of topology changes, due to network delays, there may be a temporary situation * when a singleton service instance will be active on more than one node (e.g. crash detection delay). * <p> * This method is analogous to calling * {@link #deployMultiple(String, ManagedService, int, int) deployMultiple(name, svc, 1, 1)} method. * <p> * Supports asynchronous execution (see {@link IgniteAsyncSupport}). * * @param name Service name. * @param svc Service instance. * @throws IgniteCheckedException If failed to deploy service. */ public void deployClusterSingleton(String name, ManagedService svc) throws IgniteCheckedException; /** * Deploys a per-node singleton service. GridGain will guarantee that there is always * one instance of the service running on each node. Whenever new nodes are started * within this grid projection, GridGain will automatically deploy one instance of * the service on every new node. * <p> * This method is analogous to calling * {@link #deployMultiple(String, ManagedService, int, int) deployMultiple(name, svc, 0, 1)} method. * <p> * Supports asynchronous execution (see {@link IgniteAsyncSupport}). * * @param name Service name. * @param svc Service instance. * @throws IgniteCheckedException If failed to deploy service. */ public void deployNodeSingleton(String name, ManagedService svc) throws IgniteCheckedException; /** * Deploys one instance of this service on the primary node for a given affinity key. * Whenever topology changes and primary node assignment changes, GridGain will always * make sure that the service is undeployed on the previous primary node and deployed * on the new primary node. * <p> * Note that in case of topology changes, due to network delays, there may be a temporary situation * when a service instance will be active on more than one node (e.g. crash detection delay). * <p> * This method is analogous to the invocation of {@link #deploy(ManagedServiceConfiguration)} method * as follows: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setCacheName(cacheName); * cfg.setAffinityKey(affKey); * cfg.setTotalCount(1); * cfg.setMaxPerNodeCount(1); * * grid.services().deploy(cfg); * </pre> * <p> * Supports asynchronous execution (see {@link IgniteAsyncSupport}). * * @param name Service name. * @param svc Service instance. * @param cacheName Name of the cache on which affinity for key should be calculated, {@code null} for * default cache. * @param affKey Affinity cache key. * @throws IgniteCheckedException If failed to deploy service. */ public void deployKeyAffinitySingleton(String name, ManagedService svc, @Nullable String cacheName, Object affKey) throws IgniteCheckedException; /** * Deploys multiple instances of the service on the grid. GridGain will deploy a * maximum amount of services equal to {@code 'totalCnt'} parameter making sure that * there are no more than {@code 'maxPerNodeCnt'} service instances running * on each node. Whenever topology changes, GridGain will automatically rebalance * the deployed services within cluster to make sure that each node will end up with * about equal number of deployed instances whenever possible. * <p> * Note that at least one of {@code 'totalCnt'} or {@code 'maxPerNodeCnt'} parameters must have * value greater than {@code 0}. * <p> * This method is analogous to the invocation of {@link #deploy(ManagedServiceConfiguration)} method * as follows: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setTotalCount(totalCnt); * cfg.setMaxPerNodeCount(maxPerNodeCnt); * * grid.services().deploy(cfg); * </pre> * <p> * Supports asynchronous execution (see {@link IgniteAsyncSupport}). * * @param name Service name. * @param svc Service instance. * @param totalCnt Maximum number of deployed services in the grid, {@code 0} for unlimited. * @param maxPerNodeCnt Maximum number of deployed services on each node, {@code 0} for unlimited. * @throws IgniteCheckedException If failed to deploy service. */ public void deployMultiple(String name, ManagedService svc, int totalCnt, int maxPerNodeCnt) throws IgniteCheckedException; /** * Deploys multiple instances of the service on the grid according to provided * configuration. GridGain will deploy a maximum amount of services equal to * {@link ManagedServiceConfiguration#getTotalCount() cfg.getTotalCount()} parameter * making sure that there are no more than {@link ManagedServiceConfiguration#getMaxPerNodeCount() cfg.getMaxPerNodeCount()} * service instances running on each node. Whenever topology changes, GridGain will automatically rebalance * the deployed services within cluster to make sure that each node will end up with * about equal number of deployed instances whenever possible. * <p> * If {@link ManagedServiceConfiguration#getAffinityKey() cfg.getAffinityKey()} is not {@code null}, then GridGain * will deploy the service on the primary node for given affinity key. The affinity will be calculated * on the cache with {@link ManagedServiceConfiguration#getCacheName() cfg.getCacheName()} name. * <p> * If {@link ManagedServiceConfiguration#getNodeFilter() cfg.getNodeFilter()} is not {@code null}, then * GridGain will deploy service on all grid nodes for which the provided filter evaluates to {@code true}. * The node filter will be checked in addition to the underlying grid projection filter, or the * whole grid, if the underlying grid projection includes all grid nodes. * <p> * Note that at least one of {@code 'totalCnt'} or {@code 'maxPerNodeCnt'} parameters must have * value greater than {@code 0}. * <p> * Supports asynchronous execution (see {@link IgniteAsyncSupport}). * <p> * Here is an example of creating service deployment configuration: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setTotalCount(0); // Unlimited. * cfg.setMaxPerNodeCount(2); // Deploy 2 instances of service on each node. * * grid.services().deploy(cfg); * </pre> * * @param cfg Service configuration. * @throws IgniteCheckedException If failed to deploy service. */ public void deploy(ManagedServiceConfiguration cfg) throws IgniteCheckedException; /** * Cancels service deployment. If a service with specified name was deployed on the grid, * then {@link ManagedService#cancel(ManagedServiceContext)} method will be called on it. * <p> * Note that GridGain cannot guarantee that the service exits from {@link ManagedService#execute(ManagedServiceContext)} * method whenever {@link ManagedService#cancel(ManagedServiceContext)} is called. It is up to the user to * make sure that the service code properly reacts to cancellations. * <p> * Supports asynchronous execution (see {@link IgniteAsyncSupport}). * * @param name Name of service to cancel. * @throws IgniteCheckedException If failed to cancel service. */ public void cancel(String name) throws IgniteCheckedException; /** * Cancels all deployed services. * <p> * Note that depending on user logic, it may still take extra time for a service to * finish execution, even after it was cancelled. * <p> * Supports asynchronous execution (see {@link IgniteAsyncSupport}). * * @throws IgniteCheckedException If failed to cancel services. */ public void cancelAll() throws IgniteCheckedException; /** * Gets metadata about all deployed services. * * @return Metadata about all deployed services. */ public Collection<ManagedServiceDescriptor> deployedServices(); /** * Gets deployed service with specified name. * * @param name Service name. * @param <T> Service type * @return Deployed service with specified name. */ public <T> T service(String name); /** * Gets all deployed services with specified name. * * @param name Service name. * @param <T> Service type. * @return all deployed services with specified name. */ public <T> Collection<T> services(String name); /** * Gets a remote handle on the service. If service is available locally, * then local instance is returned, otherwise, a remote proxy is dynamically * created and provided for the specified service. * * @param name Service name. * @param svcItf Interface for the service. * @param sticky Whether or not GridGain should always contact the same remote * service or try to load-balance between services. * @return Either proxy over remote service or local service if it is deployed locally. */ public <T> T serviceProxy(String name, Class<? super T> svcItf, boolean sticky) throws IgniteException; /** {@inheritDoc} */ @Override public IgniteManaged enableAsync(); }
package com.sun.facelets.tag.core; import java.io.IOException; import javax.el.ELException; import javax.faces.FacesException; import javax.faces.component.UIComponent; import com.sun.facelets.FaceletContext; import com.sun.facelets.FaceletException; import com.sun.facelets.el.ELAdaptor; import com.sun.facelets.tag.TagAttribute; import com.sun.facelets.tag.TagConfig; import com.sun.facelets.tag.TagException; import com.sun.facelets.tag.TagHandler; public final class AttributeHandler extends TagHandler { private final TagAttribute name; private final TagAttribute value; /** * @param config */ public AttributeHandler(TagConfig config) { super(config); this.name = this.getRequiredAttribute("name"); this.value = this.getRequiredAttribute("value"); } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext, * javax.faces.component.UIComponent) */ public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { if (parent == null) { throw new TagException(this.tag, "Parent UIComponent was null"); } // only process if the parent is new to the tree if (parent.getParent() == null) { String n = this.name.getValue(ctx); if (!parent.getAttributes().containsKey(n)) { if (this.value.isLiteral()) { parent.getAttributes().put(n, this.value.getValue()); } else { ELAdaptor.setExpression(parent, n, this.value .getValueExpression(ctx, Object.class)); } } } } }
package com.tepidpond.tum.WorldGen; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; import com.tepidpond.tum.G; import com.tepidpond.tum.PlateTectonics.Lithosphere; public class TUMWorldGenData extends WorldSavedData { private static final String tagWorldGen = G.ModID; private NBTTagCompound data = new NBTTagCompound(); private final String tagName; /* Region: Items saved in TUM.WorldGen.Settings */ private int mapSize = G.WorldGen.DefaultMapSize; private float landSeaRatio = G.WorldGen.DefaultLandSeaRatio; private int erosionPeriod = G.WorldGen.DefaultErosionPeriod; private float foldingRatio = G.WorldGen.DefaultFoldingRatio; private int aggrRatioAbs = G.WorldGen.DefaultAggrRatioAbs; private float aggrRatioRel = G.WorldGen.DefaultAggrRatioRel; private int maxCycles = G.WorldGen.DefaultMaxCycles; private int numPlates = G.WorldGen.DefaultNumPlates; private int maxGens = G.WorldGen.DefaultMaxGens; /* Region: Items saved in TUM.WorldGen.Storage */ private float[] heightMap; private boolean heightMapGenerated = false; public TUMWorldGenData() { super(tagWorldGen); this.tagName = tagWorldGen; } public TUMWorldGenData(String tagName) { super(tagName); this.tagName = tagName; } @Override public void readFromNBT(NBTTagCompound compound) { NBTTagCompound nbtWorldGen = compound.getCompoundTag("WorldGen"); NBTTagCompound nbtSettings = nbtWorldGen.getCompoundTag("Settings"); if (nbtSettings != null) { if (nbtSettings.hasKey("mapSize")) mapSize = nbtSettings.getInteger("mapSize"); if (nbtSettings.hasKey("landSeaRatio")) landSeaRatio = nbtSettings.getFloat("landSeaRatio"); if (nbtSettings.hasKey("erosionPeriod")) erosionPeriod = nbtSettings.getInteger("erosionPeriod"); if (nbtSettings.hasKey("foldingRatio")) foldingRatio = nbtSettings.getFloat("foldingRatio"); if (nbtSettings.hasKey("aggrRatioAbs")) aggrRatioAbs = nbtSettings.getInteger("aggrRatioAbs"); if (nbtSettings.hasKey("aggrRatioRel")) aggrRatioRel = nbtSettings.getFloat("aggrRatioRel"); if (nbtSettings.hasKey("maxCycles")) maxCycles = nbtSettings.getInteger("maxCycles"); if (nbtSettings.hasKey("numPlates")) numPlates = nbtSettings.getInteger("numPlates"); if (nbtSettings.hasKey("maxGens")) maxGens = nbtSettings.getInteger("maxGens"); } NBTTagCompound nbtStorage = nbtWorldGen.getCompoundTag("Storage"); float[] heightMap = new float[(int) Math.pow(mapSize, 2)]; if (nbtStorage != null && nbtStorage.hasKey("heightMap") && nbtStorage.hasKey("heightMapGenerated")) { // Load packed heightmap from NBT byte[] byteArray = nbtStorage.getByteArray("heightMap"); heightMapGenerated = nbtStorage.getBoolean("heightMapGenerated"); if (byteArray.length == heightMap.length * 4 && heightMapGenerated) { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(byteArray)); try { for(int i=0; i < heightMap.length; i++) { heightMap[i] = dis.readFloat(); } this.heightMap = heightMap; } catch (IOException e) { // There is no need to be upset. Just regenerate it. An extra minute at world // load time is only annoying. nbtStorage.removeTag("heightMap"); heightMapGenerated = false; } } else { heightMapGenerated = false; } } else { heightMapGenerated = false; } } @Override public void writeToNBT(NBTTagCompound compound) { NBTTagCompound nbtWorldGen = new NBTTagCompound(); NBTTagCompound nbtSettings = new NBTTagCompound(); nbtSettings.setInteger("mapSize", mapSize); nbtSettings.setFloat( "landSeaRatio", landSeaRatio); nbtSettings.setInteger("erosionPeriod", erosionPeriod); nbtSettings.setFloat( "foldingRatio", foldingRatio); nbtSettings.setInteger("aggrRatioAbs", aggrRatioAbs); nbtSettings.setFloat( "aggrRatioRel", aggrRatioRel); nbtSettings.setInteger("maxCycles", maxCycles); nbtSettings.setInteger("numPlates", numPlates); nbtSettings.setInteger("maxGens", maxGens); nbtWorldGen.setTag("Settings", nbtSettings); if (heightMapGenerated) { NBTTagCompound nbtStorage = new NBTTagCompound(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); for(int i = 0; i < heightMap.length; i++) { dos.writeFloat(heightMap[i]); } nbtStorage.setByteArray("heightMap", baos.toByteArray()); nbtStorage.setBoolean("heightMapGenerated", heightMapGenerated); nbtWorldGen.setTag("Storage", nbtStorage); } catch (IOException e) { // This is a problem. heightMapGenerated = false; assert false: "Cause for panic, unable to save HeightMap to NBT"; } } compound.setTag("WorldGen", nbtWorldGen); } public static TUMWorldGenData get(World world) { TUMWorldGenData data = (TUMWorldGenData)world.loadItemData(TUMWorldGenData.class, tagWorldGen); if (data == null) { data = new TUMWorldGenData(tagWorldGen); world.setItemData(tagWorldGen, data); } return data; } public float[] getHeightMap() { if (heightMapGenerated) return heightMap; return null; } public boolean isHeightMapGenerated() { return heightMapGenerated; } public void setHeightMap(float heightMap[], int mapSize) { if ((heightMap.length & -heightMap.length) == heightMap.length && heightMap.length == Math.pow(mapSize, 2)) { this.mapSize = mapSize; this.heightMap = heightMap; heightMapGenerated = true; this.markDirty(); } } public int getMapSize() { return mapSize; } public void setMapSize(int mapSize) { if (mapSize != this.mapSize) heightMapGenerated = false; this.mapSize = mapSize; this.markDirty(); } public float getLandSeaRatio() { return landSeaRatio; } public void setLandSeaRatio(float landSeaRatio) { this.landSeaRatio = landSeaRatio; this.markDirty(); } public int getErosionPeriod() { return erosionPeriod; } public void setErosionPeriod(int erosionPeriod) { this.erosionPeriod = erosionPeriod; this.markDirty(); } public float getFoldingRatio() { return foldingRatio; } public void setFoldingRatio(float foldingRatio) { this.foldingRatio = foldingRatio; this.markDirty(); } public int getAggrRatioAbs() { return aggrRatioAbs; } public void setAggrRatioAbs(int aggrRatioAbs) { this.aggrRatioAbs = aggrRatioAbs; this.markDirty(); } public float getAggrRatioRel() { return aggrRatioRel; } public void setAggrRatioRel(float aggrRatioRel) { this.aggrRatioRel = aggrRatioRel; this.markDirty(); } public int getMaxCycles() { return maxCycles; } public void setMaxCycles(int maxCycles) { this.maxCycles = maxCycles; this.markDirty(); } public int getNumPlates() { return numPlates; } public void setNumPlates(int numPlates) { this.numPlates = numPlates; this.markDirty(); } public int getMaxGens() { return maxGens; } public void setMaxGens(int maxGens) { this.maxGens = maxGens; this.markDirty(); } }
package nl.b3p.viewer.admin.stripes; import java.util.*; import javax.annotation.security.RolesAllowed; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.servlet.http.HttpServletResponse; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.validation.*; import nl.b3p.viewer.config.app.Application; import nl.b3p.viewer.config.app.ApplicationLayer; import nl.b3p.viewer.config.app.Level; import nl.b3p.viewer.config.security.*; import nl.b3p.viewer.config.security.Authorizations.ApplicationCache; import nl.b3p.viewer.config.services.GeoService; import nl.b3p.viewer.config.services.Layer; import org.hibernate.*; import org.hibernate.criterion.*; import org.json.*; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @StrictBinding @UrlBinding("/action/user/{$event}") @RolesAllowed({"Admin","UserAdmin"}) public class UserActionBean implements ActionBean { private static final String JSP = "/WEB-INF/jsp/security/user.jsp"; private static final String EDITJSP = "/WEB-INF/jsp/security/edituser.jsp"; private ActionBeanContext context; @Validate private int page; @Validate private int start; @Validate private int limit; @Validate private String sort; @Validate private String dir; @Validate private JSONArray filter; @Validate private User user; @Validate private String username; @Validate private String password; private List<Group> allGroups; @Validate private List<String> groups = new ArrayList<String>(); @Validate private Map<String,String> details = new HashMap<String,String>(); //<editor-fold defaultstate="collapsed" desc="getters & setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public List<Group> getAllGroups() { return allGroups; } public void setAllGroups(List<Group> allGroups) { this.allGroups = allGroups; } public List<String> getGroups() { return groups; } public void setGroups(List<String> groups) { this.groups = groups; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public JSONArray getFilter() { return filter; } public void setFilter(JSONArray filter) { this.filter = filter; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; } //</editor-fold> @DefaultHandler @HandlesEvent("default") @DontValidate public Resolution defaultResolution() { return new ForwardResolution(JSP); } @Before(stages=LifecycleStage.BindingAndValidation) @SuppressWarnings("unchecked") public void load() { allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList(); } @DontValidate public Resolution edit() { if(user != null) { for(Group g: user.getGroups()) { groups.add(g.getName()); } details = user.getDetails(); username = user.getUsername(); } return new ForwardResolution(EDITJSP); } @DontBind public Resolution cancel() { return new ForwardResolution(EDITJSP); } @ValidationMethod(on="save") public void validate(ValidationErrors errors) throws Exception { // If user already persistent username cannot be changed if(user == null) { if(username == null) { errors.add("username", new LocalizableError("validation.required.valueNotPresent")); return; } try { Object o = Stripersist.getEntityManager().createQuery("select 1 from User where username = :username") .setMaxResults(1) .setParameter("username", username) .getSingleResult(); errors.add("username", new SimpleError("Gebruikersnaam bestaat al")); return; } catch(NoResultException nre) { // username is unique } } if(user == null) { if(password == null) { errors.add("password", new LocalizableError("validation.required.valueNotPresent")); return; } } if(password != null) { if(password.length() < User.MIN_PASSWORD_LENGTH) { errors.add("password", new LocalizableError("validation.minlength.valueTooShort", User.MIN_PASSWORD_LENGTH)); return; } } } public Resolution save() throws Exception { if(user == null) { user = new User(); user.setUsername(username); user.changePassword(password); } else { if(password != null) { user.changePassword(password); } } user.getDetails().clear(); user.getDetails().putAll(details); user.getGroups().clear(); for(String groupName: groups) { user.getGroups().add(Stripersist.getEntityManager().find(Group.class, groupName)); } Stripersist.getEntityManager().persist(user); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Gebruiker is opgeslagen")); return new ForwardResolution(EDITJSP); } @DontValidate public Resolution delete() { boolean inUse = false; String currentUser = context.getRequest().getUserPrincipal().getName(); if(currentUser.equals(user.getUsername())){ inUse = true; getContext().getMessages().add(new SimpleError("Het is niet mogelijk om de gebruiker waar u mee bent ingelogt te verwijderen.")); } List applications = Stripersist.getEntityManager().createQuery("from Application where owner = :owner") .setParameter("owner", user).getResultList(); if(applications != null && applications.size() > 0){ inUse = true; getContext().getMessages().add(new SimpleError("Het is niet mogelijk om de gebruiker te verwijderen, omdat deze eigenaar is van een of meerdere applicaties.")); } if(!inUse){ Stripersist.getEntityManager().remove(user); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Gebruiker is verwijderd")); } return new ForwardResolution(EDITJSP); } @DontValidate public Resolution getGridData() throws JSONException { JSONArray jsonData = new JSONArray(); String filterName = ""; //String filterDescription = ""; /* * FILTERING: filter is delivered by frontend as JSON array [{property, value}] * for demo purposes the value is now returned, ofcourse here should the DB * query be built to filter the right records */ if(this.getFilter() != null) { for(int k = 0; k < this.getFilter().length(); k++) { JSONObject j = this.getFilter().getJSONObject(k); String property = j.getString("property"); String value = j.getString("value"); if(property.equals("username")) { filterName = value; } /*if(property.equals("description")) { filterDescription = value; }*/ } } Session sess = (Session)Stripersist.getEntityManager().getDelegate(); Criteria c = sess.createCriteria(User.class); /* Sorting is delivered by the frontend * as two variables: sort which holds the column name and dir which * holds the direction (ASC, DESC). */ if(sort != null && dir != null){ Order order = null; if(dir.equals("ASC")){ order = Order.asc(sort); }else{ order = Order.desc(sort); } order.ignoreCase(); c.addOrder(order); } if(filterName != null && filterName.length() > 0){ Criterion nameCrit = Restrictions.ilike("username", filterName, MatchMode.ANYWHERE); c.add(nameCrit); } /*if(filterDescription != null && filterDescription.length() > 0){ Criterion urlCrit = Restrictions.ilike("description", filterDescription, MatchMode.ANYWHERE); c.add(urlCrit); }*/ int rowCount = c.list().size(); c.setMaxResults(limit); c.setFirstResult(start); List users = c.list(); for(Iterator it = users.iterator(); it.hasNext();){ User us = (User)it.next(); JSONObject j = this.getGridRow(us.getUsername(), us.getDetails()); jsonData.put(j); } final JSONObject grid = new JSONObject(); grid.put("totalCount", rowCount); grid.put("gridrows", jsonData); return new StreamingResolution("application/json") { @Override public void stream(HttpServletResponse response) throws Exception { response.getWriter().print(grid.toString()); } }; } private JSONObject getGridRow(String username, Map details) throws JSONException { JSONObject j = new JSONObject(); j.put("id", username); j.put("username", username); j.put("organization", details.get("organization")); j.put("position", details.get("position")); return j; } @Validate Application application; List<Application> applications; Set<Layer> authorizedLayers = Collections.EMPTY_SET; Set<Layer> authorizedEditableLayers = Collections.EMPTY_SET; Authorizations.ApplicationCache applicationCache; Set<Level> authorizedLevels = Collections.EMPTY_SET; Set<ApplicationLayer> authorizedAppLayers = Collections.EMPTY_SET; Set<ApplicationLayer> authorizedEditableAppLayers = Collections.EMPTY_SET; //<editor-fold defaultstate="collapsed" desc="getters and setters for authorization collections"> public Application getApplication() { return application; } public void setApplication(Application application) { this.application = application; } public List<Application> getApplications() { return applications; } public Set<ApplicationLayer> getAuthorizedAppLayers() { return authorizedAppLayers; } public Set<ApplicationLayer> getAuthorizedEditableAppLayers() { return authorizedEditableAppLayers; } public Set<Layer> getAuthorizedEditableLayers() { return authorizedEditableLayers; } public Set<Layer> getAuthorizedLayers() { return authorizedLayers; } public Set<Level> getAuthorizedLevels() { return authorizedLevels; } public ApplicationCache getApplicationCache() { return applicationCache; } //</editor-fold> public Resolution authorizations() { EntityManager em = Stripersist.getEntityManager(); List<GeoService> services = em.createQuery("from GeoService").getResultList(); for(GeoService service: services) { Authorizations.getLayerAuthorizations(service.getTopLayer()); } Set<String> roles = new HashSet<String>(); if(user != null) { for(Group g: user.getGroups()) { if(g != null) { roles.add(g.getName()); } } } if(!roles.isEmpty()) { authorizedLayers = new HashSet<Layer>(); authorizedEditableLayers = new HashSet<Layer>(); for(Map.Entry<Long,Authorizations.GeoServiceCache> e: Authorizations.serviceCache.entrySet()) { for(Map.Entry<Long,Authorizations.ReadWrite> e2: e.getValue().getProtectedLayers().entrySet()) { Layer l = Stripersist.getEntityManager().find(Layer.class, e2.getKey()); Set<String> readers = e2.getValue().getReaders(); Set<String> writers = e2.getValue().getWriters(); if(readers.equals(Authorizations.EVERYBODY) || !Collections.disjoint(readers, roles)) { authorizedLayers.add(l); } if(writers.equals(Authorizations.EVERYBODY) || !Collections.disjoint(writers, roles)) { authorizedEditableLayers.add(l); } } } } applications = em.createQuery("from Application order by name, version").getResultList(); if(application != null) { applicationCache = Authorizations.getApplicationCache(application); if(!roles.isEmpty()) { authorizedLevels = new HashSet<Level>(); for(Map.Entry<Long,Authorizations.Read> e: applicationCache.getProtectedLevels().entrySet()) { Level l = Stripersist.getEntityManager().find(Level.class, e.getKey()); Set<String> readers = e.getValue().getReaders(); if(readers.equals(Authorizations.EVERYBODY) || !Collections.disjoint(readers, roles)) { authorizedLevels.add(l); } } authorizedAppLayers = new HashSet<ApplicationLayer>(); authorizedEditableAppLayers = new HashSet<ApplicationLayer>(); for(Map.Entry<Long,Authorizations.ReadWrite> e: applicationCache.getProtectedAppLayers().entrySet()) { ApplicationLayer al = Stripersist.getEntityManager().find(ApplicationLayer.class, e.getKey()); Set<String> readers = e.getValue().getReaders(); Set<String> writers = e.getValue().getWriters(); if(readers.equals(Authorizations.EVERYBODY) || !Collections.disjoint(readers, roles)) { authorizedAppLayers.add(al); } if(writers.equals(Authorizations.EVERYBODY) || !Collections.disjoint(writers, roles)) { authorizedEditableAppLayers.add(al); } } } } return new ForwardResolution("/WEB-INF/jsp/security/authorizations.jsp"); } }
package org.spine3.server.internal; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.protobuf.Descriptors; import com.google.protobuf.Message; import org.spine3.server.Entity; import org.spine3.util.Identifiers; import static com.google.common.base.Preconditions.checkNotNull; /** * A base for {@link Entity} ID value object. * * <p>An entity ID value can be of one of the following types: * <ul> * <li>String</li> * <li>Long</li> * <li>Integer</li> * <li>A class implementing {@link Message}</li> * </ul> * * <p>Consider using {@code Message}-based IDs if you want to have typed IDs in your code, and/or * if you need to have IDs with some structure inside. Examples of such structural IDs are: * <ul> * <li>EAN value used in bar codes</li> * <li>ISBN</li> * <li>Phone number</li> * <li>email address as a couple of local-part and domain</li> * </ul> * * @param <I> the type of entity IDs * * @author Alexander Yevsyukov * @author Alexander Litus */ @SuppressWarnings("AbstractClassWithoutAbstractMethods") // OK in this case public abstract class EntityId<I> { /** * The value of the id. */ private final I value; private static final ImmutableSet<Class<?>> SUPPORTED_TYPES = ImmutableSet.<Class<?>>builder() .add(String.class) .add(Long.class) .add(Integer.class) .add(Message.class) .build(); protected EntityId(I value) { checkNotNull(value); checkType(value); this.value = value; } public static <I> void checkType(I entityId) { final Class<?> idClass = entityId.getClass(); if (SUPPORTED_TYPES.contains(idClass)) { return; } if (!Message.class.isAssignableFrom(idClass)){ throw unsupportedIdType(idClass); } } /** * Returns the short name of the type of underlying value. * * @return * <ul> * <li>Short Protobuf type name if the value is {@link Message}</li> * <li>Simple class name of the value, otherwise</li> * </ul> */ public String getShortTypeName() { if (this.value instanceof Message) { //noinspection TypeMayBeWeakened final Message message = (Message)this.value; final Descriptors.Descriptor descriptor = message.getDescriptorForType(); final String result = descriptor.getName(); return result; } else { final String result = value.getClass().getSimpleName(); return result; } } @Override public String toString() { final String result = Identifiers.idToString(value()); return result; } public I value() { return this.value; } private static IllegalArgumentException unsupportedIdType(Class<?> idClass) { final String supportedTypesString = Joiner.on(", ").join(SUPPORTED_TYPES); final String message = "Expected one of the following ID types: " + supportedTypesString + "; found: " + idClass.getName(); throw new IllegalArgumentException(message); } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.parser; import java.util.ArrayList; import java.util.List; import opennlp.tools.chunker.ChunkerContextGenerator; import opennlp.tools.util.Cache; /** * Creates predivtive context for the pre-chunking phases of parsing. */ public class ChunkContextGenerator implements ChunkerContextGenerator { private static final String EOS = "eos"; private Cache contextsCache; private Object wordsKey; public ChunkContextGenerator() { this(0); } public ChunkContextGenerator(int cacheSize) { super(); if (cacheSize > 0) { contextsCache = new Cache(cacheSize); } } public String[] getContext(Object o) { Object[] data = (Object[]) o; return (getContext(((Integer) data[0]).intValue(), (String[]) data[1], (String[]) data[2], (String[]) data[3])); } public String[] getContext(int i, Object[] words, String[] prevDecisions, Object[] ac) { return(getContext(i,words,(String[]) ac[0],prevDecisions)); } public String[] getContext(int i, Object[] words, String[] tags, String[] preds) { List features = new ArrayList(19); int x0 = i; int x_2 = x0 - 2; int x_1 = x0 - 1; int x2 = x0 + 2; int x1 = x0 + 1; String w_2,w_1,w0,w1,w2; String t_2,t_1,t0,t1,t2; String p_2,p_1; // chunkandpostag(-2) if (x_2 >= 0) { t_2=tags[x_2]; p_2=preds[x_2]; w_2=words[x_2].toString(); } else { t_2=EOS; p_2=EOS; w_2=EOS; } // chunkandpostag(-1) if (x_1 >= 0) { t_1=tags[x_1]; p_1=preds[x_1]; w_1=words[x_1].toString(); } else { t_1=EOS; p_1=EOS; w_1=EOS; } // chunkandpostag(0) t0=tags[x0]; w0=words[x0].toString(); // chunkandpostag(1) if (x1 < tags.length) { t1=tags[x1]; w1=words[x1].toString(); } else { t1=EOS; w1=EOS; } // chunkandpostag(2) if (x2 < tags.length) { t2=tags[x2]; w2=words[x2].toString(); } else { t2=EOS; w2=EOS; } String cacheKey = x0+t_2+t1+t0+t1+t2+p_2+p_1; if (contextsCache!= null) { if (wordsKey == words) { String[] contexts = (String[]) contextsCache.get(cacheKey); if (contexts != null) { return contexts; } } else { contextsCache.clear(); wordsKey = words; } } String ct_2 = chunkandpostag(-2, w_2, t_2, p_2); String ctbo_2 = chunkandpostagbo(-2, t_2, p_2); String ct_1 = chunkandpostag(-1, w_1, t_1, p_1); String ctbo_1 = chunkandpostagbo(-1, t_1, p_1); String ct0 = chunkandpostag(0, w0, t0, null); String ctbo0 = chunkandpostagbo(0, t0, null); String ct1 = chunkandpostag(1, w1, t1, null); String ctbo1 = chunkandpostagbo(1, t1, null); String ct2 = chunkandpostag(2, w2, t2, null); String ctbo2 = chunkandpostagbo(2, t2, null); features.add("default"); features.add(ct_2); features.add(ctbo_2); features.add(ct_1); features.add(ctbo_1); features.add(ct0); features.add(ctbo0); features.add(ct1); features.add(ctbo1); features.add(ct2); features.add(ctbo2); //chunkandpostag(-1,0) features.add(ct_1 + "," + ct0); features.add(ctbo_1 + "," + ct0); features.add(ct_1 + "," + ctbo0); features.add(ctbo_1 + "," + ctbo0); //chunkandpostag(0,1) features.add(ct0 + "," + ct1); features.add(ctbo0 + "," + ct1); features.add(ct0 + "," + ctbo1); features.add(ctbo0 + "," + ctbo1); String contexts[] = (String[]) features.toArray(new String[features.size()]); if (contextsCache != null) { contextsCache.put(cacheKey,contexts); } return (contexts); } private String chunkandpostag(int i, String tok, String tag, String chunk) { StringBuffer feat = new StringBuffer(20); feat.append(i).append("=").append(tok).append("|").append(tag); if (i < 0) { feat.append("|").append(chunk); } return (feat.toString()); } private String chunkandpostagbo(int i, String tag, String chunk) { StringBuffer feat = new StringBuffer(20); feat.append(i).append("*=").append(tag); if (i < 0) { feat.append("|").append(chunk); } return (feat.toString()); } }
// $Id: RuntimeAdjust.java,v 1.9 2003/03/11 23:08:56 ray Exp $ package com.samskivert.util; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.Iterator; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextField; import com.samskivert.Log; import com.samskivert.swing.CollapsiblePanel; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.MultiLineLabel; import com.samskivert.swing.ScrollablePanel; import com.samskivert.swing.VGroupLayout; /** * Provides a service where named variables can be registered as * adjustable by the developer at runtime. Generally a special key is * configured (via {@link DebugChords}) to pop up the adjustable variables * interface which can then be used to toggle booleans, change integer * values and generally adjust debugging and tuning parameters. This is * not meant to be an interface for end-user configurable parameters, but * to allow the developer to tweak runtime parameters more easily. * * <p> Adjustments are bound to a {@link Config} property which can be * changed through the config interface or through the bound runtime * adjust. * * <p> <em>Note:</em> adjusts are meant to be arranged in a two level * hierarchy. An adjust's name, therefore, should be of the form: * <code>library.package.adjustment</code>. The <code>package</code> * component can consist of multiple words joined with a period, but the * <code>library</code> will always be the first word before the first * period and the <code>adjustment</code> always the last word after the * final period. This is mainly only important for organizing the runtime * adjustment editing interface. */ public class RuntimeAdjust { /** * Creates a Swing user interface that can be used to adjust all * registered runtime adjustments. */ public static JComponent createAdjustEditor () { VGroupLayout layout = new VGroupLayout( VGroupLayout.NONE, VGroupLayout.STRETCH, 3, VGroupLayout.TOP); layout.setOffAxisJustification(VGroupLayout.LEFT); JTabbedPane editor = new JTabbedPane(); Font font = editor.getFont(); Font smaller = font.deriveFont(font.getSize()-1f); String library = null; ScrollablePanel lpanel = null; String pkgname = null; CollapsiblePanel pkgpanel = null; int acount = _adjusts.size(); for (int ii = 0; ii < acount; ii++) { Adjust adjust = (Adjust)_adjusts.get(ii); // create a new library label if necessary if (!adjust.getLibrary().equals(library)) { library = adjust.getLibrary(); pkgname = null; lpanel = new ScrollablePanel(layout); lpanel.setTracksViewportWidth(true); lpanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); editor.addTab(library, lpanel); } // create a new package panel if necessary if (!adjust.getPackage().equals(pkgname)) { pkgname = adjust.getPackage(); pkgpanel = new CollapsiblePanel(); JCheckBox pkgcheck = new JCheckBox(pkgname); pkgcheck.setSelected(true); pkgpanel.setTrigger(pkgcheck, null, null); pkgpanel.setTriggerContainer(pkgcheck); pkgpanel.getContent().setLayout(layout); pkgpanel.setCollapsed(false); lpanel.add(pkgpanel); } // add an entry for this adjustment pkgpanel.getContent().add(new JSeparator()); JPanel aeditor = adjust.getEditor(); aeditor.setFont(smaller); pkgpanel.getContent().add(aeditor); } return editor; } /** Provides runtime adjustable boolean variables. */ public static class BooleanAdjust extends Adjust implements ActionListener { public BooleanAdjust (String descrip, String name, Config config, boolean defval) { super(descrip, name, config); _value = _config.getValue(_name, defval); } public final boolean getValue () { return _value; } public void setValue (boolean value) { _config.setValue(_name, value); } protected void populateEditor (JPanel editor) { editor.add(_valbox = new JCheckBox(), GroupLayout.FIXED); _valbox.setSelected(getValue()); _valbox.addActionListener(this); } public void actionPerformed (ActionEvent e) { setValue(_valbox.isSelected()); } public void propertyChange (PropertyChangeEvent evt) { _value = ((Boolean)evt.getNewValue()).booleanValue(); adjusted(_value); if (_valbox != null) { _valbox.setSelected(_value); } } protected void adjusted (boolean newValue) { // Log.info(_name + " => " + newValue); } protected boolean _value; protected JCheckBox _valbox; } /** Provides runtime adjustable integer variables. */ public static class IntAdjust extends TextFieldAdjust { public IntAdjust (String descrip, String name, Config config, int defval) { super(descrip, name, config); _value = _config.getValue(_name, defval); } public final int getValue () { return _value; } public void setValue (int value) { _config.setValue(_name, value); } protected void populateEditor (JPanel editor) { super.populateEditor(editor); _valbox.setText("" + getValue()); } public void actionPerformed (ActionEvent e) { try { setValue(Integer.parseInt(_valbox.getText())); } catch (NumberFormatException nfe) { _valbox.setText("" + getValue()); } } public void propertyChange (PropertyChangeEvent evt) { _value = ((Integer)evt.getNewValue()).intValue(); Integer oval = (Integer)evt.getOldValue(); adjusted(_value, (oval == null ? -1 : oval.intValue())); if (_valbox != null) { _valbox.setText("" + _value); } } protected void adjusted (int newValue, int oldValue) { // Log.info(_name + " => " + newValue); } protected int _value; } /** Provides runtime adjustable enumerated variables. */ public static class EnumAdjust extends Adjust implements ActionListener { public EnumAdjust (String descrip, String name, Config config, String[] values, String defval) { super(descrip, name, config); _values = values; _value = _config.getValue(_name, defval); } public final String getValue () { return _value; } public void setValue (String value) { if (!ListUtil.containsEqual(_values, value)) { Log.warning("Refusing invalid adjustment [name=" + _name + ", values=" + StringUtil.toString(_values) + ", value=" + value + "]."); } else { _config.setValue(_name, value); } } protected void populateEditor (JPanel editor) { editor.add(_valbox = new JComboBox(_values), GroupLayout.FIXED); _valbox.addActionListener(this); _valbox.setSelectedItem(getValue()); } public void actionPerformed (ActionEvent e) { setValue((String)_valbox.getSelectedItem()); } public void propertyChange (PropertyChangeEvent evt) { _value = (String)evt.getNewValue(); adjusted(_value, (String)evt.getOldValue()); if (_valbox != null) { _valbox.setSelectedItem(_value); } } protected void adjusted (String newValue, String oldValue) { // Log.info(_name + " => " + newValue); } protected String _value; protected String[] _values; protected JComboBox _valbox; } /** Provides runtime adjustable file path variables. */ public static class FileAdjust extends Adjust implements ActionListener { public FileAdjust (String descrip, String name, Config config, boolean directoriesOnly, String defval) { super(descrip, name, config); _value = _config.getValue(_name, defval); _directories = directoriesOnly; _default = defval; } public final String getValue () { return _value; } public void setValue (String value) { _config.setValue(_name, value); } protected void populateEditor (JPanel editor) { // set up the label JPanel p = GroupLayout.makeVBox(); p.add(_display = new JLabel()); redisplay(); JPanel buts = GroupLayout.makeHBox(); JButton set = new JButton("set"); set.setActionCommand("set"); set.addActionListener(this); buts.add(set); JButton def = new JButton("default"); def.setActionCommand("default"); def.addActionListener(this); buts.add(def); p.add(buts); editor.add(p, GroupLayout.FIXED); } public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals("default")) { setValue(_default); return; } // else File f = new File(_value); JFileChooser chooser = f.exists() ? new JFileChooser(f) : new JFileChooser(); // set it up like we like if (_directories) { chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } chooser.setSelectedFile(f); int result = chooser.showDialog(_editor, "Select"); if (JFileChooser.APPROVE_OPTION == result) { f = chooser.getSelectedFile(); setValue(f.getPath()); } } public void propertyChange (PropertyChangeEvent evt) { _value = (String)evt.getNewValue(); adjusted(_value, (String)evt.getOldValue()); redisplay(); } protected void redisplay () { if (_display != null) { _display.setText(StringUtil.blank(_value) ? "(unset)" : _value); } } protected void adjusted (String newValue, String oldValue) { // Log.info(_name + " => " + newValue); } protected String _value, _default; protected boolean _directories; protected JLabel _display; } /** Provides the ability to click a button and fire an action. */ public static abstract class Action extends Adjust implements ActionListener, Runnable { public Action (String descrip, String name) { super(descrip, name, null); } protected void populateEditor (JPanel editor) { JButton actbut = new JButton("Go"); editor.add(actbut, GroupLayout.FIXED); actbut.addActionListener(this); } public void actionPerformed (ActionEvent e) { run(); } public void propertyChange (PropertyChangeEvent evt) { // not needed } } /** * Base class for adjusts which use a text field for entry. */ protected abstract static class TextFieldAdjust extends Adjust implements ActionListener, FocusListener { public TextFieldAdjust (String descrip, String name, Config config) { super(descrip, name, config); } // documentation inherited protected void populateEditor (JPanel editor) { editor.add(_valbox = new JTextField(), GroupLayout.FIXED); _valbox.addFocusListener(this); _valbox.addActionListener(this); } // documentation inherited from interface FocusListener public void focusGained (FocusEvent e) { // nothing } // documentation inherited from interface FocusListener public void focusLost (FocusEvent e) { actionPerformed(new ActionEvent(_valbox, 0, "focusLost")); } /** The textbox that holds the value. */ protected JTextField _valbox; } /** Base class for type-specific adjustments. */ protected abstract static class Adjust implements PropertyChangeListener, Comparable { public Adjust (String descrip, String name, Config config) { _name = name; _descrip = descrip; _config = config; if (_config != null) { _config.addPropertyChangeListener(_name, this); } // validate the structure of the name int fdidx = _name.indexOf("."), ldidx = _name.lastIndexOf("."); if (fdidx == -1 || ldidx == -1) { Log.warning("Invalid adjustment name '" + _name + "', must be of the form " + "'library.package.adjustment'."); return; } // make sure there isn't another with the same name int idx = _adjusts.binarySearch(this); if (idx >= 0) { Log.warning("Error: duplicate adjust registration " + "[new=" + this + ", old=" + _adjusts.get(idx) + "]."); return; } _adjusts.insertSorted(this); // keep 'em sorted } public boolean equals (Object other) { return _name.equals(((Adjust)other)._name); } public int compareTo (Object other) { return _name.compareTo(((Adjust)other)._name); } public String getName () { return _name; } public String getDescription () { return _descrip; } public String getLibrary () { return _name.substring(0, _name.indexOf(".")); } public String getPackage () { return _name.substring(_name.indexOf(".")+1, _name.lastIndexOf(".")); } public String getAdjustment () { return _name.substring(_name.lastIndexOf(".")+1); } public JPanel getEditor () { if (_editor == null) { _editor = GroupLayout.makeHBox(GroupLayout.STRETCH); _editor.add(new MultiLineLabel(_descrip, MultiLineLabel.LEFT, MultiLineLabel.VERTICAL, 25)); populateEditor(_editor); } return _editor; } protected abstract void populateEditor (JPanel editor); public String toString () { return StringUtil.shortClassName(this) + "[name=" + _name + ", desc=" + _descrip + "]"; } protected String _name, _descrip; protected Config _config; protected JPanel _editor; } protected static SortableArrayList _adjusts = new SortableArrayList(); }
package org.apache.commons.digester; import java.lang.reflect.Method; import java.lang.ClassLoader; import org.xml.sax.Attributes; import org.apache.commons.beanutils.ConvertUtils; public class CallMethodRule extends Rule { /** * Construct a "call method" rule with the specified method name. The * parameter types (if any) default to java.lang.String. * * @param digester The associated Digester * @param methodName Method name of the parent method to call * @param paramCount The number of parameters to collect, or * zero for a single argument from the body of this element. */ public CallMethodRule(Digester digester, String methodName, int paramCount) { this(digester, methodName, paramCount, (Class[]) null); } /** * Construct a "call method" rule with the specified method name. * * @param digester The associated Digester * @param methodName Method name of the parent method to call * @param paramCount The number of parameters to collect, or * zero for a single argument from the body of ths element * @param paramTypes The Java class names of the arguments * (if you wish to use a primitive type, specify the corresonding * Java wrapper class instead, such as <code>java.lang.Boolean</code> * for a <code>boolean</code> parameter) */ public CallMethodRule(Digester digester, String methodName, int paramCount, String paramTypes[]) { super(digester); this.methodName = methodName; this.paramCount = paramCount; if (paramTypes == null) { this.paramTypes = new Class[paramCount]; for (int i = 0; i < this.paramTypes.length; i++) this.paramTypes[i] = "abc".getClass(); } else { this.paramTypes = new Class[paramTypes.length]; for (int i = 0; i < this.paramTypes.length; i++) { try { this.paramTypes[i] = digester.getClassLoader().loadClass(paramTypes[i]); } catch (ClassNotFoundException e) { this.paramTypes[i] = null; // Will cause NPE later } } } } /** * Construct a "call method" rule with the specified method name. * * @param digester The associated Digester * @param methodName Method name of the parent method to call * @param paramCount The number of parameters to collect, or * zero for a single argument from the body of ths element * @param paramTypes The Java classes that represent the * parameter types of the method arguments * (if you wish to use a primitive type, specify the corresonding * Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code> * for a <code>boolean</code> parameter) */ public CallMethodRule(Digester digester, String methodName, int paramCount, Class paramTypes[]) { super(digester); this.methodName = methodName; this.paramCount = paramCount; if (paramTypes == null) { this.paramTypes = new Class[paramCount]; for (int i = 0; i < this.paramTypes.length; i++) this.paramTypes[i] = "abc".getClass(); } else { this.paramTypes = new Class[paramTypes.length]; for (int i = 0; i < this.paramTypes.length; i++) this.paramTypes[i] = paramTypes[i]; } } /** * The body text collected from this element. */ protected String bodyText = null; /** * The method name to call on the parent object. */ protected String methodName = null; /** * The number of parameters to collect from <code>MethodParam</code> rules. * If this value is zero, a single parameter will be collected from the * body of this element. */ protected int paramCount = 0; /** * The parameter types of the parameters to be collected. */ protected Class paramTypes[] = null; /** * Process the start of this element. * * @param attributes The attribute list for this element */ public void begin(Attributes attributes) throws Exception { // Push an array to capture the parameter values if necessary if (paramCount > 0) { String parameters[] = new String[paramCount]; for (int i = 0; i < parameters.length; i++) parameters[i] = null; digester.pushParams(parameters); } } /** * Process the body text of this element. * * @param bodyText The body text of this element */ public void body(String bodyText) throws Exception { if (paramCount == 0) this.bodyText = bodyText.trim(); } /** * Process the end of this element. */ public void end() throws Exception { // Retrieve or construct the parameter values array String parameters[] = null; if (paramCount > 0) { parameters = (String[]) digester.popParams(); // In the case where the parameter for the method // is taken from an attribute, and that attribute // isn't actually defined in the source XML file, // skip the method call if (paramCount == 1 && parameters[0] == null) { return; } } else { // In the case where the parameter for the method // is taken from the body text, but there is no // body text included in the source XML file, // skip the method call if (bodyText == null) { return; } parameters = new String[1]; parameters[0] = bodyText; if (paramTypes.length == 0) { paramTypes = new Class[1]; paramTypes[0] = "abc".getClass(); } } // Construct the parameter values array we will need Object paramValues[] = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) paramValues[i] = ConvertUtils.convert(parameters[i], paramTypes[i]); // Invoke the required method on the top object Object top = digester.peek(); if (digester.getDebug() >= 1) { StringBuffer sb = new StringBuffer("Call "); sb.append(top.getClass().getName()); sb.append("."); sb.append(methodName); sb.append("("); for (int i = 0; i < paramValues.length; i++) { if (i > 0) sb.append(","); if (paramValues[i] == null) sb.append("null"); else sb.append(paramValues[i].toString()); sb.append("/"); if (paramTypes[i] == null) sb.append("null"); else sb.append(paramTypes[i].getName()); } sb.append(")"); digester.log(sb.toString()); } Method method = top.getClass().getMethod(methodName, paramTypes); method.invoke(top, paramValues); } /** * Clean up after parsing is complete. */ public void finish() throws Exception { bodyText = null; } /** * Render a printable version of this Rule. */ public String toString() { StringBuffer sb = new StringBuffer("CallMethodRule["); sb.append("methodName="); sb.append(methodName); sb.append(", paramCount="); sb.append(paramCount); sb.append(", paramTypes={"); if (paramTypes != null) { for (int i = 0; i < paramTypes.length; i++) { if (i > 0) sb.append(", "); sb.append(paramTypes[i].getName()); } } sb.append("}"); sb.append("]"); return (sb.toString()); } }
package bisq.core.btc.nodes; import bisq.core.app.BisqEnvironment; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; @Slf4j public class BtcNodes { public enum BitcoinNodesOption { PROVIDED, CUSTOM, PUBLIC } // For other base currencies or testnet we ignore provided nodes public List<BtcNode> getProvidedBtcNodes() { return useProvidedBtcNodes() ? Arrays.asList( // ManfredKarrer new BtcNode("btc1.0-2-1.net", "r3dsojfhwcm7x7p6.onion", "159.89.16.222", BtcNode.DEFAULT_PORT, "@manfredkarrer"), new BtcNode("btc2.0-2-1.net", "vlf5i3grro3wux24.onion", "165.227.34.56", BtcNode.DEFAULT_PORT, "@manfredkarrer"), // emzy new BtcNode("kirsche.emzy.de", "fz6nsij6jiyuwlsc.onion", "78.47.61.83", BtcNode.DEFAULT_PORT, "@emzy"), new BtcNode("node2.emzy.de", "c6ac4jdfyeiakex2.onion", "62.75.210.81", BtcNode.DEFAULT_PORT, "@emzy"), new BtcNode("node1.emzy.de", "sjyzmwwu6diiit3r.onion", "167.86.90.239", BtcNode.DEFAULT_PORT, "@emzy"), new BtcNode(null, "3xucqntxp5ddoaz5.onion", null, BtcNode.DEFAULT_PORT, "@emzy"), // cannot provide IP because no static IP // ripcurlx new BtcNode("bitcoin.christophatteneder.com", "lgkvbvro67jomosw.onion", "174.138.35.229", BtcNode.DEFAULT_PORT, "@Christoph"), // mrosseel new BtcNode("btc.vante.me", "4jyh6llqj264oggs.onion", "94.23.21.80", BtcNode.DEFAULT_PORT, "@miker"), new BtcNode("btc2.vante.me", "mxdtrjhe2yfsx3pg.onion", "94.23.205.110", BtcNode.DEFAULT_PORT, "@miker"), // sqrrm new BtcNode("btc1.sqrrm.net", "3r44ddzjitznyahw.onion", "185.25.48.184", BtcNode.DEFAULT_PORT, "@sqrrm"), new BtcNode("btc2.sqrrm.net", "i3a5xtzfm4xwtybd.onion", "81.171.22.143", BtcNode.DEFAULT_PORT, "@sqrrm"), // KanoczTomas new BtcNode("btc.ispol.sk", "mbm6ffx6j5ygi2ck.onion", "193.58.196.212", BtcNode.DEFAULT_PORT, "@KanoczTomas"), // Devin Bileck new BtcNode("btc1.dnsalias.net", "lva54pnbq2nsmjyr.onion", "165.227.34.198", BtcNode.DEFAULT_PORT, "@devinbileck"), // sgeisler new BtcNode("bcwat.ch", "z33nukt7ngik3cpe.onion", "5.189.166.193", BtcNode.DEFAULT_PORT, "@sgeisler"), // wiz new BtcNode("node100.hnl.wiz.biz", "22tg6ufbwz6o3l2u.onion", "103.99.168.100", BtcNode.DEFAULT_PORT, "@wiz"), new BtcNode("node130.hnl.wiz.biz", "jiuuuislm7ooesic.onion", "103.99.168.130", BtcNode.DEFAULT_PORT, "@wiz"), // others new BtcNode("btc.jochen-hoenicke.de", "sslnjjhnmwllysv4.onion", "88.198.39.205", BtcNode.DEFAULT_PORT, "@jhoenicke") ) : new ArrayList<>(); } public boolean useProvidedBtcNodes() { return BisqEnvironment.getBaseCurrencyNetwork().isMainnet(); } public static List<BtcNodes.BtcNode> toBtcNodesList(Collection<String> nodes) { return nodes.stream() .filter(e -> !e.isEmpty()) .map(BtcNodes.BtcNode::fromFullAddress) .collect(Collectors.toList()); } @EqualsAndHashCode @Getter public static class BtcNode { private static final int DEFAULT_PORT = BisqEnvironment.getParameters().getPort(); //8333 @Nullable private final String onionAddress; @Nullable private final String hostName; @Nullable private final String operator; // null in case the user provides a list of custom btc nodes @Nullable private final String address; // IPv4 address private int port = DEFAULT_PORT; /** * @param fullAddress [IPv4 address:port or onion:port] * @return BtcNode instance */ public static BtcNode fromFullAddress(String fullAddress) { String[] parts = fullAddress.split(":"); checkArgument(parts.length > 0); final String host = parts[0]; int port = DEFAULT_PORT; if (parts.length == 2) port = Integer.valueOf(parts[1]); return host.contains(".onion") ? new BtcNode(null, host, null, port, null) : new BtcNode(null, null, host, port, null); } public BtcNode(@Nullable String hostName, @Nullable String onionAddress, @Nullable String address, int port, @Nullable String operator) { this.hostName = hostName; this.onionAddress = onionAddress; this.address = address; this.port = port; this.operator = operator; } public boolean hasOnionAddress() { return onionAddress != null; } public String getHostNameOrAddress() { if (hostName != null) return hostName; else return address; } public boolean hasClearNetAddress() { return hostName != null || address != null; } @Override public String toString() { return "onionAddress='" + onionAddress + '\'' + ", hostName='" + hostName + '\'' + ", address='" + address + '\'' + ", port='" + port + '\'' + ", operator='" + operator; } } }
package com.intellij.codeInsight; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.testFramework.PsiTestCase; import com.intellij.testFramework.PsiTestData; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.List; import java.util.ArrayList; /** * @author Mike */ public abstract class CodeInsightTestCase extends PsiTestCase { protected Editor myEditor; public CodeInsightTestCase() { myRunCommandForTest = true; } protected Editor createEditor(VirtualFile file) { return FileEditorManager.getInstance(myProject).openTextEditor(new OpenFileDescriptor(myProject, file, 0), false); } protected void tearDown() throws Exception { FileEditorManager editorManager = FileEditorManager.getInstance(myProject); VirtualFile[] openFiles = editorManager.getOpenFiles(); for (int i = 0; i < openFiles.length; i++) { editorManager.closeFile(openFiles[i]); } myEditor = null; super.tearDown(); } protected PsiTestData createData() { return new CodeInsightTestData(); } public static final String CARET_MARKER = "<caret>"; public static final String SELECTION_START_MARKER = "<selection>"; public static final String SELECTION_END_MARKER = "</selection>"; protected void configureByFile(String filePath) throws Exception { configureByFile(filePath, null); } protected void configureByFile(String filePath, String projectRoot) throws Exception { String fullPath = getTestDataPath() + filePath; final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(fullPath.replace(File.separatorChar, '/')); assertNotNull("file " + fullPath + " not found", vFile); File projectFile = projectRoot == null ? null : new File(getTestDataPath() + projectRoot); configureByFile(vFile, projectFile); } protected String getTestDataPath() { return PathManagerEx.getTestDataPath(); } protected void configureByFile(final VirtualFile vFile) throws IOException { configureByFile(vFile, null); } protected VirtualFile configureByFiles(final VirtualFile[] vFiles, final File projectRoot) throws IOException { myFile = null; myEditor = null; final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule); final ModifiableRootModel rootModel = rootManager.getModifiableModel(); if (clearModelBeforeConfiguring()) { rootModel.clear(); } File dir = createTempDirectory(); myFilesToDelete.add(dir); VirtualFile vDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/')); final VirtualFile[] newVFiles = new VirtualFile[vFiles.length]; final RangeMarker[] caretMarkers = new RangeMarker[vFiles.length]; final RangeMarker[] selStartMarkers = new RangeMarker[vFiles.length]; final RangeMarker[] selEndMarkers = new RangeMarker[vFiles.length]; final String[] newFileTexts = new String[vFiles.length]; boolean projectCopied = false; List<Writer> writersToClose = new ArrayList<Writer>(vFiles.length); for (int i = 0; i < vFiles.length; i++) { VirtualFile vFile = vFiles[i]; assertNotNull(vFile); String fileText = new String(vFile.contentsToCharArray()); fileText = StringUtil.convertLineSeparators(fileText, "\n"); Document document = EditorFactory.getInstance().createDocument(fileText); int caretIndex = fileText.indexOf(CARET_MARKER); int selStartIndex = fileText.indexOf(SELECTION_START_MARKER); int selEndIndex = fileText.indexOf(SELECTION_END_MARKER); final RangeMarker caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex) : null; final RangeMarker selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex) : null; final RangeMarker selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex) : null; if (caretMarker != null) { document.deleteString(caretMarker.getStartOffset(), caretMarker.getStartOffset() + CARET_MARKER.length()); } if (selStartMarker != null) { document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getStartOffset() + SELECTION_START_MARKER.length()); } if (selEndMarker != null) { document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getStartOffset() + SELECTION_END_MARKER.length()); } String newFileText = document.getText(); VirtualFile newVFile; if (projectRoot != null) { if (!projectCopied) { FileUtil.copyDir(projectRoot, dir); projectCopied = true; } String path = vDir.getPath() + vFile.getPath().substring(projectRoot.getPath().length()); newVFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); Writer writer = newVFile.getWriter(this); writer.write(newFileText); writersToClose.add(writer); } else { newVFile = vDir.createChildData(this, vFile.getName()); Writer writer = newVFile.getWriter(this); writer.write(newFileText); writersToClose.add(writer); } newVFiles[i]=newVFile; newFileTexts[i]=newFileText; selEndMarkers[i]=selEndMarker; selStartMarkers[i]=selStartMarker; caretMarkers[i]=caretMarker; } for(int i = writersToClose.size() -1; i >= 0 ; --i) { writersToClose.get(i).close(); } final ContentEntry contentEntry = rootModel.addContentEntry(vDir); if (isAddDirToSource()) contentEntry.addSourceFolder(vDir, false); rootModel.commit(); for (int i = 0; i < newVFiles.length; i++) { VirtualFile newVFile = newVFiles[i]; PsiFile file = myPsiManager.findFile(newVFile); if (myFile==null) myFile = file; Editor editor = createEditor(newVFile); if (myEditor==null) myEditor = editor; if (caretMarkers[i] != null) { int caretLine = StringUtil.offsetToLineNumber(newFileTexts[i], caretMarkers[i].getStartOffset()); int caretCol = caretMarkers[i].getStartOffset() - StringUtil.lineColToOffset(newFileTexts[i], caretLine, 0); LogicalPosition pos = new LogicalPosition(caretLine, caretCol); editor.getCaretModel().moveToLogicalPosition(pos); } if (selStartMarkers[i] != null) { editor.getSelectionModel().setSelection(selStartMarkers[i].getStartOffset(), selEndMarkers[i].getStartOffset()); } } return vDir; } protected File createTempDirectory() throws IOException { File dir = FileUtil.createTempDirectory("unitTest", null); return dir; } protected boolean isAddDirToSource() { return true; } protected VirtualFile configureByFile(final VirtualFile vFile, final File projectRoot) throws IOException { return configureByFiles(new VirtualFile[] {vFile},projectRoot); } protected boolean clearModelBeforeConfiguring() { return true; } protected void setupCursorAndSelection(Editor editor) { Document document = editor.getDocument(); final String text = document.getText(); int caretIndex = text.indexOf(CARET_MARKER); int selStartIndex = text.indexOf(SELECTION_START_MARKER); int selEndIndex = text.indexOf(SELECTION_END_MARKER); final RangeMarker caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex) : null; final RangeMarker selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex) : null; final RangeMarker selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex) : null; if (caretMarker != null) { document.deleteString(caretMarker.getStartOffset(), caretMarker.getStartOffset() + CARET_MARKER.length()); } if (selStartMarker != null) { document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getStartOffset() + SELECTION_START_MARKER.length()); } if (selEndMarker != null) { document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getStartOffset() + SELECTION_END_MARKER.length()); } final String newText = document.getText(); if (caretMarker != null) { int caretLine = StringUtil.offsetToLineNumber(newText, caretMarker.getStartOffset()); int caretCol = caretMarker.getStartOffset() - StringUtil.lineColToOffset(newText, caretLine, 0); LogicalPosition pos = new LogicalPosition(caretLine, caretCol); editor.getCaretModel().moveToLogicalPosition(pos); } if (selStartMarker != null) { editor.getSelectionModel().setSelection(selStartMarker.getStartOffset(), selEndMarker.getStartOffset()); } PsiDocumentManager.getInstance(myProject).commitAllDocuments(); } protected void configure(String path, String dataName) throws Exception { super.configure(path, dataName); myEditor = createEditor(myFile.getVirtualFile()); com.intellij.codeInsight.CodeInsightTestData data = (com.intellij.codeInsight.CodeInsightTestData) myTestDataBefore; int selectionStart; int selectionEnd; LogicalPosition pos = new LogicalPosition(data.getLineNumber() - 1, data.getColumnNumber() - 1); myEditor.getCaretModel().moveToLogicalPosition(pos); selectionStart = selectionEnd = myEditor.getCaretModel().getOffset(); if (data.getSelectionStartColumnNumber() >= 0) { selectionStart = myEditor.logicalPositionToOffset(new LogicalPosition(data.getSelectionEndLineNumber() - 1, data.getSelectionStartColumnNumber() - 1)); selectionEnd = myEditor.logicalPositionToOffset(new LogicalPosition(data.getSelectionEndLineNumber() - 1, data.getSelectionEndColumnNumber() - 1)); } myEditor.getSelectionModel().setSelection(selectionStart, selectionEnd); } protected void checkResultByFile(String filePath) throws Exception { checkResultByFile(filePath, false); } protected void checkResultByFile(String filePath, boolean stripTrailingSpaces) throws Exception { if (stripTrailingSpaces) { ((DocumentEx) myEditor.getDocument()).stripTrailingSpaces(false); } PsiDocumentManager.getInstance(myProject).commitAllDocuments(); String fullPath = getTestDataPath() + filePath; final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(fullPath.replace(File.separatorChar, '/')); assertNotNull("Cannot find file " + fullPath, vFile); String fileText = new String(vFile.contentsToCharArray()); fileText = StringUtil.convertLineSeparators(fileText, "\n"); Document document = EditorFactory.getInstance().createDocument(fileText); int caretIndex = fileText.indexOf(CARET_MARKER); int selStartIndex = fileText.indexOf(SELECTION_START_MARKER); int selEndIndex = fileText.indexOf(SELECTION_END_MARKER); final RangeMarker caretMarker = caretIndex >= 0 ? document.createRangeMarker(caretIndex, caretIndex) : null; final RangeMarker selStartMarker = selStartIndex >= 0 ? document.createRangeMarker(selStartIndex, selStartIndex) : null; final RangeMarker selEndMarker = selEndIndex >= 0 ? document.createRangeMarker(selEndIndex, selEndIndex) : null; if (caretMarker != null) { document.deleteString(caretMarker.getStartOffset(), caretMarker.getStartOffset() + CARET_MARKER.length()); } if (selStartMarker != null) { document.deleteString(selStartMarker.getStartOffset(), selStartMarker.getStartOffset() + SELECTION_START_MARKER.length()); } if (selEndMarker != null) { document.deleteString(selEndMarker.getStartOffset(), selEndMarker.getStartOffset() + SELECTION_END_MARKER.length()); } String newFileText = document.getText(); String newFileText1 = newFileText; if (stripTrailingSpaces) { Document document1 = EditorFactory.getInstance().createDocument(newFileText); ((DocumentEx) document1).stripTrailingSpaces(false); newFileText1 = document1.getText(); } String text = myFile.getText(); text = StringUtil.convertLineSeparators(text, "\n"); assertEquals("Text mismatch in file " + filePath, newFileText1, text); if (caretMarker != null) { int caretLine = StringUtil.offsetToLineNumber(newFileText, caretMarker.getStartOffset()); int caretCol = caretMarker.getStartOffset() - StringUtil.lineColToOffset(newFileText, caretLine, 0); assertEquals("caretLine", caretLine + 1, myEditor.getCaretModel().getLogicalPosition().line + 1); assertEquals("caretColumn", caretCol + 1, myEditor.getCaretModel().getLogicalPosition().column + 1); } if (selStartMarker != null && selEndMarker != null) { int selStartLine = StringUtil.offsetToLineNumber(newFileText, selStartMarker.getStartOffset()); int selStartCol = selStartMarker.getStartOffset() - StringUtil.lineColToOffset(newFileText, selStartLine, 0); int selEndLine = StringUtil.offsetToLineNumber(newFileText, selEndMarker.getEndOffset()); int selEndCol = selEndMarker.getEndOffset() - StringUtil.lineColToOffset(newFileText, selEndLine, 0); assertEquals( "selectionStartLine", selStartLine + 1, StringUtil.offsetToLineNumber(newFileText, myEditor.getSelectionModel().getSelectionStart()) + 1); assertEquals( "selectionStartCol", selStartCol + 1, myEditor.getSelectionModel().getSelectionStart() - StringUtil.lineColToOffset(newFileText, selStartLine, 0) + 1); assertEquals( "selectionEndLine", selEndLine + 1, StringUtil.offsetToLineNumber(newFileText, myEditor.getSelectionModel().getSelectionEnd()) + 1); assertEquals( "selectionEndCol", selEndCol + 1, myEditor.getSelectionModel().getSelectionEnd() - StringUtil.lineColToOffset(newFileText, selEndLine, 0) + 1); } else { assertTrue("has no selection", !myEditor.getSelectionModel().hasSelection()); } } protected void checkResult(String dataName) throws Exception { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); super.checkResult(dataName); com.intellij.codeInsight.CodeInsightTestData data = (com.intellij.codeInsight.CodeInsightTestData) myTestDataAfter; if (data.getColumnNumber() >= 0) { assertEquals(dataName + ":caretColumn", data.getColumnNumber(), myEditor.getCaretModel().getLogicalPosition().column + 1); } if (data.getLineNumber() >= 0) { assertEquals(dataName + ":caretLine", data.getLineNumber(), myEditor.getCaretModel().getLogicalPosition().line + 1); } int selectionStart = myEditor.getSelectionModel().getSelectionStart(); int selectionEnd = myEditor.getSelectionModel().getSelectionEnd(); LogicalPosition startPosition = myEditor.offsetToLogicalPosition(selectionStart); LogicalPosition endPosition = myEditor.offsetToLogicalPosition(selectionEnd); if (data.getSelectionStartColumnNumber() >= 0) { assertEquals(dataName + ":selectionStartColumn", data.getSelectionStartColumnNumber(), startPosition.column + 1); } if (data.getSelectionStartLineNumber() >= 0) { assertEquals(dataName + ":selectionStartLine", data.getSelectionStartLineNumber(), startPosition.line + 1); } if (data.getSelectionEndColumnNumber() >= 0) { assertEquals(dataName + ":selectionEndColumn", data.getSelectionEndColumnNumber(), endPosition.column + 1); } if (data.getSelectionEndLineNumber() >= 0) { assertEquals(dataName + ":selectionEndLine", data.getSelectionEndLineNumber(), endPosition.line + 1); } } public Object getData(String dataId) { if (dataId.equals(DataConstants.EDITOR)) { return myEditor; } else { return super.getData(dataId); } } protected VirtualFile getVirtualFile(String filePath) { String fullPath = getTestDataPath() + filePath; final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(fullPath.replace(File.separatorChar, '/')); assertNotNull("file " + fullPath + " not found", vFile); return vFile; } }
package gov.nih.nci.cadsr.cdecurate.test; import gov.nih.nci.cadsr.cdecurate.tool.AC_Bean; import gov.nih.nci.cadsr.cdecurate.tool.AC_CONTACT_Bean; import gov.nih.nci.cadsr.cdecurate.tool.CurationServlet; import gov.nih.nci.cadsr.cdecurate.tool.DEC_Bean; import gov.nih.nci.cadsr.cdecurate.tool.EVS_Bean; import gov.nih.nci.cadsr.cdecurate.tool.GetACSearch; import gov.nih.nci.cadsr.cdecurate.tool.InsACService; import gov.nih.nci.cadsr.cdecurate.tool.Session_Data; import gov.nih.nci.cadsr.cdecurate.tool.SetACService; import gov.nih.nci.cadsr.cdecurate.tool.UtilService; import gov.nih.nci.cadsr.cdecurate.util.AdministeredItemUtil; import gov.nih.nci.cadsr.cdecurate.util.DataManager; import java.util.Hashtable; import java.util.Vector; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.easymock.EasyMock; //import com.sun.org.apache.xerces.internal.impl.xs.dom.DOMParser; /** * Setup: * * 1. mkdir -p /local/content/cadsrsentinel/reports * 2. sudo touch /local/content/cadsrsentinel/reports/evstest1_log.txt * 3. sudo chmod 777 /local/content/cadsrsentinel/reports/evstest1_log.txt * */ public class TestDECAltName //extends TestCase //CurationServlet { public static final Logger logger = Logger.getLogger(CurationServlet.class.getName()); UtilService m_util = new UtilService(); // CurationServlet m_servlet = null; CurationServlet instance; public HttpServletRequest m_classReq = null; public HttpServletResponse m_classRes = null; HttpSession mockHttpSession = null; protected SetACService m_setAC = null; /** * Files involved - * 1. CurationServlet.java 2. SetACService.java 3. DataElementConceptServlet.java * Useful SQLs - * select --* asl_name, long_name, preferred_name, preferred_definition from concepts_view_ext where length(preferred_definition) < 200 --and asl_name = 'RELEASED' --and rownum < 10 and preferred_name in ('C19067','C42774','CL000986') "ASL_NAME" "LONG_NAME" "PREFERRED_NAME" "PREFERRED_DEFINITION" "RELEASED" "Title" "C19067" "CL000986: Title " "RELEASED" "Title" "C42774" "An official descriptive name of a document, e.g. the long name of a study protocol provided by the study sponsor." "RETIRED PHASED OUT" "Title" "CL000986" "CL000986: Title " / delete from COMPONENT_CONCEPTS_EXT where CON_IDSEQ = (select CON_IDSEQ from concepts_view_ext where preferred_name = 'C62682') / delete from concepts_view_ext where preferred_name = 'C62682' --to reuse Annual Sreening concept for GF30798 test / select --* CON_IDSEQ, asl_name, long_name, preferred_name, preferred_definition from concepts_view_ext con where length(preferred_definition) < 200 --and asl_name = 'RELEASED' --and rownum < 10 and preferred_name in ('C19067','C42774','CL000986','C62682','C1134631') / * */ public static void main(String[] args) { // CurationTestLogger logger1 = new CurationTestLogger(TestDECAltName.class); // Initialize the Log4j environment. String logXML = "log4j.xml"; if (args.length > 0) { logXML = args[0]; } // logger.initLogger(logXML); //initialize connection String connXML = ""; if (args.length > 1) connXML = args[1]; TestDECAltName testdec = new TestDECAltName(); // TestConnections varCon = new TestConnections(connXML, logger1); // VMForm vmdata = new VMForm(); // testdec.m_servlet = new CurationServlet(); // try { // vmdata.setDBConnection(varCon.openConnection()); // testdec.m_servlet.setConn(varCon.openConnection()); // vmdata.setCurationServlet(testdec.m_servlet); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); testdec.test(); } public void test() { m_classReq = EasyMock.createNiceMock(HttpServletRequest.class); m_classRes = EasyMock.createMock(HttpServletResponse.class); mockHttpSession = EasyMock.createNiceMock(HttpSession.class); //Creating the ServletConfig mock here ServletConfig servletConfig = EasyMock.createMock(ServletConfig.class); //Creating the ServletContext mock here ServletContext servletContext = EasyMock.createMock(ServletContext.class); //Create the target object instance = new CurationServlet(); //Call the init of the servlet with the mock ServletConfig instance.init(m_classReq, m_classRes, servletContext); m_setAC = new SetACService(instance); //Set up the ServletConfig mock so that when //getServletContext is called it can provide the //servlet with a ServletContext mock EasyMock.expect(servletConfig.getServletContext()).andReturn(servletContext).anyTimes(); EasyMock.expect(m_classReq.getSession()).andReturn(mockHttpSession).anyTimes(); EasyMock.expect(m_classReq.getParameter("pageAction")).andReturn("UseSelection"); EasyMock.expect(m_classReq.getParameter("MenuAction")).andReturn("editDEC"); String m[] = {"ErrorMessage"}; EasyMock.expect(mockHttpSession.getAttribute("gov.nih.nci.cadsr.cdecurate.util.DataManager")).andReturn(m); //ErrorMessage EasyMock.expect(mockHttpSession.getAttribute("originAction")).andReturn("EditDEC"); EasyMock.expect(mockHttpSession.getAttribute(Session_Data.SESSION_STATUS_MESSAGE)).andReturn(""); EasyMock.replay(mockHttpSession); EasyMock.replay(m_classReq); EasyMock.replay(m_classRes); EasyMock.replay(servletConfig); EasyMock.replay(servletContext); try { doEditDECActions(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void doEditDECActions() throws Exception { HttpSession session = m_classReq.getSession(); String sMenuAction = (String) m_classReq.getParameter("MenuAction"); if (sMenuAction != null) DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); String sAction = (String) m_classReq.getParameter("pageAction"); DataManager.setAttribute(session, "DECPageAction", sAction); // store the page action in attribute String sSubAction = (String) m_classReq.getParameter("DECAction"); DataManager.setAttribute(session, "DECAction", sSubAction); String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); String sOriginAction = (String) session.getAttribute("originAction"); if (sAction.equals("submit")) doSubmitDEC(); else if (sAction.equals("validate") && sOriginAction.equals("BlockEditDEC")) doValidateDECBlockEdit(); else if (sAction.equals("validate")) doValidateDEC(); else if (sAction.equals("suggestion")) doSuggestionDE(m_classReq, m_classRes); else if (sAction.equals("UseSelection")) { String nameAction = "appendName"; if (sOriginAction.equals("BlockEditDEC")) nameAction = "blockName"; doDECUseSelection(nameAction); ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); return; } else if (sAction.equals("RemoveSelection")) { doRemoveBuildingBlocks(); // re work on the naming if new one DEC_Bean dec = (DEC_Bean) session.getAttribute("m_DEC"); EVS_Bean nullEVS = null; dec = (DEC_Bean) this.getACNames(nullEVS, "Remove", dec); // need to change the long name & def also DataManager.setAttribute(session, "m_DEC", dec); ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); return; } else if (sAction.equals("changeNameType")) { this.doChangeDECNameType(); ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); } else if (sAction.equals("Store Alternate Names") || sAction.equals("Store Reference Documents")) this.doMarkACBeanForAltRef(m_classReq, m_classRes, "DataElementConcept", sAction, "editAC"); // add, edit and remove contacts else if (sAction.equals("doContactUpd") || sAction.equals("removeContact")) { DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC"); // capture all page attributes m_setAC.setDECValueFromPage(m_classReq, m_classRes, DECBean); DECBean.setAC_CONTACTS(this.doContactACUpdates(m_classReq, sAction)); ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); } else if (sAction.equals("clearBoxes")) { DEC_Bean DECBean = (DEC_Bean) session.getAttribute("oldDECBean"); this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes); String sDECID = DECBean.getDEC_DEC_IDSEQ(); Vector vList = new Vector(); // get VD's attributes from the database again GetACSearch serAC = null; //new GetACSearch(m_classReq, m_classRes, this); if (sDECID != null && !sDECID.equals("")) serAC.doDECSearch(sDECID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", vList, "0"); if (vList.size() > 0) { DECBean = (DEC_Bean) vList.elementAt(0); // logger.debug("cleared name " + DECBean.getDEC_PREFERRED_NAME()); DECBean = serAC.getDECAttributes(DECBean, sOriginAction, sMenuAction); } DEC_Bean pgBean = new DEC_Bean(); DataManager.setAttribute(session, "m_DEC", pgBean.cloneDEC_Bean(DECBean)); ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); } // open the create DE page or search result page else if (sAction.equals("backToDE")) { this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes); // clear session attributes if (sOriginAction.equalsIgnoreCase("editDECfromDE")) ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); else if (sMenuAction.equalsIgnoreCase("editDEC") || sOriginAction.equalsIgnoreCase("BlockEditDEC") || sButtonPressed.equals("Search") || sOriginAction.equalsIgnoreCase("EditDEC")) { DEC_Bean DECBean = (DEC_Bean) session.getAttribute("m_DEC"); if (DECBean == null){ DECBean = new DEC_Bean(); } GetACSearch serAC = null; //new GetACSearch(m_classReq, m_classRes, this); serAC.refreshData(m_classReq, m_classRes, null, DECBean, null, null, "Refresh", ""); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } else ForwardJSP(m_classReq, m_classRes, "/EditDECPage.jsp"); } } public AC_Bean getACNames(EVS_Bean newBean, String nameAct, AC_Bean pageAC) { HttpSession session = m_classReq.getSession(); DEC_Bean pageDEC = (DEC_Bean)pageAC; if (pageDEC == null) pageDEC = (DEC_Bean) session.getAttribute("m_DEC"); // get DEC object class and property names String sLongName = ""; String sPrefName = ""; String sAbbName = ""; String sOCName = ""; String sPropName = ""; String sDef = ""; String sComp = (String) m_classReq.getParameter("sCompBlocks"); InsACService ins = new InsACService(m_classReq, m_classRes, instance); Vector vObjectClass = (Vector) session.getAttribute("vObjectClass"); Vector vProperty = (Vector) session.getAttribute("vProperty"); logger.debug("at Line 700 of DEC.java" + "***" + sComp + "***" + newBean); if(newBean != null) { if (sComp.startsWith("Object")) { logger.debug("at Line 703 of DEC.java" + newBean.getEVS_DATABASE()); if (!(newBean.getEVS_DATABASE().equals("caDSR"))) { String conIdseq = ins.getConcept("", newBean, false); if (conIdseq == null || conIdseq.equals("")){ logger.debug("at Line 707 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME()); }else { logger.debug("at Line 709 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME()); } } }else if (sComp.startsWith("Prop")) { logger.debug("at Line 714 of DEC.java" + newBean.getEVS_DATABASE()); if (!(newBean.getEVS_DATABASE().equals("caDSR"))) { String conIdseq = ins.getConcept("", newBean, false); if (conIdseq == null || conIdseq.equals("")){ logger.debug("at Line 718 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME()); }else { logger.debug("at Line 720 of DEC.java"+newBean.getPREFERRED_DEFINITION()+"**"+newBean.getLONG_NAME()); } } } } // get the existing one if not restructuring the name but appending it if (newBean != null) { sLongName = pageDEC.getDEC_LONG_NAME(); if (sLongName == null) sLongName = ""; sDef = pageDEC.getDEC_PREFERRED_DEFINITION(); if (sDef == null) sDef = ""; logger.debug("At line 688 of DECServlet.java"+sLongName+"**"+sDef); } // get the typed text on to user name String selNameType = ""; if (nameAct.equals("Search") || nameAct.equals("Remove")) { logger.info("At line 750 of DECServlet.java"); selNameType = (String) m_classReq.getParameter("rNameConv"); sPrefName = (String) m_classReq.getParameter("txPreferredName"); if (selNameType != null && selNameType.equals("USER") && sPrefName != null) pageDEC.setAC_USER_PREF_NAME(sPrefName); } // get the object class into the long name and abbr name //Vector vObjectClass = (Vector) session.getAttribute("vObjectClass"); //GF30798 if (vObjectClass == null) { vObjectClass = new Vector(); } //begin of GF30798 for (int i=0; i<vObjectClass.size();i++){ EVS_Bean eBean =(EVS_Bean)vObjectClass.get(i); logger.debug("At line 762 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER()); } //end of GF30798 // add the Object Class qualifiers first for (int i = 1; vObjectClass.size() > i; i++) { EVS_Bean eCon = (EVS_Bean) vObjectClass.elementAt(i); if (eCon == null) eCon = new EVS_Bean(); String conName = eCon.getLONG_NAME(); if (conName == null) conName = ""; if (!conName.equals("")) { logger.info("At line 778 of DECServlet.java"); String nvpValue = ""; if (this.checkNVP(eCon)) nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE(); // rearrange it long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += conName + nvpValue; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION() + nvpValue; logger.debug("At line 792 of DECServlet.java"+sLongName+"**"+sDef); } if (!sAbbName.equals("")) sAbbName += "_"; if (conName.length() > 3) sAbbName += conName.substring(0, 4); // truncate to four letters else sAbbName += conName; // add object qualifiers to object class name if (!sOCName.equals("")) sOCName += " "; sOCName += conName + nvpValue; logger.debug("At line 805 of DECServlet.java"+conName+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName); } } // add the Object Class primary if (vObjectClass != null && vObjectClass.size() > 0) { EVS_Bean eCon = (EVS_Bean) vObjectClass.elementAt(0); if (eCon == null) eCon = new EVS_Bean(); String sPrimary = eCon.getLONG_NAME(); if (sPrimary == null) sPrimary = ""; if (!sPrimary.equals("")) { logger.info("At line 819 of DECServlet.java"); String nvpValue = ""; if (this.checkNVP(eCon)) nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE(); // rearrange it only long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += sPrimary + nvpValue; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION() + nvpValue; logger.debug("At line 833 of DECServlet.java"+sLongName+"**"+sDef); } if (!sAbbName.equals("")) sAbbName += "_"; if (sPrimary.length() > 3) sAbbName += sPrimary.substring(0, 4); // truncate to four letters else sAbbName += sPrimary; // add primary object to object name if (!sOCName.equals("")) sOCName += " "; sOCName += sPrimary + nvpValue; logger.debug("At line 778 of DECServlet.java"+sPrimary+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName); } } // get the Property into the long name and abbr name //Vector vProperty = (Vector) session.getAttribute("vProperty"); //GF30798 if (vProperty == null) vProperty = new Vector(); //begin of GF30798 for (int i=0; i<vProperty.size();i++){ EVS_Bean eBean =(EVS_Bean)vProperty.get(i); logger.debug("At line 853 of DECServlet.java "+eBean.getPREFERRED_DEFINITION()+"**"+eBean.getLONG_NAME()+"**"+eBean.getCONCEPT_IDENTIFIER()); } //begin of GF30798 // add the property qualifiers first for (int i = 1; vProperty.size() > i; i++) { EVS_Bean eCon = (EVS_Bean) vProperty.elementAt(i); if (eCon == null) eCon = new EVS_Bean(); String conName = eCon.getLONG_NAME(); if (conName == null) conName = ""; if (!conName.equals("")) { logger.info("At line 869 of DECServlet.java"); String nvpValue = ""; if (this.checkNVP(eCon)) nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE(); // rearrange it long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += conName + nvpValue; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION() + nvpValue; logger.debug("At line 883 of DECServlet.java"+sLongName+"**"+sDef); } if (!sAbbName.equals("")) sAbbName += "_"; if (conName.length() > 3) sAbbName += conName.substring(0, 4); // truncate to four letters else sAbbName += conName; // add property qualifiers to property name if (!sPropName.equals("")) sPropName += " "; sPropName += conName + nvpValue; logger.debug("At line 895 of DECServlet.java"+conName+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName); } } // add the property primary if (vProperty != null && vProperty.size() > 0) { EVS_Bean eCon = (EVS_Bean) vProperty.elementAt(0); if (eCon == null) eCon = new EVS_Bean(); String sPrimary = eCon.getLONG_NAME(); if (sPrimary == null) sPrimary = ""; if (!sPrimary.equals("")) { logger.info("At line 909 of DECServlet.java"); String nvpValue = ""; if (this.checkNVP(eCon)) nvpValue = "::" + eCon.getNVP_CONCEPT_VALUE(); // rearrange it only long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += sPrimary + nvpValue; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION() + nvpValue; logger.debug("At line 923 of DECServlet.java"+sLongName+"**"+sDef); } if (!sAbbName.equals("")) sAbbName += "_"; if (sPrimary.length() > 3) sAbbName += sPrimary.substring(0, 4); // truncate to four letters else sAbbName += sPrimary; // add primary property to property name if (!sPropName.equals("")) sPropName += " "; sPropName += sPrimary + nvpValue; logger.debug("At line 935 of DECServlet.java"+sPrimary+"**"+nvpValue+"**"+sLongName+"**"+sDef+"**"+sOCName); } } // truncate to 30 characters if (sAbbName != null && sAbbName.length() > 30) sAbbName = sAbbName.substring(0, 30); // add the abbr name to vd bean and page is selected pageDEC.setAC_ABBR_PREF_NAME(sAbbName); // make abbr name name preferrd name if sys was selected if (selNameType != null && selNameType.equals("ABBR")) pageDEC.setDEC_PREFERRED_NAME(sAbbName); // appending to the existing; if (newBean != null) { String sSelectName = newBean.getLONG_NAME(); if (!sLongName.equals("")) sLongName += " "; sLongName += sSelectName; if (!sDef.equals("")) sDef += "_"; // add definition sDef += newBean.getPREFERRED_DEFINITION(); logger.debug("At line 956 of DECServlet.java"+sLongName+"**"+sDef); } // store the long names, definition, and usr name in vd bean if searched if (nameAct.equals("Search") || nameAct.equals("Remove")) // GF30798 - added to call when name act is remove { pageDEC.setDEC_LONG_NAME(AdministeredItemUtil.handleLongName(sLongName)); //GF32004; pageDEC.setDEC_PREFERRED_DEFINITION(sDef); logger.debug("DEC_LONG_NAME at Line 963 of DECServlet.java"+pageDEC.getDEC_LONG_NAME()+"**"+pageDEC.getDEC_PREFERRED_DEFINITION()); } if (!nameAct.equals("OpenDEC")){ pageDEC.setDEC_OCL_NAME(sOCName); pageDEC.setDEC_PROPL_NAME(sPropName); logger.debug("At line 968 of DECServlet.java"+sOCName+"**"+sPropName); } if (nameAct.equals("Search") || nameAct.equals("Remove")) { pageDEC.setAC_SYS_PREF_NAME("(Generated by the System)"); // only for dec if (selNameType != null && selNameType.equals("SYS")) pageDEC.setDEC_PREFERRED_NAME(pageDEC.getAC_SYS_PREF_NAME()); } return pageDEC; } private void clearBuildingBlockSessionAttributes( HttpServletRequest m_classReq2, HttpServletResponse m_classRes2) { // TODO Auto-generated method stub } private Hashtable<String, AC_CONTACT_Bean> doContactACUpdates( HttpServletRequest m_classReq2, String sAction) { // TODO Auto-generated method stub return null; } private void doMarkACBeanForAltRef(HttpServletRequest m_classReq2, HttpServletResponse m_classRes2, String string, String sAction, String string2) { // TODO Auto-generated method stub } private void ForwardJSP(HttpServletRequest m_classReq2, HttpServletResponse m_classRes2, String string) { // TODO Auto-generated method stub } private void doSuggestionDE(HttpServletRequest m_classReq2, HttpServletResponse m_classRes2) { // TODO Auto-generated method stub } private void doChangeDECNameType() { // TODO Auto-generated method stub System.out.println("doChangeDECNameType"); } private void doRemoveBuildingBlocks() { // TODO Auto-generated method stub System.out.println("doRemoveBuildingBlocks"); } private void doDECUseSelection(String nameAction) { // TODO Auto-generated method stub System.out.println("doDECUseSelection"); } private void doValidateDEC() { // TODO Auto-generated method stub System.out.println("doValidateDEC"); } private void doValidateDECBlockEdit() { // TODO Auto-generated method stub System.out.println("doValidateDECBlockEdit"); } private void doSubmitDEC() { // TODO Auto-generated method stub System.out.println("doSubmitDEC"); } public static boolean checkNVP(EVS_Bean eCon) { return (eCon.getNAME_VALUE_PAIR_IND() > 0 && eCon.getLONG_NAME().indexOf("::") < 1 && eCon.getNVP_CONCEPT_VALUE().length() > 0); //JT not sure what is this checking for, second portion could be buggy!!! } }
package nl.mpi.kinnate.svg; import java.net.URI; import java.net.URISyntaxException; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.util.BugCatcher; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.apache.batik.swing.svg.SVGUserAgentGUIAdapter; public class GraphUserAgent extends SVGUserAgentGUIAdapter { private GraphPanel graphPanel; private MessageDialogHandler dialogHandler; private BugCatcher bugCatcher; private ArbilDataNodeLoader dataNodeLoader; public GraphUserAgent(GraphPanel parentComponent, MessageDialogHandler dialogHandler, BugCatcher bugCatcher, ArbilDataNodeLoader dataNodeLoader) { super(parentComponent); graphPanel = parentComponent; this.dialogHandler = dialogHandler; this.bugCatcher = bugCatcher; this.dataNodeLoader = dataNodeLoader; } @Override public void displayError(String message) { dialogHandler.addMessageDialogToQueue(message, "SVG Error"); } @Override public void displayError(Exception exception) { bugCatcher.logError(exception); } @Override public void displayMessage(String message) { dialogHandler.addMessageDialogToQueue(message, "SVG Error"); } @Override public void showAlert(String message) { dialogHandler.addMessageDialogToQueue(message, "SVG Notification"); } @Override public void openLink(String targetUri, boolean newc) { graphPanel.metadataPanel.removeAllArbilDataNodeRows(); try { // put link target into the table final ArbilDataNode arbilDataNode = dataNodeLoader.getArbilDataNode(null, new URI(targetUri)); graphPanel.metadataPanel.addArbilDataNode(arbilDataNode); } catch (URISyntaxException urise) { bugCatcher.logError(urise); } // set the graph selection graphPanel.setSelectedIds(new UniqueIdentifier[]{}); graphPanel.metadataPanel.updateEditorPane(); // todo: provide a url for the imdiviewer or to launch arbil // try { // GuiHelper.getSingleInstance().openFileInExternalApplication(new URI(targetUri)); // } catch (URISyntaxException exception) { // GuiHelper.linorgBugCatcher.logError(exception); } }
package net.java.sip.communicator.impl.gui.main; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.util.*; import java.util.List; import javax.swing.*; import org.osgi.framework.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.main.call.*; import net.java.sip.communicator.impl.gui.main.contactlist.*; import net.java.sip.communicator.impl.gui.main.login.*; import net.java.sip.communicator.impl.gui.main.menus.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.service.configuration.PropertyVetoException; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; /** * The main application window. This class is the core of this ui * implementation. It stores all available protocol providers and their * operation sets, as well as all registered accounts, the * <tt>MetaContactListService</tt> and all sent messages that aren't * delivered yet. * * @author Yana Stamcheva */ public class MainFrame extends JFrame { private Logger logger = Logger.getLogger(MainFrame.class.getName()); private JPanel contactListPanel = new JPanel(new BorderLayout()); private JPanel menusPanel = new JPanel(new BorderLayout()); private MainMenu menu; private CallManager callManager; private StatusPanel statusPanel; private MainTabbedPane tabbedPane; private QuickMenu quickMenu; private Hashtable protocolSupportedOperationSets = new Hashtable(); private Hashtable protocolPresenceSets = new Hashtable(); private Hashtable protocolTelephonySets = new Hashtable(); private Hashtable protocolProviders = new Hashtable(); private Hashtable imOperationSets = new Hashtable(); private Hashtable tnOperationSets = new Hashtable(); private Hashtable webContactInfoOperationSets = new Hashtable(); private MetaContactListService contactList; private ArrayList accounts = new ArrayList(); private Hashtable waitToBeDeliveredMsgs = new Hashtable(); private LoginManager loginManager; /** * Creates an instance of <tt>MainFrame</tt>. */ public MainFrame() { callManager = new CallManager(this); tabbedPane = new MainTabbedPane(this); quickMenu = new QuickMenu(this); statusPanel = new StatusPanel(this); menu = new MainMenu(this); this.addWindowListener(new MainFrameWindowAdapter()); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setInitialBounds(); this.setTitle(Messages.getString("sipCommunicator")); this.setIconImage(ImageLoader.getImage(ImageLoader.SIP_LOGO)); this.init(); } /** * Initiates the content of this frame. */ private void init() { this.menusPanel.add(menu, BorderLayout.NORTH); this.menusPanel.add(quickMenu, BorderLayout.CENTER); this.contactListPanel.add(tabbedPane, BorderLayout.CENTER); this.contactListPanel.add(callManager, BorderLayout.SOUTH); this.getContentPane().add(menusPanel, BorderLayout.NORTH); this.getContentPane().add(contactListPanel, BorderLayout.CENTER); this.getContentPane().add(statusPanel, BorderLayout.SOUTH); } /** * Sets frame size and position. */ private void setInitialBounds() { this.setSize(200, 450); this.contactListPanel.setPreferredSize(new Dimension(180, 400)); this.contactListPanel.setMinimumSize(new Dimension(80, 200)); this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth(), 50); } /** * Returns the <tt>MetaContactListService</tt>. * * @return <tt>MetaContactListService</tt> The current meta contact list. */ public MetaContactListService getContactList() { return this.contactList; } /** * Initializes the contact list panel. * * @param contactList The <tt>MetaContactListService</tt> containing * the contact list data. */ public void setContactList(MetaContactListService contactList) { this.contactList = contactList; ContactListPanel clistPanel = this.tabbedPane.getContactListPanel(); clistPanel.initList(contactList); CListKeySearchListener keyListener = new CListKeySearchListener(clistPanel.getContactList()); //add a key listener to the tabbed pane, when the contactlist is //initialized this.tabbedPane.addKeyListener(keyListener); clistPanel.addKeyListener(keyListener); clistPanel.getContactList().addKeyListener(keyListener); } /** * Returns a set of all operation sets supported by the given * protocol provider. * * @param protocolProvider The protocol provider. * @return a set of all operation sets supported by the given * protocol provider. */ public Map getSupportedOperationSets( ProtocolProviderService protocolProvider) { return (Map) this.protocolSupportedOperationSets.get(protocolProvider); } /** * Adds all protocol supported operation sets. * * @param protocolProvider The protocol provider. */ public void addProtocolSupportedOperationSets( ProtocolProviderService protocolProvider) { Map supportedOperationSets = protocolProvider.getSupportedOperationSets(); this.protocolSupportedOperationSets.put(protocolProvider, supportedOperationSets); String ppOpSetClassName = OperationSetPersistentPresence .class.getName(); String pOpSetClassName = OperationSetPresence.class.getName(); if (supportedOperationSets.containsKey(ppOpSetClassName) || supportedOperationSets.containsKey(pOpSetClassName)) { OperationSetPresence presence = (OperationSetPresence) supportedOperationSets.get(ppOpSetClassName); if(presence == null) { presence = (OperationSetPresence) supportedOperationSets.get(pOpSetClassName); } this.protocolPresenceSets.put(protocolProvider, presence); presence.addProviderPresenceStatusListener( new GUIProviderPresenceStatusListener()); presence.addContactPresenceStatusListener( new GUIContactPresenceStatusListener()); } String imOpSetClassName = OperationSetBasicInstantMessaging .class.getName(); if (supportedOperationSets.containsKey(imOpSetClassName)) { OperationSetBasicInstantMessaging im = (OperationSetBasicInstantMessaging) supportedOperationSets.get(imOpSetClassName); this.imOperationSets.put(protocolProvider, im); //Add to all instant messaging operation sets the Message //listener implemented in the ContactListPanel, which handles //all received messages. im.addMessageListener(this.getContactListPanel()); } String tnOpSetClassName = OperationSetTypingNotifications .class.getName(); if (supportedOperationSets.containsKey(tnOpSetClassName)) { OperationSetTypingNotifications tn = (OperationSetTypingNotifications) supportedOperationSets.get(tnOpSetClassName); this.tnOperationSets.put(protocolProvider, tn); //Add to all typing notification operation sets the Message //listener implemented in the ContactListPanel, which handles //all received messages. tn.addTypingNotificationsListener(this.getContactListPanel()); } String wciOpSetClassName = OperationSetWebContactInfo.class.getName(); if (supportedOperationSets.containsKey(wciOpSetClassName)) { OperationSetWebContactInfo wContactInfo = (OperationSetWebContactInfo) supportedOperationSets.get(wciOpSetClassName); this.webContactInfoOperationSets .put(protocolProvider, wContactInfo); } String telOpSetClassName = OperationSetBasicTelephony.class.getName(); if (supportedOperationSets.containsKey(telOpSetClassName)) { OperationSetBasicTelephony telephony = (OperationSetBasicTelephony) supportedOperationSets.get(telOpSetClassName); telephony.addCallListener(new GUICallListener()); this.protocolTelephonySets.put(protocolProvider, telephony); } } /** * Returns a set of all protocol providers. * * @return a set of all protocol providers. */ public Iterator getProtocolProviders() { return this.protocolProviders.keySet().iterator(); } /** * Returns the protocol provider associated to the account given * by the account user identifier. * * @param accountName The account user identifier. * @return The protocol provider associated to the given account. */ public ProtocolProviderService getProtocolProviderForAccount( String accountName) { Iterator i = this.protocolProviders.keySet().iterator(); while(i.hasNext()) { ProtocolProviderService pps = (ProtocolProviderService)i.next(); if (pps.getAccountID().getUserID().equals(accountName)) { return pps; } } return null; } /** * Adds a protocol provider. * @param protocolProvider The protocol provider to add. */ public void addProtocolProvider(ProtocolProviderService protocolProvider) { this.protocolProviders.put(protocolProvider, new Integer(initiateProviderIndex(protocolProvider))); this.addProtocolSupportedOperationSets(protocolProvider); this.addAccount(protocolProvider); } /** * Returns the index of the given protocol provider. * @param protocolProvider the protocol provider to search for * @return the index of the given protocol provider */ public int getProviderIndex(ProtocolProviderService protocolProvider) { Object o = protocolProviders.get(protocolProvider); if(o != null) { return ((Integer)o).intValue(); } return 0; } /** * Adds an account to the application. * * @param protocolProvider The protocol provider of the account. */ public void addAccount(ProtocolProviderService protocolProvider) { if (!getStatusPanel().containsAccount(protocolProvider)) { this.accounts.add(protocolProvider); this.getStatusPanel().addAccount(protocolProvider); //request the focus int the contact list panel, which //permits to search in the contact list this.tabbedPane.getContactListPanel().getContactList() .requestFocus(); } } /** * Adds an account to the application. * * @param protocolProvider The protocol provider of the account. */ public void removeProtocolProvider(ProtocolProviderService protocolProvider) { this.protocolProviders.remove(protocolProvider); this.updateProvidersIndexes(protocolProvider); if (getStatusPanel().containsAccount(protocolProvider)) { this.accounts.remove(protocolProvider); this.getStatusPanel().removeAccount(protocolProvider); } } /** * Activates an account. Here we start the connecting process. * * @param protocolProvider The protocol provider of this account. */ public void activateAccount(ProtocolProviderService protocolProvider) { this.getStatusPanel().startConnecting(protocolProvider); } /** * Returns the account user id for the given protocol provider. * @return The account user id for the given protocol provider. */ public String getAccount(ProtocolProviderService protocolProvider) { return protocolProvider.getAccountID().getUserID(); } /** * Returns the presence operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the * presence operation set is searched. * @return the presence operation set for the given protocol provider. */ public OperationSetPresence getProtocolPresence( ProtocolProviderService protocolProvider) { return (OperationSetPresence) this.protocolPresenceSets .get(protocolProvider); } /** * Returns the basic instant messaging(IM) operation set for the given * protocol provider. * * @param protocolProvider The protocol provider for which the IM * is searched. * @return OperationSetBasicInstantMessaging The IM for the given * protocol provider. */ public OperationSetBasicInstantMessaging getProtocolIM( ProtocolProviderService protocolProvider) { return (OperationSetBasicInstantMessaging) this.imOperationSets .get(protocolProvider); } /** * Returns the typing notifications(TN) operation set for the given * protocol provider. * * @param protocolProvider The protocol provider for which the TN * is searched. * @return OperationSetTypingNotifications The TN for the given * protocol provider. */ public OperationSetTypingNotifications getTypingNotifications( ProtocolProviderService protocolProvider) { return (OperationSetTypingNotifications) this.tnOperationSets .get(protocolProvider); } /** * Returns the Web Contact Info operation set for the given * protocol provider. * * @param protocolProvider The protocol provider for which the TN * is searched. * @return OperationSetWebContactInfo The Web Contact Info operation * set for the given protocol provider. */ public OperationSetWebContactInfo getWebContactInfo( ProtocolProviderService protocolProvider) { return (OperationSetWebContactInfo) this.webContactInfoOperationSets .get(protocolProvider); } /** * Returns the telephony operation set for the given protocol provider. * * @param protocolProvider The protocol provider for which the telephony * is searched. * @return OperationSetBasicTelephony The telephony operation * set for the given protocol provider. */ public OperationSetBasicTelephony getTelephony( ProtocolProviderService protocolProvider) { return (OperationSetBasicTelephony) this.protocolTelephonySets .get(protocolProvider); } /** * Returns the call manager. * @return CallManager The call manager. */ public CallManager getCallManager() { return callManager; } /** * Returns the quick menu, placed above the main tabbed pane. * @return QuickMenu The quick menu, placed above the main tabbed pane. */ public QuickMenu getQuickMenu() { return quickMenu; } /** * Returns the status panel. * @return StatusPanel The status panel. */ public StatusPanel getStatusPanel() { return statusPanel; } /** * Listens for all contactPresenceStatusChanged events in order * to refresh tha contact list, when a status is changed. */ private class GUIContactPresenceStatusListener implements ContactPresenceStatusListener { public void contactPresenceStatusChanged( ContactPresenceStatusChangeEvent evt) { ContactListPanel clistPanel = tabbedPane.getContactListPanel(); Contact sourceContact = evt.getSourceContact(); MetaContact metaContact = contactList .findMetaContactByContact(sourceContact); if (metaContact != null) { if(!evt.getOldStatus().equals(evt.getNewStatus())) { clistPanel.getContactList().refreshAll(); clistPanel.updateChatContactStatus( metaContact, sourceContact); } } } } /** * Listens for all providerStatusChanged and providerStatusMessageChanged * events in order to refresh the account status panel, when a status is * changed. */ private class GUIProviderPresenceStatusListener implements ProviderPresenceStatusListener { public void providerStatusChanged(ProviderPresenceStatusChangeEvent evt) { } public void providerStatusMessageChanged(PropertyChangeEvent evt) { } } /** * Listens for all CallReceivedEvents. */ private class GUICallListener implements CallListener { /** * This method is called by a protocol provider whenever an incoming call * is received. * @param event a CallEvent instance describing the new incoming * call */ public void incomingCallReceived(CallEvent event) { /**@todo implement incomingCallReceived() */ System.out.println("@todo implement incomingCallReceived()"); } /** * Indicates that all participants have left the source call and that it * has been ended. The event may be considered redundant since there are * already events issued upon termination of a single call participant but * we've decided to keep it for listeners that are only intersted in call * duration and don't want to follow other call details. * @param event the <tt>CallEvent</tt> containing the source call. */ public void callEnded(CallEvent event) { /**@todo implement incomingCallReceived() */ System.out.println("@todo implement incomingCallReceived()"); } public void outgoingCallCreated(CallEvent event) { // TODO Auto-generated method stub } } public Hashtable getWaitToBeDeliveredMsgs() { return waitToBeDeliveredMsgs; } /** * Returns the list of all groups. * @return The list of all groups. */ public Iterator getAllGroups() { return getContactListPanel() .getContactList().getAllGroups(); } /** * Returns the Meta Contact Group corresponding to the given MetaUID. * * @param metaUID An identifier of a group. * @return The Meta Contact Group corresponding to the given MetaUID. */ public MetaContactGroup getGroupByID(String metaUID) { return getContactListPanel() .getContactList().getGroupByID(metaUID); } /** * Before closing the application window saves the current size and position * through the <tt>ConfigurationService</tt>. */ public class MainFrameWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { ConfigurationService configService = GuiActivator.getConfigurationService(); try { configService.setProperty( "net.java.sip.communicator.impl.ui.mainWindowWidth", new Integer(getWidth())); configService.setProperty( "net.java.sip.communicator.impl.ui.mainWindowHeight", new Integer(getHeight())); configService.setProperty( "net.java.sip.communicator.impl.ui.mainWindowX", new Integer(getX())); configService.setProperty( "net.java.sip.communicator.impl.ui.mainWindowY", new Integer(getY())); configService.setProperty( "net.java.sip.communicator.impl.ui.showCallPanel", new Boolean(callManager.isShown())); } catch (PropertyVetoException e1) { logger.error("The proposed property change " + "represents an unacceptable value"); } } public void windowClosed(WindowEvent e) { try { GuiActivator.bundleContext.getBundle(0).stop(); } catch (BundleException ex) { logger.error("Failed to gently shutdown Oscar", ex); System.exit(0); } } } /** * Sets the window size and position. */ public void setSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String width = configService.getString( "net.java.sip.communicator.impl.ui.mainWindowWidth"); String height = configService.getString( "net.java.sip.communicator.impl.ui.mainWindowHeight"); String x = configService.getString( "net.java.sip.communicator.impl.ui.mainWindowX"); String y = configService.getString( "net.java.sip.communicator.impl.ui.mainWindowY"); String isShown = configService.getString( "net.java.sip.communicator.impl.ui.showCallPanel"); if(width != null && height != null) this.setSize(new Integer(width).intValue(), new Integer(height).intValue()); if(x != null && y != null) this.setLocation(new Integer(x).intValue(), new Integer(y).intValue()); if(isShown != null && isShown != "") { callManager.setShown(new Boolean(isShown).booleanValue()); } else { callManager.setShown(true); } } /** * Returns the class that manages user login. * @return the class that manages user login. */ public LoginManager getLoginManager() { return loginManager; } /** * Sets the class that manages user login. * @param loginManager The user login manager. */ public void setLoginManager(LoginManager loginManager) { this.loginManager = loginManager; } /** * Saves the last status for all accounts. This information is used * on loging. Each time user logs in he's logged with the same status * as he was the last time before closing the application. */ public void saveStatusInformation(ProtocolProviderService protocolProvider, PresenceStatus status) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.ui.accounts"; List accounts = configService .getPropertyNamesByPrefix(prefix, true); boolean savedAccount = false; Iterator accountsIter = accounts.iterator(); while(accountsIter.hasNext()) { String accountRootPropName = (String) accountsIter.next(); String accountUID = configService.getString(accountRootPropName); if(accountUID.equals(protocolProvider .getAccountID().getAccountUniqueID())) { configService.setProperty( accountRootPropName + ".lastAccountStatus", status.getStatusName()); savedAccount = true; } } if(!savedAccount) { String accNodeName = "acc" + Long.toString(System.currentTimeMillis()); String accountPackage = "net.java.sip.communicator.impl.ui.accounts." + accNodeName; configService.setProperty(accountPackage, protocolProvider.getAccountID().getAccountUniqueID()); configService.setProperty( accountPackage+".lastAccountStatus", status.getStatusName()); } } /** * Returns the panel containing the ContactList. * @return ContactListPanel the panel containing the ContactList */ public ContactListPanel getContactListPanel() { return this.tabbedPane.getContactListPanel(); } /** * Adds a tab in the main tabbed pane, where the given call panel * will be added. */ public void addCallPanel(CallPanel callPanel) { this.tabbedPane.addTab(callPanel.getTitle(), callPanel); this.tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); this.tabbedPane.revalidate(); } /** * Checks in the configuration xml if there is already stored index for * this provider and if yes, returns it, otherwise creates a new account * index and stores it. * * @param protocolProvider the protocol provider * @return the protocol provider index */ private int initiateProviderIndex( ProtocolProviderService protocolProvider) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.ui.accounts"; List accounts = configService .getPropertyNamesByPrefix(prefix, true); Iterator accountsIter = accounts.iterator(); boolean savedAccount = false; while(accountsIter.hasNext()) { String accountRootPropName = (String) accountsIter.next(); String accountUID = configService.getString(accountRootPropName); if(accountUID.equals(protocolProvider .getAccountID().getAccountUniqueID())) { savedAccount = true; String index = configService.getString( accountRootPropName + ".accountIndex"); if(index != null) { //if we have found the accountIndex for this protocol provider //return this index return new Integer(index).intValue(); } else { //if there's no stored accountIndex for this protocol //provider, calculate the index, set it in the configuration //service and return it. int accountIndex = createAccountIndex(protocolProvider, accountRootPropName); return accountIndex; } } } if(!savedAccount) { String accNodeName = "acc" + Long.toString(System.currentTimeMillis()); String accountPackage = "net.java.sip.communicator.impl.ui.accounts." + accNodeName; configService.setProperty(accountPackage, protocolProvider.getAccountID().getAccountUniqueID()); int accountIndex = createAccountIndex(protocolProvider, accountPackage); return accountIndex; } return -1; } /** * Creates and calculates the account index for the given protocol * provider. * @param protocolProvider the protocol provider * @param accountRootPropName the path to where the index should be saved * in the configuration xml * @return the created index */ private int createAccountIndex(ProtocolProviderService protocolProvider, String accountRootPropName) { ConfigurationService configService = GuiActivator.getConfigurationService(); int accountIndex = -1; Enumeration pproviders = protocolProviders.keys(); ProtocolProviderService pps; while(pproviders.hasMoreElements()) { pps = (ProtocolProviderService)pproviders.nextElement(); if(pps.getProtocolName().equals( protocolProvider.getProtocolName()) && !pps.equals(protocolProvider)) { int index = ((Integer)protocolProviders.get(pps)) .intValue(); if(accountIndex < index) { accountIndex = index; } } } accountIndex++; configService.setProperty( accountRootPropName + ".accountIndex", new Integer(accountIndex)); return accountIndex; } /** * Updates the indexes in the configuration xml, when a provider has been * removed. * @param removedProvider the removed protocol provider */ private void updateProvidersIndexes(ProtocolProviderService removedProvider) { ConfigurationService configService = GuiActivator.getConfigurationService(); String prefix = "net.java.sip.communicator.impl.ui.accounts"; Enumeration pproviders = protocolProviders.keys(); ProtocolProviderService currentProvider = null; int sameProtocolProvidersCount = 0; while(pproviders.hasMoreElements()) { ProtocolProviderService pps = (ProtocolProviderService)pproviders.nextElement(); if(pps.getProtocolName().equals( removedProvider.getProtocolName())) { sameProtocolProvidersCount++; if(sameProtocolProvidersCount > 1) { break; } currentProvider = pps; } } if(sameProtocolProvidersCount < 2 && currentProvider != null) { protocolProviders.put(currentProvider, new Integer(0)); List accounts = configService .getPropertyNamesByPrefix(prefix, true); Iterator accountsIter = accounts.iterator(); while(accountsIter.hasNext()) { String rootPropName = (String) accountsIter.next(); String accountUID = configService.getString(rootPropName); if(accountUID.equals(currentProvider .getAccountID().getAccountUniqueID())) { configService.setProperty( rootPropName + ".accountIndex", new Integer(0)); } } this.getStatusPanel().updateAccount(currentProvider); } } }
package placebooks.services; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StringReader; import java.net.Authenticator; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Vector; import javax.persistence.EntityManager; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import placebooks.controller.CommunicationHelper; import placebooks.controller.ItemFactory; import placebooks.controller.PropertiesSingleton; import placebooks.model.GPSTraceItem; import placebooks.model.ImageItem; import placebooks.model.LoginDetails; import placebooks.model.TextItem; import placebooks.model.User; import placebooks.services.model.EverytrailLoginResponse; import placebooks.services.model.EverytrailPicturesResponse; import placebooks.services.model.EverytrailResponseStatusData; import placebooks.services.model.EverytrailTripsResponse; /** * @author pszmp * */ public class EverytrailService extends Service { public final static String SERVICE_NAME = "Everytrail"; private final static String apiBaseUrl = "http: private static final Logger log = Logger.getLogger(EverytrailService.class.getName()); private String getPostResponseWithParams(final String postDestination, final Hashtable<String, String> params) { final StringBuilder postResponse = new StringBuilder(); // Add version 3 param to all requests params.put("version", "3"); // Construct data to post by iterating through parameter Hashtable keys Enumeration final StringBuilder data = new StringBuilder(); final Enumeration<String> paramNames = params.keys(); try { while (paramNames.hasMoreElements()) { final String paramName = paramNames.nextElement(); data.append(URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(params.get(paramName), "UTF-8")); if (paramNames.hasMoreElements()) { data.append("&"); } } // Send data by setting up the api password http authentication and UoN proxy Authenticator.setDefault(new CommunicationHelper.HttpAuthenticator(PropertiesSingleton.get( EverytrailService.class .getClassLoader()) .getProperty(PropertiesSingleton.EVERYTRAIL_API_USER, ""), PropertiesSingleton .get(EverytrailService.class.getClassLoader()) .getProperty(PropertiesSingleton.EVERYTRAIL_API_PASSWORD, ""))); final URL url = new URL(apiBaseUrl + postDestination); final URLConnection conn = CommunicationHelper.getConnection(url); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data.toString()); wr.flush(); // Get the response final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { postResponse.append(line); } wr.close(); rd.close(); } catch (final Exception ex) { log.debug(ex.getMessage()); } return postResponse.toString(); } /** * Return the success/error status of an Everytrail API call * * @param targetElementId * @return */ private EverytrailResponseStatusData parseResponseStatus(final String targetElementId, final Document doc) { String status = ""; String value = ""; try { if (doc.getDocumentElement().getNodeName() == targetElementId) { status = doc.getDocumentElement().getAttribute("status"); if(doc.getDocumentElement().hasChildNodes()) { if (status.equals("success")) { value = doc.getDocumentElement().getChildNodes().item(0).getTextContent(); } else { log.debug("Everytrail call returned status: " + status); value = doc.getDocumentElement().getChildNodes().item(0).getTextContent(); } } } } catch (final Exception e) { log.error("Problem checking Everytrail response: " + e.toString()); log.debug(e.toString(), e); } return new EverytrailResponseStatusData(status, value); } /** * Parse and Everytrail API response into an XML document from HTTP string response. * * @param Strung * Post response from everytrail http post * @return Document XML structured document */ private Document parseResponseToXml(final String postString) { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document doc = null; try { db = dbf.newDocumentBuilder(); final InputSource is = new InputSource(); is.setCharacterStream(new StringReader(postString)); doc = db.parse(is); doc.getDocumentElement().normalize(); } catch (final Exception ex) { log.equals("Problem parsing Everytrail XML response: " + ex.getMessage()); log.debug(ex.getStackTrace()); } return doc; } /** * Parse and Everytrail API response into an XML document from HTTP string response. * * @param StrungBuilder * Post response from everytrail http post * @return Document XML structured document */ private Document parseResponseToXml(final StringBuilder postResponse) { return parseResponseToXml(postResponse.toString()); } /** * Return a list of all pictures for a given user_id * * @param userId * @return EverytrailPicturesResponse */ public EverytrailPicturesResponse pictures(final String userId) { return Pictures(userId, null, null); } /** * Get a list of pictures for a given userid * * @param userId * an everytrail userid - supply their username and password if private pictures are * needed * @param String * A user's username * @param String * A user's password * @return EverytrailPicturesResponse */ private EverytrailPicturesResponse Pictures(final String userId, final String username, final String password) { // The pictures API doesn't work well, so get pictures via trips... final EverytrailTripsResponse tripsData = trips(username, password, userId); HashMap<String, Node> picturesToReturn = new HashMap<String, Node>(); HashMap<String, String> pictureTrips = new HashMap<String, String>(); HashMap<String, String> tripNames = new HashMap<String, String>(); String status_to_return = "error"; if (tripsData.getStatus().equals("error")) { log.warn("Get pictures failed when getting trips with error code: " + tripsData.getStatus()); //picturesToReturn = tripsData.getTrips(); } else { status_to_return = "success"; final Vector<Node> trips = tripsData.getTrips(); // log.debug("Got " + trips.size() + " trips, getting pictures..."); for (int tripListIndex = 0; tripListIndex < trips.size(); tripListIndex++) { final Node tripNode = trips.elementAt(tripListIndex); final NamedNodeMap attributes = tripNode.getAttributes(); final String tripId = attributes.getNamedItem("id").getNodeValue(); //Then look at the properties in the child nodes to get url, title, description, etc. final NodeList tripProperties = tripNode.getChildNodes(); String tripName = ""; for (int propertyIndex = 0; propertyIndex < tripProperties.getLength(); propertyIndex++) { final Node item = tripProperties.item(propertyIndex); final String itemName = item.getNodeName(); //log.debug("Inspecting property: " + itemName + " which is " + item.getTextContent()); if (itemName.equals("name")) { tripName = item.getTextContent(); } } log.debug("Getting pictures for trip: " + tripId + " " + tripName); tripNames.put(tripId, tripName); final EverytrailPicturesResponse tripPics = TripPictures(tripId, username, password, tripName); log.debug("Pictures in trip: " + tripPics.getPicturesMap().values().size()); final HashMap<String, Node> tripPicList = tripPics.getPicturesMap(); for (String pic_id : tripPicList.keySet()) { Node picture_node = tripPicList.get(pic_id); if (picture_node.getNodeName().equals("picture")) { picturesToReturn.put(pic_id, picture_node); pictureTrips.put(pic_id, tripId); } //log.debug("Picture: " + pic_id + " " + picture_node.getTextContent()); } } } final EverytrailPicturesResponse returnValue = new EverytrailPicturesResponse(status_to_return, picturesToReturn, pictureTrips, tripNames); return returnValue; } /** * Get a list of pictures for a particular trip including private pictures * * @param tripId * @param username * @param password * @return Vector<Node> */ private EverytrailPicturesResponse TripPictures(final String tripId, final String username, final String password, final String tripNameParam) { final Hashtable<String, String> params = new Hashtable<String, String>(); params.put("trip_id", tripId); if (username != null) { params.put("username", username); } if (password != null) { params.put("password", password); } String tripName = ""; final HashMap<String, Node> picturesList = new HashMap<String, Node>(); EverytrailResponseStatusData resultStatus = null; if(tripNameParam==null) { final String tripResponse = getPostResponseWithParams("trip/", params); final Document tripDoc = parseResponseToXml(tripResponse); final EverytrailResponseStatusData tripResultStatus = parseResponseStatus("etTripPicturesResponse", tripDoc); if (tripResultStatus.getStatus().equals("success")) { final NodeList nameNodes = tripDoc.getElementsByTagName("name");; // log.debug("Child nodes: " + pictureNodes.getLength()); for (int nameNodesIndex = 0; nameNodesIndex < nameNodes.getLength(); nameNodesIndex++) { final Node nameNode = nameNodes.item(nameNodesIndex); tripName = nameNode.getTextContent(); } } else { log.error("Can't get trip name"); } } else { tripName = tripNameParam; } final HashMap<String, String> tripData = new HashMap<String, String>(); tripData.put(tripId, tripName); final HashMap<String, String> pictureTrips = new HashMap<String, String>(); final String postResponse = getPostResponseWithParams("trip/pictures", params); final Document doc = parseResponseToXml(postResponse); resultStatus = parseResponseStatus("etTripPicturesResponse", doc); if (resultStatus.getStatus().equals("success")) { final NodeList pictureNodes = doc.getElementsByTagName("picture");; //log.debug("Child nodes: " + pictureNodes.getLength()); for (int pictureNodesIndex = 0; pictureNodesIndex < pictureNodes.getLength(); pictureNodesIndex++) { final Node pictureNode = pictureNodes.item(pictureNodesIndex); // Get pic ID final NamedNodeMap attr = pictureNode.getAttributes(); final String id = attr.getNamedItem("id").getNodeValue(); pictureTrips.put(id, tripId); picturesList.put(id, pictureNode); } } else { if (resultStatus.getStatus().equals("error")) { log.warn("Get pictures failed with error code: " + resultStatus.getValue()); log.debug(postResponse); } else { log.error("Get pictures error status gave unexpected value: " + resultStatus.getStatus()); } final NodeList response_list_data = doc.getElementsByTagName("error"); { for (int i = 0; i < response_list_data.getLength(); i++) { final Node element = response_list_data.item(i); final NodeList error_children = element.getChildNodes(); for (int child_counter = 0; child_counter < error_children.getLength(); child_counter++) { try { final Node error_element = error_children.item(child_counter); picturesList.put("0", error_element); } catch (final NullPointerException npx) { log.error("Can't interpret error data for item " + child_counter + " from response: " + resultStatus.getValue()); } } } } } return new EverytrailPicturesResponse(resultStatus.getStatus(), picturesList, pictureTrips, tripData); } /** * Return a list of all trips for a given user_id * * @param userId * an everytrail userid obtained from a user - user may need to be logged in first, * and this will at least get the user id * @return EverytrailTripsResponse */ public EverytrailTripsResponse trips(final String userId) { final EverytrailTripsResponse result = Trips(null, null, userId, null, null, null, null, null, null, null, null); return result; } /** * Return a list of all trips for a given user_id - return private pictures and trips if * username.password is given * * @param username * @param password * @param userId * an everytrail userid obtained from a user - user may need to be logged in first, * and this will at least get the user id * @return * @return EverytrailTripsResponse */ private EverytrailTripsResponse trips(final String username, final String password, final String userId) { final EverytrailTripsResponse result = Trips(username, password, userId, null, null, null, null, null, null, null, null); return result; } /** * Get a list of trips for a given userid * * @param userId * an everytrail userid obtained from a user - user may need to be logged in first, * and this will at least get the user id * @param limit * Number of photos to get, limit is 20 as default, set by everytrail API. * @param start * Starting point for photos, default 0 set by everytrail api * @return EverytrailTripsResponse */ private EverytrailTripsResponse Trips(final String username, final String password, final String userId, final Double lat, final Double lon, final Date modifiedAfter, final String sort, final String order, final String limit, final String start, final Boolean minimal) { final Hashtable<String, String> params = new Hashtable<String, String>(); params.put("user_id", userId); if (username != null) { params.put("username", username); } if (password != null) { params.put("password", password); } if (lat != null) { params.put("lat", lat.toString()); } if (lon != null) { params.put("lon", lon.toString()); } if (modifiedAfter != null) { final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); params.put("modified_after", formatter.format(modifiedAfter)); } if (sort != null) { params.put("sort", sort); } if (order != null) { params.put("order", order); } if (limit != null) { params.put("limit", limit); } if (limit != null) { params.put("start", start); } if (minimal != null) { params.put("minimal", minimal.toString()); } final String postResponse = getPostResponseWithParams("user/trips", params); log.info(postResponse); final Document doc = parseResponseToXml(postResponse); final EverytrailResponseStatusData responseStatus = parseResponseStatus("etUserTripsResponse", doc); log.info("Trips called parseResponseStatus, result=" + responseStatus.getStatus()); final Vector<Node> tripsList = new Vector<Node>(); if (responseStatus.getStatus().equals("success")) { final NodeList response_list_data = doc.getElementsByTagName("trip"); for (int i = 0; i < response_list_data.getLength(); i++) { final Node element = response_list_data.item(i); tripsList.add(element); } } else { final NodeList response_list_data = doc.getElementsByTagName("error"); { for (int i = 0; i < response_list_data.getLength(); i++) { final Node element = response_list_data.item(i); final NodeList error_children = element.getChildNodes(); for (int child_counter = 0; child_counter < error_children.getLength(); child_counter++) { try { final Node error_element = error_children.item(child_counter); tripsList.add(error_element); } catch (final NullPointerException npx) { log.error("Can't interpret error data for item " + child_counter + " from response: " + responseStatus.getValue()); } } } } } final EverytrailTripsResponse returnValue = new EverytrailTripsResponse(responseStatus.getStatus(), tripsList); return returnValue; } /** * Log in to the Everytrail API with a given username and password n.b. this appears to be * submitted as HTTP not HTTPS so password is potentially insecure. * * @param username * An everytrail username * @param password * An everytrail password * @return EverytrailLoginResponse with status success/error and value userid/error code */ public EverytrailLoginResponse userLogin(final String username, final String password) { final StringBuilder postResponse = new StringBuilder(); String loginStatus = ""; String loginStatusValue = ""; try { // Construct data to post - username and password String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); // Send data by setting up the api password http authentication and UoN proxy Authenticator.setDefault(new CommunicationHelper.HttpAuthenticator(PropertiesSingleton.get( EverytrailService.class .getClassLoader()) .getProperty(PropertiesSingleton.EVERYTRAIL_API_USER, ""), PropertiesSingleton .get(EverytrailService.class.getClassLoader()) .getProperty(PropertiesSingleton.EVERYTRAIL_API_PASSWORD, ""))); final URL url = new URL(apiBaseUrl + "user/login"); // Use getConnection to get the URLConnection with or without a proxy final URLConnection conn = CommunicationHelper.getConnection(url); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { postResponse.append(line); } wr.close(); rd.close(); } catch (final Exception e) { log.debug(e.getMessage()); } final Document doc = parseResponseToXml(postResponse); // Parse the XML response and construct the response data to return log.debug(postResponse); final EverytrailResponseStatusData responseStatus = parseResponseStatus("etUserLoginResponse", doc); log.info("UserLogin called parseResponseStatus, result=" + responseStatus.getStatus() + "," + responseStatus.getValue()); loginStatus = responseStatus.getStatus(); loginStatusValue = responseStatus.getValue(); log.debug(responseStatus.getStatus()); log.debug(responseStatus.getValue()); if (responseStatus.getStatus().equals("success")) { log.info("Log in succeeded with user id: " + responseStatus.getValue()); } else { if (doc.getDocumentElement().getAttribute("status").equals("error")) { log.warn("Log in failed with error code: " + loginStatusValue); } else { log.error("Everytrail login status gave unexpected value: " + loginStatusValue); } } final EverytrailLoginResponse output = new EverytrailLoginResponse(loginStatus, loginStatusValue); return output; } @Override protected void sync(EntityManager manager, User user, LoginDetails details) { try { final EverytrailLoginResponse loginResponse = userLogin(details.getUsername(), details.getPassword()); if (loginResponse.getStatus().equals("error")) { log.error("Everytrail login failed"); return; } // Save user id if needed if(loginResponse.getValue()!=details.getUserID()) { manager.getTransaction().begin(); details.setUserID(loginResponse.getValue()); manager.merge(details); manager.getTransaction().commit(); } ArrayList<String> imported_ids = new ArrayList<String>(); ArrayList<String> available_ids = new ArrayList<String>(); final EverytrailTripsResponse trips = trips(details.getUsername(), details.getPassword(), loginResponse.getValue()); for (Node trip : trips.getTrips()) { // Get trip ID final NamedNodeMap tripAttr = trip.getAttributes(); final String tripId = tripAttr.getNamedItem("id").getNodeValue(); log.debug("IMPORT: Trip ID is " + tripId + " **************"); String tripName = "Unknown trip"; String tripDescription = ""; //Then look at the properties in the child nodes to get url, title, description, etc. final NodeList tripProperties = trip.getChildNodes(); for (int propertyIndex = 0; propertyIndex < tripProperties.getLength(); propertyIndex++) { final Node item = tripProperties.item(propertyIndex); final String itemName = item.getNodeName(); //log.debug("Inspecting property: " + itemName + " which is " + item.getTextContent()); if (itemName.equals("name")) { log.debug("Trip name is: " + item.getTextContent()); tripName = item.getTextContent(); } if (itemName.equals("description")) { log.debug("Trip description is: " + item.getTextContent()); tripDescription = item.getTextContent(); } } available_ids.add("everytrail-" + tripId); if(tripDescription.length()>0) { TextItem descriptionItem = new TextItem(); descriptionItem.setOwner(user); final String externalId = "everytrail-" + tripId + "-textItem"; descriptionItem.setExternalID(externalId); descriptionItem.setText(tripDescription); descriptionItem.addMetadataEntry("source", SERVICE_NAME); descriptionItem.addMetadataEntryIndexed("trip_name", tripName); descriptionItem.addMetadataEntryIndexed("title", tripName); descriptionItem.addMetadataEntry("trip", tripId); descriptionItem.saveUpdatedItem(); available_ids.add(externalId); imported_ids.add(externalId); } GPSTraceItem gpsItem = new GPSTraceItem(user); try { ItemFactory.toGPSTraceItem(user, trip, gpsItem, tripId, tripName); gpsItem = (GPSTraceItem) gpsItem.saveUpdatedItem(); imported_ids.add(gpsItem.getExternalID()); } catch(Exception e) { log.error("Problem importing Trip " + tripId, e); } final EverytrailPicturesResponse picturesResponse = TripPictures( tripId, details.getUsername(), details.getPassword(), tripName); final HashMap<String, Node> pictures = picturesResponse.getPicturesMap(); int i = 0; for (final Node picture : pictures.values()) { log.info("Processing picture " + i++); ImageItem imageItem = new ImageItem(user, null, null, null); ItemFactory.toImageItem(user, picture, imageItem, tripId, tripName); imageItem = (ImageItem) imageItem.saveUpdatedItem(); imported_ids.add(imageItem.getExternalID()); available_ids.add(imageItem.getExternalID()); } } int itemsDeleted = cleanupItems(manager, imported_ids, user); details.setLastSync(); log.info("Finished Everytrail import, " + imported_ids.size() + " items added/updated, " + itemsDeleted + " removed"); } finally { if (manager.getTransaction().isActive()) { manager.getTransaction().rollback(); } } } @Override public String getName() { return SERVICE_NAME; } @Override public boolean checkLogin(String username, String password) { EverytrailLoginResponse response = userLogin(username, password); log.info(response.getStatus() + ":" + response.getValue()); if (response.getStatus().equals("error")) { return false; } return true; } }
package me.iyanuadelekan.paystackjava.core; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.json.JSONObject; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import static org.apache.http.conn.ssl.SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; /** * @author Iyanu Adelekan on 17/07/2016. */ public class ApiConnection { private String url; private String apiKey; /** * @param url - Paystack API URL */ public ApiConnection(String url) { this.url = url; Keys keys = new Keys(); try { keys.initKeys(); } catch (FileNotFoundException e) { System.out.print("Required Keys.json file could not be found."); e.printStackTrace(); } this.apiKey = keys.KEY_IN_USE; this.enforceTlsV1point2(); } private void enforceTlsV1point2() { try { SSLContext sslContext = SSLContexts.custom() .useTLS() .build(); SSLConnectionSocketFactory f = new SSLConnectionSocketFactory( sslContext, new String[]{"TLSv1.2"}, null, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(f) .build(); Unirest.setHttpClient(httpClient); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ApiConnection.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(ApiConnection.class.getName()).log(Level.SEVERE, null, ex); } } /** * Connects to and queries Paystack API with POST * @param query - APIQuery containing parameters to send * @return - JSONObject containing API response */ public JSONObject connectAndQuery(ApiQuery query) { try { HttpResponse<JsonNode> queryForResponse = Unirest.post(url) .header("Accept","application/json") .header("Authorization","Bearer " + apiKey) .fields(query.getParams()) .asJson(); return queryForResponse.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return null; } /** * Connects to and queries API with POST * @param query - HashMap containing parameters to send * @return - JSONObject containing API response */ public JSONObject connectAndQuery(HashMap<String,Object> query) { try { HttpResponse<JsonNode> queryForResponse = Unirest.post(url) .header("Accept","application/json") .header("Authorization","Bearer " + apiKey) .fields(query) .asJson(); return queryForResponse.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return null; } /** * Used to send a GET request to the Paystack API * @return - JSONObject containing the API response */ public JSONObject connectAndQueryWithGet(){ try { HttpResponse<JsonNode> queryForResponse = Unirest.get(url) .header("Accept","application/json") .header("Authorization","Bearer " + apiKey) .asJson(); return queryForResponse.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return null; } /** * Used to send a GET request to the Paystack API * @param query - APIQuery containing parameters to send * @return - JSONObject containing API response */ public JSONObject connectAndQueryWithGet(ApiQuery query){ try { HttpResponse<JsonNode> queryForResponse = Unirest.get(url) .header("Accept","application/json") .header("Authorization","Bearer " + apiKey) .queryString(query.getParams()) .asJson(); return queryForResponse.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return null; } /** * Used to send a GET request to the Paystack API * @param query - HashMap containing parameters to send * @return - JSONObject containing API response */ public JSONObject connectAndQueryWithGet(HashMap<String,Object> query) { try { HttpResponse<JsonNode> queryForResponse = Unirest.get(url) .header("Accept","application/json") .header("Authorization","Bearer " + apiKey) .queryString(query) .asJson(); return queryForResponse.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return null; } /** * Used to send a PUT request to the Paystack API * @param query - APIQuery containing parameters to send * @return - JSONObject containing API response */ public JSONObject connectAndQueryWithPut(ApiQuery query) { try { HttpResponse<JsonNode> queryForResponse = Unirest.put(url) .header("Accept","application/json") .header("Authorization","Bearer " + apiKey) .fields(query.getParams()) .asJson(); return queryForResponse.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return null; } /** * Used to send a PUT request to the Paystack API * @param query - HashMap containing parameters to send * @return - JSONObject containing API response */ public JSONObject connectAndQueryWithPut(HashMap<String,Object> query) { try { HttpResponse<JsonNode> queryForResponse = Unirest.get(url) .header("Accept","application/json") .header("Authorization","Bearer " + apiKey) .queryString(query) .asJson(); return queryForResponse.getBody().getObject(); } catch (UnirestException e) { e.printStackTrace(); } return null; } /** * Called to shut down the background event loop */ public static void shutDown() { try { Unirest.shutdown(); } catch (IOException e) { e.printStackTrace(); } } }
package market.roles; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Semaphore; import market.MarketInvoice; import market.MarketOrder; import market.MarketOrder.EnumOrderEvent; import market.MarketOrder.EnumOrderStatus; import market.gui.MarketCustomerGui; import market.gui.MarketPanel; import market.interfaces.MarketCashier; import market.interfaces.MarketCustomer; import base.BaseRole; import base.ContactList; import base.Item.EnumItemType; import base.interfaces.Person; public class MarketCustomerRole extends BaseRole implements MarketCustomer { private static final Integer DEFAULT_FOOD_QTY = null; //DATA //mCash accessed from Person private MarketCustomerGui mGui; private Semaphore inTransit = new Semaphore(0,true); List<MarketOrder> mOrders = Collections.synchronizedList(new ArrayList<MarketOrder>()); List<MarketInvoice> mInvoices = Collections.synchronizedList(new ArrayList<MarketInvoice>()); Map<EnumItemType, Integer> mItemInventory = Collections.synchronizedMap(new HashMap<EnumItemType, Integer>()); Map<EnumItemType, Integer> mItemsDesired = Collections.synchronizedMap(new HashMap<EnumItemType,Integer>()); Map<EnumItemType, Integer> mCannotFulfill = new HashMap<EnumItemType, Integer>(); MarketCashier mCashier; public MarketCustomerRole(Person person) { super(person); mCashier = MarketPanel.getInstance().mCashier; mGui = new MarketCustomerGui(this); MarketPanel.getInstance().addGui(mGui); // mItemInventory = mPerson.getItemInventory(); //ANGELICA: hack for now //mItemsDesired = mPerson.getItemsDesired(); //populate inventory mItemInventory.put(EnumItemType.STEAK,DEFAULT_FOOD_QTY); mItemInventory.put(EnumItemType.CHICKEN,DEFAULT_FOOD_QTY); mItemInventory.put(EnumItemType.SALAD,DEFAULT_FOOD_QTY); mItemInventory.put(EnumItemType.PIZZA,DEFAULT_FOOD_QTY); mItemsDesired.put(EnumItemType.SALAD,2); mItemsDesired.put(EnumItemType.PIZZA,1); } //MESSAGES public void msgInvoiceToPerson(Map<EnumItemType, Integer> cannotFulfill, MarketInvoice invoice) { mInvoices.add(invoice); mCannotFulfill = cannotFulfill; invoice.mOrder.mEvent = EnumOrderEvent.RECEIVED_INVOICE; stateChanged(); } public void msgHereIsCustomerOrder(MarketOrder order){ order.mEvent = EnumOrderEvent.RECEIVED_ORDER; stateChanged(); } /* Animation Messages */ public void msgAnimationAtMarket() { inTransit.release(); } public void msgAnimationAtWaitingArea() { inTransit.release(); } public void msgAnimationLeftMarket() { inTransit.release(); } //SCHEDULER public boolean pickAndExecuteAnAction(){ for(MarketInvoice invoice : mInvoices) { MarketOrder order = invoice.mOrder; if(order.mStatus == EnumOrderStatus.PAYING && order.mEvent == EnumOrderEvent.RECEIVED_INVOICE) { order.mStatus = EnumOrderStatus.PAID; payAndProcessOrder(invoice); return true; } } for(MarketOrder order : mOrders) { if(order.mStatus == EnumOrderStatus.FULFILLING && order.mEvent == EnumOrderEvent.RECEIVED_ORDER) { order.mStatus = EnumOrderStatus.DONE; completeOrder(order); return true; } } for(MarketOrder order : mOrders) { if(order.mStatus == EnumOrderStatus.CARTED) { order.mStatus = EnumOrderStatus.PLACED; placeOrder(order); return true; } } //check efficiency of method synchronized(mItemsDesired) { for(EnumItemType iType : mItemsDesired.keySet()) { if(mItemsDesired.get(iType) != 0) { createOrder(); return true; } } } return false; } //ACTIONS private void createOrder(){ Do("ordering"); HashMap<EnumItemType,Integer> items = new HashMap<EnumItemType,Integer>(); for(EnumItemType iItemType : mItemsDesired.keySet()) { items.put(iItemType,mItemsDesired.get(iItemType)); mItemsDesired.put(iItemType,0); } MarketOrder order = new MarketOrder(items, this); mOrders.add(order); } private void placeOrder(MarketOrder order){ DoGoToMarket(); mCashier.msgOrderPlacement(order); } private void payAndProcessOrder(MarketInvoice invoice) { invoice.mPayment += invoice.mTotal; ContactList.SendPayment(mPerson.getSSN(), invoice.mMarketBankNumber, invoice.mPayment); synchronized(mItemsDesired) { for(EnumItemType item : mCannotFulfill.keySet()) { mItemsDesired.put(item, mItemsDesired.get(item)+mCannotFulfill.get(item)); } } mCashier.msgPayingForOrder(invoice); mInvoices.remove(invoice); DoWaitForOrder(); } private void completeOrder(MarketOrder order) { for(EnumItemType item : order.mItems.keySet()) { int n = mItemInventory.get(item); n += order.mItems.get(item); mItemInventory.put(item, n); } DoLeaveMarket(); } /* Animation Actions */ private void DoGoToMarket() { mGui.DoGoToMarket(); try { inTransit.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } private void DoWaitForOrder() { mGui.DoWaitForOrder(); try { inTransit.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } private void DoLeaveMarket() { mGui.DoLeaveMarket(); try { inTransit.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } /* Utilities */ public void setGui(MarketCustomerGui g) { mGui = g; } }
package jenkins.install; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.ExtensionList; import hudson.ExtensionPoint; import java.util.logging.Level; import java.util.logging.Logger; import hudson.model.UpdateCenter; import jenkins.model.Jenkins; import jenkins.model.JenkinsLocationConfiguration; import jenkins.security.apitoken.ApiTokenPropertyConfiguration; import jenkins.security.stapler.StaplerAccessibleType; import jenkins.util.Timer; import org.apache.commons.lang.StringUtils; /** * Jenkins install state. * * In order to hook into the setup wizard lifecycle, you should * include something in a script that call * to {@code onSetupWizardInitialized} with a callback * * @author <a href="mailto:tom.fennelly@gmail.com">tom.fennelly@gmail.com</a> */ @StaplerAccessibleType public class InstallState implements ExtensionPoint { /** * Only here for XStream compatibility. <p> * * Please DO NOT ADD ITEM TO THIS LIST. <p> * If you add an item here, the deserialization process will break * because it is used for serialized state like "jenkins.install.InstallState$4" * before the change from anonymous class to named class. If you need to add a new InstallState, you can just add a new inner named class but nothing to change in this list. * * @see #readResolve */ @Deprecated @SuppressWarnings("MismatchedReadAndWriteOfArray") private static final InstallState[] UNUSED_INNER_CLASSES = { new InstallState("UNKNOWN", false) {}, new InstallState("INITIAL_SETUP_COMPLETED", false) {}, new InstallState("CREATE_ADMIN_USER", false) {}, new InstallState("INITIAL_SECURITY_SETUP", false) {}, new InstallState("RESTART", false) {}, new InstallState("DOWNGRADE", false) {}, }; /** * Need InstallState != NEW for tests by default */ @Extension public static final InstallState UNKNOWN = new Unknown(); private static class Unknown extends InstallState { Unknown() { super("UNKNOWN", true); } @Override public void initializeState() { InstallUtil.proceedToNextStateFrom(this); } } /** * After any setup / restart / etc. hooks are done, states should be running */ @Extension public static final InstallState RUNNING = new InstallState("RUNNING", true); /** * The initial set up has been completed */ @Extension public static final InstallState INITIAL_SETUP_COMPLETED = new InitialSetupCompleted(); private static final class InitialSetupCompleted extends InstallState { InitialSetupCompleted() { super("INITIAL_SETUP_COMPLETED", true); } public void initializeState() { Jenkins j = Jenkins.get(); try { j.getSetupWizard().completeSetup(); } catch (Exception e) { throw new RuntimeException(e); } j.setInstallState(RUNNING); } } /** * Creating an admin user for an initial Jenkins install. */ @Extension public static final InstallState CREATE_ADMIN_USER = new CreateAdminUser(); private static final class CreateAdminUser extends InstallState { CreateAdminUser() { super("CREATE_ADMIN_USER", false); } public void initializeState() { Jenkins j = Jenkins.get(); // Skip this state if not using the security defaults // e.g. in an init script set up security already if (!j.getSetupWizard().isUsingSecurityDefaults()) { InstallUtil.proceedToNextStateFrom(this); } } } @Extension public static final InstallState CONFIGURE_INSTANCE = new ConfigureInstance(); private static final class ConfigureInstance extends InstallState { ConfigureInstance() { super("CONFIGURE_INSTANCE", false); } public void initializeState() { // Skip this state if a boot script already configured the root URL // in case we add more fields in this page, this should be adapted if (StringUtils.isNotBlank(JenkinsLocationConfiguration.getOrDie().getUrl())) { InstallUtil.proceedToNextStateFrom(this); } } } /** * New Jenkins install. The user has kicked off the process of installing an * initial set of plugins (via the install wizard). */ @Extension public static final InstallState INITIAL_PLUGINS_INSTALLING = new InstallState("INITIAL_PLUGINS_INSTALLING", false); /** * Security setup for a new Jenkins install. */ @Extension public static final InstallState INITIAL_SECURITY_SETUP = new InitialSecuritySetup(); private static final class InitialSecuritySetup extends InstallState { InitialSecuritySetup() { super("INITIAL_SECURITY_SETUP", false); } public void initializeState() { try { Jenkins.get().getSetupWizard().init(true); } catch (Exception e) { throw new RuntimeException(e); } InstallUtil.proceedToNextStateFrom(INITIAL_SECURITY_SETUP); } } /** * New Jenkins install. */ @Extension public static final InstallState NEW = new InstallState("NEW", false); /** * Restart of an existing Jenkins install. */ @Extension public static final InstallState RESTART = new Restart(); private static final class Restart extends InstallState { Restart() { super("RESTART", true); } public void initializeState() { InstallUtil.saveLastExecVersion(); } } /** * Upgrade of an existing Jenkins install. */ @Extension public static final InstallState UPGRADE = new Upgrade(); private static final class Upgrade extends InstallState { Upgrade() { super("UPGRADE", true); } @Override public void initializeState() { applyForcedChanges(); // Schedule an update of the update center after a Jenkins upgrade reloadUpdateSiteData(); InstallUtil.saveLastExecVersion(); } /** * Put here the different changes that are enforced after an update. */ private void applyForcedChanges(){ // Disable the legacy system of API Token only if the new system was not installed // in such case it means there was already an upgrade before // and potentially the admin has re-enabled the features ApiTokenPropertyConfiguration apiTokenPropertyConfiguration = ApiTokenPropertyConfiguration.get(); if(!apiTokenPropertyConfiguration.hasExistingConfigFile()){ LOGGER.log(Level.INFO, "New API token system configured with insecure options to keep legacy behavior"); apiTokenPropertyConfiguration.setCreationOfLegacyTokenEnabled(false); apiTokenPropertyConfiguration.setTokenGenerationOnCreationEnabled(false); } } } private static void reloadUpdateSiteData() { Timer.get().submit(UpdateCenter::updateAllSitesNow); } /** * Downgrade of an existing Jenkins install. */ @Extension public static final InstallState DOWNGRADE = new Downgrade(); private static final class Downgrade extends InstallState { Downgrade() { super("DOWNGRADE", true); } public void initializeState() { // Schedule an update of the update center after a Jenkins downgrade reloadUpdateSiteData(); InstallUtil.saveLastExecVersion(); } } private static final Logger LOGGER = Logger.getLogger(InstallState.class.getName()); /** * Jenkins started in test mode (JenkinsRule). */ public static final InstallState TEST = new InstallState("TEST", true); /** * Jenkins started in development mode: Boolean.getBoolean("hudson.Main.development"). * Can be run normally with the -Djenkins.install.runSetupWizard=true */ public static final InstallState DEVELOPMENT = new InstallState("DEVELOPMENT", true); private final transient boolean isSetupComplete; /** * Link with the pluginSetupWizardGui.js map: "statsHandlers" */ private final String name; public InstallState(@NonNull String name, boolean isSetupComplete) { this.name = name; this.isSetupComplete = isSetupComplete; } /** * Process any initialization this install state requires */ public void initializeState() { } /** * The actual class name is irrelevant; this is functionally an enum. * <p>Creating a {@code writeReplace} does not help much since XStream then just saves: * {@code <installState class="jenkins.install.InstallState$CreateAdminUser" resolves-to="jenkins.install.InstallState">} * @see #UNUSED_INNER_CLASSES * @deprecated Should no longer be used, as {@link Jenkins} now saves only {@link #name}. */ @Deprecated protected Object readResolve() { // If we get invalid state from the configuration, fallback to unknown if (StringUtils.isBlank(name)) { LOGGER.log(Level.WARNING, "Read install state with blank name: ''{0}''. It will be ignored", name); return UNKNOWN; } InstallState state = InstallState.valueOf(name); if (state == null) { LOGGER.log(Level.WARNING, "Cannot locate an extension point for the state ''{0}''. It will be ignored", name); return UNKNOWN; } // Otherwise we return the actual state return state; } /** * Indicates the initial setup is complete */ public boolean isSetupComplete() { return isSetupComplete; } public String name() { return name; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if(obj instanceof InstallState) { return name.equals(((InstallState)obj).name()); } return false; } @Override public String toString() { return "InstallState (" + name + ")"; } /** * Find an install state by name * @param name * @return */ @CheckForNull public static InstallState valueOf(@NonNull String name) { for (InstallState state : all()) { if (name.equals(state.name)) { return state; } } return null; } /** * Returns all install states in the system */ static ExtensionList<InstallState> all() { return ExtensionList.lookup(InstallState.class); } }
package org.col.db.mapper; import com.google.common.base.Throwables; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.apache.ibatis.io.Resources; import org.apache.ibatis.jdbc.ScriptRunner; import org.apache.ibatis.session.SqlSessionFactory; import org.col.db.MybatisFactory; import org.junit.rules.ExternalResource; import ru.yandex.qatools.embed.postgresql.EmbeddedPostgres; import ru.yandex.qatools.embed.postgresql.distribution.Version; import java.io.IOException; import java.net.ServerSocket; import java.sql.Connection; import java.sql.SQLException; import java.time.Duration; import java.time.Instant; import static org.col.db.PgConfig.SCHEMA_FILE; /** * A junit test rule that starts up an {@link EmbeddedPostgres} server together * with a {@link HikariDataSource} and stops both at the end. The rule was * designed to share the server across all tests of a test class if it runs as a * static {@link org.junit.ClassRule}. * * It can even be used to share the same postgres server across several test * classes if it is used in as a {@link org.junit.ClassRule} in a TestSuite. */ public class PgSetupRule extends ExternalResource { private static EmbeddedPostgres postgres; private static HikariDataSource dataSource; private static SqlSessionFactory sqlSessionFactory; private boolean startedHere = false; // switch this for local testing to false // Note: DO NOT COMMIT false or jenkins will fail! private static final boolean embeddedPg = true; private static final String database = "colplus"; private static final String user = "postgres"; private static final String password = "postgres"; public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } public static SqlSessionFactory getSqlSessionFactory() throws SQLException { return sqlSessionFactory; } @Override protected void before() throws Throwable { super.before(); if (postgres == null) { startDb(); startedHere = true; initDb(); } } private void startDb() { try { String url; if (embeddedPg) { System.out.println("Starting Postgres"); Instant start = Instant.now(); postgres = new EmbeddedPostgres(Version.V10_0); // assigned some free port using local socket 0 url = postgres.start("localhost", new ServerSocket(0).getLocalPort(), database, user, password); System.out.format("Pg startup time: %s ms\n", Duration.between(start, Instant.now()).toMillis()); } else { System.out.println("Use external, local Postgres server on database " + database); url = "jdbc:postgresql://localhost/" + database; } HikariConfig hikari = new HikariConfig(); hikari.setJdbcUrl(url); hikari.setUsername(user); hikari.setPassword(password); hikari.setMaximumPoolSize(2); hikari.setMinimumIdle(1); hikari.setAutoCommit(false); dataSource = new HikariDataSource(hikari); // configure single mybatis session factory sqlSessionFactory = MybatisFactory.configure(dataSource, "test"); } catch (Exception e) { System.err.println("Pg startup error: " + e.getMessage()); e.printStackTrace(); if (dataSource != null) { dataSource.close(); } if (postgres != null) { postgres.stop(); } Throwables.propagate(e); } } private void initDb() { try (Connection con = dataSource.getConnection()) { System.out.println("Init empty database schema\n"); ScriptRunner runner = new ScriptRunner(con); runner.runScript(Resources.getResourceAsReader(SCHEMA_FILE)); con.commit(); } catch (SQLException | IOException e) { Throwables.propagate(e); } } @Override public void after() { if (startedHere) { System.out.println("Shutdown dbpool"); dataSource.close(); if (postgres != null) { System.out.println("Stopping Postgres"); postgres.stop(); } } } }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeContainer; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.ui.ArbilTable; import nl.mpi.arbil.ui.ArbilTableModel; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.kindata.GraphSorter; import nl.mpi.kinnate.svg.GraphPanel; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.EntityService; import nl.mpi.kinnate.entityindexer.EntityServiceException; import nl.mpi.kinnate.entityindexer.QueryParser; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import nl.mpi.kinnate.kintypestrings.KinTypeStringConverter; import nl.mpi.kinnate.kintypestrings.ParserHighlight; public class KinDiagramPanel extends JPanel implements SavePanel, KinTermSavePanel, ArbilDataNodeContainer { private EntityCollection entityCollection; private JTextPane kinTypeStringInput; private GraphPanel graphPanel; private GraphSorter graphSorter; private EgoSelectionPanel egoSelectionPanel; private HidePane kinTermHidePane; private HidePane kinTypeHidePane; private KinTermTabPane kinTermPanel; private EntityService entityIndex; private JProgressBar progressBar; public ArbilTable imdiTable; private HashMap<UniqueIdentifier, ArbilDataNode> registeredArbilDataNode; private String defaultString = "# The kin type strings entered here will determine how the entities show on the graph below\n"; public static String defaultGraphString = "# The kin type strings entered here will determine how the entities show on the graph below\n" + "# Enter one string per line.\n" //+ "# By default all relations of the selected entity will be shown.\n" + "# for example:\n" // + "EmWMMM\n" // + "E:1:FFE\n" // + "EmWMMM:1:\n" // + "E:1:FFE\n" + "Em:Charles II of Spain:W:Marie Louise d'Orlans\n" + "Em:Charles II of Spain:F:Philip IV of Spain:F:Philip III of Spain:F:Philip II of Spain:F:Charles V, Holy Roman Emperor:F:Philip I of Castile\n" + "Em:Charles II of Spain:M:Mariana of Austria:M:Maria Anna of Spain:M:Margaret of Austria:M:Maria Anna of Bavaria\n" + "M:Mariana of Austria:F:Ferdinand III, Holy Roman Emperor:\n" + "F:Philip IV of Spain:M:Margaret of Austria\n" + "F:Ferdinand III, Holy Roman Emperor:\n" + "M:Maria Anna of Spain:\n" + "F:Philip III of Spain\n" + "M:Margaret of Austria\n" + "\n"; // + "FS:1:BSSWMDHFF:1:\n" // + "M:2:SSDHMFM:2:\n" // + "F:3:SSDHMF:3:\n" // + "E=[Bob]MFM\n" // + "E=[Bob]MZ\n" // + "E=[Bob]F\n" // + "E=[Bob]M\n" // + "E=[Bob]S"; // private String kinTypeStrings[] = new String[]{}; Color commentColour = Color.GRAY; public KinDiagramPanel(File existingFile) { entityCollection = new EntityCollection(); progressBar = new JProgressBar(); EntityData[] svgStoredEntities = null; graphPanel = new GraphPanel(this); kinTypeStringInput = new JTextPane(); kinTypeStringInput.setText(defaultString); kinTypeStringInput.setForeground(commentColour); if (existingFile != null && existingFile.exists()) { svgStoredEntities = graphPanel.readSvg(existingFile); String kinTermContents = null; for (String currentKinTypeString : graphPanel.getKinTypeStrigs()) { if (currentKinTypeString.trim().length() > 0) { if (kinTermContents == null) { kinTermContents = ""; } else { kinTermContents = kinTermContents + "\n"; } kinTermContents = kinTermContents + currentKinTypeString.trim(); } } kinTypeStringInput.setText(kinTermContents); } else { graphPanel.generateDefaultSvg(); } this.setLayout(new BorderLayout()); ArbilTableModel imdiTableModel = new ArbilTableModel(); graphPanel.setArbilTableModel(imdiTableModel); graphPanel.add(progressBar, BorderLayout.PAGE_END); imdiTable = new ArbilTable(imdiTableModel, "Selected Nodes"); TableCellDragHandler tableCellDragHandler = new TableCellDragHandler(); imdiTable.setTransferHandler(tableCellDragHandler); imdiTable.setDragEnabled(true); registeredArbilDataNode = new HashMap<UniqueIdentifier, ArbilDataNode>(); egoSelectionPanel = new EgoSelectionPanel(imdiTable, graphPanel); kinTermPanel = new KinTermTabPane(this, graphPanel.getkinTermGroups()); // set the styles for the kin type string text Style styleComment = kinTypeStringInput.addStyle("Comment", null); // StyleConstants.setForeground(styleComment, new Color(247,158,9)); StyleConstants.setForeground(styleComment, commentColour); Style styleKinType = kinTypeStringInput.addStyle("KinType", null); StyleConstants.setForeground(styleKinType, new Color(43, 32, 161)); Style styleQuery = kinTypeStringInput.addStyle("Query", null); StyleConstants.setForeground(styleQuery, new Color(183, 7, 140)); Style styleParamater = kinTypeStringInput.addStyle("Parameter", null); StyleConstants.setForeground(styleParamater, new Color(103, 7, 200)); Style styleError = kinTypeStringInput.addStyle("Error", null); // StyleConstants.setForeground(styleError, new Color(172,3,57)); StyleConstants.setForeground(styleError, Color.RED); Style styleUnknown = kinTypeStringInput.addStyle("Unknown", null); StyleConstants.setForeground(styleUnknown, Color.BLACK); // kinTypeStringInput.setText(defaultString); JPanel kinGraphPanel = new JPanel(new BorderLayout()); kinTypeHidePane = new HidePane(HidePane.HidePanePosition.top, 0); kinTypeHidePane.add(new JScrollPane(kinTypeStringInput), "Kin Type Strings"); IndexerParametersPanel indexerParametersPanel = new IndexerParametersPanel(this, graphPanel, tableCellDragHandler); JPanel advancedPanel = new JPanel(new BorderLayout()); JScrollPane tableScrollPane = new JScrollPane(imdiTable); advancedPanel.add(tableScrollPane, BorderLayout.CENTER); HidePane indexParamHidePane = new HidePane(HidePane.HidePanePosition.right, 0); indexParamHidePane.add(indexerParametersPanel, "Indexer Parameters"); advancedPanel.add(indexParamHidePane, BorderLayout.LINE_END); HidePane tableHidePane = new HidePane(HidePane.HidePanePosition.bottom, 0); tableHidePane.add(advancedPanel, "Metadata"); KinDragTransferHandler dragTransferHandler = new KinDragTransferHandler(); this.setTransferHandler(dragTransferHandler); EntitySearchPanel entitySearchPanel = new EntitySearchPanel(entityCollection, graphPanel, imdiTable); entitySearchPanel.setTransferHandler(dragTransferHandler); HidePane egoSelectionHidePane = new HidePane(HidePane.HidePanePosition.left, 0); egoSelectionHidePane.add(egoSelectionPanel, "Ego Selection"); egoSelectionHidePane.add(entitySearchPanel, "Search Entities"); kinTermHidePane = new HidePane(HidePane.HidePanePosition.right, 0); kinTermHidePane.add(kinTermPanel, "Kin Terms"); kinTermHidePane.add(new ArchiveEntityLinkerPanel(imdiTable), "Archive Linker"); kinGraphPanel.add(kinTypeHidePane, BorderLayout.PAGE_START); kinGraphPanel.add(egoSelectionHidePane, BorderLayout.LINE_START); kinGraphPanel.add(graphPanel, BorderLayout.CENTER); kinGraphPanel.add(kinTermHidePane, BorderLayout.LINE_END); kinGraphPanel.add(tableHidePane, BorderLayout.PAGE_END); this.add(kinGraphPanel); entityIndex = new QueryParser(svgStoredEntities); graphSorter = new GraphSorter(); kinTypeStringInput.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { if (kinTypeStringInput.getText().equals(defaultString)) { kinTypeStringInput.setText(""); // kinTypeStringInput.setForeground(Color.BLACK); } } public void focusLost(FocusEvent e) { if (kinTypeStringInput.getText().length() == 0) { kinTypeStringInput.setText(defaultString); kinTypeStringInput.setForeground(commentColour); } } }); kinTypeStringInput.addKeyListener(new KeyListener() { String previousKinTypeStrings = null; public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { synchronized (e) { if (previousKinTypeStrings == null || !previousKinTypeStrings.equals(kinTypeStringInput.getText())) { graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n")); // kinTypeStrings = graphPanel.getKinTypeStrigs(); drawGraph(); previousKinTypeStrings = kinTypeStringInput.getText(); } } } }); } public void createDefaultGraph(String defaultGraphString) { kinTypeStringInput.setText(defaultGraphString); graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n")); drawGraph(); } public void drawGraph() { try { String[] kinTypeStrings = graphPanel.getKinTypeStrigs(); ParserHighlight[] parserHighlight = new ParserHighlight[kinTypeStrings.length]; progressBar.setValue(0); progressBar.setVisible(true); EntityData[] graphNodes = entityIndex.processKinTypeStrings(null, graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, kinTypeStrings, parserHighlight, graphPanel.getIndexParameters(), progressBar); boolean visibleNodeFound = false; for (EntityData currentNode : graphNodes) { if (currentNode.isVisible) { visibleNodeFound = true; break; } } if (!visibleNodeFound /*graphNodes.length == 0*/) { KinTypeStringConverter graphData = new KinTypeStringConverter(); graphData.readKinTypes(kinTypeStrings, graphPanel.getkinTermGroups(), graphPanel.dataStoreSvg, parserHighlight); graphPanel.drawNodes(graphData); egoSelectionPanel.setTransientNodes(graphData.getDataNodes()); // KinDiagramPanel.this.doLayout(); } else { graphSorter.setEntitys(graphNodes); // register interest Arbil updates and update the graph when data is edited in the table registerCurrentNodes(graphSorter.getDataNodes()); graphPanel.drawNodes(graphSorter); egoSelectionPanel.setTreeNodes(graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, graphSorter.getDataNodes()); } StyledDocument styledDocument = kinTypeStringInput.getStyledDocument(); int lineStart = 0; for (int lineCounter = 0; lineCounter < parserHighlight.length; lineCounter++) { ParserHighlight currentHighlight = parserHighlight[lineCounter]; // int lineStart = styledDocument.getParagraphElement(lineCounter).getStartOffset(); // int lineEnd = styledDocument.getParagraphElement(lineCounter).getEndOffset(); int lineEnd = lineStart + kinTypeStrings[lineCounter].length(); styledDocument.setCharacterAttributes(lineStart, lineEnd, kinTypeStringInput.getStyle("Unknown"), true); while (currentHighlight.highlight != null) { int startPos = lineStart + currentHighlight.startChar; int charCount = lineEnd - lineStart; if (currentHighlight.nextHighlight.highlight != null) { charCount = currentHighlight.nextHighlight.startChar - currentHighlight.startChar; } if (currentHighlight.highlight != null) { String styleName = currentHighlight.highlight.name(); styledDocument.setCharacterAttributes(startPos, charCount, kinTypeStringInput.getStyle(styleName), true); } currentHighlight = currentHighlight.nextHighlight; } lineStart += kinTypeStrings[lineCounter].length() + 1; } // kinTypeStrings = graphPanel.getKinTypeStrigs(); } catch (EntityServiceException exception) { GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to load an entity", "Kinnate"); } progressBar.setVisible(false); } @Deprecated public void setDisplayNodes(String typeString, String[] egoIdentifierArray) { // todo: should this be replaced by the required nodes? if (kinTypeStringInput.getText().equals(defaultString)) { kinTypeStringInput.setText(""); } String kinTermContents = kinTypeStringInput.getText(); for (String currentId : egoIdentifierArray) { kinTermContents = kinTermContents + typeString + "=[" + currentId + "]\n"; } kinTypeStringInput.setText(kinTermContents); graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n")); // kinTypeStrings = graphPanel.getKinTypeStrigs(); drawGraph(); } public void setEgoNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.egoEntities = new HashSet<UniqueIdentifier>(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void addEgoNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.egoEntities.addAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void removeEgoNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.egoEntities.removeAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void addRequiredNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void removeRequiredNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.requiredEntities.removeAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public boolean hasSaveFileName() { return graphPanel.hasSaveFileName(); } public File getFileName() { return graphPanel.getFileName(); } public boolean requiresSave() { return graphPanel.requiresSave(); } public void setRequiresSave() { graphPanel.setRequiresSave(); } public void saveToFile() { graphPanel.saveToFile(); } public void saveToFile(File saveFile) { graphPanel.saveToFile(saveFile); } public void updateGraph() { this.drawGraph(); } public void exportKinTerms() { kinTermPanel.getSelectedKinTermPanel().exportKinTerms(); } public void hideShow() { kinTermHidePane.toggleHiddenState(); } public void importKinTerms() { kinTermPanel.getSelectedKinTermPanel().importKinTerms(); } public void addKinTermGroup() { graphPanel.addKinTermGroup(); kinTermPanel.updateKinTerms(graphPanel.getkinTermGroups()); } public void setSelectedKinTypeSting(String kinTypeStrings) { kinTermPanel.setAddableKinTypeSting(kinTypeStrings); } public boolean isHidden() { return kinTermHidePane.isHidden(); } private void registerCurrentNodes(EntityData[] currentEntities) { // todo: i think this is resolved but double check the issue where arbil nodes update frequency is too high and breaks basex // todo: load the nodes in the KinDataNode when putting them in the table and pass on the reload requests here when they occur // todo: replace the data node registering process // for (EntityData entityData : currentEntities) { // ArbilDataNode arbilDataNode = null; // if (!registeredArbilDataNode.containsKey(entityData.getUniqueIdentifier())) { // try { // String metadataPath = entityData.getEntityPath(); // if (metadataPath != null) { // // todo: this should not load the arbil node only register an interest //// and this needs to be tested // arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNodeWithoutLoading(new URI(metadataPath)); // registeredArbilDataNode.put(entityData.getUniqueIdentifier(), arbilDataNode); // arbilDataNode.registerContainer(this); // // todo: keep track of registered nodes and remove the unrequired ones here // } else { // GuiHelper.linorgBugCatcher.logError(new Exception("Error getting path for: " + entityData.getUniqueIdentifier().getAttributeIdentifier() + " : " + entityData.getLabel()[0])); // } catch (URISyntaxException exception) { // GuiHelper.linorgBugCatcher.logError(exception); // } else { // arbilDataNode = registeredArbilDataNode.get(entityData.getUniqueIdentifier()); // if (arbilDataNode != null) { // entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false); } public void entityRelationsChanged(UniqueIdentifier[] selectedIdentifiers) { // this method does not need to update the database because the link changing process has already done that // remove the stored graph locations of the selected ids graphPanel.clearEntityLocations(selectedIdentifiers); graphPanel.getIndexParameters().valuesChanged = true; drawGraph(); } public void dataNodeIconCleared(ArbilNode arbilNode) { // todo: this needs to be updated to be multi threaded so users can link or save multiple nodes at once boolean dataBaseRequiresUpdate = false; boolean redrawRequired = false; if (arbilNode instanceof ArbilDataNode) { ArbilDataNode arbilDataNode = (ArbilDataNode) arbilNode; // find the entity data for this arbil data node for (EntityData entityData : graphSorter.getDataNodes()) { try { String entityPath = entityData.getEntityPath(); if (entityPath != null && arbilDataNode.getURI().equals(new URI(entityPath))) { // check if the metadata has been changed // todo: something here fails to act on multiple nodes that have changed (it is the db update that was missed) if (entityData.metadataRequiresSave && !arbilDataNode.getNeedsSaveToDisk(false)) { dataBaseRequiresUpdate = true; redrawRequired = true; } // clear or set the needs save flag entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false); if (entityData.metadataRequiresSave) { redrawRequired = true; } } } catch (URISyntaxException exception) { GuiHelper.linorgBugCatcher.logError(exception); } } if (dataBaseRequiresUpdate) { entityCollection.updateDatabase(arbilDataNode.getURI()); graphPanel.getIndexParameters().valuesChanged = true; } } if (redrawRequired) { drawGraph(); } } public void dataNodeRemoved(ArbilNode adn) { throw new UnsupportedOperationException("Not supported yet."); } }
package net.kevxu.purdueassist.course.elements; public class Predefined { public enum Term { CURRENT("Current", "CURRENT"), SUMMER2013("Summer 2013", "201330"), SPRING2013( "Spring 2013", "201320"), FALL2012("Fall 2012", "201310"), SUMMER2012( "Summer 2012", "201230"), SPRING2012("Spring 2012", "201220"), FALL2011( "Fall 2011", "201210"), SUMMER2011("Summer 2011", "201130"), SPRING2011( "Spring 2011", "201120"), FALL2010("Fall 2010", "201110"), SUMMER2010( "Summer 2010", "201030"), SPRING2010("Spring 2010", "201020"), FALL2009( "Fall 2009", "201010"), SUMMER2009("Summer 2009", "200930"), SPRING2009( "Spring 2009", "200920"), FALL2008("Fall 2008", "200910"), SUMMER2008( "Summer 2008", "200830"), SPRING2008("Spring 2008", "200820"); private final String name; private final String linkName; Term(String name, String linkName) { this.name = name; this.linkName = linkName; } public String getName() { return name; } public String getLinkName() { return linkName; } @Override public String toString() { return name; } } public enum Subject { AAE("Aero & Astro Engineering"), AAS("African American Studies"), ABE( "Agri & Biol Engineering"), AD("Art & Design"), AFT( "Aerospace Studies"), AGEC("Agricultural Economics"), AGR( "Agriculture"), AGRY("Agronomy"), AMST("American Studies"), ANSC( "Animal Sciences"), ANTH("Anthropology"), ARAB("Arabic"), ASAM( "Asian American Studies"), ASL("American Sign Language"), ASM( "Agricultural Systems Mgmt"), ASTR("Astronomy"), AT( "Aviation Technology"), BAND("Bands"), BCHM("Biochemistry"), BCM( "Bldg Construct Mgmt Tech"), BIOL("Biological Sciences"), BME( "Biomedical Engineering"), BMS("Basic Medical Sciences"), BTNY( "Botany & Plant Pathology"), BUS("Business"), CAND("Candidate"), CE( "Civil Engineering"), CEM("Construction Engr & Mgmt"), CGT( "Computer Graphics Tech"), CHE("Chemical Engineering"), CHM( "Chemistry"), CHNS("Chinese"), CLCS("Classics"), CLPH( "Clinical Pharmacy"), CMPL("Comparative Literature"), CNIT( "Computer & Info Tech"), COM("Communication"), CPB( "Comparative Pathobiology"), CS("Computer Sciences"), CSR( "Consumer ScI & Retailing"), DANC("Dance"), EAS( "Earth & Atmospheric Sci"), ECE("Electrical & Computer Engr"), ECET( "Electrical&Comp Engr Tech"), ECON("Economics"), EDCI( "Educ-Curric & Instruction"), EDPS("Educ-Ed'l and Psy Studies"), EDST( "Ed Leadrship&Cultrl Fnd"), EEE("Environ & Ecological Engr"), ENE( "Engineering Education"), ENGL("English"), ENGR( "First Year Engineering"), ENTM("Entomology"), ENTR( "Entrepreneurship"), EPCS("Engr Proj Cmity Service"), FLL( "Foreign Lang & Literatures"), FNR("Forestry&Natural Resources"), FR( "French"), FS("Food Science"), FVS("Film And Video Studies"), GEP( "Global Engineering Program"), GER("German"), GRAD( "Graduate Studies"), GREK("Greek"), GS("General Studies"), HDFS( "Human Dev &Family Studies"), HEBR("Hebrew"), HHS( "College Health & Human Sci"), HIST("History"), HK( "Health And Kinesiology"), HONR("Honors"), HORT("Horticulture"), HSCI( "Health Sciences"), HTM("Hospitality & Tourism Mgmt"), IDE( "Interdisciplinary Engr"), IDIS("Interdisciplinary Studies"), IE( "Industrial Engineering"), IET("Industrial Engr Technology"), IPPH( "Industrial & Phys Pharm"), IT("Industrial Technology"), ITAL( "Italian"), JPNS("Japanese"), JWST("Jewish Studies"), LA( "Landscape Architecture"), LALS("Latina Am&Latino Studies"), LATN( "Latin"), LC("Languages and Cultures"), LCME( "Lafayette Center Med Educ"), LING("Linguistics"), MA( "Mathematics"), MARS("Medieval &Renaissance Std"), MCMP( "Med Chem &Molecular Pharm"), ME("Mechanical Engineering"), MET( "Mechanical Engr Tech"), MFET("Manufacturing Engr Tech"), MGMT( "Management"), MSE("Materials Engineering"), MSL( "Military Science & Ldrshp"), MUS("Music History & Theory"), NRES( "Natural Res & Environ Sci"), NS("Naval Science"), NUCL( "Nuclear Engineering"), NUPH("Nuclear Pharmacy"), NUR("Nursing"), NUTR( "Nutrition Science"), OBHR("Orgnztnl Bhvr &Hum Resrce"), OLS( "Organiz Ldrshp&Supervision"), PES("Physical Education Skills"), PHAD( "Pharmacy Administration"), PHIL("Philosophy"), PHPR( "Pharmacy Practice"), PHRM("Pharmacy"), PHYS("Physics"), POL( "Political Science"), PSY("Psychology"), PTGS("Portuguese"), REG( "Reg File Maintenance"), REL("Religious Studies"), RUSS( "Russian"), SA("Study Abroad"), SCI("General Science"), SLHS( "Speech, Lang&Hear Science"), SOC("Sociology"), SPAN("Spanish"), STAT( "Statistics"), TECH("Technology"), THTR("Theatre"), USP( "Undergrad Studies Prog"), VCS("Veterinary Clinical Sci"), VM( "Veterinary Medicine"), WOST("Women's Studies"), YDAE( "Youth Develop & Ag Educ"), CIC("CIC"), CMCI("CMCI"), AST("AST"), CHEM( "CHEM"), CSCI("CSCI"), COMM("COMM"), ENG("ENG"), GEOL("GEOL"), LSTU( "LSTU"), FINA("FINA"), SPCH("SPCH"), INFO("INFO"), MATH("MATH"), CMCL( "CMCL"), GEOG("GEOG"), JOUR("JOUR"), COAS("COAS"), HPER("HPER"), HSRV( "HSRV"), POLS("POLS"), SPEA("SPEA"), TEL("TEL"), CIT("CIT"), EALC( "EALC"), SWK("SWK"), ANAT("ANAT"), CJUS("CJUS"), PHYT("PHYT"), PMTD( "PMTD"), DRAF("DRAF"), PRDM("PRDM"), SUPV("SUPV"), ERTH("ERTH"), FOLK( "FOLK"), CMLT("CMLT"), OADM("OADM"), NMCM("NMCM"), PHSL("PHSL"); private final String fullName; Subject(String fullName) { this.fullName = fullName; } public String getFullName() { return fullName; } @Override public String toString() { return fullName; } } public enum Type { DistanceLearning("Distance Learning", "DIS"), IndividualStudy( "Individual Study", ""), Laboratory("Laboratory", "LAB"), Lecture( "Lecture", "LEC"), Recitation("Recitation", "REC"), PracticeStudyObservation( "Practice Study Observation", "PSO"), LaboratoryPreparation( "Laboratory Preparation", ""), Experiential("Experiential", ""), Research( "Research", ""), Studio("Studio", ""), Lab1("Lab1", ""), Clinic( "Clinic", ""), Lecture1("Lecture1", ""), Presentation( "Presentation", ""), TravelTime("TravelTime", ""), Experiential1( "Experiential1", ""), Clinic1("Clinic1", ""), Clinic2( "Clinic2", ""), Clinic3("Clinic3", ""), Studio1("Studio1", ""); private final String name; private final String linkName; Type(String name, String linkName) { this.name = name; this.linkName = linkName; } public String getName() { return name; } public String getLinkName() { return linkName; } @Override public String toString() { return name; } } }
package no.nordicsemi.android.dfu; import android.annotation.SuppressLint; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.content.Intent; import android.os.Build; import android.util.Log; import java.io.InputStream; import java.lang.reflect.Method; import java.util.UUID; import no.nordicsemi.android.dfu.internal.ArchiveInputStream; import no.nordicsemi.android.dfu.internal.exception.DeviceDisconnectedException; import no.nordicsemi.android.dfu.internal.exception.DfuException; import no.nordicsemi.android.dfu.internal.exception.UploadAbortedException; import no.nordicsemi.android.dfu.internal.scanner.BootloaderScannerFactory; /* package */ abstract class BaseDfuImpl implements DfuService { private static final String TAG = "DfuImpl"; protected static final UUID GENERIC_ATTRIBUTE_SERVICE_UUID = new UUID(0x0000180100001000L, 0x800000805F9B34FBL); protected static final UUID SERVICE_CHANGED_UUID = new UUID(0x00002A0500001000L, 0x800000805F9B34FBL); protected static final UUID CLIENT_CHARACTERISTIC_CONFIG = new UUID(0x0000290200001000L, 0x800000805f9b34fbL); protected static final int NOTIFICATIONS = 1; protected static final int INDICATIONS = 2; protected static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); protected static final int MAX_PACKET_SIZE = 20; // the maximum number of bytes in one packet is 20. May be less. /** * Lock used in synchronization purposes */ protected final Object mLock = new Object(); protected InputStream mFirmwareStream; protected InputStream mInitPacketStream; /** The target GATT device. */ protected BluetoothGatt mGatt; /** The firmware type. See TYPE_* constants. */ protected int mFileType; /** Flag set to true if sending was paused. */ protected boolean mPaused; /** Flag set to true if sending was aborted. */ protected boolean mAborted; /** Flag indicating whether the device is still connected. */ protected boolean mConnected; /** * Flag indicating whether the request was completed or not */ protected boolean mRequestCompleted; /** * Flag sent when a request has been sent that will cause the DFU target to reset. Often, after sending such command, Android throws a connection state error. If this flag is set the error will be * ignored. */ protected boolean mResetRequestSent; /** * The number of the last error that has occurred or 0 if there was no error */ protected int mError; /** * Latest data received from device using notification. */ protected byte[] mReceivedData = null; protected final byte[] mBuffer = new byte[MAX_PACKET_SIZE]; protected DfuBaseService mService; protected DfuProgressInfo mProgressInfo; protected int mImageSizeInBytes; protected int mInitPacketSizeInBytes; protected class BaseBluetoothGattCallback extends BluetoothGattCallback { // The Implementation object is created depending on device services, so after the device is connected and services were scanned. // public void onConnected() { } public void onDisconnected() { mConnected = false; notifyLock(); } @Override public void onCharacteristicRead(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) { if (status == BluetoothGatt.GATT_SUCCESS) { /* * This method is called when the DFU Version characteristic has been read. */ mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "Read Response received from " + characteristic.getUuid() + ", value (0x): " + parse(characteristic)); mReceivedData = characteristic.getValue(); mRequestCompleted = true; } else { loge("Characteristic read error: " + status); mError = DfuBaseService.ERROR_CONNECTION_MASK | status; } notifyLock(); } @Override public void onDescriptorRead(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) { if (status == BluetoothGatt.GATT_SUCCESS) { if (CLIENT_CHARACTERISTIC_CONFIG.equals(descriptor.getUuid())) { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "Read Response received from descr." + descriptor.getCharacteristic().getUuid() + ", value (0x): " + parse(descriptor)); if (SERVICE_CHANGED_UUID.equals(descriptor.getCharacteristic().getUuid())) { // We have enabled indications for the Service Changed characteristic mRequestCompleted = true; } else { // reading other descriptor is not supported loge("Unknown descriptor read"); // this have to be implemented if needed } } } else { loge("Descriptor read error: " + status); mError = DfuBaseService.ERROR_CONNECTION_MASK | status; } notifyLock(); } @Override public void onDescriptorWrite(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) { if (status == BluetoothGatt.GATT_SUCCESS) { if (CLIENT_CHARACTERISTIC_CONFIG.equals(descriptor.getUuid())) { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "Data written to descr." + descriptor.getCharacteristic().getUuid() + ", value (0x): " + parse(descriptor)); if (SERVICE_CHANGED_UUID.equals(descriptor.getCharacteristic().getUuid())) { // We have enabled indications for the Service Changed characteristic mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Indications enabled for " + descriptor.getCharacteristic().getUuid()); } else { // We have enabled notifications for this characteristic mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Notifications enabled for " + descriptor.getCharacteristic().getUuid()); } } } else { loge("Descriptor write error: " + status); mError = DfuBaseService.ERROR_CONNECTION_MASK | status; } notifyLock(); } protected String parse(final BluetoothGattCharacteristic characteristic) { return parse(characteristic.getValue()); } protected String parse(final BluetoothGattDescriptor descriptor) { return parse(descriptor.getValue()); } private String parse(final byte[] data) { if (data == null) return ""; final int length = data.length; if (length == 0) return ""; final char[] out = new char[length * 3 - 1]; for (int j = 0; j < length; j++) { int v = data[j] & 0xFF; out[j * 3] = HEX_ARRAY[v >>> 4]; out[j * 3 + 1] = HEX_ARRAY[v & 0x0F]; if (j != length - 1) out[j * 3 + 2] = '-'; } return new String(out); } }; /* package */ BaseDfuImpl(final Intent intent, final DfuBaseService service) { mService = service; mConnected = true; // the device is connected when impl object it created } @Override public void release() { mService = null; } @Override public void pause() { mPaused = true; } @Override public void resume() { mPaused = false; notifyLock(); } @Override public void abort() { mPaused = false; mAborted = true; notifyLock(); } @Override public void onBondStateChanged(final int state) { mRequestCompleted = true; notifyLock(); } @Override public boolean initialize(final Intent intent, final BluetoothGatt gatt, final int fileType, final InputStream firmwareStream, final InputStream initPacketStream) throws DfuException, DeviceDisconnectedException, UploadAbortedException { mGatt = gatt; mFileType = fileType; mFirmwareStream = firmwareStream; mInitPacketStream = initPacketStream; final int currentPart = intent.getIntExtra(DfuBaseService.EXTRA_PART_CURRENT, 1); int totalParts = intent.getIntExtra(DfuBaseService.EXTRA_PARTS_TOTAL, 1); // Sending App together with SD or BL is not supported. It must be spilt into two parts. if (fileType > DfuBaseService.TYPE_APPLICATION) { logw("DFU target does not support (SD/BL)+App update, splitting into 2 parts"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "Sending system components"); mFileType &= ~DfuBaseService.TYPE_APPLICATION; // clear application bit totalParts = 2; // Set new content type in the ZIP Input Stream and update sizes of images final ArchiveInputStream zhis = (ArchiveInputStream) mFirmwareStream; zhis.setContentType(mFileType); } if (currentPart == 2) { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "Sending application"); } int size; try { size = initPacketStream.available(); } catch (final Exception e) { size = 0; } mInitPacketSizeInBytes = size; try { size = firmwareStream.available(); } catch (final Exception e) { size = 0; // not possible } mImageSizeInBytes = size; mProgressInfo = mService.mProgressInfo.init(size, currentPart, totalParts); // If we are bonded we may want to enable Service Changed characteristic indications. // Note: Sending SC indication on services change was introduced in the SDK 8.0. // Before, the cache had to be clear manually. This Android lib supports both implementations. // Note: On iOS refreshing services is not available in the API. An app must have Service Change characteristic // if it intends ever to change its services. In that case on non-bonded devices services will never be cached, // and on bonded a change is indicated using Service Changed indication. Ergo - Legacy DFU will // not work by default on iOS with buttonless update on SDKs < 8 on bonded devices. The bootloader must be modified to // always send the indication when connected. // The requirement of enabling Service Changed indications manually has been fixed on Android 6. // Now the Android enables Service Changed indications automatically after bonding. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED) { final BluetoothGattService genericAttributeService = gatt.getService(GENERIC_ATTRIBUTE_SERVICE_UUID); if (genericAttributeService != null) { final BluetoothGattCharacteristic serviceChangedCharacteristic = genericAttributeService.getCharacteristic(SERVICE_CHANGED_UUID); if (serviceChangedCharacteristic != null) { // Let's read the current value of the Service Changed CCCD final boolean serviceChangedIndicationsEnabled = isServiceChangedCCCDEnabled(); if (!serviceChangedIndicationsEnabled) enableCCCD(serviceChangedCharacteristic, INDICATIONS); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Service Changed indications enabled"); } } } return true; } protected void notifyLock() { // Notify waiting thread synchronized (mLock) { mLock.notifyAll(); } } protected void waitIfPaused() { try { synchronized (mLock) { while (mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } } /** * Returns the final BluetoothGattCallback instance, depending on the implementation. */ protected abstract BaseBluetoothGattCallback getGattCallback(); /** * Enables or disables the notifications for given characteristic. This method is SYNCHRONOUS and wait until the * {@link android.bluetooth.BluetoothGattCallback#onDescriptorWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int)} will be called or the device gets disconnected. * If connection state will change, or an error will occur, an exception will be thrown. * * @param characteristic the characteristic to enable or disable notifications for * @param type {@link #NOTIFICATIONS} or {@link #INDICATIONS} * @throws DfuException * @throws UploadAbortedException */ protected void enableCCCD(final BluetoothGattCharacteristic characteristic, final int type) throws DeviceDisconnectedException, DfuException, UploadAbortedException { final BluetoothGatt gatt = mGatt; final String debugString = type == NOTIFICATIONS ? "notifications" : "indications"; if (!mConnected) throw new DeviceDisconnectedException("Unable to set " + debugString + " state: device disconnected"); if (mAborted) throw new UploadAbortedException(); mReceivedData = null; mError = 0; final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG); boolean cccdEnabled = descriptor.getValue() != null && descriptor.getValue().length == 2 && descriptor.getValue()[0] > 0 && descriptor.getValue()[1] == 0; if (cccdEnabled) return; logi("Enabling " + debugString + "..."); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Enabling " + debugString + " for " + characteristic.getUuid()); // enable notifications locally mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)"); gatt.setCharacteristicNotification(characteristic, true); // enable notifications on the device descriptor.setValue(type == NOTIFICATIONS ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.writeDescriptor(" + descriptor.getUuid() + (type == NOTIFICATIONS ? ", value=0x01-00)" : ", value=0x02-00)")); gatt.writeDescriptor(descriptor); // We have to wait until device receives a response or an error occur try { synchronized (mLock) { while ((!cccdEnabled && mConnected && mError == 0) || mPaused) { mLock.wait(); // Check the value of the CCCD cccdEnabled = descriptor.getValue() != null && descriptor.getValue().length == 2 && descriptor.getValue()[0] > 0 && descriptor.getValue()[1] == 0; } } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mError != 0) throw new DfuException("Unable to set " + debugString + " state", mError); if (!mConnected) throw new DeviceDisconnectedException("Unable to set " + debugString + " state: device disconnected"); } /** * Reads the value of the Service Changed Client Characteristic Configuration descriptor (CCCD). * * @return <code>true</code> if Service Changed CCCD is enabled and set to INDICATE * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private boolean isServiceChangedCCCDEnabled() throws DeviceDisconnectedException, DfuException, UploadAbortedException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Service Changed CCCD: device disconnected"); if (mAborted) throw new UploadAbortedException(); // If the Service Changed characteristic or the CCCD is not available we return false. final BluetoothGatt gatt = mGatt; final BluetoothGattService genericAttributeService = gatt.getService(GENERIC_ATTRIBUTE_SERVICE_UUID); if (genericAttributeService == null) return false; final BluetoothGattCharacteristic serviceChangedCharacteristic = genericAttributeService.getCharacteristic(SERVICE_CHANGED_UUID); if (serviceChangedCharacteristic == null) return false; final BluetoothGattDescriptor descriptor = serviceChangedCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG); if (descriptor == null) return false; mRequestCompleted = false; mError = 0; logi("Reading Service Changed CCCD value..."); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Reading Service Changed CCCD value..."); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.readDescriptor(" + descriptor.getUuid() + ")"); gatt.readDescriptor(descriptor); // We have to wait until device receives a response or an error occur try { synchronized (mLock) { while ((!mRequestCompleted && mConnected && mError == 0) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mError != 0) throw new DfuException("Unable to read Service Changed CCCD", mError); if (!mConnected) throw new DeviceDisconnectedException("Unable to read Service Changed CCCD: device disconnected"); // Return true if the CCCD value is return descriptor.getValue() != null && descriptor.getValue().length == 2 && descriptor.getValue()[0] == BluetoothGattDescriptor.ENABLE_INDICATION_VALUE[0] && descriptor.getValue()[1] == BluetoothGattDescriptor.ENABLE_INDICATION_VALUE[1]; } /** * Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the * {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} will be called or * the device gets disconnected. If connection state will change, or an error will occur, an exception will be thrown. * * @param characteristic the characteristic to write to. Should be the DFU CONTROL POINT * @param value the value to write to the characteristic * @param reset whether the command trigger restarting the device * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ protected void writeOpCode(final BluetoothGattCharacteristic characteristic, final byte[] value, final boolean reset) throws DeviceDisconnectedException, DfuException, UploadAbortedException { if (mAborted) throw new UploadAbortedException(); mReceivedData = null; mError = 0; mRequestCompleted = false; /* * Sending a command that will make the DFU target to reboot may cause an error 133 (0x85 - Gatt Error). If so, with this flag set, the error will not be shown to the user * as the peripheral is disconnected anyway. See: mGattCallback#onCharacteristicWrite(...) method */ mResetRequestSent = reset; characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); characteristic.setValue(value); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Writing to characteristic " + characteristic.getUuid()); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")"); mGatt.writeCharacteristic(characteristic); // We have to wait for confirmation try { synchronized (mLock) { while ((!mRequestCompleted && mConnected && mError == 0) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (!mResetRequestSent && mError != 0) throw new DfuException("Unable to write Op Code " + value[0], mError); if (!mResetRequestSent && !mConnected) throw new DeviceDisconnectedException("Unable to write Op Code " + value[0] + ": device disconnected"); } /** * Creates bond to the device. Works on all APIs since 18th (Android 4.3). * * @return true if it's already bonded or the bonding has started */ @SuppressLint("NewApi") protected boolean createBond() { final BluetoothDevice device = mGatt.getDevice(); if (device.getBondState() == BluetoothDevice.BOND_BONDED) return true; boolean result; mRequestCompleted = false; mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Starting pairing..."); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.getDevice().createBond()"); result = device.createBond(); } else { result = createBondApi18(device); } // We have to wait until device is bounded try { synchronized (mLock) { while (!mRequestCompleted && !mAborted) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } return result; } /** * A method that creates the bond to given device on API lower than Android 5. * * @param device the target device * @return false if bonding failed (no hidden createBond() method in BluetoothDevice, or this method returned false */ private boolean createBondApi18(final BluetoothDevice device) { /* * There is a createBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. It has been revealed in KitKat (Api19) */ try { final Method createBond = device.getClass().getMethod("createBond"); if (createBond != null) { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.getDevice().createBond() (hidden)"); return (Boolean) createBond.invoke(device); } } catch (final Exception e) { Log.w(TAG, "An exception occurred while creating bond", e); } return false; } /** * Removes the bond information for the given device. * * @return <code>true</code> if operation succeeded, <code>false</code> otherwise */ protected boolean removeBond() { final BluetoothDevice device = mGatt.getDevice(); if (device.getBondState() == BluetoothDevice.BOND_NONE) return true; mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Removing bond information..."); boolean result = false; /* * There is a removeBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. */ try { final Method removeBond = device.getClass().getMethod("removeBond"); if (removeBond != null) { mRequestCompleted = false; mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.getDevice().removeBond() (hidden)"); result = (Boolean) removeBond.invoke(device); // We have to wait until device is unbounded try { synchronized (mLock) { while (!mRequestCompleted && !mAborted) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } } result = true; } catch (final Exception e) { Log.w(TAG, "An exception occurred while removing bond information", e); } return result; } /** * Waits until the notification will arrive. Returns the data returned by the notification. This method will block the thread until response is not ready or * the device gets disconnected. If connection state will change, or an error will occur, an exception will be thrown. * * @return the value returned by the Control Point notification * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ protected byte[] readNotificationResponse() throws DeviceDisconnectedException, DfuException, UploadAbortedException { // do not clear the mReceiveData here. The response might already be obtained. Clear it in write request instead. try { synchronized (mLock) { while ((mReceivedData == null && mConnected && mError == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mError != 0) throw new DfuException("Unable to write Op Code", mError); if (!mConnected) throw new DeviceDisconnectedException("Unable to write Op Code: device disconnected"); return mReceivedData; } /** * Restarts the service based on the given intent. If parameter set this method will also scan for * an advertising bootloader that has address equal or incremented by 1 to the current one. * @param intent the intent to be started as a service * @param scanForBootloader true to scan for advertising bootloader, false to keep the same address */ protected void restartService(final Intent intent, final boolean scanForBootloader) { String newAddress = null; if (scanForBootloader) { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Scanning for the DFU Bootloader..."); newAddress = BootloaderScannerFactory.getScanner().searchFor(mGatt.getDevice().getAddress()); logi("Scanning for new address finished with: " + newAddress); if (newAddress != null) mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "DFU Bootloader found with address " + newAddress); else { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "DFU Bootloader not found. Trying the same address..."); } } if (newAddress != null) intent.putExtra(DfuBaseService.EXTRA_DEVICE_ADDRESS, newAddress); mService.startService(intent); } protected String parse(final byte[] data) { if (data == null) return ""; final int length = data.length; if (length == 0) return ""; final char[] out = new char[length * 3 - 1]; for (int j = 0; j < length; j++) { int v = data[j] & 0xFF; out[j * 3] = HEX_ARRAY[v >>> 4]; out[j * 3 + 1] = HEX_ARRAY[v & 0x0F]; if (j != length - 1) out[j * 3 + 2] = '-'; } return new String(out); } void loge(final String message) { Log.e(TAG, message); } void loge(final String message, final Throwable e) { Log.e(TAG, message, e); } void logw(final String message) { if (DfuBaseService.DEBUG) Log.w(TAG, message); } void logi(final String message) { if (DfuBaseService.DEBUG) Log.i(TAG, message); } }
package com.cgogolin.penandpdf; import android.content.SharedPreferences; import android.net.Uri; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import android.content.Context; import android.util.Log; public class RecentFilesList extends LinkedList<RecentFile> implements List<RecentFile> { //Probably not the most appropriate list type... static final int MAX_RECENT_FILES=100; private Context context = null; public RecentFilesList() { super(); } public RecentFilesList(Context context, SharedPreferences prefs) { this.context = context; for (int i = MAX_RECENT_FILES-1; i>=0; i--) //Read in reverse order because we use push { String recentFileString = prefs.getString("recentfile"+i, null); long recentFileLastModified = prefs.getLong("recentfile_lastModified"+i, 0l); String displayName = prefs.getString("recentfile_displayName"+i, null); String bitmapString = prefs.getString("recentfile_thumbnailString"+i, null); if(recentFileString != null) { Uri recentFileUri = Uri.parse(recentFileString); if( android.os.Build.VERSION.SDK_INT < 19 ) { //Make sure we add only readable files File recentFile = new File(Uri.decode(recentFileUri.getEncodedPath())); if(recentFile != null && recentFile.isFile() && recentFile.canRead()) push(new RecentFile(recentFileString, displayName, recentFileLastModified, bitmapString)); } else { push(new RecentFile(recentFileString, displayName, recentFileLastModified, bitmapString)); } } } } void write(SharedPreferences.Editor edit) { for (int i = 0; i<size(); i++) { edit.putString("recentfile"+i, get(i).getFileString()); edit.putLong("recentfile_lastModified"+i, get(i).getLastOpened()); edit.putString("recentfile_displayName"+i, get(i).getDisplayName()); edit.putString("recentfile_thumbnailString"+i, get(i).getThumbnailString()); } } public void push(String recentFileString) { push(new RecentFile(recentFileString)); } @Override public void push(RecentFile recentFile) { Log.i("Pen&PDF", "push() recent file "+recentFile.getDisplayName()+" with thunbnail "+recentFile.getThumbnailString()); //Make sure we don't put duplicates PdfThumbnailManager pdfThumbnailManager = new PdfThumbnailManager(context); int index = -1; while((index=indexOf(recentFile))!=-1) { RecentFile recentFileToRemove = super.remove(index); if(recentFile.getThumbnailString() == null) recentFile.setThumbnailString(recentFileToRemove.getThumbnailString()); else pdfThumbnailManager.delete(recentFileToRemove.getThumbnailString()); }; //Add super.addFirst(recentFile); //Remove elements until lenght is short enough while (size() > MAX_RECENT_FILES) { pdfThumbnailManager.delete(removeLast().getThumbnailString()); } } }
package org.bouncycastle.util; import java.math.BigInteger; import java.util.NoSuchElementException; /** * General array utilities. */ public final class Arrays { private Arrays() { // static class, hide constructor } public static boolean areAllZeroes(byte[] buf, int off, int len) { int bits = 0; for (int i = 0; i < len; ++i) { bits |= buf[off + i]; } return bits == 0; } public static boolean areEqual( boolean[] a, boolean[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual( char[] a, char[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual( byte[] a, byte[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual( short[] a, short[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } /** * A constant time equals comparison - does not terminate early if * test will fail. For best results always pass the expected value * as the first parameter. * * @param expected first array * @param supplied second array * @return true if arrays equal, false otherwise. */ public static boolean constantTimeAreEqual( byte[] expected, byte[] supplied) { if (expected == null || supplied == null) { return false; } if (expected.length != supplied.length) { return !Arrays.constantTimeAreEqual(expected, expected); } int nonEqual = 0; for (int i = 0; i != expected.length; i++) { nonEqual |= (expected[i] ^ supplied[i]); } return nonEqual == 0; } public static boolean areEqual( int[] a, int[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual( long[] a, long[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public static boolean areEqual(Object[] a, Object[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { Object objA = a[i], objB = b[i]; if (objA == null) { if (objB != null) { return false; } } else if (!objA.equals(objB)) { return false; } } return true; } public static int compareUnsigned(byte[] a, byte[] b) { if (a == b) { return 0; } if (a == null) { return -1; } if (b == null) { return 1; } int minLen = Math.min(a.length, b.length); for (int i = 0; i < minLen; ++i) { int aVal = a[i] & 0xFF, bVal = b[i] & 0xFF; if (aVal < bVal) { return -1; } if (aVal > bVal) { return 1; } } if (a.length < b.length) { return -1; } if (a.length > b.length) { return 1; } return 0; } public static boolean contains(short[] a, short n) { for (int i = 0; i < a.length; ++i) { if (a[i] == n) { return true; } } return false; } public static boolean contains(int[] a, int n) { for (int i = 0; i < a.length; ++i) { if (a[i] == n) { return true; } } return false; } public static void fill( byte[] array, byte value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( byte[] array, int start, int finish, byte value) { for (int i = start; i < finish; i++) { array[i] = value; } } public static void fill( char[] array, char value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( long[] array, long value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( short[] array, short value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( int[] array, int value) { for (int i = 0; i < array.length; i++) { array[i] = value; } } public static void fill( byte[] array, int out, byte value) { if(out < array.length) { for (int i = out; i < array.length; i++) { array[i] = value; } } } public static void fill( int[] array, int out, int value) { if(out < array.length) { for (int i = out; i < array.length; i++) { array[i] = value; } } } public static void fill( short[] array, int out, short value) { if(out < array.length) { for (int i = out; i < array.length; i++) { array[i] = value; } } } public static void fill( long[] array, int out, long value) { if(out < array.length) { for (int i = out; i < array.length; i++) { array[i] = value; } } } public static int hashCode(byte[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int hashCode(byte[] data, int off, int len) { if (data == null) { return 0; } int i = len; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[off + i]; } return hc; } public static int hashCode(char[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int hashCode(int[][] ints) { int hc = 0; for (int i = 0; i != ints.length; i++) { hc = hc * 257 + hashCode(ints[i]); } return hc; } public static int hashCode(int[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i]; } return hc; } public static int hashCode(int[] data, int off, int len) { if (data == null) { return 0; } int i = len; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[off + i]; } return hc; } public static int hashCode(long[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { long di = data[i]; hc *= 257; hc ^= (int)di; hc *= 257; hc ^= (int)(di >>> 32); } return hc; } public static int hashCode(long[] data, int off, int len) { if (data == null) { return 0; } int i = len; int hc = i + 1; while (--i >= 0) { long di = data[off + i]; hc *= 257; hc ^= (int)di; hc *= 257; hc ^= (int)(di >>> 32); } return hc; } public static int hashCode(short[][][] shorts) { int hc = 0; for (int i = 0; i != shorts.length; i++) { hc = hc * 257 + hashCode(shorts[i]); } return hc; } public static int hashCode(short[][] shorts) { int hc = 0; for (int i = 0; i != shorts.length; i++) { hc = hc * 257 + hashCode(shorts[i]); } return hc; } public static int hashCode(short[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= (data[i] & 0xff); } return hc; } public static int hashCode(Object[] data) { if (data == null) { return 0; } int i = data.length; int hc = i + 1; while (--i >= 0) { hc *= 257; hc ^= data[i].hashCode(); } return hc; } public static byte[] clone(byte[] data) { if (data == null) { return null; } byte[] copy = new byte[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static char[] clone(char[] data) { if (data == null) { return null; } char[] copy = new char[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static byte[] clone(byte[] data, byte[] existing) { if (data == null) { return null; } if ((existing == null) || (existing.length != data.length)) { return clone(data); } System.arraycopy(data, 0, existing, 0, existing.length); return existing; } public static byte[][] clone(byte[][] data) { if (data == null) { return null; } byte[][] copy = new byte[data.length][]; for (int i = 0; i != copy.length; i++) { copy[i] = clone(data[i]); } return copy; } public static byte[][][] clone(byte[][][] data) { if (data == null) { return null; } byte[][][] copy = new byte[data.length][][]; for (int i = 0; i != copy.length; i++) { copy[i] = clone(data[i]); } return copy; } public static int[] clone(int[] data) { if (data == null) { return null; } int[] copy = new int[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static long[] clone(long[] data) { if (data == null) { return null; } long[] copy = new long[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static long[] clone(long[] data, long[] existing) { if (data == null) { return null; } if ((existing == null) || (existing.length != data.length)) { return clone(data); } System.arraycopy(data, 0, existing, 0, existing.length); return existing; } public static short[] clone(short[] data) { if (data == null) { return null; } short[] copy = new short[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static BigInteger[] clone(BigInteger[] data) { if (data == null) { return null; } BigInteger[] copy = new BigInteger[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public static byte[] copyOf(byte[] data, int newLength) { byte[] tmp = new byte[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static char[] copyOf(char[] data, int newLength) { char[] tmp = new char[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static int[] copyOf(int[] data, int newLength) { int[] tmp = new int[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static long[] copyOf(long[] data, int newLength) { long[] tmp = new long[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } public static BigInteger[] copyOf(BigInteger[] data, int newLength) { BigInteger[] tmp = new BigInteger[newLength]; if (newLength < data.length) { System.arraycopy(data, 0, tmp, 0, newLength); } else { System.arraycopy(data, 0, tmp, 0, data.length); } return tmp; } /** * Make a copy of a range of bytes from the passed in data array. The range can * extend beyond the end of the input array, in which case the return array will * be padded with zeroes. * * @param data the array from which the data is to be copied. * @param from the start index at which the copying should take place. * @param to the final index of the range (exclusive). * * @return a new byte array containing the range given. */ public static byte[] copyOfRange(byte[] data, int from, int to) { int newLength = getLength(from, to); byte[] tmp = new byte[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } public static int[] copyOfRange(int[] data, int from, int to) { int newLength = getLength(from, to); int[] tmp = new int[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } public static long[] copyOfRange(long[] data, int from, int to) { int newLength = getLength(from, to); long[] tmp = new long[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } public static BigInteger[] copyOfRange(BigInteger[] data, int from, int to) { int newLength = getLength(from, to); BigInteger[] tmp = new BigInteger[newLength]; if (data.length - from < newLength) { System.arraycopy(data, from, tmp, 0, data.length - from); } else { System.arraycopy(data, from, tmp, 0, newLength); } return tmp; } private static int getLength(int from, int to) { int newLength = to - from; if (newLength < 0) { StringBuffer sb = new StringBuffer(from); sb.append(" > ").append(to); throw new IllegalArgumentException(sb.toString()); } return newLength; } public static byte[] append(byte[] a, byte b) { if (a == null) { return new byte[]{ b }; } int length = a.length; byte[] result = new byte[length + 1]; System.arraycopy(a, 0, result, 0, length); result[length] = b; return result; } public static short[] append(short[] a, short b) { if (a == null) { return new short[]{ b }; } int length = a.length; short[] result = new short[length + 1]; System.arraycopy(a, 0, result, 0, length); result[length] = b; return result; } public static int[] append(int[] a, int b) { if (a == null) { return new int[]{ b }; } int length = a.length; int[] result = new int[length + 1]; System.arraycopy(a, 0, result, 0, length); result[length] = b; return result; } public static String[] append(String[] a, String b) { if (a == null) { return new String[]{ b }; } int length = a.length; String[] result = new String[length + 1]; System.arraycopy(a, 0, result, 0, length); result[length] = b; return result; } public static byte[] concatenate(byte[] a, byte[] b) { if (a != null && b != null) { byte[] rv = new byte[a.length + b.length]; System.arraycopy(a, 0, rv, 0, a.length); System.arraycopy(b, 0, rv, a.length, b.length); return rv; } else if (b != null) { return clone(b); } else { return clone(a); } } public static byte[] concatenate(byte[] a, byte[] b, byte[] c) { if (a != null && b != null && c != null) { byte[] rv = new byte[a.length + b.length + c.length]; System.arraycopy(a, 0, rv, 0, a.length); System.arraycopy(b, 0, rv, a.length, b.length); System.arraycopy(c, 0, rv, a.length + b.length, c.length); return rv; } else if (a == null) { return concatenate(b, c); } else if (b == null) { return concatenate(a, c); } else { return concatenate(a, b); } } public static byte[] concatenate(byte[] a, byte[] b, byte[] c, byte[] d) { if (a != null && b != null && c != null && d != null) { byte[] rv = new byte[a.length + b.length + c.length + d.length]; System.arraycopy(a, 0, rv, 0, a.length); System.arraycopy(b, 0, rv, a.length, b.length); System.arraycopy(c, 0, rv, a.length + b.length, c.length); System.arraycopy(d, 0, rv, a.length + b.length + c.length, d.length); return rv; } else if (d == null) { return concatenate(a, b, c); } else if (c == null) { return concatenate(a, b, d); } else if (b == null) { return concatenate(a, c, d); } else { return concatenate(b, c, d); } } public static byte[] concatenate(byte[][] arrays) { int size = 0; for (int i = 0; i != arrays.length; i++) { size += arrays[i].length; } byte[] rv = new byte[size]; int offSet = 0; for (int i = 0; i != arrays.length; i++) { System.arraycopy(arrays[i], 0, rv, offSet, arrays[i].length); offSet += arrays[i].length; } return rv; } public static int[] concatenate(int[] a, int[] b) { if (a == null) { return clone(b); } if (b == null) { return clone(a); } int[] c = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } public static byte[] prepend(byte[] a, byte b) { if (a == null) { return new byte[]{ b }; } int length = a.length; byte[] result = new byte[length + 1]; System.arraycopy(a, 0, result, 1, length); result[0] = b; return result; } public static short[] prepend(short[] a, short b) { if (a == null) { return new short[]{ b }; } int length = a.length; short[] result = new short[length + 1]; System.arraycopy(a, 0, result, 1, length); result[0] = b; return result; } public static int[] prepend(int[] a, int b) { if (a == null) { return new int[]{ b }; } int length = a.length; int[] result = new int[length + 1]; System.arraycopy(a, 0, result, 1, length); result[0] = b; return result; } public static byte[] reverse(byte[] a) { if (a == null) { return null; } int p1 = 0, p2 = a.length; byte[] result = new byte[p2]; while (--p2 >= 0) { result[p2] = a[p1++]; } return result; } public static int[] reverse(int[] a) { if (a == null) { return null; } int p1 = 0, p2 = a.length; int[] result = new int[p2]; while (--p2 >= 0) { result[p2] = a[p1++]; } return result; } /** * Iterator backed by a specific array. */ public static class Iterator<T> implements java.util.Iterator<T> { private final T[] dataArray; private int position = 0; /** * Base constructor. * <p> * Note: the array is not cloned, changes to it will affect the values returned by next(). * </p> * * @param dataArray array backing the iterator. */ public Iterator(T[] dataArray) { this.dataArray = dataArray; } public boolean hasNext() { return position < dataArray.length; } public T next() { if (position == dataArray.length) { throw new NoSuchElementException("Out of elements: " + position); } return dataArray[position++]; } public void remove() { throw new UnsupportedOperationException("Cannot remove element from an Array."); } } /** * Fill input array by zeros * * @param array input array */ public static void clear(byte[] array) { if (array != null) { for (int i = 0; i < array.length; i++) { array[i] = 0; } } } }
package com.ecyrd.jspwiki.plugin; import com.ecyrd.jspwiki.*; import junit.framework.*; import java.io.*; import java.util.*; public class ReferringPagesPluginTest extends TestCase { Properties props = new Properties(); TestEngine2 engine; WikiContext context; PluginManager manager; public ReferringPagesPluginTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); engine = new TestEngine2(props); engine.saveText( "TestPage", "Reference to [Foobar]." ); engine.saveText( "Foobar", "Reference to [TestPage]." ); engine.saveText( "Foobar2", "Reference to [TestPage]." ); engine.saveText( "Foobar3", "Reference to [TestPage]." ); engine.saveText( "Foobar4", "Reference to [TestPage]." ); engine.saveText( "Foobar5", "Reference to [TestPage]." ); engine.saveText( "Foobar6", "Reference to [TestPage]." ); engine.saveText( "Foobar7", "Reference to [TestPage]." ); context = new WikiContext( engine, "TestPage" ); manager = new PluginManager(); } public void tearDown() { engine.deletePage( "TestPage" ); engine.deletePage( "Foobar" ); engine.deletePage( "Foobar2" ); engine.deletePage( "Foobar3" ); engine.deletePage( "Foobar4" ); engine.deletePage( "Foobar5" ); engine.deletePage( "Foobar6" ); engine.deletePage( "Foobar7" ); } private String mkLink( String page ) { return mkFullLink( page, page ); } private String mkFullLink( String page, String link ) { return "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page="+link+"\">"+page+"</A>"; } public void testSingleReferral() throws Exception { WikiContext context2 = new WikiContext( engine, "Foobar" ); String res = manager.execute( context2, "{INSERT com.ecyrd.jspwiki.plugin.ReferringPagesPlugin WHERE max=5}"); assertEquals( mkLink( "TestPage" )+"\n<BR>\n", res ); } public void testMaxReferences() throws Exception { String res = manager.execute( context, "{INSERT com.ecyrd.jspwiki.plugin.ReferringPagesPlugin WHERE max=5}"); int count = 0, index = -1; // Count the number of hyperlinks. We could check their // correctness as well, though. while( (index = res.indexOf("<A",index+1)) != -1 ) { count++; } assertEquals( 5, count ); assertEquals( "End", "...and 2 more<BR>\n", res.substring( res.length()-18 ) ); } public void testReferenceWidth() throws Exception { WikiContext context2 = new WikiContext( engine, "Foobar" ); String res = manager.execute( context2, "{INSERT com.ecyrd.jspwiki.plugin.ReferringPagesPlugin WHERE maxwidth=5}"); assertEquals( mkFullLink( "TestP...", "TestPage" )+"\n<BR>\n", res ); } public static Test suite() { return new TestSuite( ReferringPagesPluginTest.class ); } }
/* * ProductionPipeline */ package net.maizegenetics.analysis.gbs; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.io.Files; import net.maizegenetics.analysis.imputation.FILLINImputationPlugin; import net.maizegenetics.dna.snp.GenotypeTable; import net.maizegenetics.dna.snp.ImportUtils; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.util.CheckSum; import net.maizegenetics.util.SMTPClient; import net.maizegenetics.util.Utils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import java.io.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * This class is for running the GBS Production Pipeline. It is to be run from * within the sTASSEL.jar. The cron job should be set up to run the * run_pipeline.pl which has been modified to make this class the main() to be * run. The JVM memory settings within run_pipeline.pl should also be adjusted * upwards. * * cron example 20 3 * * * cd /workdir/tassel/tassel4-src && /usr/local/bin/perl * /workdir/tassel/tassel4-src/run_prod_cron.pl >> * /workdir/tassel/tassel4-src/20130808_cron.log 2>&1 * * 20130718 Note from Jeff Glaubitz: A minor detail: ProductionSNPCallerPlugin * needs the key file name to end with "_key.txt". All the output files are * named after the key file but replacing "_key.txt" with the appropriate * extension. * * @author Dallas Kroon * @author Terry Casstevens * */ public class ProductionPipeline { private static final Logger myLogger = Logger.getLogger(ProductionPipeline.class); private static final String DEFAULT_APPLICATION_CONFIGURATION = "production_pipeline.properties"; private static final String EMAIL_ADDRESS_DELIMITER = ";"; private static final SimpleDateFormat LOGGING_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); private static final String RUN_FILE_SUFFIX = ".run"; // host on which pipeline is running private String myApplicationHost = "unknown"; // application properties file private String myAppPropertiesFile = null; // default server to be used to send email notifications private String myEmailHost = "appsmtp.mail.cornell.edu"; // pipeline admin default email address private String[] myRecipientEmailAddresses = null; // directory into which the key and run files are // placed for pickup by cron job private String myRunDirectory = "/SSD/prop_pipeline/run/"; // directory into which the key and run files are placed // after being run a dated directory will be created // within this directory and artifacts such as the .log // and .xml file will be placed there private String myArchiveDirectory = "/SSD/prop_pipeline/arcvtmp/"; // directory containing the haplotype files to be used // in imputation private String myHaplotypeDirectory = "/SSD/haplos/"; // Input variable to ProductionSNPCallerPlugin private String myInputFolder = null; private String myEnzyme = null; private String myTopmFile = null; private String myOutputFolder = null; private String myKeyFile = null; private boolean runImputation = true; private String myPropertiesFileContents = null; private final Map<String, String> myEmailSubjects = new HashMap<>(); private static final String EXAMPLE_CONFIG_FILE = "emailHost=appsmtp.mail.cornell.edu\n" + "emailAddress=dek29@cornell.edu\n" + "runDirectory=/SSD/prop_pipeline/run/\n" + "archiveDirectory=/SSD/prop_pipeline/arcvtmp/\n" + "haplosDirectory=/SSD/haplos/\n"; private static final String EXAMPLE_RUN_FILE = "inputFolder=/workdir/tassel/tassel4-src/20130716test/raw_seq\n" + "enzyme=ApeKI\n" + "topmFile=/workdir/tassel/tassel4-src/20130716test/topm/AllZeaGBSv2.6ProdTOPM_20130605.topm.h5\n" + "outputFolder=/workdir/tassel/tassel4-src/20130716test/hap_maps\n" + "keyFile=/workdir/tassel/tassel4-src/20130716test/keyfile/MGP1_low_vol_2smallReps_key.txt"; public ProductionPipeline(String appPropertiesFile, boolean runCheckSum) { try { myApplicationHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { // do nothing } // if no application property file is specified, try looking for something in the home directory myAppPropertiesFile = appPropertiesFile; if (myAppPropertiesFile == null) { myAppPropertiesFile = DEFAULT_APPLICATION_CONFIGURATION; } myPropertiesFileContents = loadApplicationConfiguration(myAppPropertiesFile); executeRunFiles(myRunDirectory, runCheckSum); } private String getEmailSubjectRun(String runFile) { String result = myEmailSubjects.get(runFile); if (result != null) { return result; } StringBuilder builder = new StringBuilder(); builder.append("Discussion: "); builder.append(getTimeStamp()); builder.append("Run File: ").append(runFile).append(" "); result = builder.toString(); myEmailSubjects.put(runFile, result); return result; } private String getEmailSubjectApp() { String result = myEmailSubjects.get(myAppPropertiesFile); if (result != null) { return result; } StringBuilder builder = new StringBuilder(); builder.append("Discussion: "); builder.append(getTimeStamp()); builder.append("Properties File: ").append(myAppPropertiesFile).append(" "); result = builder.toString(); myEmailSubjects.put(myAppPropertiesFile, result); return result; } /** * * @param runDirectoryIn Directory containing any number of .run files */ private void executeRunFiles(String runDirectoryIn, boolean doCheckSum) { File dir = new File(runDirectoryIn); if (!dir.exists()) { System.out.println("Could not find the directory containing .run files: " + dir.getPath()); System.out.println("Exiting program."); sendAlertNotification(getEmailSubjectApp(), "Could not find run directory: " + dir.getAbsolutePath() + " on server " + myApplicationHost); System.exit(1); } // get all property files in the directory File[] files = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(RUN_FILE_SUFFIX); } }); if (files == null) { System.out.println("************** Could not find a valid .run file ***************"); System.out.println("************** Example .run file: "); System.out.println(EXAMPLE_RUN_FILE); sendAlertNotification(getEmailSubjectApp(), "No .run files found on " + myApplicationHost); } else { StringBuilder sb = new StringBuilder(); for (File f : files) { sb.append(f).append("\n"); } sb.append("\nRunning on server: ").append(myApplicationHost).append("\n"); sendAlertNotification(getEmailSubjectApp(), sb.toString()); } for (File runFile : files) { String currentRunFile = runFile.getAbsolutePath(); String msgBody = "Starting to run " + currentRunFile + " on server " + myApplicationHost; sendAlertNotification(getEmailSubjectRun(currentRunFile), msgBody); String runFileContents = loadRunConfiguration(runFile); String todayDate = new SimpleDateFormat("yyyyMMdd").format(new Date()); String fileName = FilenameUtils.removeExtension(runFile.getName()); String fileNameBase = todayDate + "_" + fileName; String logFileName = fileNameBase + ".log"; File logFile = new File(myOutputFolder + "/" + logFileName); try { if (!logFile.exists()) { logFile.createNewFile(); } BufferedWriter bw = Utils.getBufferedWriter(logFile); bw.write("Contents of the .properties file:\n" + myPropertiesFileContents); bw.write(getTimeStamp() + "Contents of the .run file: " + "\n" + runFileContents); bw.write(getCurrentRunContext(doCheckSum)); bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } // redirect System.out and System.err to the log file PrintStream ps = null; try { ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(logFile, true))); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } System.setOut(ps); System.setErr(ps); System.out.println(getTimeStamp() + "Initializing ProductionSNPCallerPlugin \n"); long start = System.nanoTime(); String[] pluginArgs = getPipelinePluginArgs(); StringBuilder builder = new StringBuilder(); for (String s : pluginArgs) { builder.append(s + "\n"); } System.out.println("Arguments passed to ProductionSNPCallerPlugin:\n" + builder.toString()); ProductionSNPCallerPlugin pscp = new ProductionSNPCallerPlugin(); System.out.println(getTimeStamp() + "Initialized ProductionSNPCallerPlugin \n"); pscp.setParameters(pluginArgs); System.out.println(getTimeStamp() + "Done with ProductionSNPCallerPlugin.setParameters() \n"); pscp.performFunction(null); System.out.println(getTimeStamp() + "Done with ProductionSNPCallerPlugin.performFunction() \n"); double elapsedSeconds = (double) (System.nanoTime() - start) / 1_000_000_000.0; System.out.println(getTimeStamp() + "Time to run ProductionSNPCallerPlugin: " + elapsedSeconds + " sec."); if (runImputation) { start = System.nanoTime(); String[] name = runFile.getName().split("\\."); String h5File = myOutputFolder + "/" + name[0] + ".hmp.h5"; String haploDir = myHaplotypeDirectory + "/" + "AllZeaGBSv27.gX.hmp.txt.gz"; String targetFile = myOutputFolder + "/" + name[0] + ".globalimp.hmp.h5"; runImputation(h5File, haploDir, targetFile); elapsedSeconds = (double) (System.nanoTime() - start) / 1_000_000_000.0; System.out.println(getTimeStamp() + "Time to run Imputation: " + elapsedSeconds + " sec."); } String email = "Ran:\n " + myInputFolder + "\n\n Tassel Pipeline Execution Time: " + elapsedSeconds + " seconds" + "\n\n Attachment:\n " + logFile.getAbsolutePath() + "\nRun on server: " + myApplicationHost; StringBuilder emailMsg = new StringBuilder(email); File toFile = new File(myArchiveDirectory + "/" + runFile.getName()); boolean movedFile = false; try { Files.move(runFile, toFile); movedFile = true; } catch (IOException ioe) { } if (movedFile) { System.out.println("Moved file " + runFile.getAbsolutePath() + " to " + toFile.getAbsolutePath()); } else { String msg = "******* COULD NOT MOVE FILE " + runFile.getAbsolutePath() + " TO " + toFile.getAbsolutePath() + " on server: " + myApplicationHost; System.out.println(msg); sendAlertNotification(getEmailSubjectRun(currentRunFile), msg); } // send email notification that a .run file has been processed SMTPClient sc = new SMTPClient(myEmailHost, myRecipientEmailAddresses); try { sc.sendMessageWithAttachment(getEmailSubjectRun(currentRunFile), emailMsg.toString(), logFile.getAbsolutePath()); } catch (javax.mail.MessagingException me) { // do nothing } } } /** * @return Arguments to run ProductionSNPCallerPlugin */ private String[] getPipelinePluginArgs() { String[] args = { "-i", myInputFolder, "-k", myKeyFile, "-e", myEnzyme, "-o", myOutputFolder, "-m", myTopmFile }; return args; } private String getPipelinePluginArgsString() { StringBuilder builder = new StringBuilder(); builder.append("-i ").append(myInputFolder); builder.append(" -k ").append(myKeyFile); builder.append(" -e ").append(myEnzyme); builder.append(" -o ").append(myOutputFolder); builder.append(" -m ").append(myTopmFile); return builder.toString(); } /** * Load application-wide properties file and initialize variables. * * @param aFileIn config file * * @return Contents of config file */ private String loadApplicationConfiguration(String aFileIn) { Properties props = new Properties(); try { File propsFile = new File(aFileIn); System.out.println(propsFile.getAbsoluteFile()); props.load(new FileInputStream(aFileIn)); } catch (IOException ioe) { System.out.println("Problem loading application configuration file:" + aFileIn); System.out.println("************** Example .properties file: "); System.out.println(EXAMPLE_CONFIG_FILE); ioe.printStackTrace(); sendAlertNotification(getEmailSubjectApp(), "Properties file could not be loaded: " + aFileIn + " on server " + myApplicationHost); System.exit(1); } // server used for sending email String configurationElement = "emailHost"; myEmailHost = props.getProperty(configurationElement, myEmailHost); // to whom the email notifications should be sent configurationElement = "emailAddress"; String address = props.getProperty(configurationElement); if (address != null) { Iterable<String> results = Splitter.on(EMAIL_ADDRESS_DELIMITER).split(address); myRecipientEmailAddresses = Iterables.toArray(results, String.class); } // directory where the .run files are expected to be configurationElement = "runDirectory"; myRunDirectory = props.getProperty(configurationElement); String response = testInputDirectory(aFileIn, myRunDirectory, configurationElement); if (response != null) { System.out.println(response); } // directory into which the key and run files are placed after being run configurationElement = "archiveDirectory"; myArchiveDirectory = props.getProperty(configurationElement); response = testInputDirectory(aFileIn, myArchiveDirectory, configurationElement); if (response != null) { System.out.println(response); } // directory into which the key and run files are placed after being run configurationElement = "haplosDirectory"; myHaplotypeDirectory = props.getProperty(configurationElement); response = testInputDirectory(aFileIn, myHaplotypeDirectory, configurationElement); if (response != null) { System.out.println(response); } // read in the contents of the properties file so it can be placed into the log BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { br = new BufferedReader(new FileReader(aFileIn)); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException ioe) { } finally { try { br.close(); } catch (Exception e) { // do nothing } } return sb.toString(); } /** * Load a file containing the information necessary to write out an XML * output file necessary for running the production pipeline * * @param aFileIn * @return */ private String loadRunConfiguration(File aFileIn) { Properties props = new Properties(); try { props.load(new FileInputStream(aFileIn)); } catch (IOException ioe) { System.err.println("Issue loading run configuration file: " + aFileIn.getName()); ioe.printStackTrace(); } String configurationElement = "inputFolder"; myInputFolder = props.getProperty(configurationElement); String response = testInputDirectory(aFileIn.getName(), myInputFolder, configurationElement); if (response != null) { System.out.println(response); } configurationElement = "enzyme"; myEnzyme = props.getProperty(configurationElement); response = testInputDirectory(aFileIn.getName(), myInputFolder, configurationElement); if (response != null) { System.out.println(response); } configurationElement = "topmFile"; myTopmFile = props.getProperty(configurationElement); response = testInputDirectory(aFileIn.getName(), myInputFolder, configurationElement); if (response != null) { System.out.println(response); } configurationElement = "outputFolder"; myOutputFolder = props.getProperty(configurationElement); response = testInputDirectory(aFileIn.getName(), myInputFolder, configurationElement); if (response != null) { System.out.println(response); } configurationElement = "keyFile"; myKeyFile = props.getProperty(configurationElement); response = testInputDirectory(aFileIn.getName(), myInputFolder, configurationElement); if (response != null) { System.out.println(response); } BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { br = new BufferedReader(new FileReader(aFileIn)); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException ioe) { } return sb.toString(); } /** * Verify that element specifying a directory exists in a configuration or * properties file and that the directory exists on the file system. * * @param filename Name of configuration/properties/.run file * @param input String containing the fully qualified path of a directory * @param configurationElement * * @return Description of the problem with the input. If return is null then * there is no problem with the entered file or directory */ private String testInputDirectory(String filename, String input, String configurationElement) { String response = null; if (input == null) { response = filename + " is missing a run configuration element: " + configurationElement; } else { File aFileOrDir = new File(input); if (!aFileOrDir.exists()) { response = filename + "'s configuration element " + configurationElement + " does not exist. Please confirm path and filename."; } } return response; } /** * Collect information about the context in which the pipeline is being run. * This information includes the following: 1) Current date and time. 2) * Name of the machine on which run occurs. 3) User account used 4) Files * used and their MD5sums 5) Contents of XML configuration file used to run * TasselPipeline * * @param calculateChecksum Calculating MD5sum can be time consuming. This * allows it to be skipped when appropriate. * * @return Information about current run */ private String getCurrentRunContext(boolean calculateChecksum) { StringBuilder sb = new StringBuilder(); // date sb.append(getTimeStamp()).append("\n"); // user account name String user = System.getProperty("user.name"); sb.append("User Account Name: ").append(user).append("\n"); // hostname sb.append("Name of Machine on which JVM is Running: ").append(myApplicationHost).append("\n"); // for each file in a directory, include the md5sum if (calculateChecksum) { sb.append(getTimeStamp()).append("MD5: ").append(myKeyFile).append(": ").append(CheckSum.getMD5Checksum(myKeyFile)).append("\n"); File inFldr = new File(myInputFolder); if (inFldr.isDirectory()) { File[] files = inFldr.listFiles(); for (File f : files) { sb.append(getTimeStamp()).append("MD5: ").append(f.getPath()).append(": ").append(CheckSum.getMD5Checksum(f.getPath())).append("\n"); } } else { sb.append(getTimeStamp()).append(CheckSum.getMD5Checksum(myInputFolder)).append("\n"); } } else { sb.append(getTimeStamp()).append("MD5sum checking has been switched off using the --skipCheckSum argument"); } return sb.toString(); } /** * * @param unImpTargetFile * @param donorFile "AllZeaGBSv27.gX.hmp.txt.gz" * @param impTargetFile * @return */ private void runImputation(String unImpTargetFile, String donorFile, String impTargetFile) { String[] args2 = new String[]{ "-hmp", unImpTargetFile, "-d", donorFile, "-o", impTargetFile, "-minMnCnt", "20", "-mxInbErr", "0.02", "-mxHybErr", "0.005", "-mnTestSite", "50", "-mxDonH", "10", // "-projA", }; StringBuilder builder = new StringBuilder(); for (String s : args2) { builder.append(s).append("\n"); } System.out.println("Arguments passed to MinorWindowViterbiImputationPlugin:\n" + builder.toString()); TasselPrefs.putAlignmentRetainRareAlleles(false); FILLINImputationPlugin plugin = new FILLINImputationPlugin(); plugin.setParameters(args2); plugin.performFunction(null); } /** * Generates basic summary information about imputation such as change in * sites or taxa count change in missing data change in heterozygosity how * many sites changed their major allele * * @param originalFile * @param imputedFile * @return */ public static String compareOriginalAgainstImputed(String originalFile, String imputedFile) { StringBuilder sb = new StringBuilder(); GenotypeTable origAlignment = ImportUtils.readGuessFormat(originalFile); GenotypeTable impAlignment = ImportUtils.readGuessFormat(imputedFile); int siteCount = origAlignment.numberOfSites(); int taxaCount = origAlignment.numberOfTaxa(); int totalSiteCount = siteCount * taxaCount; int siteDelta = Math.abs(origAlignment.numberOfSites() - impAlignment.numberOfSites()); int taxaDelta = Math.abs(origAlignment.numberOfTaxa() - impAlignment.numberOfTaxa()); int origTotalSitesNotMissing = 0, impTotalSitesNotMissing = 0, totalSitesNotMissingDelta = 0; double origProportionNotMissing = 0, impProportionNotMissing = 0, proportionNotMissingDelta = 0; int origHetCount = 0, impHetCount = 0, hetCountDelta = 0; double origHetProportion = 0, impHetProportion = 0, hetProportionDelta = 0; int flipCount = 0; // number of sites that have had a change in which allele is major int allelicChangeCount = 0; if (siteDelta == 0) { for (int i = 0; i < siteCount; i++) { // heterozygous counts origHetCount += origAlignment.heterozygousCount(i); impHetCount += impAlignment.heterozygousCount(i); hetCountDelta = impHetCount - origHetCount; //not missing origTotalSitesNotMissing += origAlignment.totalNonMissingForSite(i); impTotalSitesNotMissing += impAlignment.totalNonMissingForSite(i); // switching of major and minor allele byte origMajorAllele = origAlignment.majorAllele(i); byte impMajorAllele = impAlignment.majorAllele(i); if (origMajorAllele != impMajorAllele) { flipCount++; double diff = Math.abs(origAlignment.majorAlleleFrequency(i) - impAlignment.minorAlleleFrequency(i)); allelicChangeCount += (int) diff * taxaCount; } else { double diff = Math.abs(origAlignment.majorAlleleFrequency(i) - impAlignment.majorAlleleFrequency(i)); allelicChangeCount += (int) diff * taxaCount; } } totalSitesNotMissingDelta = impTotalSitesNotMissing - origTotalSitesNotMissing; origProportionNotMissing = (double) origTotalSitesNotMissing / (double) totalSiteCount; impProportionNotMissing = (double) impTotalSitesNotMissing / (double) totalSiteCount; proportionNotMissingDelta = impProportionNotMissing - origProportionNotMissing; hetCountDelta = impHetCount - origHetCount; origHetProportion = (double) origHetCount / (double) totalSiteCount; impHetProportion = (double) impHetCount / (double) totalSiteCount; hetProportionDelta = impHetProportion - origHetProportion; } sb.append("\nSites: " + siteCount + "\tSite Delta: " + siteDelta); sb.append("\nTaxa: " + taxaCount + "\tTaxa Delta: " + taxaDelta); sb.append("\nTotal Sites: " + totalSiteCount); sb.append("\nSites Not Missing Original: " + origTotalSitesNotMissing + "\tSites Not Missing Imputed: " + impTotalSitesNotMissing + "\tSites Not Missing Delta: " + totalSitesNotMissingDelta); sb.append("\nProportion Not Missing Original: " + origProportionNotMissing + "\tProportion Not Missing Imputed: " + impProportionNotMissing + "\tProportion Not Missing Delta: " + proportionNotMissingDelta); sb.append("\nChange in Heterozygous Sites: " + hetCountDelta); sb.append("\nHeterozygous Sites Original: " + origHetCount + "\tHeterozygous Sites Imputed: " + impHetCount + "\tHet Delta: " + hetCountDelta); sb.append("\nHeterozygous Proportion Original: " + origHetProportion + "\tHeterozygous Proportion Imputed: " + impHetProportion + "\tHet Proportion Delta: " + hetProportionDelta); sb.append("\nTotal Alleles Changed: " + allelicChangeCount + "\tProportion of Alleles Changed: " + (double) allelicChangeCount / totalSiteCount); sb.append("\nNumber of Sites Changing Major Allele: " + flipCount + "\tMajor <-> Minor Proportion: " + (double) flipCount / (double) totalSiteCount); return sb.toString(); } /** * Convenience method to provide uniformly labeled timestamps */ private static String getTimeStamp() { return "Timestamp: " + LOGGING_DATE_FORMAT.format(new Date()) + ": "; } /** * Send email to pipeline administrator when issue is encountered that may * keep pipeline from successfully completing, e.g., cannot load .properties * file, or send notification of how many times the pipeline should run, * i.e., how many .run files are present. * * @param subject Subject line of email * @param message Message body of email */ private void sendAlertNotification(String subject, String message) { SMTPClient sc = new SMTPClient(myEmailHost, myRecipientEmailAddresses); try { sc.sendMessage(subject, message); } catch (javax.mail.MessagingException me) { // do nothing } } public static void main(String[] args) { String msg = "--skipImputation flag allows imputation to be skipped\n" + "--propsFile should be followed by a fully-qualified path name without spaces\n"; String propsFile = "propsFile"; String propsFilePath = null; boolean doCheckSum = true; if (args != null) { for (int i = 0; i < args.length; i++) { if (StringUtils.containsIgnoreCase(args[i], propsFile)) { if (args.length > i + 1) { propsFilePath = args[i + 1]; i++; System.out.println("--" + propsFile + "\tUsing this properties file: " + propsFilePath); } else { System.out.println("No path following --" + propsFile + " flag.\n" + "Will look for " + DEFAULT_APPLICATION_CONFIGURATION + " file in the current directory"); System.out.println(msg); } } } } else { System.out.println(msg); } new ProductionPipeline(propsFilePath, doCheckSum); } }
package org.jpos.ee.cli; import org.apache.sshd.common.Factory; import org.apache.sshd.common.SshConstants; import org.apache.sshd.server.Command; import org.apache.sshd.server.Environment; import org.apache.sshd.server.ExitCallback; import org.apache.sshd.server.SessionAware; import org.apache.sshd.server.session.ServerSession; import org.jpos.q2.CLI; import org.jpos.q2.Q2; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class CliShellFactory implements Factory<Command> { Q2 q2; String[] prefixes; public CliShellFactory(Q2 q2, String[] prefixes) { this.q2 = q2; this.prefixes = prefixes; } public Command create() { return new JPosCLIShell(); } public class JPosCLIShell implements Command, SessionAware { InputStream in; OutputStream out; OutputStream err; SshCLI cli = null; ServerSession serverSession; public void setInputStream(InputStream in) { this.in = in; } public void setOutputStream(OutputStream out) { this.out = out; } public void setErrorStream(OutputStream err) { this.err = err; } public void setExitCallback(ExitCallback exitCallback) { } public void setSession(ServerSession serverSession) { this.serverSession = serverSession; } public void start(Environment environment) throws IOException { MyFilterOutputStream fout = new MyFilterOutputStream(out); cli = new SshCLI(q2, in, fout, null, true); try { cli.setServerSession(serverSession); cli.start(); } catch (Exception e) { throw new IOException("Could not start", e); } } public void destroy() { if (cli != null) { cli.stop(); } } } protected class MyFilterOutputStream extends FilterOutputStream { public MyFilterOutputStream(OutputStream out) { super(out); } @Override public void write(int c) throws IOException { if (c == '\n' || c == '\r') { super.write('\r'); super.write('\n'); return; } super.write(c); } @Override public void write(byte[] b, int off, int len) throws IOException { for (int i = off; i < len; i++) { write(b[i]); } } } public class SshCLI extends CLI { ServerSession serverSession = null; public SshCLI(Q2 q2, InputStream in, OutputStream out, String line, boolean keepRunning) throws IOException { super(q2, in, out, line, keepRunning); } protected boolean isRunning() { return !ctx.isStopped(); } protected void markStopped() { ctx.setStopped(true); } protected void markStarted() { ctx.setStopped(false); } protected String[] getCompletionPrefixes() { return prefixes; } protected String getPrompt() { return "q2> "; } protected void handleExit() { if (serverSession != null) { try { serverSession.disconnect(SshConstants.SSH2_DISCONNECT_BY_APPLICATION, "User triggered exit"); } catch (IOException e) { } } } public void setServerSession(ServerSession serverSession) { this.serverSession = serverSession; } } }
package net.java.sip.communicator.impl.gui; import java.awt.*; import java.util.*; import java.util.List; import javax.swing.*; import net.java.sip.communicator.impl.gui.customcontrols.*; import net.java.sip.communicator.impl.gui.event.*; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.lookandfeel.*; import net.java.sip.communicator.impl.gui.main.*; import net.java.sip.communicator.impl.gui.main.account.*; import net.java.sip.communicator.impl.gui.main.chat.*; import net.java.sip.communicator.impl.gui.main.chat.conference.*; import net.java.sip.communicator.impl.gui.main.configforms.*; import net.java.sip.communicator.impl.gui.main.contactlist.addcontact.*; import net.java.sip.communicator.impl.gui.main.login.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.configuration.event.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.gui.Container; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.util.*; import com.sun.jna.examples.*; import org.osgi.framework.*; /** * An implementation of the <tt>UIService</tt> that gives access to other * bundles to this particular swing ui implementation. * * @author Yana Stamcheva */ public class UIServiceImpl implements UIService, ServiceListener, PropertyChangeListener { private static final Logger logger = Logger.getLogger(UIServiceImpl.class); private PopupDialogImpl popupDialog; private AccountRegWizardContainerImpl wizardContainer; private Map<Container, Vector<Object>> registeredPlugins = new Hashtable<Container, Vector<Object>>(); private Vector<PluginComponentListener> pluginComponentListeners = new Vector<PluginComponentListener>(); private static final List<Container> supportedContainers = new ArrayList<Container>(); static { supportedContainers.add(Container.CONTAINER_MAIN_TOOL_BAR); supportedContainers.add(Container.CONTAINER_CONTACT_RIGHT_BUTTON_MENU); supportedContainers.add(Container.CONTAINER_GROUP_RIGHT_BUTTON_MENU); supportedContainers.add(Container.CONTAINER_TOOLS_MENU); supportedContainers.add(Container.CONTAINER_HELP_MENU); supportedContainers.add(Container.CONTAINER_CHAT_TOOL_BAR); supportedContainers.add(Container.CONTAINER_CALL_HISTORY); supportedContainers.add(Container.CONTAINER_MAIN_TABBED_PANE); supportedContainers.add(Container.CONTAINER_CHAT_HELP_MENU); } private static final Hashtable<WindowID, ExportedWindow> exportedWindows = new Hashtable<WindowID, ExportedWindow>(); private MainFrame mainFrame; private LoginManager loginManager; private ConfigurationFrame configurationFrame; private boolean exitOnClose = true; /** * Creates an instance of <tt>UIServiceImpl</tt>. */ public UIServiceImpl() { } /** * Initializes all frames and panels and shows the gui. */ public void loadApplicationGui() { this.setDefaultThemePack(); this.mainFrame = new MainFrame(); this.mainFrame.initBounds(); GuiActivator.getUIService().registerExportedWindow(mainFrame); this.loginManager = new LoginManager(mainFrame); this.popupDialog = new PopupDialogImpl(); this.wizardContainer = new AccountRegWizardContainerImpl(mainFrame); this.configurationFrame = new ConfigurationFrame(mainFrame); mainFrame.setContactList(GuiActivator.getMetaContactListService()); if (ConfigurationManager.isTransparentWindowEnabled()) { try { WindowUtils.setWindowTransparent(mainFrame, true); } catch (UnsupportedOperationException ex) { logger.error(ex.getMessage(), ex); ConfigurationManager.setTransparentWindowEnabled(false); } } if(ConfigurationManager.isApplicationVisible()) mainFrame.setVisible(true); SwingUtilities.invokeLater(new RunLoginGui()); this.initExportedWindows(); } /** * Implements <code>UISercie.getSupportedContainers</code>. Returns the * list of supported containers by this implementation . * * @see UIService#getSupportedContainers() * @return an Iterator over all supported containers. */ public Iterator getSupportedContainers() { return Collections.unmodifiableList(supportedContainers).iterator(); } /** * Creates the corresponding PluginComponentEvent and notifies all * <tt>ContainerPluginListener</tt>s that a plugin component is added or * removed from the container. * * @param pluginComponent the plugin component that is added to the * container. * @param containerID the containerID that corresponds to the container * where the component is added. * @param eventID one of the PLUGIN_COMPONENT_XXX static fields indicating * the nature of the event. */ private void firePluginEvent( PluginComponent pluginComponent, int eventID) { PluginComponentEvent evt = new PluginComponentEvent( pluginComponent, eventID); logger.debug("Will dispatch the following plugin component event: " + evt); synchronized (pluginComponentListeners) { Iterator listeners = this.pluginComponentListeners.iterator(); while (listeners.hasNext()) { PluginComponentListener l = (PluginComponentListener) listeners .next(); switch (evt.getEventID()) { case PluginComponentEvent.PLUGIN_COMPONENT_ADDED: l.pluginComponentAdded(evt); break; case PluginComponentEvent.PLUGIN_COMPONENT_REMOVED: l.pluginComponentRemoved(evt); break; default: logger.error("Unknown event type " + evt.getEventID()); } } } } /** * Implements <code>isVisible</code> in the UIService interface. Checks if * the main application window is visible. * * @return <code>true</code> if main application window is visible, * <code>false</code> otherwise * @see UIService#isVisible() */ public boolean isVisible() { return mainFrame.isVisible(); } /** * Implements <code>setVisible</code> in the UIService interface. Shows or * hides the main application window depending on the parameter * <code>visible</code>. * * @param isVisible true if we are to show the main application frame and * false otherwise. * * @see UIService#setVisible(boolean) */ public void setVisible(final boolean isVisible) { this.mainFrame.setVisible(isVisible); } /** * Locates the main application window to the new x and y coordinates. * * @param x The new x coordinate. * @param y The new y coordinate. */ public void setLocation(int x, int y) { mainFrame.setLocation(x, y); } /** * Returns the current location of the main application window. The returned * point is the top left corner of the window. * * @return The top left corner coordinates of the main application window. */ public Point getLocation() { return mainFrame.getLocation(); } /** * Returns the size of the main application window. * * @return the size of the main application window. */ public Dimension getSize() { return mainFrame.getSize(); } /** * Sets the size of the main application window. * * @param width The width of the window. * @param height The height of the window. */ public void setSize(int width, int height) { mainFrame.setSize(width, height); } /** * Implements <code>minimize</code> in the UIService interface. Minimizes * the main application window. * * @see UIService#minimize() */ public void minimize() { this.mainFrame.minimize(); } /** * Implements <code>maximize</code> in the UIService interface. Maximizes * the main application window. * * @see UIService#maximize() */ public void maximize() { this.mainFrame.maximize(); } /** * Implements <code>restore</code> in the UIService interface. Restores * the main application window. * * @see UIService#restore() */ public void restore() { if (mainFrame.isVisible()) { if (mainFrame.getState() == JFrame.ICONIFIED) mainFrame.setState(JFrame.NORMAL); mainFrame.toFront(); } else mainFrame.setVisible(true); } /** * Implements <code>resize</code> in the UIService interface. Resizes the * main application window. * * @param height the new height of tha main application frame. * @param width the new width of the main application window. * * @see UIService#resize(int, int) */ public void resize(int width, int height) { this.mainFrame.setSize(width, height); } /** * Implements <code>move</code> in the UIService interface. Moves the main * application window to the point with coordinates - x, y. * * @param x the value of X where the main application frame is to be placed. * @param y the value of Y where the main application frame is to be placed. * * @see UIService#move(int, int) */ public void move(int x, int y) { this.mainFrame.setLocation(x, y); } /** * Implements the <code>UIService.setExitOnMainWindowClose</code>. Sets a * boolean property, which indicates whether the application should be * exited when the main application window is closed. * * @param exitOnClose specifies if closing the main application window * should also be exiting the application. */ public void setExitOnMainWindowClose(boolean exitOnClose) { this.exitOnClose = exitOnClose; if (exitOnClose) mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); else mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); } /** * Implements the <code>UIService.getExitOnMainWindowClose</code>. * Returns the boolean property, which indicates whether the application * should be exited when the main application window is closed. * * @return determines whether the UI impl would exit the application when * the main application window is closed. */ public boolean getExitOnMainWindowClose() { return this.exitOnClose; } /** * Adds all <tt>ExportedWindow</tt>s to the list of application windows, * which could be used from other bundles. Once registered in the * <tt>UIService</tt> this window could be obtained through the * <tt>getExportedWindow(WindowID)</tt> method and could be shown, * hidden, resized, moved, etc. */ public void initExportedWindows() { registerExportedWindow(configurationFrame); registerExportedWindow(new AddContactWizardExportedWindow(mainFrame)); } /** * Registers the given <tt>ExportedWindow</tt> to the list of windows that * could be accessed from other bundles. * * @param window the window to be exported */ public void registerExportedWindow(ExportedWindow window) { exportedWindows.put(window.getIdentifier(), window); } /** * Unregisters the given <tt>ExportedWindow</tt> from the list of windows * that could be accessed from other bundles. * * @param window the window to no longer be exported */ public void unregisterExportedWindow(ExportedWindow window) { WindowID identifier = window.getIdentifier(); ExportedWindow removed = exportedWindows.remove(identifier); /* * In case the unexpected happens and we happen to have the same * WindowID for multiple ExportedWindows going through * #registerExportedWindow(), we have to make sure we're not * unregistering some other ExportedWindow which has overwritten the * registration of the specified window. */ if ((removed != null) && !removed.equals(window)) { /* * We accidentally unregistered another window so bring back its * registration. */ exportedWindows.put(identifier, removed); /* Now unregister the right window. */ for (Iterator<Map.Entry<WindowID, ExportedWindow>> entryIt = exportedWindows.entrySet().iterator(); entryIt.hasNext();) { Map.Entry<WindowID, ExportedWindow> entry = entryIt.next(); if (window.equals(entry.getValue())) entryIt.remove(); } } } /** * Sets the contact list service to this UI Service implementation. * @param contactList the MetaContactList service */ public void setContactList(MetaContactListService contactList) { this.mainFrame.setContactList(contactList); } public void addPluginComponentListener(PluginComponentListener l) { synchronized (pluginComponentListeners) { pluginComponentListeners.add(l); } } public void removePluginComponentListener(PluginComponentListener l) { synchronized (pluginComponentListeners) { pluginComponentListeners.remove(l); } } /** * Implements <code>getSupportedExportedWindows</code> in the UIService * interface. Returns an iterator over a set of all windows exported by * this implementation. * * @return an Iterator over all windows exported by this implementation of * the UI service. * * @see UIService#getSupportedExportedWindows() */ public Iterator getSupportedExportedWindows() { return Collections.unmodifiableMap(exportedWindows).keySet().iterator(); } /** * Implements the <code>getExportedWindow</code> in the UIService * interface. Returns the window corresponding to the given * <tt>WindowID</tt>. * * @param windowID the id of the window we'd like to retrieve. * * @return a reference to the <tt>ExportedWindow</tt> instance corresponding * to <tt>windowID</tt>. * @see UIService#getExportedWindow(WindowID) */ public ExportedWindow getExportedWindow(WindowID windowID) { if (exportedWindows.containsKey(windowID)) { return (ExportedWindow) exportedWindows.get(windowID); } return null; } /** * Implements the <code>UIService.isExportedWindowSupported</code> method. * Checks if there's an exported component for the given * <tt>WindowID</tt>. * * @param windowID the id of the window that we're making the query for. * * @return true if a window with the corresponding windowID is exported by * the UI service implementation and false otherwise. * * @see UIService#isExportedWindowSupported(WindowID) */ public boolean isExportedWindowSupported(WindowID windowID) { return exportedWindows.containsKey(windowID); } /** * Implements <code>getPopupDialog</code> in the UIService interface. * Returns a <tt>PopupDialog</tt> that could be used to show simple * messages, warnings, errors, etc. * * @return a <tt>PopupDialog</tt> that could be used to show simple * messages, warnings, errors, etc. * * @see UIService#getPopupDialog() */ public PopupDialog getPopupDialog() { return this.popupDialog; } /** * Implements <code>getChat</code> in the UIService interface. If a * chat for the given contact exists already - returns it, otherwise * creates a new one. * * @param contact the contact that we'd like to retrieve a chat window for. * * @return a Chat corresponding to the specified contact. * * @see UIService#getChat(Contact) */ public Chat getChat(Contact contact) { MetaContact metaContact = mainFrame.getContactList() .findMetaContactByContact(contact); ChatWindowManager chatWindowManager = mainFrame.getChatWindowManager(); MetaContactChatPanel chatPanel = chatWindowManager.getContactChat(metaContact); return chatPanel; } /** * Returns the <tt>Chat</tt> corresponding to the given <tt>ChatRoom</tt>. * * @param chatRoom the <tt>ChatRoom</tt> for which the searched chat is * about. * @return the <tt>Chat</tt> corresponding to the given <tt>ChatRoom</tt>. */ public Chat getChat(ChatRoom chatRoom) { ChatWindowManager chatWindowManager = mainFrame.getChatWindowManager(); ConferenceChatPanel chatPanel = chatWindowManager.getMultiChat(chatRoom); return chatPanel; } /** * Returns the selected <tt>Chat</tt>. * * @return the selected <tt>Chat</tt>. */ public Chat getCurrentChat() { ChatWindowManager chatWindowManager = mainFrame.getChatWindowManager(); return chatWindowManager.getSelectedChat(); } /** * Returns the phone number currently entered in the phone number field. * * @return the phone number currently entered in the phone number field. */ public String getCurrentPhoneNumber() { return mainFrame.getCurrentPhoneNumber(); } /** * Implements the <code>UIService.isContainerSupported</code> method. * Checks if the plugable container with the given Container is supported * by this implementation. * * @param containderID the id of the container that we're making the query * for. * * @return true if the container with the specified id is exported by the * implementation of the UI service and false otherwise. * * @see UIService#isContainerSupported(Container) */ public boolean isContainerSupported(Container containderID) { return supportedContainers.contains(containderID); } /** * Implements the <code>UIService.getAccountRegWizardContainer</code> * method. Returns the current implementation of the * <tt>AccountRegistrationWizardContainer</tt>. * * @see UIService#getAccountRegWizardContainer() * * @return a reference to the currently valid instance of * <tt>AccountRegistrationWizardContainer</tt>. */ public WizardContainer getAccountRegWizardContainer() { return this.wizardContainer; } /** * Returns an instance of <tt>AuthenticationWindow</tt> for the given * protocol provider, realm and user credentials. */ public ExportedWindow getAuthenticationWindow( ProtocolProviderService protocolProvider, String realm, UserCredentials userCredentials, boolean isUserNameEditable) { return new AuthenticationWindow(mainFrame, protocolProvider, realm, userCredentials, isUserNameEditable); } /** * Returns a default implementation of the <tt>SecurityAuthority</tt> * interface that can be used by non-UI components that would like to launch * the registration process for a protocol provider. Initially this method * was meant for use by the systray bundle and the protocol URI handlers. * * @param protocolProvider the <tt>ProtocolProviderService</tt> for which * the authentication window is about. * * @return a default implementation of the <tt>SecurityAuthority</tt> * interface that can be used by non-UI components that would like to launch * the registration process for a protocol provider. */ public SecurityAuthority getDefaultSecurityAuthority( ProtocolProviderService protocolProvider) { return new DefaultSecurityAuthority(protocolProvider); } /** * Returns the LoginManager. * @return the LoginManager */ public LoginManager getLoginManager() { return loginManager; } /** * Returns the <tt>MainFrame</tt>. This is the class defining the main * application window. * * @return the <tt>MainFrame</tt> */ public MainFrame getMainFrame() { return mainFrame; } /** * The <tt>RunLogin</tt> implements the Runnable interface and is used to * shows the login windows in a seperate thread. */ private class RunLoginGui implements Runnable { public void run() { loginManager.runLogin(mainFrame); } } /** * The <tt>RunApplication</tt> implements the Runnable interface and is used to * shows the main application window in a separate thread. */ private class RunApplicationGui implements Runnable { public void run() { mainFrame.setVisible(true); } } /** * Sets the look&feel and the theme. */ private void setDefaultThemePack() { // we need to set the UIDefaults class loader so that it may access // resources packed inside OSGI bundles UIManager.put("ClassLoader", getClass().getClassLoader()); String osName = System.getProperty("os.name"); if (!osName.startsWith("Mac")) { /* * Attempt to use the OS-native LookAndFeel instead of * SIPCommLookAndFeel. */ String laf = UIManager.getSystemLookAndFeelClassName(); boolean lafIsSet = false; if ((laf != null) && !laf .equals(UIManager.getCrossPlatformLookAndFeelClassName())) { try { UIManager.setLookAndFeel(laf); lafIsSet = true; } catch (ClassNotFoundException ex) { /* * Ignore the exceptions because we're only trying to set * the native LookAndFeel and, if it fails, we'll use * SIPCommLookAndFeel. */ } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } } if (!lafIsSet) { try { SIPCommLookAndFeel lf = new SIPCommLookAndFeel(); SIPCommLookAndFeel .setCurrentTheme(new SIPCommDefaultTheme()); // Check the isLookAndFeelDecorated property and set the // appropriate // default decoration. boolean isDecorated = new Boolean(GuiActivator.getResources() .getSettingsString("isLookAndFeelDecorated")) .booleanValue(); if (isDecorated) { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); } UIManager.setLookAndFeel(lf); } catch (UnsupportedLookAndFeelException e) { logger.error("The provided Look & Feel is not supported.", e); } } } } /** * Notifies all plugin containers of a <tt>PluginComponent</tt> * registration. */ public void serviceChanged(ServiceEvent event) { Object sService = GuiActivator.bundleContext.getService( event.getServiceReference()); // we don't care if the source service is not a plugin component if (! (sService instanceof PluginComponent)) { return; } PluginComponent pluginComponent = (PluginComponent) sService; if (event.getType() == ServiceEvent.REGISTERED) { logger .info("Handling registration of a new Plugin Component."); if(pluginComponent.getComponent() == null || !(pluginComponent.getComponent() instanceof Component)) { logger.error("Plugin Component type is not supported." + "Should provide a plugin in AWT, SWT or Swing."); logger.debug("Logging exception to show the calling plugin", new Exception("")); return; } this.firePluginEvent( pluginComponent, PluginComponentEvent.PLUGIN_COMPONENT_ADDED); } else if (event.getType() == ServiceEvent.UNREGISTERING) { this.firePluginEvent( pluginComponent, PluginComponentEvent .PLUGIN_COMPONENT_REMOVED); } } /** * Returns the corresponding <tt>BorderLayout</tt> constraint from the given * <tt>Container</tt> constraint. * * @param containerConstraints constraints defined in the <tt>Container</tt> * @return the corresponding <tt>BorderLayout</tt> constraint from the given * <tt>Container</tt> constraint. */ public static Object getBorderLayoutConstraintsFromContainer( Object containerConstraints) { Object layoutConstraint = null; if (containerConstraints == null) return null; if (containerConstraints.equals(Container.START)) layoutConstraint = BorderLayout.LINE_START; else if (containerConstraints.equals(Container.END)) layoutConstraint = BorderLayout.LINE_END; else if (containerConstraints.equals(Container.TOP)) layoutConstraint = BorderLayout.NORTH; else if (containerConstraints.equals(Container.BOTTOM)) layoutConstraint = BorderLayout.SOUTH; else if (containerConstraints.equals(Container.LEFT)) layoutConstraint = BorderLayout.WEST; else if (containerConstraints.equals(Container.RIGHT)) layoutConstraint = BorderLayout.EAST; return layoutConstraint; } private class DefaultPluginComponent implements PluginComponent { private Component component; private Container container; public DefaultPluginComponent( Component component, Container container) { this.component = component; this.container = container; } public Object getComponent() { return component; } public String getConstraints() { return Container.END; } public Container getContainer() { return container; } public String getName() { return component.getName(); } public void setCurrentContact(MetaContact metaContact) { if (component instanceof ContactAwareComponent) ((ContactAwareComponent) component) .setCurrentContact(metaContact); } public void setCurrentContactGroup(MetaContactGroup metaGroup) { if (component instanceof ContactAwareComponent) ((ContactAwareComponent) component) .setCurrentContactGroup(metaGroup); } public int getPositionIndex() { return -1; } public boolean isNativeComponent() { return false; } } public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals( "net.java.sip.communicator.impl.gui.isTransparentWindowEnabled")) { String isTransparentString = (String) evt.getNewValue(); boolean isTransparentWindowEnabled = new Boolean(isTransparentString).booleanValue(); try { WindowUtils.setWindowTransparent( mainFrame, isTransparentWindowEnabled); } catch (UnsupportedOperationException ex) { logger.error(ex.getMessage(), ex); if (isTransparentWindowEnabled) { new ErrorDialog(mainFrame, Messages.getI18NString("error").getText(), Messages.getI18NString("transparencyNotEnabled").getText()) .showDialog(); } ConfigurationManager.setTransparentWindowEnabled(false); } } else if (evt.getPropertyName().equals( "net.java.sip.communicator.impl.gui.windowTransparency")) { mainFrame.repaint(); } } }
package com.cv4j.image.util; import com.cv4j.core.binary.ConnectedAreaLabel; import com.cv4j.core.binary.MorphOpen; import com.cv4j.core.binary.Threshold; import com.cv4j.core.datamodel.ByteProcessor; import com.cv4j.core.datamodel.ImageProcessor; import com.cv4j.core.datamodel.Rect; import com.cv4j.core.datamodel.Size; import java.util.ArrayList; import java.util.List; public class QRCodeScanner { public Rect findQRCodeBounding(ImageProcessor image) { Rect rect = new Rect(); image.getImage().convert2Gray(); ByteProcessor src = ((ByteProcessor)image); int width = src.getWidth(); int height = src.getHeight(); Threshold t = new Threshold(); t.process(src, Threshold.THRESH_VALUE, Threshold.METHOD_THRESH_BINARY_INV, 20); MorphOpen mOpen = new MorphOpen(); byte[] data = new byte[width*height]; System.arraycopy(src.getGray(), 0, data, 0, data.length); ByteProcessor copy = new ByteProcessor(data, width, height); mOpen.process(src, new Size(4, 24)); mOpen.process(copy, new Size(24, 4)); for(int i=0; i<data.length; i++) { int pv = src.getGray()[i]&0xff; if(pv == 255) { copy.getGray()[i] = (byte)255; } } src.putGray(copy.getGray()); ConnectedAreaLabel ccal = new ConnectedAreaLabel(); List<Rect> rectList = new ArrayList<>(); int[] labelMask = new int[width*height]; ccal.process(src, labelMask, rectList, true); float w = 0; float h = 0; float rate = 0; List<Rect> qrRects = new ArrayList<>(); for(Rect roi : rectList) { w = roi.width; h = roi.height; rate = (float)Math.abs(w / h - 1.0); if(rate < 0.05 && isRect(roi, labelMask, width, height)) { qrRects.add(roi); } } // find RQ code bounding Rect[] blocks = qrRects.toArray(new Rect[0]); if (blocks.length == 1) { rect.x = blocks[0].x-5; rect.y = blocks[0].y- 5; rect.width= blocks[0].width + 10; rect.height = blocks[0].height + 10; } else if (blocks.length == 3) { for (int i = 0; i < 2; i++) { int idx1 = blocks[i].tl().y*width + blocks[i].tl().x; for (int j = i + 1; j < 3; j++) { int idx2 = blocks[j].tl().y*width + blocks[j].tl().x; if (idx2 < idx1){ Rect temp = blocks[i]; blocks[i] = blocks[j]; blocks[j] = temp; } } } rect.x = blocks[0].x - 5; rect.y = blocks[0].y - 5; rect.width = blocks[1].width + (blocks[1].x - blocks[0].x) + 10; rect.height = (blocks[2].height + blocks[2].y - blocks[0].y) + 10; } else { rect.width = 0; rect.height = 0; } return rect; } private boolean isRect(Rect roi, int[] labelMask, int w, int h) { int ox = roi.x; int oy = roi.y; int width = roi.width; int height = roi.height; byte[] image = new byte[width*height]; int label = roi.labelIdx; for(int row=oy; row<(oy + height); row++) { for(int col=ox; col<(ox + width); col++) { int v = labelMask[row*w + col]; if(v == label) { image[(row - oy) * width + col - ox] = (byte)255; } } } int cx = width / 2; int offset = 0; if (width % 2 > 0) { offset = 1; } int sum=0; int v1=0, v2=0; for(int row=0; row<height; row++) { for(int col=0; col<cx; col++) { v1 = image[row*width+ col]&0xff; v2 = image[row*width-1-col]&0xff; sum += Math.abs(v1-v2); } } return (sum / 255) <= 10; } }
package org.voltdb.export; import java.io.IOException; import java.nio.ByteBuffer; import junit.framework.TestCase; import org.voltdb.messaging.FastDeserializer; import org.voltcore.utils.DeferredSerialization; public class TestExportProtoMessage extends TestCase { private void assertMsgType(ExportProtoMessage m, int skip) { if ((skip & ExportProtoMessage.kOpen) == 0) assertFalse(m.isOpen()); if ((skip & ExportProtoMessage.kOpenResponse) == 0) assertFalse(m.isOpenResponse()); if ((skip & ExportProtoMessage.kPoll) == 0) assertFalse(m.isPoll()); if ((skip & ExportProtoMessage.kPollResponse) == 0) assertFalse(m.isPollResponse()); if ((skip & ExportProtoMessage.kAck) == 0) assertFalse(m.isAck()); if ((skip & ExportProtoMessage.kClose) == 0) assertFalse(m.isClose()); if ((skip & ExportProtoMessage.kError) == 0) assertFalse(m.isError()); } public void testIsOpen() { ExportProtoMessage m = new ExportProtoMessage( 0, 1, ""); m.open(); assertTrue(m.isOpen()); assertMsgType(m, ExportProtoMessage.kOpen); } public void testIsOpenResponse() { ExportProtoMessage m = new ExportProtoMessage( 0, 1, ""); m.openResponse(null); assertTrue(m.isOpenResponse()); assertMsgType(m, ExportProtoMessage.kOpenResponse); } public void testIsPoll() { ExportProtoMessage m = new ExportProtoMessage( 0, 1, ""); m.poll(); assertTrue(m.isPoll()); assertMsgType(m, ExportProtoMessage.kPoll); } public void testIsPollResponse() { ExportProtoMessage m = new ExportProtoMessage( 0, 1, ""); ByteBuffer bb = ByteBuffer.allocate(10); m.pollResponse(1024, bb); assertTrue(m.isPollResponse()); assertTrue(m.getData() == bb); assertTrue(m.getAckOffset() == 1024); assertMsgType(m, ExportProtoMessage.kPollResponse); } public void testIsAck() { ExportProtoMessage m = new ExportProtoMessage( -1, 1, ""); m.ack(2048); assertTrue(m.isAck()); assertTrue(m.getAckOffset() == 2048); assertMsgType(m, ExportProtoMessage.kAck); } public void testIsClose() { ExportProtoMessage m = new ExportProtoMessage( -1, 1, ""); m.close(); assertTrue(m.isClose()); assertMsgType(m, ExportProtoMessage.kClose); } public void testIsError() { ExportProtoMessage m = new ExportProtoMessage( -1, 1, ""); m.error(); assertTrue(m.isError()); assertMsgType(m, ExportProtoMessage.kError); } // also tests toBuffer, serializableBytes() // serialize with bytebuffer data public void testReadExternal1() throws IOException { ExportProtoMessage m1, m2; m1 = new ExportProtoMessage( -1, 1, "foo"); ByteBuffer b = ByteBuffer.allocate(100); b.putInt(100); b.putInt(200); b.flip(); m1.pollResponse(1000, b); ByteBuffer bm1 = m1.toBuffer(); FastDeserializer fdsm1 = new FastDeserializer(bm1); // test the length prefix, which isn't consumed by readExternal assertEquals(m1.serializableBytes(), fdsm1.readInt()); m2 = ExportProtoMessage.readExternal(fdsm1); assertTrue(m2.isPollResponse()); assertMsgType(m2, ExportProtoMessage.kPollResponse); assertEquals(1000, m2.getAckOffset()); assertEquals(100, m2.getData().getInt()); assertEquals(200, m2.getData().getInt()); assertEquals(1, m2.getPartitionId()); assertEquals("foo", m2.getSignature()); } // also tests toBuffer, serializableBytes() // with null data payload public void testReadExternal2() throws IOException { ExportProtoMessage m1, m2; m1 = new ExportProtoMessage( -1, 1, "foo"); m1.ack(2000); ByteBuffer bm1 = m1.toBuffer(); FastDeserializer fdsm1 = new FastDeserializer(bm1); // test the length prefix, which isn't consumed by readExternal assertEquals(m1.serializableBytes(), fdsm1.readInt()); m2 = ExportProtoMessage.readExternal(fdsm1); assertTrue(m2.isAck()); assertMsgType(m2, ExportProtoMessage.kAck); assertEquals(2000, m2.getAckOffset()); assertEquals(0, m2.getData().capacity()); assertEquals(1, m2.getPartitionId()); assertEquals("foo", m2.getSignature()); } // also tests toBuffer, serializableBytes() // serialize with 0 capacity bytebuffer data public void testReadExternal3() throws IOException { ExportProtoMessage m1, m2; m1 = new ExportProtoMessage( -1, 1, "foo"); ByteBuffer b = ByteBuffer.allocate(0); m1.pollResponse(1000, b); ByteBuffer bm1 = m1.toBuffer(); FastDeserializer fdsm1 = new FastDeserializer(bm1); // test the length prefix, which isn't consumed by readExternal assertEquals(m1.serializableBytes(), fdsm1.readInt()); m2 = ExportProtoMessage.readExternal(fdsm1); assertTrue(m2.isPollResponse()); assertMsgType(m2, ExportProtoMessage.kPollResponse); assertEquals(1000, m2.getAckOffset()); assertEquals(0, m2.getData().capacity()); assertEquals(1, m2.getPartitionId()); assertEquals("foo", m2.getSignature()); } // mimic what raw processor and the el poller do to each other public void testELPollerPattern() throws IOException { final ExportProtoMessage r = new ExportProtoMessage( -1, 1, "bar"); ByteBuffer data = ByteBuffer.allocate(8); data.putInt(100); data.putInt(200); data.flip(); r.pollResponse(1000, data); ByteBuffer b = new DeferredSerialization() { @Override public ByteBuffer[] serialize() throws IOException { ByteBuffer buf = ByteBuffer.allocate(r.serializableBytes() + 4); r.flattenToBuffer(buf); return new ByteBuffer[] { buf }; } @Override public void cancel() { } }.serialize()[0]; b.flip(); assertEquals(39, b.getInt()); FastDeserializer fds = new FastDeserializer(b); ExportProtoMessage m = ExportProtoMessage.readExternal(fds); assertEquals(1, m.m_partitionId); assertEquals("bar", m.getSignature()); assertTrue(m.isPollResponse()); assertTrue(m.getData().remaining() == 8); assertMsgType(m, ExportProtoMessage.kPollResponse); } }
package org.jeo.geom; import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.CoordinateSequenceFactory; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryCollection; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.LinearRing; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * A builder for {@link Geometry} objects. Primarily intended to * support fluent programming in test code. * <p> * Features include: * <ul> * <li>Both 2D and 3D coordinate dimensions are supported * (assuming the provided {@link CoordinateSequenceFactory} supports them) * <li>Sequences of ordinate values can be supplied in a number of ways * <li>Rings do not need to be explicitly closed; a closing point will be * supplied if needed * <li>Empty geometries of all types can be created * <li>Composite geometries are validated to ensure they have a consistent * GeometryFactory and coordinate sequence dimension * <p> * Examples of intended usage are: * * <pre> * GeometryBuilder gb = new GeometryBuilder(geomFact); * LineString line = gb.linestring(1,2, 3,4); * Polygon poly = gb.polygon(0,0, 0,1, 1,1, 1,0); * Polygon box = gb.box(0,0, 1,1); * Polygon hexagon = gb.circle(0,0, 1,1, 6); * Polygon polyhole = gb.polygon(gb.linearring(0,0, 0,10, 10,10, 10,0), gb.linearring(1,1, 1,9, 9,9, 9,1)) * </pre> * * @author Martin Davis - OpenGeo * */ public class GeometryBuilder { private GeometryFactory geomFact; private CoordinateSequenceFactory csFact; /** * Create a new instance using the default {@link GeometryFactory}. */ public GeometryBuilder() { this(new GeometryFactory()); } /** * Creates a new instance using a provided GeometryFactory. * * @param geomFact the factory to use */ public GeometryBuilder(GeometryFactory geomFact) { this.geomFact = geomFact; csFact = geomFact.getCoordinateSequenceFactory(); } /** * Creates an empty Point * * @return an empty Point */ public Point point() { return geomFact.createPoint(createCS(new double[0], 2)); } /** * Creates an empty Point with coordinate dimension = 3. * * @return an empty Point */ public Point pointZ() { return geomFact.createPoint(createCS(new double[0], 3)); } /** * Creates a 2D Point. * * @param x the X ordinate * @param y the Y ordinate * @return a Point */ public Point point(double x, double y) { return geomFact.createPoint(createCS(new double[] { x, y }, 2)); } /** * Creates a 3D Point. * * @param x the X ordinate * @param y the Y ordinate * @param z the Z ordinate * @return a Point */ public Point pointZ(double x, double y, double z) { return geomFact.createPoint(createCS(new double[] { x, y, z }, 3)); } /** * Creates an empty 2D LineString * * @return an empty LineString */ public LineString lineString() { return geomFact.createLineString(createCS(new double[0], 2)); } /** * Creates an empty 3D LineString * * @return an empty LineString */ public LineString lineStringZ() { return geomFact.createLineString(createCS(new double[0], 3)); } /** * Creates a 2D LineString. * * @param ord the XY ordinates * @return a LineString */ public LineString lineString(double... ord) { return geomFact.createLineString(createCS(ord, 2)); } /** * Creates a 3D LineString. * * @param ord the XYZ ordinates * @return a LineString */ public LineString lineStringZ(double... ord) { return geomFact.createLineString(createCS(ord, 3)); } /** * Creates an empty 2D LinearRing * * @return an empty LinearRing */ public LinearRing linearRing() { return geomFact.createLinearRing(createRingCS(new double[0], 2)); } /** * Creates an empty 3D LinearRing * * @return an empty LinearRing */ public LinearRing linearRingZ() { return geomFact.createLinearRing(createRingCS(new double[0], 3)); } /** * Creates a 2D LinearRing. If the supplied coordinate list is not closed, a * closing coordinate is added. * * @param ord * @return a LinearRing */ public LinearRing linearRing(double... ord) { return geomFact.createLinearRing(createRingCS(ord, 2)); } /** * Creates a 3D LinearRing. If the supplied coordinate list is not closed, a * closing coordinate is added. * * @param ord the XYZ ordinates * @return a LinearRing */ public LinearRing linearRingZ(double... ord) { return geomFact.createLinearRing(createRingCS(ord, 3)); } /** * Creates an empty 2D Polygon. * * @return an empty Polygon */ public Polygon polygon() { return geomFact.createPolygon(linearRing(), null); } /** * Creates an empty 3D Polygon. * * @return an empty Polygon */ public Polygon polygonZ() { return geomFact.createPolygon(linearRingZ(), null); } /** * Creates a Polygon from a list of XY coordinates. * * @param ord a list of XY ordinates * @return a Polygon */ public Polygon polygon(double... ord) { return geomFact.createPolygon(linearRing(ord), null); } /** * Creates a Polygon from a list of XYZ coordinates. * * @param ord a list of XYZ ordinates * @return a Polygon */ public Polygon polygonZ(double... ord) { return geomFact.createPolygon(linearRingZ(ord), null); } /** * Creates a Polygon from an exterior ring. The coordinate dimension of the * Polygon is the dimension of the LinearRing. * * @param shell the exterior ring * @return a Polygon */ public Polygon polygon(LinearRing shell) { return geomFact.createPolygon(shell, null); } /** * Creates a Polygon with a hole from an exterior ring and an interior ring. * * @param shell the exterior ring * @param hole the interior ring * @return a Polygon with a hole */ public Polygon polygon(LinearRing shell, LinearRing hole) { return geomFact.createPolygon(shell, new LinearRing[] { hole }); } /** * Creates a Polygon with a hole from an exterior ring and an interior ring * supplied by the rings of Polygons. * * @param shell the exterior ring * @param hole the interior ring * @return a Polygon with a hole */ public Polygon polygon(Polygon shell, Polygon hole) { return geomFact.createPolygon((LinearRing) shell.getExteriorRing(), new LinearRing[] { (LinearRing) hole.getExteriorRing() }); } /** * Creates a rectangular 2D Polygon from X and Y bounds. * * @param x1 the lower X bound * @param y1 the lower Y bound * @param x2 the upper X bound * @param y2 the upper Y bound * @return a 2D Polygon */ public Polygon box(double x1, double y1, double x2, double y2) { double[] ord = new double[] { x1, y1, x1, y2, x2, y2, x2, y1, x1, y1 }; return polygon(ord); } /** * Creates a rectangular 3D Polygon from X and Y bounds. * * @param x1 the lower X bound * @param y1 the lower Y bound * @param x2 the upper X bound * @param y2 the upper Y bound * @param z the Z value for all coordinates * @return a 3D Polygon */ public Polygon boxZ(double x1, double y1, double x2, double y2, double z) { double[] ord = new double[] { x1, y1, z, x1, y2, z, x2, y2, z, x2, y1, z, x1, y1, z }; return polygonZ(ord); } /** * Creates an elliptical Polygon from a bounding box with a given number of * sides. * * @param x1 * @param y1 * @param x2 * @param y2 * @param nsides * @return a 2D Polygon */ public Polygon ellipse(double x1, double y1, double x2, double y2, int nsides) { double rx = Math.abs(x2 - x1) / 2; double ry = Math.abs(y2 - y1) / 2; double cx = Math.min(x1, x2) + rx; double cy = Math.min(y1, y2) + ry; double[] ord = new double[2 * nsides + 2]; double angInc = 2 * Math.PI / nsides; // create ring in CW order for (int i = 0; i < nsides; i++) { double ang = -(i * angInc); ord[2 * i] = cx + rx * Math.cos(ang); ord[2 * i + 1] = cy + ry * Math.sin(ang); } ord[2 * nsides] = ord[0]; ord[2 * nsides + 1] = ord[1]; return polygon(ord); } /** * Creates a circular Polygon with a given center, radius and number of sides. * * @param x the center X ordinate * @param y the center Y ordinate * @param radius the radius * @param nsides the number of sides * @return a 2D Polygon */ public Polygon circle(double x, double y, double radius, int nsides) { return ellipse(x - radius, y - radius, x + radius, y + radius, nsides); } /** * Creates a MultiPoint with 2 2D Points. * * @param x1 the X ordinate of the first point * @param y1 the Y ordinate of the first point * @param x2 the X ordinate of the second point * @param y2 the Y ordinate of the second point * @return A MultiPoint */ public MultiPoint multiPoint(double x1, double y1, double x2, double y2) { return geomFact .createMultiPoint(new Point[] { point(x1, y1), point(x2, y2) }); } /** * Creates a 2D MultiPoint. * * @param ord the XY ordinates * @return a MutliPoint */ public MultiPoint multiPoint(double... ord) { return geomFact.createMultiPoint(createCS(ord, 2)); } /** * Creates a MultiPoint with 2 3D Points. * * @param x1 the X ordinate of the first point * @param y1 the Y ordinate of the first point * @param z1 the Z ordinate of the first point * @param x2 the X ordinate of the second point * @param y2 the Y ordinate of the second point * @param z2 the Z ordinate of the second point * @return A 3D MultiPoint */ public MultiPoint multiPointZ(double x1, double y1, double z1, double x2, double y2, double z2) { return geomFact.createMultiPoint(new Point[] { pointZ(x1, y1, z1), pointZ(x2, y2, z2) }); } /** * Creates a MultiLineString from a set of LineStrings * * @param lines the component LineStrings * @return a MultiLineString */ public MultiLineString multiLineString(LineString... lines) { return geomFact.createMultiLineString(lines); } /** * Creates a MultiPolygon from a set of Polygons. * * @param polys the component polygons * @return A MultiPolygon */ public MultiPolygon multiPolygon(Polygon... polys) { return geomFact.createMultiPolygon(polys); } /** * Creates a GeometryCollection from a set of Geometrys * * @param geoms the component Geometrys * @return a GeometryCollection */ public GeometryCollection geometryCollection(Geometry... geoms) { return geomFact.createGeometryCollection(geoms); } /** * Tests whether a sequence of ordinates of a given dimension is closed (i.e. * has the first and last coordinate identical). * * @param ord the list of ordinate values * @param dim the dimension of each coordinate * @return true if the sequence is closed */ private boolean isClosed(double[] ord, int dim) { int n = ord.length / dim; if (n == 0) return true; int lastPos = dim * (n - 1); double lastx = ord[lastPos]; double lasty = ord[lastPos + 1]; boolean isClosed = lastx == ord[0] && lasty == ord[1]; return isClosed; } /** * @param ord * @param dim * @return */ private CoordinateSequence createRingCS(double[] ord, int dim) { if (isClosed(ord, dim)) return createCS(ord, dim); double[] ord2 = new double[ord.length + dim]; System.arraycopy(ord, 0, ord2, 0, ord.length); // copy first coord to last int lastPos = ord.length; for (int i = 0; i < dim; i++) { ord2[lastPos + i] = ord2[i]; } return createCS(ord2, dim); } /** * @param ord * @param dim * @return */ private CoordinateSequence createCS(double[] ord, int dim) { if (ord.length % dim != 0) throw new IllegalArgumentException("Ordinate array length " + ord.length + " is not a multiple of dimension " + dim); int n = ord.length / dim; CoordinateSequence cs = csFact.create(n, dim); for (int i = 0; i < n; i++) { for (int d = 0; d < dim; d++) cs.setOrdinate(i, d, ord[dim * i + d]); } return cs; } }
package net.net16.jeremiahlowe.scicalc.utility; import java.awt.Color; import java.awt.Graphics; import net.net16.jeremiahlowe.scicalc.Enums.LineStyle; public class LineDrawer { public static int defaultIteratorPixels = 30; public static LineStyle defaultLineStyle = LineStyle.Normal; private LineStyle style = defaultLineStyle; private Color lineColor = Color.BLACK; private int lineWidth = 1; private int lineIteratorPixels = 10; private double lineIterator = 0; private int dotWidth = 0, dotHeight = 0; /*private int[] waveBank; private int waveAmplitude = 5; private int waveFrequency = 20;*/ private boolean dotCycle = false; public LineDrawer(){this(defaultLineStyle, defaultIteratorPixels);} public LineDrawer(int lip){this(defaultLineStyle, lip);} public LineDrawer(Color c){this(defaultLineStyle, c, defaultIteratorPixels);} public LineDrawer(LineStyle ls){this(ls, defaultIteratorPixels);} public LineDrawer(LineStyle s, int lip){this(s, Color.black, lip);} public LineDrawer(LineStyle style, Color lineColor, int lineIteratorPixels){ //initializeTrigonometryBank(lineIteratorPixels, waveAmplitude, waveFrequency); this.lineIteratorPixels = lineIteratorPixels; this.lineColor = lineColor; dotWidth = lineIteratorPixels / 4; dotHeight = dotWidth; this.style = style; } public void resetIterator(){ lineIterator = 0; } public void draw(Graphics g, int x1, int y1, int x2, int y2){ if(style == LineStyle.Normal){ drawLineGeneral(g, x1, y1, x2, y2, lineWidth); return; } //Initialization g.setColor(lineColor); //if(waveBank.length != lineIteratorPixels) initializeTrigonometryBank(lineIteratorPixels, waveAmplitude, waveFrequency); //Get stuff we might need int a = x2 - x1, b = y2 - y1; //Calculate slope double m = Double.POSITIVE_INFINITY; if(a != 0) m = (double) b / (double) a; //Get y-intercept int yi = (int) (y1 - m * x1); // max (m1) and min (m0) values int m0 = x1 < x2 ? x1 : x2, m1 = x1 < x2 ? x2 : x1; int lastX = m0, lastY = (int) (m0 * m + yi); for(int i = m0 + 1; i <= m1; i++){ //Get x and y (via y=mx+b) int x = i, y = (int) m * i + yi; if(style == LineStyle.Dashed) drawDashed(g, lastX, lastY, x, y); else if(style == LineStyle.Dotted) drawDot(g, x, y); else if(style == LineStyle.DashedDotted){ drawDashed(g, lastX, lastY, x, y); if(!dotCycle && drawDot(g, x, y)) dotCycle = true; } else drawLineGeneral(g, lastX, lastY, x, y, lineWidth); double pm = m < 0 ? -m : m; lineIterator += pm; //This code is FUNKY!!! if(lineIterator >= lineIteratorPixels){ dotCycle = false; lineIterator = 0; } lastX = x; lastY = y; } } private static void drawLineGeneral(Graphics g, int x1, int y1, int x2, int y2, int lw){ if(lw > 1) Utility.drawLineWithWidth(g, x1, y1, x2, y2, lw); else g.drawLine(x1, y1, x2, y2); } private void drawDashed(Graphics g, int x1, int y1, int x2, int y2){ if(lineIterator < lineIteratorPixels / 2d) drawLineGeneral(g, x1, y1, x2, y2, lineWidth); } private boolean drawDot(Graphics g, int x, int y){ if(lineIterator > lineIteratorPixels / 2d + lineIteratorPixels / 4d){ g.fillOval(x - dotWidth / 2, y - dotHeight / 2, dotWidth, dotHeight); return true; } return false; } /*//We use this to hold all the points in a sine wave so we don't have to re-compute them later private void initializeTrigonometryBank(int to, int amp, int freq){ waveBank = new int[to]; for(int i = 0; i < to; i++) waveBank[i] = (int) (amp * Math.sin(gradientToRadiant(0, to, i))); } private double gradientToRadiant(double min, double max, double val){ return ((val - min) / (max - min)) * 2 * Math.PI; }*/ public LineStyle getStyle() {return style;} public void setStyle(LineStyle style) {this.style = style;} public Color getLineColor() {return lineColor;} public void setLineColor(Color lineColor) {this.lineColor = lineColor;} public int getLineWidth() {return lineWidth;} public void setLineWidth(int lineWidth) {this.lineWidth = lineWidth;} public int getLineIteratorPixels() {return lineIteratorPixels;} public void setLineIteratorPixels(int lineIteratorPixels) {this.lineIteratorPixels = lineIteratorPixels;} }
package com.powsybl.commons.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.google.common.base.Strings; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.powsybl.commons.extensions.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; /** * @author Mathieu Bague <mathieu.bague@rte-france.com> */ public final class JsonUtil { private static final Supplier<ExtensionProviders<ExtensionJsonSerializer>> SUPPLIER = Suppliers.memoize(() -> ExtensionProviders.createProvider(ExtensionJsonSerializer.class)); private JsonUtil() { } public static ObjectMapper createObjectMapper() { return new ObjectMapper() .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) .disable(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS) .enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS); } public static JsonFactory createJsonFactory() { return new JsonFactory() .disable(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS) .enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS); } public static void writeJson(Writer writer, Consumer<JsonGenerator> consumer) { Objects.requireNonNull(writer); Objects.requireNonNull(consumer); JsonFactory factory = createJsonFactory(); try (JsonGenerator generator = factory.createGenerator(writer)) { generator.useDefaultPrettyPrinter(); consumer.accept(generator); } catch (IOException e) { throw new UncheckedIOException(e); } } public static String toJson(Consumer<JsonGenerator> consumer) { try (StringWriter writer = new StringWriter()) { writeJson(writer, consumer); return writer.toString(); } catch (IOException e) { throw new UncheckedIOException(e); } } public static void writeJson(Path file, Consumer<JsonGenerator> consumer) { Objects.requireNonNull(file); Objects.requireNonNull(consumer); try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { writeJson(writer, consumer); } catch (IOException e) { throw new UncheckedIOException(e); } } public static <T> T parseJson(Path file, Function<JsonParser, T> function) { Objects.requireNonNull(file); try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { return parseJson(reader, function); } catch (IOException e) { throw new UncheckedIOException(e); } } public static <T> T parseJson(String json, Function<JsonParser, T> function) { Objects.requireNonNull(json); try (StringReader reader = new StringReader(json)) { return parseJson(reader, function); } } public static <T> T parseJson(Reader reader, Function<JsonParser, T> function) { Objects.requireNonNull(reader); Objects.requireNonNull(function); JsonFactory factory = createJsonFactory(); try (JsonParser parser = factory.createParser(reader)) { return function.apply(parser); } catch (IOException e) { throw new UncheckedIOException(e); } } public static void writeOptionalStringField(JsonGenerator jsonGenerator, String fieldName, String value) throws IOException { Objects.requireNonNull(jsonGenerator); Objects.requireNonNull(fieldName); if (!Strings.isNullOrEmpty(value)) { jsonGenerator.writeStringField(fieldName, value); } } public static void writeOptionalEnumField(JsonGenerator jsonGenerator, String fieldName, Enum<?> value) throws IOException { Objects.requireNonNull(jsonGenerator); Objects.requireNonNull(fieldName); if (value != null) { jsonGenerator.writeStringField(fieldName, value.name()); } } public static void writeOptionalFloatField(JsonGenerator jsonGenerator, String fieldName, float value) throws IOException { Objects.requireNonNull(jsonGenerator); Objects.requireNonNull(fieldName); if (!Float.isNaN(value)) { jsonGenerator.writeNumberField(fieldName, value); } } public static void writeOptionalDoubleField(JsonGenerator jsonGenerator, String fieldName, double value) throws IOException { Objects.requireNonNull(jsonGenerator); Objects.requireNonNull(fieldName); if (!Double.isNaN(value)) { jsonGenerator.writeNumberField(fieldName, value); } } public static void writeOptionalIntegerField(JsonGenerator jsonGenerator, String fieldName, int value) throws IOException { Objects.requireNonNull(jsonGenerator); Objects.requireNonNull(fieldName); if (value != Integer.MAX_VALUE) { jsonGenerator.writeNumberField(fieldName, value); } } public static <T> void writeExtensions(Extendable<T> extendable, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { writeExtensions(extendable, jsonGenerator, serializerProvider, SUPPLIER.get()); } public static <T> void writeExtensions(Extendable<T> extendable, JsonGenerator jsonGenerator, SerializerProvider serializerProvider, ExtensionProviders<? extends ExtensionJsonSerializer> supplier) throws IOException { Objects.requireNonNull(extendable); Objects.requireNonNull(jsonGenerator); Objects.requireNonNull(serializerProvider); Objects.requireNonNull(supplier); boolean headerDone = false; if (!extendable.getExtensions().isEmpty()) { for (Extension<T> extension : extendable.getExtensions()) { ExtensionJsonSerializer serializer = supplier.findProvider(extension.getName()); if (serializer != null) { if (!headerDone) { jsonGenerator.writeFieldName("extensions"); jsonGenerator.writeStartObject(); headerDone = true; } jsonGenerator.writeFieldName(extension.getName()); serializer.serialize(extension, jsonGenerator, serializerProvider); } } if (headerDone) { jsonGenerator.writeEndObject(); } } } public static <T> List<Extension<T>> readExtensions(JsonParser parser, DeserializationContext context) throws IOException { return readExtensions(parser, context, SUPPLIER.get()); } public static <T> List<Extension<T>> readExtensions(JsonParser parser, DeserializationContext context, ExtensionProviders<? extends ExtensionJsonSerializer> supplier) throws IOException { Objects.requireNonNull(parser); Objects.requireNonNull(context); Objects.requireNonNull(supplier); List<Extension<T>> extensions = new ArrayList<>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String extensionName = parser.getCurrentName(); ExtensionJsonSerializer extensionJsonSerializer = supplier.findProvider(extensionName); if (extensionJsonSerializer != null) { parser.nextToken(); Extension<T> extension = extensionJsonSerializer.deserialize(parser, context); extensions.add(extension); } else { skip(parser); } } return extensions; } /** * Skip a part of a JSON document */ public static void skip(JsonParser parser) throws IOException { int objectCount = 0; do { JsonToken token = parser.nextToken(); if (token == JsonToken.START_OBJECT) { objectCount++; } else if (token == JsonToken.END_OBJECT) { objectCount } } while (objectCount != 0); } }
package net.java.sip.communicator.util.swing; import java.awt.*; import javax.swing.*; import net.java.sip.communicator.util.*; /** * A custom component, used to show images in a frame. * * @author Yana Stamcheva */ public class FramedImage extends JComponent { private final Image frameImage; private Image image; private final int width; private final int height; /** * Creates a FramedImage by specifying the width and the height of the * label. These are used to paint the image frame in the correct bounds. * * @param imageIcon the icon to show within the frame * @param width the width of the frame * @param height the height of the frame */ public FramedImage(ImageIcon imageIcon, int width, int height) { this.width = width; this.height = height; this.setPreferredSize(new Dimension(width, height)); this.frameImage = ImageUtils .scaleImageWithinBounds( UtilActivator .getResources() .getImage("service.gui.USER_PHOTO_FRAME").getImage(), width, height); if (imageIcon != null) this.setImageIcon(imageIcon); } /** * Creates a FramedImage by specifying the width and the height of the frame. * * @param width the width of the frame * @param height the height of the frame */ public FramedImage(int width, int height) { this(null, width, height); } /** * Sets the image to display in the frame. * * @param imageIcon the image to display in the frame */ public void setImageIcon(ImageIcon imageIcon) { image = ImageUtils.getScaledRoundedImage( imageIcon.getImage(), width - 2, height - 2); if (this.isVisible()) { this.revalidate(); this.repaint(); } } /** * Paints the contained image in a frame. * * Overrides {@link JComponent#paintComponent(Graphics)}. */ public void paintComponent(Graphics g) { if (image != null) { int imageWidth = image.getWidth(this); int imageHeight = image.getHeight(this); if ((imageWidth != -1) && (imageHeight != -1)) g.drawImage( image, width / 2 - imageWidth / 2, height / 2 - imageHeight / 2, null); } int frameWidth = frameImage.getWidth(this); int frameHeight = frameImage.getHeight(this); if ((frameWidth != -1) && (frameHeight != -1)) g.drawImage( frameImage, width / 2 - frameWidth / 2, height / 2 - frameHeight / 2, null); } }
package com.emc.ia.sdk.sip.assembly; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import java.util.function.Supplier; import org.apache.commons.io.IOUtils; import com.emc.ia.sdk.support.io.DataBuffer; import com.emc.ia.sdk.support.io.DataBufferSupplier; import com.emc.ia.sdk.support.io.DefaultZipAssembler; import com.emc.ia.sdk.support.io.EncodedHash; import com.emc.ia.sdk.support.io.FileBuffer; import com.emc.ia.sdk.support.io.HashAssembler; import com.emc.ia.sdk.support.io.MemoryBuffer; import com.emc.ia.sdk.support.io.NoHashAssembler; import com.emc.ia.sdk.support.io.RuntimeIoException; import com.emc.ia.sdk.support.io.ZipAssembler; public class SipAssembler<D> implements Assembler<D> { private static final String PACKAGING_INFORMATION_ENTRY = "eas_sip.xml"; private static final String PDI_ENTRY = "eas_pdi.xml"; private final ZipAssembler zip; private final Assembler<PackagingInformation> packagingInformationAssembler; private final Assembler<HashedContents<D>> pdiAssembler; private final HashAssembler pdiHashAssembler; private final DigitalObjectsExtraction<D> contentsExtraction; private final HashAssembler contentHashAssembler; private final Supplier<? extends DataBuffer> pdiBufferSupplier; private final PackagingInformationFactory packagingInformationFactory; private final Counters metrics = new Counters(); private DataBuffer pdiBuffer; private Optional<EncodedHash> pdiHash; /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param prototype Prototype for the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdi(PackagingInformation prototype, Assembler<HashedContents<D>> pdiAssembler) { return forPdiWithHashing(prototype, pdiAssembler, new NoHashAssembler()); } /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param factory Factory for creating the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdi(PackagingInformationFactory factory, Assembler<HashedContents<D>> pdiAssembler) { return forPdiWithHashing(factory, pdiAssembler, new NoHashAssembler()); } /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param prototype Prototype for the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param pdiHashAssembler Assembler that builds up an encoded hash for the PDI * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiWithHashing(PackagingInformation prototype, Assembler<HashedContents<D>> pdiAssembler, HashAssembler pdiHashAssembler) { return forPdiAndContentWithHashing(prototype, pdiAssembler, pdiHashAssembler, noDigitalObjectsExtraction(), new NoHashAssembler()); } private static <D> DigitalObjectsExtraction<D> noDigitalObjectsExtraction() { return domainObject -> Collections.emptyIterator(); } /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param factory Factory for creating the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param pdiHashAssembler Assembler that builds up an encoded hash for the PDI * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiWithHashing(PackagingInformationFactory factory, Assembler<HashedContents<D>> pdiAssembler, HashAssembler pdiHashAssembler) { return forPdiAndContentWithHashing(factory, pdiAssembler, pdiHashAssembler, noDigitalObjectsExtraction(), new NoHashAssembler()); } /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param prototype Prototype for the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param contentsExtraction Extraction of content from domain objects added to the SIP * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiAndContent(PackagingInformation prototype, Assembler<HashedContents<D>> pdiAssembler, DigitalObjectsExtraction<D> contentsExtraction) { HashAssembler noHashAssembler = new NoHashAssembler(); return forPdiAndContentWithHashing(prototype, pdiAssembler, noHashAssembler, contentsExtraction, noHashAssembler); } /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param factory Factory for creating the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param contentsExtraction Extraction of content from domain objects added to the SIP * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiAndContent(PackagingInformationFactory factory, Assembler<HashedContents<D>> pdiAssembler, DigitalObjectsExtraction<D> contentsExtraction) { HashAssembler noHashAssembler = new NoHashAssembler(); return forPdiAndContentWithHashing(factory, pdiAssembler, noHashAssembler, contentsExtraction, noHashAssembler); } /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param prototype Prototype for the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param contentsExtraction Extraction of content from domain objects added to the SIP * @param contentHashAssembler Assembler that builds up an encoded hash for the extracted content * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiAndContentWithContentHashing(PackagingInformation prototype, Assembler<HashedContents<D>> pdiAssembler, DigitalObjectsExtraction<D> contentsExtraction, HashAssembler contentHashAssembler) { return forPdiAndContentWithHashing(prototype, pdiAssembler, new NoHashAssembler(), contentsExtraction, contentHashAssembler); } /** * Assemble a SIP that contains only structured data and is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param factory Factory for creating the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param contentsExtraction Extraction of content from domain objects added to the SIP * @param contentHashAssembler Assembler that builds up an encoded hash for the extracted content * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiAndContentWithContentHashing(PackagingInformationFactory factory, Assembler<HashedContents<D>> pdiAssembler, DigitalObjectsExtraction<D> contentsExtraction, HashAssembler contentHashAssembler) { return forPdiAndContentWithHashing(factory, pdiAssembler, new NoHashAssembler(), contentsExtraction, contentHashAssembler); } /** * Assemble a SIP that is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param prototype Prototype for the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param pdiHashAssembler Assembler that builds up an encoded hash for the PDI * @param contentsExtraction Extraction of content from domain objects added to the SIP * @param contentHashAssembler Assembler that builds up an encoded hash for the extracted content * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiAndContentWithHashing(PackagingInformation prototype, Assembler<HashedContents<D>> pdiAssembler, HashAssembler pdiHashAssembler, DigitalObjectsExtraction<D> contentsExtraction, HashAssembler contentHashAssembler) { return new SipAssembler<>(new DefaultPackagingInformationFactory(prototype), pdiAssembler, pdiHashAssembler, new DataBufferSupplier<>(MemoryBuffer.class), contentsExtraction, contentHashAssembler); } /** * Assemble a SIP that is the only SIP in its DSS. * @param <D> The type of domain objects to assemble the SIP from * @param factory Factory for creating the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param pdiHashAssembler Assembler that builds up an encoded hash for the PDI * @param contentsExtraction Extraction of content from domain objects added to the SIP * @param contentHashAssembler Assembler that builds up an encoded hash for the extracted content * @return The newly created SIP assembler */ public static <D> SipAssembler<D> forPdiAndContentWithHashing(PackagingInformationFactory factory, Assembler<HashedContents<D>> pdiAssembler, HashAssembler pdiHashAssembler, DigitalObjectsExtraction<D> contentsExtraction, HashAssembler contentHashAssembler) { return new SipAssembler<>(factory, pdiAssembler, pdiHashAssembler, new DataBufferSupplier<>(MemoryBuffer.class), contentsExtraction, contentHashAssembler); } /** * Create a new instance. * @param packagingInformationFactory Factory for creating the Packaging Information * @param pdiAssembler Assembler that builds up the PDI * @param pdiHashAssembler Assembler that builds up an encoded hash for the PDI and the unstructured data * @param pdiBufferSupplier Supplier for a data buffer to store the PDI * @param contentsExtraction Extraction of content from domain objects added to the SIP * @param contentHashAssembler Assembler that builds up an encoded hash for the extracted content */ public SipAssembler(PackagingInformationFactory packagingInformationFactory, Assembler<HashedContents<D>> pdiAssembler, HashAssembler pdiHashAssembler, Supplier<? extends DataBuffer> pdiBufferSupplier, DigitalObjectsExtraction<D> contentsExtraction, HashAssembler contentHashAssembler) { this(packagingInformationFactory, new InfoArchivePackagingInformationAssembler(), pdiAssembler, pdiHashAssembler, pdiBufferSupplier, contentsExtraction, contentHashAssembler, new DefaultZipAssembler()); } SipAssembler(PackagingInformationFactory packagingInformationFactory, Assembler<PackagingInformation> packagingInformationAssembler, Assembler<HashedContents<D>> pdiAssembler, HashAssembler pdiHashAssembler, Supplier<? extends DataBuffer> pdiBufferSupplier, DigitalObjectsExtraction<D> contentsExtraction, HashAssembler contentHashAssembler, ZipAssembler zipAssembler) { this.packagingInformationFactory = packagingInformationFactory; this.packagingInformationAssembler = packagingInformationAssembler; this.pdiAssembler = pdiAssembler; this.pdiHashAssembler = pdiHashAssembler; this.pdiBufferSupplier = pdiBufferSupplier; this.contentsExtraction = contentsExtraction; this.contentHashAssembler = contentHashAssembler; this.zip = zipAssembler; } @Override public void start(DataBuffer buffer) throws IOException { pdiHash = Optional.empty(); metrics.reset(); metrics.set(SipMetrics.ASSEMBLY_TIME, System.currentTimeMillis()); zip.begin(buffer.openForWriting()); startPdi(); } private void startPdi() throws IOException { pdiBuffer = pdiBufferSupplier.get(); pdiAssembler.start(pdiBuffer); } @Override public void add(D domainObject) { try { Map<String, Collection<EncodedHash>> contentHashes = addContentsOf(domainObject); pdiAssembler.add(new HashedContents<>(domainObject, contentHashes)); metrics.inc(SipMetrics.NUM_AIUS); setPdiSize(pdiBuffer.length()); // Approximate PDI size until the end, when we know for sure } catch (IOException e) { throw new RuntimeIoException(e); } } private void setPdiSize(long pdiSize) { metrics.set(SipMetrics.SIZE_PDI, pdiSize); metrics.set(SipMetrics.SIZE_SIP, metrics.get(SipMetrics.SIZE_DIGITAL_OBJECTS) + metrics.get(SipMetrics.SIZE_PDI)); } private Map<String, Collection<EncodedHash>> addContentsOf(D domainObject) throws IOException { Map<String, Collection<EncodedHash>> result = new TreeMap<>(); Iterator<? extends DigitalObject> digitalObjects = contentsExtraction.apply(domainObject); while (digitalObjects.hasNext()) { DigitalObject digitalObject = digitalObjects.next(); metrics.inc(SipMetrics.NUM_DIGITAL_OBJECTS); String entry = digitalObject.getReferenceInformation(); try (InputStream stream = digitalObject.get()) { Collection<EncodedHash> hashes = zip.addEntry(entry, stream, contentHashAssembler); result.put(entry, hashes); metrics.inc(SipMetrics.SIZE_DIGITAL_OBJECTS, contentHashAssembler.numBytesHashed()); } } return result; } @Override public void end() throws IOException { try { endPdi(); addPackagingInformation(); } finally { IOUtils.closeQuietly(zip); metrics.set(SipMetrics.ASSEMBLY_TIME, System.currentTimeMillis() - metrics.get(SipMetrics.ASSEMBLY_TIME)); } } private void endPdi() throws IOException { try { pdiAssembler.end(); addPdiToZip(); } finally { pdiBuffer = null; } } void addPdiToZip() throws IOException { try (InputStream in = pdiBuffer.openForReading()) { pdiHash = zip.addEntry(PDI_ENTRY, in, pdiHashAssembler).stream() .limit(1) .findAny(); } setPdiSize(pdiHashAssembler.numBytesHashed()); } private void addPackagingInformation() throws IOException { DataBuffer buffer = new MemoryBuffer(); packagingInformationAssembler.start(buffer); packagingInformationAssembler.add(packagingInformation()); packagingInformationAssembler.end(); try (InputStream stream = buffer.openForReading()) { zip.addEntry(PACKAGING_INFORMATION_ENTRY, stream, new NoHashAssembler()); } } private PackagingInformation packagingInformation() { return packagingInformationFactory.newInstance(metrics.get(SipMetrics.NUM_AIUS), pdiHash); } @Override public SipMetrics getMetrics() { return new SipMetrics(metrics.forReading()); } public PackagingInformationFactory getPackagingInformationFactory() { return packagingInformationFactory; } }
package lombok.ast.javac; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import lombok.ast.StringLiteral; import com.google.common.collect.MapMaker; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.main.OptionName; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCArrayAccess; import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree; import com.sun.tools.javac.tree.JCTree.JCAssert; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCAssignOp; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCBreak; import com.sun.tools.javac.tree.JCTree.JCCase; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCConditional; import com.sun.tools.javac.tree.JCTree.JCContinue; import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop; import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; import com.sun.tools.javac.tree.JCTree.JCErroneous; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCForLoop; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCIf; import com.sun.tools.javac.tree.JCTree.JCImport; import com.sun.tools.javac.tree.JCTree.JCInstanceOf; import com.sun.tools.javac.tree.JCTree.JCLabeledStatement; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCParens; import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree; import com.sun.tools.javac.tree.JCTree.JCReturn; import com.sun.tools.javac.tree.JCTree.JCSkip; import com.sun.tools.javac.tree.JCTree.JCSwitch; import com.sun.tools.javac.tree.JCTree.JCSynchronized; import com.sun.tools.javac.tree.JCTree.JCThrow; import com.sun.tools.javac.tree.JCTree.JCTry; import com.sun.tools.javac.tree.JCTree.JCTypeApply; import com.sun.tools.javac.tree.JCTree.JCTypeCast; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCUnary; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.JCWhileLoop; import com.sun.tools.javac.tree.JCTree.JCWildcard; import com.sun.tools.javac.tree.JCTree.LetExpr; import com.sun.tools.javac.tree.JCTree.TypeBoundKind; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Options; /** * Diagnostic tool that turns a {@code JCTree} (javac) based tree into a hierarchical dump that should make * it easy to analyse the exact structure of the AST. */ public class JcTreePrinter { private final StringBuilder output = new StringBuilder(); private final boolean includePositions; private final boolean includeObjectRefs; private int indent; private String rel; private Map<JCTree, Integer> endPosTable; private boolean modsOfEnum; private final Map<Object, Integer> visited = new MapMaker().weakKeys().makeMap(); private int objectCounter = 0; private static final Method GET_TAG_METHOD; private static final Field TAG_FIELD; //TODO Adopt the reflective printer principle used in the EcjTreePrinter. For example, we don't currently know if the type ref is shared or unique amongst // JCVarDecls that all come from the same line: int[] x, y; static { Method m = null; Field f = null; try { m = JCTree.class.getDeclaredMethod("getTag"); } catch (NoSuchMethodException e) { try { f = JCTree.class.getDeclaredField("tag"); } catch (NoSuchFieldException e1) { e1.printStackTrace(); } } GET_TAG_METHOD = m; TAG_FIELD = f; } static int getTag(JCTree tree) { if (GET_TAG_METHOD != null) { try { return (Integer) GET_TAG_METHOD.invoke(tree); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } try { return TAG_FIELD.getInt(tree); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public JcTreePrinter(boolean includePositions) { this.includePositions = includePositions; this.includeObjectRefs = true; } @Override public String toString() { return output.toString(); } public static void main(String[] args) throws IOException { if (args.length == 0) { System.out.println("Usage: Supply a file name to print."); return; } Context context = new Context(); Options.instance(context).put(OptionName.ENCODING, "UTF-8"); JavaCompiler compiler = new JavaCompiler(context); compiler.genEndPos = true; compiler.keepComments = true; @SuppressWarnings("deprecation") JCCompilationUnit cu = compiler.parse(args[0]); JcTreePrinter printer = new JcTreePrinter(true); printer.visit(cu); System.out.println(printer); } private void printNode(JCTree tree) { if (tree == null) { printNode("NULL"); } else { String suffix = ""; int objId; Integer backRef = visited.get(tree); if (backRef == null) { objId = ++objectCounter; visited.put(tree, objId); } else { objId = backRef; } if (includePositions) { Integer endPos_ = null; if (endPosTable != null) endPos_ = endPosTable.get(tree); int endPos = endPos_ == null ? tree.getEndPosition(endPosTable) : endPos_; int startPos = tree.pos; if (tree instanceof JCTypeApply || tree instanceof JCWildcard || tree instanceof JCTypeParameter) { // Javac itself actually has bugs in generating the right endpos. To make sure our tests that compare end pos don't fail, // as we do set the end pos at the right place, we overwrite it with magic value -2 which means: javac screws this up. endPos = -2; } // When there are no modifiers but an internal flag is set, javac screws up, // and sets start to the beginning of the node, and end to the last non-whitespace thing before it; // yes - that would make for negatively sized modifier nodes. if (tree instanceof JCModifiers && endPos-tree.pos <= 0) { startPos = -1; endPos = -1; } // The end value of an annotation is end-of-annotation-type in older javac, and end-of-parenslist in new javac. if (tree instanceof JCAnnotation) { endPos = -2; } // Modifiers of enums never get their position set, but we do set the position. if (modsOfEnum) { startPos = -1; endPos = -1; modsOfEnum = false; } //In rare conditions, the end pos table is filled with a silly value, but start is -1. if (startPos == -1 && endPos >= 0) endPos = -1; /*Javac bug: sometimes the startpos of a binary expression is set to the wrong operator.*/ { if (tree instanceof JCBinary && ((JCBinary)tree).rhs instanceof JCBinary) { if (getTag(tree) != getTag(((JCBinary)tree).rhs)) { startPos = -2; } } if (tree instanceof JCBinary && ((JCBinary)tree).rhs instanceof JCInstanceOf) { startPos = -2; } } /* Javac bug: The end position of a "super.FOO" node which is itself the LHS of a select-like concept (Select, Method Invocation, etcetera) are set to right after the dot following it. This doesn't happen with 'this' or anything other than super. */ { if (tree instanceof JCMethodInvocation) { JCMethodInvocation invoke = (JCMethodInvocation) tree; if (invoke.meth instanceof JCFieldAccess && ((JCFieldAccess) invoke.meth).selected instanceof JCIdent) { JCIdent selected = (JCIdent) ((JCFieldAccess) invoke.meth).selected; if (selected.name.toString().equals("super")) endPos = -2; } } if (tree instanceof JCFieldAccess && ((JCFieldAccess) tree).selected instanceof JCIdent) { JCIdent selected = (JCIdent) ((JCFieldAccess) tree).selected; if (selected.name.toString().equals("super")) endPos = -2; } } /* Javac bug: the 'JCAssign' starts at a dot (if present) in the expression instead of at the start of it, which is weird and inconsistent. */ { if (tree instanceof JCAssign && ((JCAssign) tree).rhs instanceof JCFieldAccess) { startPos = -2; } } suffix += String.format("(%d-%d)", startPos, endPos); } if (includeObjectRefs) { suffix += String.format("(id: %d%s)", objId, backRef != null ? " BACKREF" : ""); } printNode(String.format("%s%s", tree.getClass().getSimpleName(), suffix)); } } private void printNode(String nodeKind) { printIndent(); if (rel != null) output.append(rel).append(": "); rel = null; output.append("[").append(nodeKind).append("]\n"); indent++; } private void printIndent() { for (int i = 0; i < indent; i++) { output.append("\t"); } } private void property(String rel, Object val) { printIndent(); if (rel != null) output.append(rel).append(": "); if (val instanceof JCTree) output.append("!!JCTree-AS-PROP!!"); if (val == null) { output.append("[NULL]\n"); } else { String content; if (val instanceof String) { content = new StringLiteral().astValue(val.toString()).rawValue(); } else { content = String.valueOf(val); } output.append("[").append(val.getClass().getSimpleName()).append(" ").append(content).append("]\n"); } } private void child(String rel, JCTree node) { this.rel = rel; if (node != null) { node.accept(visitor); } else { printNode("NULL"); indent } } private void children(String rel, List<? extends JCTree> nodes) { this.rel = rel; if (nodes == null) { ; printNode("LISTNULL"); indent } else if (nodes.isEmpty()) { printNode("LISTEMPTY"); indent } else { int i = 0; for (JCTree node : nodes) { child(String.format("%s[%d]", rel, i++), node); } } } public void visit(JCTree tree) { tree.accept(visitor); } private final JCTree.Visitor visitor = new JCTree.Visitor() { @Override public void visitTopLevel(JCCompilationUnit tree) { printNode(tree); endPosTable = tree.endPositions; child("pid", tree.pid); children("defs", tree.defs); indent } @Override public void visitImport(JCImport tree) { printNode(tree); property("staticImport", tree.staticImport); child("qualid", tree.qualid); indent } @Override public void visitClassDef(JCClassDecl tree) { printNode(tree); modsOfEnum = (tree.mods != null && (tree.mods.flags & Flags.ENUM) != 0); child("mods", tree.mods); property("name", tree.name); children("typarams", tree.typarams); child("extends", tree.extending); children("implementing", tree.implementing); children("defs", tree.defs); indent } @Override public void visitMethodDef(JCMethodDecl tree) { printNode(tree); property("name", tree.name); child("mods", tree.mods); children("typarams", tree.typarams); children("params", tree.params); children("thrown", tree.thrown); child("default", tree.defaultValue); child("body", tree.body); indent } @Override public void visitVarDef(JCVariableDecl tree) { printNode(tree); child("mods", tree.mods); child("vartype", tree.vartype); property("name", tree.name); child("init", tree.init); indent } @Override public void visitSkip(JCSkip tree) { printNode(tree); indent } @Override public void visitBlock(JCBlock tree) { printNode(tree); property("flags", "0x" + Long.toString(tree.flags, 0x10)); children("stats", tree.stats); indent } @Override public void visitDoLoop(JCDoWhileLoop tree) { printNode(tree); child("body", tree.body); child("cond", tree.cond); indent } @Override public void visitWhileLoop(JCWhileLoop tree) { printNode(tree); child("cond", tree.cond); child("body", tree.body); indent } @Override public void visitForLoop(JCForLoop tree) { printNode(tree); children("init", tree.init); child("cond", tree.cond); children("step", tree.step); child("body", tree.body); indent } @Override public void visitForeachLoop(JCEnhancedForLoop tree) { printNode(tree); child("var", tree.var); child("expr", tree.expr); child("body", tree.body); indent } @Override public void visitLabelled(JCLabeledStatement tree) { printNode(tree); property("label", tree.label); child("body", tree.body); indent } @Override public void visitSwitch(JCSwitch tree) { printNode(tree); child("selector", tree.selector); children("cases", tree.cases); indent } @Override public void visitCase(JCCase tree) { printNode(tree); child("pat", tree.pat); children("stats", tree.stats); indent } @Override public void visitSynchronized(JCSynchronized tree) { printNode(tree); child("lock", tree.lock); child("body", tree.body); indent } @Override public void visitTry(JCTry tree) { printNode(tree); child("body", tree.body); children("catchers", tree.catchers); child("finalizer", tree.finalizer); indent } @Override public void visitCatch(JCCatch tree) { printNode(tree); child("param", tree.param); child("body", tree.body); indent } @Override public void visitConditional(JCConditional tree) { printNode(tree); child("cond", tree.cond); child("truepart", tree.truepart); child("falsepart", tree.falsepart); indent } @Override public void visitIf(JCIf tree) { printNode(tree); child("cond", tree.cond); child("thenpart", tree.thenpart); child("elsepart", tree.elsepart); indent } @Override public void visitExec(JCExpressionStatement tree) { printNode(tree); child("expr", tree.expr); indent } @Override public void visitBreak(JCBreak tree) { printNode(tree); property("label", tree.label); indent } @Override public void visitContinue(JCContinue tree) { printNode(tree); property("label", tree.label); indent } @Override public void visitReturn(JCReturn tree) { printNode(tree); child("expr", tree.expr); indent } @Override public void visitThrow(JCThrow tree) { printNode(tree); child("expr", tree.expr); indent } @Override public void visitAssert(JCAssert tree) { printNode(tree); child("cond", tree.cond); child("detail", tree.detail); indent } @Override public void visitApply(JCMethodInvocation tree) { printNode(tree); children("typeargs", tree.typeargs); child("meth", tree.meth); children("args", tree.args); indent } @Override public void visitNewClass(JCNewClass tree) { printNode(tree); child("encl", tree.encl); children("typeargs", tree.typeargs); child("clazz", tree.clazz); children("args", tree.args); child("def", tree.def); indent } @Override public void visitNewArray(JCNewArray tree) { printNode(tree); child("elemtype", tree.elemtype); children("dims", tree.dims); children("elems", tree.elems); indent } @Override public void visitParens(JCParens tree) { printNode(tree); child("expr", tree.expr); indent } @Override public void visitAssign(JCAssign tree) { printNode(tree); child("lhs", tree.lhs); child("rhs", tree.rhs); indent } public String operatorName(int tag) { switch (tag) { case JCTree.POS: return "+"; case JCTree.NEG: return "-"; case JCTree.NOT: return "!"; case JCTree.COMPL: return "~"; case JCTree.PREINC: return "++X"; case JCTree.PREDEC: return "--X"; case JCTree.POSTINC: return "X++"; case JCTree.POSTDEC: return "X case JCTree.NULLCHK: return "<*nullchk*>"; case JCTree.OR: return "||"; case JCTree.AND: return "&&"; case JCTree.EQ: return "=="; case JCTree.NE: return "!="; case JCTree.LT: return "<"; case JCTree.GT: return ">"; case JCTree.LE: return "<="; case JCTree.GE: return ">="; case JCTree.BITOR: return "|"; case JCTree.BITXOR: return "^"; case JCTree.BITAND: return "&"; case JCTree.SL: return "<<"; case JCTree.SR: return ">>"; case JCTree.USR: return ">>>"; case JCTree.PLUS: return "+"; case JCTree.MINUS: return "-"; case JCTree.MUL: return "*"; case JCTree.DIV: return "/"; case JCTree.MOD: return "%"; case JCTree.PLUS_ASG: return "+="; case JCTree.MINUS_ASG: return "-="; case JCTree.MUL_ASG: return "*="; case JCTree.DIV_ASG: return "/="; case JCTree.MOD_ASG: return "%="; case JCTree.BITAND_ASG: return "&="; case JCTree.BITXOR_ASG: return "^="; case JCTree.BITOR_ASG: return "|="; case JCTree.SL_ASG: return "<<="; case JCTree.SR_ASG: return ">>="; case JCTree.USR_ASG: return ">>>="; case JCTree.TYPETEST: return "instanceof"; default: throw new Error("Unexpected operator: " + tag); } } @Override public void visitAssignop(JCAssignOp tree) { printNode(tree); child("lhs", tree.lhs); property("(operator)", operatorName(getTag(tree) - JCTree.ASGOffset) + "="); child("rhs", tree.rhs); indent } @Override public void visitUnary(JCUnary tree) { printNode(tree); child("arg", tree.arg); property("(operator)", operatorName(getTag(tree))); indent } @Override public void visitBinary(JCBinary tree) { printNode(tree); child("lhs", tree.lhs); property("(operator)", operatorName(getTag(tree))); child("rhs", tree.rhs); indent } @Override public void visitTypeCast(JCTypeCast tree) { printNode(tree); child("clazz", tree.clazz); child("expr", tree.expr); indent } @Override public void visitTypeTest(JCInstanceOf tree) { printNode(tree); child("expr", tree.expr); child("clazz", tree.clazz); indent } @Override public void visitIndexed(JCArrayAccess tree) { printNode(tree); child("indexed", tree.indexed); child("index", tree.index); indent } @Override public void visitSelect(JCFieldAccess tree) { printNode(tree); child("selected", tree.selected); property("name", tree.name); indent } @Override public void visitIdent(JCIdent tree) { printNode(tree); property("name", tree.name); indent } public String literalName(int typeTag) { switch (typeTag) { case TypeTags.BYTE: return "BYTE"; case TypeTags.SHORT: return "SHORT"; case TypeTags.INT: return "INT"; case TypeTags.LONG: return "LONG"; case TypeTags.FLOAT: return "FLOAT"; case TypeTags.DOUBLE: return "DOUBLE"; case TypeTags.CHAR: return "CHAR"; case TypeTags.BOOLEAN: return "BOOLEAN"; case TypeTags.VOID: return "VOID"; case TypeTags.CLASS: return "CLASS/STRING"; case TypeTags.BOT: return "BOT"; default: return "ERROR(" + typeTag + ")"; } } @Override public void visitLiteral(JCLiteral tree) { printNode(tree); property("typetag", literalName(tree.typetag)); property("value", tree.value); indent } @Override public void visitTypeIdent(JCPrimitiveTypeTree tree) { printNode(tree); property("typetag", literalName(tree.typetag)); indent } @Override public void visitTypeArray(JCArrayTypeTree tree) { printNode(tree); child("elemtype", tree.elemtype); indent } @Override public void visitTypeApply(JCTypeApply tree) { printNode(tree); child("clazz", tree.clazz); children("arguments", tree.arguments); indent } @Override public void visitTypeParameter(JCTypeParameter tree) { printNode(tree); property("name", tree.name); children("bounds", tree.bounds); indent } @Override public void visitWildcard(JCWildcard tree) { printNode(tree); Object o; // In some javacs (older ones), JCWildcard.kind is a BoundKind, which is an enum. In newer ones its a TypeBoundKind which is a JCTree, i.e. has positions. try { o = tree.getClass().getField("kind").get(tree); } catch (Exception e) { throw new RuntimeException("There's no field at all named 'kind' in JCWildcard? This is not a javac I understand.", e); } if (o instanceof JCTree) { child("kind", (JCTree)o); } else if (o instanceof BoundKind) { property("kind", String.valueOf(o)); } child("inner", tree.inner); indent } // In older javacs this method does not exist, so no @Override here public void visitTypeBoundKind(TypeBoundKind tree) { printNode(tree); property("kind", String.valueOf(tree.kind)); indent } @Override public void visitErroneous(JCErroneous tree) { printNode(tree); children("errs", tree.errs); indent } @Override public void visitLetExpr(LetExpr tree) { printNode(tree); children("defs", tree.defs); child("expr", tree.expr); indent } @Override public void visitModifiers(JCModifiers tree) { printNode(tree); children("annotations", tree.annotations); property("flags", "0x" + Long.toString(tree.flags, 0x10)); indent } @Override public void visitAnnotation(JCAnnotation tree) { printNode(tree); child("annotationType", tree.annotationType); children("args", tree.args); indent } @Override public void visitTree(JCTree tree) { String typeName = tree == null ? "NULL" : tree.getClass().getSimpleName(); printNode("UNKNOWN(" + typeName + ")"); indent } }; }
package net.maizegenetics.pal.distance; import net.maizegenetics.baseplugins.ConvertSBitTBitPlugin; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.util.BitUtil; import net.maizegenetics.util.ProgressListener; /** * This class calculates an identity by state matrix. It is scaled so only non-missing data is used. * Class needs to be updated to use TBit alignment, and then bit calculations * * @author Ed Buckler * @version 1.0 */ public class IBSDistanceMatrix extends DistanceMatrix { private ProgressListener myListener = null; private int numSeqs; private Alignment theAlignment; private Alignment theTBA=null; /** * Holds the average numbers of sites in the comparisons */ private double avgTotalSites; /** * Caches one row at a time to improve performance */ private int lastCachedRowNum = 0; private byte[] lastCachedRow = null; private int minSitesComp=0; private boolean isTrueIBS = false; /** * compute observed distances. Missing sites are ignored. This is no weighting for ambigous bases. * * @param theAlignment Alignment used to computed proportion that */ public IBSDistanceMatrix(Alignment theAlignment) { this(theAlignment, 0, null); } public IBSDistanceMatrix(Alignment theAlignment, ProgressListener listener) { this(theAlignment, 0, listener); } public IBSDistanceMatrix(Alignment theAlignment, int minSiteComp, ProgressListener listener) { this(theAlignment, minSiteComp, false, listener); } public IBSDistanceMatrix(Alignment theAlignment, int minSiteComp, boolean trueIBS, ProgressListener listener) { super(); this.minSitesComp=minSiteComp; isTrueIBS = trueIBS; myListener = listener; numSeqs = theAlignment.getSequenceCount(); this.theAlignment = theAlignment; //if(theAlignment instanceof TBitAlignment) { // theTBA=(TBitAlignment)theAlignment; //} else { // theTBA=TBitAlignment.getInstance(theAlignment,2,false); theTBA = ConvertSBitTBitPlugin.convertAlignment(theAlignment, ConvertSBitTBitPlugin.CONVERT_TYPE.tbit, listener); // this should have an option to only use the 2 or 3 most common alleles setIdGroup(theAlignment.getIdGroup()); long time=System.currentTimeMillis(); // computeDistances(); // System.out.println("Old Distance Time:"+(System.currentTimeMillis()-time)); // time=System.currentTimeMillis(); // computeBitDistances(); // System.out.println("NewBit Distance Time:"+(System.currentTimeMillis()-time)); time=System.currentTimeMillis(); computeHetBitDistances(); System.out.println("NewBitHet Distance Time:"+(System.currentTimeMillis()-time)); } // /** // * Only work for inbreds // */ // private void computeBitDistances() { // avgTotalSites = 0; // int count = 0; // double[] params; // double[][] distance = new double[numSeqs][numSeqs]; // for (int i = 0; i < numSeqs; i++) { // distance[i][i] = 0; // BitSet iMj=theTBA.getAllelePresenceForAllSites(i, 0); // BitSet iMn=theTBA.getAllelePresenceForAllSites(i, 1); // //there are lots of approaches to deal with the hets // for (int j = i + 1; j < numSeqs; j++) { // BitSet jMj=theTBA.getAllelePresenceForAllSites(j, 0); // BitSet jMn=theTBA.getAllelePresenceForAllSites(j, 1); // long same=OpenBitSet.intersectionCount(iMj, jMj)+OpenBitSet.intersectionCount(iMn, jMn); // long diff=OpenBitSet.intersectionCount(iMj, jMn)+OpenBitSet.intersectionCount(iMn, jMj); // double identity=(double)same/(double)(same+diff); // double dist=1-identity; // distance[i][j] = distance[j][i] = dist; // avgTotalSites += (same+diff); //this assumes not hets // count++; // fireProgress((int) (((double) (i + 1) / (double) numSeqs) * 100.0)); // lastCachedRow = null; // setDistances(distance); // avgTotalSites /= (double) count; /** * This is a cleanest, fastest and most accurate way to calculate distance. * It includes a simple approach for hets. * This method is actually 10% faster than the inbred approach. * Key reason for the speed increase is only 3 bit counts versus the 4 above. */ private void computeHetBitDistances() { avgTotalSites = 0; int count = 0; double[] params; double[][] distance = new double[numSeqs][numSeqs]; for (int i = 0; i < numSeqs; i++) { long[] iMj=theTBA.getAllelePresenceForAllSites(i, 0).getBits(); long[] iMn=theTBA.getAllelePresenceForAllSites(i, 1).getBits(); for (int j = i; j < numSeqs; j++) { if (j==i && !isTrueIBS) { distance[i][i] = 0; } else { long[] jMj=theTBA.getAllelePresenceForAllSites(j, 0).getBits(); long[] jMn=theTBA.getAllelePresenceForAllSites(j, 1).getBits(); int sameCnt=0, diffCnt=0, hetCnt=0; for(int x=0; x<iMj.length; x++) { long same=(iMj[x]&jMj[x])|(iMn[x]&jMn[x]); long diff=(iMj[x]&jMn[x])|(iMn[x]&jMj[x]); long hets=same&diff; sameCnt+=BitUtil.pop(same); diffCnt+=BitUtil.pop(diff); hetCnt+=BitUtil.pop(hets); } double identity=(double)(sameCnt+(hetCnt/2))/(double)(sameCnt+diffCnt+hetCnt); double dist=1-identity; int sites=sameCnt+diffCnt-hetCnt; if(sites>minSitesComp) {distance[i][j] = distance[j][i] = dist;} else { distance[i][j] = distance[j][i] = Double.NaN; } avgTotalSites += sites; //this assumes not hets count++; } } fireProgress((int) (((double) (i + 1) / (double) numSeqs) * 100.0)); } lastCachedRow = null; setDistances(distance); avgTotalSites /= (double) count; } // private void computeDistances() { // avgTotalSites = 0; // int count = 0; // double[] params; // double[][] distance = new double[numSeqs][numSeqs]; // for (int i = 0; i < numSeqs; i++) { // distance[i][i] = 0; // for (int j = i + 1; j < numSeqs; j++) { // params = calculateDistance(i, j); // distance[i][j] = params[0]; // distance[j][i] = params[0]; // avgTotalSites += params[1]; // count++; // fireProgress((int) (((double) (i + 1) / (double) numSeqs) * 100.0)); // lastCachedRow = null; // setDistances(distance); // avgTotalSites /= (double) count; private double[] calculateDistance(int s1, int s2) { int siteCount = theAlignment.getSiteCount(); if ((lastCachedRow == null) || (s1 != lastCachedRowNum)) { lastCachedRowNum = s1; lastCachedRow = theAlignment.getBaseRange(s1, 0, siteCount); } byte[] s2Row = theAlignment.getBaseRange(s2, 0, siteCount); double[] params = new double[2]; int numIdentical = 0, numDifferent = 0; for (int i = 0; i < siteCount; i++) { byte s1b = lastCachedRow[i]; byte s2b = s2Row[i]; if ((s1b != Alignment.UNKNOWN_DIPLOID_ALLELE) && (s2b != Alignment.UNKNOWN_DIPLOID_ALLELE)) { if (s1b == s2b) { numIdentical++; } else { numDifferent++; } } } params[1] = numIdentical + numDifferent; if (params[1] == 0) { params[0] = Double.NaN; } else { params[0] = (double) numDifferent / params[1]; } return params; } public double getAverageTotalSites() { return avgTotalSites; } public double[][] getDistance() { return super.getDistances(); } public String toString(int d) { double[][] distance = this.getDistance(); /*Return a string representation of this matrix with 'd' displayed digits*/ String newln = System.getProperty("line.separator"); String outPut = new String(); String num = new String(); int i, j; java.text.NumberFormat nf = new java.text.DecimalFormat(); nf.setMaximumFractionDigits(5); for (i = 0; i < distance.length; i++) { for (j = 0; j < distance[i].length; j++) { //Numeric x = new Numeric(distance[i][j]); num = nf.format(d); //num = x.toString(d); //ed change that screws up formatting //num=""+this.element[i][j]; outPut = outPut + num + (char) 9; } outPut = outPut + newln; } return outPut; } public String toString() { return this.toString(6); } protected void fireProgress(int percent) { if (myListener != null) { myListener.progress(percent, null); } } public boolean isTrueIBS() { return isTrueIBS; } }
/* * This samples uses multiple threads to post synchronous requests to the * VoltDB server, simulating multiple client application posting * synchronous requests to the database, using the native VoltDB client * library. * * While synchronous processing can cause performance bottlenecks (each * caller waits for a transaction answer before calling another * transaction), the VoltDB cluster at large is still able to perform at * blazing speeds when many clients are connected to it. */ package voter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Timer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.json_voltpatches.JSONArray; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.voltdb.CLIConfig; import org.voltdb.ParameterSet; import org.voltdb.VoltTable; import org.voltdb.utils.Encoder; import voter.procedures.Vote; public class HTTPBenchmark { // Initialize some common constants and variables static final String CONTESTANT_NAMES_CSV = "Edwina Burnam,Tabatha Gehling,Kelly Clauss,Jessie Alloway," + "Alana Bregman,Jessie Eichman,Allie Rogalski,Nita Coster," + "Kurt Walser,Ericka Dieter,Loraine NygrenTania Mattioli"; // handy, rather than typing this out several times static final String HORIZONTAL_RULE = " " // validated command line configuration final VoterConfig config; // Phone number generator PhoneCallGenerator switchboard; // Timer for periodic stats printing Timer timer; // Benchmark start time long benchmarkStartTS; // Flags to tell the worker threads to stop or go AtomicBoolean warmupComplete = new AtomicBoolean(false); AtomicBoolean benchmarkComplete = new AtomicBoolean(false); // voter benchmark state AtomicLong acceptedVotes = new AtomicLong(0); AtomicLong badContestantVotes = new AtomicLong(0); AtomicLong badVoteCountVotes = new AtomicLong(0); AtomicLong failedVotes = new AtomicLong(0); static class Response { public byte status = 0; public String statusString = null; public byte appStatus = Byte.MIN_VALUE; public String appStatusString = null; public VoltTable[] results = new VoltTable[0]; public String exception = null; } static String getHTTPVarString(Map<String,String> params) throws UnsupportedEncodingException { String s = ""; for (Entry<String, String> e : params.entrySet()) { String encodedValue = URLEncoder.encode(e.getValue(), "UTF-8"); s += "&"+ e.getKey() + "=" + encodedValue; } s = s.substring(1); return s; } public static String callProcOverJSONRaw(String varString, int expectedCode) throws Exception { URL jsonAPIURL = new URL("http://localhost:8080/api/1.0/"); HttpURLConnection conn = (HttpURLConnection) jsonAPIURL.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(varString); out.flush(); out.close(); out = null; conn.getOutputStream().close(); BufferedReader in = null; try { if(conn.getInputStream()!=null){ in = new BufferedReader( new InputStreamReader( conn.getInputStream(), "UTF-8")); } } catch(IOException e){ if(conn.getErrorStream()!=null){ in = new BufferedReader( new InputStreamReader( conn.getErrorStream(), "UTF-8")); } } if(in==null) { throw new Exception("Unable to read response from server"); } StringBuffer decodedString = new StringBuffer(); String line; while ((line = in.readLine()) != null) { decodedString.append(line); } in.close(); in = null; // get result code int responseCode = conn.getResponseCode(); String response = decodedString.toString(); try { conn.getInputStream().close(); conn.disconnect(); } // ignore closing problems here catch (Exception e) {} conn = null; //System.err.println(response); return response; } public static String getHashedPasswordForHTTPVar(String password) { assert(password != null); MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } byte hashedPassword[] = null; try { hashedPassword = md.digest(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("JVM doesn't support UTF-8. Please use a supported JVM", e); } String retval = Encoder.hexEncode(hashedPassword); return retval; } public static String callProcOverJSON(String procName, ParameterSet pset, String username, String password, boolean preHash) throws Exception { return callProcOverJSON(procName, pset, username, password, preHash, false, 200 /* HTTP_OK */); } public static String callProcOverJSON(String procName, ParameterSet pset, String username, String password, boolean preHash, boolean admin) throws Exception { return callProcOverJSON(procName, pset, username, password, preHash, admin, 200 /* HTTP_OK */); } public static String callProcOverJSON(String procName, ParameterSet pset, String username, String password, boolean preHash, boolean admin, int expectedCode) throws Exception { // Call insert String paramsInJSON = pset.toJSONString(); //System.out.println(paramsInJSON); HashMap<String,String> params = new HashMap<String,String>(); params.put("Procedure", procName); params.put("Parameters", paramsInJSON); if (username != null) { params.put("User", username); } if (password != null) { if (preHash) { params.put("Hashedpassword", getHashedPasswordForHTTPVar(password)); } else { params.put("Password", password); } } if (admin) { params.put("admin", "true"); } String varString = getHTTPVarString(params); varString = getHTTPVarString(params); return callProcOverJSONRaw(varString, expectedCode); } public static Response responseFromJSON(String jsonStr) throws JSONException, IOException { Response response = new Response(); JSONObject jsonObj = new JSONObject(jsonStr); JSONArray resultsJson = jsonObj.getJSONArray("results"); response.results = new VoltTable[resultsJson.length()]; for (int i = 0; i < response.results.length; i++) { JSONObject tableJson = resultsJson.getJSONObject(i); response.results[i] = VoltTable.fromJSONObject(tableJson); System.out.println(response.results[i].toString()); } if (jsonObj.isNull("status") == false) { response.status = (byte) jsonObj.getInt("status"); } if (jsonObj.isNull("appstatus") == false) { response.appStatus = (byte) jsonObj.getInt("appstatus"); } if (jsonObj.isNull("statusstring") == false) { response.statusString = jsonObj.getString("statusstring"); } if (jsonObj.isNull("appstatusstring") == false) { response.appStatusString = jsonObj.getString("appstatusstring"); } if (jsonObj.isNull("exception") == false) { response.exception = jsonObj.getString("exception"); } return response; } /** * Uses included {@link CLIConfig} class to * declaratively state command line options with defaults * and validation. */ static class VoterConfig extends CLIConfig { @Option(desc = "Interval for performance feedback, in seconds.") long displayinterval = 5; @Option(desc = "Benchmark duration, in seconds.") int duration = 120; @Option(desc = "Warmup duration in seconds.") int warmup = 5; @Option(desc = "Comma separated list of the form server[:port] to connect to.") String servers = "localhost"; @Option(desc = "Number of contestants in the voting contest (from 1 to 10).") int contestants = 6; @Option(desc = "Maximum number of votes cast per voter.") int maxvotes = 2; @Option(desc = "Filename to write raw summary statistics to.") String statsfile = ""; @Option(desc = "Number of concurrent threads synchronously calling procedures.") int threads = 40; @Override public void validate() { if (duration <= 0) { exitWithMessageAndUsage("duration must be > 0"); } if (warmup < 0) { exitWithMessageAndUsage("warmup must be >= 0"); } if (displayinterval <= 0) { exitWithMessageAndUsage("displayinterval must be > 0"); } if (contestants <= 0) { exitWithMessageAndUsage("contestants must be > 0"); } if (maxvotes <= 0) { exitWithMessageAndUsage("maxvotes must be > 0"); } if (threads <= 0) { exitWithMessageAndUsage("threads must be > 0"); } } } /** * Constructor for benchmark instance. * Configures VoltDB client and prints configuration. * * @param config Parsed & validated CLI options. */ public HTTPBenchmark(VoterConfig config) { this.config = config; switchboard = new PhoneCallGenerator(config.contestants); System.out.print(HORIZONTAL_RULE); System.out.println(" Command Line Configuration"); System.out.println(HORIZONTAL_RULE); System.out.println(config.getConfigDumpString()); } /** * Prints the results of the voting simulation and statistics * about performance. * * @throws Exception if anything unexpected happens. */ public synchronized void printResults() throws Exception { // 1. Voting Board statistics, Voting results and performance statistics String display = "\n" + HORIZONTAL_RULE + " Voting Results\n" + HORIZONTAL_RULE + " - %,9d Accepted\n" + " - %,9d Rejected (Invalid Contestant)\n" + " - %,9d Rejected (Maximum Vote Count Reached)\n" + " - %,9d Failed (Transaction Error)\n\n"; System.out.printf(display, acceptedVotes.get(), badContestantVotes.get(), badVoteCountVotes.get(), failedVotes.get()); // 2. Voting results String res = callProcOverJSON("Results", ParameterSet.emptyParameterSet(), "myadmin", "voltdbadmin", false); Response response = responseFromJSON(res); VoltTable result = response.results[0]; System.out.println("Contestant Name\t\tVotes Received"); while(result.advanceRow()) { System.out.printf("%s\t\t%,14d\n", result.getString(0), result.getLong(2)); } System.out.printf("\nThe Winner is: %s\n\n", result.fetchRow(0).getString(0)); } /** * While <code>benchmarkComplete</code> is set to false, run as many * synchronous procedure calls as possible and record the results. * */ class VoterThread implements Runnable { @Override public void run() { // Set up some usernames/passwords String names[] = {"john", "scott", "bruce"}; String passwords[] = {"piekos", "jarr", "reading"}; // Choose random credentials int idx = (int)(Math.random() * names.length); String username = names[idx]; String password = passwords[idx]; while (warmupComplete.get() == false) { // Get the next phone call PhoneCallGenerator.PhoneCall call = switchboard.receive(); // Use the JSON/HTTP API to synchronously call the "Vote" procedure try { ParameterSet pset = ParameterSet.fromArrayNoCopy(call.phoneNumber, call.contestantNumber, config.maxvotes); callProcOverJSON("Vote", pset, username, password, true); } catch (Exception e) {} } while (benchmarkComplete.get() == false) { // Get the next phone call PhoneCallGenerator.PhoneCall call = switchboard.receive(); // Use the JSON/HTTP API to synchronously call the "Vote" procedure try { ParameterSet pset = ParameterSet.fromArrayNoCopy(call.phoneNumber, call.contestantNumber, config.maxvotes); String res = callProcOverJSON("Vote", pset, username, password, true); Response response = responseFromJSON(res); assert (response.results[0].advanceRow()); long resultCode = response.results[0].getLong(0); if (resultCode == Vote.ERR_INVALID_CONTESTANT) { badContestantVotes.incrementAndGet(); } else if (resultCode == Vote.ERR_VOTER_OVER_VOTE_LIMIT) { badVoteCountVotes.incrementAndGet(); } else { assert(resultCode == Vote.VOTE_SUCCESSFUL); acceptedVotes.incrementAndGet(); } } catch (Exception e) { failedVotes.incrementAndGet(); e.printStackTrace(System.out); } } } } /** * Core benchmark code. * Connect. Initialize. Run the loop. Cleanup. Print Results. * * @throws Exception if anything unexpected happens. */ public void runBenchmark() throws Exception { System.out.print(HORIZONTAL_RULE); System.out.println(" Setup & Initialization"); System.out.println(HORIZONTAL_RULE); System.out.println("\nPopulating Static Tables\n"); // initialize using JSON over HTTP call ParameterSet pset = ParameterSet.fromArrayNoCopy(config.contestants, CONTESTANT_NAMES_CSV); String res = callProcOverJSON("Initialize", pset, "myadmin", "voltdbadmin", false); System.out.println("JSON response INITIALIZE: " + res); System.out.print(HORIZONTAL_RULE); System.out.println(" Starting Benchmark"); System.out.println(HORIZONTAL_RULE); // create/start the requested number of threads Thread[] voterThreads = new Thread[config.threads]; for (int i = 0; i < config.threads; ++i) { voterThreads[i] = new Thread(new VoterThread()); voterThreads[i].start(); } // Run the benchmark loop for the requested warmup time System.out.println("Warming up..."); Thread.sleep(1000l * config.warmup); // signal to threads to end the warmup phase warmupComplete.set(true); // print periodic statistics to the console benchmarkStartTS = System.currentTimeMillis(); // Run the benchmark loop for the requested warmup time System.out.println("\nRunning benchmark..."); Thread.sleep(1000l * config.duration); // stop the threads benchmarkComplete.set(true); // join on the threads for (Thread t : voterThreads) { t.join(); } // print the summary results printResults(); } /** * Main routine creates a benchmark instance and kicks off the run method. * * @param args Command line arguments. * @throws Exception if anything goes wrong. * @see {@link VoterConfig} */ public static void main(String[] args) throws Exception { // create a configuration from the arguments VoterConfig config = new VoterConfig(); config.parse(HTTPBenchmark.class.getName(), args); HTTPBenchmark benchmark = new HTTPBenchmark(config); benchmark.runBenchmark(); } }
package ru.stga.pft.sandbox; import java.awt.*; public class MyFirstProgram { public static void main(String[] args) { Point p1 = new Point(6,2); Point p2 = new Point(10,2); System.out.println("Расстояние между двумя точками р1 и р2 =" + distance(p1,p2)); } public static double distance(Point p1, Point p2){ return Math.sqrt ((Math.pow((p2.x-p1.x), 2)) + (Math.pow((p2.y-p1.y), 2)) ); } }
package org.bouncycastle.asn1.tsp; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.util.Arrays; public class MessageImprint extends ASN1Object { AlgorithmIdentifier hashAlgorithm; byte[] hashedMessage; /** * Return an instance of MessageImprint, or null, based on o. * * @param o the object to be converted. * @return a MessageImprint object. */ public static MessageImprint getInstance(Object o) { if (o instanceof MessageImprint) { return (MessageImprint)o; } if (o != null) { return new MessageImprint(ASN1Sequence.getInstance(o)); } return null; } private MessageImprint( ASN1Sequence seq) { if (seq.size() == 2) { this.hashAlgorithm = AlgorithmIdentifier.getInstance(seq.getObjectAt(0)); this.hashedMessage = ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets(); } else { throw new IllegalArgumentException("sequence has wrong number of elements"); } } public MessageImprint( AlgorithmIdentifier hashAlgorithm, byte[] hashedMessage) { this.hashAlgorithm = hashAlgorithm; this.hashedMessage = Arrays.clone(hashedMessage); } public AlgorithmIdentifier getHashAlgorithm() { return hashAlgorithm; } public byte[] getHashedMessage() { return Arrays.clone(hashedMessage); } /** * <pre> * MessageImprint ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * hashedMessage OCTET STRING } * </pre> */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(2); v.add(hashAlgorithm); v.add(new DEROctetString(hashedMessage)); return new DERSequence(v); } }
package org.adligo.tests4j_4jacoco.plugin; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * this provides a way to load classes (mostly interfaces) in the default class loader * so that they are the same in child class loaders. * * @author scott * */ public class SharedClassList { public static Set<String> WHITELIST = getSharedClassWhitelist(); private static Set<String> getSharedClassWhitelist() { Set<String> toRet = new HashSet<String>(); toRet.add("org.adligo.tests4j.models.shared.AfterTrial"); toRet.add("org.adligo.tests4j.models.shared.BeforeTrial"); toRet.add("org.adligo.tests4j.models.shared.I_AbstractTrial"); toRet.add("org.adligo.tests4j.models.shared.IgnoreTest"); toRet.add("org.adligo.tests4j.models.shared.IgnoreTrial"); toRet.add("org.adligo.tests4j.models.shared.I_Trial"); toRet.add("org.adligo.tests4j.models.shared.I_TrialProcessorBindings"); toRet.add("org.adligo.tests4j.models.shared.I_MetaTrial"); toRet.add("org.adligo.tests4j.models.shared.PackageScope"); toRet.add("org.adligo.tests4j.models.shared.SourceFileScope"); toRet.add("org.adligo.tests4j.models.shared.Test"); toRet.add("org.adligo.tests4j.models.shared.TrialType"); toRet.add("org.adligo.tests4j.models.shared.UseCaseScope"); toRet.add("org.adligo.tests4j.models.shared.asserts.AssertType"); toRet.add("org.adligo.tests4j.models.shared.asserts.I_AssertType"); toRet.add("org.adligo.tests4j.models.shared.asserts.I_Thrower"); toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_LineTextCompareResult"); toRet.add("org.adligo.tests4j.models.shared.common.TrialTypeEnum"); toRet.add("org.adligo.tests4j.models.shared.common.I_Platform"); toRet.add("org.adligo.tests4j.models.shared.common.PlatformEnum"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_CoverageUnits"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_CoverageUnitsContainer"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_LineCoverage"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_LineCoverageSegment"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_PackageCoverage"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_SourceFileCoverage"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_SourceInfo"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_TestMetadata"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_TrialMetadata"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_TrialRunMetadata"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_UseCase"); toRet.add("org.adligo.tests4j.models.shared.results.I_ApiTrialResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_Duration"); toRet.add("org.adligo.tests4j.models.shared.results.I_SourceFileTrialResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_TestFailure"); toRet.add("org.adligo.tests4j.models.shared.results.I_TestResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_TrialFailure"); toRet.add("org.adligo.tests4j.models.shared.results.I_TrialResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_TrialRunResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_UseCaseTrialResult"); toRet.add("org.adligo.tests4j.models.shared.system.I_ThreadCount"); toRet.add("org.adligo.tests4j.models.shared.system.I_AssertListener"); toRet.add("org.adligo.tests4j.models.shared.system.I_CoveragePlugin"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_Params"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_RemoteInfo"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.I_Tests4J_Constants"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.eclipse.I_EclipseErrors"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_AfterTrialErrors"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_AfterTrialTestErrors"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_AnnotationErrors"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_BeforeTrialErrors"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_TestMethodErrors"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_TrialDescriptionMessages"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.asserts.I_Tests4J_AssertionInputMessages"); toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.asserts.I_Tests4J_AssertionResultMessages"); toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_Probes"); return Collections.unmodifiableSet(toRet); } }
package org.broadinstitute.sting.atk; import net.sf.samtools.SAMFileReader.ValidationStringency; import edu.mit.broad.picard.cmdline.CommandLineProgram; import edu.mit.broad.picard.cmdline.Usage; import edu.mit.broad.picard.cmdline.Option; import org.broadinstitute.sting.atk.modules.*; import org.broadinstitute.sting.utils.ReferenceOrderedData; import org.broadinstitute.sting.utils.rodGFF; import org.broadinstitute.sting.utils.rodDbSNP; import java.io.*; import java.util.HashMap; public class AnalysisTK extends CommandLineProgram { // Usage and parameters @Usage(programVersion="0.1") public String USAGE = "SAM Validator\n"; @Option(shortName="I", doc="SAM or BAM file for validation") public File INPUT_FILE; @Option(shortName="M", doc="Maximum number of reads to process before exiting", optional=true) public String MAX_READS_ARG = "-1"; @Option(shortName="S", doc="How strict should we be with validation", optional=true) public String STRICTNESS_ARG = "strict"; @Option(shortName="R", doc="Reference sequence file", optional=true) public File REF_FILE_ARG = null; @Option(shortName="B", doc="Debugging output", optional=true) public String DEBUGGING_STR = null; @Option(shortName="L", doc="Genome region to operation on: from chr:start-end", optional=true) public String REGION_STR = null; @Option(shortName="T", doc="Type of analysis to run") public String Analysis_Name = null; @Option(shortName="DBSNP", doc="DBSNP file", optional=true) public String DBSNP_FILE = null; @Option(shortName="THREADED_IO", doc="If true, enables threaded I/O operations", optional=true) public String ENABLED_THREADED_IO = "false"; public static HashMap<String, Object> MODULES = new HashMap<String,Object>(); public static void addModule(final String name, final Object walker) { System.out.printf("* Adding module %s%n", name); MODULES.put(name, walker); } static { addModule("CountLoci", new CountLociWalker()); addModule("Pileup", new PileupWalker()); addModule("CountReads", new CountReadsWalker()); addModule("PrintReads", new PrintReadsWalker()); addModule("Base_Quality_Histogram", new BaseQualityHistoWalker()); addModule("AlleleFrequency", new AlleleFrequencyWalker()); addModule("SingleSampleGenotyper", new SingleSampleGenotyper()); addModule("Null", new NullWalker()); addModule("DepthOfCoverage", new DepthOfCoverageWalker()); } private TraversalEngine engine = null; public boolean DEBUGGING = false; /** Required main method implementation. */ public static void main(String[] argv) { System.exit(new AnalysisTK().instanceMain(argv)); } protected int doWork() { final boolean TEST_ROD = false; ReferenceOrderedData[] rods = null; if ( TEST_ROD ) { ReferenceOrderedData gff = new ReferenceOrderedData(new File("trunk/data/gFFTest.gff"), rodGFF.class ); gff.testMe(); //ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("trunk/data/dbSNP_head.txt"), rodDbSNP.class ); ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("/Volumes/Users/mdepristo/broad/ATK/exampleSAMs/dbSNP_chr20.txt"), rodDbSNP.class ); //dbsnp.testMe(); rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp }; } else if ( DBSNP_FILE != null ) { ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File(DBSNP_FILE), rodDbSNP.class ); //dbsnp.testMe(); rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp }; } else { rods = new ReferenceOrderedData[] {}; // { gff, dbsnp }; } this.engine = new TraversalEngine(INPUT_FILE, REF_FILE_ARG, rods); engine.initialize(ENABLED_THREADED_IO.toLowerCase().equals("true")); //engine.testReference(); ValidationStringency strictness; if ( STRICTNESS_ARG == null ) { strictness = ValidationStringency.STRICT; } else if ( STRICTNESS_ARG.toLowerCase().equals("lenient") ) { strictness = ValidationStringency.LENIENT; } else if ( STRICTNESS_ARG.toLowerCase().equals("silent") ) { strictness = ValidationStringency.SILENT; } else { strictness = ValidationStringency.STRICT; } System.err.println("Strictness is " + strictness); engine.setStrictness(strictness); engine.setDebugging(! ( DEBUGGING_STR == null || DEBUGGING_STR.toLowerCase().equals("true"))); engine.setMaxReads(Integer.parseInt(MAX_READS_ARG)); if ( REGION_STR != null ) { engine.setLocation(REGION_STR); } //LocusWalker<Integer,Integer> walker = new PileupWalker(); // Try to get the module specified Object my_module; if (MODULES.containsKey(Analysis_Name)) { my_module = MODULES.get(Analysis_Name); } else { System.out.println("Could not find module "+Analysis_Name); return 0; } try { LocusWalker<?, ?> walker = (LocusWalker<?, ?>)my_module; engine.traverseByLoci(walker); } catch ( java.lang.ClassCastException e ) { // I guess we're a read walker LOL ReadWalker<?, ?> walker = (ReadWalker<?, ?>)my_module; engine.traverseByRead(walker); } return 0; } }
package com.kii.thingif; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.kii.thingif.internal.utils._Log; import com.kii.thingif.schema.Schema; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; public class ThingIFAPIBuilder { private static final String TAG = ThingIFAPIBuilder.class.getSimpleName(); private final Context context; private final KiiApp app; private final Owner owner; private Target target; private String installationID; private String tag; private final List<Schema> schemas = new ArrayList<Schema>(); private ThingIFAPIBuilder( @Nullable Context context, @NonNull KiiApp app, @NonNull Owner owner) { this.context = context; this.app = app; this.owner = owner; } /** Instantiate new ThingIFAPIBuilder. * @param context Application context. * @param app Kii Cloud Application. * @param owner Specify who uses the ThingIFAPI. * @return ThingIFAPIBuilder instance. */ @NonNull public static ThingIFAPIBuilder newBuilder( @NonNull Context context, @NonNull KiiApp app, @NonNull Owner owner) { if (context == null) { throw new IllegalArgumentException("context is null"); } if (app == null) { throw new IllegalArgumentException("app is null"); } if (owner == null) { throw new IllegalArgumentException("owner is null"); } return new ThingIFAPIBuilder(context, app, owner); } /** * Instantiate new ThingIFAPIBuilder without Context. * This method is for internal use only. Do not call it from your application. * * @param app Kii Cloud Application. * @param owner Specify who uses the ThingIFAPI. * @return ThingIFAPIBuilder instance. */ @NonNull public static ThingIFAPIBuilder _newBuilder( @NonNull KiiApp app, @NonNull Owner owner) { if (app == null) { throw new IllegalArgumentException("app is null"); } if (owner == null) { throw new IllegalArgumentException("owner is null"); } return new ThingIFAPIBuilder(null, app, owner); } /** Add Schema to the ThingIFAPI. * @param schema schema for {@link ThingIFAPI} instance. * @return ThingIFAPIBuilder instance for method chaining. */ @NonNull public ThingIFAPIBuilder addSchema( @NonNull Schema schema) { if (schema == null) { throw new IllegalArgumentException("schema is null"); } this.schemas.add(schema); _Log.d(TAG, MessageFormat.format("Added new schema SchemaName={0}, SchemaVersion={1}", schema.getSchemaName(), schema.getSchemaVersion())); return this; } /** * Set target thing to the ThingIFAPI. * @param target target of {@link ThingIFAPI} instance. * @return builder instance for chaining call. */ public ThingIFAPIBuilder setTarget(Target target) { this.target = target; return this; } /** Set tag to this ThingIFAPI instance. * tag is used to distinguish storage area of instance. * <br> * If the api instance is tagged with same string, It will be overwritten. * <br> * If the api instance is tagged with different string, Different key is used to store the * instance. * <br> * <br> * Please refer to {@link ThingIFAPI#loadFromStoredInstance(Context, String)} as well. * @param tag if null or empty string is passed, it will be ignored. * @return builder instance for chaining call. */ @NonNull public ThingIFAPIBuilder setTag(@Nullable String tag) { this.tag = tag; return this; } /** * Set InstallationID to the ThingIFAPI. * @param installationID installation id * @return builder instance for chaining call. */ public ThingIFAPIBuilder setInstallationID(String installationID) { this.installationID = installationID; return this; } @NonNull public ThingIFAPI build() { if (this.schemas.size() == 0) { throw new IllegalStateException("Builder has no schemas"); } _Log.d(TAG, MessageFormat.format("Initialize ThingIFAPI AppID={0}, AppKey={1}, BaseUrl={2}", app.getAppID(), app.getAppKey(), app.getBaseUrl())); return new ThingIFAPI(this.context, this.tag, app, this.owner, this.target, this.schemas, this.installationID); } }
package jsettlers.logic.algorithms.fogofwar; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.concurrent.ConcurrentLinkedQueue; import jsettlers.common.CommonConstants; import jsettlers.common.logging.MilliStopWatch; import jsettlers.common.logging.StopWatch; import jsettlers.common.player.IPlayerable; import jsettlers.common.position.ShortPoint2D; import jsettlers.logic.algorithms.fogofwar.CachedViewCircle.CachedViewCircleIterator; /** * This class holds the fog of war for a given map and player. * * @author Andreas Eberle */ public final class NewFogOfWar implements Serializable { private static final long serialVersionUID = 1877994785778678510L; /** * Longest distance any unit may look */ static final byte MAX_VIEWDISTANCE = 55; static final int PADDING = 10; private final byte player; final short width; final short height; byte[][] sight; private transient boolean enabled = true; transient private IFogOfWarGrid grid; private transient boolean canceled; public NewFogOfWar(short width, short height) { this(width, height, (byte) 0, false); } public NewFogOfWar(final short width, final short height, final byte player, final boolean exploredOnStart) { this.width = width; this.height = height; this.player = player; this.sight = new byte[width][height]; byte defaultSight = 0; if (exploredOnStart) { defaultSight = CommonConstants.FOG_OF_WAR_EXPLORED; } for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { sight[x][y] = defaultSight; } } } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); enabled = true; } public void start(IFogOfWarGrid grid) { this.grid = grid; NewFoWThread thread = new NewFoWThread(); thread.start(); } /** * Gets the visible status of a map pint * * @param x * The x coordinate of the point in 0..(mapWidth - 1) * @param y * The y coordinate of the point in 0..(mapHeight - 1) * @return The status from 0 to visible. */ public final byte getVisibleStatus(int x, int y) { if (enabled) { return (byte) Math.min(sight[x][y], CommonConstants.FOG_OF_WAR_VISIBLE); } else { return CommonConstants.FOG_OF_WAR_VISIBLE; } } @SuppressWarnings("unused") private final boolean isPlayerOK(IPlayerable playerable) { return (CommonConstants.ENABLE_ALL_PLAYER_FOG_OF_WAR || (playerable.getPlayer() == player)); } public final boolean isVisible(int centerx, int centery) { return sight[centerx][centery] >= CommonConstants.FOG_OF_WAR_VISIBLE; } public final void toggleEnabled() { enabled = !enabled; } final class NewFoWThread extends Thread { private static final byte DIM_DOWN_SPEED = 10; private final CircleDrawer drawer; private byte[][] buffer; NewFoWThread() { super("NewFoWThread"); super.setDaemon(true); this.buffer = new byte[width][height]; drawer = new CircleDrawer(); } @Override public final void run() { mySleep(500); while (!canceled) { StopWatch watch = new MilliStopWatch(); watch.start(); if (enabled) { rebuildSight(); } // watch.stop("NewFoWThread needed: "); mySleep(800); } } private final void rebuildSight() { drawer.setBuffer(buffer); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { byte currSight = sight[x][y]; if (currSight >= CommonConstants.FOG_OF_WAR_EXPLORED) { byte newSight = (byte) (currSight - DIM_DOWN_SPEED); if (newSight < CommonConstants.FOG_OF_WAR_EXPLORED) { buffer[x][y] = CommonConstants.FOG_OF_WAR_EXPLORED; } else { buffer[x][y] = newSight; } } else { buffer[x][y] = sight[x][y]; } } } ConcurrentLinkedQueue<? extends IViewDistancable> buildings = grid.getBuildingViewDistancables(); applyViewDistances(buildings); ConcurrentLinkedQueue<? extends IViewDistancable> movables = grid.getMovableViewDistancables(); applyViewDistances(movables); byte[][] temp = sight; sight = buffer; buffer = temp; } private final void applyViewDistances(ConcurrentLinkedQueue<? extends IViewDistancable> objects) { for (IViewDistancable curr : objects) { if (isPlayerOK(curr)) { short distance = curr.getViewDistance(); if (distance > 0) { ShortPoint2D pos = curr.getPos(); if (pos != null) drawer.drawCircleToBuffer(pos.getX(), pos.getY(), distance); } } } } private final void mySleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { e.printStackTrace(); } } } final class CircleDrawer { private byte[][] buffer; private final CachedViewCircle[] cachedCircles = new CachedViewCircle[MAX_VIEWDISTANCE]; public final void setBuffer(byte[][] buffer) { this.buffer = buffer; } /** * Draws a circle to the buffer line. Each point is only brightened and onlydrawn if its x coordinate is in [0, mapWidth - 1] and its computed * y coordinate is bigger than 0. */ final void drawCircleToBuffer(int bufferX, int bufferY, int viewDistance) { CachedViewCircle circle = getCachedCircle(viewDistance); CachedViewCircleIterator iterator = circle.iterator(bufferX, bufferY); while (iterator.hasNext()) { final int x = iterator.getCurrX(); final int y = iterator.getCurrY(); if (x >= 0 && x < width && y > 0 && y < height) { byte oldSight = buffer[x][y]; if (oldSight < CommonConstants.FOG_OF_WAR_VISIBLE) { byte newSight = iterator.getCurrSight(); if (oldSight < newSight) { buffer[x][y] = newSight; } } } } } private CachedViewCircle getCachedCircle(int viewDistance) { int radius = Math.min(viewDistance + PADDING, MAX_VIEWDISTANCE); if (cachedCircles[radius] == null) { cachedCircles[radius] = new CachedViewCircle(radius); } return cachedCircles[radius]; } } public void cancel() { this.canceled = true; } }
package org.bouncycastle.math.field; import java.math.BigInteger; public abstract class FiniteFields { static final FiniteField GF_2 = new PrimeField(BigInteger.valueOf(2)); static final FiniteField GF_3 = new PrimeField(BigInteger.valueOf(3)); public static PolynomialExtensionField getBinaryExtensionField(int[] exponents) { if (exponents[0] != 0) { throw new IllegalArgumentException("Irreducible polynomials in GF(2) must have constant term"); } for (int i = 1; i < exponents.length; ++i) { if (exponents[i] <= exponents[i - 1]) { throw new IllegalArgumentException("Polynomial exponents must be montonically increasing"); } } return new GenericPolynomialExtensionField(GF_2, new GF2Polynomial(exponents)); } // public static PolynomialExtensionField getTernaryExtensionField(Term[] terms) // return new GenericPolynomialExtensionField(GF_3, new GF3Polynomial(terms)); public static FiniteField getPrimeField(BigInteger characteristic) { int bitLength = characteristic.bitLength(); if (characteristic.signum() <= 0 || bitLength < 2) { throw new IllegalArgumentException("'characteristic' must be >= 2"); } if (bitLength < 3) { switch (characteristic.intValue()) { case 2: return GF_2; case 3: return GF_3; } } return new PrimeField(characteristic); } }
package org.eclipse.rdf4j.console; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.rdf4j.http.client.HttpClientSessionManager; import org.eclipse.rdf4j.http.client.SharedHttpClientSessionManager; import org.eclipse.rdf4j.http.client.RDF4JProtocolSession; import org.eclipse.rdf4j.http.protocol.UnauthorizedException; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.repository.manager.LocalRepositoryManager; import org.eclipse.rdf4j.repository.manager.RemoteRepositoryManager; import org.eclipse.rdf4j.repository.manager.RepositoryManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author dale */ public class Connect implements Command { private static final Logger LOGGER = LoggerFactory.getLogger(Connect.class); private final ConsoleState appInfo; private final ConsoleIO consoleIO; private final Disconnect disconnect; Connect(ConsoleIO consoleIO, ConsoleState info, Disconnect disconnect) { super(); this.consoleIO = consoleIO; this.appInfo = info; this.disconnect = disconnect; } public void execute(String... tokens) { if (tokens.length < 2) { consoleIO.writeln(PrintHelp.CONNECT); return; } final String target = tokens[1]; if ("default".equalsIgnoreCase(target)) { connectDefault(); } else { try { new URL(target); // target is a valid URL final String username = (tokens.length > 2) ? tokens[2] : null; // NOPMD final String password = (tokens.length > 3) ? tokens[3] : null; // NOPMD connectRemote(target, username, password); } catch (MalformedURLException e) { // assume target is a directory path connectLocal(target); } } } protected boolean connectDefault() { return installNewManager(new LocalRepositoryManager(this.appInfo.getDataDirectory()), "default data directory"); } private boolean connectRemote(final String url, final String user, final String passwd) { final String pass = (passwd == null) ? "" : passwd; boolean result = false; try { // Ping server final HttpClientSessionManager client = new SharedHttpClientSessionManager(); try { try (RDF4JProtocolSession httpClient = client.createRDF4JProtocolSession(url)) { if (user != null) { httpClient.setUsernameAndPassword(user, pass); } // Ping the server httpClient.getServerProtocol(); } } finally { client.shutDown(); } final RemoteRepositoryManager manager = new RemoteRepositoryManager(url); manager.setUsernameAndPassword(user, pass); result = installNewManager(manager, url); } catch (UnauthorizedException e) { if (user != null && pass.length() > 0) { consoleIO.writeError("Authentication for user '" + user + "' failed"); LOGGER.warn("Authentication for user '" + user + "' failed", e); } else { // Ask user for credentials try { consoleIO.writeln("Authentication required"); final String username = consoleIO.readln("Username:"); final String password = consoleIO.readPassword("Password:"); connectRemote(url, username, password); } catch (IOException ioe) { consoleIO.writeError("Failed to read user credentials"); LOGGER.warn("Failed to read user credentials", ioe); } } } catch (IOException e) { consoleIO.writeError("Failed to access the server: " + e.getMessage()); LOGGER.warn("Failed to access the server", e); } catch (RepositoryException e) { consoleIO.writeError("Failed to access the server: " + e.getMessage()); LOGGER.warn("Failed to access the server", e); } return result; } protected boolean connectLocal(final String path) { final File dir = new File(path); boolean result = false; if (dir.exists() && dir.isDirectory()) { result = installNewManager(new LocalRepositoryManager(dir), dir.toString()); } else { consoleIO.writeError("Specified path is not an (existing) directory: " + path); } return result; } private boolean installNewManager(final RepositoryManager newManager, final String newManagerID) { boolean installed = false; final String managerID = this.appInfo.getManagerID(); if (newManagerID.equals(managerID)) { consoleIO.writeln("Already connected to " + managerID); installed = true; } else { try { newManager.initialize(); disconnect.execute(false); this.appInfo.setManager(newManager); this.appInfo.setManagerID(newManagerID); consoleIO.writeln("Connected to " + newManagerID); installed = true; } catch (RepositoryException e) { consoleIO.writeError(e.getMessage()); LOGGER.error("Failed to install new manager", e); } } return installed; } protected boolean connectRemote(final String url) { return connectRemote(url, null, null); } }
package org.adligo.xml_io.client.schema; import org.adligo.models.params.client.I_XMLBuilder; import org.adligo.tests.ATest; public class Xml_IOSchemaTests extends ATest { public void testSchemaString() throws Exception { SchemaXmlBuilder builder = new SchemaXmlBuilder(); String result = builder.build(Xml_IOSchema.SCHEMA); //the following is the real test, then open in a xml schema editor and make sure it looks ok; /* FileWriter.write("xml_io.xsd", result); */ assertEqualsInternal(new String(new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + I_XMLBuilder.DOS_LINE_FEED + "<schema xmlns=\"http: " targetNamespace=\"http: " xmlns:a=\"http: " elementFormDefault=\"qualified\">" + I_XMLBuilder.DOS_LINE_FEED + "" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"f\" type=\"float\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"D\" type=\"decimal\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"d\" type=\"double\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"b\" type=\"a:Boolean\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"c\" type=\"string\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"A\" type=\"a:BooleanArray\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"B\" type=\"base64Binary\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"a\" type=\"base64Binary\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"C\" type=\"a:Character\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"L\" type=\"a:Collection\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"l\" type=\"long\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"m\" type=\"a:Map\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"I\" type=\"integer\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"k\" type=\"a:KeyValue\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"i\" type=\"int\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"s\" type=\"string\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"S\" type=\"short\"/>" + I_XMLBuilder.DOS_LINE_FEED + "" + I_XMLBuilder.DOS_LINE_FEED + " <simpleType name=\"BooleanArray\">" + I_XMLBuilder.DOS_LINE_FEED + " <restriction base=\"string\">" + I_XMLBuilder.DOS_LINE_FEED + " <pattern value=\"string\"/>" + I_XMLBuilder.DOS_LINE_FEED + " </restriction>" + I_XMLBuilder.DOS_LINE_FEED + " </simpleType>" + I_XMLBuilder.DOS_LINE_FEED + " <simpleType name=\"Boolean\">" + I_XMLBuilder.DOS_LINE_FEED + " <restriction base=\"string\">" + I_XMLBuilder.DOS_LINE_FEED + " <pattern value=\"string\"/>" + I_XMLBuilder.DOS_LINE_FEED + " <maxLength value=\"1\"/>" + I_XMLBuilder.DOS_LINE_FEED + " </restriction>" + I_XMLBuilder.DOS_LINE_FEED + " </simpleType>" + I_XMLBuilder.DOS_LINE_FEED + " <simpleType name=\"Character\">" + I_XMLBuilder.DOS_LINE_FEED + " <restriction base=\"string\">" + I_XMLBuilder.DOS_LINE_FEED + " <maxLength value=\"1\"/>" + I_XMLBuilder.DOS_LINE_FEED + " </restriction>" + I_XMLBuilder.DOS_LINE_FEED + " </simpleType>" + I_XMLBuilder.DOS_LINE_FEED + "" + I_XMLBuilder.DOS_LINE_FEED + " <complexType name=\"Collection\">" + I_XMLBuilder.DOS_LINE_FEED + " <sequence>" + I_XMLBuilder.DOS_LINE_FEED + " <any minOccurs=\"1\" maxOccurs=\"unbounded\"/>" + I_XMLBuilder.DOS_LINE_FEED + " </sequence>" + I_XMLBuilder.DOS_LINE_FEED + " </complexType>" + I_XMLBuilder.DOS_LINE_FEED + " <complexType name=\"Map\">" + I_XMLBuilder.DOS_LINE_FEED + " <sequence>" + I_XMLBuilder.DOS_LINE_FEED + " <element name=\"k\" type=\"a:KeyValue\" minOccurs=\"1\" maxOccurs=\"unbounded\"/>" + I_XMLBuilder.DOS_LINE_FEED + " </sequence>" + I_XMLBuilder.DOS_LINE_FEED + " </complexType>" + I_XMLBuilder.DOS_LINE_FEED + " <complexType name=\"KeyValue\">" + I_XMLBuilder.DOS_LINE_FEED + " <sequence>" + I_XMLBuilder.DOS_LINE_FEED + " <any minOccurs=\"1\" maxOccurs=\"2\"/>" + I_XMLBuilder.DOS_LINE_FEED + " </sequence>" + I_XMLBuilder.DOS_LINE_FEED + " </complexType>" + I_XMLBuilder.DOS_LINE_FEED + "" + I_XMLBuilder.DOS_LINE_FEED + "</schema>" + I_XMLBuilder.DOS_LINE_FEED).getBytes("UTF-8")), result); } private void assertEqualsInternal(String a, String b) { assertEquals(a, b); /* assertEquals(a.length(), b.length()); char [] aChars = a.toCharArray(); char [] bChars = b.toCharArray(); for (int i = 0; i < bChars.length; i++) { char aC = aChars[i]; char bC = bChars[i]; assertEquals("The characters should match at character " + i, aC, bC); } */ } }
package to.etc.domui.component.layout; import java.util.*; import to.etc.domui.dom.css.*; import to.etc.domui.dom.errors.*; import to.etc.domui.dom.html.*; import to.etc.domui.util.*; public class TabPanel extends Div { //vmijic 20090923 TabInstance can be registered as ErrorMessageListener in case when TabPanel has m_markErrorTabs set. private static class TabInstance implements IErrorMessageListener { private NodeBase m_label; private NodeBase m_content; private Img m_img; // private Img m_errorInfo; private Li m_tab; private List<UIMessage> m_msgList = new ArrayList<UIMessage>(); public TabInstance(NodeBase label, NodeBase content, Img img) { m_label = label; m_content = content; m_img = img; } public NodeBase getContent() { return m_content; } public NodeBase getLabel() { return m_label; } public Li getTab() { return m_tab; } public void setTab(Li tab) { m_tab = tab; } public Img getImg() { return m_img; } public void errorMessageAdded(Page pg, UIMessage m) { if(isPartOfContent(m.getErrorNode())) { if(m_msgList.contains(m)) return; m_msgList.add(m); adjustUI(); } } public void errorMessageRemoved(Page pg, UIMessage m) { if(isPartOfContent(m.getErrorNode())) { if(!m_msgList.remove(m)) return; adjustUI(); } } private boolean isPartOfContent(NodeBase errorNode) { if(errorNode == null) { return false; } if(errorNode == m_content) { return true; } return isPartOfContent(errorNode.getParent()); } private void adjustUI() { if(hasErrors()) { m_tab.addCssClass("ui-tab-err"); //FIXME: this code can not work since there is refresh problem (error image is added only after refresh in browser is pressed) //is this same 'HTML rendering already done for visited node' bug in framework? //for now error image is set through css /* if(m_errorInfo == null) { m_errorInfo = new Img("THEME/mini-error.png"); m_errorInfo.setTitle("Tab contain errors."); if(m_tab.getChildCount() > 0 && m_tab.getChild(0) instanceof ATag) { ((ATag) m_tab.getChild(0)).add(m_errorInfo); } } */ } else { m_tab.removeCssClass("ui-tab-err"); //FIXME: this code can not work since there is refresh problem (error image is added only after refresh in browser is pressed) //is this same 'HTML rendering already done for visited node' bug in framework? /* if(m_errorInfo != null) { if(m_tab.getChildCount() > 0 && m_tab.getChild(0) instanceof ATag) { ((ATag) m_tab.getChild(0)).removeChild(m_errorInfo); } m_errorInfo = null; } */ } } public boolean hasErrors() { return m_msgList.size() > 0; } } public interface ITabSelected { public void onTabSelected(TabPanel tabPanel, int oldTabIndex, int newTabIndex) throws Exception; } private List<TabInstance> m_tablist = new ArrayList<TabInstance>(); /** The index for the currently visible tab. */ private int m_currentTab; private Ul m_tabul; /** In case that it is set through constructor TabPanel would mark tabs that contain errors in content */ private boolean m_markErrorTabs = false; private ITabSelected m_onTabSelected; public TabPanel() {} public TabPanel(final boolean markErrorTabs) { m_markErrorTabs = markErrorTabs; if(m_markErrorTabs) { setErrorFence(); } } /** * Simple form for adding a tab which contains a text tabel. * * @param content * @param label */ public void add(NodeBase content, String label) { TextNode tn = new TextNode(label); add(content, tn); } public void add(NodeBase content, String label, String icon) { TextNode tn = new TextNode(label); add(content, tn, icon); } /** * Add a tab page with a complex label part. * @param content * @param tablabel */ public void add(NodeBase content, NodeBase tablabel) { TabInstance tabInstance = new TabInstance(tablabel, content, null); if(m_markErrorTabs) { DomUtil.getMessageFence(this).addErrorListener(tabInstance); } m_tablist.add(tabInstance); if(!isBuilt()) return; //-- Render the new thingies. } public void add(NodeBase content, NodeBase tablabel, String icon) { Img i = new Img(); i.setSrc(icon); i.setCssClass("ui-tab-icon"); i.setBorder(0); TabInstance tabInstance = new TabInstance(tablabel, content, i); if(m_markErrorTabs) { DomUtil.getMessageFence(this).addErrorListener(tabInstance); } m_tablist.add(tabInstance); if(!isBuilt()) return; //-- Render the new thingies. } /** * Build the tab. We generate a "sliding window" variant where the tabs are part of an * "ul"; each content pane is a div. * The complete generated structure looks like: * <pre><![CDATA[ * <div class="ui-tab-c"> * * * </div> * ]]></pre> * * @see to.etc.domui.dom.html.NodeBase#createContent() */ @Override public void createContent() throws Exception { setCssClass("ui-tab-c"); //-- Adjust selected tab index if(getCurrentTab() >= m_tablist.size()) m_currentTab = 0; //-- Create the TAB structure.. Div hdr = new Div(); add(hdr); // The div containing the tab buttons hdr.setCssClass("ui-tab-hdr"); Ul u = new Ul(); m_tabul = u; hdr.add(u); int index = 0; for(TabInstance ti : m_tablist) { renderLabel(index, ti); //-- Add the body to the tab's main div. add(ti.getContent()); ti.getContent().setClear(ClearType.BOTH); ti.getContent().setDisplay(m_currentTab == index ? DisplayType.BLOCK : DisplayType.NONE); ti.getContent().addCssClass("ui-tab-pg"); index++; } } private void renderLabel(int index, TabInstance ti) { Li li = new Li(); m_tabul.add(index, li); ti.setTab(li); // Save for later use, if(index == m_currentTab) { li.addCssClass("ui-tab-sel"); } else { li.removeCssClass("ui-tab-sel"); } //li.setCssClass(index == m_currentTab ? "ui-tab-lbl ui-tab-sel" : "ui-tab-lbl"); ATag a = new ATag(); li.add(a); if(ti.getImg() != null) a.add(ti.getImg()); a.add(ti.getLabel()); // Append the label. final int index_ = index; a.setClicked(new IClicked<ATag>() { public void clicked(ATag b) throws Exception { setCurrentTab(index_); } }); } public int getCurrentTab() { return m_currentTab; } public int getTabIndex(NodeBase tabContent) { for(TabInstance tab : m_tablist) { if(tab.getContent() == tabContent) { return m_tablist.indexOf(tab); } } return -1; } public void setCurrentTab(int index) throws Exception { // System.out.println("Switching to tab " + index); if(index == getCurrentTab() || index < 0 || index >= m_tablist.size()) // Silly index return; if(isBuilt()) { //-- We must switch the styles on the current "active" panel and the current "old" panel int oldIndex = getCurrentTab(); TabInstance oldti = m_tablist.get(getCurrentTab()); // Get the currently active instance, TabInstance newti = m_tablist.get(index); oldti.getContent().setDisplay(DisplayType.NONE); // Switch displays on content newti.getContent().setDisplay(DisplayType.BLOCK); oldti.getTab().removeCssClass("ui-tab-sel"); // Remove selected indicator newti.getTab().addCssClass("ui-tab-sel"); if(m_onTabSelected != null) { m_onTabSelected.onTabSelected(this, oldIndex, index); } } m_currentTab = index; // ORDERED!!! Must be below the above!!! } public void setOnTabSelected(ITabSelected onTabSelected) { m_onTabSelected = onTabSelected; } public ITabSelected getOnTabSelected() { return m_onTabSelected; } }
package org.mskcc.cbio.oncokb.util; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang3.StringUtils; import org.mskcc.cbio.oncokb.bo.*; import org.mskcc.cbio.oncokb.importer.ClinicalTrialsImporter; import org.mskcc.cbio.oncokb.model.*; import org.mskcc.oncotree.model.TumorType; import javax.xml.parsers.ParserConfigurationException; import java.util.*; public class EvidenceUtils { private static EvidenceBo evidenceBo = ApplicationContextSingleton.getEvidenceBo(); /** * Remove evidences if its alteration in the alteration list * * @param evidences * @param alterations * @return */ public static List<Evidence> removeByAlterations(List<Evidence> evidences, Collection<Alteration> alterations) { if (alterations != null) { Iterator<Evidence> i = evidences.iterator(); while (i.hasNext()) { Boolean contain = false; Evidence evidence = i.next(); for (Alteration alteration : alterations) { if (alteration != null) { for (Alteration eviAlt : evidence.getAlterations()) { if (eviAlt != null && alteration.equals(eviAlt)) { contain = true; break; } } if (contain) { i.remove(); break; } } } } } return evidences; } public static Set<Evidence> getRelevantEvidences( Query query, String source, String geneStatus, Set<EvidenceType> evidenceTypes, Set<LevelOfEvidence> levelOfEvidences) { if (query == null) { return new HashSet<>(); } Gene gene = query.getEntrezGeneId() == null ? GeneUtils.getGeneByHugoSymbol(query.getHugoSymbol()) : GeneUtils.getGeneByEntrezId(query.getEntrezGeneId()); if (gene != null) { String variantId = query.getQueryId() + (source != null ? ("&" + source) : "") + "&" + evidenceTypes.toString() + (levelOfEvidences == null ? "" : ("&" + levelOfEvidences.toString())); Alteration alt = AlterationUtils.getAlteration(gene.getHugoSymbol(), query.getAlteration(), null, query.getConsequence(), query.getProteinStart(), query.getProteinEnd()); List<Alteration> relevantAlterations = AlterationUtils.getRelevantAlterations(alt); Set<Evidence> relevantEvidences; List<TumorType> relevantTumorTypes = new ArrayList<>(); if (query.getTumorType() != null) { relevantTumorTypes = TumorTypeUtils.getMappedOncoTreeTypesBySource(query.getTumorType(), source); } EvidenceQueryRes evidenceQueryRes = new EvidenceQueryRes(); evidenceQueryRes.setGene(gene); evidenceQueryRes.setQuery(query); evidenceQueryRes.setAlterations(relevantAlterations); evidenceQueryRes.setOncoTreeTypes(relevantTumorTypes); evidenceQueryRes.setLevelOfEvidences(levelOfEvidences == null ? null : new ArrayList<>(levelOfEvidences)); List<EvidenceQueryRes> evidenceQueryResList = new ArrayList<>(); evidenceQueryResList.add(evidenceQueryRes); if (CacheUtils.isEnabled() && CacheUtils.containRelevantEvidences(gene.getEntrezGeneId(), variantId)) { relevantEvidences = CacheUtils.getRelevantEvidences(gene.getEntrezGeneId(), variantId); } else { relevantEvidences = getEvidence(evidenceQueryResList, evidenceTypes, geneStatus, levelOfEvidences); if (CacheUtils.isEnabled()) { CacheUtils.setRelevantEvidences(gene.getEntrezGeneId(), variantId, relevantEvidences); } } return filterEvidence(relevantEvidences, evidenceQueryRes); } else { return new HashSet<>(); } } public static Set<Evidence> getEvidenceByEvidenceTypesAndLevels(Set<EvidenceType> types, Set<LevelOfEvidence> levels) { if (CacheUtils.isEnabled()) { String levelStr = levels.toString(); String typeStr = types.toString(); StringBuilder sb = new StringBuilder(); if (types != null) { sb.append(typeStr); } if (levelStr != null) { sb.append(levelStr); } String variantId = sb.toString(); if (!CacheUtils.containRelevantEvidences(-1, variantId)) { Set<Alteration> alterations = AlterationUtils.getAllAlterations(); List<Evidence> evidences = EvidenceUtils.getEvidence(new ArrayList<>(alterations), types, levels); CacheUtils.setRelevantEvidences(-1, variantId, new HashSet<>(evidences)); } return CacheUtils.getRelevantEvidences(-1, variantId); } else { Set<Alteration> alterations = AlterationUtils.getAllAlterations(); List<Evidence> evidences = EvidenceUtils.getEvidence(new ArrayList<>(alterations), types, levels); return new HashSet<>(evidences); } } private static List<Evidence> getEvidence(List<Alteration> alterations) { if (alterations == null || alterations.size() == 0) { return new ArrayList<>(); } if (CacheUtils.isEnabled()) { return getAlterationEvidences(alterations); } else { return evidenceBo.findEvidencesByAlteration(alterations); } } public static List<Evidence> getEvidence(List<Alteration> alterations, Set<EvidenceType> evidenceTypes, Set<LevelOfEvidence> levelOfEvidences) { if (alterations == null) { alterations = new ArrayList<>(); } if (evidenceTypes == null) { evidenceTypes = new HashSet<>(); } if (levelOfEvidences == null) { levelOfEvidences = new HashSet<>(); } if (alterations.size() == 0) { return new ArrayList<>(); } if (evidenceTypes.size() == 0 && levelOfEvidences.size() == 0) { return getEvidence(alterations); } if (CacheUtils.isEnabled()) { List<Evidence> alterationEvidences = getAlterationEvidences(alterations); List<Evidence> result = new ArrayList<>(); for (Evidence evidence : alterationEvidences) { if (evidenceTypes.size() > 0 && !evidenceTypes.contains(evidence.getEvidenceType())) { continue; } if (levelOfEvidences.size() > 0 && !levelOfEvidences.contains(evidence.getLevelOfEvidence())) { continue; } result.add(evidence); } return result; } else { if (levelOfEvidences.size() == 0) { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes); } else { return evidenceBo.findEvidencesByAlterationWithLevels(alterations, evidenceTypes, levelOfEvidences); } } } public static List<Evidence> getEvidence(List<Alteration> alterations, Set<EvidenceType> evidenceTypes, Set<TumorType> tumorTypes, Set<LevelOfEvidence> levelOfEvidences) { if (alterations == null || alterations.size() == 0) { return new ArrayList<>(); } if (evidenceTypes == null || evidenceTypes.size() == 0) { return getEvidence(alterations); } if (tumorTypes == null || tumorTypes.size() == 0) { return getEvidence(alterations, evidenceTypes, levelOfEvidences); } if (levelOfEvidences == null || levelOfEvidences.size() == 0) { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes, tumorTypes); } else { return evidenceBo.findEvidencesByAlteration(alterations, evidenceTypes, tumorTypes, levelOfEvidences); } } public static Set<Evidence> getEvidence(List<EvidenceQueryRes> queries, Set<EvidenceType> evidenceTypes, String geneStatus, Set<LevelOfEvidence> levelOfEvidences) { Set<Evidence> evidences = new HashSet<>(); List<EvidenceType> filteredETs = new ArrayList<>(); Map<Integer, Gene> genes = new HashMap<>(); //Get gene evidences Map<Integer, Alteration> alterations = new HashMap<>(); Map<Integer, Alteration> alterationsME = new HashMap<>(); //Mutation effect only Set<TumorType> tumorTypes = new HashSet<>(); for (EvidenceQueryRes query : queries) { if (query.getGene() != null) { int entrezGeneId = query.getGene().getEntrezGeneId(); if (!genes.containsKey(entrezGeneId)) { genes.put(entrezGeneId, query.getGene()); } if (query.getAlterations() != null) { for (Alteration alt : query.getAlterations()) { int altId = alt.getId(); if (!alterations.containsKey(altId)) { alterations.put(altId, alt); } } } if (query.getOncoTreeTypes() != null) { for (TumorType tumorType : query.getOncoTreeTypes()) { if (!tumorTypes.contains(tumorType)) { tumorTypes.add(tumorType); } } } } } if (evidenceTypes.contains(EvidenceType.GENE_SUMMARY)) { filteredETs.add(EvidenceType.GENE_SUMMARY); } if (evidenceTypes.contains(EvidenceType.GENE_BACKGROUND)) { filteredETs.add(EvidenceType.GENE_BACKGROUND); } if (filteredETs.size() > 0) { Map<Gene, Set<Evidence>> mappedEvidences = EvidenceUtils.getEvidenceByGenesAndEvidenceTypes(new HashSet<>(genes.values()), new HashSet<>(filteredETs)); for (Map.Entry<Gene, Set<Evidence>> cursor : mappedEvidences.entrySet()) { evidences.addAll(cursor.getValue()); } } Set<Alteration> alts = new HashSet<>(); alts.addAll(alterations.values()); alts.addAll(alterationsME.values()); if (evidenceTypes.contains(EvidenceType.MUTATION_EFFECT)) { filteredETs.add(EvidenceType.MUTATION_EFFECT); evidences.addAll(getEvidence(new ArrayList<>(alts), Collections.singleton(EvidenceType.MUTATION_EFFECT), null)); } if (evidenceTypes.contains(EvidenceType.ONCOGENIC)) { filteredETs.add(EvidenceType.ONCOGENIC); evidences.addAll(getEvidence(new ArrayList<>(alts), Collections.singleton(EvidenceType.ONCOGENIC), null)); } if (evidenceTypes.contains(EvidenceType.VUS)) { filteredETs.add(EvidenceType.VUS); evidences.addAll(getEvidence(new ArrayList<>(alts), Collections.singleton(EvidenceType.VUS), null)); } if (evidenceTypes.size() != filteredETs.size()) { //Include all level 1 evidences Set<EvidenceType> tmpTypes = new HashSet<>(); tmpTypes.add(EvidenceType.STANDARD_THERAPEUTIC_IMPLICATIONS_FOR_DRUG_SENSITIVITY); tmpTypes.add(EvidenceType.INVESTIGATIONAL_THERAPEUTIC_IMPLICATIONS_DRUG_SENSITIVITY); evidences.addAll(getEvidence(new ArrayList<>(alterations.values()), tmpTypes, levelOfEvidences)); evidenceTypes.remove(EvidenceType.STANDARD_THERAPEUTIC_IMPLICATIONS_FOR_DRUG_SENSITIVITY); evidenceTypes.remove(EvidenceType.INVESTIGATIONAL_THERAPEUTIC_IMPLICATIONS_DRUG_SENSITIVITY); List<Evidence> tumorTypesEvidences = getEvidence(new ArrayList<>(alterations.values()), evidenceTypes, tumorTypes.isEmpty() ? null : tumorTypes, levelOfEvidences); evidences.addAll(tumorTypesEvidences); } return evidences; } public static List<Evidence> getAlterationEvidences(List<Alteration> alterations) { List<Evidence> evidences = new ArrayList<>(); if (CacheUtils.isEnabled()) { Set<Evidence> geneEvidences = new HashSet<>(); for (Alteration alteration : alterations) { geneEvidences.addAll(CacheUtils.getEvidences(alteration.getGene())); } for (Evidence evidence : geneEvidences) { if (!Collections.disjoint(evidence.getAlterations(), alterations)) { evidences.add(evidence); } } } else { evidences = evidenceBo.findEvidencesByAlteration(alterations); } return evidences; } public static Map<Gene, Set<Evidence>> getEvidenceByGenes(Set<Gene> genes) { Map<Gene, Set<Evidence>> evidences = new HashMap<>(); if (CacheUtils.isEnabled()) { for (Gene gene : genes) { if (gene != null) { evidences.put(gene, CacheUtils.getEvidences(gene)); } } } else { evidences = EvidenceUtils.separateEvidencesByGene(genes, new HashSet<Evidence>(ApplicationContextSingleton.getEvidenceBo().findAll())); } return evidences; } public static Map<Gene, Set<Evidence>> getEvidenceByGenesAndEvidenceTypes(Set<Gene> genes, Set<EvidenceType> evidenceTypes) { Map<Gene, Set<Evidence>> result = new HashMap<>(); if (CacheUtils.isEnabled()) { for (Gene gene : genes) { if (gene != null) { Set<Evidence> evidences = CacheUtils.getEvidences(gene); Set<Evidence> filtered = new HashSet<>(); for (Evidence evidence : evidences) { if (evidenceTypes.contains(evidence.getEvidenceType())) { filtered.add(evidence); } } result.put(gene, filtered); } } } else { result = EvidenceUtils.separateEvidencesByGene(genes, new HashSet<Evidence>(ApplicationContextSingleton.getEvidenceBo().findAll())); for (Gene gene : genes) { Set<Evidence> evidences = result.get(gene); for (Evidence evidence : evidences) { if (!evidenceTypes.contains(evidence.getEvidenceType())) { evidences.remove(evidence); } } } } return result; } public static Set<Evidence> getEvidenceByGeneAndEvidenceTypes(Gene gene, Set<EvidenceType> evidenceTypes) { Set<Evidence> result = new HashSet<>(); if (gene != null) { if (CacheUtils.isEnabled()) { Set<Evidence> evidences = CacheUtils.getEvidences(gene); for (Evidence evidence : evidences) { if (evidenceTypes.contains(evidence.getEvidenceType())) { result.add(evidence); } } } else { List<Evidence> evidences = evidenceBo.findEvidencesByGene(Collections.singleton(gene), evidenceTypes); if (evidences != null) { result = new HashSet<>(evidences); } } } return result; } public static Set<Evidence> convertEvidenceLevel(List<Evidence> evidences, Set<TumorType> tumorTypes) { Set<Evidence> tmpEvidences = new HashSet<>(); for (Evidence evidence : evidences) { Evidence tmpEvidence = new Evidence(evidence); Boolean flag = true; if (CollectionUtils.intersection(Collections.singleton(tmpEvidence.getOncoTreeType()), tumorTypes).isEmpty()) { if (tmpEvidence.getLevelOfEvidence() != null) { if (tmpEvidence.getPropagation() != null) { LevelOfEvidence propagationLevel = LevelOfEvidence.getByName(tmpEvidence.getPropagation()); if (propagationLevel != null) { tmpEvidence.setLevelOfEvidence(propagationLevel); }else { flag = false; } } // Don't include any resistance evidence if tumor type is not matched. if (LevelUtils.getResistanceLevels().contains(tmpEvidence.getLevelOfEvidence())) { flag = false; } } } if (flag) { tmpEvidences.add(tmpEvidence); } } return tmpEvidences; } public static Set<Evidence> filterEvidence(Set<Evidence> evidences, EvidenceQueryRes evidenceQuery) { Set<Evidence> filtered = new HashSet<>(); if (evidenceQuery.getGene() != null) { for (Evidence evidence : evidences) { Evidence tempEvidence = new Evidence(evidence); if (tempEvidence.getGene().equals(evidenceQuery.getGene())) { //Add all gene specific evidences if (tempEvidence.getAlterations().isEmpty()) { filtered.add(tempEvidence); } else { if (!CollectionUtils.intersection(tempEvidence.getAlterations(), evidenceQuery.getAlterations()).isEmpty()) { if (tempEvidence.getOncoTreeType() == null) { if (tempEvidence.getEvidenceType().equals(EvidenceType.ONCOGENIC)) { if (tempEvidence.getDescription() == null) { List<Alteration> alterations = new ArrayList<>(); alterations.addAll(tempEvidence.getAlterations()); // tempEvidence.setDescription(SummaryUtils.variantSummary(Collections.singleton(tempEvidence.getGene()), alterations, evidenceQuery.getQueryAlteration(), Collections.singleton(tempEvidence.getTumorType()), evidenceQuery.getQueryTumorType())); } } filtered.add(tempEvidence); } else { List<TumorType> tumorType = new ArrayList<>(); if (tempEvidence.getOncoTreeType() != null) { tumorType.add(tempEvidence.getOncoTreeType()); } if (!Collections.disjoint(evidenceQuery.getOncoTreeTypes(), tumorType)) { filtered.add(tempEvidence); } else { if (tempEvidence.getLevelOfEvidence() != null && tempEvidence.getPropagation() != null) { LevelOfEvidence propagationLevel = LevelOfEvidence.getByName(tempEvidence.getPropagation()); if (propagationLevel != null) { if (evidenceQuery.getLevelOfEvidences() == null || evidenceQuery.getLevelOfEvidences().size() == 0 || evidenceQuery.getLevelOfEvidences().contains(propagationLevel)) { tempEvidence.setLevelOfEvidence(propagationLevel); filtered.add(tempEvidence); } } } } } } } } } } return filtered; } public static List<Evidence> filterAlteration(List<Evidence> evidences, List<Alteration> alterations) { for (Evidence evidence : evidences) { Set<Alteration> filterEvidences = new HashSet<>(); for (Alteration alt : evidence.getAlterations()) { if (alterations.contains(alt)) { filterEvidences.add(alt); } } evidence.getAlterations().clear(); evidence.setAlterations(filterEvidences); } return evidences; } public static Map<Gene, Set<Evidence>> separateEvidencesByGene(Set<Gene> genes, Set<Evidence> evidences) { Map<Gene, Set<Evidence>> result = new HashMap<>(); for (Gene gene : genes) { result.put(gene, new HashSet<Evidence>()); } for (Evidence evidence : evidences) { if (result.containsKey(evidence.getGene())) { result.get(evidence.getGene()).add(evidence); } } return result; } public static MutationEffect getMutationEffectFromEvidence(Set<Evidence> evidences) { Set<MutationEffect> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null) { result.add(MutationEffect.getByName(evidence.getKnownEffect())); } } if (result.size() > 1) { return MainUtils.findHighestMutationEffect(result); } else if (result.size() == 1) { return result.iterator().next(); } else { return null; } } public static Oncogenicity getOncogenicityFromEvidence(Set<Evidence> evidences) { Set<Oncogenicity> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null) { result.add(Oncogenicity.getByEvidence(evidence)); } } if (result.size() > 1) { return MainUtils.findHighestOncogenicity(result); } else if (result.size() == 1) { return result.iterator().next(); } else { return null; } } public static Set<String> getPmids(Set<Evidence> evidences) { Set<String> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Article article : evidence.getArticles()) { if (article.getPmid() != null) { result.add(article.getPmid()); } } } return result; } public static Set<ArticleAbstract> getAbstracts(Set<Evidence> evidences) { Set<ArticleAbstract> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Article article : evidence.getArticles()) { if (article.getAbstractContent() != null) { ArticleAbstract articleAbstract = new ArticleAbstract(); articleAbstract.setAbstractContent(article.getAbstractContent()); articleAbstract.setLink(article.getLink()); result.add(articleAbstract); } } } return result; } public static Set<String> getDrugs(Set<Evidence> evidences) { Set<String> result = new HashSet<>(); for (Evidence evidence : evidences) { for (Treatment treatment : evidence.getTreatments()) { Set<String> drugsInTreatment = new HashSet<>(); for (Drug drug : treatment.getDrugs()) { if (drug.getDrugName() != null) { drugsInTreatment.add(drug.getDrugName()); } } result.add(StringUtils.join(drugsInTreatment, " + ")); } } return result; } public static Map<Gene, Set<Evidence>> getAllGeneBasedEvidences() { Set<Gene> genes = GeneUtils.getAllGenes(); Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); return evidences; } public static Set<Evidence> getEvidenceBasedOnHighestOncogenicity(Set<Evidence> evidences) { Set<Evidence> filtered = new HashSet<>(); Map<Oncogenicity, Set<Evidence>> map = new HashMap<>(); if (evidences == null || evidences.size() == 0) return filtered; for (Evidence evidence : evidences) { if (evidence.getEvidenceType() != null && evidence.getEvidenceType().equals(EvidenceType.ONCOGENIC)) { Oncogenicity oncogenicity = Oncogenicity.getByEvidence(evidence); if (oncogenicity != null) { if (!map.containsKey(oncogenicity)) map.put(oncogenicity, new HashSet<Evidence>()); map.get(oncogenicity).add(evidence); } } } Oncogenicity highestOncogenicity = MainUtils.findHighestOncogenicByEvidences(evidences); if (map.get(highestOncogenicity) != null) filtered = map.get(highestOncogenicity); return filtered; } public static Set<Evidence> getOnlyHighestLevelEvidences(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = separateEvidencesByLevel(evidences); Set<LevelOfEvidence> keys = levels.keySet(); LevelOfEvidence highestLevel = LevelUtils.getHighestLevel(keys); if (highestLevel != null) { return levels.get(highestLevel); } else { return new HashSet<>(); } } public static Set<Evidence> getOnlySignificantLevelsEvidences(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = separateEvidencesByLevel(evidences); Set<LevelOfEvidence> keys = levels.keySet(); LevelOfEvidence highestLevel = LevelUtils.getHighestLevel(keys); Set<Evidence> result = new HashSet<>(); if (highestLevel != null) { if (highestLevel.equals(LevelOfEvidence.LEVEL_2B) && levels.containsKey(LevelOfEvidence.LEVEL_3A)) { result.addAll(levels.get(LevelOfEvidence.LEVEL_3A)); } result.addAll(levels.get(highestLevel)); } return result; } public static Map<LevelOfEvidence, Set<Evidence>> separateEvidencesByLevel(Set<Evidence> evidences) { Map<LevelOfEvidence, Set<Evidence>> levels = new HashMap<>(); for (Evidence evidence : evidences) { if (evidence.getLevelOfEvidence() != null) { if (!levels.containsKey(evidence.getLevelOfEvidence())) { levels.put(evidence.getLevelOfEvidence(), new HashSet<Evidence>()); } levels.get(evidence.getLevelOfEvidence()).add(evidence); } } return levels; } public static Set<Evidence> keepHighestLevelForSameTreatments(Set<Evidence> evidences) { Map<String, Set<Evidence>> maps = new HashedMap(); Set<Evidence> filtered = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getTreatments() != null && evidence.getTreatments().size() > 0) { String treatmentsName = TreatmentUtils.getTreatmentName(evidence.getTreatments(), true); if (!maps.containsKey(treatmentsName)) { maps.put(treatmentsName, new HashSet<Evidence>()); } maps.get(treatmentsName).add(evidence); } else { // Keep all un-treatment evidences filtered.add(evidence); } } for (Map.Entry<String, Set<Evidence>> entry : maps.entrySet()) { Set<Evidence> highestEvis = EvidenceUtils.getOnlyHighestLevelEvidences(entry.getValue()); // If highestEvis has more than 1 items, find highest original level if the level is 2B, 3B if (highestEvis.size() > 1) { Set<LevelOfEvidence> checkLevels = new HashSet<>(); checkLevels.add(LevelOfEvidence.LEVEL_2B); checkLevels.add(LevelOfEvidence.LEVEL_3B); if (checkLevels.contains(highestEvis.iterator().next().getLevelOfEvidence())) { Set<Integer> evidenceIds = new HashSet<>(); for (Evidence evidence : highestEvis) { evidenceIds.add(evidence.getId()); } Set<Evidence> originalEvis = EvidenceUtils.getEvidenceByEvidenceIds(evidenceIds); Set<Evidence> highestOriginalEvis = EvidenceUtils.getOnlyHighestLevelEvidences(originalEvis); Set<Integer> filteredIds = new HashSet<>(); for (Evidence evidence : highestOriginalEvis) { filteredIds.add(evidence.getId()); } for (Evidence evidence : highestEvis) { if (filteredIds.contains(evidence.getId())) { filtered.add(evidence); // Only add one break; } } } else { filtered.add(highestEvis.iterator().next()); } } else { filtered.addAll(highestEvis); } } return filtered; } public static Evidence getEvidenceByEvidenceId(Integer id) { if (id == null) { return null; } Set<Evidence> evidences = new HashSet<>(); if (CacheUtils.isEnabled()) { evidences = CacheUtils.getEvidencesByIds(Collections.singleton(id)); } else { List<Evidence> evidenceList = evidenceBo.findEvidencesByIds(Collections.singletonList(id)); if (evidenceList == null) { evidences = null; } else { evidences = new HashSet<>(evidenceList); } } if (evidences == null || evidences.size() > 1) { return null; } return evidences.iterator().next(); } public static Set<Evidence> getEvidenceByEvidenceIds(Set<Integer> ids) { if (ids == null) { return new HashSet<>(); } if (CacheUtils.isEnabled()) { return CacheUtils.getEvidencesByIds(ids); } else { return new HashSet<>(evidenceBo.findEvidencesByIds(new ArrayList<Integer>(ids))); } } public static Set<Evidence> filterEvidenceByKnownEffect(Set<Evidence> evidences, String knownEffect) { if (knownEffect == null) { return null; } Set<Evidence> result = new HashSet<>(); for (Evidence evidence : evidences) { if (evidence.getKnownEffect() != null && evidence.getKnownEffect().equalsIgnoreCase(knownEffect)) { result.add(evidence); } } return result; } public static Set<Evidence> getSensitiveEvidences(Set<Evidence> evidences) { return filterEvidenceByKnownEffect(evidences, "sensitive"); } public static Set<Evidence> getResistanceEvidences(Set<Evidence> evidences) { return filterEvidenceByKnownEffect(evidences, "resistant"); } // Temporary move evidence process methods here in order to share the code between new APIs and legacies public static List<EvidenceQueryRes> processRequest(List<Query> requestQueries, Set<EvidenceType> evidenceTypes, String geneStatus, String source, Set<LevelOfEvidence> levelOfEvidences, Boolean highestLevelOnly) { List<EvidenceQueryRes> evidenceQueries = new ArrayList<>(); if (source == null) { source = "quest"; } if (evidenceTypes == null) { evidenceTypes = new HashSet<>(MainUtils.getAllEvidenceTypes()); } if (levelOfEvidences == null) { levelOfEvidences = LevelUtils.getPublicLevels(); } if (requestQueries == null || requestQueries.size() == 0) { Set<Evidence> evidences = new HashSet<>(); if ((evidenceTypes != null && evidenceTypes.size() > 0) || (levelOfEvidences != null && levelOfEvidences.size() > 0)) { evidences = EvidenceUtils.getEvidenceByEvidenceTypesAndLevels(evidenceTypes, levelOfEvidences); } EvidenceQueryRes query = new EvidenceQueryRes(); query.setEvidences(new ArrayList<>(evidences)); return Collections.singletonList(query); } else { for (Query requestQuery : requestQueries) { EvidenceQueryRes query = new EvidenceQueryRes(); query.setQuery(requestQuery); query.setGene(getGene(requestQuery.getEntrezGeneId(), requestQuery.getHugoSymbol())); if (query.getGene() != null) { query.setOncoTreeTypes(TumorTypeUtils.getMappedOncoTreeTypesBySource(requestQuery.getTumorType(), source)); if (requestQuery.getAlteration() != null) { Alteration alt = AlterationUtils.getAlteration(query.getGene().getHugoSymbol(), requestQuery.getAlteration(), null, requestQuery.getConsequence(), requestQuery.getProteinStart(), requestQuery.getProteinEnd()); List<Alteration> relevantAlts = AlterationUtils.getRelevantAlterations(alt); // Look for Oncogenic Mutations if no relevantAlt found for alt and alt is hotspot if (relevantAlts.isEmpty() && HotspotUtils.isHotspot(alt.getGene().getHugoSymbol(), alt.getProteinStart(), alt.getProteinEnd())) { Alteration oncogenicMutations = AlterationUtils.findAlteration(alt.getGene(), "Oncogenic Mutations"); if (oncogenicMutations != null) { relevantAlts.add(oncogenicMutations); } } query.setAlterations(relevantAlts); Alteration alteration = AlterationUtils.getAlteration(requestQuery.getHugoSymbol(), requestQuery.getAlteration(), AlterationType.MUTATION.name(), requestQuery.getConsequence(), requestQuery.getProteinStart(), requestQuery.getProteinEnd()); List<Alteration> allelesAlts = AlterationUtils.getAlleleAlterations(alteration); query.setAlleles(new ArrayList<>(allelesAlts)); } else if (query.getOncoTreeTypes() != null && query.getOncoTreeTypes().size() > 0) { // if no alteration assigned, but has tumor type query.setAlterations(new ArrayList<Alteration>(AlterationUtils.getAllAlterations(query.getGene()))); } } if (levelOfEvidences != null) { query.setLevelOfEvidences(new ArrayList<LevelOfEvidence>(levelOfEvidences)); } evidenceQueries.add(query); } } return assignEvidence(EvidenceUtils.getEvidence(evidenceQueries, evidenceTypes, geneStatus, levelOfEvidences), evidenceQueries, highestLevelOnly); } private static Gene getGene(Integer entrezGeneId, String hugoSymbol) { Gene entrezGene = null; Gene hugoGene = null; if (entrezGeneId != null) { entrezGene = GeneUtils.getGeneByEntrezId(entrezGeneId); } if (hugoSymbol != null) { hugoGene = GeneUtils.getGeneByHugoSymbol(hugoSymbol); } if (entrezGene != null) { if (hugoGene != null && !entrezGene.equals(hugoGene)) { return null; } else { return entrezGene; } } return hugoGene; } private static List<EvidenceQueryRes> assignEvidence(Set<Evidence> evidences, List<EvidenceQueryRes> evidenceQueries, Boolean highestLevelOnly) { highestLevelOnly = highestLevelOnly == null ? false : highestLevelOnly; for (EvidenceQueryRes query : evidenceQueries) { query.setEvidences( new ArrayList<>( EvidenceUtils.keepHighestLevelForSameTreatments(EvidenceUtils.filterEvidence(evidences, query)))); // Attach evidence if query doesn't contain any alteration and has alleles. if ((query.getAlterations() == null || query.getAlterations().isEmpty() || AlterationUtils.excludeVUS(query.getGene(), query.getAlterations()).size() == 0) && (query.getAlleles() != null && !query.getAlleles().isEmpty())) { // Get oncogenic and mutation effect evidences List<Alteration> alleles = query.getAlleles(); List<Alteration> allelesAndRelevantAlterations = new ArrayList<>(); Set<Alteration> oncogenicMutations = new HashSet<>(); allelesAndRelevantAlterations.addAll(alleles); Alteration oncogenicAllele = AlterationUtils.findOncogenicAllele(alleles); if (oncogenicAllele != null) { oncogenicMutations = AlterationUtils.getOncogenicMutations(oncogenicAllele); allelesAndRelevantAlterations.addAll(oncogenicMutations); } List<Evidence> oncogenics = EvidenceUtils.getEvidence(allelesAndRelevantAlterations, Collections.singleton(EvidenceType.ONCOGENIC), null); Oncogenicity highestOncogenic = MainUtils.findHighestOncogenicByEvidences(new HashSet<>(oncogenics)); if (highestOncogenic != null) { Evidence recordMatchHighestOncogenicity = null; for (Evidence evidence : oncogenics) { if (evidence.getKnownEffect() != null) { Oncogenicity oncogenicity = Oncogenicity.getByEvidence(evidence); if (oncogenicity != null && oncogenicity.equals(highestOncogenic)) { recordMatchHighestOncogenicity = evidence; break; } } } if (recordMatchHighestOncogenicity != null) { Oncogenicity alleleOncogenicity = MainUtils.setToAlleleOncogenicity(highestOncogenic); Evidence evidence = new Evidence(); evidence.setId(recordMatchHighestOncogenicity.getId()); evidence.setGene(recordMatchHighestOncogenicity.getGene()); evidence.setEvidenceType(EvidenceType.ONCOGENIC); evidence.setKnownEffect(alleleOncogenicity == null ? "" : alleleOncogenicity.getOncogenic()); query.getEvidences().add(evidence); } } Set<Alteration> altsWithHighestOncogenicity = new HashSet<>(); for (Evidence evidence : EvidenceUtils.getEvidenceBasedOnHighestOncogenicity(new HashSet<Evidence>(oncogenics))) { for (Alteration alt : evidence.getAlterations()) { if (allelesAndRelevantAlterations.contains(alt)) { altsWithHighestOncogenicity.add(alt); } } } List<Evidence> mutationEffectsEvis = EvidenceUtils.getEvidence(new ArrayList<>(altsWithHighestOncogenicity), Collections.singleton(EvidenceType.MUTATION_EFFECT), null); if (mutationEffectsEvis != null && mutationEffectsEvis.size() > 0) { Set<String> effects = new HashSet<>(); for (Evidence mutationEffectEvi : mutationEffectsEvis) { effects.add(mutationEffectEvi.getKnownEffect()); } Evidence mutationEffect = new Evidence(); Evidence example = mutationEffectsEvis.iterator().next(); mutationEffect.setId(example.getId()); mutationEffect.setGene(example.getGene()); mutationEffect.setEvidenceType(EvidenceType.MUTATION_EFFECT); mutationEffect.setKnownEffect(MainUtils.getAlleleConflictsMutationEffect(effects)); query.getEvidences().add(mutationEffect); } // Get alternate allele treatment evidences, only match sensitive treatments List<Evidence> alleleEvidences = EvidenceUtils.getEvidence(new ArrayList<>(alleles), MainUtils.getSensitiveTreatmentEvidenceTypes(), LevelUtils.getPublicLevels()); if (oncogenicMutations != null) { alleleEvidences.addAll(EvidenceUtils.getEvidence(new ArrayList<>(oncogenicMutations), MainUtils.getTreatmentEvidenceTypes(), LevelUtils.getPublicLevels())); } List<Evidence> alleleEvidencesCopy = new ArrayList<>(); if (alleleEvidences != null) { for (Evidence evidence : alleleEvidences) { Evidence tmpEvidence = new Evidence(evidence); LevelOfEvidence levelOfEvidence = LevelUtils.setToAlleleLevel(evidence.getLevelOfEvidence(), CollectionUtils.intersection(Collections.singleton(evidence.getOncoTreeType()), query.getOncoTreeTypes()).size() > 0); if (levelOfEvidence != null) { tmpEvidence.setLevelOfEvidence(levelOfEvidence); alleleEvidencesCopy.add(tmpEvidence); } } query.getEvidences().addAll(convertEvidenceLevel(alleleEvidencesCopy, new HashSet<>(query.getOncoTreeTypes()))); } } if (highestLevelOnly) { Set<Evidence> allEvidences = new HashSet<>(query.getEvidences()); List<Evidence> filteredEvidences = new ArrayList<>(); // Get highest sensitive evidences Set<Evidence> sensitiveEvidences = EvidenceUtils.getSensitiveEvidences(allEvidences); filteredEvidences.addAll(EvidenceUtils.getOnlyHighestLevelEvidences(sensitiveEvidences)); // Get highest resistance evidences Set<Evidence> resistanceEvidences = EvidenceUtils.getResistanceEvidences(allEvidences); filteredEvidences.addAll(EvidenceUtils.getOnlyHighestLevelEvidences(resistanceEvidences)); query.setEvidences(filteredEvidences); } } return evidenceQueries; } public static void annotateEvidence(Evidence evidence) throws ParserConfigurationException { ClinicalTrialBo clinicalTrialBo = ApplicationContextSingleton.getClinicalTrialBo(); ArticleBo articleBo = ApplicationContextSingleton.getArticleBo(); NccnGuidelineBo nccnGuidelineBo = ApplicationContextSingleton.getNccnGuidelineBo(); DrugBo drugBo = ApplicationContextSingleton.getDrugBo(); TreatmentBo treatmentBo = ApplicationContextSingleton.getTreatmentBo(); Set<ClinicalTrial> trials = evidence.getClinicalTrials(); Set<Article> articles = evidence.getArticles(); Set<Treatment> treatments = evidence.getTreatments(); Set<NccnGuideline> nccnGuidelines = evidence.getNccnGuidelines(); if(trials != null && !trials.isEmpty()){ Set<ClinicalTrial> annotatedTrials = new HashSet<>(); Set<String> nctIds = new HashSet<String>(); for(ClinicalTrial trial: trials){ String tempNctID = trial.getNctId(); ClinicalTrial tempCT = clinicalTrialBo.findClinicalTrialByNctId(tempNctID); if(tempCT == null){ nctIds.add(tempNctID); }else{ annotatedTrials.add(tempCT); } } annotatedTrials.addAll(ClinicalTrialsImporter.importTrials(nctIds)); evidence.setClinicalTrials(annotatedTrials); } if(articles != null && !articles.isEmpty()){ Set<Article> annotatedArticles = new HashSet<>(); for(Article article : articles){ String tempPMID = article.getPmid(); if(tempPMID == null){ Article tempAT = articleBo.findArticleByAbstract(article.getAbstractContent()); if(tempAT == null){ articleBo.save(article); annotatedArticles.add(article); }else{ annotatedArticles.add(tempAT); } }else{ Article tempAT = articleBo.findArticleByPmid(tempPMID); if(tempAT == null){ Article newArticle = NcbiEUtils.readPubmedArticle(tempPMID); if(newArticle != null) { articleBo.save(newArticle); annotatedArticles.add(newArticle); } }else{ annotatedArticles.add(tempAT); } } } evidence.setArticles(annotatedArticles); } if(treatments != null && !treatments.isEmpty()){ for(Treatment treatment : treatments) { Set<Drug> drugs = treatment.getDrugs(); if(drugs != null && !drugs.isEmpty()) { Set<Drug> drugsFromDB = new HashSet<>(); for(Drug drug : drugs){ Drug tempDrug = drugBo.findDrugByName(drug.getDrugName()); if(tempDrug == null){ drugBo.save(drug); drugsFromDB.add(drug); } else{ drugsFromDB.add(tempDrug); } } treatment.setDrugs(drugsFromDB); } treatmentBo.saveOrUpdate(treatment); } } if(nccnGuidelines != null && !nccnGuidelines.isEmpty()){ Set<NccnGuideline> nccnFromDB = new HashSet<>(); for(NccnGuideline nccnGuideline : nccnGuidelines) { NccnGuideline tempNccnGuideline = nccnGuidelineBo.findNccnGuideline(nccnGuideline.getDisease(), nccnGuideline.getVersion(), nccnGuideline.getPages()); if(tempNccnGuideline == null){ nccnGuidelineBo.saveOrUpdate(nccnGuideline); nccnFromDB.add(nccnGuideline); }else { nccnFromDB.add(tempNccnGuideline); } } evidence.setNccnGuidelines(nccnFromDB); } } }
package org.apache.xerces.jaxp; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import java.util.Hashtable; import org.apache.xerces.parsers.DOMParser; /** * @author Rajiv Mordani * @author Edwin Goei */ public class DocumentBuilderFactoryImpl extends DocumentBuilderFactory { /** These are DocumentBuilderFactory attributes not DOM attributes */ private Hashtable attributes; /** * Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder} * using the currently configured parameters. */ public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { try { return new DocumentBuilderImpl(this, attributes); } catch (SAXException se) { // Handles both SAXNotSupportedException, SAXNotRecognizedException throw new ParserConfigurationException(se.getMessage()); } } /** * Allows the user to set specific attributes on the underlying * implementation. * @param name name of attribute * @param value null means to remove attribute */ public void setAttribute(String name, Object value) throws IllegalArgumentException { // This handles removal of attributes if (value == null) { if (attributes != null) { attributes.remove(name); } // Unrecognized attributes do not cause an exception return; } // This is ugly. We have to collect the attributes and then // later create a DocumentBuilderImpl to verify the attributes. // Create Hashtable if none existed before if (attributes == null) { attributes = new Hashtable(); } attributes.put(name, value); // Test the attribute name by possibly throwing an exception try { new DocumentBuilderImpl(this, attributes); } catch (Exception e) { attributes.remove(name); throw new IllegalArgumentException(e.getMessage()); } } /** * Allows the user to retrieve specific attributes on the underlying * implementation. */ public Object getAttribute(String name) throws IllegalArgumentException { // See if it's in the attributes Hashtable if (attributes != null) { Object val = attributes.get(name); if (val != null) { return val; } } DOMParser domParser = null; try { // We create a dummy DocumentBuilderImpl in case the attribute // name is not one that is in the attributes hashtable. domParser = new DocumentBuilderImpl(this, attributes).getDOMParser(); return domParser.getProperty(name); } catch (SAXException se1) { // assert(name is not recognized or not supported), try feature try { boolean result = domParser.getFeature(name); // Must have been a feature return result ? Boolean.TRUE : Boolean.FALSE; } catch (SAXException se2) { // Not a property or a feature throw new IllegalArgumentException(se1.getMessage()); } } } }
//FILE: SetupPanel.java //PROJECT: Micro-Manager //SUBSYSTEM: ASIdiSPIM plugin // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager.asidispim; import com.swtdesigner.SwingResourceManager; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Point2D; import org.micromanager.asidispim.Data.Cameras; import org.micromanager.asidispim.Data.Devices; import org.micromanager.asidispim.Data.Joystick; import org.micromanager.asidispim.Data.Positions; import org.micromanager.asidispim.Data.Prefs; import org.micromanager.asidispim.Data.Properties; import org.micromanager.asidispim.Utils.ListeningJPanel; import org.micromanager.asidispim.Utils.PanelUtils; import mmcorej.CMMCore; import javax.swing.*; import net.miginfocom.swing.MigLayout; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.ScriptInterface; import org.micromanager.internalinterfaces.LiveModeListener; import org.micromanager.utils.NumberUtils; /** * * @author Nico * @author Jon */ @SuppressWarnings("serial") public final class SetupPanel extends ListeningJPanel implements LiveModeListener { private final Devices devices_; private final Properties props_; private final Joystick joystick_; private final Positions positions_; private final Cameras cameras_; private final Prefs prefs_; private final ScriptInterface gui_; private final CMMCore core_; private String port_; // needed to send serial commands directly private final JoystickSubPanel joystickPanel_; private final CameraSubPanel cameraPanel_; private final BeamSubPanel beamPanel_; // used to store the start/stop positions of the single-axis moves for imaging piezo and micromirror sheet move axis private double imagingStartPos_; private double imagingStopPos_; private double imagingCenterPos_; private double sheetStartPos_; private double sheetStopPos_; private double sheetCenterPos_; private boolean illumPiezoHomeEnable_; // device keys, get assigned in constructor based on side private Devices.Keys piezoImagingDeviceKey_; private Devices.Keys piezoIlluminationDeviceKey_; private Devices.Keys micromirrorDeviceKey_; private JLabel imagingPiezoPositionLabel_; private JLabel illuminationPiezoPositionLabel_; private JLabel sheetPositionLabel_; private final JLabel sheetStartPosLabel_; private final JLabel sheetEndPositionLabel_; private final JLabel piezoStartPositionLabel_; final JLabel piezoEndPositionLabel_; public SetupPanel(ScriptInterface gui, Devices devices, Properties props, Joystick joystick, Devices.Sides side, Positions positions, Cameras cameras, Prefs prefs) { super("Setup Path " + side.toString(), new MigLayout( "", "[center]8[align center]", "[]16[]16[]")); devices_ = devices; props_ = props; joystick_ = joystick; positions_ = positions; cameras_ = cameras; prefs_ = prefs; gui_ = gui; core_ = gui_.getMMCore(); PanelUtils pu = new PanelUtils(gui_, prefs_); piezoImagingDeviceKey_ = Devices.getSideSpecificKey(Devices.Keys.PIEZOA, side); piezoIlluminationDeviceKey_ = Devices.getSideSpecificKey(Devices.Keys.PIEZOA, Devices.getOppositeSide(side)); micromirrorDeviceKey_ = Devices.getSideSpecificKey(Devices.Keys.GALVOA, side); port_ = null; updatePort(); // These labels will be updated in the updateStartStopPositions function sheetStartPosLabel_ = new JLabel(""); sheetEndPositionLabel_ = new JLabel(""); piezoStartPositionLabel_ = new JLabel(""); piezoEndPositionLabel_ = new JLabel(""); updateStartStopPositions(); // Create sheet Panel with sheet and piezo controls MigLayout ml = new MigLayout( "", "[right]8[align center]8[right]8[]8[center]8[center]8[center]8[center]8[center]", "[]6[]6[]10[]6[]6[]10[]10[]10[]"); JPanel sheetPanel = new JPanel(ml); final JFormattedTextField offsetField = pu.makeFloatEntryField(panelName_, "Offset", 0.1, 8); final JFormattedTextField rateField = pu.makeFloatEntryField(panelName_, "Rate", -10, 8); JButton setMiddleButton = new JButton("Set Acquisition Center"); setMiddleButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Point2D.Double pt = core_.getGalvoPosition( devices_.getMMDeviceException(micromirrorDeviceKey_)); sheetCenterPos_ = pt.y; imagingCenterPos_ = core_.getPosition( devices_.getMMDeviceException(piezoImagingDeviceKey_)); } catch (Exception ex) { gui_.showError(ex); } } }); sheetPanel.add(setMiddleButton, "span 7, center"); // TODO: let the user choose galvodelta final double galvoDelta = 0.05; JButton upButton = new JButton(); upButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "icons/arrow_up.png")); upButton.setText(""); upButton.setToolTipText("Move sheet and piezo together"); upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Point2D.Double pt = core_.getGalvoPosition( devices_.getMMDeviceException(micromirrorDeviceKey_)); double galvoPos = pt.y; setGalvoAndPiezo(galvoPos + galvoDelta, (Double) offsetField.getValue(),(Double)rateField.getValue() ); } catch (Exception ex) { gui_.showError(ex); } } }); JButton downButton = new JButton(); downButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "icons/arrow_down.png")); downButton.setText(""); downButton.setToolTipText("Move sheet and piezo together"); downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Point2D.Double pt = core_.getGalvoPosition( devices_.getMMDeviceException(micromirrorDeviceKey_)); double galvoPos = pt.y; setGalvoAndPiezo(galvoPos - galvoDelta, (Double) offsetField.getValue(),(Double)rateField.getValue() ); } catch (Exception ex) { gui_.showError(ex); } } }); sheetPanel.add(upButton); sheetPanel.add(downButton, "wrap"); sheetPanel.add(new JSeparator(SwingConstants.HORIZONTAL), "span 9, growx, wrap"); sheetPanel.add(new JLabel("Piezo Position = ")); sheetPanel.add(offsetField); sheetPanel.add(new JLabel(" + "), "center"); sheetPanel.add(rateField, "skip 1"); sheetPanel.add(new JLabel (" * Sheet Position")); JButton tmp_but = new JButton("Compute"); tmp_but.setToolTipText("Computes ratio from start and end positions"); tmp_but.setContentAreaFilled(false); tmp_but.setOpaque(true); tmp_but.setBackground(Color.green); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { double rate = (imagingStopPos_ - imagingStartPos_)/(sheetStopPos_ - sheetStartPos_); rateField.setValue((Double)rate); double offset = (imagingStopPos_ + imagingStartPos_) / 2 - (rate * ( (sheetStopPos_ + sheetStartPos_) / 2) ); offsetField.setValue((Double) offset); } catch (Exception ex) { gui_.showError(ex); } } }); sheetPanel.add(tmp_but, "skip 2, wrap"); sheetPanel.add(new JSeparator(SwingConstants.HORIZONTAL), "span 9, growx, wrap"); sheetPanel.add(new JLabel("Start"), "skip 4, span2, center"); sheetPanel.add(new JLabel("End"), "skip 1, span 2, center, wrap"); sheetPanel.add(new JLabel("Sheet/slice position:")); sheetPositionLabel_ = new JLabel(""); sheetPanel.add(sheetPositionLabel_); sheetPanel.add(pu.makeSetPositionField(micromirrorDeviceKey_, Joystick.Directions.Y, positions_)); sheetPanel.add(new JSeparator(SwingConstants.VERTICAL), "spany 2, growy, shrinkx"); sheetPanel.add(sheetStartPosLabel_); // Go to start button tmp_but = new JButton("Go to"); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { positions_.setPosition(micromirrorDeviceKey_, Joystick.Directions.Y, sheetStartPos_); positions_.setPosition(piezoImagingDeviceKey_, Joystick.Directions.NONE, imagingStartPos_); } catch (Exception ex) { gui_.showError(ex); } } }); sheetPanel.add(tmp_but, ""); sheetPanel.add(new JSeparator(SwingConstants.VERTICAL), "spany 2, growy"); sheetPanel.add(sheetEndPositionLabel_); // go to end button tmp_but = new JButton("Go to"); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { positions_.setPosition(micromirrorDeviceKey_, Joystick.Directions.Y, sheetStopPos_); positions_.setPosition(piezoImagingDeviceKey_, Joystick.Directions.NONE, imagingStopPos_); } catch (Exception ex) { gui_.showError(ex); } } }); sheetPanel.add(tmp_but, "wrap"); sheetPanel.add(new JLabel("Imaging piezo:")); imagingPiezoPositionLabel_ = new JLabel(""); sheetPanel.add(imagingPiezoPositionLabel_); sheetPanel.add(pu.makeSetPositionField(piezoImagingDeviceKey_, Joystick.Directions.NONE, positions_)); sheetPanel.add(piezoStartPositionLabel_); tmp_but = new JButton("Set"); tmp_but.setToolTipText("Saves start position for imaging piezo and scanner slice (should be focused)"); tmp_but.setContentAreaFilled(false); tmp_but.setOpaque(true); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { // bypass cached positions in positions_ in case they aren't current Point2D.Double pt = core_.getGalvoPosition( devices_.getMMDeviceException(micromirrorDeviceKey_)); sheetStartPos_ = pt.y; updateSheetSAParams(); imagingStartPos_ = core_.getPosition( devices_.getMMDeviceException(piezoImagingDeviceKey_)); updateImagingSAParams(); updateStartStopPositions(); } catch (Exception ex) { gui_.showError(ex); } } }); sheetPanel.add(tmp_but); sheetPanel.add(piezoEndPositionLabel_); tmp_but = new JButton("Set"); tmp_but.setToolTipText("Saves end position for imaging piezo and scanner slice (should be focused)"); tmp_but.setContentAreaFilled(false); tmp_but.setOpaque(true); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { // bypass cached positions in positions_ in case they aren't current Point2D.Double pt = core_.getGalvoPosition( devices_.getMMDeviceException(micromirrorDeviceKey_)); sheetStopPos_ = pt.y; updateSheetSAParams(); imagingStopPos_ = core_.getPosition( devices_.getMMDeviceException(piezoImagingDeviceKey_)); updateImagingSAParams(); updateStartStopPositions(); } catch (Exception ex) { gui_.showError(ex); } } }); sheetPanel.add(tmp_but, "wrap"); sheetPanel.add(new JSeparator(SwingConstants.HORIZONTAL), "span 9, growx, wrap"); sheetPanel.add(new JLabel("Illumination Piezo:")); illuminationPiezoPositionLabel_ = new JLabel(""); sheetPanel.add(illuminationPiezoPositionLabel_); sheetPanel.add(pu.makeSetPositionField(piezoIlluminationDeviceKey_, Joystick.Directions.NONE, positions_)); tmp_but = new JButton("Set home"); tmp_but.setToolTipText("During SPIM, illumination piezo is moved to home position"); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String letter = ""; updatePort(); if (port_ == null) { return; } try { letter = props_.getPropValueString(piezoIlluminationDeviceKey_, Properties.Keys.AXIS_LETTER); core_.setSerialPortCommand(port_, "HM " + letter + "+", "\r"); } catch (Exception ex) { gui_.showError("could not execute core function set home here for axis " + letter); } } }); sheetPanel.add(tmp_but, "skip 1"); tmp_but = new JButton("Go home"); tmp_but.setToolTipText("During SPIM, illumination piezo is moved to home position"); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String letter = ""; updatePort(); if (port_ == null) { return; } try { letter = props_.getPropValueString(piezoIlluminationDeviceKey_, Properties.Keys.AXIS_LETTER); core_.setSerialPortCommand(port_, "! " + letter, "\r"); } catch (Exception ex) { gui_.showError("could not execute core function move to home for axis " + letter); } } }); sheetPanel.add(tmp_but); final JCheckBox illumPiezoHomeEnable = new JCheckBox("Go home on tab activate"); ActionListener ae = new ActionListener() { public void actionPerformed(ActionEvent e) { illumPiezoHomeEnable_ = illumPiezoHomeEnable.isSelected(); prefs_.putBoolean(panelName_, Prefs.Keys.ENABLE_ILLUM_PIEZO_HOME, illumPiezoHomeEnable.isSelected()); } }; illumPiezoHomeEnable.addActionListener(ae); illumPiezoHomeEnable.setSelected(prefs_.getBoolean(panelName_, Prefs.Keys.ENABLE_ILLUM_PIEZO_HOME, true)); ae.actionPerformed(null); sheetPanel.add(illumPiezoHomeEnable, "skip 1, span 2, wrap"); sheetPanel.add(new JLabel("Sheet width:")); sheetPanel.add(new JLabel(""), "span 2"); // TODO update this label with current value JSlider tmp_sl = pu.makeSlider(0, // 0 is min amplitude props_.getPropValueFloat(micromirrorDeviceKey_,Properties.Keys.MAX_DEFLECTION_X) - props_.getPropValueFloat(micromirrorDeviceKey_, Properties.Keys.MIN_DEFLECTION_X), // compute max amplitude 1000, // the scale factor between internal integer representation and float representation props_, devices_, micromirrorDeviceKey_, Properties.Keys.SA_AMPLITUDE_X_DEG); sheetPanel.add(tmp_sl, "skip 1, span 5, growx, center, wrap"); sheetPanel.add(new JLabel("Sheet offset:")); sheetPanel.add(new JLabel(""), "span 2"); // TODO update this label with current value tmp_sl = pu.makeSlider( props.getPropValueFloat(micromirrorDeviceKey_, Properties.Keys.MIN_DEFLECTION_X), // min value props.getPropValueFloat(micromirrorDeviceKey_, Properties.Keys.MAX_DEFLECTION_X), // max value 1000, // the scale factor between internal integer representation and float representation props_, devices_, micromirrorDeviceKey_, Properties.Keys.SA_OFFSET_X_DEG); sheetPanel.add(tmp_sl, "skip 1, span 5, growx, center, wrap"); // Layout of the SetupPanel joystickPanel_ = new JoystickSubPanel(joystick_, devices_, panelName_, side, prefs_); add(joystickPanel_, "center"); sheetPanel.setBorder(BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); add(sheetPanel, "center, aligny top, span 1 3, wrap"); beamPanel_ = new BeamSubPanel(devices_, panelName_, side, prefs_, props_); beamPanel_.setBorder(BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); add(beamPanel_, "center, wrap"); cameraPanel_ = new CameraSubPanel(gui_, cameras_, devices_, panelName_, side, prefs_, true); cameraPanel_.setBorder(BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); add(cameraPanel_, "center"); // set scan waveform to be triangle, just like SPIM is props_.setPropValue(micromirrorDeviceKey_, Properties.Keys.SA_PATTERN_X, Properties.Values.SAM_TRIANGLE, true); }// end of SetupPanel constructor /** * Utility function that moves the galvo and piezo together */ public void setGalvoAndPiezo(double newGalvoPos, double offset, double rate) { positions_.setPosition(micromirrorDeviceKey_, Joystick.Directions.Y, newGalvoPos); positions_.setPosition(piezoImagingDeviceKey_, Joystick.Directions.NONE, offset + rate * newGalvoPos); } /** * updates single-axis parameters for stepped piezos according to * sheetStartPos_ and sheetEndPos_ */ public void updateImagingSAParams() { if (devices_.getMMDevice(piezoImagingDeviceKey_) == null) { return; } float amplitude = (float) (imagingStopPos_ - imagingStartPos_); float offset = (float) (imagingStartPos_ + imagingStopPos_) / 2; props_.setPropValue(piezoImagingDeviceKey_, Properties.Keys.SA_AMPLITUDE, amplitude); props_.setPropValue(piezoImagingDeviceKey_, Properties.Keys.SA_OFFSET, offset); } /** * updates single-axis parameters for slice positions of micromirrors * according to sheetStartPos_ and sheetEndPos_ */ public void updateSheetSAParams() { if (devices_.getMMDevice(micromirrorDeviceKey_) == null) { return; } float amplitude = (float) (sheetStopPos_ - sheetStartPos_); float offset = (float) (sheetStartPos_ + sheetStopPos_) / 2; props_.setPropValue(micromirrorDeviceKey_, Properties.Keys.SA_AMPLITUDE_Y_DEG, amplitude); props_.setPropValue(micromirrorDeviceKey_, Properties.Keys.SA_OFFSET_Y_DEG, offset); } /** * updates start/stop positions from the present values of properties i'm * undecided if this should be called when tab is selected if yes, then * start/end settings are clobbered when you change tabs if no, then changes * to start/end settings made elsewhere (notably using joystick with scan * enabled) will be clobbered */ // TODO remove this, should not be needed any more because we aren't setting // up single axis values in this tab anymore but just calculating the ratio public void updateStartStopPositions() { if (devices_.getMMDevice(piezoImagingDeviceKey_) == null) { return; } // compute initial start/stop positions from properties double amplitude = (double) props_.getPropValueFloat( piezoImagingDeviceKey_, Properties.Keys.SA_AMPLITUDE); double offset = (double) props_.getPropValueFloat( piezoImagingDeviceKey_, Properties.Keys.SA_OFFSET); imagingStartPos_ = offset - amplitude / 2; piezoStartPositionLabel_.setText( NumberUtils.doubleToDisplayString(imagingStartPos_)); imagingStopPos_ = offset + amplitude / 2; piezoEndPositionLabel_.setText( NumberUtils.doubleToDisplayString(imagingStopPos_)); amplitude = props_.getPropValueFloat( micromirrorDeviceKey_, Properties.Keys.SA_AMPLITUDE_Y_DEG); offset = props_.getPropValueFloat( micromirrorDeviceKey_, Properties.Keys.SA_OFFSET_Y_DEG); sheetStartPos_ = offset - amplitude / 2; sheetStartPosLabel_.setText( NumberUtils.doubleToDisplayString(sheetStartPos_)); sheetStopPos_ = offset + amplitude / 2; sheetEndPositionLabel_.setText( NumberUtils.doubleToDisplayString(sheetStopPos_)); } /** * finds the appropriate COM port, because we have to send "home" (!) and * "sethome" (HM) commands "manually" over serial since the right API calls * don't yet exist // TODO pester Nico et al. for API * * @return true if port is valid, false if not */ private void updatePort() { if (port_ != null) { // if we've already found it then skip return; } try { String mmDevice = devices_.getMMDevice(piezoIlluminationDeviceKey_); if (mmDevice == null) { return; } String hubname = core_.getParentLabel(mmDevice); port_ = core_.getProperty(hubname, Properties.Keys.SERIAL_COM_PORT.toString()); } catch (Exception ex) { gui_.showError("Could not get COM port in SetupPanel constructor."); } } @Override public void saveSettings() { beamPanel_.saveSettings(); // all other prefs are updated on button press instead of here } @Override public void updateStagePositions() { imagingPiezoPositionLabel_.setText(positions_.getPositionString(piezoImagingDeviceKey_)); illuminationPiezoPositionLabel_.setText(positions_.getPositionString(piezoIlluminationDeviceKey_)); sheetPositionLabel_.setText(positions_.getPositionString(micromirrorDeviceKey_, Joystick.Directions.Y)); } /** * required by LiveModeListener interface; just pass call along to camera * panel */ public void liveModeEnabled(boolean enable) { cameraPanel_.liveModeEnabled(enable); } /** * Gets called when this tab gets focus. Uses the ActionListeners of the UI * components */ @Override public void gotSelected() { joystickPanel_.gotSelected(); cameraPanel_.gotSelected(); beamPanel_.gotSelected(); // props_.callListeners(); // not used yet, only for SPIM Params updateStartStopPositions(); // I'm undecided if this is wise or not, see updateStartStopPositions() JavaDoc // moves illumination piezo to home // TODO do this more elegantly (ideally MM API would add Home() function) String letter = ""; updatePort(); if (port_ == null) { return; } if (illumPiezoHomeEnable_) { try { letter = props_.getPropValueString(piezoIlluminationDeviceKey_, Properties.Keys.AXIS_LETTER); core_.setSerialPortCommand(port_, "! " + letter, "\r"); // we need to read the answer or we can get in trouble later on // It would be nice to check the answer core_.getSerialPortAnswer(port_, "\r\n"); } catch (Exception ex) { gui_.showError("could not execute core function move to home for axis " + letter); } } } }
package nl.sense_os.service.ambience; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import nl.sense_os.service.R; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensorData.DataPoint; import nl.sense_os.service.constants.SensorData.SensorNames; import nl.sense_os.service.provider.SNTP; import nl.sense_os.service.shared.PeriodicPollAlarmReceiver; import nl.sense_os.service.shared.PeriodicPollingSensor; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; /** * Represents the magnetic field sensor. Registers itself for updates from the Android * {@link SensorManager}. * * @author Ted Schmidt <ted@sense-os.nl> */ public class MagneticFieldSensor implements SensorEventListener, PeriodicPollingSensor { private static final String TAG = "Sense Magnetic Field Sensor"; private static final String SENSOR_DISPLAY_NAME = "magnetic field"; private static MagneticFieldSensor instance; /** * Factory method to get the singleton instance. * * @param context * @return instance */ public static MagneticFieldSensor getInstance(Context context) { if (null == instance) { instance = new MagneticFieldSensor(context); } return instance; } private long sampleDelay = 0; // in milliseconds private long[] lastSampleTimes = new long[50]; private Context context; private List<Sensor> sensors; private SensorManager smgr; private boolean magneticFieldSensingActive = false; private PeriodicPollAlarmReceiver alarmReceiver; private WakeLock wakeLock; protected MagneticFieldSensor(Context context) { this.context = context; smgr = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); sensors = new ArrayList<Sensor>(); if (null != smgr.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)) { sensors.add(smgr.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)); } alarmReceiver = new PeriodicPollAlarmReceiver(this); } @Override public void doSample() { // Log.v(TAG, "start sample"); // acquire wake lock if (null == wakeLock) { PowerManager powerMgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wakeLock = powerMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.setReferenceCounted(false); } if (!wakeLock.isHeld()) { wakeLock.acquire(500); } else { // Log.v(TAG, "Wake lock already held"); } // register as sensor listener for (Sensor sensor : sensors) { if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { // Log.d(TAG, "registering for sensor " + sensor.getName()); smgr.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL); } } } /** * @return The delay between samples in milliseconds */ @Override public long getSampleRate() { return sampleDelay; } @Override public boolean isActive() { return magneticFieldSensingActive; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // not used } @Override public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; if (System.currentTimeMillis() > lastSampleTimes[sensor.getType()] + sampleDelay) { lastSampleTimes[sensor.getType()] = System.currentTimeMillis(); String sensorName = ""; if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { sensorName = SensorNames.MAGNETIC_FIELD; double x = event.values[0]; // scale to three decimal precision x = BigDecimal.valueOf(x).setScale(3, 0).doubleValue(); double y = event.values[1]; // scale to three decimal precision y = BigDecimal.valueOf(y).setScale(3, 0).doubleValue(); double z = event.values[2]; // scale to three decimal precision z = BigDecimal.valueOf(z).setScale(3, 0).doubleValue(); HashMap<String, Object> dataFields = new HashMap<String, Object>(); dataFields.put("x", x); dataFields.put("y", y); dataFields.put("z", z); String jsonString = new JSONObject(dataFields).toString(); // send msg to MsgHandler Intent i = new Intent(context.getString(R.string.action_sense_new_data)); i.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.JSON); i.putExtra(DataPoint.VALUE, jsonString); i.putExtra(DataPoint.SENSOR_NAME, sensorName); i.putExtra(DataPoint.DISPLAY_NAME, SENSOR_DISPLAY_NAME); i.putExtra(DataPoint.SENSOR_DESCRIPTION, sensor.getName()); i.putExtra(DataPoint.TIMESTAMP, SNTP.getInstance().getTime()); context.startService(i); // sample is successful: unregister the listener stopSample(); } } } /** * Sets the delay between samples. The sensor registers itself for periodic sampling bursts, and * unregisters after it received a sample. * * @param sampleDelay * Sample delay in milliseconds */ @Override public void setSampleRate(long sampleDelay) { stopPolling(); this.sampleDelay = sampleDelay; startPolling(); } private void startPolling() { // Log.v(TAG, "start polling"); alarmReceiver.start(context); } /** * Starts sensing by registering for updates at the Android SensorManager. The sensor registers * for updates at the rate specified by the sampleDelay parameter. * * @param sampleDelay * Delay between samples in milliseconds */ @Override public void startSensing(long sampleRate) { magneticFieldSensingActive = true; setSampleRate(sampleRate); } private void stopPolling() { // Log.v(TAG, "stop polling"); alarmReceiver.stop(context); } private void stopSample() { // Log.v(TAG, "stop sample"); // release wake lock if (null != wakeLock && wakeLock.isHeld()) { wakeLock.release(); } // unregister sensor listener try { smgr.unregisterListener(this); } catch (Exception e) { Log.e(TAG, "Failed to stop magnetic field sample!", e); } } /** * Stops the periodic sampling. */ @Override public void stopSensing() { magneticFieldSensingActive = false; stopPolling(); } }
package org.citygml.textureAtlasAPI; import java.util.HashMap; import org.citygml.textureAtlasAPI.dataStructure.ErrorTypes; import org.citygml.textureAtlasAPI.dataStructure.TexImageInfo; import org.citygml.textureAtlasAPI.dataStructure.TexImageInfo4GMLFile; import org.citygml.textureAtlasAPI.imageIO.ImageLoader; /** * It is a starting point for using Textureatlas API. * After setting properties, call the convert(TexImageInfo,...) method. * It will return modified TexImageInfo. Check getLOG() or getLOGInText * to see the message related to current conversion. * * Note that all the textures in TexImageInfo should be potentially combinable. * * In the case of standalone tool, TexImageInfo4GMLFile should be used instead of TexImageInfo. * In this case images will be loaded in this API. * * To see how should input data structured please see TexImageInfo or TexImageInfo4GMLFile according * to type of your usage. * * User can also set the packing algorithm which should be used and maximum size of atlas. */ public class TextureAtlasGenerator { /** * Different packing algorithm (more info in readme file) * FFDH: First-Fit Decreasing Height * NFDH: Next-Fit Decreasing Height * SLEA: Sleator's algorithm * TPIM: Improved version of Touching Perimeter algorithm. * TPIM_WITHOUT_ROTATION: TPIM algorithm without rotating textures. */ public static final int FFDH = 0; public static final int NFDH = 1; public static final int SLEA = 2; //Touching Perimeter+ improved public static final int TPIM = 5; public static final int TPIM_WITHOUT_ROTATION = 6; private int PackingAlgorithm; private int ImageMaxWidth=2048; private int ImageMaxHeight=2048; private Modifier modifier; private ImageLoader imageLoader; private boolean usePOTS=false; public TextureAtlasGenerator() { PackingAlgorithm= FFDH; ImageMaxWidth=2048; ImageMaxHeight=2048; modifier = new Modifier(PackingAlgorithm, ImageMaxWidth, ImageMaxHeight, usePOTS); imageLoader= new ImageLoader(); } public TextureAtlasGenerator(int PackingAlg, int atlasMaxWidth, int atlasMaxHeight) { usePOTS = false; setGeneralProp(PackingAlg, atlasMaxWidth, atlasMaxHeight, usePOTS); modifier = new Modifier(PackingAlgorithm, ImageMaxWidth, ImageMaxHeight, usePOTS); imageLoader= new ImageLoader(); } public TextureAtlasGenerator(int PackingAlg, int atlasMaxWidth, int atlasMaxHeight, boolean usePOTS) { setGeneralProp(PackingAlg, atlasMaxWidth, atlasMaxHeight,usePOTS); modifier = new Modifier(this.PackingAlgorithm, this.ImageMaxWidth, this.ImageMaxHeight,this.usePOTS); imageLoader= new ImageLoader(); } private void setGeneralProp(int PackingAlg, int atlasMaxWidth, int atlasMaxHeight, boolean usePOTS){ this.usePOTS = usePOTS; this.PackingAlgorithm = PackingAlg; this.ImageMaxHeight = atlasMaxHeight; this.ImageMaxWidth= atlasMaxWidth; } public int getPackingAlgorithm() { return PackingAlgorithm; } public void setPackingAlgorithm(int packingAlgorithm) { this.PackingAlgorithm = packingAlgorithm; } public int getImageMaxWidth() { return ImageMaxWidth; } public void setImageMaxWidth(int imageMaxWidth) { this.ImageMaxWidth = imageMaxWidth; } public int getImageMaxHeight() { return ImageMaxHeight; } public void setImageMaxHeight(int imageMaxHeight) { this.ImageMaxHeight = imageMaxHeight; } public TexImageInfo convert(TexImageInfo tii){ return convert(tii,PackingAlgorithm); } public TexImageInfo convert(TexImageInfo tii, int PackingAlgorithm){ modifier.reset(); if( tii instanceof TexImageInfo4GMLFile){ if( !((TexImageInfo4GMLFile)tii).isImageLoaded()){ tii.setTexImages(imageLoader.loadAllImage(((TexImageInfo4GMLFile)tii).getImagesLocalPath())); } } if (tii instanceof TexImageInfo && tii!=null) imageLoader.setImageLoader(tii.getTexImages()); this.PackingAlgorithm=PackingAlgorithm; // check tii.isImagesReady() modifier.setGeneralSettings(this.PackingAlgorithm, this.ImageMaxWidth, this.ImageMaxHeight,this.usePOTS); return modifier.run(tii); } public HashMap<Object, ErrorTypes> getLOG() { return modifier.getLOG(); } public String getLOGInText(){ HashMap<Object, ErrorTypes> LOG= modifier.getLOG(); StringBuffer sb = new StringBuffer(); for(Object key: LOG.keySet()){ sb.append("<"); sb.append(key.toString()); sb.append(": "); sb.append(LOG.get(key)); sb.append(">\r\n"); } LOG=null; if (sb.length()==0) return null; return sb.toString(); } public void setUsePOTS(boolean usePOTS) { this.usePOTS = usePOTS; } public boolean isUsePOTS() { return usePOTS; } }
package openblocks.common.tileentity.tank; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.INetworkManager; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.Packet132TileEntityData; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.liquids.ILiquidTank; import net.minecraftforge.liquids.ITankContainer; import net.minecraftforge.liquids.LiquidContainerRegistry; import net.minecraftforge.liquids.LiquidStack; import net.minecraftforge.liquids.LiquidTank; import openblocks.OpenBlocks; import openblocks.sync.ISyncableObject; import openblocks.sync.SyncableInt; import openblocks.sync.SyncableShort; import openblocks.utils.BlockUtils; import openblocks.utils.ItemUtils; public class TileEntityTank extends TileEntityTankBase implements ITankContainer { public static int getTankCapacity() { return LiquidContainerRegistry.BUCKET_VOLUME * OpenBlocks.Config.bucketsPerTank; } /** * The tank holding the liquid */ private LiquidTank tank = new LiquidTank(getTankCapacity()); /** * The Id of the liquid in the tank */ private SyncableInt liquidId = new SyncableInt(); /** * The meta of the liquid metadata in the tank */ private SyncableInt liquidMeta = new SyncableInt(); /** * The level of the liquid that is rendered on the client */ private SyncableShort liquidRenderAmount = new SyncableShort(); /** * The amount that will be rendered by the client, interpolated towards * liquidRenderAmount each tick */ private short interpolatedRenderAmount = 0; /** * How quickly the interpolatedRenderAmount approaches liquidRenderAmount */ private static final short adjustRate = 1000; private double flowTimer = Math.random() * 100; /** * Keys of things what get synced */ public enum Keys { liquidId, liquidMeta, renderLevel } public TileEntityTank() { syncMap.put(Keys.liquidId, liquidId); syncMap.put(Keys.liquidMeta, liquidMeta); syncMap.put(Keys.renderLevel, liquidRenderAmount); } public boolean containsValidLiquid() { return liquidId.getValue() != 0 && tank.getLiquidName() != null; } private void interpolateLiquidLevel() { /* Client interpolates render amount */ if (!worldObj.isRemote) return; if (interpolatedRenderAmount + adjustRate < liquidRenderAmount.getValue()) { interpolatedRenderAmount += adjustRate; } else if (interpolatedRenderAmount - adjustRate > liquidRenderAmount.getValue()) { interpolatedRenderAmount -= adjustRate; } else { interpolatedRenderAmount = liquidRenderAmount.getValue(); } } public void updateEntity() { super.updateEntity(); if (!worldObj.isRemote) { HashSet<TileEntityTank> except = new HashSet<TileEntityTank>(); except.add(this); // if we have a liquid if (tank.getLiquid() != null) { // try to fill up the tank below with as much liquid as possible TileEntityTank below = getTankInDirection(ForgeDirection.DOWN); if (below != null) { if (below.getSpace() > 0) { LiquidStack myLiquid = tank.getLiquid().copy(); if (below.canReceiveLiquid(myLiquid)) { int toFill = Math.min(below.getSpace(), myLiquid.amount); myLiquid.amount = toFill; int filled = below.fill(myLiquid, true, except); tank.drain(filled, true); } } } if (getAmount() > 0 && containsValidLiquid()) { // now fill up the horizontal tanks, start with the least // full ArrayList<TileEntityTank> horizontals = getHorizontalTanksOrdererdBySpace(except); for (TileEntityTank horizontal : horizontals) { LiquidStack liquid = tank.getLiquid(); if (horizontal.canReceiveLiquid(liquid) && liquid != null) { int difference = getAmount() - horizontal.getAmount(); if (difference <= 0) continue; int halfDifference = Math.max(difference / 2, 1); LiquidStack liquidCopy = liquid.copy(); liquidCopy.amount = Math.min(500, halfDifference); int filled = horizontal.fill(liquidCopy, true, except); tank.drain(filled, true); } } } if (tank.getLiquid() != null) { // set the sync values for this liquid liquidId.setValue(tank.getLiquid().itemID); liquidMeta.setValue(tank.getLiquid().itemMeta); } } // calculate render height if (containsValidLiquid()) { /* ratio the liquid amount in to the entire short, clamp it */ short newLiquidRender = (short)Math.max(0, Math.min(Short.MAX_VALUE, Short.MAX_VALUE * tank.getLiquid().amount / (float)tank.getCapacity())); liquidRenderAmount.setValue(newLiquidRender); } else { liquidRenderAmount.setValue((short)0); liquidId.setValue(0); liquidMeta.setValue(0); } /* Update EVERY tick */ syncMap.sync(worldObj, this, xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, 1); } else { interpolateLiquidLevel(); flowTimer += 0.1f; } } public boolean canReceiveLiquid(LiquidStack liquid) { if (!tank.containsValidLiquid()) { return true; } if (liquid == null) { return true; } LiquidStack otherLiquid = tank.getLiquid(); if (otherLiquid != null) { return otherLiquid.isLiquidEqual(liquid); } return true; } public LiquidTank getInternalTank() { return tank; } public int getSpace() { return getInternalTank().getCapacity() - getAmount(); } public boolean isFull() { return getAmount() == getInternalTank().getCapacity(); } public int getAmount() { if (getInternalTank() == null || getInternalTank().getLiquid() == null) return 0; return getInternalTank().getLiquid().amount; } public int fill(LiquidStack resource, boolean doFill, HashSet<TileEntityTank> except) { TileEntityTank below = getTankInDirection(ForgeDirection.DOWN); int filled = 0; if (except == null) { except = new HashSet<TileEntityTank>(); } if (resource == null) { return 0; } int startAmount = resource.amount; if (except.contains(this)) { return 0; } except.add(this); resource = resource.copy(); // fill the tank below as much as possible if (below != null && below.getSpace() > 0) { filled = below.fill(resource, doFill, except); resource.amount -= filled; } // fill myself up if (resource.amount > 0) { filled = tank.fill(resource, doFill); resource.amount -= filled; } // ok we cant, so lets fill the tank above if (resource.amount > 0) { TileEntityTank above = getTankInDirection(ForgeDirection.UP); if (above != null) { filled = above.fill(resource, doFill, except); resource.amount -= filled; } } // finally, distribute any remaining to the sides if (resource.amount > 0 && canReceiveLiquid(resource)) { ArrayList<TileEntityTank> horizontals = getHorizontalTanksOrdererdBySpace(except); if (horizontals.size() > 0) { int amountPerSide = resource.amount / horizontals.size(); for (TileEntityTank sideTank : horizontals) { LiquidStack copy = resource.copy(); copy.amount = amountPerSide; filled = sideTank.fill(copy, doFill, except); resource.amount -= filled; } } } return startAmount - resource.amount; } /** * TODO */ public LiquidStack drain(int amount, boolean doDrain) { return tank.drain(amount, doDrain); } @Override public void onSynced(List<ISyncableObject> changes) { // Mikee, we don't need to create the liquid client side cause we don't // care, right? :D if (changes.contains(liquidId) || changes.contains(liquidMeta)) { if (liquidId.getValue() == 0) { tank.setLiquid(null); } else { tank.setLiquid(new LiquidStack(liquidId.getValue(), 1, liquidMeta.getValue())); } } } @Override public void onBlockBroken() { // invalidate(); } @Override public void onBlockPlacedBy(EntityPlayer player, ForgeDirection side, ItemStack stack, float hitX, float hitY, float hitZ) { if (stack.hasTagCompound() && stack.getTagCompound().hasKey("tank")) { NBTTagCompound tankTag = stack.getTagCompound().getCompoundTag("tank"); this.tank.readFromNBT(tankTag); } } @Override public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tank.writeToNBT(tag); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); tank.readFromNBT(tag); interpolatedRenderAmount = (short)((double)getAmount() / (double)tank.getCapacity() * Short.MAX_VALUE); } @Override public int fill(ForgeDirection from, LiquidStack resource, boolean doFill) { int filled = fill(resource, doFill, null); if (doFill && filled > 0) { if (resource != null) { liquidId.setValue(resource.itemID); liquidMeta.setValue(resource.itemMeta); } } return filled; } @Override public int fill(int tankIndex, LiquidStack resource, boolean doFill) { return fill(ForgeDirection.UNKNOWN, resource, doFill); } @Override public LiquidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { return drain(maxDrain, doDrain); } @Override public LiquidStack drain(int tankIndex, int maxDrain, boolean doDrain) { return drain(maxDrain, doDrain); } @Override public ILiquidTank[] getTanks(ForgeDirection direction) { return new ILiquidTank[] { tank }; } @Override public ILiquidTank getTank(ForgeDirection direction, LiquidStack type) { return tank; } public int countDownwardsTanks() { int count = 1; TileEntityTank below = getTankInDirection(ForgeDirection.DOWN); if (below != null) { count += below.countDownwardsTanks(); } return count; } @Override public Packet getDescriptionPacket() { return syncMap.getDescriptionPacket(this); } @Override public void onDataPacket(INetworkManager net, Packet132TileEntityData pkt) { syncMap.handleTileDataPacket(this, pkt); interpolatedRenderAmount = liquidRenderAmount.getValue(); } @Override public boolean onBlockActivated(EntityPlayer player, int side, float hitX, float hitY, float hitZ) { /* TODO: Fix some bugs here with client/server side stuff */ ForgeDirection direction = BlockUtils.sideToDirection(side); ItemStack current = player.inventory.getCurrentItem(); if (current != null) { LiquidStack liquid = LiquidContainerRegistry.getLiquidForFilledItem(current); // Handle filled containers if (liquid != null) { int qty = fill(direction, liquid, true); if (qty != 0 && !player.capabilities.isCreativeMode) { player.inventory.setInventorySlotContents(player.inventory.currentItem, ItemUtils.consumeItem(current)); } return true; } else { // Fix for if(worldObj.isRemote && liquidRenderAmount.getValue() > 0) return true; // End of fix LiquidStack available = tank.getLiquid(); if (available != null) { ItemStack filled = LiquidContainerRegistry.fillLiquidContainer(available, current); liquid = LiquidContainerRegistry.getLiquidForFilledItem(filled); if (liquid != null) { if (!player.capabilities.isCreativeMode) { if (current.stackSize > 1) { if (!player.inventory.addItemStackToInventory(filled)) return false; else { player.inventory.setInventorySlotContents(player.inventory.currentItem, ItemUtils.consumeItem(current)); } } else { player.inventory.setInventorySlotContents(player.inventory.currentItem, ItemUtils.consumeItem(current)); player.inventory.setInventorySlotContents(player.inventory.currentItem, filled); } } drain(ForgeDirection.UNKNOWN, liquid.amount, true); return true; } } } } return false; } public double getHeightForRender() { double percent = getPercentFull(); if(worldObj == null || worldObj.isRemote){ return Math.max(percent > 0 ? 0.1 : 0, percent); } return percent; } public double getPercentFull() { if (containsValidLiquid()) { if (worldObj == null || worldObj.isRemote) { return interpolatedRenderAmount / (double)Short.MAX_VALUE; } else { return liquidRenderAmount.getValue() / (double)Short.MAX_VALUE; } } else { return 0D; /* No D for you ;) */ } } public double getFlowOffset() { return Math.sin(flowTimer) / 35; } public double getLiquidHeightForSide(ForgeDirection... sides) { if (containsValidLiquid()) { double percentFull = getHeightForRender(); if (percentFull > 0.98) { return 1.0; } double fullness = percentFull + getFlowOffset(); int count = 1; for (ForgeDirection side : sides) { TileEntityTank sideTank = getTankInDirection(side); if (sideTank != null && sideTank.canReceiveLiquid(tank.getLiquid())) { fullness += sideTank.getHeightForRender() + sideTank.getFlowOffset(); count++; } } return Math.max(0, Math.min(1, fullness / count)); } else { return 0D; /* No D for you ;) */ } } public void setClientLiquidId(int itemID) { liquidId.setValue(itemID); } public void setClientLiquidMeta(int itemMeta) { liquidMeta.setValue(itemMeta); } public NBTTagCompound getItemNBT() { NBTTagCompound nbt = new NBTTagCompound(); tank.writeToNBT(nbt); return nbt; } }
package org.wandledi.spells; import org.xml.sax.Attributes; import org.wandledi.Attribute; /** * * @author Markus Kahl */ public class TransformedAttribute { private String name; private StringTransformation transformation; public TransformedAttribute(String name, StringTransformation transformation) { this.name = name; this.transformation = transformation; } /**Tries to perform the transformation to a regular Attribute. * * @param attributes The attribute set of which one is to be transformed. * @return An Attribute or null if no corresponding Attribute to transform could be found. */ public Attribute toAttribute(Attributes attributes) { String value = attributes.getValue(name); if (value != null) { return new Attribute(name, transformation.transform(attributes.getValue(name))); } else { return null; } } }
package org.ensembl.healthcheck.eg_gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.ensembl.healthcheck.ConfigurableTestRunner; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseServer; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.GroupOfTests; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.SystemPropertySetter; import org.ensembl.healthcheck.configuration.ConfigurationUserParameters; import org.ensembl.healthcheck.configuration.ConfigureHost; import org.ensembl.healthcheck.configurationmanager.ConfigurationByProperties; import org.ensembl.healthcheck.configurationmanager.ConfigurationFactory; import org.ensembl.healthcheck.configurationmanager.ConfigurationFactory.ConfigurationType; import org.ensembl.healthcheck.eg_gui.AdminTab; import org.ensembl.healthcheck.eg_gui.Constants; import org.ensembl.healthcheck.eg_gui.DatabaseTabbedPane; import org.ensembl.healthcheck.eg_gui.GuiReporterTab; import org.ensembl.healthcheck.eg_gui.TestInstantiatorDynamic; import org.ensembl.healthcheck.eg_gui.TestProgressDialog; import org.ensembl.healthcheck.testcase.EnsTestCase; import org.ensembl.healthcheck.testcase.PerlScriptConfig; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.eg_gui.CopyAndPastePopupBuilder; /** * <p> * The main window of the healthcheck GUI. * </p> * * @author michael * */ public class GuiTestRunnerFrame extends JFrame implements ActionListener { /** The logger to use for this class */ protected static Logger logger = Logger.getLogger("HealthCheckLogger"); /** * Preferred size of the window. * */ protected int windowWidth = Constants.INITIAL_APPLICATION_WINDOW_WIDTH; protected int windowHeight = Constants.INITIAL_APPLICATION_WINDOW_HEIGHT; /** * Name of the server that will be set as default, if there is a * configuration for this. */ String defaultSecondaryServerName = "mysql.ebi.ac.uk"; /** * Title of the Window * */ String windowTitle = "Healthchecks"; /** * Directories in which configuration files for database servers will be * searched for. * */ final String[] dirsWithDbServerConfigs = new String[] { // ~ does not work in java to reference the home directory: // "~/.ensj", System.getProperty("user.home") + "/.ensj" }; //protected DatabaseTabbedPane databaseTabbedPane; protected DatabaseTabbedPaneWithSearchBox databaseTabbedPaneWithSearchBox; protected JTextField MysqlConnectionCmd; protected final JList listOfTestsToBeRun; protected final JButton rmSelectedTests; protected final JButton runAllTests; protected final JButton runSelectedTests; protected final JTree tree; protected final JComboBox dbServerSelector; protected final JComboBox secondaryDbServerSelector; protected List<ConfigureHost> dbDetails; protected TestProgressDialog testProgressDialog; // The tabs on the main window. final protected JTabbedPane tab; final protected JPanel tabSetup; protected int tabSetupTabIndex; protected String tabSetupName = "Setup"; protected JPanel tabResults; protected int tabResultsTabIndex; protected String tabResultsName = "Results"; protected JPanel tabResultsLegacy; protected int tabResultsLegacyTabIndex; protected AdminTab tabAdmin; protected int tabAdminTabIndex; // Holds a reference to the gui reporter. It is a component of the // JPanel tabResults. protected GuiReporterTab currentGuiReporter; protected Thread currentGuiTestRunnerThread; protected GuiLogHandler guiLogHandler; protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { // If a healthcheck session is currently running, terminate this. // Perl based healthchecks don't automatically terminate when the // window closes, so this is done here explicitly. if (currentGuiTestRunnerThread != null) { currentGuiTestRunnerThread.interrupt(); } } super.processWindowEvent(e); } /** * <p> * Sets the primary and secondary host details in DBUtils. * </p> * * @param primaryHostDetails * @param secondaryHostDetails */ protected void setPrimaryAndSecondaryAndSystemPropertiesHost( ConfigureHost primaryHostDetails, ConfigureHost secondaryHostDetails ) { ConfigurationUserParameters combinedHostConfig = createConfigurationObject(primaryHostDetails, secondaryHostDetails); // And finally set the new configuration file in which the // secondary host has been configured. DBUtils.setHostConfiguration((ConfigureHost) combinedHostConfig); SystemPropertySetter systemPropertySetter = new SystemPropertySetter(combinedHostConfig); systemPropertySetter.setPropertiesForHealthchecks(); } protected ConfigurationUserParameters createConfigurationObject( ConfigureHost primaryHostDetails, ConfigureHost secondaryHostDetails ) { Properties secondaryHostProperties = new Properties(); if (secondaryHostDetails!=null) { secondaryHostProperties.setProperty("secondary.host", secondaryHostDetails.getHost()); secondaryHostProperties.setProperty("secondary.port", secondaryHostDetails.getPort()); secondaryHostProperties.setProperty("secondary.user", secondaryHostDetails.getUser()); secondaryHostProperties.setProperty("secondary.password", secondaryHostDetails.getPassword()); secondaryHostProperties.setProperty("secondary.driver", secondaryHostDetails.getDriver()); } ConfigureHost secondaryHostConfiguration = (ConfigureHost) ConfigurationByProperties.newInstance( ConfigureHost.class, secondaryHostProperties ); List<File> propertyFileNames = new ArrayList<File>(); propertyFileNames.add(new File(ConfigurableTestRunner.getDefaultPropertiesFile())); ConfigurationUserParameters ConfigurationByPropertyFiles = new ConfigurationFactory<ConfigurationUserParameters>( ConfigurationUserParameters.class, propertyFileNames ).getConfiguration(ConfigurationType.Properties); ConfigurationFactory<ConfigurationUserParameters> confFact = new ConfigurationFactory<ConfigurationUserParameters>( ConfigurationUserParameters.class, primaryHostDetails, secondaryHostConfiguration, ConfigurationByPropertyFiles ); ConfigurationUserParameters combinedHostConfig = confFact.getConfiguration(ConfigurationType.Cascading); return combinedHostConfig; } protected String createDbCmdLine() { int selectedIndex = dbServerSelector.getSelectedIndex(); // if nothing has been selected if (selectedIndex==-1) { return "No database has been selected."; } ConfigureHost selectedDbServerConf = dbDetails.get(selectedIndex); String passwordParam; if (selectedDbServerConf.getPassword().isEmpty()) { passwordParam = ""; } else { passwordParam = " --password=" + selectedDbServerConf.getPassword(); } return "mysql" + " --host " + selectedDbServerConf.getHost() + " --port " + selectedDbServerConf.getPort() + " --user " + selectedDbServerConf.getUser() + passwordParam ; } protected void updateDbCmdLine() { if (MysqlConnectionCmd ==null) { return; } MysqlConnectionCmd.setText(createDbCmdLine()); MysqlConnectionCmd.selectAll(); } protected void updateDbCmdLine(String dbName) { if (MysqlConnectionCmd ==null) { return; } String cmd = createDbCmdLine() + " " + dbName; MysqlConnectionCmd.setText(cmd); MysqlConnectionCmd.selectAll(); } @Override public void actionPerformed(ActionEvent arg0) { String cmd = arg0.getActionCommand(); if (cmd.equals(Constants.selectedDatabaseChanged)) { DatabaseRadioButton selectedDbRadioButton = (DatabaseRadioButton) arg0.getSource(); String currentlySelectsDBName = selectedDbRadioButton.getText(); updateDbCmdLine(currentlySelectsDBName); } // Not implemented yet if (cmd.equals(Constants.Add_to_tests_to_be_run)) { } if (cmd.equals(Constants.REMOVE_SELECTED_TESTS)) { GuiTestRunnerFrameActionPerformer.removeSelectedTests(listOfTestsToBeRun); } if (cmd.equals(Constants.DB_SERVER_CHANGED)) { GuiTestRunnerFrameActionPerformer.setupDatabasePane( databaseTabbedPaneWithSearchBox.getDtp(), dbDetails.get(dbServerSelector.getSelectedIndex()) ); updateDbCmdLine(); } if (cmd.equals(Constants.RUN_ALL_TESTS) || cmd.equals(Constants.RUN_SELECTED_TESTS)) { // Check, if basic conditions have been met so that tests can be // run. if ( (currentGuiTestRunnerThread != null) && (currentGuiTestRunnerThread.isAlive()) ) { JOptionPane.showMessageDialog( this, "A session of healthchecks is currently running already. " + "Please wait for it to terminate before starting another.", "Error", JOptionPane.ERROR_MESSAGE ); return; } if ( cmd.equals(Constants.RUN_SELECTED_TESTS) && listOfTestsToBeRun.getSelectedValues().length==0 ) { JOptionPane.showMessageDialog( this, "You have not selected any tests!", "Error", JOptionPane.ERROR_MESSAGE ); return; } if ( cmd.equals(Constants.RUN_ALL_TESTS) && listOfTestsToBeRun.getModel().getSize()==0 ) { JOptionPane.showMessageDialog( this, "No tests! Please drag tests from the tree in the left into the area above.", "Error", JOptionPane.ERROR_MESSAGE ); return; } DatabaseRegistryEntry[] selectedDatabases = databaseTabbedPaneWithSearchBox.getDtp().getSelectedDatabases(); if (selectedDatabases.length == 0) { JOptionPane.showMessageDialog( this, "No databases selected!", "Error", JOptionPane.ERROR_MESSAGE ); } else { ReportManager.initialise(); // If currentGuiReporter has been initialised once, it has // also been added to the tabResults. It has to be removed // first, before a new one is created and put in its place. if (currentGuiReporter!=null) { tabResults.remove(currentGuiReporter); } currentGuiReporter = new GuiReporterTab(); guiLogHandler = new GuiLogHandler(); guiLogHandler.setReporter(currentGuiReporter); // Set the formatter for EnsTestcases to what the user // configured them to look like. // Check, if a formatter was configured. If so, then use // this formatter, otherwise create a new one. Handler[] configuredHandler = Logger.getLogger( EnsTestCase.class.getCanonicalName() ).getHandlers(); Formatter configuredFormatter; if (configuredHandler.length == 0) { configuredFormatter = new SimpleFormatter(); } else { configuredFormatter = configuredHandler[0].getFormatter(); } // Set the formatter. guiLogHandler.setFormatter(configuredFormatter); testProgressDialog = new TestProgressDialog("", 0, 100); tabResults.setLayout(new BorderLayout()); tabResults.add(testProgressDialog, BorderLayout.SOUTH); tabResults.add(currentGuiReporter, BorderLayout.CENTER); tab.setEnabledAt(tabResultsTabIndex, true); tab.setEnabledAt(tabResultsLegacyTabIndex, true); tab.setSelectedIndex(tabResultsTabIndex); tabResultsLegacy.setLayout(new BorderLayout()); ReportManager.setReporter(currentGuiReporter); PerlScriptConfig psc = new PerlScriptConfig( tabAdmin.getPerl5Binary(), tabAdmin.getPerlOptions() ); setPrimaryAndSecondaryAndSystemPropertiesHost( dbDetails.get(dbServerSelector.getSelectedIndex()), dbDetails.get(secondaryDbServerSelector.getSelectedIndex()) ); if (cmd.equals(Constants.RUN_SELECTED_TESTS)) { currentGuiTestRunnerThread = GuiTestRunnerFrameActionPerformer.runSelectedTests( listOfTestsToBeRun, selectedDatabases, testProgressDialog, tabResultsLegacy, tabAdmin.getPerl5Lib(), psc, guiLogHandler ); } if (cmd.equals(Constants.RUN_ALL_TESTS)) { currentGuiTestRunnerThread = GuiTestRunnerFrameActionPerformer.runAllTests( listOfTestsToBeRun, selectedDatabases, testProgressDialog, tabResultsLegacy, tabAdmin.getPerl5Lib(), psc, guiLogHandler ); } } } } public GuiTestRunnerFrame( List<GroupOfTests> testGroupList, TestInstantiatorDynamic testInstantiator ) { final ActionListener defaultAL = this; final JPopupMenu popupMenuList = GuiTestRunnerFrameComponentBuilder .createListOfTestsToBeExecutedPopupMenu(defaultAL); // Functionality of the popup menu is not implemented yet, // so no popup menu for the tree //final JPopupMenu popupMenuTree = GuiComponentBuilder // .createTreeOfTestGroupsPopupMenu(defaultAL); final JPopupMenu popupMenuTree = null; listOfTestsToBeRun = GuiTestRunnerFrameComponentBuilder.createListOfTestsToBeRunArea( testInstantiator, popupMenuList, defaultAL ); tree = GuiTestRunnerFrameComponentBuilder.createTreeOfTestGroups( testGroupList, popupMenuTree ); rmSelectedTests = GuiTestRunnerFrameComponentBuilder.createRemoveSelectedTestsButton(defaultAL); runAllTests = GuiTestRunnerFrameComponentBuilder.createRunAllTestsButton(defaultAL); runSelectedTests = GuiTestRunnerFrameComponentBuilder.createRunSelectedTestsButton(defaultAL); tabSetup = new JPanel(); dbDetails = GuiTestRunnerFrameUtils.createDbDetailsConfigurations( dirsWithDbServerConfigs ); // Set to false, because checking availability costs too much startup // time when there are many servers configured and opens too many // connections. boolean checkAvailabilityOfServers = false; if (checkAvailabilityOfServers) { dbDetails = GuiTestRunnerFrameUtils.grepForAvailableServers(dbDetails); } dbServerSelector = GuiTestRunnerFrameComponentBuilder.createDbServerSelector(dbDetails); dbServerSelector.setActionCommand(Constants.DB_SERVER_CHANGED); dbServerSelector.addActionListener(this); secondaryDbServerSelector = GuiTestRunnerFrameComponentBuilder.createDbServerSelector(dbDetails); secondaryDbServerSelector.setActionCommand(Constants.SECONDARY_DB_SERVER_CHANGED); secondaryDbServerSelector.addActionListener(this); DBUtils.initialise(false); // databaseTabbedPane must be set up before running // dbServerSelector.setSelectedIndex(defaultSelectedServerIndex); // because the above statement will trigger an action that will // reconfigure what is in the databaseTabbedPane. If databaseTabbedPane // is null then, because it has not been initialised, it will result // in an error which is hard to find. List<String> regexps = new ArrayList<String>(); regexps.add(".*"); DatabaseRegistry databaseRegistry = new DatabaseRegistry(regexps, null, null, false); if (databaseRegistry.getEntryCount() == 0) { logger.warning("Warning: no databases found!"); } DatabaseTabbedPane databaseTabbedPane = new DatabaseTabbedPane( databaseRegistry, this ); databaseTabbedPaneWithSearchBox = new DatabaseTabbedPaneWithSearchBox(databaseTabbedPane); // See, if defaultSecondaryServerName can be found in dbDetails. If so, // select this as the default secondary server. int numServers = dbDetails.size(); int defaultSelectedServerIndex = 0; for (int index=0; index<numServers; index++) { String serverName = dbDetails.get(index).getHost(); if (serverName.contains(defaultSecondaryServerName)) { defaultSelectedServerIndex = index; } } ConfigureHost primaryHostDetails = null; ConfigureHost secondaryHostDetails = null; if (dbServerSelector.getItemCount()>0) { dbServerSelector.setSelectedIndex(defaultSelectedServerIndex); primaryHostDetails = dbDetails.get(defaultSelectedServerIndex); actionPerformed(new ActionEvent(this, 0, Constants.DB_SERVER_CHANGED)); } if (secondaryDbServerSelector.getItemCount()>0) { secondaryDbServerSelector.setSelectedIndex(defaultSelectedServerIndex); secondaryHostDetails = dbDetails.get(defaultSelectedServerIndex); actionPerformed(new ActionEvent(this, 1, Constants.DB_SERVER_CHANGED)); } setPrimaryAndSecondaryAndSystemPropertiesHost(primaryHostDetails, secondaryHostDetails); this.setTitle(windowTitle); tab = new JTabbedPane(); init(); } /** * <p> * Plugs the individual components of the GUI to the JFrame. This is where * the components are arranged. * </p> * * @param databaseTabbedPane * @param tree * @param testsToBeRun * @param buttonPanel * */ protected void addComponentsToLayout( DatabaseTabbedPaneWithSearchBox databaseTabbedPaneWithSearchBox, JTree tree, JList testsToBeRun, JPanel buttonPanel, JComboBox dbServerSelector, JComboBox secondaryDbServerSelector, JTextField MysqlConnectionCmd ) { JScrollPane treePane = new JScrollPane(tree); JPanel testsPane = new JPanel(new BorderLayout()); Box buttonBox = Box.createHorizontalBox(); buttonBox.add(rmSelectedTests); buttonBox.add(Box.createHorizontalStrut(Constants.DEFAULT_HORIZONTAL_COMPONENT_SPACING)); buttonBox.add(runSelectedTests); buttonBox.add(Box.createHorizontalStrut(Constants.DEFAULT_HORIZONTAL_COMPONENT_SPACING)); buttonBox.add(runAllTests); testsPane.add(buttonBox, BorderLayout.SOUTH); testsPane.add(new JScrollPane(testsToBeRun), BorderLayout.CENTER); JSplitPane testSelectionWidgets = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, treePane, testsPane ); tabSetup.setLayout(new BorderLayout()); MysqlConnectionCmd.setBorder( BorderFactory.createTitledBorder( GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder, "Use this command to connect to the selected database") ); tabSetup.add(MysqlConnectionCmd, BorderLayout.SOUTH); tabSetup.add( new JSplitPane( JSplitPane.VERTICAL_SPLIT, databaseTabbedPaneWithSearchBox, testSelectionWidgets ), BorderLayout.CENTER ); Box hbox = Box.createHorizontalBox(); hbox.add(dbServerSelector); hbox.add(secondaryDbServerSelector); tabSetup.add(hbox, BorderLayout.NORTH); tabAdmin = new AdminTab(); tabResults = new JPanel(); tabResultsLegacy = new JPanel(); tab.add(tabSetupName, tabSetup); tabSetupTabIndex = 0; tab.add(tabResultsName, tabResults); tabResultsTabIndex = 1; tab.add("Legacy", tabResultsLegacy); tabResultsLegacyTabIndex = 2; tab.add("Admin", tabAdmin); tabAdminTabIndex = 3; tab.setEnabledAt(tabResultsTabIndex, false); tab.setEnabledAt(tabResultsLegacyTabIndex, false); this.getContentPane().add(tab); // Create space around components so they don't look too crammed. Border defaultEmptyBorder = GuiTestRunnerFrameComponentBuilder.defaultEmptyBorder; Border noBorder = BorderFactory.createEmptyBorder(0, 0, 0, 0); hbox .setBorder(BorderFactory.createTitledBorder(defaultEmptyBorder, "1. Select database servers:")); dbServerSelector .setBorder(BorderFactory.createTitledBorder(noBorder, "Primary (where your database is):")); secondaryDbServerSelector .setBorder(BorderFactory.createTitledBorder(noBorder, "Secondary (Some tests require a secondary db server):")); databaseTabbedPaneWithSearchBox .setBorder(BorderFactory.createTitledBorder(defaultEmptyBorder, "2. Select a database:")); testSelectionWidgets .setBorder(BorderFactory.createTitledBorder(defaultEmptyBorder, "3. Select tests to be run:")); treePane .setBorder(BorderFactory.createTitledBorder("Drag tests to the panel on the right")); testsPane .setBorder(BorderFactory.createTitledBorder("Select tests and run from context menu")); // The default dimensions look appalling. This looks slightly less // appalling. databaseTabbedPaneWithSearchBox.setMinimumSize(new Dimension(0, windowHeight/4)); testsPane .setMinimumSize(new Dimension(0, windowHeight/4)); treePane .setMinimumSize(new Dimension(windowWidth/3, 0)); } /** * * <p> * Creates the GUI components and arranges them on the JFrame (this). * </p> * * @param testGroupList * @param testInstantiator * */ protected void init() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 1)); buttonPanel.add(rmSelectedTests); buttonPanel.add(runAllTests); MysqlConnectionCmd = new JTextField(); new CopyAndPastePopupBuilder().addPopupMenu(MysqlConnectionCmd); addComponentsToLayout( databaseTabbedPaneWithSearchBox, tree, listOfTestsToBeRun, buttonPanel, dbServerSelector, secondaryDbServerSelector, MysqlConnectionCmd ); updateDbCmdLine(); this.setPreferredSize(new Dimension(windowWidth, windowHeight)); this.pack(); // The following stuff that positions the frame must come after the // this.pack() statement above otherwise it won't work as expected. // Center on screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle frame = getBounds(); setLocation( (screen.width - frame.width) / 2, (screen.height - frame.height) / 2 ); } }
package dr.app.beagle.multidimensionalscaling; /** * MultiDimensionalScalingCoreImpl * * @author Andrew Rambaut * @author Marc Suchard * @version $Id$ * * $HeadURL$ * * $LastChangedBy$ * $LastChangedDate$ * $LastChangedRevision$ */ public class MultiDimensionalScalingCoreImpl implements MultiDimensionalScalingCore { private static final boolean USE_CACHING = true; @Override public void initialize(int embeddingDimension, int locationCount) { this.embeddingDimension = embeddingDimension; this.locationCount = locationCount; this.observationCount = (locationCount * (locationCount - 1)) / 2; observations = new double[locationCount][locationCount]; squaredResiduals = new double[locationCount][locationCount]; storedSquaredResiduals = new double[locationCount][locationCount]; residualsKnown = false; sumOfSquaredResidualsKnown = false; locationUpdated = new boolean[locationCount]; for (int i = 0; i < locationUpdated.length; i++) { locationUpdated[i] = true; } locations = new double[locationCount][embeddingDimension]; storedLocations = new double[locationCount][embeddingDimension]; } @Override public void setPairwiseData(double[] observations) { if (observations.length != (locationCount * locationCount)) { throw new RuntimeException("Observation data is not the correct dimension"); } int k = 0; for (int i = 0; i < locationCount; i++) { System.arraycopy(observations, k, this.observations[i], 0, locationCount); k += locationCount; } } @Override public void setParameters(double[] parameters) { precision = parameters[0]; } @Override public void updateLocation(int locationIndex, double[] location) { if (USE_CACHING && locationUpdateCount != -1) { if (locationUpdateCount > 1) { throw new RuntimeException("Cannot change more than one location per step with caching on"); } locationUpdateCount += 1; } if (location.length != embeddingDimension) { throw new RuntimeException("Location is not the correct dimension"); } System.arraycopy(location, 0, locations[locationIndex], 0, embeddingDimension); locationUpdated[locationIndex] = true; sumOfSquaredResidualsKnown = false; } @Override public double calculateLogLikelihood() { if (!sumOfSquaredResidualsKnown) { if (USE_CACHING) { if (!residualsKnown) { computeSumOfSquaredResiduals(); } else { updateSumOfSquaredResiduals(); } } else { computeSumOfSquaredResiduals(); } sumOfSquaredResidualsKnown = true; } double logLikelihood = (0.5 * Math.log(precision) * observationCount) - (0.5 * precision * sumOfSquaredResiduals); if (isLeftTruncated) { throw new UnsupportedOperationException("Truncations not implemented"); // if (!truncationsKnown) { // calculateTruncations(precision); // truncationSum = calculateTruncationSum(); // logLikelihood -= truncationSum; } for (int i = 0; i < locationUpdated.length; i++) { locationUpdated[i] = false; } return logLikelihood; } @Override public void storeState() { storedSumOfSquaredResiduals = sumOfSquaredResiduals; for (int i = 0; i < locationCount; i++) { System.arraycopy(squaredResiduals[i], 0 , storedSquaredResiduals[i], 0, locationCount); System.arraycopy(locations[i], 0 , storedLocations[i], 0, embeddingDimension); } storedPrecision = precision; locationUpdateCount = 0; } @Override public void restoreState() { sumOfSquaredResiduals = storedSumOfSquaredResiduals; sumOfSquaredResidualsKnown = true; double[][] tmp = storedSquaredResiduals; storedSquaredResiduals = squaredResiduals; squaredResiduals = tmp; tmp = storedLocations; storedLocations = locations; locations = tmp; precision = storedPrecision; residualsKnown = true; } @Override public void makeDirty() { sumOfSquaredResidualsKnown = false; residualsKnown = false; } protected void computeSumOfSquaredResiduals() { sumOfSquaredResiduals = 0.0; for (int i = 0; i < locationCount; i++) { for (int j = i+1; j < locationCount; j++) { double distance = calculateDistance(locations[i], locations[j]); double residual = distance - observations[i][j]; double squaredResidual = residual * residual; squaredResiduals[i][j] = squaredResidual; squaredResiduals[j][i] = squaredResidual; sumOfSquaredResiduals += squaredResidual; } } residualsKnown = true; sumOfSquaredResidualsKnown = true; } protected void updateSumOfSquaredResiduals() { double delta = 0.0; double[] oldSquaredResidualRow = new double[locationCount]; for (int i = 0; i < locationCount; i++) { if (locationUpdated[i]) { System.arraycopy(squaredResiduals[i], 0, oldSquaredResidualRow, 0, locationCount); // if location i is updated, calculate the residuals to all js // also sum the change in sum residual for (int j = 0; j < locationCount; j++) { if (i != j) { double distance = calculateDistance(locations[i], locations[j]); double residual = distance - observations[i][j]; double squaredResidual = residual * residual; delta += squaredResidual - oldSquaredResidualRow[j]; squaredResiduals[i][j] = squaredResidual; squaredResiduals[j][i] = squaredResidual; } } } } sumOfSquaredResiduals += delta; } protected double calculateDistance(double[] X, double[] Y) { double sum = 0.0; for (int i = 0; i < embeddingDimension; i++) { double difference = X[i] - Y[i]; sum += difference * difference; } return Math.sqrt(sum); } // protected void calculateTruncations(double precision) { // double sd = 1.0 / Math.sqrt(precision); // for (int i = 0; i < distanceCount; i++) { // if (distanceUpdated[i]) { // truncations[i] = NormalDistribution.cdf(distances[i], 0.0, sd, true); // truncationsKnown = true; // protected double calculateTruncationSum() { // double sum = 0.0; // for (int i = 0; i < observationCount; i++) { // int dist = getDistanceIndexForObservation(i); // if (dist != -1) { // sum += truncations[dist]; // } else { // sum += Math.log(0.5); // return sum; private int embeddingDimension; private boolean isLeftTruncated = false; private int locationCount; private int observationCount; private double precision; private double storedPrecision; // Prevents more than one location being updated per step. Is initialized // to zero in store(). private int locationUpdateCount = -1; private double[][] observations; private double[][] locations; private double[][] storedLocations; private boolean[] locationUpdated; private boolean residualsKnown = false; private boolean sumOfSquaredResidualsKnown = false; private double[][] squaredResiduals; private double[][] storedSquaredResiduals; private double sumOfSquaredResiduals; private double storedSumOfSquaredResiduals; private boolean truncationsKnown = false; private double truncationSum; private double storedTruncationSum; private double[] truncations; private double[] storedTruncations; }
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.EquivClassComparator; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.validators.datatype.StateMessageDatatype; import org.apache.xerces.validators.datatype.IDREFDatatypeValidator; import org.apache.xerces.validators.datatype.IDDatatypeValidator; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k private StateMessageDatatype fStoreIDRef = new StateMessageDatatype() { private Hashtable fIdDefs; public Object getDatatypeObject(){ return(Object) fIdDefs; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_STORE; } }; private StateMessageDatatype fResetIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ Hashtable t = null; return(Object) t; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_CLEAR; } }; private StateMessageDatatype fValidateIDRef = new StateMessageDatatype() { public Object getDatatypeObject(){ Hashtable t = null; return(Object) t; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_VALIDATE; } }; // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // debugging // private static boolean DEBUG = false; // other // attribute validators private AttributeValidator fAttValidatorCDATA = null; private AttributeValidator fAttValidatorENTITY = new AttValidatorENTITY(); private AttributeValidator fAttValidatorENTITIES = new AttValidatorENTITIES(); private AttributeValidator fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); private AttributeValidator fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fSchemaValidation = true; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; private boolean fLoadDTDGrammar = true; // declarations private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8]; private int[] fValidationFlagStack = new int[8]; private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private static final int sizeQNameParts = 8; private QName[] fElementQNamePartsStack = new QName[sizeQNameParts]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = -1; private int fEmptyURI = - 1; private int fXsiPrefix = - 1; private int fXsiURI = -2; private int fXsiTypeAttValue = -1; private DatatypeValidator fXsiTypeValidator = null; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = -1; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; private boolean fNeedValidationOff = false; // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; //Datatype Registry private DatatypeValidatorFactoryImpl fDataTypeReg = DatatypeValidatorFactoryImpl.getDatatypeRegistry(); private DatatypeValidator fValID = this.fDataTypeReg.getDatatypeValidator("ID" ); private DatatypeValidator fValIDRef = this.fDataTypeReg.getDatatypeValidator("IDREF" ); private DatatypeValidator fValIDRefs = this.fDataTypeReg.getDatatypeValidator("IDREFS" ); // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); for (int i = 0; i < sizeQNameParts; i++) { fElementQNamePartsStack[i] = new QName(); } init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether Schema support is on/off. */ public void setSchemaValidationEnabled(boolean flag) { fSchemaValidation = flag; } /** Returns true if Schema support is on. */ public boolean getSchemaValidationEnabled() { return fSchemaValidation; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets fLoadDTDGrammar when validation is off **/ public void setLoadDTDGrammar(boolean loadDG){ if (fValidating) { fLoadDTDGrammar = true; } else{ fLoadDTDGrammar = loadDG; } } /** Returns fLoadDTDGrammar **/ public boolean getLoadDTDGrammar() { return fLoadDTDGrammar; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** Process characters. */ /** Process characters. */ /** Process whitespace. */ /** Process whitespace. */ /** Scans element type. */ /** Scans expected element type. */ /** Scans attribute name. */ /** Call start document. */ /** Call end document. */ /** Call XML declaration. */ /** Call text declaration. */ /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } if (fGrammar != null && fGrammarIsDTDGrammar) { fAttrListHandle = addDTDDefaultAttributes(element, fAttrList, fAttrListHandle, fValidating, fStandaloneReader != -1); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { fAttrList.endAttrList(); } fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fAttrListHandle = -1; //before we increment the element depth, add this element's QName to its enclosing element 's children list fElementDepth++; //if (fElementDepth >= 0) { if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length < fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } // One more level of depth //fElementDepth++; ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement); fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; if (fNeedValidationOff) { fValidating = false; fNeedValidationOff = false; } if (fValidating && fGrammarIsSchemaGrammar) { pushContentLeafStack(); } fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void pushContentLeafStack() throws Exception { int contentType = getContentSpecType(fCurrentElementIndex); if ( contentType == XMLElementDecl.TYPE_CHILDREN) { XMLContentModel cm = getElementContentModel(fCurrentElementIndex); ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector(); if (cm != null) { fContentLeafStack[fElementDepth] = cv; } } } private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementQNamePartsStack.length ) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; QName[] newStackOfQueue = new QName[newElementDepth * 2]; System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth ); fElementQNamePartsStack = newStackOfQueue; QName qname = fElementQNamePartsStack[newElementDepth]; if (qname == null) { for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) { fElementQNamePartsStack[i] = new QName(); } } newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth); fValidationFlagStack = newStack; ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2]; System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth); fContentLeafStack = newStackV; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType) }, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) { reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), "EMPTY"); } else reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating ) { this.fValIDRefs.validate( null, this.fValidateIDRef ); } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; if (fNamespacesEnabled) { //If Namespace enable then localName != rawName fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname; } fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname; fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri; fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false; fCurrentScope = fScopeStack[fElementDepth]; //if ( DEBUG_SCHEMA_VALIDATION ) { /** Call start CDATA section. */ /** Call end CDATA section. */ /** Call characters. */ /** Call processing instruction. */ /** Call comment. */ /** Start a new namespace declaration scope. */ /** End a namespace declaration scope. */ /** Sets the root element. */ /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getElementContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // initialization /** Reset pool. */ private void poolReset() { try{ this.fValIDRef.validate(null, this.fResetIDRef ); this.fValIDRefs.validate(null, this.fResetIDRef ); } catch( InvalidDatatypeValueException ex ){ System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" ); } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = -1; fEmptyURI = - 1; fXsiPrefix = - 1; fXsiTypeValidator = null; fGrammar = null; fGrammarNameSpaceIndex = -1; fGrammarResolver = null; fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); } // init() // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { //int adChunk = attlistIndex >> CHUNK_SHIFT; //int adIndex = attlistIndex & CHUNK_MASK; fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** addDTDDefaultAttributes. */ /** Queries the content model for the specified element index. */ /** Returns the validatator for an attribute type. */ /** Returns an attribute definition for an element type. */ /** Returns an attribute definition for an element type. */ /** Root element specified. */ /** Switchs to correct validating symbol tables when Schema changes.*/ /** Binds namespaces to the element and attributes. */ /** Warning. */ /** Error. */ /** Fatal error. */ /** Returns a string of the location. */ /** Validates element and attributes. */ /** Character data in content. */ /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // debugging //System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType); // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED || contentType == XMLElementDecl.TYPE_CHILDREN) { // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getElementContentModel(elementIndex); int result = cmElem.validateContent(children, childOffset, childCount); if (result != -1 && fGrammarIsSchemaGrammar) { // REVISIT: not optimized for performance, EquivClassComparator comparator = new EquivClassComparator(fGrammarResolver, fStringPool); cmElem.setEquivClassComparator(comparator); result = cmElem.validateContentSpecial(children, childOffset, childCount); } return result; } catch(CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; if (childCount > 0) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "Can not have element children within a simple type content" }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { fGrammar.getElementDecl(elementIndex, fTempElementDecl); DatatypeValidator dv = fTempElementDecl.datatypeValidator; // If there is xsi:type validator, substitute it. if ( fXsiTypeValidator != null ) { dv = fXsiTypeValidator; fXsiTypeValidator = null; } if (dv == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { dv.validate(fDatatypeBuffer.toString(), null); } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage() }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } // Classes /** * AttValidatorCDATA. */ final class AttValidatorCDATA implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... return attValueHandle; } } // class AttValidatorCDATA /** * AttValidatorENTITY. */ final class AttValidatorENTITY implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENTITY - check that the value is an unparsed entity name (V_TAGa) if (!fEntityHandler.isUnparsedEntity(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITY /** * AttValidatorENTITIES. */ final class AttValidatorENTITIES implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String entityName = tokenizer.nextToken(); // ENTITIES - check that each value is an unparsed entity name (V_TAGa) if (fValidating && !fEntityHandler.isUnparsedEntity(fStringPool.addSymbol(entityName))) { ok = false; } sb.append(entityName); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITIES /** * AttValidatorNMTOKEN. */ final class AttValidatorNMTOKEN implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validNmtoken(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKEN /** * AttValidatorNMTOKENS. */ final class AttValidatorNMTOKENS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String nmtoken = tokenizer.nextToken(); if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) { ok = false; } sb.append(nmtoken); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKENS /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION } // class XMLValidator
package at.archistar.crypto.math; import de.flexiprovider.common.math.codingtheory.GF2mField; import de.flexiprovider.common.math.linearalgebra.GF2mMatrix; /** * * GF2mMatrix does not support rightMultiply, add a (very) simple implementation * of this operation. * * @author Andreas Happe <andreashappe@snikt.net> */ public class CustomMatrix extends GF2mMatrix { private static final GF2mField gf256 = new GF2mField(8, 0x11d); // Galois-Field (x^8 + x^4 + x^3 + x + 1 = 0) / 285 public CustomMatrix(int[][] data) { super(gf256, data); } public CustomMatrix(byte[] encoded) { super(gf256, encoded); } public int[] rightMultiply(int vec[]) { assert (vec.length == matrix.length); assert (vec.length == matrix[0].length); int[] result = new int[vec.length]; for (int i = 0; i < vec.length; i++) { int tmp = 0; for (int j = 0; j < vec.length; j++) { tmp = GF256.add(tmp, GF256.mult(matrix[i][j], vec[j])); } result[i] = tmp; } return result; } public int[] getRow(int i) { return matrix[i]; } public void output() { System.err.println("matrix:"); for (int[] tmp : matrix) { for (int i : tmp) { System.err.print(" " + i); } System.err.println(""); } } }
package VASSAL.configure; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.Builder; import VASSAL.build.Configurable; import VASSAL.build.GameModule; import VASSAL.build.IllegalBuildException; import VASSAL.build.module.Chatter; import VASSAL.build.module.KeyNamer; import VASSAL.build.module.Plugin; import VASSAL.build.module.PrototypeDefinition; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.documentation.HelpWindow; import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone; import VASSAL.build.module.properties.GlobalProperties; import VASSAL.build.module.properties.GlobalProperty; import VASSAL.build.module.properties.GlobalTranslatableMessage; import VASSAL.build.module.properties.ZoneProperty; import VASSAL.build.widget.CardSlot; import VASSAL.build.widget.PieceSlot; import VASSAL.counters.Decorator; import VASSAL.counters.EditablePiece; import VASSAL.counters.GamePiece; import VASSAL.counters.MassPieceLoader; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslateAction; import VASSAL.launch.EditorWindow; import VASSAL.preferences.Prefs; import VASSAL.search.SearchTarget; import VASSAL.tools.ErrorDialog; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.ProblemDialog; import VASSAL.tools.ReflectionUtils; import VASSAL.tools.menu.MenuManager; import VASSAL.tools.swing.SwingUtils; import java.awt.Component; import java.awt.Font; import java.awt.Frame; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.IntStream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DropMode; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang3.StringUtils; /** * The beating heart of the Editor, this class handles the Configuration Tree * that appears in the Configuration window when editing a VASSAL module. Each * node in the tree structure is a {@link VASSAL.build.Configurable} object, * whose child nodes are obtained via {@link VASSAL.build.Configurable#getConfigureComponents}. * * When we're running as the Extension Editor, this is subclassed by {@link ExtensionTree}, which * overrides some methods to handle extension-specific differences. */ public class ConfigureTree extends JTree implements PropertyChangeListener, MouseListener, MouseMotionListener, TreeSelectionListener, TreeExpansionListener { private static final long serialVersionUID = 1L; protected Map<Configurable, DefaultMutableTreeNode> nodes = new HashMap<>(); protected DefaultMutableTreeNode copyData; protected DefaultMutableTreeNode cutData; protected HelpWindow helpWindow; protected EditorWindow editorWindow; protected Configurable selected; protected int selectedRow; protected String searchCmd; protected String moveCmd; protected String deleteCmd; protected String pasteCmd; protected String copyCmd; protected String cutCmd; protected String helpCmd; protected String propertiesCmd; protected String translateCmd; protected KeyStroke cutKey; protected KeyStroke copyKey; protected KeyStroke pasteKey; protected KeyStroke deleteKey; protected KeyStroke moveKey; protected KeyStroke searchKey; protected KeyStroke helpKey; protected KeyStroke propertiesKey; protected KeyStroke translateKey; protected Action cutAction; protected Action copyAction; protected Action pasteAction; protected Action deleteAction; protected Action moveAction; protected Action searchAction; protected Action propertiesAction; protected Action translateAction; protected Action helpAction; protected JDialog searchDialog; protected JTextField searchField; protected JCheckBox searchAdvanced; private final SearchParameters searchParameters; protected static Chatter chatter; public static final Font POPUP_MENU_FONT = new Font(Font.DIALOG, Font.PLAIN, 11); protected static final List<AdditionalComponent> additionalComponents = new ArrayList<>(); /** * Creates new ConfigureTree */ public ConfigureTree(Configurable root, HelpWindow helpWindow) { this(root, helpWindow, null); } public ConfigureTree(Configurable root, HelpWindow helpWindow, EditorWindow editorWindow) { toggleClickCount = 3; this.helpWindow = helpWindow; this.editorWindow = editorWindow; setShowsRootHandles(true); setModel(new DefaultTreeModel(buildTreeNode(root))); setCellRenderer(buildRenderer()); addMouseListener(this); addMouseMotionListener(this); addTreeSelectionListener(this); addTreeExpansionListener(this); searchCmd = Resources.getString("Editor.search"); //$NON-NLS-1$ moveCmd = Resources.getString("Editor.move"); //$NON-NLS-1$ deleteCmd = Resources.getString("Editor.delete"); //$NON-NLS-1$ pasteCmd = Resources.getString("Editor.paste"); //$NON-NLS-1$ copyCmd = Resources.getString("Editor.copy"); //$NON-NLS-1$ cutCmd = Resources.getString("Editor.cut"); //$NON-NLS-1$ propertiesCmd = Resources.getString("Editor.properties"); //$NON-NLS-1$ translateCmd = Resources.getString("Editor.ModuleEditor.translate"); //$NON-NLS-1$ helpCmd = Resources.getString("Editor.ModuleEditor.component_help"); //$NON-NLS-1$ final int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx(); cutKey = KeyStroke.getKeyStroke(KeyEvent.VK_X, mask); copyKey = KeyStroke.getKeyStroke(KeyEvent.VK_C, mask); pasteKey = KeyStroke.getKeyStroke(KeyEvent.VK_V, mask); deleteKey = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0); moveKey = KeyStroke.getKeyStroke(KeyEvent.VK_M, mask); searchKey = KeyStroke.getKeyStroke(KeyEvent.VK_F, mask); propertiesKey = KeyStroke.getKeyStroke(KeyEvent.VK_P, mask); translateKey = KeyStroke.getKeyStroke(KeyEvent.VK_T, mask); helpKey = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0); copyAction = new KeyAction(copyCmd, copyKey); pasteAction = new KeyAction(pasteCmd, pasteKey); cutAction = new KeyAction(cutCmd, cutKey); deleteAction = new KeyAction(deleteCmd, deleteKey); moveAction = new KeyAction(moveCmd, moveKey); searchAction = new KeyAction(searchCmd, searchKey); propertiesAction = new KeyAction(propertiesCmd, propertiesKey); translateAction = new KeyAction(translateCmd, translateKey); helpAction = new KeyAction(helpCmd, helpKey); /* * Cut, Copy and Paste will not work unless I add them to the JTree input and action maps. Why??? All the others * work fine. */ getInputMap().put(cutKey, cutCmd); getInputMap().put(copyKey, copyCmd); getInputMap().put(pasteKey, pasteCmd); getInputMap().put(deleteKey, deleteCmd); getActionMap().put(cutCmd, cutAction); getActionMap().put(copyCmd, copyAction); getActionMap().put(pasteCmd, pasteAction); getActionMap().put(deleteCmd, deleteAction); this.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); searchParameters = new SearchParameters(); final TreePath path = new TreePath(((DefaultMutableTreeNode) (getModel().getRoot())).getPath()); setSelectionPath(path); scrollPathToVisible(path); chatter = GameModule.getGameModule().getChatter(); createKeyBindings(); setDragEnabled(true); setDropMode(DropMode.ON_OR_INSERT); setTransferHandler(new TreeTransferHandler()); } protected static String noHTML(String text) { return text.replaceAll("<", "&lt;") //NON-NLS // This prevents any unwanted tag from functioning .replaceAll(">", "&gt;"); //NON-NLS // This makes sure > doesn't break any of our legit <div> tags } protected static void chat(String text) { if (chatter != null) { chatter.show("- " + text); } } protected JDialog getSearchDialog() { return searchDialog; } protected void setSearchDialog(JDialog searchDialog) { this.searchDialog = searchDialog; } protected JTextField getSearchField() { return searchField; } protected void setSearchField(JTextField searchField) { this.searchField = searchField; } protected void setSearchAdvanced(JCheckBox searchAdvanced) { this.searchAdvanced = searchAdvanced; } protected JCheckBox getSearchAdvanced() { return searchAdvanced; } public JFrame getFrame() { return editorWindow; } /** * Create a key binding for ENTER key to do meaningful things. */ private void createKeyBindings() { getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); getActionMap().put("Enter", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { // Do something meaningful when Enter key pressed final TreePath path = getSelectionPath(); if (path == null) { //BR// Apparently this can happen. return; } final DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (isExpanded(path) || (node.getChildCount() == 0)) { final Configurable target = (Configurable) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); if ((target != null) && (target.getConfigurer() != null)) { final Action a = buildEditAction(target); if (a != null) { a.actionPerformed(new ActionEvent(ae.getSource(), ActionEvent.ACTION_PERFORMED, "Edit")); //NON-NLS } } } else { setExpandedState(path, true); } } }); } @Override public void treeExpanded(TreeExpansionEvent event) { } /** * A cell has been collapsed. Reset the edit flag on all the children owned by this node * @param event Expansion event */ @Override public void treeCollapsed(TreeExpansionEvent event) { final ConfigureTreeNode node = (ConfigureTreeNode) event.getPath().getLastPathComponent(); node.resetChildEditFlags(); } class KeyAction extends AbstractAction { private static final long serialVersionUID = 1L; protected String actionName; public KeyAction(String name, KeyStroke key) { super(name); actionName = name; putValue(Action.ACCELERATOR_KEY, key); } @Override public void actionPerformed(ActionEvent e) { doKeyAction(actionName); } } protected Renderer buildRenderer() { return new Renderer(); } /** * Tell our enclosing EditorWindow that we are now clean * or dirty. * * @param changed true = state is not dirty */ protected void notifyStateChanged(boolean changed) { if (editorWindow != null) { editorWindow.treeStateChanged(changed); } } protected Configurable getTarget(int x, int y) { final TreePath path = getPathForLocation(x, y); Configurable target = null; if (path != null) { target = (Configurable) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); } return target; } protected DefaultMutableTreeNode buildTreeNode(Configurable c) { c.addPropertyChangeListener(this); final DefaultMutableTreeNode node = new ConfigureTreeNode(c); final Configurable[] children = c.getConfigureComponents(); for (final Configurable child : children) { if (! (child instanceof Plugin)) { // Hide Plug-ins node.add(buildTreeNode(child)); } } nodes.put(c, node); return node; } protected void addAction(JPopupMenu menu, Action a) { if (a != null) { menu.add(a).setFont(POPUP_MENU_FONT); } } protected void addSubMenu(JPopupMenu menu, String name, List<Action> l) { if ((l != null) && !l.isEmpty()) { final JMenu subMenu = new JMenu(name); for (final Action a: l) { subMenu.add(a).setFont(POPUP_MENU_FONT); } menu.add(subMenu).setFont(POPUP_MENU_FONT); l.clear(); } } private void addActionGroup(JPopupMenu menu, List<Action> l) { boolean empty = true; for (final Action a : l) { if (a != null) { menu.add(a).setFont(POPUP_MENU_FONT); empty = false; } } if (!empty) { menu.addSeparator(); } l.clear(); } protected JPopupMenu buildPopupMenu(final Configurable target) { final JPopupMenu popup = new JPopupMenu(); final List<Action> l = new ArrayList<>(); l.add(buildEditAction(target)); l.add(buildEditPiecesAction(target)); addActionGroup(popup, l); l.add(buildTranslateAction(target)); addActionGroup(popup, l); l.add(buildHelpAction(target)); addActionGroup(popup, l); l.add(buildSearchAction(target)); addActionGroup(popup, l); l.add(buildDeleteAction(target)); l.add(buildCutAction(target)); l.add(buildCopyAction(target)); l.add(buildPasteAction(target)); l.add(buildMoveAction(target)); addActionGroup(popup, l); final List<Action> inserts = new ArrayList<>(); final List<Action> adds = buildAddActionsFor(target, inserts); for (final Action a : adds) { addAction(popup, a); } addSubMenu(popup, Resources.getString("Editor.ConfigureTree.insert"), inserts); if (hasChild(target, PieceSlot.class) || hasChild(target, CardSlot.class)) { addAction(popup, buildMassPieceLoaderAction(target)); } addAction(popup, buildImportAction(target)); return popup; } /** * Enumerates our configure tree in preparation for searching it * @param root - root of our module's tree. * @return a list of search nodes */ private List<DefaultMutableTreeNode> getSearchNodes(DefaultMutableTreeNode root) { final List<DefaultMutableTreeNode> searchNodes = new ArrayList<>(); final Enumeration<?> e = root.preorderEnumeration(); while (e.hasMoreElements()) { searchNodes.add((DefaultMutableTreeNode)e.nextElement()); } return searchNodes; } /** * @return Search action - runs search dialog box, then searches */ protected Action buildSearchAction(final Configurable target) { final Action a = new SearchAction(this, searchParameters); a.setEnabled(true); return a; } protected Action buildMoveAction(final Configurable target) { Action a = null; if (getTreeNode(target).getParent() != null) { a = new AbstractAction(moveCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), true); d.setTitle(target.getConfigureName() == null ? moveCmd : moveCmd + " " + target.getConfigureName()); d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS)); final Box box = Box.createHorizontalBox(); box.add(new JLabel(Resources.getString("Editor.ConfigureTree.move_to_position"))); box.add(Box.createHorizontalStrut(10)); final JComboBox<String> select = new JComboBox<>(); final TreeNode parentNode = getTreeNode(target).getParent(); for (int i = 0; i < parentNode.getChildCount(); ++i) { final Configurable c = (Configurable) ((DefaultMutableTreeNode) parentNode.getChildAt(i)).getUserObject(); final String name = (c.getConfigureName() != null ? c.getConfigureName() : "") + " [" + getConfigureName(c.getClass()) + "]"; select.addItem((i + 1) + ": " + name); } final DefaultMutableTreeNode targetNode = getTreeNode(target); final int currentIndex = targetNode.getParent().getIndex(targetNode); select.setSelectedIndex(currentIndex); box.add(select); final JButton ok = new JButton(Resources.getString(Resources.OK)); ok.addActionListener(e1 -> { final int index = select.getSelectedIndex(); if (currentIndex != index) { final Configurable parent = getParent(targetNode); if (remove(parent, target)) { insert(parent, target, index); } } d.dispose(); }); d.add(box); d.add(ok); SwingUtils.repack(d); d.setLocationRelativeTo(d.getParent()); d.setVisible(true); } }; } return a; } protected Action buildCutAction(final Configurable target) { Action a = null; if (getTreeNode(target).getParent() != null) { a = new AbstractAction(cutCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { cutData = getTreeNode(target); copyData = null; updateEditMenu(); } }; } return a; } protected Action buildCopyAction(final Configurable target) { Action a = null; if (getTreeNode(target).getParent() != null) { a = new AbstractAction(copyCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { copyData = getTreeNode(target); cutData = null; updateEditMenu(); } }; } return a; } protected Action buildPasteAction(final Configurable target) { final Action a = new AbstractAction(pasteCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { if (cutData != null) { final DefaultMutableTreeNode targetNode = getTreeNode(target); if (targetNode.isNodeAncestor(cutData)) { chat(Resources.getString("Editor.cant_cut_ancestor_to_child")); return; } final Configurable cutObj = (Configurable) cutData.getUserObject(); final Configurable convertedCutObj = convertChild(target, cutObj); if (remove(getParent(cutData), cutObj)) { insert(target, convertedCutObj, targetNode.getChildCount()); } copyData = getTreeNode(convertedCutObj); } else if (copyData != null) { final Configurable copyBase = (Configurable) copyData.getUserObject(); Configurable clone = null; try { clone = convertChild(target, copyBase.getClass().getConstructor().newInstance()); } catch (Throwable t) { ReflectionUtils.handleNewInstanceFailure(t, copyBase.getClass()); } if (clone != null) { clone.build(copyBase.getBuildElement(Builder.createNewDocument())); insert(target, clone, getTreeNode(target).getChildCount()); updateGpIds(clone); } } cutData = null; updateEditMenu(); } }; a.setEnabled(isValidPasteTarget(target)); return a; } protected boolean isValidPasteTarget(Configurable target, DefaultMutableTreeNode sourceNode) { if (sourceNode == null) { return false; } // We can always be dragged/pasted onto our own parent. DefaultMutableTreeNode parent = (DefaultMutableTreeNode) sourceNode.getParent(); if (parent != null) { if (parent.getUserObject().equals(target)) { return true; } } return isValidParent(target, (Configurable) sourceNode.getUserObject()); } protected boolean isValidPasteTarget(Configurable target) { return isValidPasteTarget(target, cutData) || isValidPasteTarget(target, copyData); } /** * Some components need to be converted to a new type before insertion. * * Currently this is used to allow cut and paste of CardSlots and PieceSlots * between Decks and GamePiece Palette components. * * @param parent Parent Configurable * @param child Child Configurable * @return new Child */ protected Configurable convertChild(Configurable parent, Configurable child) { if (child.getClass() == PieceSlot.class && isAllowedChildClass(parent, CardSlot.class)) { return new CardSlot((PieceSlot) child); } else if (child.getClass() == CardSlot.class && isAllowedChildClass(parent, PieceSlot.class)) { return new PieceSlot((CardSlot) child); } else { return child; } } protected boolean isAllowedChildClass(Configurable parent, Class<?> childClass) { final Class<?>[] allowableClasses = parent.getAllowableConfigureComponents(); for (final Class<?> allowableClass : allowableClasses) { if (allowableClass == childClass) { return true; } } return false; } /** * Allocate new PieceSlot Id's to any PieceSlot sub-components * * @param c Configurable to update */ public void updateGpIds(Configurable c) { if (c instanceof PieceSlot) { ((PieceSlot) c).updateGpId(GameModule.getGameModule()); } else { for (final Configurable comp : c.getConfigureComponents()) updateGpIds(comp); } } protected Action buildImportAction(final Configurable target) { return new AbstractAction(Resources.getString("Editor.ConfigureTree.add_imported_class")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { final Configurable child = importConfigurable(); if (child != null) { try { child.build(null); if (child.getConfigurer() != null) { final PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), false, child, helpWindow) { private static final long serialVersionUID = 1L; @Override public void save() { super.save(); insert(target, child, getTreeNode(target).getChildCount()); } @Override public void cancel() { dispose(); } }; w.setVisible(true); } else { insert(target, child, getTreeNode(target).getChildCount()); } } // FIXME: review error message catch (Exception ex) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Error adding " + getConfigureName(child) + " to " + getConfigureName(target) + "\n" //NON-NLS + ex.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE); //NON-NLS } } } }; } protected Action buildMassPieceLoaderAction(final Configurable target) { Action a = null; final ConfigureTree tree = this; if (getTreeNode(target).getParent() != null) { Resources.getString("Editor.ConfigureTree.add_cards"); final String desc = hasChild(target, CardSlot.class) ? Resources.getString("Editor.ConfigureTree.add_cards") : Resources.getString("Editor.ConfigureTree.add_pieces"); a = new AbstractAction(desc) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { new MassPieceLoader(tree, target).load(); } }; } return a; } protected boolean hasChild(Configurable parent, Class<?> childClass) { for (final Class<?> c : parent.getAllowableConfigureComponents()) { if (c.equals(childClass)) { return true; } } return false; } protected List<Action> buildAddActionsFor(final Configurable target) { return buildAddActionsFor(target, null); } protected List<Action> buildAddActionsFor(final Configurable target, List<Action> peerInserts) { final ArrayList<Action> l = new ArrayList<>(); if (target instanceof AbstractConfigurable) { final DefaultMutableTreeNode targetNode = getTreeNode(target); if (targetNode != null) { final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) targetNode.getParent(); if (parentNode != null) { l.add(buildAddAction((Configurable)parentNode.getUserObject(), target.getClass(), "Editor.ConfigureTree.add_duplicate", parentNode.getIndex(targetNode) + 1, target)); if (peerInserts != null) { final Configurable parent = ((Configurable)parentNode.getUserObject()); for (final Class<? extends Buildable> newConfig : parent.getAllowableConfigureComponents()) { peerInserts.add(buildAddAction(parent, newConfig, "Editor.ConfigureTree.add_peer", parentNode.getIndex(targetNode) + 1, null)); } } } } } for (final Class<? extends Buildable> newConfig : target.getAllowableConfigureComponents()) { l.add(buildAddAction(target, newConfig)); } for (final AdditionalComponent add : additionalComponents) { if (target.getClass().equals(add.getParent())) { final Class<? extends Buildable> newConfig = add.getChild(); l.add(buildAddAction(target, newConfig)); } } return l; } /** * @deprecated Use {@link #buildAddActionsFor(Configurable)} instead. */ @Deprecated(since = "2020-08-06", forRemoval = true) protected Enumeration<Action> buildAddActions(final Configurable target) { ProblemDialog.showDeprecated("2020-08-06"); return Collections.enumeration(buildAddActionsFor(target)); } protected Action buildAddAction(final Configurable target, final Class<? extends Buildable> newConfig) { return buildAddAction(target, newConfig, "Editor.ConfigureTree.add_component", -1, null); } protected Action buildAddAction(final Configurable target, final Class<? extends Buildable> newConfig, String key, int index, final Configurable duplicate) { return new AbstractAction(Resources.getString(key, getConfigureName(newConfig))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { Configurable ch = null; try { ch = (Configurable) newConfig.getConstructor().newInstance(); } catch (Throwable t) { ReflectionUtils.handleNewInstanceFailure(t, newConfig); } if (ch != null) { final Configurable child = ch; child.build((duplicate != null) ? duplicate.getBuildElement(Builder.createNewDocument()) : null); if (child instanceof PieceSlot) { ((PieceSlot) child).updateGpId(GameModule.getGameModule()); } final int finalIndex = (index < 0) ? getTreeNode(target).getChildCount() : checkMinimumIndex(getTreeNode(target), index); if (child.getConfigurer() != null) { if (insert(target, child, finalIndex)) { if (duplicate != null) { updateGpIds(child); } // expand the new node final TreePath path = new TreePath(getTreeNode(child).getPath()); expandPath(path); final PropertiesWindow w = new PropertiesWindow((Frame) SwingUtilities.getAncestorOfClass(Frame.class, ConfigureTree.this), false, child, helpWindow) { private static final long serialVersionUID = 1L; @Override public void cancel() { ConfigureTree.this.remove(target, child); dispose(); } }; w.setVisible(true); } } else { insert(target, child, finalIndex); if (duplicate != null) { updateGpIds(child); } } } } }; } protected Action buildHelpAction(final Configurable target) { final Action showHelp; final HelpFile helpFile = target.getHelpFile(); if (helpFile == null) { showHelp = new ShowHelpAction(null, null); showHelp.setEnabled(false); } else { showHelp = new ShowHelpAction(helpFile.getContents(), null); } return showHelp; } protected Action buildCloneAction(final Configurable target) { final DefaultMutableTreeNode targetNode = getTreeNode(target); if (targetNode.getParent() != null) { return new AbstractAction(Resources.getString("Editor.ConfigureTree.clone")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { Configurable clone = null; try { clone = target.getClass().getConstructor().newInstance(); } catch (Throwable t) { ReflectionUtils.handleNewInstanceFailure(t, target.getClass()); } if (clone != null) { clone.build(target.getBuildElement(Builder.createNewDocument())); insert(getParent(targetNode), clone, targetNode.getParent().getIndex(targetNode) + 1); } } }; } else { return null; } } protected Configurable getParent(final DefaultMutableTreeNode targetNode) { final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) targetNode.getParent(); return parentNode == null ? null : (Configurable) parentNode.getUserObject(); } protected Action buildDeleteAction(final Configurable target) { final DefaultMutableTreeNode targetNode = getTreeNode(target); final Configurable parent = getParent(targetNode); if (targetNode.getParent() != null) { return new AbstractAction(deleteCmd) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { final int row = selectedRow; remove(parent, target); if (row < getRowCount()) { setSelectionRow(row); } else { setSelectionRow(row - 1); } } }; } else { return null; } } protected Action buildEditPiecesAction(final Configurable target) { if (canContainGamePiece(target)) { return new EditContainedPiecesAction(target); } else { return null; } } protected Action buildEditAction(final Configurable target) { return new EditPropertiesAction(target, helpWindow, (Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this); } protected Action buildTranslateAction(final Configurable target) { final Action a = new TranslateAction(target, helpWindow, this); a.setEnabled(target.getI18nData().isTranslatable()); return a; } public boolean canContainGamePiece(final Configurable target) { boolean canContainPiece = false; for (final Class<?> c : target.getAllowableConfigureComponents()) { if (PieceSlot.class.isAssignableFrom(c)) { canContainPiece = true; break; } } return canContainPiece; } protected boolean remove(Configurable parent, Configurable child) { try { child.removeFrom(parent); parent.remove(child); ((DefaultTreeModel) getModel()).removeNodeFromParent(getTreeNode(child)); notifyStateChanged(true); return true; } // FIXME: review error message catch (IllegalBuildException err) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Cannot delete " + getConfigureName(child) + " from " + getConfigureName(parent) + "\n" //NON-NLS + err.getMessage(), "Illegal configuration", JOptionPane.ERROR_MESSAGE); //NON-NLS return false; } } protected boolean insert(Configurable parent, Configurable child, int index) { Configurable theChild = child; // Convert subclasses of GlobalProperty to an actual GlobalProperty before inserting into the GlobalProperties container if (parent.getClass() == GlobalProperties.class && child.getClass() == ZoneProperty.class) { theChild = new GlobalProperty((GlobalProperty) child); } if (parent.getClass() == Zone.class && child.getClass() == GlobalProperty.class) { theChild = new ZoneProperty((GlobalProperty) child); } final DefaultMutableTreeNode childNode = buildTreeNode(theChild); final DefaultMutableTreeNode parentNode = getTreeNode(parent); final Configurable[] oldContents = parent.getConfigureComponents(); final ArrayList<Configurable> moveToBack = new ArrayList<>(); for (int i = index; i < oldContents.length; ++i) { try { oldContents[i].removeFrom(parent); parent.remove(oldContents[i]); } // FIXME: review error message catch (IllegalBuildException err) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Can't insert " + getConfigureName(theChild) + " before " + getConfigureName(oldContents[i]), //NON-NLS "Illegal configuration", JOptionPane.ERROR_MESSAGE); //NON-NLS for (int j = index; j < i; ++j) { parent.add(oldContents[j]); oldContents[j].addTo(parent); } return false; } moveToBack.add(oldContents[i]); } boolean succeeded = true; try { theChild.addTo(parent); parent.add(theChild); parentNode.insert(childNode, index); final int[] childI = new int[1]; childI[0] = index; ((DefaultTreeModel) getModel()).nodesWereInserted(parentNode, childI); } // FIXME: review error message catch (IllegalBuildException err) { JOptionPane.showMessageDialog(getTopLevelAncestor(), "Can't add " + getConfigureName(child) + "\n" + err.getMessage(), "Illegal configuration", //NON-NLS JOptionPane.ERROR_MESSAGE); succeeded = false; } for (final Configurable c : moveToBack) { parent.add(c); c.addTo(parent); } notifyStateChanged(true); return succeeded; } @Override public void propertyChange(PropertyChangeEvent evt) { final DefaultMutableTreeNode newValue = getTreeNode((Configurable) evt.getSource()); ((DefaultTreeModel) getModel()).nodeChanged(newValue); } /** * Custom Tree Cell Renderer * Change the font to italic if the Configurable held by the node for this cell has been edited. */ static class Renderer extends javax.swing.tree.DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; private Font plainFont; private Font italicFont; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { final JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (plainFont == null) { plainFont = label.getFont(); } if (value instanceof ConfigureTreeNode) { final ConfigureTreeNode c = (ConfigureTreeNode) value; if (c.isEdited()) { if (italicFont == null) { final Font f = label.getFont(); italicFont = new Font(f.getFontName(), Font.ITALIC, f.getSize()); } label.setFont(italicFont); } else { label.setFont(plainFont); } } return label; } } /** * Returns the name of the class for display purposes. Reflection is * used to call <code>getConfigureTypeName()</code>, which should be * a static method if it exists in the given class. (This is necessary * because static methods are not permitted in interfaces.) * * @param c the class whose configure name will be returned * @return the configure name of the class */ public static String getConfigureName(Class<?> c) { try { return (String) c.getMethod("getConfigureTypeName").invoke(null); } catch (NoSuchMethodException e) { // Ignore. This is normal, since some classes won't have this method. } catch (IllegalAccessException | ExceptionInInitializerError | NullPointerException | InvocationTargetException | IllegalArgumentException e) { ErrorDialog.bug(e); } return c.getName().substring(c.getName().lastIndexOf(".") + 1); } public static String getConfigureName(Configurable c) { if (c.getConfigureName() != null && c.getConfigureName().length() > 0) { return c.getConfigureName(); } else { return getConfigureName(c.getClass()); } } protected Configurable importConfigurable() { final String className = JOptionPane.showInputDialog( getTopLevelAncestor(), Resources.getString("Editor.ConfigureTree.java_name")); if (className == null) return null; Object o = null; try { o = GameModule.getGameModule().getDataArchive() .loadClass(className).getConstructor().newInstance(); } catch (Throwable t) { ReflectionUtils.handleImportClassFailure(t, className); } if (o == null) return null; if (o instanceof Configurable) return (Configurable) o; ErrorDialog.show("Error.not_a_configurable", className); //$NON-NLS-1$// return null; } protected void maybePopup(MouseEvent e) { final Configurable target = getTarget(e.getX(), e.getY()); if (target == null) { return; } setSelectionRow(getClosestRowForLocation(e.getX(), e.getY())); final JPopupMenu popup = buildPopupMenu(target); popup.show(this, e.getX(), e.getY()); popup.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuCanceled(PopupMenuEvent evt) { repaint(); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent evt) { repaint(); } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent evt) { } }); } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { maybePopup(e); } } // FIXME: should clicked handling be in mouseClicked()? @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { maybePopup(e); } else if (e.getClickCount() == 2 && SwingUtils.isMainMouseButtonDown(e)) { final Configurable target = getTarget(e.getX(), e.getY()); if (target == null) { return; } if (target.getConfigurer() != null) { final Action a = buildEditAction(target); if (a != null) { a.actionPerformed(new ActionEvent(e.getSource(), ActionEvent.ACTION_PERFORMED, "Edit")); //NON-NLS } } } } /* * protected void performDrop(Configurable target) { DefaultMutableTreeNode dragNode = getTreeNode(dragging); * DefaultMutableTreeNode targetNode = getTreeNode(target); Configurable parent = null; int index = 0; if * (isValidParent(target, dragging)) { parent = target; index = targetNode.getChildCount(); if (dragNode.getParent() == * targetNode) { index--; } } else if (targetNode.getParent() != null && isValidParent(getParent(targetNode), * dragging)) { parent = (Configurable) ((DefaultMutableTreeNode) targetNode.getParent()).getUserObject(); index = * targetNode.getParent().getIndex(targetNode); } if (parent != null) { remove(getParent(dragNode), dragging); * insert(parent, dragging, index); } dragging = null; } */ public DefaultMutableTreeNode getTreeNode(Configurable target) { return nodes.get(target); } @Override public void mouseDragged(MouseEvent evt) { } protected boolean isValidParent(Configurable parent, Configurable child) { if (parent != null && child != null) { final Class<?>[] c = parent.getAllowableConfigureComponents(); for (final Class<?> aClass : c) { if (aClass.isAssignableFrom(child.getClass()) || ((aClass == CardSlot.class) && (child.getClass() == PieceSlot.class)) || // Allow PieceSlots to be pasted to Decks ((aClass == ZoneProperty.class) && (child.getClass() == GlobalProperty.class)) // Allow Global Properties to be saved as Zone Properties ) { return true; } } } return false; } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } /* * Refresh the display of a node */ public void nodeUpdated(Configurable target) { final DefaultMutableTreeNode node = getTreeNode(target); final Configurable parent = getParent(node); if (remove(parent, target)) { insert(parent, target, 0); } ((DefaultTreeModel) getModel()).nodeChanged(node); } /** * Configurers that add or remove their own children directly should implement the Mutable interface so that * ConfigureTree can refresh the changed node. */ public interface Mutable { } /** * Build an AddAction and execute it to request a new component from the user * * @param parent * Target Parent * @param child * Type to add */ public void externalInsert(Configurable parent, Configurable child) { insert(parent, child, getTreeNode(parent).getChildCount()); } public Action getHelpAction() { return helpAction; } public void populateEditMenu(EditorWindow ew) { final MenuManager mm = MenuManager.getInstance(); mm.addAction("Editor.delete", deleteAction); mm.addAction("Editor.cut", cutAction); mm.addAction("Editor.copy", copyAction); mm.addAction("Editor.paste", pasteAction); mm.addAction("Editor.move", moveAction); mm.addAction("Editor.search", searchAction); mm.addAction("Editor.properties", propertiesAction); mm.addAction("Editor.ModuleEditor.translate", translateAction); updateEditMenu(); } /** * Handle main Edit menu selections/accelerators * * @param action * Edit command name */ protected void doKeyAction(String action) { final DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode) this.getLastSelectedPathComponent(); if (targetNode != null) { final Configurable target = (Configurable) targetNode.getUserObject(); Action a = null; if (cutCmd.equals(action)) { a = buildCutAction(target); } else if (copyCmd.equals(action)) { a = buildCopyAction(target); } else if (pasteCmd.equals(action) || action.equals(String.valueOf(pasteKey.getKeyChar()))) { a = buildPasteAction(target); } else if (deleteCmd.equals(action)) { a = buildDeleteAction(target); } else if (moveCmd.equals(action)) { a = buildMoveAction(target); } else if (searchCmd.equals(action)) { a = buildSearchAction(target); } else if (propertiesCmd.equals(action)) { a = buildEditAction(target); } else if (translateCmd.equals(action)) { a = buildTranslateAction(target); } else if (helpCmd.equals(action)) { a = buildHelpAction(target); } if (a != null) { a.actionPerformed(null); } } } /** * Tree selection changed, record info about the currently selected component */ @Override public void valueChanged(TreeSelectionEvent e) { selected = null; final TreePath path = e.getPath(); if (path != null) { final DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent(); selected = (Configurable) selectedNode.getUserObject(); selectedRow = getRowForPath(path); updateEditMenu(); ((DefaultTreeModel) getModel()).nodeChanged(selectedNode); } } protected void updateEditMenu() { deleteAction.setEnabled(selected != null); cutAction.setEnabled(selected != null); copyAction.setEnabled(selected != null); pasteAction.setEnabled(selected != null && isValidPasteTarget(selected)); moveAction.setEnabled(selected != null); searchAction.setEnabled(true); // Check the cached Configurer in the TreeNode, not the Configurable as Configurable.getConfigurer() // is very expensive and resets the Configurer causing label truncation issues in the JTree propertiesAction.setEnabled(selected != null && selected.getConfigurer() != null); translateAction.setEnabled(selected != null); } /** * Find the parent Configurable of a specified Configurable * * @param target target Configurable * @return parent */ protected Configurable getParent(Configurable target) { final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) getTreeNode(target).getParent(); return (Configurable) parentNode.getUserObject(); } public String getSearchCmd() { return searchCmd; } /** * Record additional available components to add to the popup menu. * * @param parent Parent Class * @param child Child Class */ public static void addAdditionalComponent(Class<? extends Buildable> parent, Class<? extends Buildable> child) { additionalComponents.add(new AdditionalComponent(parent, child)); } protected static class AdditionalComponent { Class<? extends Buildable> parent; Class<? extends Buildable> child; public AdditionalComponent(Class<? extends Buildable> p, Class<? extends Buildable> c) { parent = p; child = c; } public Class<? extends Buildable> getParent() { return parent; } public Class<? extends Buildable> getChild() { return child; } } /** * Container for search parameters */ private static class SearchParameters { public static final String SEARCH_STRING = "searchString"; //$NON-NLS-1$// public static final String MATCH_CASE = "matchCase"; //$NON-NLS-1$// public static final String MATCH_NAMES = "matchNames"; //$NON-NLS-1$// public static final String MATCH_TYPES = "matchTypes"; //$NON-NLS-1$// public static final String MATCH_ADVANCED = "matchAdvanced"; //$NON-NLS-1$// public static final String MATCH_TRAITS = "matchTraits"; //$NON-NLS-1$// public static final String MATCH_EXPRESSIONS = "matchExpressions"; //$NON-NLS-1$// public static final String MATCH_PROPERTIES = "matchProperties"; //$NON-NLS-1$// public static final String MATCH_KEYS = "matchKeys"; //$NON-NLS-1$// public static final String MATCH_MENUS = "matchMenus"; //$NON-NLS-1$// public static final String MATCH_MESSAGES = "matchMessages"; //$NON-NLS-1$// /** Current search string */ private String searchString; /** True if case-sensitive */ private boolean matchCase; /** True if match configurable names */ private boolean matchNames; /** True if match class names */ private boolean matchTypes; /** True if using advanced search (enables subsequent items) */ private boolean matchAdvanced; /** True if match traits (names, descriptions, menu commands) */ private boolean matchTraits; /** True if match expressions */ private boolean matchExpressions; /** True if match Properties */ private boolean matchProperties; /** True if match key commands */ private boolean matchKeys; /** True if match context menu text */ private boolean matchMenus; /** True if match Message Formats */ private boolean matchMessages; /** Attach to our module preferences, if relevant */ private static Prefs prefs; /** * Constructs a new search parameters object, using the preferences. */ public SearchParameters() { // Attach to our module preferences if constructed this way. This also marks that we will write them when modified prefs = GameModule.getGameModule().getPrefs(); prefs.addOption(null, new StringConfigurer(SearchParameters.SEARCH_STRING, null, "")); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_CASE, null, false)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_NAMES, null, true)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_TYPES, null, true)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_ADVANCED, null, false)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_TRAITS, null, true)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_EXPRESSIONS, null, true)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_PROPERTIES, null, true)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_KEYS, null, true)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_MENUS, null, true)); prefs.addOption(null, new BooleanConfigurer(SearchParameters.MATCH_MESSAGES, null, true)); searchString = (String) prefs.getValue(SearchParameters.SEARCH_STRING); matchCase = (Boolean)prefs.getValue(SearchParameters.MATCH_CASE); matchNames = (Boolean)prefs.getValue(SearchParameters.MATCH_NAMES); matchTypes = (Boolean)prefs.getValue(SearchParameters.MATCH_TYPES); matchAdvanced = (Boolean)prefs.getValue(SearchParameters.MATCH_ADVANCED); matchTraits = (Boolean)prefs.getValue(SearchParameters.MATCH_TRAITS); matchExpressions = (Boolean)prefs.getValue(SearchParameters.MATCH_EXPRESSIONS); matchProperties = (Boolean)prefs.getValue(SearchParameters.MATCH_PROPERTIES); matchKeys = (Boolean)prefs.getValue(SearchParameters.MATCH_KEYS); matchMenus = (Boolean)prefs.getValue(SearchParameters.MATCH_MENUS); matchMessages = (Boolean)prefs.getValue(SearchParameters.MATCH_MESSAGES); } /** * Constructs a new search parameters object */ public SearchParameters(String searchString, boolean matchCase, boolean matchNames, boolean matchTypes, boolean matchAdvanced, boolean matchTraits, boolean matchExpressions, boolean matchProperties, boolean matchKeys, boolean matchMenus, boolean matchMessages) { this.searchString = searchString; this.matchCase = matchCase; this.matchNames = matchNames; this.matchTypes = matchTypes; this.matchAdvanced = matchAdvanced; this.matchTraits = matchTraits; this.matchExpressions = matchExpressions; this.matchProperties = matchProperties; this.matchKeys = matchKeys; this.matchMenus = matchMenus; this.matchMessages = matchMessages; } public String getSearchString() { return searchString; } public void setSearchString(String searchString) { this.searchString = searchString; writePrefs(); } public boolean isMatchCase() { return matchCase; } public void setMatchCase(boolean matchCase) { this.matchCase = matchCase; writePrefs(); } public boolean isMatchNames() { return matchNames; } public void setMatchNames(boolean matchNames) { this.matchNames = matchNames; writePrefs(); } public boolean isMatchTypes() { return matchTypes; } public void setMatchTypes(boolean matchTypes) { this.matchTypes = matchTypes; writePrefs(); } public boolean isMatchAdvanced() { return matchAdvanced; } public void setMatchAdvanced(boolean matchAdvanced) { this.matchAdvanced = matchAdvanced; writePrefs(); } public boolean isMatchTraits() { return matchTraits; } public void setMatchTraits(boolean matchTraits) { this.matchTraits = matchTraits; writePrefs(); } public boolean isMatchExpressions() { return matchExpressions; } public void setMatchExpressions(boolean matchExpressions) { this.matchExpressions = matchExpressions; writePrefs(); } public boolean isMatchProperties() { return matchProperties; } public void setMatchProperties(boolean matchProperties) { this.matchProperties = matchProperties; writePrefs(); } public boolean isMatchKeys() { return matchKeys; } public void setMatchKeys(boolean matchKeys) { this.matchKeys = matchKeys; writePrefs(); } public boolean isMatchMenus() { return matchMenus; } public void setMatchMenus(boolean matchMenus) { this.matchMenus = matchMenus; writePrefs(); } public boolean isMatchMessages() { return matchMessages; } public void setMatchMessages(boolean matchMessages) { this.matchMessages = matchMessages; writePrefs(); } public void setFrom(final SearchParameters searchParameters) { searchString = searchParameters.getSearchString(); matchCase = searchParameters.isMatchCase(); matchNames = searchParameters.isMatchNames(); matchTypes = searchParameters.isMatchTypes(); matchAdvanced = searchParameters.isMatchAdvanced(); matchTraits = searchParameters.isMatchTraits(); matchExpressions = searchParameters.isMatchExpressions(); matchProperties = searchParameters.isMatchProperties(); matchKeys = searchParameters.isMatchKeys(); matchMenus = searchParameters.isMatchMenus(); matchMessages = searchParameters.isMatchMessages(); writePrefs(); } public void writePrefs() { if (prefs != null) { prefs.setValue(SEARCH_STRING, searchString); prefs.setValue(MATCH_CASE, matchCase); prefs.setValue(MATCH_NAMES, matchNames); prefs.setValue(MATCH_TYPES, matchTypes); prefs.setValue(MATCH_ADVANCED, matchAdvanced); prefs.setValue(MATCH_TRAITS, matchTraits); prefs.setValue(MATCH_EXPRESSIONS, matchExpressions); prefs.setValue(MATCH_PROPERTIES, matchProperties); prefs.setValue(MATCH_KEYS, matchKeys); prefs.setValue(MATCH_MENUS, matchMenus); prefs.setValue(MATCH_MESSAGES, matchMessages); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SearchParameters that = (SearchParameters) o; return isMatchCase() == that.isMatchCase() && isMatchNames() == that.isMatchNames() && isMatchTypes() == that.isMatchTypes() && isMatchTraits() == that.isMatchTraits() && isMatchAdvanced() == that.isMatchAdvanced() && isMatchExpressions() == that.isMatchExpressions() && isMatchProperties() == that.isMatchProperties() && isMatchKeys() == that.isMatchKeys() && isMatchMenus() == that.isMatchMenus() && isMatchMessages() == that.isMatchMessages() && getSearchString().equals(that.getSearchString()); } @Override public int hashCode() { return Objects.hash(getSearchString(), isMatchCase(), isMatchNames(), isMatchTypes(), isMatchAdvanced(), isMatchTraits(), isMatchExpressions(), isMatchProperties(), isMatchKeys(), isMatchMenus(), isMatchMessages()); } } private static class SearchAction extends AbstractAction { private static final long serialVersionUID = 1L; private final ConfigureTree configureTree; private final SearchParameters searchParameters; /** * Constructs a new {@link SearchAction} * * @param configureTree back reference to the {@link ConfigureTree} * @param searchParameters reference to the search parameter object */ public SearchAction(ConfigureTree configureTree, SearchParameters searchParameters) { super(configureTree.getSearchCmd()); this.configureTree = configureTree; this.searchParameters = searchParameters; } @Override public void actionPerformed(ActionEvent e) { JDialog d = configureTree.getSearchDialog(); final JTextField search; if (d != null) { search = configureTree.getSearchField(); search.selectAll(); } else { d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, configureTree), false); configureTree.setSearchDialog(d); d.setTitle(configureTree.getSearchCmd()); search = new HintTextField(32, Resources.getString("Editor.search_string")); search.setText(searchParameters.getSearchString()); configureTree.setSearchField(search); search.selectAll(); final JCheckBox sensitive = new JCheckBox(Resources.getString("Editor.search_case"), searchParameters.isMatchCase()); final JCheckBox advanced = new JCheckBox(Resources.getString("Editor.search_advanced"), searchParameters.isMatchAdvanced()); final JCheckBox names = new JCheckBox(Resources.getString("Editor.search_names"), searchParameters.isMatchNames()); final JCheckBox types = new JCheckBox(Resources.getString("Editor.search_types"), searchParameters.isMatchTypes()); final JCheckBox traits = new JCheckBox(Resources.getString("Editor.search_traits"), searchParameters.isMatchTraits()); final JCheckBox expressions = new JCheckBox(Resources.getString("Editor.search_expressions"), searchParameters.isMatchExpressions()); final JCheckBox properties = new JCheckBox(Resources.getString("Editor.search_properties"), searchParameters.isMatchProperties()); final JCheckBox keys = new JCheckBox(Resources.getString("Editor.search_keys"), searchParameters.isMatchKeys()); final JCheckBox menus = new JCheckBox(Resources.getString("Editor.search_menus"), searchParameters.isMatchMenus()); final JCheckBox messages = new JCheckBox(Resources.getString("Editor.search_messages"), searchParameters.isMatchMessages()); final Consumer<Boolean> visSetter = visible -> { names.setVisible(visible); types.setVisible(visible); traits.setVisible(visible); expressions.setVisible(visible); properties.setVisible(visible); keys.setVisible(visible); menus.setVisible(visible); messages.setVisible(visible); }; advanced.addChangeListener(l -> { visSetter.accept(advanced.isSelected()); SwingUtils.repack(configureTree.getSearchDialog()); }); visSetter.accept(advanced.isSelected()); configureTree.setSearchAdvanced(advanced); final JButton find = new JButton(Resources.getString("Editor.search_next")); find.addActionListener(e12 -> { final SearchParameters parametersSetInDialog = new SearchParameters(search.getText(), sensitive.isSelected(), names.isSelected(), types.isSelected(), true, traits.isSelected(), expressions.isSelected(), properties.isSelected(), keys.isSelected(), menus.isSelected(), messages.isSelected()); final boolean anyChanges = !searchParameters.equals(parametersSetInDialog); if (anyChanges) { searchParameters.setFrom(parametersSetInDialog); } // If literally no search parameters are selectable, turn at least one on (and print warning) if (!searchParameters.isMatchNames() && !searchParameters.isMatchTypes() && searchParameters.isMatchAdvanced() && (!searchParameters.isMatchTraits() && !searchParameters.isMatchExpressions() && !searchParameters.isMatchProperties() && !searchParameters.isMatchKeys() && !searchParameters.isMatchMenus() && !searchParameters.isMatchMessages())) { searchParameters.setMatchNames(true); names.setSelected(true); ConfigureTree.chat(Resources.getString("Editor.search_all_off")); } if (!searchParameters.getSearchString().isEmpty()) { if (anyChanges) { // Unless we're just continuing to the next match in an existing search, compute & display hit count final int matches = getNumMatches(searchParameters.getSearchString()); chat(matches + " " + Resources.getString("Editor.search_count") + noHTML(searchParameters.getSearchString())); } // Find first match final DefaultMutableTreeNode node = findNode(searchParameters.getSearchString()); // Assuming *something* matched, scroll to it and show any "trait hits" if (node != null) { final TreePath path = new TreePath(node.getPath()); configureTree.setSelectionPath(path); configureTree.scrollPathToVisible(path); if (searchParameters.isMatchAdvanced()) { showHitList(node, searchParameters.getSearchString()); } } else { chat(Resources.getString("Editor.search_none_found") + noHTML(searchParameters.getSearchString())); } } }); final JButton cancel = new JButton(Resources.getString(Resources.CANCEL)); cancel.addActionListener(e1 -> configureTree.getSearchDialog().setVisible(false)); final JButton help = new JButton(Resources.getString(Resources.HELP)); help.addActionListener(e2 -> showSearchHelp()); d.setLayout(new MigLayout("", "[fill]")); // NON-NLS final JPanel panel = new JPanel(new MigLayout("hidemode 3,wrap 1" + "," + ConfigurerLayout.STANDARD_GAPY, "[fill]")); // NON-NLS panel.setBorder(BorderFactory.createEtchedBorder()); // top row panel.add(search); // options row panel.add(sensitive); panel.add(advanced); // Advanced 1 panel.add(names); panel.add(types); // Advanced 2 panel.add(traits); panel.add(expressions); panel.add(properties); // Advanced 3 panel.add(keys); panel.add(menus); panel.add(messages); // buttons row final JPanel bPanel = new JPanel(new MigLayout("ins 0", "push[]rel[]rel[]push")); // NON-NLS bPanel.add(find, "tag ok,sg 1"); //$NON-NLS-1$// bPanel.add(cancel, "tag cancel,sg 1"); //$NON-NLS-1$// bPanel.add(help, "tag help,sg 1"); // NON-NLS panel.add(bPanel, "grow"); // NON-NLS d.add(panel, "grow"); // NON-NLS d.getRootPane().setDefaultButton(find); // Enter key activates search // Esc Key cancels final KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); d.getRootPane().registerKeyboardAction(ee -> configureTree.getSearchDialog().setVisible(false), k, JComponent.WHEN_IN_FOCUSED_WINDOW); } search.requestFocus(); // Start w/ focus in search string field if (!d.isVisible()) { d.setLocationRelativeTo(d.getParent()); SwingUtils.repack(d); d.setVisible(true); } } private void showSearchHelp() { // FIXME - Add Help ref } /** * Search through the tree, starting at the currently selected location (and wrapping around if needed) * Compare nodes until we find our search string (or have searched everything we can search) * @return the node we found, or null if none */ private DefaultMutableTreeNode findNode(String searchString) { final List<DefaultMutableTreeNode> searchNodes = configureTree.getSearchNodes((DefaultMutableTreeNode)configureTree.getModel().getRoot()); final DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)configureTree.getLastSelectedPathComponent(); int bookmark = -1; if (currentNode != null) { bookmark = IntStream .range(0, searchNodes.size()) .filter(i -> searchNodes.get(i) == currentNode) .findFirst() .orElse(-1); } final Predicate<DefaultMutableTreeNode> nodeMatchesSearchString = node -> checkNode(node, searchString); final DefaultMutableTreeNode foundNode = searchNodes .stream() .skip(bookmark + 1) .filter(nodeMatchesSearchString) .findFirst() .orElse(null); if (foundNode != null) { return foundNode; } return searchNodes .stream() .limit(bookmark + 1) .filter(nodeMatchesSearchString) .findFirst() .orElse(null); } /** * @return how many total nodes match the search string */ private int getNumMatches(String searchString) { final List<DefaultMutableTreeNode> searchNodes = configureTree.getSearchNodes((DefaultMutableTreeNode)configureTree.getModel().getRoot()); return (int) searchNodes.stream().filter(node -> checkNode(node, searchString)).count(); } /** * @param st - Search target (usually Decorator or AbstractConfigurable) * @param searchString - our search string * @return true if the node matches our searchString based on search configuration ("match" checkboxes) */ private boolean checkSearchTarget(SearchTarget st, String searchString) { if (searchParameters.isMatchExpressions()) { final List<String> exps = st.getExpressionList(); if (exps != null) { for (final String s : exps) { if (!StringUtils.isEmpty(s) && checkString(s, searchString)) { return true; } } } } if (searchParameters.isMatchProperties()) { final List<String> props = st.getPropertyList(); if (props != null) { for (final String s : props) { if (!StringUtils.isEmpty(s) && checkString(s, searchString)) { return true; } } } } if (searchParameters.isMatchKeys()) { final List<NamedKeyStroke> keys = st.getNamedKeyStrokeList(); if (keys != null) { for (final NamedKeyStroke k : keys) { if (k != null) { final String s = k.isNamed() ? k.getName() : KeyNamer.getKeyString(k.getStroke()); if (!StringUtils.isEmpty(s) && checkString(s, searchString)) { return true; } } } } } if (searchParameters.isMatchMenus()) { final List<String> menus = st.getMenuTextList(); if (menus != null) { for (final String s : menus) { if (!StringUtils.isEmpty(s) && checkString(s, searchString)) { return true; } } } } if (searchParameters.isMatchMessages()) { final List<String> msgs = st.getFormattedStringList(); if (msgs != null) { for (final String s : msgs) { if (!StringUtils.isEmpty(s) && checkString(s, searchString)) { return true; } } } } return false; } /** * @param node - any node of our module tree * @param searchString - our search string * @return true if the node matches our searchString based on search configuration ("match" checkboxes) */ private boolean checkNode(DefaultMutableTreeNode node, String searchString) { final Configurable c = (Configurable) node.getUserObject(); if (searchParameters.isMatchNames() || !searchParameters.isMatchAdvanced()) { final String objectName = c.getConfigureName(); if (objectName != null && checkString(objectName, searchString)) { return true; } } if (searchParameters.isMatchTypes() || !searchParameters.isMatchAdvanced()) { final String className = getConfigureName(c.getClass()); if ((className != null) && checkString(className, searchString)) { return true; } } if (!searchParameters.isMatchAdvanced()) { return false; } // From here down we are only searching inside of SearchTarget objects (Piece/Prototypes, or searchable AbstractConfigurables) GamePiece p; boolean protoskip; if (c instanceof GamePiece) { p = (GamePiece) c; protoskip = false; } else if (c instanceof PieceSlot) { p = ((PieceSlot)c).getPiece(); protoskip = false; } else if (c instanceof PrototypeDefinition) { p = ((PrototypeDefinition)c).getPiece(); protoskip = true; } else if (c instanceof SearchTarget) { return checkSearchTarget((SearchTarget) c, searchString); } else { return false; } // We're going to search Decorator from inner-to-outer (BasicPiece-on-out), so that user sees the traits hit in // the same order they're listed in the PieceDefiner window. So we first traverse them in the "normal" direction // outer to inner and make a list in the order we want to traverse it (for architectural reasons, just traversing // with getOuter() would take us inside of prototypes inside a piece, which we don't want). final List<GamePiece> pieces = new ArrayList<>(); pieces.add(p); while (p instanceof Decorator) { p = ((Decorator) p).getInner(); pieces.add(p); } Collections.reverse(pieces); for (final GamePiece piece : pieces) { if (!protoskip) { // Skip the fake "Basic Piece" on a Prototype definition if (searchParameters.isMatchTraits()) { if (piece instanceof EditablePiece) { final String desc = ((EditablePiece) piece).getDescription(); if ((desc != null) && checkString(desc, searchString)) { return true; } } } if (piece instanceof SearchTarget) { if (checkSearchTarget((SearchTarget)piece, searchString)) { return true; } } } protoskip = false; } return false; } /** * Tracks how we are progressing through searching a target GamePiece or Configurable and its traits/attributes, and whether we need to display headers */ private static class TargetProgress { public boolean targetShown = false; public boolean traitShown = false; /** * When we're starting a new trait within the piece, clear the traitShown flag. */ void startNewTrait() { traitShown = false; } /** * Checks and displays the piece header if needed * @param matchString our match string */ void checkShowPiece(String matchString) { if (!targetShown) { targetShown = true; chat(matchString); } } /** * Checks and displays the piece header & trait/component headers, if needed * @param matchString our match string * @param desc trait description */ void checkShowTrait(String matchString, String idString, String desc) { checkShowPiece(matchString); if (!traitShown) { traitShown = true; chat("&nbsp;&nbsp;{" + idString + "} " + ((desc != null) ? desc : "")); //NON-NLS } } } private void hitCheck(String s, String searchString, String matchString, String item, String desc, String show, TargetProgress progress) { if (!StringUtils.isEmpty(s) && checkString(s, searchString)) { progress.checkShowTrait(matchString, item, desc); chat("&nbsp;&nbsp;&nbsp;&nbsp;{" + show + "} " + noHTML(s)); //NON-NLS } } private void stringListHits(Boolean flag, List<String> strings, String searchString, String matchString, String item, String desc, String show, TargetProgress progress) { if (!flag || (strings == null)) { return; } for (final String s : strings) { hitCheck(s, searchString, matchString, item, desc, show, progress); } } private void keyListHits(Boolean flag, List<NamedKeyStroke> keys, String searchString, String matchString, String item, String desc, String show, TargetProgress progress) { if (!flag || (keys == null)) { return; } for (final NamedKeyStroke k : keys) { if (k != null) { final String s = k.isNamed() ? k.getName() : KeyNamer.getKeyString(k.getStroke()); hitCheck(s, searchString, matchString, item, desc, show, progress); } } } private void showConfigurableHitList(DefaultMutableTreeNode node, String searchString) { final Configurable c = (Configurable) node.getUserObject(); if (!(c instanceof SearchTarget)) { return; } final String name = (c.getConfigureName() != null ? c.getConfigureName() : "") + " [" + getConfigureName(c.getClass()) + "]"; final String matchString = "<b><u>Matches for " + noHTML(name) + ": </u></b>"; //NON-NLS final SearchTarget st = (SearchTarget) c; final String item = getConfigureName(c.getClass()); final TargetProgress progress = new TargetProgress(); stringListHits(searchParameters.isMatchNames(), Arrays.asList(c.getConfigureName()), searchString, matchString, item, "", "Name", progress); //NON-NLS stringListHits(searchParameters.isMatchTypes(), Arrays.asList(item), searchString, matchString, item, "", "Type", progress); //NON-NLS stringListHits(searchParameters.isMatchExpressions(), st.getExpressionList(), searchString, matchString, item, "", "Expression", progress); //NON-NLS stringListHits(searchParameters.isMatchProperties(), st.getPropertyList(), searchString, matchString, item, "", "Property", progress); //NON-NLS stringListHits(searchParameters.isMatchMenus(), st.getMenuTextList(), searchString, matchString, item, "", "UI Text", progress); //NON-NLS stringListHits(searchParameters.isMatchMessages(), st.getFormattedStringList(), searchString, matchString, item, "", "Message/Field", progress); //NON-NLS //NON-NLSkeyListHits(searchParameters.isMatchKeys(), st.getNamedKeyStrokeList(), searchString, matchString, item, "", "KeyCommand", progress); } /** * If this node contains a Game Piece of some kind, displays a list of Trait information from the piece that * matches our search parameters. * @param node - any node of our module tree * @param searchString - our search string */ private void showHitList(DefaultMutableTreeNode node, String searchString) { final Configurable c = (Configurable) node.getUserObject(); GamePiece p; boolean protoskip; if (c instanceof GamePiece) { p = (GamePiece)c; protoskip = false; // This is a "real" GamePiece so we will look at the BasicPiece too } else if (c instanceof PieceSlot) { p = ((PieceSlot)c).getPiece(); protoskip = false; // This is a "real" GamePiece so we will look at the BasicPiece too } else if (c instanceof PrototypeDefinition) { p = ((PrototypeDefinition)c).getPiece(); protoskip = true; // This is a prototype definition, so we will ignore the BasicPiece entry } else { showConfigurableHitList(node, searchString); // If no GamePiece, try regular Configurable search. return; } final String name = (c.getConfigureName() != null ? c.getConfigureName() : "") + " [" + getConfigureName(c.getClass()) + "]"; final TargetProgress progress = new TargetProgress(); final String matchString = "<b><u>Matches for " + name + ": </u></b>"; //NON-NLS stringListHits(searchParameters.isMatchNames(), Arrays.asList(c.getConfigureName()), searchString, matchString, protoskip ? "Prototype Definition" : "Game Piece", "", "Name", progress); //NON-NLS stringListHits(searchParameters.isMatchTypes(), Arrays.asList(getConfigureName(c.getClass())), searchString, matchString, protoskip ? "Prototype Definition" : "Game Piece", "", "Type", progress); //NON-NLS // We're going to search Decorator from inner-to-outer (BasicPiece-on-out), so that user sees the traits hit in // the same order they're listed in the PieceDefiner window. So we first traverse them in the "normal" direction // outer to inner and make a list in the order we want to traverse it (for architectural reasons, just traversing // with getOuter() would take us inside of prototypes inside a piece, which we don't want). final List<GamePiece> pieces = new ArrayList<>(); pieces.add(p); while (p instanceof Decorator) { p = ((Decorator) p).getInner(); pieces.add(p); } Collections.reverse(pieces); for (final GamePiece piece : pieces) { if (!protoskip && (piece instanceof EditablePiece) && (piece instanceof Decorator)) { // Skip the fake "Basic Piece" on a Prototype definition final String desc = ((EditablePiece) piece).getDescription(); final Decorator d = (Decorator)piece; progress.startNewTrait(); // A new trait, so reset our "trait progress". if (searchParameters.isMatchTraits()) { if ((desc != null) && checkString(desc, searchString)) { progress.checkShowTrait(matchString, "Trait", desc); //NON-NLS } } stringListHits(searchParameters.isMatchExpressions(), d.getExpressionList(), searchString, matchString, "Trait", desc, "Expression", progress); //NON-NLS stringListHits(searchParameters.isMatchProperties(), d.getPropertyList(), searchString, matchString, "Trait", desc, "Property", progress); //NON-NLS stringListHits(searchParameters.isMatchMenus(), d.getMenuTextList(), searchString, matchString, "Trait", desc, "UI Text", progress); //NON-NLS stringListHits(searchParameters.isMatchMessages(), d.getFormattedStringList(), searchString, matchString, "Trait", desc, "Message/Field", progress); //NON-NLS keyListHits(searchParameters.isMatchKeys(), d.getNamedKeyStrokeList(), searchString, matchString, "Trait", desc, "KeyCommand", progress); //NON-NLS } protoskip = false; } } /** * Checks a single string against our search parameters * @param target - string to check * @param searchString - our search string * @return true if this is a match based on our "matchCase" checkbox */ private boolean checkString(String target, String searchString) { if (searchParameters.isMatchCase()) { return target.contains(searchString); } else { return target.toLowerCase().contains(searchString.toLowerCase()); } } } /** * Called when the Configurable held by a node has been edited. * Set the edit status and re-build the Jtree label * @param target Edited Configurable */ public void nodeEdited(Configurable target) { final ConfigureTreeNode node = (ConfigureTreeNode) getTreeNode(target); node.setEdited(true); ((DefaultTreeModel) getModel()).nodeChanged(node); } /** * Custom TreeNode * - Determine description for the node * - Track this node has been edited */ private static class ConfigureTreeNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 1L; private boolean edited; public ConfigureTreeNode(Object userObject) { super(userObject); edited = false; } @Override public String toString() { String description = ""; final Configurable c = (Configurable) getUserObject(); if (c != null) { description = (c.getConfigureName() != null ? c.getConfigureName() : ""); if (c instanceof GlobalProperty) { final String desc = ((GlobalProperty)c).getDescription(); if (!desc.isEmpty()) { description += " - " + desc; } } if (c instanceof GlobalTranslatableMessage) { final String desc = ((GlobalTranslatableMessage)c).getDescription(); if (!desc.isEmpty()) { description += " - " + desc; } } description += " [" + getConfigureName(c.getClass()) + "]"; } return description; } public boolean isEdited() { return edited; } public void setEdited(boolean edited) { this.edited = edited; } /** * Reset the edit flags on this node and all Children of this node */ private void resetEditFlags() { setEdited(false); resetChildEditFlags(); } /** * Reset the edit flags on all Children of this node */ public void resetChildEditFlags() { if (getChildCount() > 0) { for (final TreeNode node : children) { ((ConfigureTreeNode) node).resetEditFlags(); } } } } /** * Allows ExtensionEditor to override and control what indexes are allowed */ public int checkMinimumIndex(DefaultMutableTreeNode targetNode, int index) { return index; } /** * Tree Transfer Handler provides drag-and-drop support for editor items. Heavily adapted from Oracle "tutorial" and * various StackOverflow and Code Ranch articles, but yeah, google ftw. (Brian Reynolds Apr 4 2021) */ class TreeTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; DataFlavor nodesFlavor; DataFlavor[] flavors = new DataFlavor[1]; public TreeTransferHandler() { try { final String mimeType = DataFlavor.javaJVMLocalObjectMimeType + ";class=\"" + DefaultMutableTreeNode[].class.getName() + "\""; nodesFlavor = new DataFlavor(mimeType); flavors[0] = nodesFlavor; } catch (ClassNotFoundException e) { System.out.println("Class Not Found: " + e.getMessage()); //NON-NLS } } @Override public boolean canImport(TransferHandler.TransferSupport support) { if (!support.isDrop()) { return false; } support.setShowDropLocation(true); if (!support.isDataFlavorSupported(nodesFlavor)) { return false; } // Do not allow a drop on the drag source selections. final JTree.DropLocation dl = (JTree.DropLocation)support.getDropLocation(); final JTree tree = (JTree)support.getComponent(); final int dropRow = tree.getRowForPath(dl.getPath()); final int[] selRows = tree.getSelectionRows(); if (selRows == null) return false; for (final int selRow : selRows) { if (selRow == dropRow) { return false; } } // Only allow drag to a valid parent (same logic as our regular cut-and-paste) final TreePath dest = dl.getPath(); final DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode)dest.getLastPathComponent(); final TreePath path = tree.getPathForRow(selRows[0]); final DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode)path.getLastPathComponent(); final Configurable target = (Configurable)targetNode.getUserObject(); if (!isValidPasteTarget(target, firstNode)) { return false; } // If we're editing an extension, components owned by the module can never be dragged if (tree instanceof ExtensionTree) { final ExtensionTree xTree = (ExtensionTree) tree; if (!xTree.isEditable(firstNode)) { return false; } } final int action = support.getDropAction(); if (action == MOVE) { // Don't allow move (cut) to our own descendant return !targetNode.isNodeAncestor(firstNode); } return true; } /** * @param c The component being dragged * @return Package describing data to be moved/copied */ @Override protected Transferable createTransferable(JComponent c) { final JTree tree = (JTree)c; final TreePath[] paths = tree.getSelectionPaths(); if (paths != null) { // Array w/ node to be transferred final DefaultMutableTreeNode node = (DefaultMutableTreeNode)paths[0].getLastPathComponent(); final DefaultMutableTreeNode[] nodes = new DefaultMutableTreeNode[1]; nodes[0] = node; return new NodesTransferable(nodes); } return null; } /** * Nothing to do here, as we do our removal in the import stage (original algorithm made a copy and then deleted * the source, but that would make our "unique ID" code barf a mighty barf) */ @Override protected void exportDone(JComponent source, Transferable data, int action) { } @Override public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } /** * Actually performs the data transfer for a move or copy operation * @param support Info on the drag being performed * @return true if drag/drop operation was successful */ @Override public boolean importData(TransferHandler.TransferSupport support) { if (!canImport(support)) { return false; } // Extract transfer data. DefaultMutableTreeNode[] nodes = null; try { final Transferable t = support.getTransferable(); nodes = (DefaultMutableTreeNode[])t.getTransferData(nodesFlavor); } catch (UnsupportedFlavorException ufe) { System.out.println("Unsupported Flavor: " + ufe.getMessage()); //NON-NLS } catch (java.io.IOException ioe) { System.out.println("I/O error: " + ioe.getMessage()); //NON-NLS } if (nodes == null) { return false; } // Get drop location info. final JTree.DropLocation dl = (JTree.DropLocation)support.getDropLocation(); final TreePath dest = dl.getPath(); final DefaultMutableTreeNode targetNode = (DefaultMutableTreeNode)dest.getLastPathComponent(); final Configurable target = (Configurable)targetNode.getUserObject(); final DefaultMutableTreeNode sourceNode = nodes[0]; // What new index shall we drop it at? -1 means it was dropped directly on the parent item. int childIndex = dl.getChildIndex(); if (childIndex < 0) { if (sourceNode.getParent() == targetNode) { childIndex = 0; // If we've been dragged up to our same parent then drop at top of list. } else { childIndex = targetNode.getChildCount(); // Otherwise we drop it at the bottom } } // This is for Extension editor to override childIndex = checkMinimumIndex(targetNode, childIndex); if (childIndex > targetNode.getChildCount()) { childIndex = targetNode.getChildCount(); } if ((support.getDropAction() & MOVE) == MOVE) { if (!targetNode.isNodeAncestor(sourceNode)) { // Here's we're "moving", so therefore "cutting" the source object from its original location (plain drag) final Configurable cutObj = (Configurable) sourceNode.getUserObject(); final Configurable convertedCutObj = convertChild(target, cutObj); if (sourceNode.getParent() == targetNode) { final int oldIndex = targetNode.getIndex(sourceNode); //BR// If we're being dragged to our same parent, but lower down the list, adjust index to account for the //BR// fact we're about to be cut from it. Such humiliations are the price of keeping the Unique ID manager //BR// copacetic. if (childIndex > oldIndex) { childIndex } // If just moving to same place, report success without doing anything. if (childIndex == oldIndex) { return true; } } if (remove(getParent(sourceNode), cutObj)) { insert(target, convertedCutObj, childIndex); } } } else { // Or, if we're actually making a new copy (ctrl-drag) final Configurable copyBase = (Configurable) sourceNode.getUserObject(); Configurable clone = null; try { clone = convertChild(target, copyBase.getClass().getConstructor().newInstance()); } catch (Throwable t) { ReflectionUtils.handleNewInstanceFailure(t, copyBase.getClass()); } if (clone != null) { clone.build(copyBase.getBuildElement(Builder.createNewDocument())); insert(target, clone, childIndex); updateGpIds(clone); } } return true; } @Override public String toString() { return getClass().getName(); } /** * Self-important data blurp that describes a potential drag/drop source. But there's stuff * about flavor, and who doesn't like flavor? */ public class NodesTransferable implements Transferable { DefaultMutableTreeNode[] nodes; public NodesTransferable(DefaultMutableTreeNode[] nodes) { this.nodes = nodes; } @SuppressWarnings("NullableProblems") //BR// Because I just have no idea @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (!isDataFlavorSupported(flavor)) { throw new UnsupportedFlavorException(flavor); } return nodes; } @Override public DataFlavor[] getTransferDataFlavors() { return flavors; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return nodesFlavor.equals(flavor); } } } }
package com.intellij.execution.junit; import com.intellij.execution.CantRunException; import com.intellij.execution.ConfigurationUtil; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.JavaExecutionUtil; import com.intellij.execution.configurations.RuntimeConfigurationException; import com.intellij.execution.configurations.RuntimeConfigurationWarning; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.SourceScope; import com.intellij.execution.util.JavaParametersUtil; import com.intellij.execution.util.ProgramParametersUtil; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.intellij.refactoring.listeners.RefactoringElementListenerComposite; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.LinkedHashSet; import java.util.Set; public class TestsPattern extends TestPackage { public TestsPattern(JUnitConfiguration configuration, ExecutionEnvironment environment) { super(configuration, environment); } @Override protected TestClassFilter getClassFilter(JUnitConfiguration.Data data) throws CantRunException { return TestClassFilter.create(getSourceScope(), getConfiguration().getConfigurationModule().getModule(), data.getPatternPresentation()); } @NotNull @Override protected String getPackageName(JUnitConfiguration.Data data) { return ""; } @Override protected boolean filterOutputByDirectoryForJunit5(Set<PsiClass> classNames) { return super.filterOutputByDirectoryForJunit5(classNames) && classNames.isEmpty(); } @Override protected void searchTests5(Module module, TestClassFilter classFilter, Set<PsiClass> classes) { searchTests(module, classFilter, classes, true); } @Override protected void searchTests(Module module, TestClassFilter classFilter, Set<PsiClass> classes) { searchTests(module, classFilter, classes, false); } private void searchTests(Module module, TestClassFilter classFilter, Set<PsiClass> classes, boolean junit5) { JUnitConfiguration.Data data = getConfiguration().getPersistentData(); Project project = getConfiguration().getProject(); for (String className : data.getPatterns()) { final PsiClass psiClass = ReadAction.compute(() -> getTestClass(project, className)); if (psiClass != null) { if (ReadAction.compute(() -> JUnitUtil.isTestClass(psiClass))) { classes.add(psiClass); //with method, comma separated } } else { classes.clear(); if (!junit5) {//junit 5 process tests automatically ConfigurationUtil.findAllTestClasses(classFilter, module, classes); } return; } } } @Override protected String getFilters(Set<PsiClass> foundClasses, String packageName) { return foundClasses.isEmpty() ? getConfiguration().getPersistentData().getPatternPresentation() : ""; } private PsiClass getTestClass(Project project, String className) { SourceScope sourceScope = getSourceScope(); GlobalSearchScope searchScope = sourceScope != null ? sourceScope.getGlobalSearchScope() : GlobalSearchScope.allScope(project); return JavaExecutionUtil.findMainClass(project, className.contains(",") ? StringUtil.getPackageName(className, ',') : className, searchScope); } @Override protected boolean configureByModule(Module module) { return module != null; } @Override public String suggestActionName() { return null; } @Nullable @Override public RefactoringElementListener getListener(PsiElement element, JUnitConfiguration configuration) { final RefactoringElementListenerComposite composite = new RefactoringElementListenerComposite(); final JUnitConfiguration.Data data = configuration.getPersistentData(); final Set<String> patterns = data.getPatterns(); for (final String pattern : patterns) { final PsiClass testClass = getTestClass(configuration.getProject(), pattern.trim()); if (testClass != null && testClass.equals(element)) { final RefactoringElementListener listeners = RefactoringListeners.getListeners(testClass, new RefactoringListeners.Accessor<PsiClass>() { private String myOldName = testClass.getQualifiedName(); @Override public void setName(String qualifiedName) { final Set<String> replaced = new LinkedHashSet<>(); for (String currentPattern : patterns) { if (myOldName.equals(currentPattern)) { replaced.add(qualifiedName); myOldName = qualifiedName; } else { replaced.add(currentPattern); } } patterns.clear(); patterns.addAll(replaced); } @Override public PsiClass getPsiElement() { return testClass; } @Override public void setPsiElement(PsiClass psiElement) { if (psiElement == testClass) { setName(psiElement.getQualifiedName()); } } }); if (listeners != null) { composite.addListener(listeners); } } } return composite; } @Override public boolean isConfiguredByElement(JUnitConfiguration configuration, PsiClass testClass, PsiMethod testMethod, PsiPackage testPackage, PsiDirectory testDir) { return false; } @Override public void checkConfiguration() throws RuntimeConfigurationException { JavaParametersUtil.checkAlternativeJRE(getConfiguration()); ProgramParametersUtil.checkWorkingDirectoryExist(getConfiguration(), getConfiguration().getProject(), getConfiguration().getConfigurationModule().getModule()); final JUnitConfiguration.Data data = getConfiguration().getPersistentData(); final Set<String> patterns = data.getPatterns(); if (patterns.isEmpty()) { throw new RuntimeConfigurationWarning(ExecutionBundle.message("no.pattern.error.message")); } final GlobalSearchScope searchScope = GlobalSearchScope.allScope(getConfiguration().getProject()); for (String pattern : patterns) { final String className = pattern.contains(",") ? StringUtil.getPackageName(pattern, ',') : pattern; final PsiClass psiClass = JavaExecutionUtil.findMainClass(getConfiguration().getProject(), className, searchScope); if (psiClass != null && !JUnitUtil.isTestClass(psiClass)) { throw new RuntimeConfigurationWarning(ExecutionBundle.message("class.not.test.error.message", className)); } if (psiClass == null && !pattern.contains("*")) { throw new RuntimeConfigurationWarning(ExecutionBundle.message("class.not.found.error.message", className)); } } } }
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.IntStack; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.GeneralAttrCheck; import org.apache.xerces.validators.schema.SubstitutionGroupComparator; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.schema.identity.Field; import org.apache.xerces.validators.schema.identity.FieldActivator; import org.apache.xerces.validators.schema.identity.IdentityConstraint; import org.apache.xerces.validators.schema.identity.IDValue; import org.apache.xerces.validators.schema.identity.Key; import org.apache.xerces.validators.schema.identity.KeyRef; import org.apache.xerces.validators.schema.identity.Selector; import org.apache.xerces.validators.schema.identity.Unique; import org.apache.xerces.validators.schema.identity.ValueStore; import org.apache.xerces.validators.schema.identity.XPathMatcher; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.validators.datatype.StateMessageDatatype; import org.apache.xerces.validators.datatype.IDREFDatatypeValidator; import org.apache.xerces.validators.datatype.IDDatatypeValidator; import org.apache.xerces.validators.datatype.ENTITYDatatypeValidator; import org.apache.xerces.validators.datatype.NOTATIONDatatypeValidator; import org.apache.xerces.validators.datatype.UnionDatatypeValidator; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler, FieldActivator // for identity constraints { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; /** Compile to true to debug identity constraints. */ protected static final boolean DEBUG_IDENTITY_CONSTRAINTS = false; /** Compile to true to debug value stores. */ protected static final boolean DEBUG_VALUE_STORES = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k private Hashtable fIdDefs = new Hashtable(); private Hashtable fIdREFDefs = new Hashtable(); private StateMessageDatatype fValidateIDRef = new StateMessageDatatype() { private Hashtable fIdDefs; public Object getDatatypeObject(){ return(Object) fIdDefs; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_VALIDATE; } public void setDatatypeObject( Object data ){ fIdDefs = (Hashtable) data; } }; private StateMessageDatatype fCheckIDRef = new StateMessageDatatype() { private Object[] fLists; public Object getDatatypeObject(){ return(Object) fLists; } public int getDatatypeState(){ return IDREFDatatypeValidator.IDREF_CHECKID; } public void setDatatypeObject( Object data ){ fLists = (Object[]) data; } }; private StateMessageDatatype fValidateEntity = new StateMessageDatatype() { private Object fData; public Object getDatatypeObject(){ return fData; } public int getDatatypeState(){ return ENTITYDatatypeValidator.ENTITY_VALIDATE; } public void setDatatypeObject( Object data ){ fData = data; } }; // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // attribute validators private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fSchemaValidation = true; private boolean fSchemaValidationFullChecking = false; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; private boolean fNormalizeAttributeValues = true; private boolean fLoadDTDGrammar = true; // Private temporary variables private Hashtable fLocationUriPairs = new Hashtable(10); // declarations private String fExternalSchemas = null; private String fExternalNoNamespaceSchema = null; private DOMParser fSchemaGrammarParser = null; private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8]; //OTWI: on-the-way-in // store the content model private XMLContentModel[] fContentModelStack = new XMLContentModel[8]; // >= 0 normal state; -1: error; -2: on-the-way-out private int[] fContentModelStateStack = new int[8]; // how many child elements have succefully validated private int[] fContentModelEleCount = new int[8]; private int[] fValidationFlagStack = new int[8]; private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private static final int sizeQNameParts = 8; private QName[] fElementQNamePartsStack = new QName[sizeQNameParts]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = StringPool.EMPTY_STRING; private int fEmptyURI = StringPool.EMPTY_STRING; private int fXsiPrefix = - 1; private int fXsiURI = -2; private int fXsiTypeAttValue = -1; private DatatypeValidator fXsiTypeValidator = null; private boolean fNil = false; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = StringPool.EMPTY_STRING; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; private boolean fNeedValidationOff = false; //Schema Normalization private static final boolean DEBUG_NORMALIZATION = false; private DatatypeValidator fCurrentDV = null; //current datatype validator private boolean fFirstChunk = true; // got first chunk in characters() (SAX) private boolean fTrailing = false; // Previous chunk had a trailing space private short fWhiteSpace = DatatypeValidator.COLLAPSE; //whiteSpace: preserve/replace/collapse private StringBuffer fStringBuffer = new StringBuffer(CHUNK_SIZE); //holds normalized str value private StringBuffer fTempBuffer = new StringBuffer(CHUNK_SIZE); //holds unnormalized str value // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; //Datatype Registry private DatatypeValidatorFactoryImpl fDataTypeReg = null; private DatatypeValidator fValID = null; private DatatypeValidator fValIDRef = null; private DatatypeValidator fValIDRefs = null; private DatatypeValidator fValENTITY = null; private DatatypeValidator fValENTITIES = null; private DatatypeValidator fValNMTOKEN = null; private DatatypeValidator fValNMTOKENS = null; private DatatypeValidator fValNOTATION = null; // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement, characters * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // store the substitution group comparator protected SubstitutionGroupComparator fSGComparator = null; // on which grammars we have checked UPA protected Hashtable UPACheckedGrammarURIs = new Hashtable(); protected static Object fgNullObject = new Object(); // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fValidateEntity.setDatatypeObject(new Object[]{entityHandler, stringPool}); fValidateIDRef.setDatatypeObject(fIdREFDefs); fCheckIDRef.setDatatypeObject(new Object[]{fIdDefs, fIdREFDefs}); fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); for (int i = 0; i < sizeQNameParts; i++) { fElementQNamePartsStack[i] = new QName(); } init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; fSGComparator = new SubstitutionGroupComparator(fGrammarResolver, fStringPool, fErrorReporter); if (fValidating) { //optimization -el initDataTypeValidators(); } } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; //optimization: don't create unnecessary DatatypeValidators. - el if (fValidating) { initDataTypeValidators(); } } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether Schema support is on/off. */ public void setSchemaValidationEnabled(boolean flag) { fSchemaValidation = flag; } /** Returns true if Schema support is on. */ public boolean getSchemaValidationEnabled() { return fSchemaValidation; } /** Sets whether full Schema error checking is on/off */ public void setSchemaFullCheckingEnabled(boolean flag) { fSchemaValidationFullChecking = flag; } //Properties on the parser to allow the user to specify //XML schemas externaly public void setExternalSchemas(Object value){ fExternalSchemas = (String)value; } public void setExternalNoNamespaceSchema(Object value){ fExternalNoNamespaceSchema = (String)value; } public String getExternalSchemas(){ return fExternalSchemas; } public String getExternalNoNamespaceSchema(){ return fExternalNoNamespaceSchema; } /** Returns true if full Schema checking is on. */ public boolean getSchemaFullCheckingEnabled() { return fSchemaValidationFullChecking; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; //optimization: don't create unnecessary DatatypeValidators. - el if (fValidating) { initDataTypeValidators(); } } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets fNormalizeAttributeValues **/ public void setNormalizeAttributeValues(boolean normalize){ fNormalizeAttributeValues = normalize; } /** Sets fLoadDTDGrammar when validation is off **/ public void setLoadDTDGrammar(boolean loadDG){ if (fValidating) { fLoadDTDGrammar = true; } else { fLoadDTDGrammar = loadDG; } } /** Returns fLoadDTDGrammar **/ public boolean getLoadDTDGrammar() { return fLoadDTDGrammar; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // FieldActivator methods /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint) throws Exception { for(int i=0; i<identityConstraint.getFieldCount(); i++) { Field field = identityConstraint.getFieldAt(i); ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(field); valueStore.startValueScope(); } } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field) throws Exception { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: activateField(\""+field+"\")"); } ValueStore valueStore = fValueStoreCache.getValueStoreFor(field); field.setMayMatch(true); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(fStringPool); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint) throws Exception { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** * Normalize whitespace in an XMLString according to the rules of attribute * value normalization - converting all whitespace characters to space * characters. * In addition for attributes of type other than CDATA: trim leading and * trailing spaces and collapse spaces (0x20 only). * * @param value The string to normalize. * @returns 0 if no triming is done or if there is neither leading nor * trailing whitespace, * 1 if there is only leading whitespace, * 2 if there is only trailing whitespace, * 3 if there is both leading and trailing whitespace. */ private int normalizeWhitespace( StringBuffer chars, boolean collapse) { int length = fTempBuffer.length(); fStringBuffer.setLength(0); boolean skipSpace = collapse; boolean sawNonWS = false; int leading = 0; int trailing = 0; int c; for (int i = 0; i < length; i++) { c = chars.charAt(i); if (c == 0x20 || c == 0x0D || c == 0x0A || c == 0x09) { if (!skipSpace) { // take the first whitespace as a space and skip the others fStringBuffer.append(' '); skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = 1; } } else { fStringBuffer.append((char)c); skipSpace = false; sawNonWS = true; } } if (skipSpace) { c = fStringBuffer.length(); if ( c != 0) { // if we finished on a space trim it but also record it fStringBuffer.setLength (--c); trailing = 2; } else if (leading != 0 && !sawNonWS) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = 2; } } //value.setValues(fStringBuffer); return collapse ? leading + trailing : 0; } /** Process characters. Schema Normalization*/ public void processCharacters(char[] chars, int offset, int length) throws Exception { if (DEBUG_NORMALIZATION) { System.out.println("==>processCharacters(char[] chars, int offset, int length"); } if (fValidating) { if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { if (DEBUG_NORMALIZATION) { System.out.println("==>charDataInContent()"); } charDataInContent(); } if (fBufferDatatype) { if (fFirstChunk && fGrammar!=null) { fGrammar.getElementDecl(fCurrentElementIndex, fTempElementDecl); fCurrentDV = fTempElementDecl.datatypeValidator; if (fCurrentDV !=null) { fWhiteSpace = fCurrentDV.getWSFacet(); } } if (DEBUG_NORMALIZATION) { System.out.println("Start schema datatype normalization <whiteSpace value=" +fWhiteSpace+">"); } if (fWhiteSpace == DatatypeValidator.PRESERVE) { //do not normalize fDatatypeBuffer.append(chars, offset, length); } else { fTempBuffer.setLength(0); fTempBuffer.append(chars, offset, length); int spaces = normalizeWhitespace(fTempBuffer, (fWhiteSpace==DatatypeValidator.COLLAPSE)); int nLength = fStringBuffer.length(); if (nLength > 0) { if (!fFirstChunk && (fWhiteSpace==DatatypeValidator.COLLAPSE) && fTrailing) { fStringBuffer.insert(0, ' '); nLength++; } if ((length-offset)!=nLength) { char[] newChars = new char[nLength]; fStringBuffer.getChars(0, nLength , newChars, 0); chars = newChars; offset = 0; length = nLength; } else { fStringBuffer.getChars(0, nLength , chars, 0); } fDatatypeBuffer.append(chars, offset, length); fDocumentHandler.characters(chars, offset, length); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(chars, offset, length); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } fTrailing = (spaces > 1)?true:false; fFirstChunk = false; return; } } } fFirstChunk = false; fDocumentHandler.characters(chars, offset, length); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(chars, offset, length); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } /** Process characters. */ public void processCharacters(int data) throws Exception { if (fValidating) { if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { charDataInContent(); } if (fBufferDatatype) { fGrammar.getElementDecl(fCurrentElementIndex, fTempElementDecl); //REVISIT: add normalization according to datatypes fCurrentDV = fTempElementDecl.datatypeValidator; if (fCurrentDV !=null) { fWhiteSpace = fCurrentDV.getWSFacet(); } if (fWhiteSpace == DatatypeValidator.PRESERVE) { //no normalization done fDatatypeBuffer.append(fStringPool.toString(data)); } else { String str = fStringPool.toString(data); int length = str.length(); fTempBuffer.setLength(0); fTempBuffer.append(str); int spaces = normalizeWhitespace(fTempBuffer, (fWhiteSpace == DatatypeValidator.COLLAPSE)); if (fWhiteSpace != DatatypeValidator.PRESERVE) { //normalization was done. fStringPool.releaseString(data); data = fStringPool.addString(fStringBuffer.toString()); } fDatatypeBuffer.append(fStringBuffer.toString()); } } } fDocumentHandler.characters(data); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); if (count > 0) { String text = fStringPool.toString(data); char[] chars = new char[text.length()]; int offset = 0; int length = chars.length; text.getChars(offset, length, chars, offset); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } } /** Process whitespace. */ public void processWhitespace(char[] chars, int offset, int length) throws Exception { if (fInElementContent) { if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) { reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION); } fDocumentHandler.ignorableWhitespace(chars, offset, length); } else { if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { charDataInContent(); } fDocumentHandler.characters(chars, offset, length); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(chars, offset, length); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } } // processWhitespace(char[],int,int) /** Process whitespace. */ public void processWhitespace(int data) throws Exception { if (fInElementContent) { if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) { reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION); } fDocumentHandler.ignorableWhitespace(data); } else { if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) { charDataInContent(); } fDocumentHandler.characters(data); // call all active identity constraints int count = fMatcherStack.getMatcherCount(); if (count > 0) { String text = fStringPool.toString(data); char[] chars = new char[text.length()]; int offset = 0; int length = chars.length; text.getChars(length, length, chars, offset); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(chars, offset, length); } } } } // processWhitespace(int) // XMLDocumentScanner.EventHandler methods /** Scans element type. */ public void scanElementType(XMLEntityHandler.EntityReader entityReader, char fastchar, QName element) throws Exception { if (!fNamespacesEnabled) { element.clear(); element.localpart = entityReader.scanName(fastchar); element.rawname = element.localpart; } else { entityReader.scanQName(fastchar, element); if (entityReader.lookingAtChar(':', false)) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_TWO_COLONS_IN_QNAME, XMLMessages.P5_INVALID_CHARACTER, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); entityReader.skipPastNmtoken(' '); } } } // scanElementType(XMLEntityHandler.EntityReader,char,QName) /** Scans expected element type. */ public boolean scanExpectedElementType(XMLEntityHandler.EntityReader entityReader, char fastchar, QName element) throws Exception { if (fCurrentElementCharArrayRange == null) { fCurrentElementCharArrayRange = fStringPool.createCharArrayRange(); } fStringPool.getCharArrayRange(fCurrentElement.rawname, fCurrentElementCharArrayRange); return entityReader.scanExpectedName(fastchar, fCurrentElementCharArrayRange); } // scanExpectedElementType(XMLEntityHandler.EntityReader,char,QName) /** Scans attribute name. */ public void scanAttributeName(XMLEntityHandler.EntityReader entityReader, QName element, QName attribute) throws Exception { if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } if (!fNamespacesEnabled) { attribute.clear(); attribute.localpart = entityReader.scanName('='); attribute.rawname = attribute.localpart; } else { entityReader.scanQName('=', attribute); if (entityReader.lookingAtChar(':', false)) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_TWO_COLONS_IN_QNAME, XMLMessages.P5_INVALID_CHARACTER, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); entityReader.skipPastNmtoken(' '); } } } // scanAttributeName(XMLEntityHandler.EntityReader,QName,QName) /** Call start document. */ public void callStartDocument() throws Exception { if (!fCalledStartDocument) { fDocumentHandler.startDocument(); fCalledStartDocument = true; if (fValidating) { fValueStoreCache.startDocument(); } } } /** Call end document. */ public void callEndDocument() throws Exception { if (fCalledStartDocument) { if (fValidating) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: ValueStoreCache#endDocument()"); } fValueStoreCache.endDocument(); } fDocumentHandler.endDocument(); } } /** Call XML declaration. */ public void callXMLDecl(int version, int encoding, int standalone) throws Exception { fDocumentHandler.xmlDecl(version, encoding, standalone); } public void callStandaloneIsYes() throws Exception { // standalone = "yes". said XMLDocumentScanner. fStandaloneReader = fEntityHandler.getReaderId() ; } /** Call text declaration. */ public void callTextDecl(int version, int encoding) throws Exception { fDocumentHandler.textDecl(version, encoding); } /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { rootElementSpecified(element); fStringPool.resetShuffleCount(); } if (fGrammar != null && fGrammarIsDTDGrammar) { fAttrListHandle = addDTDDefaultAttributes(element, fAttrList, fAttrListHandle, fValidating, fStandaloneReader != -1); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } if (!fSeenRootElement) { fSeenRootElement = true; } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { //fAttrList.endAttrList(); int dupAttrs[]; if ((dupAttrs = fAttrList.endAttrList()) != null) { Object[] args = {fStringPool.toString(element.rawname), null}; for (int i = 0; i < dupAttrs.length; i++) { args[1] = fStringPool.toString(dupAttrs[i]); fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XMLNS_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_UNIQUE, XMLMessages.WFC_UNIQUE_ATT_SPEC, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } // activate identity constraints if (fValidating && fGrammar != null && fGrammarIsSchemaGrammar) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: pushing context - element: "+fStringPool.toString(element.rawname)); } fValueStoreCache.startElement(); fMatcherStack.pushContext(); int eindex = fGrammar.getElementDeclIndex(element, -1); if (eindex != -1) { fGrammar.getElementDecl(eindex, fTempElementDecl); fValueStoreCache.initValueStoresFor(fTempElementDecl); int uCount = fTempElementDecl.unique.size(); for (int i = 0; i < uCount; i++) { activateSelectorFor((IdentityConstraint)fTempElementDecl.unique.elementAt(i)); } int kCount = fTempElementDecl.key.size(); for (int i = 0; i < kCount; i++) { activateSelectorFor((IdentityConstraint)fTempElementDecl.key.elementAt(i)); } int krCount = fTempElementDecl.keyRef.size(); for (int i = 0; i < krCount; i++) { activateSelectorFor((IdentityConstraint)fTempElementDecl.keyRef.elementAt(i)); } } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher.toString()+"#startElement("+fStringPool.toString(element.rawname)+")"); } matcher.startElement(element, fAttrList, fAttrListHandle, fCurrentElementIndex, (SchemaGrammar)fGrammar); } } // call handler fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fElementDepth++; fAttrListHandle = -1; //if (fElementDepth >= 0) { // REVISIT: Why are doing anything if the grammar is null? -Ac if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length <= fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement); fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; if (fNeedValidationOff) { fValidating = false; fNeedValidationOff = false; } if (fValidating && fGrammarIsSchemaGrammar) { pushContentLeafStack(); } else { fContentModelStateStack[fElementDepth] = -2; } fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void activateSelectorFor(IdentityConstraint ic) throws Exception { Selector selector = ic.getSelector(); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: XMLValidator#activateSelectorFor("+selector+')'); } FieldActivator activator = this; if(selector == null) return; XPathMatcher matcher = selector.createMatcher(activator); fMatcherStack.addMatcher(matcher); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#startDocumentFragment()"); } matcher.startDocumentFragment(fStringPool); } private void pushContentLeafStack() throws Exception { int contentType = getContentSpecType(fCurrentElementIndex); if ( contentType == XMLElementDecl.TYPE_CHILDREN || contentType == XMLElementDecl.TYPE_MIXED_COMPLEX) { XMLContentModel cm = getElementContentModel(fCurrentElementIndex); ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector(); if (cm != null) { fContentLeafStack[fElementDepth] = cv; //OTWI: on-the-way-in fContentModelStack[fElementDepth] = cm; // for DFA with wildcard, we validate on-the-way-in // for other content models, we do it on-the-way-out if (cm instanceof DFAContentModel && cv != null) fContentModelStateStack[fElementDepth] = 0; else fContentModelStateStack[fElementDepth] = -2; fContentModelEleCount[fElementDepth] = 0; } } else { fContentModelStateStack[fElementDepth] = -2; } } private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementQNamePartsStack.length ) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; QName[] newStackOfQueue = new QName[newElementDepth * 2]; System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth ); fElementQNamePartsStack = newStackOfQueue; QName qname = fElementQNamePartsStack[newElementDepth]; if (qname == null) { for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) { fElementQNamePartsStack[i] = new QName(); } } newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth); fValidationFlagStack = newStack; ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2]; System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth); fContentLeafStack = newStackV; //OTWI: on-the-way-in XMLContentModel[] newStackCM = new XMLContentModel[newElementDepth * 2]; System.arraycopy(fContentModelStack, 0, newStackCM, 0, newElementDepth); fContentModelStack = newStackCM; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentModelStateStack, 0, newStack, 0, newElementDepth); fContentModelStateStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentModelEleCount, 0, newStack, 0, newElementDepth); fContentModelEleCount = newStack; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType)}, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.println("fCurrentContentSpecType : " + fCurrentContentSpecType ); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) { reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), "EMPTY"); } else reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; // call matchers and de-activate context if(fGrammarIsSchemaGrammar) { int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#endElement("+fStringPool.toString(fCurrentElement.rawname)+")"); } matcher.endElement(fCurrentElement, fCurrentElementIndex, (SchemaGrammar)fGrammar); } if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: popping context - element: "+fStringPool.toString(fCurrentElement.rawname)); } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if((id = matcher.getIDConstraint()) != null && id.getType() != IdentityConstraint.KEYREF) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#endDocumentFragment()"); } matcher.endDocumentFragment(); fValueStoreCache.transplant(id); } else if (id == null) matcher.endDocumentFragment(); } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i XPathMatcher matcher = fMatcherStack.getMatcherAt(i); IdentityConstraint id; if((id = matcher.getIDConstraint()) != null && id.getType() == IdentityConstraint.KEYREF) { if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: "+matcher+"#endDocumentFragment()"); } ValueStoreBase values = fValueStoreCache.getValueStoreFor(id); if(values != null) // nothing to do if nothing matched! values.endDocumentFragment(); matcher.endDocumentFragment(); } } fValueStoreCache.endElement(); } } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating ) { try { this.fValIDRef.validate( null, this.fCheckIDRef ); //Do final IDREF validation round this.fIdDefs.clear(); this.fIdREFDefs.clear(); } catch ( InvalidDatatypeValueException ex ) { reportRecoverableXMLError( ex.getMajorCode(), ex.getMinorCode(), ex.getMessage() ); } } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; if (fNamespacesEnabled) { //If Namespace enable then localName != rawName fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname; } fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname; fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri; fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false; fCurrentScope = fScopeStack[fElementDepth]; if ( DEBUG_SCHEMA_VALIDATION ) { System.out.println("+++++ currentElement : " + fStringPool.toString(elementType)+ "\n fCurrentElementIndex : " + fCurrentElementIndex + "\n fCurrentScope : " + fCurrentScope + "\n fCurrentContentSpecType : " + fCurrentContentSpecType + "\n++++++++++++++++++++++++++++++++++++++++++++++++" ); } // if enclosing element's Schema is different, need to switch "context" if ( fGrammarNameSpaceIndex != fGrammarNameSpaceIndexStack[fElementDepth] ) { fGrammarNameSpaceIndex = fGrammarNameSpaceIndexStack[fElementDepth]; if ( fValidating && fGrammarIsSchemaGrammar ) if (fGrammarNameSpaceIndex < StringPool.EMPTY_STRING) { fGrammar = null; fGrammarIsSchemaGrammar = false; fGrammarIsDTDGrammar = false; } else if (!switchGrammar(fGrammarNameSpaceIndex)) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 1: " + fStringPool.toString(fGrammarNameSpaceIndex) + " , can not be found"); } } if (fValidating) { fBufferDatatype = false; } fInElementContent = (fCurrentContentSpecType == XMLElementDecl.TYPE_CHILDREN); } // callEndElement(int) /** Call start CDATA section. */ public void callStartCDATA() throws Exception { if (fValidating && fInElementContent) { charDataInContent(); } fDocumentHandler.startCDATA(); } /** Call end CDATA section. */ public void callEndCDATA() throws Exception { fDocumentHandler.endCDATA(); } /** Call characters. */ public void callCharacters(int ch) throws Exception { if (fCharRefData == null) { fCharRefData = new char[2]; } int count = (ch < 0x10000) ? 1 : 2; if (count == 1) { fCharRefData[0] = (char)ch; } else { fCharRefData[0] = (char)(((ch-0x00010000)>>10)+0xd800); fCharRefData[1] = (char)(((ch-0x00010000)&0x3ff)+0xdc00); } if (fValidating && (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY)) { charDataInContent(); } if (fValidating) { if (fBufferDatatype) { fDatatypeBuffer.append(fCharRefData,0,1); } } if (fSendCharDataAsCharArray) { fDocumentHandler.characters(fCharRefData, 0, count); } else { int index = fStringPool.addString(new String(fCharRefData, 0, count)); fDocumentHandler.characters(index); } // call all active identity constraints int matcherCount = fMatcherStack.getMatcherCount(); for (int i = 0; i < matcherCount; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (DEBUG_IDENTITY_CONSTRAINTS) { String text = new String(fCharRefData, 0, count); System.out.println("<IC>: "+matcher.toString()+"#characters("+text+")"); } matcher.characters(fCharRefData, 0, count); } } // callCharacters(int) /** Call processing instruction. */ public void callProcessingInstruction(int target, int data) throws Exception { fDocumentHandler.processingInstruction(target, data); } /** Call comment. */ public void callComment(int comment) throws Exception { fDocumentHandler.comment(comment); } // NamespacesScope.NamespacesHandler methods /** Start a new namespace declaration scope. */ public void startNamespaceDeclScope(int prefix, int uri) throws Exception { fDocumentHandler.startNamespaceDeclScope(prefix, uri); } /** End a namespace declaration scope. */ public void endNamespaceDeclScope(int prefix) throws Exception { fDocumentHandler.endNamespaceDeclScope(prefix); } // attributes // other /** Sets the root element. */ public void setRootElementType(QName rootElement) { fRootElement.setValues(rootElement); } /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable schema error. */ private void reportSchemaError(int code, Object[] args) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, code, SchemaMessageProvider.MSG_NONE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportSchemaError(int,Object) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getElementContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // initialization /** Reset pool. */ private void poolReset() { if (fValidating) { this.fIdDefs.clear(); this.fIdREFDefs.clear(); } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidateEntity.setDatatypeObject(new Object[]{fEntityHandler, stringPool}); fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = StringPool.EMPTY_STRING; fEmptyURI = StringPool.EMPTY_STRING; fXsiPrefix = - 1; fXsiTypeValidator = null; // xsi:nill fNil = false; fGrammar = null; fGrammarNameSpaceIndex = StringPool.EMPTY_STRING; // we reset fGrammarResolver in XMLParser before passing it to Validator fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; //Normalization fCurrentDV = null; fFirstChunk = true; fTrailing = false; fWhiteSpace = DatatypeValidator.COLLAPSE; fMatcherStack.clear(); UPACheckedGrammarURIs.clear(); //REVISIT: fExternalSchemas/fExternalNoNamespaceSchema is not reset 'cause we don't have grammar cashing in Xerces-J // reconsider implementation when we have grammar chashing init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); } // init() /** * This method should only be invoked when validation * is turn on. * fDataTypeReg object of type DatatypeValidatorFactoryImpl * needs to be initialized. * In the XMLValidator the table will be by default * first initialized to 9 validators used by DTD * validation. * These Validators are known. * Later on if we ever find a Schema and need to do * Schema validation then we will expand this * registry table of fDataTypeReg. */ private void initDataTypeValidators() { //Initialize Validators //Datatype Registry if ( fGrammarResolver != null ) { fDataTypeReg = (DatatypeValidatorFactoryImpl) fGrammarResolver.getDatatypeRegistry(); fDataTypeReg.initializeDTDRegistry(); } if ( fDataTypeReg != null ) { fValID = fDataTypeReg.getDatatypeValidator("ID" ); fValIDRef = fDataTypeReg.getDatatypeValidator("IDREF" ); fValIDRefs = fDataTypeReg.getDatatypeValidator("IDREFS" ); fValENTITY = fDataTypeReg.getDatatypeValidator("ENTITY" ); fValENTITIES = fDataTypeReg.getDatatypeValidator("ENTITIES" ); fValNMTOKEN = fDataTypeReg.getDatatypeValidator("NMTOKEN"); fValNMTOKENS = fDataTypeReg.getDatatypeValidator("NMTOKENS"); fValNOTATION = fDataTypeReg.getDatatypeValidator("NOTATION" ); } } // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) check that FIXED attrs have matching value (V_TAGd) // (4) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); int attPrefix = fTempAttDecl.name.prefix; int attName = fTempAttDecl.name.localpart; int attType = attributeTypeName(fTempAttDecl); int attDefType =fTempAttDecl.defaultType; int attValue = -1 ; if (fTempAttDecl.defaultValue != null ) { attValue = fStringPool.addSymbol(fTempAttDecl.defaultValue); } boolean specified = false; boolean required = (attDefType & XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) > 0; boolean prohibited = (attDefType & XMLAttributeDecl.DEFAULT_TYPE_PROHIBITED) > 0; boolean fixed = (attDefType & XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0; if (firstCheck != -1) { boolean cdata = attType == fCDATASymbol; if (!cdata || required || prohibited || attValue != -1) { int i = attrList.getFirstAttr(firstCheck); while (i != -1 && (lastCheck == -1 || i <= lastCheck)) { if ( (fGrammarIsDTDGrammar && (attrList.getAttrName(i) == fTempAttDecl.name.rawname)) || ( fStringPool.equalNames(attrList.getAttrLocalpart(i), attName) && fStringPool.equalNames(attrList.getAttrURI(i), fTempAttDecl.name.uri) ) ) { if (prohibited && validationEnabled) { Object[] args = { fStringPool.toString(elementNameIndex), fStringPool.toString(attName)}; fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.ProhibitedAttributePresent, SchemaMessageProvider.MSG_NONE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } specified = true; break; } i = attrList.getNextAttr(i); } } } if (!specified) { if (required) { if (validationEnabled) { Object[] args = { fStringPool.toString(elementNameIndex), fStringPool.toString(attName)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED, XMLMessages.VC_REQUIRED_ATTRIBUTE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } else if (attValue != -1) { if (validationEnabled && standalone ) { if ( fGrammarIsDTDGrammar && ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attlistIndex) ) { Object[] args = { fStringPool.toString(elementNameIndex), fStringPool.toString(attName)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } if (validationEnabled) { validateUsingDV (fTempAttDecl.datatypeValidator, fStringPool.toString(attValue), true); } if (attrIndex == -1) { attrIndex = attrList.startAttrList(); } // REVISIT: Validation. What should the prefix be? fTempQName.setValues(attPrefix, attName, attName, fTempAttDecl.name.uri); int newAttr = attrList.addAttr(fTempQName, attValue, attType, false, false); if (lastCheck == -1) { lastCheck = newAttr; } } } attlistIndex = fGrammar.getNextAttributeDeclIndex(attlistIndex); } return attrIndex; } // addDefaultAttributes(int,XMLAttrList,int,boolean,boolean):int /** addDTDDefaultAttributes. */ private int addDTDDefaultAttributes(QName element, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) int elementIndex = fGrammar.getElementDeclIndex(element, -1); if (elementIndex == -1) { return attrIndex; } fGrammar.getElementDecl(elementIndex,fTempElementDecl); int elementNameIndex = fTempElementDecl.name.rawname; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** Queries the content model for the specified element index. */ /** Returns an attribute definition for an element type. */ /** Returns an attribute definition for an element type. */ /** Root element specified. */ /** Switchs to correct validating symbol tables when Schema changes.*/ /** Binds namespaces to the element and attributes. */ /* * for <notation> must resolve values "b:myNotation" * * @param value string value of element or attribute * @return * @exception Exception */ private String bindNotationURI (String value) throws Exception{ int colonP = value.indexOf(":"); String prefix = ""; String localpart = value; if (colonP > -1) { prefix = value.substring(0,colonP); localpart = value.substring(colonP+1); } String uri = ""; int uriIndex = StringPool.EMPTY_STRING; if (fNamespacesScope != null) { //if prefix.equals("") it would bing to xmlns URI uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)); if (uriIndex > 0) { return fStringPool.toString(uriIndex)+":"+localpart; } else if (fGrammarNameSpaceIndex!=-1){ // REVISIT: try binding to current namespace // trying to solve the case: // might not work in all cases (need clarification from schema?) return fStringPool.toString( fGrammarNameSpaceIndex)+":"+localpart; } } return value; } static class Resolver implements EntityResolver { // Constants private static final String SYSTEM[] = { "http: "http: "http: }; private static final String PATH[] = { "structures.dtd", "datatypes.dtd", "versionInfo.ent", }; // Data private DefaultEntityHandler fEntityHandler; // Constructors public Resolver(DefaultEntityHandler handler) { fEntityHandler = handler; } // EntityResolver methods public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { // looking for the schema DTDs? for (int i = 0; i < SYSTEM.length; i++) { if (systemId.equals(SYSTEM[i])) { InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i])); source.setPublicId(publicId); source.setSystemId(systemId); return source; } } // first try to resolve using user's entity resolver EntityResolver resolver = fEntityHandler.getEntityResolver(); if (resolver != null) { InputSource source = resolver.resolveEntity(publicId, systemId); if (source != null) { return source; } } // use default resolution return new InputSource(fEntityHandler.expandSystemId(systemId)); } // resolveEntity(String,String):InputSource } // class Resolver static class ErrorHandler implements org.xml.sax.ErrorHandler { /** Warning. */ public void warning(SAXParseException ex) { System.err.println("[Warning] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Error. */ public void error(SAXParseException ex) { System.err.println("[Error] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Fatal error. */ public void fatalError(SAXParseException ex) { System.err.println("[Fatal Error] "+ getLocationString(ex)+": "+ ex.getMessage()); //throw ex; } // Private methods /** Returns a string of the location. */ private String getLocationString(SAXParseException ex) { StringBuffer str = new StringBuffer(); String systemId_ = ex.getSystemId(); if (systemId_ != null) { int index = systemId_.lastIndexOf('/'); if (index != -1) systemId_ = systemId_.substring(index + 1); str.append(systemId_); } str.append(':'); str.append(ex.getLineNumber()); str.append(':'); str.append(ex.getColumnNumber()); return str.toString(); } // getLocationString(SAXParseException):String } private int attributeTypeName(XMLAttributeDecl attrDecl) { switch (attrDecl.type) { case XMLAttributeDecl.TYPE_ENTITY: { return attrDecl.list ? fENTITIESSymbol : fENTITYSymbol; } case XMLAttributeDecl.TYPE_ENUMERATION: { String enumeration = fStringPool.stringListAsString(attrDecl.enumeration); return fStringPool.addSymbol(enumeration); } case XMLAttributeDecl.TYPE_ID: { return fIDSymbol; } case XMLAttributeDecl.TYPE_IDREF: { return attrDecl.list ? fIDREFSSymbol : fIDREFSymbol; } case XMLAttributeDecl.TYPE_NMTOKEN: { return attrDecl.list ? fNMTOKENSSymbol : fNMTOKENSymbol; } case XMLAttributeDecl.TYPE_NOTATION: { return fNOTATIONSymbol; } } return fCDATASymbol; } /** Validates element and attributes. */ private void validateElementAndAttributes(QName element, XMLAttrList attrList) throws Exception { if ((fGrammarIsSchemaGrammar && fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )|| (fGrammar == null && !fValidating && !fNamespacesEnabled) ) { fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; if (fAttrListHandle != -1) { //fAttrList.endAttrList(); int dupAttrs[]; if ((dupAttrs = fAttrList.endAttrList()) != null) { Object[] args = {fStringPool.toString(element.rawname), null}; for (int i = 0; i < dupAttrs.length; i++) { args[1] = fStringPool.toString(dupAttrs[i]); fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XMLNS_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_UNIQUE, XMLMessages.WFC_UNIQUE_ATT_SPEC, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } int index = fAttrList.getFirstAttr(fAttrListHandle); while (index != -1) { if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) { fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index)); break; } index = fAttrList.getNextAttr(index); } } return; } int elementIndex = -1; int contentSpecType = -1; boolean skipThisOne = false; boolean laxThisOne = false; if ( fGrammarIsSchemaGrammar && fElementDepth > -1 && fContentLeafStack[fElementDepth] != null ) { ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth]; //OTWI: on-the-way-in if (fContentModelStateStack[fElementDepth] >= 0) { // get the position of the current element in the content model int pos = ((DFAContentModel)fContentModelStack[fElementDepth]). oneTransition(element, fContentModelStateStack, fElementDepth); // if it's a valid child, increase succeful count // and check whether we need to lax or skip this one if (pos >= 0) { fContentModelEleCount[fElementDepth]++; switch (cv.leafTypes[pos]) { case XMLContentSpec.CONTENTSPECNODE_ANY_SKIP: case XMLContentSpec.CONTENTSPECNODE_ANY_NS_SKIP: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP: skipThisOne = true; break; case XMLContentSpec.CONTENTSPECNODE_ANY_LAX: case XMLContentSpec.CONTENTSPECNODE_ANY_NS_LAX: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX: laxThisOne = true; break; } } } } if (skipThisOne) { fNeedValidationOff = true; } else { //REVISIT: is this the right place to check on if the Schema has changed? TraverseSchema.ComplexTypeInfo baseTypeInfo = null; if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex); if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != StringPool.EMPTY_STRING) { fGrammarNameSpaceIndex = element.uri; boolean success = switchGrammar(fGrammarNameSpaceIndex); if (!success && !laxThisOne) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex) + " , can not be found"); } } if ( fGrammar != null ) { if (DEBUG_SCHEMA_VALIDATION) { System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+ " localpart: '" + fStringPool.toString(element.localpart) +"' and scope : " + fCurrentScope+"\n"); } elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope); if (elementIndex == -1 ) { elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE); } if (elementIndex == -1) { // if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) { int aGrammarNSIndex = fGrammarNameSpaceIndex; while (baseTypeInfo != null) { String baseTName = baseTypeInfo.typeName; if (!baseTName.startsWith(" int comma = baseTName.indexOf(','); aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim()); if (aGrammarNSIndex != fGrammarNameSpaceIndex) { if ( !switchGrammar(aGrammarNSIndex) ) { break; //exit the loop in this case } fGrammarNameSpaceIndex = aGrammarNSIndex; } } elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined); if (elementIndex > -1 ) { //System.out.println("found element index for " + fStringPool.toString(element.localpart)); // update the current Grammar NS index if resolving element succeed. break; } baseTypeInfo = baseTypeInfo.baseComplexTypeInfo; } // if *still* can't find it, try a grammar with no targetNamespace if(elementIndex == -1 && element.uri == StringPool.EMPTY_STRING) { boolean success = switchGrammar(element.uri); if(success) { fGrammarNameSpaceIndex = element.uri; elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE); } } } //if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN if ( element.uri == StringPool.EMPTY_STRING && elementIndex == -1 && fNamespacesScope != null ) { elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE); // REVISIT: // this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there // is a "noNamespaceSchemaLocation" specified, and element element.uri = StringPool.EMPTY_STRING; } if (elementIndex == -1) { if (laxThisOne) { fNeedValidationOff = true; } else if (DEBUG_SCHEMA_VALIDATION) System.out.println("!!! can not find elementDecl in the grammar, " + " the element localpart: " + element.localpart + "["+fStringPool.toString(element.localpart) +"]" + " the element uri: " + element.uri + "["+fStringPool.toString(element.uri) +"]" + " and the current enclosing scope: " + fCurrentScope ); } } if (DEBUG_SCHEMA_VALIDATION) { fGrammar.getElementDecl(elementIndex, fTempElementDecl); System.out.println("elementIndex: " + elementIndex+" \n and itsName : '" + fStringPool.toString(fTempElementDecl.name.localpart) +"' \n its ContentType:" + fTempElementDecl.type +"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+ " and the current enclosing scope: " + fCurrentScope); } } contentSpecType = getContentSpecType(elementIndex); if (fGrammarIsSchemaGrammar) { // handle "xsi:type" right here if (fXsiTypeAttValue > -1) { String xsiType = fStringPool.toString(fXsiTypeAttValue); int colonP = xsiType.indexOf(":"); String prefix = ""; String localpart = xsiType; if (colonP > -1) { prefix = xsiType.substring(0,colonP); localpart = xsiType.substring(colonP+1); } String uri = ""; int uriIndex = StringPool.EMPTY_STRING; if (fNamespacesScope != null) { uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)); if (uriIndex > 0) { uri = fStringPool.toString(uriIndex); if (uriIndex != fGrammarNameSpaceIndex) { fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex; boolean success = switchGrammar(fCurrentSchemaURI); if (!success && !fNeedValidationOff) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 3: " + fStringPool.toString(fCurrentSchemaURI) + " , can not be found"); } } } } Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry(); DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry(); if (complexRegistry==null || dataTypeReg == null) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, fErrorReporter.getLocator().getSystemId() +" line"+fErrorReporter.getLocator().getLineNumber() +", canot resolve xsi:type = " + xsiType+" } else { TraverseSchema.ComplexTypeInfo typeInfo = (TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart); if (typeInfo==null) { if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) { fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart); } else fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart); if ( fXsiTypeValidator == null ) reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "unresolved type : "+uri+","+localpart +" found in xsi:type handling"); else if (elementIndex != -1) { // make sure the new type is related to the // type of the expected element XMLElementDecl tempElementDecl = new XMLElementDecl(); fGrammar.getElementDecl(elementIndex, tempElementDecl); DatatypeValidator ancestorValidator = tempElementDecl.datatypeValidator; DatatypeValidator tempVal = fXsiTypeValidator; for(; tempVal != null; tempVal = tempVal.getBaseValidator()) // WARNING!!! Comparison by reference. if(tempVal == ancestorValidator) break; if(tempVal == null) { // now if ancestorValidator is a union, then we must // look through its members to see whether we derive from any of them. if(ancestorValidator instanceof UnionDatatypeValidator) { // fXsiTypeValidator must derive from one of its members... Vector subUnionMemberDV = ((UnionDatatypeValidator)ancestorValidator).getBaseValidators(); int subUnionSize = subUnionMemberDV.size(); boolean found = false; for (int i=0; i<subUnionSize && !found; i++) { DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i); DatatypeValidator dTemp = fXsiTypeValidator; for(; dTemp != null; dTemp = dTemp.getBaseValidator()) { // WARNING!!! This uses comparison by reference andTemp is thus inherently suspect! if(dTempSub == dTemp) { found = true; break; } } } if(!found) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type of element " + fStringPool.toString(tempElementDecl.name.localpart)); } } else { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type of element " + fStringPool.toString(tempElementDecl.name.localpart)); } } else { // if we have an attribute but xsi:type's type is simple, we have a problem... if (tempVal != null && fXsiTypeValidator != null && (fGrammar.getFirstAttributeDeclIndex(elementIndex) != -1)) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type of element " + fStringPool.toString(tempElementDecl.name.localpart)); } // check if element has block set if((((SchemaGrammar)fGrammar).getElementDeclBlockSet(elementIndex) & SchemaSymbols.RESTRICTION) != 0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Element " + fStringPool.toString(tempElementDecl.name.localpart) + "does not permit substitution by a type such as "+uri+","+localpart); } } } } else { // The type must not be abstract if (typeInfo.isAbstractType()) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Abstract type " + xsiType + " should not be used in xsi:type"); } if (elementIndex != -1) { // now we look at whether there is a type // relation and whether the type (and element) allow themselves to be substituted for. TraverseSchema.ComplexTypeInfo tempType = typeInfo; TraverseSchema.ComplexTypeInfo destType = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(elementIndex); for(; tempType != null && destType != null; tempType = tempType.baseComplexTypeInfo) { if(tempType.typeName.equals(destType.typeName)) break; } if(tempType == null) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type " + destType.typeName); } else if (destType == null) { // if the original type is a simple type, check derivation ok. XMLElementDecl tempElementDecl = new XMLElementDecl(); fGrammar.getElementDecl(elementIndex, tempElementDecl); DatatypeValidator ancestorValidator = tempElementDecl.datatypeValidator; DatatypeValidator tempVal = fXsiTypeValidator; for(; tempVal != null; tempVal = tempVal.getBaseValidator()) // WARNING!!! Comparison by reference. if(tempVal == ancestorValidator) break; if(tempVal == null) { // now if ancestorValidator is a union, then we must // look through its members to see whether we derive from any of them. if(ancestorValidator instanceof UnionDatatypeValidator) { // fXsiTypeValidator must derive from one of its members... Vector subUnionMemberDV = ((UnionDatatypeValidator)ancestorValidator).getBaseValidators(); int subUnionSize = subUnionMemberDV.size(); boolean found = false; for (int i=0; i<subUnionSize && !found; i++) { DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i); DatatypeValidator dTemp = fXsiTypeValidator; for(; dTemp != null; dTemp = dTemp.getBaseValidator()) { // WARNING!!! This uses comparison by reference andTemp is thus inherently suspect! if(dTempSub == dTemp) { found = true; break; } } } if(!found) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type of element " + fStringPool.toString(tempElementDecl.name.localpart)); } } else { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type : "+uri+","+localpart +" does not derive from the type of element " + fStringPool.toString(tempElementDecl.name.localpart)); } } } else if (typeInfo != destType) { // now check whether the element or typeInfo's baseType blocks us. int derivationMethod = typeInfo.derivedBy; if((((SchemaGrammar)fGrammar).getElementDeclBlockSet(elementIndex) & derivationMethod) != 0) { XMLElementDecl tempElementDecl = new XMLElementDecl(); fGrammar.getElementDecl(elementIndex, tempElementDecl); reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Element " + fStringPool.toString(tempElementDecl.name.localpart) + " does not permit xsi:type substitution in the manner required by type "+uri+","+localpart); } else if ((typeInfo.baseComplexTypeInfo.blockSet & derivationMethod) != 0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Type " + typeInfo.baseComplexTypeInfo.typeName + " does not permit other types, such as " +uri+","+localpart + " to be substituted for itself using xsi:type"); } } } elementIndex = typeInfo.templateElementIndex; } } fXsiTypeAttValue = -1; } else if (elementIndex != -1) { // xsi:type was not specified... // If the corresponding type is abstract, detect an error TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex); if (typeInfo != null && typeInfo.isAbstractType()) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Element " + fStringPool.toString(element.rawname) + " is declared with a type that is abstract. Use xsi:type to specify a non-abstract type"); } } if (elementIndex != -1) { // Check whether this element is abstract. If so, an error int miscFlags = ((SchemaGrammar) fGrammar).getElementDeclMiscFlags(elementIndex); if ((miscFlags & SchemaSymbols.ABSTRACT) != 0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "A member of abstract element " + fStringPool.toString(element.rawname) + "'s substitution group must be specified"); } if (fNil && (miscFlags & SchemaSymbols.NILLABLE) == 0 ) { fNil = false; reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "xsi:nil must not be specified for the element "+ fStringPool.toString(element.rawname)+ " with {nillable} equals 'false'"); } //Change the current scope to be the one defined by this element. fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex); // here need to check if we need to switch Grammar by asking SchemaGrammar whether // this element actually is of a type in another Schema. String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex); if (anotherSchemaURI != null) { //before switch Grammar, set the elementIndex to be the template elementIndex of its type if (contentSpecType != -1) { TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex); if (typeInfo != null) { elementIndex = typeInfo.templateElementIndex; } // now switch the grammar fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI); boolean success = switchGrammar(fCurrentSchemaURI); if (!success && !fNeedValidationOff) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Grammar with uri 4: " + fStringPool.toString(fCurrentSchemaURI) + " , can not be found"); } } } } } // since the elementIndex could change since last time we query the content type, so do it again. contentSpecType = getContentSpecType(elementIndex); if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, element.rawname); } if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) { fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1); } if (fAttrListHandle != -1) { //fAttrList.endAttrList(); int dupAttrs[]; if ((dupAttrs = fAttrList.endAttrList()) != null) { Object[] args = {fStringPool.toString(element.rawname), null}; for (int i = 0; i < dupAttrs.length; i++) { args[1] = fStringPool.toString(dupAttrs[i]); fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XMLNS_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_UNIQUE, XMLMessages.WFC_UNIQUE_ATT_SPEC, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } if (DEBUG_PRINT_ATTRIBUTES) { String elementStr = fStringPool.toString(element.rawname); System.out.print("startElement: <" + elementStr); if (fAttrListHandle != -1) { int index = attrList.getFirstAttr(fAttrListHandle); while (index != -1) { System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" + fStringPool.toString(attrList.getAttValue(index)) + "\""); index = attrList.getNextAttr(index); } } System.out.println(">"); } // REVISIT: Validation. Do we need to recheck for the xml:lang // attribute? It was already checked above -- perhaps // this is to check values that are defaulted in? If // so, this check could move to the attribute decl // callback so we can check the default value before // it is used. if (fAttrListHandle != -1 && !fNeedValidationOff ) { int index = fAttrList.getFirstAttr(fAttrListHandle); while (index != -1) { int attrNameIndex = attrList.getAttrName(index); if (fStringPool.equalNames(attrNameIndex, fXMLLang)) { fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index)); // break; } // here, we validate every "user-defined" attributes int _xmlns = fStringPool.addSymbol("xmlns"); if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns) if (fGrammar != null) { fTempQName.setValues(attrList.getAttrPrefix(index), attrList.getAttrLocalpart(index), attrList.getAttrName(index), attrList.getAttrURI(index) ); int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName); if (fTempQName.uri != fXsiURI) if (attDefIndex == -1 ) { if (fValidating) { // REVISIT - cache the elem/attr tuple so that we only give // this error once for each unique occurrence Object[] args = { fStringPool.toString(element.rawname), fStringPool.toString(attrList.getAttrName(index))}; fAttrNameLocator = getLocatorImpl(fAttrNameLocator); fErrorReporter.reportError(fAttrNameLocator, XMLMessages.XML_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED, XMLMessages.VC_ATTRIBUTE_VALUE_TYPE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } else { fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl); int attributeType = attributeTypeName(fTempAttDecl); attrList.setAttType(index, attributeType); if (fValidating) { if (fGrammarIsDTDGrammar) { int normalizedValue = validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl); attrList.setAttValue(index, normalizedValue); } // check to see if this attribute matched an attribute wildcard else if ( fGrammarIsSchemaGrammar && (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY ||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST ||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) { if ((fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_SKIP) > 0) { // attribute should just be bypassed, } else if ( (fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_STRICT) > 0 || (fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_LAX) > 0) { boolean reportError = false; boolean processContentStrict = (fTempAttDecl.defaultType & XMLAttributeDecl.PROCESSCONTENTS_STRICT) > 0; // ??? REVISIT: can't tell whether it's a local attribute // or a global one with empty namespace //if (fTempQName.uri == StringPool.EMPTY_STRING) { // if (processContentStrict) { // reportError = true; //} else { { Grammar aGrammar = fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri)); if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) { if (processContentStrict) { reportError = true; } } else { SchemaGrammar sGrammar = (SchemaGrammar) aGrammar; Hashtable attRegistry = sGrammar.getAttributeDeclRegistry(); if (attRegistry == null) { if (processContentStrict) { reportError = true; } } else { XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart)); if (attDecl == null) { if (processContentStrict) { reportError = true; } } else { DatatypeValidator attDV = attDecl.datatypeValidator; if (attDV == null) { if (processContentStrict) { reportError = true; } } else { try { String unTrimValue = fStringPool.toString(attrList.getAttValue(index)); String value = unTrimValue.trim(); fWhiteSpace = attDV.getWSFacet(); if (fWhiteSpace == DatatypeValidator.REPLACE) { //CDATA attDV.validate(unTrimValue, null ); } else { // normalize int normalizedValue = fStringPool.addString(value); attrList.setAttValue(index,normalizedValue ); validateUsingDV(attDV, value, false); } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage()}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } } } } if (reportError) { Object[] args = { fStringPool.toString(element.rawname), "ANY---"+fStringPool.toString(attrList.getAttrName(index))}; fAttrNameLocator = getLocatorImpl(fAttrNameLocator); fErrorReporter.reportError(fAttrNameLocator, XMLMessages.XML_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED, XMLMessages.VC_ATTRIBUTE_VALUE_TYPE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } else if (fTempAttDecl.datatypeValidator == null) { Object[] args = { fStringPool.toString(element.rawname), fStringPool.toString(attrList.getAttrName(index))}; System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index)) + " not found in element type " + fStringPool.toString(element.rawname)); fAttrNameLocator = getLocatorImpl(fAttrNameLocator); fErrorReporter.reportError(fAttrNameLocator, XMLMessages.XML_DOMAIN, XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED, XMLMessages.VC_ATTRIBUTE_VALUE_TYPE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { String unTrimValue = fStringPool.toString(attrList.getAttValue(index)); String value = unTrimValue.trim(); DatatypeValidator tempDV = fTempAttDecl.datatypeValidator; // if "fixed" is specified, then get the fixed string, // and compare over value space if ((fTempAttDecl.defaultType & XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0 && tempDV.compare(value, fTempAttDecl.defaultValue) != 0) { Object[] args = { fStringPool.toString(element.rawname), fStringPool.toString(attrList.getAttrName(index)), unTrimValue, fTempAttDecl.defaultValue}; fErrorReporter.reportError( fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_FIXED_ATTVALUE_INVALID, XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } fWhiteSpace = tempDV.getWSFacet(); if (fWhiteSpace == DatatypeValidator.REPLACE) { //CDATA tempDV.validate(unTrimValue, null ); } else { // normalize int normalizedValue = fStringPool.addString(value); attrList.setAttValue(index,normalizedValue ); validateUsingDV(tempDV, value, false); } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage()}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } // end of if (fValidating) } // end of if (attDefIndex == -1) else }// end of if (fGrammar != null) index = fAttrList.getNextAttr(index); } } } if (fAttrListHandle != -1) { int index = attrList.getFirstAttr(fAttrListHandle); while (index != -1) { int attName = attrList.getAttrName(index); if (!fStringPool.equalNames(attName, fNamespacesPrefix)) { int attPrefix = attrList.getAttrPrefix(index); if (attPrefix != fNamespacesPrefix) { if (attPrefix != -1) { int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix); if (uri == StringPool.EMPTY_STRING) { Object[] args = { fStringPool.toString(attPrefix)}; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XMLNS_DOMAIN, XMLMessages.MSG_PREFIX_DECLARED, XMLMessages.NC_PREFIX_DECLARED, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } attrList.setAttrURI(index, uri); } } } index = attrList.getNextAttr(index); } } fCurrentElementIndex = elementIndex; fCurrentContentSpecType = contentSpecType; if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) { fBufferDatatype = true; fDatatypeBuffer.setLength(0); } fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN); } // validateElementAndAttributes(QName,XMLAttrList) /** * Validate attributes in DTD fashion. * @return normalized attribute value */ private int validateDTDattribute(QName element, int attValue, XMLAttributeDecl attributeDecl) throws Exception{ AttributeValidator av = null; switch (attributeDecl.type) { case XMLAttributeDecl.TYPE_ENTITY: { boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); //System.out.println("value = " + value ); //changes fTempAttDef if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } try { if ( isAlistAttribute ) { fValENTITIES.validate( value, fValidateEntity ); } else { fValENTITY.validate( value, fValidateEntity ); } } catch ( InvalidDatatypeValueException ex ) { if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) { reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } else { reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString( attributeDecl.name.rawname), value ); } } /*if (attributeDecl.list) { av = fAttValidatorENTITIES; } else { av = fAttValidatorENTITY; }*/ if (fNormalizeAttributeValues) { if (attributeDecl.list) { attValue = normalizeListAttribute(value, attValue, unTrimValue); } else { if (value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } } } break; case XMLAttributeDecl.TYPE_ENUMERATION: av = fAttValidatorENUMERATION; break; case XMLAttributeDecl.TYPE_ID: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } try { fValID.validate( value, fIdDefs ); fValIDRef.validate( value, this.fValidateIDRef ); //just in case we called id after IDREF } catch ( InvalidDatatypeValueException ex ) { int major = ex.getMajorCode(), minor = ex.getMinorCode(); if (major == -1) { major = XMLMessages.MSG_ID_INVALID; minor = XMLMessages.VC_ID; } reportRecoverableXMLError(major, minor, fStringPool.toString( attributeDecl.name.rawname), value ); } if (fNormalizeAttributeValues && value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } break; case XMLAttributeDecl.TYPE_IDREF: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef //changes fTempAttDef if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } if (attributeDecl.list && value.length() == 0 ) { reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attributeDecl.name.rawname) ) ; } } try { if ( isAlistAttribute ) { fValIDRefs.validate( value, this.fValidateIDRef ); } else { fValIDRef.validate( value, this.fValidateIDRef ); } } catch ( InvalidDatatypeValueException ex ) { if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) { reportRecoverableXMLError(ex.getMajorCode(), ex.getMinorCode(), fStringPool.toString( attributeDecl.name.rawname), value ); } else { reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID, XMLMessages.VC_IDREF, fStringPool.toString( attributeDecl.name.rawname), value ); } } if (fNormalizeAttributeValues) { if (attributeDecl.list) { attValue = normalizeListAttribute(value, attValue, unTrimValue); } else { if (value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } } } break; case XMLAttributeDecl.TYPE_NOTATION: { /* WIP String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } } } */ av = fAttValidatorNOTATION; } break; case XMLAttributeDecl.TYPE_NMTOKEN: { String unTrimValue = fStringPool.toString(attValue); String value = unTrimValue.trim(); boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef //changes fTempAttDef if (fValidationEnabled) { if (value != unTrimValue) { if (invalidStandaloneAttDef(element, attributeDecl.name)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value); } } if (attributeDecl.list && value.length() == 0 ) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attributeDecl.name.rawname) ) ; } } try { if ( isAlistAttribute ) { fValNMTOKENS.validate( value, null ); } else { fValNMTOKEN.validate( value, null ); } } catch ( InvalidDatatypeValueException ex ) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attributeDecl.name.rawname), value);//TODO NMTOKENS messge } if (fNormalizeAttributeValues) { if (attributeDecl.list) { attValue = normalizeListAttribute(value, attValue, unTrimValue); } else { if (value != unTrimValue) { attValue = fStringPool.addSymbol(value); } } } } break; } if ( av != null ) { int newValue = av.normalize(element, attributeDecl.name, attValue, attributeDecl.type, attributeDecl.enumeration); if (fNormalizeAttributeValues) attValue = newValue; } return attValue; } /** * @param value This is already trimmed. */ private int normalizeListAttribute(String value, int origIndex, String origValue) { int length = value.length(); StringBuffer buffer = null; int state = 0; // 0:non-S, 1: 1st S, 2: non-1st S int copyStart = 0; for (int i = 0; i < length; i++) { int ch = value.charAt(i); if (ch == ' ') { if (state == 0) { state = 1; } else if (state == 1) { state = 2; if (buffer == null) buffer = new StringBuffer(length); buffer.append(value.substring(copyStart, i)); } } else { if (state == 2) copyStart = i; state = 0; } } if (buffer == null) return value == origValue ? origIndex : fStringPool.addSymbol(value); buffer.append(value.substring(copyStart)); return fStringPool.addSymbol(new String(buffer)); } /** Character data in content. */ private void charDataInContent() { if (DEBUG_ELEMENT_CHILDREN) { System.out.println("charDataInContent()"); } if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildren.length * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.clear(); fElementChildrenLength++; } // charDataInCount() /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED_SIMPLE || contentType == XMLElementDecl.TYPE_MIXED_COMPLEX || contentType == XMLElementDecl.TYPE_CHILDREN) { // XML Schema REC: Validation Rule: Element Locally Valid (Element) // 3.2.1 The element information item must have no // character or element information item [children]. if (childCount == 0 && fNil) { fNil = false; //return success return -1; } // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getElementContentModel(elementIndex); int curState = fContentModelStateStack[fElementDepth+1]; // if state!=-2, we have validate the children if (curState != -2) { // if state==-1, there is invalid child // if !finalState, then the content is not complete // both indicate an error, we return successful element count if (curState == -1 || !((DFAContentModel)cmElem).isFinalState(curState)) { return fContentModelEleCount[fElementDepth+1]; } else { // otherwise -1: succeeded return -1; } } //otherwise, we need to validateContent int result = cmElem.validateContent(children, childOffset, childCount); if (result != -1 && fGrammarIsSchemaGrammar) { result = cmElem.validateContentSpecial(children, childOffset, childCount); } return result; } catch (CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; if (childCount > 0) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+ "Can not have element children within a simple type content"}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } else { try { if (fCurrentDV == null ) { //no character data fGrammar.getElementDecl(elementIndex, fTempElementDecl); fCurrentDV = fTempElementDecl.datatypeValidator; } // If there is xsi:type validator, substitute it. if ( fXsiTypeValidator != null ) { fCurrentDV = fXsiTypeValidator; fXsiTypeValidator = null; } if (fCurrentDV == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { String value =fDatatypeBuffer.toString(); String currentElementDefault = ((SchemaGrammar)fGrammar).getElementDefaultValue(fCurrentElementIndex); int hasFixed = (((SchemaGrammar)fGrammar).getElementDeclMiscFlags(fCurrentElementIndex) & SchemaSymbols.FIXED); if (fNil) { if (value.length() != 0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "An element <" +fStringPool.toString(elementType)+"> with attribute xsi:nil=\"true\" must be empty"); } if (hasFixed !=0) { reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "An element <" +fStringPool.toString(elementType)+"> with attribute xsi:nil=\"true\" must not have fixed value constraint"); } fNil = false; return -1; } // check for fixed/default values of elements here. if( currentElementDefault == null || currentElementDefault.length() == 0) { validateUsingDV(fCurrentDV, value, false); } else { if (hasFixed !=0) { if ( value.length() == 0 ) { // use fixed as default value // Note: this is inefficient where the DOMParser // is concerned. However, if we used the characters(int) // callback instead, this would be just as inefficient for SAX. fDocumentHandler.characters(currentElementDefault.toCharArray(), 0, currentElementDefault.length()); validateUsingDV(fCurrentDV, currentElementDefault, true); } else { // must check in valuespace! if ( fCurrentDV.compare(value, currentElementDefault) != 0 ) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.FixedDiffersFromActual, 0, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } validateUsingDV(fCurrentDV, value, true); } } else { if ( value.length() == 0) { // use default value fDocumentHandler.characters(currentElementDefault.toCharArray(), 0, currentElementDefault.length()); validateUsingDV(fCurrentDV, currentElementDefault, true); } else { validateUsingDV(fCurrentDV, value, false); } } } } } catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+idve.getMessage()}, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } fCurrentDV = null; fFirstChunk= true; fTrailing=false; } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } void validateUsingDV (DatatypeValidator dv, String content, boolean onlyVal3Types) throws Exception, InvalidDatatypeValueException { if (dv instanceof IDDatatypeValidator) { dv.validate( content, fIdDefs ); } else if (dv instanceof IDREFDatatypeValidator) { dv.validate( content, fValidateIDRef ); } else if (dv instanceof ENTITYDatatypeValidator) { dv.validate( content, fValidateEntity); } else if (!onlyVal3Types) { if (dv instanceof NOTATIONDatatypeValidator && content != null) { content = bindNotationURI(content); } dv.validate( content, null); } } // Classes /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // Data /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // Constructors public XPathMatcherStack() { } // <init>() // Public methods /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // Private methods /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // Constants /** Not a value (Unicode: #FFFF). */ protected IDValue NOT_AN_IDVALUE = new IDValue("\uFFFF", null); // Data /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; /** Current data values. */ protected final OrderedHashtable fValues = new OrderedHashtable(); /** Current data value count. */ protected int fValuesCount; /** Data value tuples. */ protected final Vector fValueTuples = new Vector(); // Constructors /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint) { fIdentityConstraint = identityConstraint; } // <init>(IdentityConstraint) // Public methods // destroys this ValueStore; useful when, for instanc,e a // locally-scoped ID constraint is involved. public void destroy() { fValuesCount = 0; fValues.clear(); fValueTuples.removeAllElements(); } // end destroy():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValueTuples.size(); i++) { OrderedHashtable o = (OrderedHashtable)newVal.fValueTuples.elementAt(i); if (!contains(o)) fValueTuples.addElement(o); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#startValueScope()"); } fValuesCount = 0; int count = fIdentityConstraint.getFieldCount(); for (int i = 0; i < count; i++) { fValues.put(fIdentityConstraint.getFieldAt(i), NOT_AN_IDVALUE); } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#endValueScope()"); } // is there anything to do? // REVISIT: This check solves the problem with field matchers // that get activated because they are at the same // level as the declaring element (e.g. selector xpath // is ".") but never match. // However, this doesn't help us catch the problem // when we expect a field value but never see it. A // better solution has to be found. -Ac // REVISIT: Is this a problem? -Ac // Yes - NG if (fValuesCount == 0) { if(fIdentityConstraint.getType() == IdentityConstraint.KEY) { int code = SchemaMessageProvider.AbsentKeyValue; String eName = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{eName}); } return; } // do we have enough values? if (fValuesCount != fIdentityConstraint.getFieldCount()) { switch (fIdentityConstraint.getType()) { case IdentityConstraint.UNIQUE: { int code = SchemaMessageProvider.UniqueNotEnoughValues; String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{ename}); break; } case IdentityConstraint.KEY: { int code = SchemaMessageProvider.KeyNotEnoughValues; Key key = (Key)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = key.getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } case IdentityConstraint.KEYREF: { int code = SchemaMessageProvider.KeyRefNotEnoughValues; KeyRef keyref = (KeyRef)fIdentityConstraint; String ename = fIdentityConstraint.getElementName(); String kname = (keyref.getKey()).getIdentityConstraintName(); reportSchemaError(code, new Object[]{ename,kname}); break; } } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() throws Exception { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#endDocument()"); } } // endDocument() // ValueStore methods /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportNilError(IdentityConstraint id) throws Exception { if(id.getType() == IdentityConstraint.KEY) { int code = SchemaMessageProvider.KeyMatchesNillable; reportSchemaError(code, new Object[]{id.getElementName()}); } } // reportNilError /** * Adds the specified value to the value store. * * @param value The value to add. * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. */ public void addValue(Field field, IDValue value) throws Exception { if(!field.mayMatch()) { int code = SchemaMessageProvider.FieldMultipleMatch; reportSchemaError(code, new Object[]{field.toString()}); } if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#addValue("+ "field="+field+','+ "value="+value+ ")"); } // do we even know this field? int index = fValues.indexOf(field); if (index == -1) { int code = SchemaMessageProvider.UnknownField; reportSchemaError(code, new Object[]{field.toString()}); return; } // store value IDValue storedValue = fValues.valueAt(index); if (storedValue.isDuplicateOf(NOT_AN_IDVALUE)) { fValuesCount++; } fValues.put(field, value); if (fValuesCount == fValues.size()) { // is this value as a group duplicated? if (contains(fValues)) { duplicateValue(fValues); } // store values OrderedHashtable values = (OrderedHashtable)fValues.clone(); fValueTuples.addElement(values); } } // addValue(String,Field) /** * Returns true if this value store contains the specified * values tuple. */ public boolean contains(OrderedHashtable tuple) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+this.toString()+"#contains("+toString(tuple)+")"); } // do sizes match? int tcount = tuple.size(); // iterate over tuples to find it int count = fValueTuples.size(); LOOP: for (int i = 0; i < count; i++) { OrderedHashtable vtuple = (OrderedHashtable)fValueTuples.elementAt(i); // compare values for (int j = 0; j < tcount; j++) { IDValue value1 = vtuple.valueAt(j); IDValue value2 = tuple.valueAt(j); if(!(value1.isDuplicateOf(value2))) { continue LOOP; } } // found it return true; } // didn't find it return false; } // contains(Hashtable):boolean // Protected methods /** * Called when a duplicate value is added. Subclasses should override * this method to perform error checking. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws Exception { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(OrderedHashtable tuple) { // no values int size = tuple.size(); if (size == 0) { return ""; } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < size; i++) { if (i > 0) { str.append(','); } str.append(tuple.valueAt(i)); } return str.toString(); } // toString(OrderedHashtable):String // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // Constructors /** Constructs a unique value store. */ public UniqueValueStore(Unique unique) { super(unique); } // <init>(Unique) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws Exception { int code = SchemaMessageProvider.DuplicateUnique; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // Constructors /** Constructs a key value store. */ public KeyValueStore(Key key) { super(key); } // <init>(Key) // ValueStoreBase protected methods /** * Called when a duplicate value is added. * * @param tuple The duplicate value tuple. */ protected void duplicateValue(OrderedHashtable tuple) throws Exception { int code = SchemaMessageProvider.DuplicateKey; String value = toString(tuple); String ename = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,ename}); } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // Data /** Key value store. */ protected ValueStoreBase fKeyValueStore; // Constructors /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) { super(keyRef); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // ValueStoreBase methods // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment () throws Exception { // do all the necessary management... super.endDocumentFragment (); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase)fValueStoreCache.fGlobalIDConstraintMap.get(((KeyRef)fIdentityConstraint).getKey()); if(fKeyValueStore == null) { // report error int code = SchemaMessageProvider.KeyRefOutOfScope; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[]{value}); return; } int count = fValueTuples.size(); for (int i = 0; i < count; i++) { OrderedHashtable values = (OrderedHashtable)fValueTuples.elementAt(i); if (!fKeyValueStore.contains(values)) { int code = SchemaMessageProvider.KeyNotFound; String value = toString(values); String element = fIdentityConstraint.getElementName(); reportSchemaError(code, new Object[]{value,element}); } } } // endDocumentFragment() /** End document. */ public void endDocument() throws Exception { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // Data // values stores /** stores all global Values stores. */ protected final Vector fValueStores = new Vector(); /** Values stores associated to specific identity constraints. */ protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., wen it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // the fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endelement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final Hashtable fGlobalIDConstraintMap = new Hashtable(); // Constructors /** Default constructor. */ public ValueStoreCache() { } // <init>() // Public methods /** Resets the identity constraint cache. */ public void startDocument() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#startDocument()"); } fValueStores.removeAllElements(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); fGlobalIDConstraintMap.clear(); } // startElement(void) // endElement(): merges contents of fGlobalIDConstraintMap with the // top of fGlobalMapStack into fGlobalIDConstraintMap. public void endElement() { if (fGlobalMapStack.isEmpty()) return; // must be an invalid doc! Hashtable oldMap = (Hashtable)fGlobalMapStack.pop(); Enumeration keys = oldMap.keys(); while(keys.hasMoreElements()) { IdentityConstraint id = (IdentityConstraint)keys.nextElement(); ValueStoreBase oldVal = (ValueStoreBase)oldMap.get(id); if(oldVal != null) { ValueStoreBase currVal = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVal == null) fGlobalIDConstraintMap.put(id, oldVal); else { currVal.append(oldVal); fGlobalIDConstraintMap.put(id, currVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XMLElementDecl eDecl) throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#initValueStoresFor("+ fStringPool.toString(eDecl.name.rawname)+ ")"); } // initialize value stores for unique fields Vector uVector = eDecl.unique; int uCount = uVector.size(); for (int i = 0; i < uCount; i++) { Unique unique = (Unique)uVector.elementAt(i); UniqueValueStore valueStore = (UniqueValueStore)fIdentityConstraint2ValueStoreMap.get(unique); if (valueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } valueStore = new UniqueValueStore(unique); fValueStores.addElement(valueStore); if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+unique+" -> "+valueStore); } fIdentityConstraint2ValueStoreMap.put(unique, valueStore); } // initialize value stores for key fields Vector kVector = eDecl.key; int kCount = kVector.size(); for (int i = 0; i < kCount; i++) { Key key = (Key)kVector.elementAt(i); KeyValueStore valueStore = (KeyValueStore)fIdentityConstraint2ValueStoreMap.get(key); if (valueStore != null) { // NOTE: If already initialized, don't need to // do it again. -Ac continue; } valueStore = new KeyValueStore(key); fValueStores.addElement(valueStore); if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+key+" -> "+valueStore); } fIdentityConstraint2ValueStoreMap.put(key, valueStore); } // initialize value stores for key reference fields Vector krVector = eDecl.keyRef; int krCount = krVector.size(); for (int i = 0; i < krCount; i++) { KeyRef keyRef = (KeyRef)krVector.elementAt(i); KeyRefValueStore keyRefValueStore = new KeyRefValueStore(keyRef, null); fValueStores.addElement(keyRefValueStore); if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+keyRef+" -> "+keyRefValueStore); } fIdentityConstraint2ValueStoreMap.put(keyRef, keyRefValueStore); } } // initValueStoresFor(XMLElementDecl) /** Returns the value store associated to the specified field. */ public ValueStoreBase getValueStoreFor(Field field) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#getValueStoreFor("+field+")"); } IdentityConstraint identityConstraint = field.getIdentityConstraint(); return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(identityConstraint); } // getValueStoreFor(Field):ValueStoreBase /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#getValueStoreFor("+id+")"); } return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#getGlobalValueStoreFor("+id+")"); } return (ValueStoreBase)fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id) throws Exception { if (id.getType() == IdentityConstraint.KEYREF ) return; ValueStoreBase newVals = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id); fIdentityConstraint2ValueStoreMap.remove(id); ValueStoreBase currVals = (ValueStoreBase)fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() throws Exception { if (DEBUG_VALUE_STORES) { System.out.println("<VS>: "+toString()+"#endDocument()"); } int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase)fValueStores.elementAt(i); valueStore.endDocument(); } } // endDocument() // Object methods /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // utility classes /** * Ordered hashtable. This class acts as a hashtable with * <code>put()</code> and <code>get()</code> operations but also * allows values to be queried via the order that they were * added to the hashtable. * <p> * <strong>Note:</strong> This class does not perform any error * checking. * <p> * <strong>Note:</strong> This class is <em>not</em> efficient but * is assumed to be used for a very small set of values. * * @author Andy Clark, IBM */ static final class OrderedHashtable implements Cloneable { // Data /** Size. */ private int fSize; /** Hashtable entries. */ private Entry[] fEntries = null; // Public methods /** Returns the number of entries in the hashtable. */ public int size() { return fSize; } // size():int /** Puts an entry into the hashtable. */ public void put(Field key, IDValue value) { int index = indexOf(key); if (index == -1) { ensureCapacity(fSize); index = fSize++; fEntries[index].key = key; } fEntries[index].value = value; } // put(Field,String) /** Returns the value associated to the specified key. */ public IDValue get(Field key) { return fEntries[indexOf(key)].value; } // get(Field):String /** Returns the index of the entry with the specified key. */ public int indexOf(Field key) { for (int i = 0; i < fSize; i++) { // NOTE: Only way to be sure that the keys are the // same is by using a reference comparison. In // order to rely on the equals method, each // field would have to take into account its // position in the identity constraint, the // identity constraint, the declaring element, // and the grammar that it is defined in. // Otherwise, you have the possibility that // the equals method would return true for two // fields that look *very* similar. // The reference compare isn't bad, actually, // because the field objects are cacheable. -Ac if (fEntries[i].key == key) { return i; } } return -1; } // indexOf(Field):int /** Returns the key at the specified index. */ public Field keyAt(int index) { return fEntries[index].key; } // keyAt(int):Field /** Returns the value at the specified index. */ public IDValue valueAt(int index) { return fEntries[index].value; } // valueAt(int):String /** Removes all of the entries from the hashtable. */ public void clear() { fSize = 0; } // clear() // Private methods /** Ensures the capacity of the entries array. */ private void ensureCapacity(int size) { // sizes int osize = -1; int nsize = -1; // create array if (fEntries == null) { osize = 0; nsize = 2; fEntries = new Entry[nsize]; } // resize array else if (fEntries.length <= size) { osize = fEntries.length; nsize = 2 * osize; Entry[] array = new Entry[nsize]; System.arraycopy(fEntries, 0, array, 0, osize); fEntries = array; } // create new entries for (int i = osize; i < nsize; i++) { fEntries[i] = new Entry(); } } // ensureCapacity(int) // Cloneable methods /** Clones this object. */ public Object clone() { OrderedHashtable hashtable = new OrderedHashtable(); for (int i = 0; i < fSize; i++) { hashtable.put(fEntries[i].key, fEntries[i].value); } return hashtable; } // clone():Object // Object methods /** Returns a string representation of this object. */ public String toString() { if (fSize == 0) { return "[]"; } StringBuffer str = new StringBuffer(); str.append('['); for (int i = 0; i < fSize; i++) { if (i > 0) { str.append(','); } str.append('{'); str.append(fEntries[i].key); str.append(','); str.append(fEntries[i].value); str.append('}'); } str.append(']'); return str.toString(); } // toString():String // Classes /** * Hashtable entry. */ public static final class Entry { // Data /** Key. */ public Field key; /** Value. */ public IDValue value; } // class Entry } // class OrderedHashtable } // class XMLValidator
package au.com.noojee.acceloapi.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.gson.Gson; import au.com.noojee.acceloapi.AcceloAbstractResponseList; import au.com.noojee.acceloapi.AcceloApi; import au.com.noojee.acceloapi.AcceloException; import au.com.noojee.acceloapi.AcceloFieldList; import au.com.noojee.acceloapi.AcceloResponse; import au.com.noojee.acceloapi.DaoOperation; import au.com.noojee.acceloapi.EndPoint; import au.com.noojee.acceloapi.HTTPResponse; import au.com.noojee.acceloapi.Meta; import au.com.noojee.acceloapi.cache.AcceloCache; import au.com.noojee.acceloapi.cache.CacheKey; import au.com.noojee.acceloapi.dao.gson.GsonForAccelo; import au.com.noojee.acceloapi.entities.AcceloEntity; import au.com.noojee.acceloapi.entities.generator.JsonValidator; import au.com.noojee.acceloapi.entities.meta.fieldTypes.FilterField; import au.com.noojee.acceloapi.filter.AcceloFilter; public abstract class AcceloDao<E extends AcceloEntity<E>> { private static Logger logger = LogManager.getLogger(); protected abstract Class<? extends AcceloAbstractResponseList<E>> getResponseListClass(); protected abstract Class<? extends AcceloResponse<E>> getResponseClass(); protected abstract EndPoint getEndPoint(); protected abstract Class<E> getEntityClass(); /** * Returns the list of tickets that match the pass in filter. * * @param acceloApi * @param filter the filter defining the tickets to be returned. * @return * @throws AcceloException */ public List<E> getByFilter(AcceloFilter<E> filter) throws AcceloException { AcceloFieldList fields = getFieldList(); return this.getByFilter(filter, fields); } /** * Returns the list of tickets that match the pass in filter. * * @param acceloApi * @param filter the filter defining the tickets to be returned. * @param fileds - the set of fields to return * @return * @throws AcceloException * @throws ExecutionException */ @SuppressWarnings("unchecked") public List<E> getByFilter(AcceloFilter<E> filter, AcceloFieldList fields) throws AcceloException { List<E> entities = new ArrayList<>(); CacheKey<E> key = new CacheKey<>(getEndPoint(), filter, fields, getResponseListClass(), this.getEntityClass()); entities = (List<E>) AcceloCache.getInstance().get(key); return entities; } @SuppressWarnings("unchecked") protected Optional<E> getSingleByFilter(AcceloFilter<E> filter, AcceloFieldList fields) throws AcceloException { CacheKey<E> key = new CacheKey<>(getEndPoint(), filter, fields, getResponseClass(), this.getEntityClass()); List<? extends AcceloEntity<E>> list = (List<? extends AcceloEntity<E>>) AcceloCache.getInstance().get(key); return list.isEmpty() ? Optional.empty() : Optional.of((E) list.get(0)); } public E getById(int id) throws AcceloException { return getById(getEndPoint(), id, getFieldList(), false); } public E getById(int id, boolean refreshCache) throws AcceloException { return getById(getEndPoint(), id, AcceloFieldList.ALL, refreshCache); } protected E getById(EndPoint endpoint, int id) throws AcceloException { return getById(endpoint, id, getFieldList(), false); } protected E getById(EndPoint endpoint, int id, AcceloFieldList fields, boolean refreshCache) throws AcceloException { E entity = null; if (id != 0) { AcceloFilter<E> filter = new AcceloFilter<>(); if (refreshCache) filter.refreshCache(); FilterField<E, Integer> idField = new FilterField<>("id"); filter.where(filter.eq(idField, id)); @SuppressWarnings("unchecked") List<E> entities = (List<E>) AcceloCache.getInstance() .get(new CacheKey<>(endpoint, filter, fields, getResponseListClass(), this.getEntityClass())); if (entities.size() > 0) entity = entities.get(0); } return entity; } /** * This will return 'ALL" entities associated with the end point. - USE WITH CARE!!! * * @param endpoint * @param id * @param fieldValues * @return * @throws AcceloException */ @SuppressWarnings("unchecked") public List<E> getAll() throws AcceloException { List<E> entities = new ArrayList<>(); // pass in an empty filter AcceloFilter<E> filter = new AcceloFilter<>(); CacheKey<E> key = new CacheKey<>(getEndPoint(), filter, AcceloFieldList.ALL, getResponseListClass(), this.getEntityClass()); entities = (List<E>) AcceloCache.getInstance().get(key); return entities; } /** * Inserts an entity into Accelo. Becareful when doing inserts as any cached queries will not included the newly * inserted entity. You may need to identify any cached queries and flush them. * * @param entity * @return the newly inserted entity as returned from Accelo. */ public E insert(E entity) { entity.setFieldList(getFieldList()); preInsertValidation(entity); String fieldValues = toJson(entity, DaoOperation.INSERT); AcceloResponse<E> response = AcceloApi.getInstance().insert(this.getEndPoint(), fieldValues, // fields, this.getResponseClass()); logger.error(response); return (response != null ? response.getEntity() : null); } /** * Updated an existing entity. Any instances in the cache will be updated. * * @param ticket * @throws AcceloException */ public E update(E entity) { entity.setFieldList(getFieldList()); preUpdateValidation(entity); String fieldValues = toJson(entity, DaoOperation.UPDATE); AcceloResponse<E> response = AcceloApi.getInstance().update(this.getEndPoint(), entity.getId(), fieldValues, // fields, this.getResponseClass()); logger.error(response); if (response == null || response.getEntity() == null) { throw new AcceloException("Failed to update " + entity.getClass().getSimpleName() + ":" + entity.getId() + " details:" + this.toString()); } AcceloCache.getInstance().updateEntity(response.getEntity()); return response.getEntity(); } protected String toJson(E entity, DaoOperation operation) { return GsonForAccelo.toJson(entity); } protected E fromJson(String jsonEntity) { return GsonForAccelo.fromJson(jsonEntity, getEntityClass()); } public void delete(E entity) { HTTPResponse response = AcceloApi.getInstance().delete(getEndPoint(), entity.getId()); if (response.getResponseCode() != 200 && response.getResponseCode() != 400) throw new AcceloException("Delete failed with error code: " + response.getResponseCode() + " Message:" + response.getResponseMessage()); // We remove the entity from the cache. Of course it may also be attached to a query. AcceloCache.getInstance().flushEntity(entity); } /** * In same cases (such as activity) we can't update the entity so we have to insert a new (cloned) entity and then * delete the old one. WARNING: entities such as Activities have a hierarchy (thread, parent). If you delete an * activity that is the owner of a thread or a parent then all owned/child activities are deleted! WARNING: To use * this method, retrieve an entity from accelo. Adjust the details of the entity and then call replace. This method * will delete the original entity using its id and then insert an new replacement entity based on the entity you * pass in. This method will also flush the cache, including any queries that contained the original entity. * * @param activity */ public E replace(E entity) { // We need to clear the query from the cache now as after the // delete/insert the query will be invalid but the entity won't exists // so we can't flush it. AcceloCache.getInstance().flushEntity(entity, true); // we do the insert first so if anything goes wrong we don't loose data. E replacementEntity = insert(entity); delete(entity); return replacementEntity; } /** * a handy method used when adding new entities to the dao to validate that the raw json data matches the defined * entity. */ public void validateEntityClass() { AcceloApi api = AcceloApi.getInstance(); AcceloFilter<E> filter = new AcceloFilter<>(); String rawResponse = api.getRaw(this.getEndPoint(), filter, AcceloFieldList.ALL, this.getResponseListClass()); @SuppressWarnings("unchecked") ResponseForValidation response = new Gson().fromJson(rawResponse, ResponseForValidation.class); JsonValidator.validate(getEntityClass(), response.response[0]); } public class ResponseForValidation { Meta meta; Entity[] response; } static class Entity extends HashMap<String, String> { private static final long serialVersionUID = 1L; } /** * Overload this method to apply validation on the entity before it is inserted. * * @param entity */ void preInsertValidation(E entity) { // default validation takes no action. } /** * Overload this method to apply validation on the entity before it is update. By default this method calls * preInsertValidation(E entity) * * @param entity */ void preUpdateValidation(E entity) { preInsertValidation(entity); } /** * Override this method if you need to have you Dao return other than the default fieldlist of ALL. This is * typcially used to get sub-objects like the ticket priority field which can't be gotten via a direct api call. */ protected AcceloFieldList getFieldList() { AcceloFieldList fields = new AcceloFieldList(); fields.add("_ALL"); return fields; } }
package tk.mybatis.mapper.mapperhelper; import tk.mybatis.mapper.LogicDeleteException; import tk.mybatis.mapper.annotation.LogicDelete; import tk.mybatis.mapper.annotation.Version; import tk.mybatis.mapper.entity.EntityColumn; import tk.mybatis.mapper.entity.IDynamicTableName; import tk.mybatis.mapper.util.StringUtil; import tk.mybatis.mapper.version.VersionException; import java.util.Set; /** * SQL * * @author liuzh * @since 2015-11-03 22:40 */ public class SqlHelper { /** * - * * @param entityClass * @param tableName * @return */ public static String getDynamicTableName(Class<?> entityClass, String tableName) { if (IDynamicTableName.class.isAssignableFrom(entityClass)) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(_parameter) and dynamicTableName != null and dynamicTableName != ''\">"); sql.append("${dynamicTableName}\n"); sql.append("</when>"); sql.append("<otherwise>"); sql.append(tableName); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } else { return tableName; } } /** * - parameterName@Param * * @param entityClass * @param tableName * @param parameterName * @return */ public static String getDynamicTableName(Class<?> entityClass, String tableName, String parameterName) { if (IDynamicTableName.class.isAssignableFrom(entityClass)) { if (StringUtil.isNotEmpty(parameterName)) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@isDynamicParameter(" + parameterName + ") and " + parameterName + ".dynamicTableName != null and " + parameterName + ".dynamicTableName != ''\">"); sql.append("${" + parameterName + ".dynamicTableName}"); sql.append("</when>"); sql.append("<otherwise>"); sql.append(tableName); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } else { return getDynamicTableName(entityClass, tableName); } } else { return tableName; } } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getBindCache(EntityColumn column) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\""); sql.append(column.getProperty()).append("_cache\" "); sql.append("value=\"").append(column.getProperty()).append("\"/>"); return sql.toString(); } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getBindValue(EntityColumn column, String value) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\""); sql.append(column.getProperty()).append("_bind\" "); sql.append("value='").append(value).append("'/>"); return sql.toString(); } /** * <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> * * @param column * @return */ public static String getIfCacheNotNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache != null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * _cache == null * * @param column * @return */ public static String getIfCacheIsNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache == null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * !=null * * @param column * @param contents * @param empty * @return */ public static String getIfNotNull(EntityColumn column, String contents, boolean empty) { return getIfNotNull(null, column, contents, empty); } /** * ==null * * @param column * @param contents * @param empty * @return */ public static String getIfIsNull(EntityColumn column, String contents, boolean empty) { return getIfIsNull(null, column, contents, empty); } /** * !=null * * @param entityName * @param column * @param contents * @param empty * @return */ public static String getIfNotNull(String entityName, EntityColumn column, String contents, boolean empty) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\""); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" != null"); if (empty && column.getJavaType().equals(String.class)) { sql.append(" and "); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" != '' "); } sql.append("\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * ==null * * @param entityName * @param column * @param contents * @param empty * @return */ public static String getIfIsNull(String entityName, EntityColumn column, String contents, boolean empty) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\""); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" == null"); if (empty && column.getJavaType().equals(String.class)) { sql.append(" or "); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(" == '' "); } sql.append("\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); } /** * id,name,code... * * @param entityClass * @return */ public static String getAllColumns(Class<?> entityClass) { Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); StringBuilder sql = new StringBuilder(); for (EntityColumn entityColumn : columnSet) { sql.append(entityColumn.getColumn()).append(","); } return sql.substring(0, sql.length() - 1); } /** * select xxx,xxx... * * @param entityClass * @return */ public static String selectAllColumns(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT "); sql.append(getAllColumns(entityClass)); sql.append(" "); return sql.toString(); } /** * select count(x) * * @param entityClass * @return */ public static String selectCount(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT "); Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass); if (pkColumns.size() == 1) { sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") "); } else { sql.append("COUNT(*) "); } return sql.toString(); } /** * select case when count(x) > 0 then 1 else 0 end * * @param entityClass * @return */ public static String selectCountExists(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("SELECT CASE WHEN "); Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass); if (pkColumns.size() == 1) { sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") "); } else { sql.append("COUNT(*) "); } sql.append(" > 0 THEN 1 ELSE 0 END AS result "); return sql.toString(); } /** * from tableName - * * @param entityClass * @param defaultTableName * @return */ public static String fromTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append(" FROM "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * update tableName - * * @param entityClass * @param defaultTableName * @return */ public static String updateTable(Class<?> entityClass, String defaultTableName) { return updateTable(entityClass, defaultTableName, null); } /** * update tableName - * * @param entityClass * @param defaultTableName * @param entityName * @return */ public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE "); sql.append(getDynamicTableName(entityClass, defaultTableName, entityName)); sql.append(" "); return sql.toString(); } /** * delete tableName - * * @param entityClass * @param defaultTableName * @return */ public static String deleteFromTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * insert into tableName - * * @param entityClass * @param defaultTableName * @return */ public static String insertIntoTable(Class<?> entityClass, String defaultTableName) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO "); sql.append(getDynamicTableName(entityClass, defaultTableName)); sql.append(" "); return sql.toString(); } /** * insert into tableName - * * @param entityClass * @param defaultTableName * @param parameterName * @return */ public static String insertIntoTable(Class<?> entityClass, String defaultTableName, String parameterName) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO "); sql.append(getDynamicTableName(entityClass, defaultTableName, parameterName)); sql.append(" "); return sql.toString(); } /** * insert table() * * @param entityClass * @param skipId id * @param notNull !=null * @param notEmpty String!='' * @return */ public static String insertColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); for (EntityColumn column : columnSet) { if (!column.isInsertable()) { continue; } if (skipId && column.isId()) { continue; } if (notNull) { sql.append(SqlHelper.getIfNotNull(column, column.getColumn() + ",", notEmpty)); } else { sql.append(column.getColumn() + ","); } } sql.append("</trim>"); return sql.toString(); } /** * insert-values() * * @param entityClass * @param skipId id * @param notNull !=null * @param notEmpty String!='' * @return */ public static String insertValuesColumns(Class<?> entityClass, boolean skipId, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<trim prefix=\"VALUES (\" suffix=\")\" suffixOverrides=\",\">"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); for (EntityColumn column : columnSet) { if (!column.isInsertable()) { continue; } if (skipId && column.isId()) { continue; } if (notNull) { sql.append(SqlHelper.getIfNotNull(column, column.getColumnHolder() + ",", notEmpty)); } else { sql.append(column.getColumnHolder() + ","); } } sql.append("</trim>"); return sql.toString(); } /** * update set * * @param entityClass * @param entityName * @param notNull !=null * @param notEmpty String!='' * @return */ public static String updateSetColumns(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<set>"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); EntityColumn versionColumn = null; EntityColumn logicDeleteColumn = null; for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(Version.class)) { if (versionColumn != null) { throw new VersionException(entityClass.getCanonicalName() + " @Version @Version !"); } versionColumn = column; } if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { if (logicDeleteColumn != null) { throw new LogicDeleteException(entityClass.getCanonicalName() + " @LogicDelete @LogicDelete !"); } logicDeleteColumn = column; } if (!column.isId() && column.isUpdatable()) { if (column == versionColumn) { Version version = versionColumn.getEntityField().getAnnotation(Version.class); String versionClass = version.nextVersion().getCanonicalName(); sql.append("<bind name=\"").append(column.getProperty()).append("Version\" value=\""); //version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)} sql.append("@tk.mybatis.mapper.version.VersionUtil@nextVersion(") .append("@").append(versionClass).append("@class, "); if (StringUtil.isNotEmpty(entityName)) { sql.append(entityName).append("."); } sql.append(column.getProperty()).append(")\"/>"); sql.append(column.getColumn()).append(" = #{").append(column.getProperty()).append("Version},"); } else if (column == logicDeleteColumn) { sql.append(logicDeleteColumnEqualsValue(column, false)).append(","); } else if (notNull) { sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty)); } else { sql.append(column.getColumnEqualsHolder(entityName) + ","); } } } sql.append("</set>"); return sql.toString(); } /** * update set @Version * * @param entityClass * @param entityName * @param notNull !=null * @param notEmpty String!='' * @return */ public static String updateSetColumnsIgnoreVersion(Class<?> entityClass, String entityName, boolean notNull, boolean notEmpty) { StringBuilder sql = new StringBuilder(); sql.append("<set>"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); EntityColumn logicDeleteColumn = null; for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { if (logicDeleteColumn != null) { throw new LogicDeleteException(entityClass.getCanonicalName() + " @LogicDelete @LogicDelete !"); } logicDeleteColumn = column; } if (!column.isId() && column.isUpdatable()) { if (column.getEntityField().isAnnotationPresent(Version.class)) { //ignore } else if (column == logicDeleteColumn) { sql.append(logicDeleteColumnEqualsValue(column, false)).append(","); } else if (notNull) { sql.append(SqlHelper.getIfNotNull(entityName, column, column.getColumnEqualsHolder(entityName) + ",", notEmpty)); } else { sql.append(column.getColumnEqualsHolder(entityName) + ","); } } } sql.append("</set>"); return sql.toString(); } /** * null * * @param parameterName * @param columnSet * @return */ public static String notAllNullParameterCheck(String parameterName, Set<EntityColumn> columnSet) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"notAllNullParameterCheck\" value=\"@tk.mybatis.mapper.util.OGNL@notAllNullParameterCheck("); sql.append(parameterName).append(", '"); StringBuilder fields = new StringBuilder(); for (EntityColumn column : columnSet) { if (fields.length() > 0) { fields.append(","); } fields.append(column.getProperty()); } sql.append(fields); sql.append("')\"/>"); return sql.toString(); } /** * Example 1 * * @param parameterName * @return */ public static String exampleHasAtLeastOneCriteriaCheck(String parameterName) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"exampleHasAtLeastOneCriteriaCheck\" value=\"@tk.mybatis.mapper.util.OGNL@exampleHasAtLeastOneCriteriaCheck("); sql.append(parameterName).append(")\"/>"); return sql.toString(); } /** * where * * @param entityClass * @return */ public static String wherePKColumns(Class<?> entityClass) { return wherePKColumns(entityClass, false); } /** * where * * @param entityClass * @param useVersion * @return */ public static String wherePKColumns(Class<?> entityClass, boolean useVersion) { return wherePKColumns(entityClass, null, useVersion); } /** * where * * @param entityClass * @param entityName * @param useVersion * @return */ public static String wherePKColumns(Class<?> entityClass, String entityName, boolean useVersion) { StringBuilder sql = new StringBuilder(); boolean hasLogicDelete = hasLogicDeleteColumn(entityClass); sql.append("<where>"); Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass); for (EntityColumn column : columnSet) { sql.append(" AND ").append(column.getColumnEqualsHolder(entityName)); } if (useVersion) { sql.append(whereVersion(entityClass)); } if (hasLogicDelete) { sql.append(whereLogicDelete(entityClass, false)); } sql.append("</where>"); return sql.toString(); } /** * where!=null * * @param entityClass * @param empty * @return */ public static String whereAllIfColumns(Class<?> entityClass, boolean empty) { return whereAllIfColumns(entityClass, empty, false); } /** * where!=null * * @param entityClass * @param empty * @param useVersion * @return */ public static String whereAllIfColumns(Class<?> entityClass, boolean empty, boolean useVersion) { StringBuilder sql = new StringBuilder(); boolean hasLogicDelete = false; sql.append("<where>"); Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); EntityColumn logicDeleteColumn = SqlHelper.getLogicDeleteColumn(entityClass); for (EntityColumn column : columnSet) { if (!useVersion || !column.getEntityField().isAnnotationPresent(Version.class)) { if (logicDeleteColumn != null && logicDeleteColumn == column) { hasLogicDelete = true; continue; } sql.append(getIfNotNull(column, " AND " + column.getColumnEqualsHolder(), empty)); } } if (useVersion) { sql.append(whereVersion(entityClass)); } if (hasLogicDelete) { sql.append(whereLogicDelete(entityClass, false)); } sql.append("</where>"); return sql.toString(); } /** * * * @param entityClass * @return */ public static String whereVersion(Class<?> entityClass) { Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); boolean hasVersion = false; String result = ""; for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(Version.class)) { if (hasVersion) { throw new VersionException(entityClass.getCanonicalName() + " @Version @Version !"); } hasVersion = true; result = " AND " + column.getColumnEqualsHolder(); } } return result; } /** * where * <br> * AND column = value * * @param entityClass * @param isDeleted truefalse * @return */ public static String whereLogicDelete(Class<?> entityClass, boolean isDeleted) { String value = logicDeleteColumnEqualsValue(entityClass, isDeleted); return "".equals(value) ? "" : " AND " + value; } /** * : column = value * <br> * isDeletedValue = 1 notDeletedValue = 0 * <br> * is_deleted = 1 is_deleted = 0 * <br> * * * @param entityClass * @param isDeleted true false */ public static String logicDeleteColumnEqualsValue(Class<?> entityClass, boolean isDeleted) { EntityColumn logicDeleteColumn = SqlHelper.getLogicDeleteColumn(entityClass); if (logicDeleteColumn != null) { return logicDeleteColumnEqualsValue(logicDeleteColumn, isDeleted); } return ""; } /** * : column = value * <br> * isDeletedValue = 1 notDeletedValue = 0 * <br> * is_deleted = 1 is_deleted = 0 * <br> * * * @param column * @param isDeleted true false */ public static String logicDeleteColumnEqualsValue(EntityColumn column, boolean isDeleted) { String result = ""; if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { result = column.getColumn() + " = " + getLogicDeletedValue(column, isDeleted); } return result; } /** * * * @param column * @param isDeleted truefalse * @return */ public static int getLogicDeletedValue(EntityColumn column, boolean isDeleted) { if (!column.getEntityField().isAnnotationPresent(LogicDelete.class)) { throw new LogicDeleteException(column.getColumn() + " @LogicDelete !"); } LogicDelete logicDelete = column.getEntityField().getAnnotation(LogicDelete.class); if (isDeleted) { return logicDelete.isDeletedValue(); } return logicDelete.notDeletedValue(); } /** * * * @param entityClass * @return */ public static boolean hasLogicDeleteColumn(Class<?> entityClass) { return getLogicDeleteColumn(entityClass) != null; } /** * null * * @param entityClass * @return */ public static EntityColumn getLogicDeleteColumn(Class<?> entityClass) { EntityColumn logicDeleteColumn = null; Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass); boolean hasLogicDelete = false; for (EntityColumn column : columnSet) { if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { if (hasLogicDelete) { throw new LogicDeleteException(entityClass.getCanonicalName() + " @LogicDelete @LogicDelete !"); } hasLogicDelete = true; logicDeleteColumn = column; } } return logicDeleteColumn; } /** * orderBy * * @param entityClass * @return */ public static String orderByDefault(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append(" ORDER BY "); sql.append(orderByClause); } return sql.toString(); } /** * example * * @return */ public static String exampleSelectColumns(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasSelectColumns(_parameter)\">"); sql.append("<foreach collection=\"_parameter.selectColumns\" item=\"selectColumn\" separator=\",\">"); sql.append("${selectColumn}"); sql.append("</foreach>"); sql.append("</when>"); sql.append("<otherwise>"); sql.append(getAllColumns(entityClass)); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } /** * example * * @return */ public static String exampleCountColumn(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<choose>"); sql.append("<when test=\"@tk.mybatis.mapper.util.OGNL@hasCountColumn(_parameter)\">"); sql.append("COUNT(<if test=\"distinct\">distinct </if>${countColumn})"); sql.append("</when>"); sql.append("<otherwise>"); sql.append("COUNT(*)"); sql.append("</otherwise>"); sql.append("</choose>"); return sql.toString(); } /** * exampleorderByorderBy * * @return */ public static String exampleOrderBy(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"orderByClause != null\">"); sql.append("order by ${orderByClause}"); sql.append("</if>"); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append("<if test=\"orderByClause == null\">"); sql.append("ORDER BY " + orderByClause); sql.append("</if>"); } return sql.toString(); } /** * exampleorderByorderBy * * @return */ public static String exampleOrderBy(String entityName, Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(entityName).append(".orderByClause != null\">"); sql.append("order by ${").append(entityName).append(".orderByClause}"); sql.append("</if>"); String orderByClause = EntityHelper.getOrderByClause(entityClass); if (orderByClause.length() > 0) { sql.append("<if test=\"").append(entityName).append(".orderByClause == null\">"); sql.append("ORDER BY " + orderByClause); sql.append("</if>"); } return sql.toString(); } /** * example for update * * @return */ public static String exampleForUpdate() { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"@tk.mybatis.mapper.util.OGNL@hasForUpdate(_parameter)\">"); sql.append("FOR UPDATE"); sql.append("</if>"); return sql.toString(); } /** * example for update * * @return */ public static String exampleCheck(Class<?> entityClass) { StringBuilder sql = new StringBuilder(); sql.append("<bind name=\"checkExampleEntityClass\" value=\"@tk.mybatis.mapper.util.OGNL@checkExampleEntityClass(_parameter, '"); sql.append(entityClass.getCanonicalName()); sql.append("')\"/>"); return sql.toString(); } /** * ExamplewhereExample * * @return */ public static String exampleWhereClause() { return "<if test=\"_parameter != null\">" + "<where>\n" + " ${@tk.mybatis.mapper.util.OGNL@andNotLogicDelete(_parameter)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"oredCriteria\" item=\"criteria\">\n" + " <if test=\"criteria.valid\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" + " <choose>\n" + " <when test=\"criterion.noValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " </when>\n" + " <when test=\"criterion.singleValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" + " </when>\n" + " <when test=\"criterion.betweenValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" + " </when>\n" + " <when test=\"criterion.listValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" + " #{listItem}\n" + " </foreach>\n" + " </when>\n" + " </choose>\n" + " </foreach>\n" + " </trim>\n" + " </if>\n" + " </foreach>\n" + " </trim>\n" + "</where>" + "</if>"; } /** * Example-UpdatewhereExample@Param("example") * * @return */ public static String updateByExampleWhereClause() { return "<where>\n" + " ${@tk.mybatis.mapper.util.OGNL@andNotLogicDelete(example)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"example.oredCriteria\" item=\"criteria\">\n" + " <if test=\"criteria.valid\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criteria)}" + " <trim prefix=\"(\" prefixOverrides=\"and |or \" suffix=\")\">\n" + " <foreach collection=\"criteria.criteria\" item=\"criterion\">\n" + " <choose>\n" + " <when test=\"criterion.noValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " </when>\n" + " <when test=\"criterion.singleValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value}\n" + " </when>\n" + " <when test=\"criterion.betweenValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition} #{criterion.value} and #{criterion.secondValue}\n" + " </when>\n" + " <when test=\"criterion.listValue\">\n" + " ${@tk.mybatis.mapper.util.OGNL@andOr(criterion)} ${criterion.condition}\n" + " <foreach close=\")\" collection=\"criterion.value\" item=\"listItem\" open=\"(\" separator=\",\">\n" + " #{listItem}\n" + " </foreach>\n" + " </when>\n" + " </choose>\n" + " </foreach>\n" + " </trim>\n" + " </if>\n" + " </foreach>\n" + " </trim>\n" + "</where>"; } }
package nl.b3p.viewer.print; import java.io.ByteArrayInputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.parsers.DocumentBuilderFactory; import org.json.JSONObject; import org.w3c.dom.Node; /** * * @author Meine Toonen */ @XmlType//(propOrder = {"className","componentName","info"}) public class PrintExtraInfo { private String className; private String componentName; private Node info; @XmlAttribute(name="classname") public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @XmlAttribute(name ="componentname") public String getComponentName() { return componentName; } public void setComponentName(String componentName) { this.componentName = componentName; } @XmlAnyElement public Node getInfo() { return info; } public void setInfoText(JSONObject j) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); JSONObject root = new JSONObject(); root.put("root", j); String s = org.json.XML.toString(root); // replace spaces in element names, because the json lib we use is not // smart enough and the produces string will have spaces in element names // is attribute nems have spaces final Pattern p = Pattern.compile("(?s)(?<=<).*?(?=/?>|\\s*\\w+\\s*=)"); Matcher m = p.matcher(s); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group().replace(" ", "_")); } m.appendTail(sb); s = sb.toString(); this.info =dbf.newDocumentBuilder().parse(new ByteArrayInputStream(s.getBytes("UTF-8"))).getDocumentElement(); } }
package org.citydb.modules.kml.database; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import javax.vecmath.Point3d; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import net.opengis.kml._2.AltitudeModeEnumType; import net.opengis.kml._2.BoundaryType; import net.opengis.kml._2.LinearRingType; import net.opengis.kml._2.LinkType; import net.opengis.kml._2.LocationType; import net.opengis.kml._2.ModelType; import net.opengis.kml._2.MultiGeometryType; import net.opengis.kml._2.OrientationType; import net.opengis.kml._2.PlacemarkType; import net.opengis.kml._2.PolygonType; import org.citydb.api.database.DatabaseGeometryConverter; import org.citydb.api.database.DatabaseSrs; import org.citydb.api.event.EventDispatcher; import org.citydb.api.geometry.GeometryObject; import org.citydb.api.geometry.GeometryObject.ElementType; import org.citydb.api.geometry.GeometryObject.GeometryType; import org.citydb.api.log.LogLevel; import org.citydb.config.Config; import org.citydb.config.project.kmlExporter.AltitudeOffsetMode; import org.citydb.config.project.kmlExporter.Balloon; import org.citydb.config.project.kmlExporter.ColladaOptions; import org.citydb.config.project.kmlExporter.DisplayForm; import org.citydb.config.project.kmlExporter.KmlExporter; import org.citydb.database.adapter.AbstractDatabaseAdapter; import org.citydb.database.adapter.BlobExportAdapter; import org.citydb.log.Logger; import org.citydb.modules.common.balloon.BalloonTemplateHandlerImpl; import org.citydb.modules.common.event.CounterEvent; import org.citydb.modules.common.event.CounterType; import org.citydb.modules.common.event.GeometryCounterEvent; import org.citydb.modules.kml.datatype.TypeAttributeValueEnum; import org.citydb.textureAtlas.TextureAtlasCreator; import org.citydb.textureAtlas.image.ImageReader; import org.citydb.textureAtlas.model.TextureImage; import org.citydb.textureAtlas.model.TextureImagesInfo; import org.citydb.util.Util; import org.citygml4j.model.citygml.CityGMLClass; import org.citygml4j.model.citygml.appearance.Color; import org.citygml4j.model.citygml.appearance.X3DMaterial; import org.collada._2005._11.colladaschema.Accessor; import org.collada._2005._11.colladaschema.Asset; import org.collada._2005._11.colladaschema.BindMaterial; import org.collada._2005._11.colladaschema.COLLADA; import org.collada._2005._11.colladaschema.CommonColorOrTextureType; import org.collada._2005._11.colladaschema.CommonFloatOrParamType; import org.collada._2005._11.colladaschema.CommonNewparamType; import org.collada._2005._11.colladaschema.CommonTransparentType; import org.collada._2005._11.colladaschema.Effect; import org.collada._2005._11.colladaschema.Extra; import org.collada._2005._11.colladaschema.FloatArray; import org.collada._2005._11.colladaschema.FxOpaqueEnum; import org.collada._2005._11.colladaschema.FxSampler2DCommon; import org.collada._2005._11.colladaschema.FxSurfaceCommon; import org.collada._2005._11.colladaschema.FxSurfaceInitFromCommon; import org.collada._2005._11.colladaschema.Geometry; import org.collada._2005._11.colladaschema.Image; import org.collada._2005._11.colladaschema.InputLocal; import org.collada._2005._11.colladaschema.InputLocalOffset; import org.collada._2005._11.colladaschema.InstanceEffect; import org.collada._2005._11.colladaschema.InstanceGeometry; import org.collada._2005._11.colladaschema.InstanceMaterial; import org.collada._2005._11.colladaschema.InstanceWithExtra; import org.collada._2005._11.colladaschema.LibraryEffects; import org.collada._2005._11.colladaschema.LibraryGeometries; import org.collada._2005._11.colladaschema.LibraryImages; import org.collada._2005._11.colladaschema.LibraryMaterials; import org.collada._2005._11.colladaschema.LibraryVisualScenes; import org.collada._2005._11.colladaschema.Material; import org.collada._2005._11.colladaschema.Mesh; import org.collada._2005._11.colladaschema.ObjectFactory; import org.collada._2005._11.colladaschema.Param; import org.collada._2005._11.colladaschema.ProfileCOMMON; import org.collada._2005._11.colladaschema.Source; import org.collada._2005._11.colladaschema.Technique; import org.collada._2005._11.colladaschema.Triangles; import org.collada._2005._11.colladaschema.UpAxisType; import org.collada._2005._11.colladaschema.Vertices; import org.collada._2005._11.colladaschema.VisualScene; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.sun.j3d.utils.geometry.GeometryInfo; public abstract class KmlGenericObject { protected final int GEOMETRY_AMOUNT_WARNING = 10000; private final double TOLERANCE = Math.pow(10, -7); private final double PRECISION = Math.pow(10, 7); private final String NO_TEXIMAGE = "default"; private HashMap<Long, SurfaceInfo> surfaceInfos = new HashMap<Long, SurfaceInfo>(); private NodeZ coordinateTree; // key is surfaceId, surfaceId is originally a Long, here we use an Object for compatibility with the textureAtlasAPI private HashMap<Object, String> texImageUris = new HashMap<Object, String>(); // key is imageUri private HashMap<String, TextureImage> texImages = new HashMap<String, TextureImage>(); // for images in unusual formats or wrapping textures. Most times it will be null. // key is imageUri private HashMap<String, Long> unsupportedTexImageIds = null; // key is surfaceId, surfaceId is originally a Long private HashMap<Long, X3DMaterial> x3dMaterials = null; private long id; private String gmlId; private BigInteger vertexIdCounter = new BigInteger("-1"); protected VertexInfo firstVertexInfo = null; private VertexInfo lastVertexInfo = null; // origin of the relative coordinates for the object private List<Point3d> origins = new ArrayList<Point3d>(); private Point3d origin = new Point3d(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); // placemark location in WGS84 private Point3d location = new Point3d(); private double zOffset; private boolean ignoreSurfaceOrientation = true; protected Connection connection; protected KmlExporterManager kmlExporterManager; protected net.opengis.kml._2.ObjectFactory kmlFactory; protected AbstractDatabaseAdapter databaseAdapter; protected BlobExportAdapter textureExportAdapter; protected DatabaseGeometryConverter geometryConverterAdapter; protected ElevationServiceHandler elevationServiceHandler; protected BalloonTemplateHandlerImpl balloonTemplateHandler; protected EventDispatcher eventDispatcher; protected Config config; protected int currentLod; protected DatabaseSrs dbSrs; protected X3DMaterial defaultX3dMaterial; private SimpleDateFormat dateFormatter; protected final ImageReader imageReader; protected KmlGenericObject(Connection connection, KmlExporterManager kmlExporterManager, net.opengis.kml._2.ObjectFactory kmlFactory, AbstractDatabaseAdapter databaseAdapter, BlobExportAdapter textureExportAdapter, ElevationServiceHandler elevationServiceHandler, BalloonTemplateHandlerImpl balloonTemplateHandler, EventDispatcher eventDispatcher, Config config) { this.connection = connection; this.kmlExporterManager = kmlExporterManager; this.kmlFactory = kmlFactory; this.textureExportAdapter = textureExportAdapter; this.elevationServiceHandler = elevationServiceHandler; this.balloonTemplateHandler = balloonTemplateHandler; this.eventDispatcher = eventDispatcher; this.config = config; this.databaseAdapter = databaseAdapter; geometryConverterAdapter = databaseAdapter.getGeometryConverter(); dbSrs = databaseAdapter.getConnectionMetaData().getReferenceSystem(); dateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); defaultX3dMaterial = new X3DMaterial(); defaultX3dMaterial.setAmbientIntensity(0.2d); defaultX3dMaterial.setShininess(0.2d); defaultX3dMaterial.setTransparency(0d); defaultX3dMaterial.setDiffuseColor(getX3dColorFromString("0.8 0.8 0.8")); defaultX3dMaterial.setSpecularColor(getX3dColorFromString("1.0 1.0 1.0")); defaultX3dMaterial.setEmissiveColor(getX3dColorFromString("0.0 0.0 0.0")); imageReader = new ImageReader(); } public abstract void read(KmlSplittingResult work); public abstract String getStyleBasisName(); public abstract ColladaOptions getColladaOptions(); public abstract Balloon getBalloonSettings(); protected abstract List<DisplayForm> getDisplayForms(); protected abstract String getHighlightingQuery(); protected BalloonTemplateHandlerImpl getBalloonTemplateHandler() { return balloonTemplateHandler; } protected void setBalloonTemplateHandler(BalloonTemplateHandlerImpl balloonTemplateHandler) { this.balloonTemplateHandler = balloonTemplateHandler; } public void setId(long id) { this.id = id; } public long getId() { return id; } public void setGmlId(String gmlId) { this.gmlId = gmlId.replace(':', '_'); } public String getGmlId() { return gmlId; } protected void updateOrigins(double x, double y, double z) { // update origin and list of lowest points if (z < origin.z) { origins.clear(); origin.x = x; origin.y = y; origin.z = z; origins.add(origin); } else if (z == origin.z) origins.add(new Point3d(x, y, z)); } protected Point3d getOrigin() { return origin; } protected List<Point3d> getOrigins() { return origins; } protected void setZOffset(double zOffset) { this.zOffset = zOffset; } protected double getZOffset() { return zOffset; } protected Point3d getLocation() { return location; } protected void setLocation(double x, double y, double z) { location.x = x; location.y = y; location.z = z; } protected void setIgnoreSurfaceOrientation(boolean ignoreSurfaceOrientation) { this.ignoreSurfaceOrientation = ignoreSurfaceOrientation; } protected boolean isIgnoreSurfaceOrientation() { return ignoreSurfaceOrientation; } protected void addSurfaceInfo(long surfaceId, SurfaceInfo surfaceInfo) { surfaceInfos.put(surfaceId, surfaceInfo); } public COLLADA generateColladaTree() throws DatatypeConfigurationException{ ObjectFactory colladaFactory = new ObjectFactory(); // java and XML... DatatypeFactory df = DatatypeFactory.newInstance(); XMLGregorianCalendar xmlGregorianCalendar = df.newXMLGregorianCalendar(new GregorianCalendar()); xmlGregorianCalendar.setTimezone(DatatypeConstants.FIELD_UNDEFINED); COLLADA collada = colladaFactory.createCOLLADA(); collada.setVersion("1.4.1"); Asset asset = colladaFactory.createAsset(); asset.setCreated(xmlGregorianCalendar); asset.setModified(xmlGregorianCalendar); Asset.Unit unit = colladaFactory.createAssetUnit(); unit.setName("meters"); unit.setMeter(1.0); asset.setUnit(unit); asset.setUpAxis(UpAxisType.Z_UP); Asset.Contributor contributor = colladaFactory.createAssetContributor(); // System.getProperty("line.separator") produces weird effects here contributor.setAuthoringTool(this.getClass().getPackage().getImplementationTitle() + ", version " + this.getClass().getPackage().getImplementationVersion() + "; " + this.getClass().getPackage().getImplementationVendor()); asset.getContributor().add(contributor); collada.setAsset(asset); LibraryImages libraryImages = colladaFactory.createLibraryImages(); LibraryMaterials libraryMaterials = colladaFactory.createLibraryMaterials(); LibraryEffects libraryEffects = colladaFactory.createLibraryEffects(); LibraryGeometries libraryGeometries = colladaFactory.createLibraryGeometries(); LibraryVisualScenes libraryVisualScenes = colladaFactory.createLibraryVisualScenes(); Geometry geometry = colladaFactory.createGeometry(); geometry.setId("geometry0"); Source positionSource = colladaFactory.createSource(); positionSource.setId("geometry0-position"); FloatArray positionArray = colladaFactory.createFloatArray(); positionArray.setId("geometry0-position-array"); List<Double> positionValues = positionArray.getValue(); positionSource.setFloatArray(positionArray); Accessor positionAccessor = colladaFactory.createAccessor(); positionAccessor.setSource("#" + positionArray.getId()); positionAccessor.setStride(new BigInteger("3")); Param paramX = colladaFactory.createParam(); paramX.setType("float"); paramX.setName("X"); Param paramY = colladaFactory.createParam(); paramY.setType("float"); paramY.setName("Y"); Param paramZ = colladaFactory.createParam(); paramZ.setType("float"); paramZ.setName("Z"); positionAccessor.getParam().add(paramX); positionAccessor.getParam().add(paramY); positionAccessor.getParam().add(paramZ); Source.TechniqueCommon positionTechnique = colladaFactory.createSourceTechniqueCommon(); positionTechnique.setAccessor(positionAccessor); positionSource.setTechniqueCommon(positionTechnique); Source texCoordsSource = colladaFactory.createSource(); texCoordsSource.setId("geometry0-texCoords"); FloatArray texCoordsArray = colladaFactory.createFloatArray(); texCoordsArray.setId("geometry0-texCoords-array"); List<Double> texCoordsValues = texCoordsArray.getValue(); texCoordsSource.setFloatArray(texCoordsArray); Accessor texCoordsAccessor = colladaFactory.createAccessor(); texCoordsAccessor.setSource("#" + texCoordsArray.getId()); texCoordsAccessor.setStride(new BigInteger("2")); Param paramS = colladaFactory.createParam(); paramS.setType("float"); paramS.setName("S"); Param paramT = colladaFactory.createParam(); paramT.setType("float"); paramT.setName("T"); texCoordsAccessor.getParam().add(paramS); texCoordsAccessor.getParam().add(paramT); Source.TechniqueCommon texCoordsTechnique = colladaFactory.createSourceTechniqueCommon(); texCoordsTechnique.setAccessor(texCoordsAccessor); texCoordsSource.setTechniqueCommon(texCoordsTechnique); Vertices vertices = colladaFactory.createVertices(); vertices.setId("geometry0-vertex"); InputLocal input = colladaFactory.createInputLocal(); input.setSemantic("POSITION"); input.setSource("#" + positionSource.getId()); vertices.getInput().add(input); Mesh mesh = colladaFactory.createMesh(); mesh.getSource().add(positionSource); mesh.getSource().add(texCoordsSource); mesh.setVertices(vertices); geometry.setMesh(mesh); libraryGeometries.getGeometry().add(geometry); BigInteger texCoordsCounter = BigInteger.ZERO; VisualScene visualScene = colladaFactory.createVisualScene(); visualScene.setId("Building_" + gmlId); BindMaterial.TechniqueCommon techniqueCommon = colladaFactory.createBindMaterialTechniqueCommon(); BindMaterial bindMaterial = colladaFactory.createBindMaterial(); bindMaterial.setTechniqueCommon(techniqueCommon); InstanceGeometry instanceGeometry = colladaFactory.createInstanceGeometry(); instanceGeometry.setUrl("#" + geometry.getId()); instanceGeometry.setBindMaterial(bindMaterial); org.collada._2005._11.colladaschema.Node node = colladaFactory.createNode(); node.getInstanceGeometry().add(instanceGeometry); visualScene.getNode().add(node); libraryVisualScenes.getVisualScene().add(visualScene); Triangles triangles = null; HashMap<String, Triangles> trianglesByTexImageName = new HashMap<String, Triangles>(); // geometryInfos contains all surfaces, textured or not Set<Long> keySet = surfaceInfos.keySet(); Iterator<Long> iterator = keySet.iterator(); while (iterator.hasNext()) { Long surfaceId = iterator.next(); String texImageName = texImageUris.get(surfaceId); X3DMaterial x3dMaterial = getX3dMaterial(surfaceId); boolean surfaceTextured = true; if (texImageName == null) { surfaceTextured = false; texImageName = (x3dMaterial != null) ? buildNameFromX3dMaterial(x3dMaterial): NO_TEXIMAGE; // <- should never happen } triangles = trianglesByTexImageName.get(texImageName); if (triangles == null) { // never worked on this image or material before Material material = colladaFactory.createMaterial(); material.setId(replaceExtensionWithSuffix(texImageName, "_mat")); InstanceEffect instanceEffect = colladaFactory.createInstanceEffect(); instanceEffect.setUrl("#" + replaceExtensionWithSuffix(texImageName, "_eff")); material.setInstanceEffect(instanceEffect); libraryMaterials.getMaterial().add(material); Effect effect = colladaFactory.createEffect(); effect.setId(replaceExtensionWithSuffix(texImageName, "_eff")); ProfileCOMMON profileCommon = colladaFactory.createProfileCOMMON(); if (surfaceTextured) { Image image = colladaFactory.createImage(); image.setId(replaceExtensionWithSuffix(texImageName, "_img")); image.setInitFrom(texImageName); libraryImages.getImage().add(image); FxSurfaceInitFromCommon initFrom = colladaFactory.createFxSurfaceInitFromCommon(); initFrom.setValue(image); // evtl. image.getId(); FxSurfaceCommon surface = colladaFactory.createFxSurfaceCommon(); surface.setType("2D"); // ColladaConstants.SURFACE_TYPE_2D surface.getInitFrom().add(initFrom); CommonNewparamType newParam1 = colladaFactory.createCommonNewparamType(); newParam1.setSurface(surface); newParam1.setSid(replaceExtensionWithSuffix(texImageName, "_surface")); profileCommon.getImageOrNewparam().add(newParam1); FxSampler2DCommon sampler2D = colladaFactory.createFxSampler2DCommon(); sampler2D.setSource(newParam1.getSid()); CommonNewparamType newParam2 = colladaFactory.createCommonNewparamType(); newParam2.setSampler2D(sampler2D); newParam2.setSid(replaceExtensionWithSuffix(texImageName, "_sampler")); profileCommon.getImageOrNewparam().add(newParam2); ProfileCOMMON.Technique profileCommonTechnique = colladaFactory.createProfileCOMMONTechnique(); profileCommonTechnique.setSid("COMMON"); ProfileCOMMON.Technique.Lambert lambert = colladaFactory.createProfileCOMMONTechniqueLambert(); CommonColorOrTextureType.Texture texture = colladaFactory.createCommonColorOrTextureTypeTexture(); texture.setTexture(newParam2.getSid()); texture.setTexcoord("TEXCOORD"); // ColladaConstants.INPUT_SEMANTIC_TEXCOORD CommonColorOrTextureType ccott = colladaFactory.createCommonColorOrTextureType(); ccott.setTexture(texture); lambert.setDiffuse(ccott); profileCommonTechnique.setLambert(lambert); profileCommon.setTechnique(profileCommonTechnique); } else { ProfileCOMMON.Technique profileCommonTechnique = colladaFactory.createProfileCOMMONTechnique(); profileCommonTechnique.setSid("COMMON"); ProfileCOMMON.Technique.Lambert lambert = colladaFactory.createProfileCOMMONTechniqueLambert(); CommonFloatOrParamType cfopt = colladaFactory.createCommonFloatOrParamType(); CommonFloatOrParamType.Float cfoptf = colladaFactory.createCommonFloatOrParamTypeFloat(); if (x3dMaterial.isSetShininess()) { cfoptf.setValue(x3dMaterial.getShininess()); cfopt.setFloat(cfoptf); lambert.setReflectivity(cfopt); } if (x3dMaterial.isSetTransparency()) { cfopt = colladaFactory.createCommonFloatOrParamType(); cfoptf = colladaFactory.createCommonFloatOrParamTypeFloat(); cfoptf.setValue(1.0-x3dMaterial.getTransparency()); cfopt.setFloat(cfoptf); lambert.setTransparency(cfopt); CommonTransparentType transparent = colladaFactory.createCommonTransparentType(); transparent.setOpaque(FxOpaqueEnum.A_ONE); CommonColorOrTextureType.Color color = colladaFactory.createCommonColorOrTextureTypeColor(); color.getValue().add(1.0); color.getValue().add(1.0); color.getValue().add(1.0); color.getValue().add(1.0); transparent.setColor(color); lambert.setTransparent(transparent); } if (x3dMaterial.isSetDiffuseColor()) { CommonColorOrTextureType.Color color = colladaFactory.createCommonColorOrTextureTypeColor(); color.getValue().add(x3dMaterial.getDiffuseColor().getRed()); color.getValue().add(x3dMaterial.getDiffuseColor().getGreen()); color.getValue().add(x3dMaterial.getDiffuseColor().getBlue()); color.getValue().add(1d); // alpha CommonColorOrTextureType ccott = colladaFactory.createCommonColorOrTextureType(); ccott.setColor(color); lambert.setDiffuse(ccott); } if (x3dMaterial.isSetSpecularColor()) { CommonColorOrTextureType.Color color = colladaFactory.createCommonColorOrTextureTypeColor(); color.getValue().add(x3dMaterial.getSpecularColor().getRed()); color.getValue().add(x3dMaterial.getSpecularColor().getGreen()); color.getValue().add(x3dMaterial.getSpecularColor().getBlue()); color.getValue().add(1d); // alpha CommonColorOrTextureType ccott = colladaFactory.createCommonColorOrTextureType(); ccott.setColor(color); lambert.setReflective(ccott); } if (x3dMaterial.isSetEmissiveColor()) { CommonColorOrTextureType.Color color = colladaFactory.createCommonColorOrTextureTypeColor(); color.getValue().add(x3dMaterial.getEmissiveColor().getRed()); color.getValue().add(x3dMaterial.getEmissiveColor().getGreen()); color.getValue().add(x3dMaterial.getEmissiveColor().getBlue()); color.getValue().add(1d); // alpha CommonColorOrTextureType ccott = colladaFactory.createCommonColorOrTextureType(); ccott.setColor(color); lambert.setEmission(ccott); } profileCommonTechnique.setLambert(lambert); profileCommon.setTechnique(profileCommonTechnique); } Technique geTechnique = colladaFactory.createTechnique(); geTechnique.setProfile("GOOGLEEARTH"); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document document = docBuilder.newDocument(); factory.setNamespaceAware(true); Element doubleSided = document.createElementNS("http: doubleSided.setTextContent(ignoreSurfaceOrientation ? "1": "0"); geTechnique.getAny().add(doubleSided); } catch (ParserConfigurationException e) { e.printStackTrace(); } Extra extra = colladaFactory.createExtra(); extra.getTechnique().add(geTechnique); profileCommon.getExtra().add(extra); effect.getFxProfileAbstract().add(colladaFactory.createProfileCOMMON(profileCommon)); libraryEffects.getEffect().add(effect); triangles = colladaFactory.createTriangles(); triangles.setMaterial(replaceExtensionWithSuffix(texImageName, "_tri")); InputLocalOffset inputV = colladaFactory.createInputLocalOffset(); inputV.setSemantic("VERTEX"); // ColladaConstants.INPUT_SEMANTIC_VERTEX inputV.setSource("#" + vertices.getId()); inputV.setOffset(BigInteger.ZERO); triangles.getInput().add(inputV); if (surfaceTextured) { InputLocalOffset inputT = colladaFactory.createInputLocalOffset(); inputT.setSemantic("TEXCOORD"); // ColladaConstants.INPUT_SEMANTIC_TEXCOORD inputT.setSource("#" + texCoordsSource.getId()); inputT.setOffset(BigInteger.ONE); triangles.getInput().add(inputT); } trianglesByTexImageName.put(texImageName, triangles); } SurfaceInfo surfaceInfo = surfaceInfos.get(surfaceId); List<VertexInfo> vertexInfos = surfaceInfo.getVertexInfos(); double[] ordinatesArray = new double[vertexInfos.size() * 3]; int count = 0; for (VertexInfo vertexInfo : vertexInfos) { ordinatesArray[count++] = vertexInfo.getX() - origin.x; ordinatesArray[count++] = vertexInfo.getY() - origin.y; ordinatesArray[count++] = vertexInfo.getZ() - origin.z; } GeometryInfo ginfo = new GeometryInfo(GeometryInfo.POLYGON_ARRAY); ginfo.setCoordinates(ordinatesArray); ginfo.setContourCounts(surfaceInfo.getRingCountAsArray()); ginfo.setStripCounts(surfaceInfo.getVertexCount()); int outerRingCount = ginfo.getStripCounts()[0]; // triangulate the surface geometry ginfo.convertToIndexedTriangles(); // fix a reversed orientation of the triangulated surface int[] indexes = ginfo.getCoordinateIndices(); byte[] edges = {0, 1, 1, 2, 2, 0}; boolean hasFound = false; boolean reverseIndexes = false; for (int i = 0; !hasFound && i < indexes.length; i += 3) { // skip degenerated triangles if (indexes[i] == indexes[i + 1] || indexes[i + 1] == indexes[i + 2] || indexes[i] == indexes[i + 2]) continue; // find the first edge on the exterior ring for (int j = 0; j < edges.length; j += 2) { int first = i + edges[j]; int second = i + edges[j + 1]; if (indexes[first] < outerRingCount && indexes[second] < outerRingCount && Math.abs(indexes[first] - indexes[second]) == 1) { // ok, we found it. now check the order of the vertex indices hasFound = true; if (indexes[first] > indexes[second]) reverseIndexes = true; break; } } } if (reverseIndexes) { int[] tmp = new int[indexes.length]; int j = 0; for (int i = 0; i < indexes.length; i+=3) { tmp[j++] = indexes[i+2]; tmp[j++] = indexes[i+1]; tmp[j++] = indexes[i]; } indexes = tmp; } // use vertex indices of the triangulation to populate // the vertex arrays in the collada file for(int i = 0; i < indexes.length; i++) { VertexInfo vertexInfo = vertexInfos.get(indexes[i]); triangles.getP().add(vertexInfo.getVertexId()); if (surfaceTextured) { TexCoords texCoords = vertexInfo.getTexCoords(surfaceId); if (texCoords != null) { // trying to save some texture points int indexOfT = texCoordsValues.indexOf(texCoords.getT()); if (indexOfT > 0 && indexOfT%2 == 1 && // avoid coincidences texCoordsValues.get(indexOfT - 1).equals(texCoords.getS())) { triangles.getP().add(new BigInteger(String.valueOf((indexOfT - 1)/2))); } else { texCoordsValues.add(texCoords.getS()); texCoordsValues.add(texCoords.getT()); triangles.getP().add(texCoordsCounter); texCoordsCounter = texCoordsCounter.add(BigInteger.ONE); } } else { // should never happen triangles.getP().add(texCoordsCounter); // wrong data is better than triangles out of sync Logger.getInstance().log(LogLevel.DEBUG, "texCoords not found for (" + vertexInfo.getX() + ", " + vertexInfo.getY() + ", " + vertexInfo.getZ() + "). TOLERANCE = " + TOLERANCE); } } } } VertexInfo vertexInfoIterator = firstVertexInfo; while (vertexInfoIterator != null) { positionValues.add(reducePrecisionForXorY((vertexInfoIterator.getX() - origin.x))); positionValues.add(reducePrecisionForXorY((vertexInfoIterator.getY() - origin.y))); positionValues.add(reducePrecisionForZ((vertexInfoIterator.getZ() - origin.z))); vertexInfoIterator = vertexInfoIterator.getNextVertexInfo(); } positionArray.setCount(new BigInteger(String.valueOf(positionValues.size()))); // gotta love BigInteger! texCoordsArray.setCount(new BigInteger(String.valueOf(texCoordsValues.size()))); positionAccessor.setCount(positionArray.getCount().divide(positionAccessor.getStride())); texCoordsAccessor.setCount(texCoordsArray.getCount().divide(texCoordsAccessor.getStride())); Set<String> trianglesKeySet = trianglesByTexImageName.keySet(); Iterator<String> trianglesIterator = trianglesKeySet.iterator(); while (trianglesIterator.hasNext()) { String texImageName = trianglesIterator.next(); triangles = trianglesByTexImageName.get(texImageName); triangles.setCount(new BigInteger(String.valueOf(triangles.getP().size()/(3*triangles.getInput().size())))); if (texImageName.startsWith(NO_TEXIMAGE)) { // materials first, textures last mesh.getLinesOrLinestripsOrPolygons().add(0, triangles); } else { mesh.getLinesOrLinestripsOrPolygons().add(triangles); } InstanceMaterial instanceMaterial = colladaFactory.createInstanceMaterial(); instanceMaterial.setSymbol(triangles.getMaterial()); instanceMaterial.setTarget("#" + replaceExtensionWithSuffix(texImageName, "_mat")); techniqueCommon.getInstanceMaterial().add(instanceMaterial); } List<Object> libraries = collada.getLibraryAnimationsOrLibraryAnimationClipsOrLibraryCameras(); if (!libraryImages.getImage().isEmpty()) { // there may be buildings with no textures at all libraries.add(libraryImages); } libraries.add(libraryMaterials); libraries.add(libraryEffects); libraries.add(libraryGeometries); libraries.add(libraryVisualScenes); InstanceWithExtra instanceWithExtra = colladaFactory.createInstanceWithExtra(); instanceWithExtra.setUrl("#" + visualScene.getId()); COLLADA.Scene scene = colladaFactory.createCOLLADAScene(); scene.setInstanceVisualScene(instanceWithExtra); collada.setScene(scene); return collada; } private String replaceExtensionWithSuffix (String imageName, String suffix) { int indexOfExtension = imageName.lastIndexOf('.'); if (indexOfExtension != -1) { imageName = imageName.substring(0, indexOfExtension); } return imageName + suffix; } protected int getGeometryAmount(){ return surfaceInfos.size(); } protected void addX3dMaterial(long surfaceId, X3DMaterial x3dMaterial){ if (x3dMaterial == null) return; if (x3dMaterial.isSetAmbientIntensity() || x3dMaterial.isSetShininess() || x3dMaterial.isSetTransparency() || x3dMaterial.isSetDiffuseColor() || x3dMaterial.isSetSpecularColor() || x3dMaterial.isSetEmissiveColor()) { if (x3dMaterials == null) { x3dMaterials = new HashMap<Long, X3DMaterial>(); } x3dMaterials.put(new Long(surfaceId), x3dMaterial); } } protected X3DMaterial getX3dMaterial(long surfaceId) { X3DMaterial x3dMaterial = null; if (x3dMaterials != null) { x3dMaterial = x3dMaterials.get(new Long(surfaceId)); } return x3dMaterial; } protected void addTexImageUri(long surfaceId, String texImageUri){ if (texImageUri != null) { texImageUris.put(new Long(surfaceId), texImageUri); } } protected void addTexImage(String texImageUri, TextureImage texImage){ if (texImage != null) { texImages.put(texImageUri, texImage); } } protected void removeTexImage(String texImageUri){ texImages.remove(texImageUri); } public HashMap<String, TextureImage> getTexImages(){ return texImages; } protected TextureImage getTexImage(String texImageUri){ TextureImage texImage = null; if (texImages != null) { texImage = texImages.get(texImageUri); } return texImage; } protected void addUnsupportedTexImageId(String texImageUri, long surfaceDataId){ if (surfaceDataId < 0) { return; } if (unsupportedTexImageIds == null) { unsupportedTexImageIds = new HashMap<String, Long>(); } unsupportedTexImageIds.put(texImageUri, surfaceDataId); } public HashMap<String, Long> getUnsupportedTexImageIds(){ return unsupportedTexImageIds; } protected long getUnsupportedTexImageId(String texImageUri){ long surfaceDataId = -1; if (unsupportedTexImageIds != null) { Long tmp = unsupportedTexImageIds.get(texImageUri); if (tmp != null) surfaceDataId = tmp.longValue(); } return surfaceDataId; } protected VertexInfo setVertexInfoForXYZ(long surfaceId, double x, double y, double z){ vertexIdCounter = vertexIdCounter.add(BigInteger.ONE); VertexInfo vertexInfo = new VertexInfo(vertexIdCounter, x, y, z); NodeZ nodeToInsert = new NodeZ(z, new NodeY(y, new NodeX(x, vertexInfo))); if (coordinateTree == null) { coordinateTree = nodeToInsert; firstVertexInfo = vertexInfo; lastVertexInfo = vertexInfo; } else { Node node = insertNode(coordinateTree, nodeToInsert); if (node.value instanceof VertexInfo) vertexInfo = (VertexInfo)node.value; } return vertexInfo; } private Node insertNode(Node currentBasis, Node nodeToInsert) { int compareKeysResult = compareKeys(nodeToInsert.key, currentBasis.key, TOLERANCE); if (compareKeysResult > 0) { if (currentBasis.rightArc == null){ currentBasis.setRightArc(nodeToInsert); linkCurrentVertexInfoToLastVertexInfo(nodeToInsert); return nodeToInsert; } else { return insertNode(currentBasis.rightArc, nodeToInsert); } } else if (compareKeysResult < 0) { if (currentBasis.leftArc == null){ currentBasis.setLeftArc(nodeToInsert); linkCurrentVertexInfoToLastVertexInfo(nodeToInsert); return nodeToInsert; } else { return insertNode(currentBasis.leftArc, nodeToInsert); } } else { return replaceOrAddValue(currentBasis, nodeToInsert); } } private Node replaceOrAddValue(Node currentBasis, Node nodeToInsert) { if (nodeToInsert.value instanceof VertexInfo) { VertexInfo vertexInfoToInsert = (VertexInfo)nodeToInsert.value; if (currentBasis.value == null) { // no vertexInfo yet for this point currentBasis.value = nodeToInsert.value; linkCurrentVertexInfoToLastVertexInfo(vertexInfoToInsert); } else vertexIdCounter = vertexIdCounter.subtract(BigInteger.ONE); return currentBasis; } else { // Node return insertNode((Node)currentBasis.value, (Node)nodeToInsert.value); } } private void linkCurrentVertexInfoToLastVertexInfo (Node node) { while (!(node.value instanceof VertexInfo)) { node = (Node)node.value; } linkCurrentVertexInfoToLastVertexInfo((VertexInfo)node.value); } private void linkCurrentVertexInfoToLastVertexInfo (VertexInfo currentVertexInfo) { lastVertexInfo.setNextVertexInfo(currentVertexInfo); lastVertexInfo = currentVertexInfo; } private int compareKeys (double key1, double key2, double tolerance){ int result = 0; if (Math.abs(key1 - key2) > tolerance) { result = key1 > key2 ? 1 : -1; } return result; } public void appendObject (KmlGenericObject objectToAppend) { VertexInfo vertexInfoIterator = objectToAppend.firstVertexInfo; while (vertexInfoIterator != null) { if (vertexInfoIterator.getAllTexCoords() == null) { VertexInfo tmp = this.setVertexInfoForXYZ(-1, // dummy vertexInfoIterator.getX(), vertexInfoIterator.getY(), vertexInfoIterator.getZ()); vertexInfoIterator.setVertexId(tmp.getVertexId()); } else { Set<Long> keySet = vertexInfoIterator.getAllTexCoords().keySet(); Iterator<Long> iterator = keySet.iterator(); while (iterator.hasNext()) { Long surfaceId = iterator.next(); VertexInfo tmp = this.setVertexInfoForXYZ(surfaceId, vertexInfoIterator.getX(), vertexInfoIterator.getY(), vertexInfoIterator.getZ()); vertexInfoIterator.setVertexId(tmp.getVertexId()); tmp.addTexCoords(surfaceId, vertexInfoIterator.getTexCoords(surfaceId)); } } vertexInfoIterator = vertexInfoIterator.getNextVertexInfo(); } Set<Long> keySet = objectToAppend.surfaceInfos.keySet(); Iterator<Long> iterator = keySet.iterator(); while (iterator.hasNext()) { Long surfaceId = iterator.next(); this.addX3dMaterial(surfaceId, objectToAppend.getX3dMaterial(surfaceId)); String imageUri = objectToAppend.texImageUris.get(surfaceId); this.addTexImageUri(surfaceId, imageUri); this.addTexImage(imageUri, objectToAppend.getTexImage(imageUri)); this.addUnsupportedTexImageId(imageUri, objectToAppend.getUnsupportedTexImageId(imageUri)); this.surfaceInfos.put(surfaceId, objectToAppend.surfaceInfos.get(surfaceId)); } // adapt id accordingly int indexOf_to_ = this.gmlId.indexOf("_to_"); String ownLowerLimit = ""; String ownUpperLimit = ""; if (indexOf_to_ != -1) { // already more than one building in here ownLowerLimit = this.gmlId.substring(0, indexOf_to_); ownUpperLimit = this.gmlId.substring(indexOf_to_ + 4); } else { ownLowerLimit = this.gmlId; ownUpperLimit = ownLowerLimit; } int btaIndexOf_to_ = objectToAppend.gmlId.indexOf("_to_"); String btaLowerLimit = ""; String btaUpperLimit = ""; if (btaIndexOf_to_ != -1) { // already more than one building in there btaLowerLimit = objectToAppend.gmlId.substring(0, btaIndexOf_to_); btaUpperLimit = objectToAppend.gmlId.substring(btaIndexOf_to_ + 4); } else { btaLowerLimit = objectToAppend.gmlId; btaUpperLimit = btaLowerLimit; } ownLowerLimit = ownLowerLimit.compareTo(btaLowerLimit)<0 ? ownLowerLimit: btaLowerLimit; ownUpperLimit = ownUpperLimit.compareTo(btaUpperLimit)>0 ? ownUpperLimit: btaUpperLimit; this.setGmlId(String.valueOf(ownLowerLimit) + "_to_" + ownUpperLimit); } public void createTextureAtlas(int packingAlgorithm, double imageScaleFactor, boolean pots) throws SQLException, IOException { if (texImages.size() < 2) { // building has not enough textures or they are in an unknown image format return; } useExternalTAGenerator(packingAlgorithm, imageScaleFactor, pots); } private void useExternalTAGenerator(int packingAlgorithm, double scaleFactor, boolean pots) throws SQLException, IOException { // in some cases, several buildings may share one monster texture image. // This function is used to crop such big image into small pieces for each surface geometry before creating the TextureAltas // Currently, it is difficult to detect, if one image is shared by more than one building of not. // Therefore, this function is called in all cases. It should be improved in the future... cropImages(packingAlgorithm); TextureAtlasCreator taCreator = new TextureAtlasCreator(); TextureImagesInfo tiInfo = new TextureImagesInfo(); tiInfo.setTexImageURIs(texImageUris); tiInfo.setTexImages(texImages); // texture coordinates HashMap<Object, String> tiInfoCoords = new HashMap<Object, String>(); Set<Object> sgIdSet = texImageUris.keySet(); Iterator<Object> sgIdIterator = sgIdSet.iterator(); while (sgIdIterator.hasNext()) { Long sgId = (Long) sgIdIterator.next(); VertexInfo vertexInfoIterator = firstVertexInfo; while (vertexInfoIterator != null) { if (vertexInfoIterator.getAllTexCoords() != null && vertexInfoIterator.getAllTexCoords().containsKey(sgId)) { double s = vertexInfoIterator.getTexCoords(sgId).getS(); double t = vertexInfoIterator.getTexCoords(sgId).getT(); String tiInfoCoordsForSgId = tiInfoCoords.get(sgId); tiInfoCoordsForSgId = (tiInfoCoordsForSgId == null) ? "" : tiInfoCoordsForSgId + " "; tiInfoCoords.put(sgId, tiInfoCoordsForSgId + String.valueOf(s) + " " + String.valueOf(t)); } vertexInfoIterator = vertexInfoIterator.getNextVertexInfo(); } } tiInfo.setTexCoordinates(tiInfoCoords); taCreator.setUsePOTS(pots); taCreator.setScaleFactor(scaleFactor); // create texture atlases taCreator.convert(tiInfo, packingAlgorithm); sgIdIterator = sgIdSet.iterator(); while (sgIdIterator.hasNext()) { Long sgId = (Long) sgIdIterator.next(); StringTokenizer texCoordsTokenized = new StringTokenizer(tiInfoCoords.get(sgId), " "); VertexInfo vertexInfoIterator = firstVertexInfo; while (texCoordsTokenized.hasMoreElements() && vertexInfoIterator != null) { if (vertexInfoIterator.getAllTexCoords() != null && vertexInfoIterator.getAllTexCoords().containsKey(sgId)) { vertexInfoIterator.getTexCoords(sgId).setS(Double.parseDouble(texCoordsTokenized.nextToken())); vertexInfoIterator.getTexCoords(sgId).setT(Double.parseDouble(texCoordsTokenized.nextToken())); } vertexInfoIterator = vertexInfoIterator.getNextVertexInfo(); } } } private void cropImages (int packingAlgorithm) { if (texImageUris.size() > 1000 && (packingAlgorithm == TextureAtlasCreator.TPIM || packingAlgorithm == TextureAtlasCreator.TPIM_WO_ROTATION)) { // too many pieces lead to crash when using TPIM algorithm return; } HashMap<String, TextureImage> newTexImages = new HashMap<String, TextureImage>(); Set<Object> sgIdSet = texImageUris.keySet(); Iterator<Object> sgIdIterator = sgIdSet.iterator(); while (sgIdIterator.hasNext()) { Long sgId = (Long) sgIdIterator.next(); // step 1: get maximal and minimal coordinates VertexInfo vertexInfoIterator = firstVertexInfo; double maxS = 0; double minS = Double.MAX_VALUE; double maxT = 0; double minT = Double.MAX_VALUE; while (vertexInfoIterator != null) { if (vertexInfoIterator.getAllTexCoords() != null && vertexInfoIterator.getAllTexCoords().containsKey(sgId)) { double s = vertexInfoIterator.getTexCoords(sgId).getS(); double t = vertexInfoIterator.getTexCoords(sgId).getT(); if (s > maxS) { maxS = s; } if (s < minS) { minS = s; } if (t > maxT) { maxT = t; } if (t < minT) { minT = t; } } vertexInfoIterator = vertexInfoIterator.getNextVertexInfo(); } // step 2: crop images try { TextureImage texImage = texImages.get(texImageUris.get(sgId)); int imageWidth = texImage.getWidth(); int imageHeight = texImage.getHeight(); int startS = (int) Math.floor(imageWidth * minS); int startT = (int) Math.floor(imageHeight * (1- maxT)); int newImageWidth = (int) Math.floor((maxS - minS) * imageWidth); int newImageHeight = (int) Math.floor((maxT - minT) * imageHeight); if (startT < 0) startT = 0; if (startS < 0) startS = 0; if (newImageWidth <= 0) newImageWidth = 1; if (newImageHeight <= 0) newImageHeight = 1; BufferedImage imageToCrop = texImage.getBufferedImage().getSubimage(startS, startT, newImageWidth, newImageHeight); String newImageUri = sgId + "_" + texImageUris.get(sgId); texImageUris.put(sgId, newImageUri); newTexImages.put(newImageUri, new TextureImage(imageToCrop)); } catch (Exception e) { Logger.getInstance().error(e.getMessage()); } // step 3: update the vertex coordinate according to the cropped images vertexInfoIterator = firstVertexInfo; while (vertexInfoIterator != null) { if (vertexInfoIterator.getAllTexCoords() != null && vertexInfoIterator.getAllTexCoords().containsKey(sgId)) { double s = vertexInfoIterator.getTexCoords(sgId).getS(); double t = vertexInfoIterator.getTexCoords(sgId).getT(); double newS = (s - minS) / (maxS - minS); double newT = (t - minT) / (maxT - minT); vertexInfoIterator.getTexCoords(sgId).setS(newS); vertexInfoIterator.getTexCoords(sgId).setT(newT); } vertexInfoIterator = vertexInfoIterator.getNextVertexInfo(); } } // step 4: update textImages texImages = newTexImages; } public void resizeAllImagesByFactor (double factor) throws SQLException, IOException { if (texImages.size() == 0) { // building has no textures at all return; } Set<String> keySet = texImages.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String imageName = iterator.next(); BufferedImage imageToResize = texImages.get(imageName).getBufferedImage(); if (imageToResize.getWidth()*factor < 1 || imageToResize.getHeight()*factor < 1) { continue; } BufferedImage resizedImage = getScaledInstance(imageToResize, (int)(imageToResize.getWidth()*factor), (int)(imageToResize.getHeight()*factor), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); texImages.put(imageName, new TextureImage(resizedImage)); } } /** * Convenience method that returns a scaled instance of the * provided {@code BufferedImage}. * * @param img the original image to be scaled * @param targetWidth the desired width of the scaled instance, * in pixels * @param targetHeight the desired height of the scaled instance, * in pixels * @param hint one of the rendering hints that corresponds to * {@code RenderingHints.KEY_INTERPOLATION} (e.g. * {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, * {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, * {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) * @param higherQuality if true, this method will use a multi-step * scaling technique that provides higher quality than the usual * one-step technique (only useful in downscaling cases, where * {@code targetWidth} or {@code targetHeight} is * smaller than the original dimensions, and generally only when * the {@code BILINEAR} hint is specified) * @return a scaled version of the original {@code BufferedImage} */ private BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint, boolean higherQuality) { int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage ret = (BufferedImage)img; int w, h; if (higherQuality) { // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); h = img.getHeight(); } else { // Use one-step technique: scale directly from original // size to target size with a single drawImage() call w = targetWidth; h = targetHeight; } do { if (higherQuality && w > targetWidth) { w /= 2; if (w < targetWidth) { w = targetWidth; } } if (higherQuality && h > targetHeight) { h /= 2; if (h < targetHeight) { h = targetHeight; } } BufferedImage tmp = new BufferedImage(w, h, type); Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint); g2.drawImage(ret, 0, 0, w, h, null); g2.dispose(); ret = tmp; } while (w != targetWidth || h != targetHeight); return ret; } private String buildNameFromX3dMaterial(X3DMaterial x3dMaterial) { String name = NO_TEXIMAGE; if (x3dMaterial.isSetAmbientIntensity()) { name = name + "_ai_" + x3dMaterial.getAmbientIntensity();} if (x3dMaterial.isSetShininess()) { name = name + "_sh_" + x3dMaterial.getShininess();} if (x3dMaterial.isSetTransparency()) { name = name + "_tr_" + x3dMaterial.getTransparency();} if (x3dMaterial.isSetDiffuseColor()) { name = name + "_dc_r_" + x3dMaterial.getDiffuseColor().getRed() + "_g_" + x3dMaterial.getDiffuseColor().getGreen() + "_b_" + x3dMaterial.getDiffuseColor().getBlue();} if (x3dMaterial.isSetSpecularColor()) { name = name + "_sc_r_" + x3dMaterial.getSpecularColor().getRed() + "_g_" + x3dMaterial.getSpecularColor().getGreen() + "_b_" + x3dMaterial.getSpecularColor().getBlue();} if (x3dMaterial.isSetEmissiveColor()) { name = name + "_ec_r_" + x3dMaterial.getEmissiveColor().getRed() + "_g_" + x3dMaterial.getEmissiveColor().getGreen() + "_b_" + x3dMaterial.getEmissiveColor().getBlue();} return name; } protected double reducePrecisionForXorY (double originalValue) { return Math.rint(originalValue * PRECISION) / PRECISION; } protected double reducePrecisionForZ (double originalValue) { return Math.rint(originalValue * PRECISION) / PRECISION; } protected List<PlacemarkType> createPlacemarksForFootprint(ResultSet rs, KmlSplittingResult work) throws SQLException { List<PlacemarkType> placemarkList = new ArrayList<PlacemarkType>(); PlacemarkType placemark = kmlFactory.createPlacemarkType(); placemark.setName(work.getGmlId()); placemark.setId(config.getProject().getKmlExporter().getIdPrefixes().getPlacemarkFootprint() + placemark.getName()); if (work.getDisplayForm().isHighlightingEnabled()) { placemark.setStyleUrl("#" + getStyleBasisName() + DisplayForm.FOOTPRINT_STR + "Style"); } else { placemark.setStyleUrl("#" + getStyleBasisName() + DisplayForm.FOOTPRINT_STR + "Normal"); } if (getBalloonSettings().isIncludeDescription()) { addBalloonContents(placemark, work.getId()); } MultiGeometryType multiGeometry = kmlFactory.createMultiGeometryType(); placemark.setAbstractGeometryGroup(kmlFactory.createMultiGeometry(multiGeometry)); PolygonType polygon = null; while (rs.next()) { Object buildingGeometryObj = rs.getObject(1); if (!rs.wasNull() && buildingGeometryObj != null) { eventDispatcher.triggerEvent(new GeometryCounterEvent(null, this)); GeometryObject groundSurface = convertToWGS84(geometryConverterAdapter.getGeometry(buildingGeometryObj)); if (groundSurface.getGeometryType() != GeometryType.POLYGON && groundSurface.getGeometryType() != GeometryType.MULTI_POLYGON) return placemarkList; int dim = groundSurface.getDimension(); for (int i = 0; i < groundSurface.getNumElements(); i++) { LinearRingType linearRing = kmlFactory.createLinearRingType(); BoundaryType boundary = kmlFactory.createBoundaryType(); boundary.setLinearRing(linearRing); if (groundSurface.getElementType(i) == ElementType.EXTERIOR_LINEAR_RING) { polygon = kmlFactory.createPolygonType(); polygon.setTessellate(true); polygon.setExtrude(false); polygon.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.CLAMP_TO_GROUND)); polygon.setOuterBoundaryIs(boundary); multiGeometry.getAbstractGeometryGroup().add(kmlFactory.createPolygon(polygon)); } else if (polygon != null) polygon.getInnerBoundaryIs().add(boundary); // order points counter-clockwise double[] ordinatesArray = groundSurface.getCoordinates(i); for (int j = ordinatesArray.length - dim; j >= 0; j = j-dim) linearRing.getCoordinates().add(String.valueOf(ordinatesArray[j] + "," + ordinatesArray[j+1] + ",0")); } } } if (polygon != null) { // if there is at least some content placemarkList.add(placemark); } return placemarkList; } protected List<PlacemarkType> createPlacemarksForExtruded(ResultSet rs, KmlSplittingResult work, double measuredHeight, boolean reversePointOrder) throws SQLException { List<PlacemarkType> placemarkList = new ArrayList<PlacemarkType>(); PlacemarkType placemark = kmlFactory.createPlacemarkType(); placemark.setName(work.getGmlId()); placemark.setId(config.getProject().getKmlExporter().getIdPrefixes().getPlacemarkExtruded() + placemark.getName()); if (work.getDisplayForm().isHighlightingEnabled()) { placemark.setStyleUrl("#" + getStyleBasisName() + DisplayForm.EXTRUDED_STR + "Style"); } else { placemark.setStyleUrl("#" + getStyleBasisName() + DisplayForm.EXTRUDED_STR + "Normal"); } if (getBalloonSettings().isIncludeDescription()) { addBalloonContents(placemark, work.getId()); } MultiGeometryType multiGeometry = kmlFactory.createMultiGeometryType(); placemark.setAbstractGeometryGroup(kmlFactory.createMultiGeometry(multiGeometry)); PolygonType polygon = null; while (rs.next()) { Object buildingGeometryObj = rs.getObject(1); if (!rs.wasNull() && buildingGeometryObj != null) { eventDispatcher.triggerEvent(new GeometryCounterEvent(null, this)); GeometryObject groundSurface = convertToWGS84(geometryConverterAdapter.getGeometry(buildingGeometryObj)); if (groundSurface.getGeometryType() != GeometryType.POLYGON && groundSurface.getGeometryType() != GeometryType.MULTI_POLYGON) return placemarkList; int dim = groundSurface.getDimension(); for (int i = 0; i < groundSurface.getNumElements(); i++) { LinearRingType linearRing = kmlFactory.createLinearRingType(); BoundaryType boundary = kmlFactory.createBoundaryType(); boundary.setLinearRing(linearRing); if (groundSurface.getElementType(i) == ElementType.EXTERIOR_LINEAR_RING) { polygon = kmlFactory.createPolygonType(); polygon.setTessellate(true); polygon.setExtrude(true); polygon.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.RELATIVE_TO_GROUND)); polygon.setOuterBoundaryIs(boundary); multiGeometry.getAbstractGeometryGroup().add(kmlFactory.createPolygon(polygon)); } else polygon.getInnerBoundaryIs().add(boundary); double[] ordinatesArray = groundSurface.getCoordinates(i); if (reversePointOrder) { for (int j = 0; j < ordinatesArray.length; j = j+dim) linearRing.getCoordinates().add(String.valueOf(ordinatesArray[j] + "," + ordinatesArray[j+1] + "," + measuredHeight)); } else if (polygon != null) // order points counter-clockwise for (int j = ordinatesArray.length - dim; j >= 0; j = j-dim) linearRing.getCoordinates().add(String.valueOf(ordinatesArray[j] + "," + ordinatesArray[j+1] + "," + measuredHeight)); } } } if (polygon != null) { // if there is at least some content placemarkList.add(placemark); } return placemarkList; } protected List<PlacemarkType> createPlacemarksForGeometry(ResultSet rs, KmlSplittingResult work) throws SQLException{ return createPlacemarksForGeometry(rs, work, false, false); } private List<PlacemarkType> createPlacemarksForGeometry(ResultSet rs, KmlSplittingResult work, boolean includeGroundSurface, boolean includeClosureSurface) throws SQLException { HashMap<String, MultiGeometryType> multiGeometries = new HashMap<String, MultiGeometryType>(); MultiGeometryType multiGeometry = null; PolygonType polygon = null; double zOffset = getZOffsetFromConfigOrDB(work.getId()); List<Point3d> lowestPointCandidates = getLowestPointsCoordinates(rs, (zOffset == Double.MAX_VALUE)); rs.beforeFirst(); // return cursor to beginning if (zOffset == Double.MAX_VALUE) { zOffset = getZOffsetFromGEService(work.getId(), lowestPointCandidates); } double lowestZCoordinate = convertPointCoordinatesToWGS84(new double[] { lowestPointCandidates.get(0).x, lowestPointCandidates.get(0).y, lowestPointCandidates.get(0).z}) [2]; while (rs.next()) { int objectclass_id = rs.getInt("objectclass_id"); String surfaceType = null; // in case that the Building, Bridge or Tunnel don't have thematic Surface, but normal LODxSurface, the "surfaceType" variable will be null. // in this case, the thematic surface e.g. WallSurface, RoofSurface can be determined by using a walk-around-way e.g. calculate the Normal-vector if (objectclass_id != 0){ surfaceType = TypeAttributeValueEnum.fromCityGMLClass(Util.classId2cityObject(objectclass_id)).toString(); } // Building Ground Surface and Closure Surface are not going to be exported for Visualization if ((!includeGroundSurface && TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BUILDING_GROUND_SURFACE).toString().equalsIgnoreCase(surfaceType)) || (!includeClosureSurface && TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BUILDING_CLOSURE_SURFACE).toString().equalsIgnoreCase(surfaceType))) { continue; } // Bridge Closure Surfaces are not going to be exported for Visualization if (!includeClosureSurface && TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BRIDGE_CLOSURE_SURFACE).toString().equalsIgnoreCase(surfaceType)) { continue; } // Tunnel Closure Surfaces are not going to be exported for Visualization if (!includeClosureSurface && TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.TUNNEL_CLOSURE_SURFACE).toString().equalsIgnoreCase(surfaceType)) { continue; } Object buildingGeometryObj = rs.getObject(1); GeometryObject surface = convertToWGS84(geometryConverterAdapter.getPolygon(buildingGeometryObj)); eventDispatcher.triggerEvent(new GeometryCounterEvent(null, this)); polygon = kmlFactory.createPolygonType(); switch (config.getProject().getKmlExporter().getAltitudeMode()) { case ABSOLUTE: polygon.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.ABSOLUTE)); break; case RELATIVE: polygon.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.RELATIVE_TO_GROUND)); break; } // just in case surfaceType == null boolean probablyRoof = true; double nx = 0; double ny = 0; double nz = 0; for (int i = 0; i < surface.getNumElements(); i++) { LinearRingType linearRing = kmlFactory.createLinearRingType(); BoundaryType boundary = kmlFactory.createBoundaryType(); boundary.setLinearRing(linearRing); if (i == 0) polygon.setOuterBoundaryIs(boundary); else polygon.getInnerBoundaryIs().add(boundary); // order points clockwise double[] ordinatesArray = surface.getCoordinates(i); for (int j = 0; j < ordinatesArray.length; j = j+3) { linearRing.getCoordinates().add(String.valueOf(reducePrecisionForXorY(ordinatesArray[j]) + "," + reducePrecisionForXorY(ordinatesArray[j+1]) + "," + reducePrecisionForZ(ordinatesArray[j+2] + zOffset))); // not touching the ground probablyRoof = probablyRoof && (reducePrecisionForZ(ordinatesArray[j+2] - lowestZCoordinate) > 0); if (currentLod == 1) { // calculate normal int current = j; int next = j+3; if (next >= ordinatesArray.length) next = 0; nx = nx + ((ordinatesArray[current+1] - ordinatesArray[next+1]) * (ordinatesArray[current+2] + ordinatesArray[next+2])); ny = ny + ((ordinatesArray[current+2] - ordinatesArray[next+2]) * (ordinatesArray[current] + ordinatesArray[next])); nz = nz + ((ordinatesArray[current] - ordinatesArray[next]) * (ordinatesArray[current+1] + ordinatesArray[next+1])); } } } if (currentLod == 1) { // calculate normal double value = Math.sqrt(nx * nx + ny * ny + nz * nz); if (value == 0) { // not a surface, but a line continue; } nx = nx / value; ny = ny / value; nz = nz / value; } if (surfaceType == null) { if (work.isBuilding()){ surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BUILDING_WALL_SURFACE).toString(); switch (currentLod) { case 1: if (probablyRoof && (nz > 0.999)) { surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BUILDING_ROOF_SURFACE).toString(); } break; case 2: if (probablyRoof) { surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BUILDING_ROOF_SURFACE).toString(); } break; } } else if (work.isBridge()){ surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BRIDGE_WALL_SURFACE).toString(); switch (currentLod) { case 1: if (probablyRoof && (nz > 0.999)) { surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BRIDGE_ROOF_SURFACE).toString(); } break; case 2: if (probablyRoof) { surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.BRIDGE_ROOF_SURFACE).toString(); } break; } } else if (work.isTunnel()){ surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.TUNNEL_WALL_SURFACE).toString(); switch (currentLod) { case 1: if (probablyRoof && (nz > 0.999)) { surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.TUNNEL_ROOF_SURFACE).toString(); } break; case 2: if (probablyRoof) { surfaceType = TypeAttributeValueEnum.fromCityGMLClass(CityGMLClass.TUNNEL_ROOF_SURFACE).toString(); } break; } } } multiGeometry = multiGeometries.get(surfaceType); if (multiGeometry == null) { multiGeometry = kmlFactory.createMultiGeometryType(); multiGeometries.put(surfaceType, multiGeometry); } multiGeometry.getAbstractGeometryGroup().add(kmlFactory.createPolygon(polygon)); } List<PlacemarkType> placemarkList = new ArrayList<PlacemarkType>(); Set<String> keySet = multiGeometries.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String surfaceType = iterator.next(); PlacemarkType placemark = kmlFactory.createPlacemarkType(); if (work.isBuilding() || work.isBridge() || work.isTunnel()){ placemark.setName(work.getGmlId() + "_" + surfaceType); placemark.setId(config.getProject().getKmlExporter().getIdPrefixes().getPlacemarkGeometry() + placemark.getName()); placemark.setStyleUrl("#" + surfaceType + "Normal"); } else{ placemark.setName(work.getGmlId() + "_" + getStyleBasisName()); placemark.setId(config.getProject().getKmlExporter().getIdPrefixes().getPlacemarkGeometry() + placemark.getName()); placemark.setStyleUrl("#" + getStyleBasisName() + DisplayForm.GEOMETRY_STR + "Normal"); } if (getBalloonSettings().isIncludeDescription() && !work.getDisplayForm().isHighlightingEnabled()) { // avoid double description addBalloonContents(placemark, work.getId()); } multiGeometry = multiGeometries.get(surfaceType); placemark.setAbstractGeometryGroup(kmlFactory.createMultiGeometry(multiGeometry)); placemarkList.add(placemark); } return placemarkList; } protected void fillGenericObjectForCollada(ResultSet rs, boolean generateTextureAtlas) throws SQLException { String selectedTheme = config.getProject().getKmlExporter().getAppearanceTheme(); int texImageCounter = 0; while (rs.next()) { long surfaceRootId = rs.getLong(1); for (String colladaQuery: Queries.COLLADA_GEOMETRY_AND_APPEARANCE_FROM_ROOT_ID) { // parent surfaces come first PreparedStatement psQuery = null; ResultSet rs2 = null; try { psQuery = connection.prepareStatement(colladaQuery); psQuery.setLong(1, surfaceRootId); // psQuery.setString(2, selectedTheme); rs2 = psQuery.executeQuery(); while (rs2.next()) { String theme = rs2.getString("theme"); Object buildingGeometryObj = rs2.getObject(1); // surfaceId is the key to all Hashmaps in object long surfaceId = rs2.getLong("id"); long textureImageId = rs2.getLong("tex_image_id"); long parentId = rs2.getLong("parent_id"); long rootId = rs2.getLong("root_id"); if (buildingGeometryObj == null) { // root or parent if (selectedTheme.equalsIgnoreCase(theme)) { X3DMaterial x3dMaterial = new X3DMaterial(); fillX3dMaterialValues(x3dMaterial, rs2); // x3dMaterial will only added if not all x3dMaterial members are null addX3dMaterial(surfaceId, x3dMaterial); } else if (theme == null) { // no theme for this parent surface if (getX3dMaterial(parentId) != null) { // material for parent's parent known addX3dMaterial(surfaceId, getX3dMaterial(parentId)); } } continue; } // Closure Surfaces are not going to be exported int surfaceTypeID = rs2.getInt("objectclass_id"); if (surfaceTypeID != 0){ if (Util.classId2cityObject(surfaceTypeID)==CityGMLClass.BUILDING_CLOSURE_SURFACE || Util.classId2cityObject(surfaceTypeID)==CityGMLClass.BRIDGE_CLOSURE_SURFACE || Util.classId2cityObject(surfaceTypeID)==CityGMLClass.TUNNEL_CLOSURE_SURFACE){ continue; } } // from here on it is an elementary surfaceMember eventDispatcher.triggerEvent(new GeometryCounterEvent(null, this)); String texImageUri = null; StringTokenizer texCoordsTokenized = null; if (selectedTheme.equals(KmlExporter.THEME_NONE)) addX3dMaterial(surfaceId, defaultX3dMaterial); else { if (!selectedTheme.equalsIgnoreCase(theme) && !selectedTheme.equalsIgnoreCase("<unknown>")) { // no surface data for this surface and theme if (getX3dMaterial(parentId) != null) // material for parent surface known addX3dMaterial(surfaceId, getX3dMaterial(parentId)); else if (getX3dMaterial(rootId) != null) // material for root surface known addX3dMaterial(surfaceId, getX3dMaterial(rootId)); else addX3dMaterial(surfaceId, defaultX3dMaterial); } else { texImageUri = rs2.getString("tex_image_uri"); StringBuilder sb = new StringBuilder(); Object texCoordsObject = rs2.getObject("texture_coordinates"); if (texCoordsObject != null){ GeometryObject texCoordsGeometryObject = geometryConverterAdapter.getGeometry(texCoordsObject); for (int i = 0; i < texCoordsGeometryObject.getNumElements(); i++) { double[] coordinates = texCoordsGeometryObject.getCoordinates(i); for (double coordinate : coordinates){ sb.append(String.valueOf(coordinate)); sb.append(" "); } } } String texCoords = sb.toString(); if (texImageUri != null && texImageUri.trim().length() != 0 && texCoords != null && texCoords.trim().length() != 0) { int fileSeparatorIndex = Math.max(texImageUri.lastIndexOf("\\"), texImageUri.lastIndexOf("/")); texImageUri = "_" + texImageUri.substring(fileSeparatorIndex + 1); // for example: _tex4712047.jpeg addTexImageUri(surfaceId, texImageUri); if ((getUnsupportedTexImageId(texImageUri) == -1) && (getTexImage(texImageUri) == null)) { // not already marked as wrapping texture && not already read in TextureImage texImage = null; try { byte[] imageBytes = textureExportAdapter.getInByteArray(textureImageId, "tex_image", texImageUri); if (imageBytes != null) { imageReader.setSupportRGB(generateTextureAtlas); texImage = imageReader.read(new ByteArrayInputStream(imageBytes)); } } catch (IOException ioe) { } if (texImage != null) // image in JPEG, PNG or another usual format addTexImage(texImageUri, texImage); else addUnsupportedTexImageId(texImageUri, textureImageId); texImageCounter++; if (texImageCounter > 20) { eventDispatcher.triggerEvent(new CounterEvent(CounterType.TEXTURE_IMAGE, texImageCounter, this)); texImageCounter = 0; } } texCoordsTokenized = new StringTokenizer(texCoords.trim(), " "); } else { X3DMaterial x3dMaterial = new X3DMaterial(); fillX3dMaterialValues(x3dMaterial, rs2); // x3dMaterial will only added if not all x3dMaterial members are null addX3dMaterial(surfaceId, x3dMaterial); if (getX3dMaterial(surfaceId) == null) { // untextured surface and no x3dMaterial -> default x3dMaterial (gray) addX3dMaterial(surfaceId, defaultX3dMaterial); } } } } GeometryObject surface = geometryConverterAdapter.getPolygon(buildingGeometryObj); List<VertexInfo> vertexInfos = new ArrayList<VertexInfo>(); int ringCount = surface.getNumElements(); int[] vertexCount = new int[ringCount]; for (int i = 0; i < surface.getNumElements(); i++) { double[] ordinatesArray = surface.getCoordinates(i); int vertices = 0; for (int j = 0; j < ordinatesArray.length - 3; j = j+3) { // calculate origin and list of lowest points updateOrigins(ordinatesArray[j], ordinatesArray[j + 1], ordinatesArray[j + 2]); // get or create node in vertex info tree VertexInfo vertexInfo = setVertexInfoForXYZ(surfaceId, ordinatesArray[j], ordinatesArray[j+1], ordinatesArray[j+2]); if (texCoordsTokenized != null && texCoordsTokenized.hasMoreTokens()) { double s = Double.parseDouble(texCoordsTokenized.nextToken()); double t = Double.parseDouble(texCoordsTokenized.nextToken()); vertexInfo.addTexCoords(surfaceId, new TexCoords(s, t)); } vertexInfos.add(vertexInfo); vertices++; } vertexCount[i] = vertices; if (texCoordsTokenized != null && texCoordsTokenized.hasMoreTokens()) { texCoordsTokenized.nextToken(); // geometryInfo ignores last point in a polygon texCoordsTokenized.nextToken(); // keep texture coordinates in sync } } addSurfaceInfo(surfaceId, new SurfaceInfo(ringCount, vertexCount, vertexInfos)); } } catch (SQLException sqlEx) { Logger.getInstance().error("SQL error while querying city object: " + sqlEx.getMessage()); } finally { if (rs2 != null) try { rs2.close(); } catch (SQLException e) {} if (psQuery != null) try { psQuery.close(); } catch (SQLException e) {} } } } // count rest images eventDispatcher.triggerEvent(new CounterEvent(CounterType.TEXTURE_IMAGE, texImageCounter, this)); } public PlacemarkType createPlacemarkForColladaModel() throws SQLException { PlacemarkType placemark = kmlFactory.createPlacemarkType(); placemark.setName(getGmlId()); placemark.setId(config.getProject().getKmlExporter().getIdPrefixes().getPlacemarkCollada() + placemark.getName()); DisplayForm colladaDisplayForm = null; for (DisplayForm displayForm: getDisplayForms()) { if (displayForm.getForm() == DisplayForm.COLLADA) { colladaDisplayForm = displayForm; break; } } if (getBalloonSettings().isIncludeDescription() && !colladaDisplayForm.isHighlightingEnabled()) { // avoid double description ColladaOptions colladaOptions = getColladaOptions(); if (!colladaOptions.isGroupObjects() || colladaOptions.getGroupSize() == 1) { addBalloonContents(placemark, getId()); } } ModelType model = kmlFactory.createModelType(); LocationType location = kmlFactory.createLocationType(); switch (config.getProject().getKmlExporter().getAltitudeMode()) { case ABSOLUTE: model.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.ABSOLUTE)); break; case RELATIVE: model.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.RELATIVE_TO_GROUND)); break; } location.setLatitude(this.location.y); location.setLongitude(this.location.x); location.setAltitude(this.location.z + reducePrecisionForZ(getZOffset())); model.setLocation(location); // correct heading value double lat1 = Math.toRadians(this.location.y); double[] dummy = convertPointCoordinatesToWGS84(new double[] {origin.x, origin.y - 20, origin.z}); double lat2 = Math.toRadians(dummy[1]); double dLon = Math.toRadians(dummy[0] - this.location.x); double y = Math.sin(dLon) * Math.cos(lat2); double x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon); double bearing = Math.toDegrees(Math.atan2(y, x)); bearing = (bearing + 180) % 360; OrientationType orientation = kmlFactory.createOrientationType(); orientation.setHeading(reducePrecisionForZ(bearing)); model.setOrientation(orientation); LinkType link = kmlFactory.createLinkType(); if (config.getProject().getKmlExporter().isOneFilePerObject() && !config.getProject().getKmlExporter().isExportAsKmz() && config.getProject().getKmlExporter().getFilter().getComplexFilter().getTiledBoundingBox().getActive().booleanValue()) { link.setHref(getGmlId() + ".dae"); } else { // File.separator would be wrong here, it MUST be "/" link.setHref(getId() + "/" + getGmlId() + ".dae"); } model.setLink(link); placemark.setAbstractGeometryGroup(kmlFactory.createModel(model)); return placemark; } protected List<PlacemarkType> createPlacemarksForHighlighting(KmlSplittingResult work) throws SQLException { List<PlacemarkType> placemarkList= new ArrayList<PlacemarkType>(); PlacemarkType placemark = kmlFactory.createPlacemarkType(); placemark.setStyleUrl("#" + getStyleBasisName() + work.getDisplayForm().getName() + "Style"); placemark.setName(work.getGmlId()); placemark.setId(config.getProject().getKmlExporter().getIdPrefixes().getPlacemarkHighlight() + placemark.getName()); placemarkList.add(placemark); if (getBalloonSettings().isIncludeDescription()) { addBalloonContents(placemark, work.getId()); } MultiGeometryType multiGeometry = kmlFactory.createMultiGeometryType(); placemark.setAbstractGeometryGroup(kmlFactory.createMultiGeometry(multiGeometry)); PreparedStatement getGeometriesStmt = null; ResultSet rs = null; double hlDistance = work.getDisplayForm().getHighlightingDistance(); try { getGeometriesStmt = connection.prepareStatement(getHighlightingQuery(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); for (int i = 1; i <= getGeometriesStmt.getParameterMetaData().getParameterCount(); i++) { getGeometriesStmt.setLong(i, work.getId()); } rs = getGeometriesStmt.executeQuery(); double zOffset = getZOffsetFromConfigOrDB(work.getId()); if (zOffset == Double.MAX_VALUE) { List<Point3d> lowestPointCandidates = getLowestPointsCoordinates(rs, (zOffset == Double.MAX_VALUE)); rs.beforeFirst(); // return cursor to beginning zOffset = getZOffsetFromGEService(work.getId(), lowestPointCandidates); } while (rs.next()) { Object unconvertedObj = rs.getObject(1); GeometryObject unconvertedSurface = geometryConverterAdapter.getPolygon(unconvertedObj); if (unconvertedSurface == null || unconvertedSurface.getNumElements() == 0) return null; double[] ordinatesArray = unconvertedSurface.getCoordinates(0); double nx = 0; double ny = 0; double nz = 0; for (int current = 0; current < ordinatesArray.length - 3; current = current+3) { int next = current+3; if (next >= ordinatesArray.length - 3) next = 0; nx = nx + ((ordinatesArray[current+1] - ordinatesArray[next+1]) * (ordinatesArray[current+2] + ordinatesArray[next+2])); ny = ny + ((ordinatesArray[current+2] - ordinatesArray[next+2]) * (ordinatesArray[current] + ordinatesArray[next])); nz = nz + ((ordinatesArray[current] - ordinatesArray[next]) * (ordinatesArray[current+1] + ordinatesArray[next+1])); } double value = Math.sqrt(nx * nx + ny * ny + nz * nz); if (value == 0) { // not a surface, but a line continue; } nx = nx / value; ny = ny / value; nz = nz / value; for (int i = 0; i < unconvertedSurface.getNumElements(); i++) { ordinatesArray = unconvertedSurface.getCoordinates(i); for (int j = 0; j < ordinatesArray.length; j = j + 3) { // coordinates = coordinates + hlDistance * (dot product of normal vector and unity vector) ordinatesArray[j] = ordinatesArray[j] + hlDistance * nx; ordinatesArray[j+1] = ordinatesArray[j+1] + hlDistance * ny; ordinatesArray[j+2] = ordinatesArray[j+2] + zOffset + hlDistance * nz; } } // now convert to WGS84 GeometryObject surface = convertToWGS84(unconvertedSurface); unconvertedSurface = null; PolygonType polygon = kmlFactory.createPolygonType(); switch (config.getProject().getKmlExporter().getAltitudeMode()) { case ABSOLUTE: polygon.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.ABSOLUTE)); break; case RELATIVE: polygon.setAltitudeModeGroup(kmlFactory.createAltitudeMode(AltitudeModeEnumType.RELATIVE_TO_GROUND)); break; } multiGeometry.getAbstractGeometryGroup().add(kmlFactory.createPolygon(polygon)); for (int i = 0; i < surface.getNumElements(); i++) { LinearRingType linearRing = kmlFactory.createLinearRingType(); BoundaryType boundary = kmlFactory.createBoundaryType(); boundary.setLinearRing(linearRing); if (i == 0) polygon.setOuterBoundaryIs(boundary); else polygon.getInnerBoundaryIs().add(boundary); // order points clockwise ordinatesArray = surface.getCoordinates(i); for (int j = 0; j < ordinatesArray.length; j = j+3) linearRing.getCoordinates().add(String.valueOf(reducePrecisionForXorY(ordinatesArray[j]) + "," + reducePrecisionForXorY(ordinatesArray[j+1]) + "," + reducePrecisionForZ(ordinatesArray[j+2]))); } } } catch (Exception e) { Logger.getInstance().warn("Exception when generating highlighting geometry of object " + work.getGmlId()); e.printStackTrace(); } finally { if (rs != null) rs.close(); if (getGeometriesStmt != null) getGeometriesStmt.close(); } return placemarkList; } private String getBalloonContentFromGenericAttribute(long id) { String balloonContent = null; String genericAttribName = "Balloon_Content"; PreparedStatement selectQuery = null; ResultSet rs = null; try { // look for the value in the DB selectQuery = connection.prepareStatement(Queries.GET_STRVAL_GENERICATTRIB_FROM_ID); selectQuery.setLong(1, id); selectQuery.setString(2, genericAttribName); rs = selectQuery.executeQuery(); if (rs.next()) { balloonContent = rs.getString(1); } } catch (Exception e) {} finally { try { if (rs != null) rs.close(); if (selectQuery != null) selectQuery.close(); } catch (Exception e2) {} } return balloonContent; } protected void addBalloonContents(PlacemarkType placemark, long id) { try { switch (getBalloonSettings().getBalloonContentMode()) { case GEN_ATTRIB: String balloonTemplate = getBalloonContentFromGenericAttribute(id); if (balloonTemplate != null) { if (getBalloonTemplateHandler() == null) { // just in case setBalloonTemplateHandler(new BalloonTemplateHandlerImpl((File) null, connection)); } placemark.setDescription(getBalloonTemplateHandler().getBalloonContent(balloonTemplate, id, currentLod)); } break; case GEN_ATTRIB_AND_FILE: balloonTemplate = getBalloonContentFromGenericAttribute(id); if (balloonTemplate != null) { placemark.setDescription(getBalloonTemplateHandler().getBalloonContent(balloonTemplate, id, currentLod)); break; } case FILE : if (getBalloonTemplateHandler() != null) { getBalloonTemplateHandler().getBalloonContent(id, currentLod); placemark.setDescription(getBalloonTemplateHandler().getBalloonContent(id, currentLod)); } break; } } catch (Exception e) { } // invalid balloons are silently discarded } protected void fillX3dMaterialValues (X3DMaterial x3dMaterial, ResultSet rs) throws SQLException { double ambientIntensity = rs.getDouble("x3d_ambient_intensity"); if (!rs.wasNull()) { x3dMaterial.setAmbientIntensity(ambientIntensity); } double shininess = rs.getDouble("x3d_shininess"); if (!rs.wasNull()) { x3dMaterial.setShininess(shininess); } double transparency = rs.getDouble("x3d_transparency"); if (!rs.wasNull()) { x3dMaterial.setTransparency(transparency); } Color color = getX3dColorFromString(rs.getString("x3d_diffuse_color")); if (color != null) { x3dMaterial.setDiffuseColor(color); } color = getX3dColorFromString(rs.getString("x3d_specular_color")); if (color != null) { x3dMaterial.setSpecularColor(color); } color = getX3dColorFromString(rs.getString("x3d_emissive_color")); if (color != null) { x3dMaterial.setEmissiveColor(color); } x3dMaterial.setIsSmooth(rs.getInt("x3d_is_smooth") == 1); } private Color getX3dColorFromString(String colorString) { Color color = null; if (colorString != null) { List<Double> colorList = Util.string2double(colorString, "\\s+"); if (colorList != null && colorList.size() >= 3) { color = new Color(colorList.get(0), colorList.get(1), colorList.get(2)); } } return color; } protected double getZOffsetFromConfigOrDB (long id) { double zOffset = Double.MAX_VALUE;; switch (config.getProject().getKmlExporter().getAltitudeOffsetMode()) { case NO_OFFSET: zOffset = 0; break; case CONSTANT: zOffset = config.getProject().getKmlExporter().getAltitudeOffsetValue(); break; case BOTTOM_ZERO: zOffset = Double.MAX_VALUE; break; case GENERIC_ATTRIBUTE: PreparedStatement selectQuery = null; ResultSet rs = null; String genericAttribName = "GE_LoD" + currentLod + "_zOffset"; try { // first look for the value in the DB selectQuery = connection.prepareStatement(Queries.GET_STRVAL_GENERICATTRIB_FROM_ID); selectQuery.setLong(1, id); selectQuery.setString(2, genericAttribName); rs = selectQuery.executeQuery(); if (rs.next()) { String strVal = rs.getString(1); if (strVal != null) { // use value in DB StringTokenizer attributeTokenized = new StringTokenizer(strVal, "|"); attributeTokenized.nextToken(); // skip mode zOffset = Double.parseDouble(attributeTokenized.nextToken()); } } } catch (Exception e) {} finally { try { if (rs != null) rs.close(); if (selectQuery != null) selectQuery.close(); } catch (Exception e2) {} } } return zOffset; } protected double getZOffsetFromGEService (long id, List<Point3d> candidates) { double zOffset = 0; if (config.getProject().getKmlExporter().getAltitudeOffsetMode() == AltitudeOffsetMode.BOTTOM_ZERO) { try { // convert candidate points to WGS84 double[] coords = new double[candidates.size()*3]; int index = 0; for (Point3d point3d: candidates) { coords[index++] = point3d.x; coords[index++] = point3d.y; coords[index++] = point3d.z; } if (candidates.size() == 1) { coords = convertPointCoordinatesToWGS84(coords); } else { GeometryObject geomObj = convertToWGS84(GeometryObject.createCurve(coords, 3, dbSrs.getSrid())); coords = geomObj.getCoordinates(0); } double minElevation = Double.MAX_VALUE; for (int i = 0; i < coords.length; i = i + 3) { if (minElevation > coords[i+2]) { minElevation = coords[i+2]; } } zOffset = 0 - minElevation; } catch (Exception e) {} } else if (config.getProject().getKmlExporter().isCallGElevationService()) { // allowed to query PreparedStatement insertQuery = null; ResultSet rs = null; try { // convert candidate points to WGS84 double[] coords = new double[candidates.size()*3]; int index = 0; for (Point3d point3d: candidates) { coords[index++] = point3d.x; coords[index++] = point3d.y; coords[index++] = point3d.z; } if (candidates.size() == 1) { coords = convertPointCoordinatesToWGS84(coords); } else { GeometryObject geomObj = convertToWGS84(GeometryObject.createCurve(coords, 3, dbSrs.getSrid())); coords = geomObj.getCoordinates(0); } Logger.getInstance().info("Getting zOffset from Google's elevation API for " + getGmlId() + " with " + candidates.size() + " points."); zOffset = elevationServiceHandler.getZOffset(coords); // save result in DB for next time String genericAttribName = "GE_LoD" + currentLod + "_zOffset"; insertQuery = connection.prepareStatement(Queries.INSERT_GE_ZOFFSET(databaseAdapter.getSQLAdapter())); insertQuery.setString(1, genericAttribName); String strVal = "Auto|" + zOffset + "|" + dateFormatter.format(new Date(System.currentTimeMillis())); insertQuery.setString(2, strVal); insertQuery.setLong(3, id); rs = insertQuery.executeQuery(); } catch (Exception e) {} finally { try { if (rs != null) rs.close(); if (insertQuery != null) insertQuery.close(); } catch (Exception e2) {} } } return zOffset; } protected List<Point3d> getLowestPointsCoordinates(ResultSet rs, boolean willCallGEService) throws SQLException { double currentlyLowestZCoordinate = Double.MAX_VALUE; List<Point3d> coords = new ArrayList<Point3d>(); rs.next(); do { GeometryObject buildingGeometryObj = geometryConverterAdapter.getGeometry(rs.getObject(1)); // we are only interested in the z coordinate for (int i = 0; i < buildingGeometryObj.getNumElements(); i++) { double[] ordinatesArray = buildingGeometryObj.getCoordinates(i); for (int j = 2; j < ordinatesArray.length; j = j+3) { if (ordinatesArray[j] < currentlyLowestZCoordinate) { coords.clear(); Point3d point3d = new Point3d(ordinatesArray[j-2], ordinatesArray[j-1], ordinatesArray[j]); coords.add(point3d); currentlyLowestZCoordinate = point3d.z; } if (willCallGEService && ordinatesArray[j] == currentlyLowestZCoordinate) { Point3d point3d = new Point3d(ordinatesArray[j-2], ordinatesArray[j-1], ordinatesArray[j]); if (!coords.contains(point3d)) { coords.add(point3d); } } } } if (!rs.next()) break; } while (true); return coords; } protected double[] convertPointCoordinatesToWGS84(double[] coords) throws SQLException { double[] pointCoords = null; GeometryObject convertedPointGeom = null; // this is a nasty hack for Oracle. In Oracle, transforming a single point to WGS84 does not change // its z-value, whereas transforming a series of vertices does affect their z-value switch (databaseAdapter.getDatabaseType()) { case ORACLE: convertedPointGeom = convertToWGS84(GeometryObject.createCurve(coords, coords.length, dbSrs.getSrid())); break; case POSTGIS: convertedPointGeom = convertToWGS84(GeometryObject.createPoint(coords, coords.length, dbSrs.getSrid())); break; } if (convertedPointGeom != null) pointCoords = convertedPointGeom.getCoordinates(0); return pointCoords; } protected GeometryObject convertToWGS84(GeometryObject geomObj) throws SQLException { GeometryObject convertedGeomObj = null; PreparedStatement convertStmt = null; ResultSet rs2 = null; try { convertStmt = (dbSrs.is3D() && geomObj.getDimension() == 3) ? connection.prepareStatement(Queries.TRANSFORM_GEOMETRY_TO_WGS84_3D(databaseAdapter.getSQLAdapter())) : connection.prepareStatement(Queries.TRANSFORM_GEOMETRY_TO_WGS84(databaseAdapter.getSQLAdapter())); // now convert to WGS84 Object unconverted = geometryConverterAdapter.getDatabaseObject(geomObj, connection); if (unconverted == null) return null; convertStmt.setObject(1, unconverted); rs2 = convertStmt.executeQuery(); while (rs2.next()) { // ColumnName is SDO_CS.TRANSFORM(JGeometry, 4326) convertedGeomObj = geometryConverterAdapter.getGeometry(rs2.getObject(1)); } } catch (Exception e) { Logger.getInstance().warn("Exception when converting geometry to WGS84"); e.printStackTrace(); } finally { try { if (rs2 != null) rs2.close(); if (convertStmt != null) convertStmt.close(); } catch (Exception e2) {} } if (config.getProject().getKmlExporter().isUseOriginalZCoords()) { double[][] originalCoords = geomObj.getCoordinates(); double[][] convertedCoords = convertedGeomObj.getCoordinates(); for (int i = 0; i < originalCoords.length; i++) { for (int j = 2; j < originalCoords[i].length; j += 3) convertedCoords[i][j] = originalCoords[i][j]; } } return convertedGeomObj; } protected class Node{ double key; Object value; Node rightArc; Node leftArc; protected Node(double key, Object value){ this.key = key; this.value = value; } protected void setLeftArc(Node leftArc) { this.leftArc = leftArc; } protected Node getLeftArc() { return leftArc; } protected void setRightArc (Node rightArc) { this.rightArc = rightArc; } protected Node getRightArc() { return rightArc; } } protected class NodeX extends Node{ protected NodeX(double key, Object value){ super(key, value); } } protected class NodeY extends Node{ protected NodeY(double key, Object value){ super(key, value); } } protected class NodeZ extends Node{ protected NodeZ(double key, Object value){ super(key, value); } } }
package br.com.six2six.fixturefactory; import java.util.LinkedHashMap; import java.util.Map; public class Fixture { private static Map<Class<?>, TemplateHolder> templates = new LinkedHashMap<Class<?>, TemplateHolder>(); public static TemplateHolder of(Class<?> clazz) { TemplateHolder template = templates.get(clazz); if (template == null) { template = new TemplateHolder(clazz); templates.put(clazz, template); } return template; } public static ObjectFactory from(Class<?> clazz) { return new ObjectFactory(of(clazz)); } }
package net.bolbat.utils.lang; import java.util.Calendar; /** * Time utils. * * @author Vasyl Zarva */ public final class TimeUtils { /** * Default constructor with preventing instantiations of this class. */ private TimeUtils() { throw new IllegalAccessError("Can't be instantiated."); } /** * Get timestamp for X years ago from now. * * @param years * years, can't be <code>null</code> * @param mode * rounding mode * @return timestamp */ public static long getYearsFromNow(final int years, final Rounding mode) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, years); if (mode == null || Rounding.NONE == mode) return cal.getTimeInMillis(); roundYearTime(cal, mode); return cal.getTimeInMillis(); } /** * Get timestamp from now for given months. * * @param months * days count * @param mode * rounding mode * @return timestamp */ public static long getMonthFromNow(final int months, final Rounding mode) { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, months); if (mode == null || Rounding.NONE == mode) return cal.getTimeInMillis(); roundMonthTime(cal, mode); return cal.getTimeInMillis(); } /** * Get timestamp from now for given days. * * @param days * days count * @param mode * rounding mode * @return timestamp */ public static long getDaysFromNow(final int days, final Rounding mode) { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, days); if (mode == null || Rounding.NONE == mode) return cal.getTimeInMillis(); roundDayTime(cal, mode); return cal.getTimeInMillis(); } /** * Get timestamp from now for given hours. * * @param hours * days count * @param mode * rounding mode * @return timestamp */ public static long getHoursFromNow(final int hours, final Rounding mode) { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, hours); if (mode == null || Rounding.NONE == mode) return cal.getTimeInMillis(); roundHourTime(cal, mode); return cal.getTimeInMillis(); } /** * Rounding incoming time to seconds, up/down rounding defined by {@link Rounding}. * * @param time * time in millis * @param mode * rounding mode * @return rounded time in millis */ public static long roundTimeToSecondTime(final long time, final Rounding mode) { if (mode == null || Rounding.NONE == mode) return time; final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); roundSecondTime(cal, mode); return cal.getTimeInMillis(); } /** * Round date to maximum or minimum in second, depending of rounding mode. * * @param cal * {@link Calendar} with configured date * @param mode * rounding mode */ public static void roundSecondTime(final Calendar cal, final Rounding mode) { if (cal == null) throw new IllegalArgumentException("cal argument is null."); if (mode == null || Rounding.NONE == mode) return; switch (mode) { case MAX: cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND)); break; case MIN: cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); break; case NONE: default: break; } } /** * Rounding incoming time to minutes, up/down rounding defined by {@link Rounding}. * * @param time * time in millis * @param mode * rounding mode * @return rounded time in millis */ public static long roundTimeToMinuteTime(final long time, final Rounding mode) { if (mode == null || Rounding.NONE == mode) return time; final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); roundMinuteTime(cal, mode); return cal.getTimeInMillis(); } /** * Round date to maximum or minimum in minute, depending of rounding mode. * * @param cal * {@link Calendar} with configured date * @param mode * rounding mode */ public static void roundMinuteTime(final Calendar cal, final Rounding mode) { if (cal == null) throw new IllegalArgumentException("cal argument is null."); if (mode == null || Rounding.NONE == mode) return; switch (mode) { case MAX: cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND)); break; case MIN: cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); break; case NONE: default: break; } } /** * Rounding incoming time to hour, up/down rounding defined by {@link Rounding}. * * @param time * time in millis * @param mode * rounding mode * @return rounded time in millis */ public static long roundTimeToHourTime(final long time, final Rounding mode) { if (mode == null || Rounding.NONE == mode) return time; final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); roundHourTime(cal, mode); return cal.getTimeInMillis(); } /** * Round date to maximum or minimum in hour, depending of rounding mode. * * @param cal * {@link Calendar} with configured date * @param mode * rounding mode */ public static void roundHourTime(final Calendar cal, final Rounding mode) { if (cal == null) throw new IllegalArgumentException("cal argument is null."); if (mode == null || Rounding.NONE == mode) return; switch (mode) { case MAX: cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND)); break; case MIN: cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); break; case NONE: default: break; } } /** * Rounding incoming time to day, up/down rounding defined by {@link Rounding}. * * @param time * time in millis * @param mode * rounding mode * @return rounded time in millis */ public static long roundTimeToDayTime(final long time, final Rounding mode) { if (mode == null || Rounding.NONE == mode) return time; final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); roundDayTime(cal, mode); return cal.getTimeInMillis(); } /** * Round date to maximum or minimum in day, depending of rounding mode. * * @param cal * {@link Calendar} with configured date * @param mode * rounding mode */ public static void roundDayTime(final Calendar cal, final Rounding mode) { if (cal == null) throw new IllegalArgumentException("cal argument is null."); if (mode == null) return; switch (mode) { case MAX: cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND)); return; case MIN: cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); return; case NONE: default: break; } } /** * Rounding incoming time to Month, up/down rounding defined by {@link Rounding}. * * @param time * time in millis * @param mode * rounding mode * @return rounded time in millis */ public static long roundTimeToMonthTime(final long time, final Rounding mode) { if (mode == null || Rounding.NONE == mode) return time; final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); roundMonthTime(cal, mode); return cal.getTimeInMillis(); } /** * Round date to maximum or minimum in month, depending of rounding mode. * * @param cal * {@link Calendar} with configured date * @param mode * rounding mode */ public static void roundMonthTime(final Calendar cal, final Rounding mode) { if (cal == null) throw new IllegalArgumentException("cal argument is null."); if (mode == null || Rounding.NONE == mode) return; switch (mode) { case MAX: cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND)); break; case MIN: cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); break; case NONE: default: break; } } /** * Rounding incoming time to Year, up/down rounding defined by {@link Rounding}. * * @param time * time in millis * @param mode * rounding mode * @return rounded time in millis */ public static long roundTimeToYearTime(final long time, final Rounding mode) { if (mode == null || Rounding.NONE == mode) return time; final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); roundYearTime(cal, mode); return cal.getTimeInMillis(); } /** * Round date to maximum or minimum in year, depending of rounding mode. * * @param cal * {@link Calendar} with configured date * @param mode * rounding mode */ public static void roundYearTime(final Calendar cal, final Rounding mode) { if (cal == null) throw new IllegalArgumentException("cal argument is null."); if (mode == null || Rounding.NONE == mode) return; switch (mode) { case MAX: cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH)); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND)); break; case MIN: cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH)); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND)); break; case NONE: default: break; } } /** * Rounding mode. * * @author Alexandr Bolbat */ public enum Rounding { /** * No rounding. */ NONE, /** * Round to min time. */ MAX, /** * Round to max time. */ MIN; /** * Default {@link Rounding}. */ public static final Rounding DEFAULT = NONE; } }
package enc; import static java.lang.System.out; import java.io.IOException; import org.apache.parquet.column.values.rle.RunLengthBitPackingHybridEncoder; public class GenerateRLETestCases { private static void printLine() { out.println("===============================================\n"); } private static void printBytes(byte[] bytes) { for (byte b : bytes) { out.printf("0x%02X ", b); } out.println(); } private static void genSingleRLERun_10_Zeroes_1_bit() throws IOException { out.println("Single RLE run: 1-bit per value, 10x0"); RunLengthBitPackingHybridEncoder e = new RunLengthBitPackingHybridEncoder( 1, 10, 10000); for (int i = 0; i < 10; i++) { e.writeInt(0); } printBytes(e.toBytes().toByteArray()); printLine(); } private static void genSingleRLERun_300_Ones_20_bit() throws IOException { out.println("Single RLE run: 20-bits per value, 300x1"); RunLengthBitPackingHybridEncoder e = new RunLengthBitPackingHybridEncoder( 20, 10, 10000); for (int i = 0; i < 300; i++) { e.writeInt(1); } printBytes(e.toBytes().toByteArray()); printLine(); } private static void gen2RLERuns_10_Zeroes_9_Ones_1_bit() throws IOException { out.println("2 RLE runs: 1-bit per value, 10x0, 9x1"); RunLengthBitPackingHybridEncoder e = new RunLengthBitPackingHybridEncoder( 1, 10, 10000); for (int i = 0; i < 10; i++) { e.writeInt(0); } for (int i = 0; i < 9; i++) { e.writeInt(1); } printBytes(e.toBytes().toByteArray()); printLine(); } public static void main(String[] args) throws IOException { genSingleRLERun_10_Zeroes_1_bit(); genSingleRLERun_300_Ones_20_bit(); gen2RLERuns_10_Zeroes_9_Ones_1_bit(); } }
package org.eclipse.imp.pdb.facts.impl.fast; import java.util.HashSet; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IListRelation; import org.eclipse.imp.pdb.facts.IListRelationWriter; import org.eclipse.imp.pdb.facts.IListWriter; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; import org.eclipse.imp.pdb.facts.exceptions.IllegalOperationException; import org.eclipse.imp.pdb.facts.impl.util.collections.ShareableValuesHashSet; import org.eclipse.imp.pdb.facts.impl.util.collections.ShareableValuesList; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.visitors.IValueVisitor; import org.eclipse.imp.pdb.facts.visitors.VisitorException; /*package*/ class ListRelation extends List implements IListRelation { /*package*/ ListRelation(Type type, ShareableValuesList content) { super(type, content); assert listType == typeFactory.lrelTypeFromTuple(type); } public int arity() { return this.elementType.getArity(); } public IListRelation closure() throws FactTypeUseException { Type resultType = getType().closure(); // will throw exception if not binary and reflexive IListRelation tmp = this; int prevCount = 0; ShareableValuesHashSet addedTuples = new ShareableValuesHashSet(); while (prevCount != tmp.length()) { prevCount = tmp.length(); IListRelation tcomp = tmp.compose(tmp); IListRelationWriter w = ListRelation.createListRelationWriter(resultType.getElementType()); for(IValue t1 : tcomp){ if(!tmp.contains(t1)){ if(!addedTuples.contains(t1)){ addedTuples.add(t1); w.append(t1); } } } tmp = tmp.concat(w.done()); addedTuples.clear(); } return tmp; } public IListRelation closureStar() throws FactTypeUseException { Type resultType = getType().closure(); // an exception will have been thrown if the type is not acceptable IListRelationWriter reflex = ListRelation.createListRelationWriter(resultType.getElementType()); for (IValue e: carrier()) { reflex.insert(new Tuple(new IValue[] {e, e})); } return (IListRelation) closure().concat(reflex.done()); } public IListRelation compose(IListRelation other) throws FactTypeUseException { Type otherTupleType = other.getFieldTypes(); if(elementType == voidType) return this; if(otherTupleType == voidType) return other; if(elementType.getArity() != 2 || otherTupleType.getArity() != 2) throw new IllegalOperationException("compose", elementType, otherTupleType); // Relaxed type constraint: if(!elementType.getFieldType(1).comparable(otherTupleType.getFieldType(0))) throw new IllegalOperationException("compose", elementType, otherTupleType); Type[] newTupleFieldTypes = new Type[]{elementType.getFieldType(0), otherTupleType.getFieldType(1)}; Type tupleType = typeFactory.tupleType(newTupleFieldTypes); IListRelationWriter w = ValueFactory.getInstance().listRelationWriter(tupleType); for (IValue v1 : data) { ITuple tuple1 = (ITuple) v1; for (IValue t2 : other) { ITuple tuple2 = (ITuple) t2; if (tuple1.get(1).isEqual(tuple2.get(0))) { w.append(new Tuple(tuple1.get(0), tuple2.get(1))); } } } return w.done(); } public IList carrier() { Type newType = getType().carrier(); IListWriter w = List.createListWriter(newType.getElementType()); HashSet<IValue> cache = new HashSet<IValue>(); for (IValue v : this) { ITuple t = (ITuple) v; for(IValue e : t){ if(!cache.contains(e)){ cache.add(e); w.append(e); } } } return w.done(); } public IList domain() { Type lrelType = getType(); IListWriter w = List.createListWriter(lrelType.getFieldType(0)); HashSet<IValue> cache = new HashSet<IValue>(); for (IValue elem : this) { ITuple tuple = (ITuple) elem; IValue e = tuple.get(0); if(!cache.contains(e)){ cache.add(e); w.append(e); } } return w.done(); } public IList range() { Type lrelType = getType(); int last = lrelType.getArity() - 1; IListWriter w = List.createListWriter(lrelType.getFieldType(last)); HashSet<IValue> cache = new HashSet<IValue>(); for (IValue elem : this) { ITuple tuple = (ITuple) elem; IValue e = tuple.get(last); if(!cache.contains(e)){ cache.add(e); w.append(e); } } return w.done(); } public <T> T accept(IValueVisitor<T> v) throws VisitorException { return v.visitListRelation(this); } public Type getFieldTypes() { return elementType; //listRelationType.getFieldTypes(); } public static IListRelationWriter createListRelationWriter(Type tupleType) { return new ListRelationWriter(tupleType); } public static IListRelationWriter createListRelationWriter() { return new ListRelationWriter(); } protected static class ListRelationWriter extends ListWriter implements IListRelationWriter { public ListRelationWriter(Type eltType) { super(eltType); } public ListRelationWriter() { super(); } public IListRelation done() { if(constructedList == null){ constructedList = new ListRelation(data.isEmpty() ? TypeFactory.getInstance().voidType() : elementType, data); } return (IListRelation) constructedList; } public int size() { // TODO Auto-generated method stub return 0; } } public IList select(int... fields) { Type eltType = getFieldTypes().select(fields); IListWriter w = ValueFactory.getInstance().listWriter(eltType); for (IValue v : this) { w.append(((ITuple) v).select(fields)); } return w.done(); } public IList selectByFieldNames(String... fields) { int[] indexes = new int[fields.length]; int i = 0; if (getFieldTypes().hasFieldNames()) { for (String field : fields) { indexes[i++] = getFieldTypes().getFieldIndex(field); } return select(indexes); } throw new IllegalOperationException("select with field names", getType()); } }
package ch.ethz.geco.bass.audio.util; import ch.ethz.geco.bass.Main; import ch.ethz.geco.bass.server.RequestSender; import com.google.gson.JsonObject; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import java.util.*; /** * Represents a playlist. */ public class Playlist { private final Comparator<AudioTrack> comparator = Comparator.comparing((AudioTrack track) -> ((AudioTrackMetaData) track.getUserData()).getVoteCount()).reversed().thenComparing(Comparator.comparing((AudioTrack track) -> ((AudioTrackMetaData) track.getUserData()).getTrackID())); /** * The internal mapping of trackIDs to tracks. */ private final HashMap<Integer, AudioTrack> trackSet = new HashMap<>(); /** * The playlist in a sorted format. */ private ArrayList<AudioTrack> sortedPlaylist = new ArrayList<>(); /** * Adds a track to the playlist if the track is not already in it. * * @param track the track to add * @return true on success, false if the track is already in the playlist */ public boolean add(AudioTrack track) { synchronized (this) { Integer trackID = ((AudioTrackMetaData) track.getUserData()).getTrackID(); if (trackSet.putIfAbsent(trackID, track) == null) { if (sortedPlaylist.add(track)) { resort(); return true; } else { trackSet.remove(trackID); } } return false; } } /** * Returns the next track in order. * * @return the next track in order, or null if the playlist is empty */ public AudioTrack poll() { synchronized (this) { if (sortedPlaylist.isEmpty()) { // Broadcast to users JsonObject jo = new JsonObject(); JsonObject data = new JsonObject(); data.addProperty("state", "stopped"); jo.addProperty("method", "post"); jo.addProperty("type", "player/control"); jo.add("data", data); Main.server.broadcast(jo); return null; } AudioTrack track = sortedPlaylist.remove(0); trackSet.remove(((AudioTrackMetaData) track.getUserData()).getTrackID()); RequestSender.broadcastPlaylist(); return track; } } /** * Returns a sorted list of all audio tracks. * * @return a sorted list of all audio tracks */ public List<AudioTrack> getSortedList() { synchronized (this) { return sortedPlaylist; } } /** * Sets the vote of a user for the given track. * <p> * vote = 0 means that the vote gets removed for that user. * * @param trackID the ID of the track * @param userID the ID of the user who voted * @param vote the vote */ public void setVote(Integer trackID, String userID, Byte vote) { AudioTrack track = trackSet.get(trackID); if (track != null) { ((AudioTrackMetaData) track.getUserData()).getVotes().put(userID, vote); resort(); } } /** * Resorts the playlist */ public void resort() { synchronized (this) { AudioTrack[] tracks = sortedPlaylist.toArray(new AudioTrack[sortedPlaylist.size()]); for (int i = 1; i < tracks.length; i++) { AudioTrack x = tracks[i]; int j = i - 1; while (j >= 0 && comparator.compare(tracks[j], x) > 0) { tracks[j + 1] = tracks[j]; j } tracks[j + 1] = x; } sortedPlaylist = new ArrayList<>(Arrays.asList(tracks)); RequestSender.broadcastPlaylist(); } } }
package net.domesdaybook.automata; import net.domesdaybook.automata.strategy.AllMatchingTransitions; import net.domesdaybook.automata.strategy.FirstMatchingTransition; import net.domesdaybook.automata.strategy.NoTransition; import java.util.Collection; import net.domesdaybook.object.copy.DeepCopy; import java.util.List; import java.util.Map; /** * State is an interface representing a single state of an automata. * A state can have transitions to other states (or to itself), * and is either a final or non-final state. * <p> * A {@link Transition} is a reference to another State reachable from this State. * Transitions specify on which bytes a transition to the other State can be made. * To find which States are reachable given a byte, call appendNextStatesForByte(). * The states which are reachable depend both on the transitions that actually exist, * and the {@link TransitionStrategy} in use by this State. * <p> * A final State is one which marks the completion of some part of the automata. * It is possible for a State to be both final and have transitions out of it * to other States. This is because an automata may continue to match after * some part of it has found a match. * <p> * For example, given the text 'AB' and using an automata which matches the expression * 'A'|'AB', the first 'A' will produce a match. So the State transitioned * to on the 'A' must be a final state. If matching continues, it can produce * another match on 'AB', making the State transitioned to on 'B' (from the 'A' * State) also a final state. * <p> * Finality implies that the automata could stop matching at this point, having * found a match of some sort. It does not imply that the automata cannot continue * to produce other matches afterwards by following outgoing transitions. * <p> * It extends the {@link DeepCopy} interface, to ensure that all states * can provide deep copies of themselves. * * @see Transition * @see TransitionStrategy * * @author Matt Palmer */ public interface State extends DeepCopy { // Constants //FIXME: replace these with an enum and wherever they are currently used? /** A constant representing a final state. */ public static boolean FINAL = true; /** A constant representing a non-final state. */ public static boolean NON_FINAL = false; /** * A reusable instance of the first matching transition strategy, which given * a byte will return the first State it can find a transition to. * <p/> * This strategy is entirely stateless, so it is safe to re-use anywhere. */ public static final TransitionStrategy FIRST_MATCHING_TRANSITION = new FirstMatchingTransition(); /** * A reusable instance of the all matching transition strategy, which given * a byte will return all the States it can find a transition to. * <p/> * This strategy is entirely stateless, so it is safe to re-use anywhere. */ public static final TransitionStrategy ALL_MATCHING_TRANSITIONS = new AllMatchingTransitions(); /** * A reusable instance of the no transition strategy, which given * a byte will always return no States. * <p/> * This strategy is entirely stateless, so it is safe to re-use anywhere. */ public static final TransitionStrategy NO_TRANSITION = new NoTransition(); // Methods /** * Appends to the collection supplied any states reachable by the byte given. * <p/> * The {@link TransitionStrategy} used by this State controls which states are appended. * * @param value The byte value to find the next states for. * @param states The collection to which the next states (if any) will be added. * @see TransitionStrategy */ public void appendNextStatesForByte(final Collection<State> states, final byte value); /** * Returns true if this state is final. * * @return if this State is final. */ public boolean isFinal(); /** * Returns a list of the transitions which exist from this State. * * @return A list of transitions from this state. */ public List<Transition> getTransitions(); /** * Sets a {@link TransitionStrategy} to use for this state. * <p> * Implementations of State must call the initialise() method * on any TransitionStrategy set here, to ensure that the strategy * is properly initialised. * <p> * Note: not all TransitionStrategies require initialisation, but some do. * * @param strategy The transition strategy to use for this state. */ public void setTransitionStrategy(final TransitionStrategy strategy); /** * Returns the {@link TransitionStrategy} in use for this state. * * @return The transition strategy used by this state. */ public TransitionStrategy getTransitionStrategy(); /** * Sets whether this state is final or not. * * @param isFinal The finality of the state. */ public void setIsFinal(final boolean isFinal); /** * Adds a {@link Transition} to this state. * * @param transition The transition to add to this state. */ public void addTransition(final Transition transition); /** * Adds the list of {@link Transition}s to this state. * * @param transitions A list of transitions to add to this state. */ public void addAllTransitions(final List<Transition> transitions); /** * Removes a {@link Transition} from this state. * * @param transition The transition to remove from this state. * @return boolean Whether the transition was in the State. */ public boolean removeTransition(final Transition transition); /** * This is a convenience method, providing the initial map to: * <CODE>deepCopy(Map<DeepCopy, DeepCopy> oldToNewObjects)</CODE> * * @return State a deep copy of this object. * @see #deepCopy(Map<DeepCopy, DeepCopy> oldToNewObjects) */ public State deepCopy(); /** * This method is inherited from the {@link DeepCopy} interface, * and is redeclared here with a return type of State (rather than DeepCopy), * to make using the method easier. * * @param oldToNewObjects A map of the original objects to their new deep copies. * @return State A deep copy of this State and any Transitions and States * reachable from this State. */ public State deepCopy(final Map<DeepCopy, DeepCopy> oldToNewObjects); }
package org.exist.xquery.functions.xmldb; import org.exist.dom.QName; import org.exist.security.User; import org.exist.xmldb.LocalCollection; import org.exist.xmldb.UserManagementService; import org.exist.xmldb.XmldbURI; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.AnyURIValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.xmldb.api.base.Collection; import org.xmldb.api.base.XMLDBException; /** * @author wolf */ public class XMLDBCreateUser extends BasicFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("create-user", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX), "Create a new user in the database. Arguments are: username, password, group memberships and " + "home collection.", new SequenceType[]{ new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.ONE_OR_MORE), new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE) }, new SequenceType(Type.ITEM, Cardinality.EMPTY)); /** * @param context */ public XMLDBCreateUser(XQueryContext context) { super(context, signature); } /* * (non-Javadoc) * * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet, * org.exist.xquery.value.Sequence, org.exist.xquery.value.Item) */ public Sequence eval(Sequence args[], Sequence contextSequence) throws XPathException { String user = args[0].getStringValue(); String pass = args[1].getStringValue(); User userObj = new User(user, pass); LOG.info("Attempting to create user "+user); // changed by wolf: the first group is always the primary group, so we don't need // an additional argument Sequence groups = args[2]; int len = groups.getItemCount(); for (int x = 0; x < len; x++) userObj.addGroup(groups.itemAt(x).getStringValue()); if(!"".equals(args[3].getStringValue())) { try { userObj.setHome(new AnyURIValue(args[3].getStringValue()).toXmldbURI()); } catch(XPathException e) { throw new XPathException(getASTNode(),"Invalid home collection URI",e); } } Collection collection = null; try { collection = new LocalCollection(context.getUser(), context.getBroker().getBrokerPool(), XmldbURI.ROOT_COLLECTION_URI, context.getAccessContext()); UserManagementService ums = (UserManagementService) collection.getService("UserManagementService", "1.0"); ums.addUser(userObj); } catch (XMLDBException xe) { throw new XPathException(getASTNode(), "Failed to create new user " + user, xe); } finally { if (null != collection) try { collection.close(); } catch (XMLDBException e) { /* ignore */ } } return Sequence.EMPTY_SEQUENCE; } }
package chesspresso.game.view; import java.io.*; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import freemarker.template.Version; import chesspresso.*; import chesspresso.game.*; import chesspresso.move.*; import chesspresso.position.*; /** * Producer for HTML pages displaying a game. * * @author Bernhard Seybold * @author Jeff Tsay * @version $Revision: 1.3 $ */ public class HTMLGameBrowser implements GameListener { // GameListener Methods @Override public void notifyLineStart(int level) { m_isLineStart = true; m_showMoveNumber = true; m_lasts[level + 1] = m_lasts[level]; } @Override public void notifyLineEnd(int level) { m_isLineEnd = true; m_showMoveNumber = true; } @Override public void notifyMove(Move move, short[] nags, String comment, int plyNumber, int level) { ImmutablePosition pos = m_game.getPosition(); final PlyModel plyModel = new PlyModel(); plyModel.plyNumber = plyNumber; plyModel.lineStart = m_isLineStart; plyModel.lineEnd = m_isLineEnd; m_isLineStart = m_isLineEnd = false; plyModel.showMoveNumber = m_showMoveNumber; plyModel.moveNumber = m_moveNumber; m_showMoveNumber = Chess.isWhitePly(plyNumber + 1); plyModel.level = level; plyModel.move = move; if (nags != null) { for (int i = 0; i < nags.length; i++) { plyModel.nags.add(NAG.getShortString(nags[i])); } m_showMoveNumber = true; } plyModel.comment = comment; m_plyModels.add(plyModel); addPosData(pos); m_lastData.add(m_lasts[level]); m_lasts[level] = m_moveNumber; m_moveNumber++; } /** * Create a new HTMLGameBrowser with default settings. */ public HTMLGameBrowser() { m_wimgs = new String[]{ "wkw.gif", "wpw.gif", "wqw.gif", "wrw.gif", "wbw.gif", "wnw.gif", "now.gif", "bnw.gif", "bbw.gif", "brw.gif", "bqw.gif", "bpw.gif", "bkw.gif" }; m_bimgs = new String[]{ "wkb.gif", "wpb.gif", "wqb.gif", "wrb.gif", "wbb.gif", "wnb.gif", "nob.gif", "bnb.gif", "bbb.gif", "brb.gif", "bqb.gif", "bpb.gif", "bkb.gif" }; } /** * Sets the name of an square image. The default names are set according to * the following scheme: First letter is the color of the stone (b, w), second * letter the piece (k, q, r, b, n, p) third letter the square color (b, w), * extension is gif. now.gif and nob.gif are used for empty squares.<br> * For instance: wkw.gif determines a white king on a white square, * bbb.gif is a black bishop on a black square. * * @param stone the stone displayed * @param whiteSquare whether or not the square is white * @param name the name of the corresponding image */ private void setStoneImageName(int stone, boolean whiteSquare, String name) { if (whiteSquare) { m_wimgs[stone - Chess.MIN_STONE] = name; } else { m_bimgs[stone - Chess.MIN_STONE] = name; } } /** * Produces HTML to display a game. * * @param outStream where the HTML will be sent to * @param game the game to display. */ public void produceHtml(OutputStream outStream, Game game) throws Exception { produceHtml(outStream, game, new HtmlGenerationOptions(), false); } public static class HtmlGenerationOptions { /** Creates an instance that uses Bootstrap 3, with contentOnly false. */ public HtmlGenerationOptions() { } boolean contentOnly = false; String styleHtml = DEFAULT_STYLE_HTML; String scriptHtml = DEFAULT_SCRIPT_HTML; int bootstrapMajorVersion = 3; String imagePrefix = ""; public boolean isContentOnly() { return contentOnly; } public String getStyleHtml() { return styleHtml; } public String getScriptHtml() { return scriptHtml; } public int getBootstrapMajorVersion() { return bootstrapMajorVersion; } public String getImagePrefix() { return imagePrefix; } } public static HtmlGenerationOptions makeBootstrap2HtmlGenerationOptions() { final HtmlGenerationOptions options = new HtmlGenerationOptions(); options.styleHtml = BOOTSTRAP_2_STYLE_HTML + CHESSPRESSO_STYLE_HTML; options.scriptHtml = JQUERY_SCRIPT_HTML + BOOTSTRAP_2_SCRIPT_HTML; options.bootstrapMajorVersion = 2; return options; } /** * Produces HTML to display a game. * * @param outStream where the HTML will be sent to * @param game the game to display. * @param contentOnly if true skip header and footer information, use this if you want to * produce your own header and footer */ public synchronized void produceHtml(final OutputStream outStream, final Game game, final HtmlGenerationOptions options, final boolean debugMode) throws Exception { m_plyModels = new LinkedList<>(); m_posData = new LinkedList<>(); m_lastData = new LinkedList<>(); m_game = game; m_moveNumber = 0; m_showMoveNumber = true; m_lasts = new int[100]; m_lasts[0] = 0; m_lastData.add(0); m_game.gotoStart(); addPosData(m_game.getPosition()); m_moveNumber++; game.traverse(this, true); List<String> imagePaths = null; if (!options.contentOnly) { imagePaths = new LinkedList<String>(); for (int stone = Chess.MIN_STONE; stone <= Chess.MAX_STONE; stone++) { imagePaths.add(getImageForStone(stone, true)); } for (int stone = Chess.MIN_STONE; stone <= Chess.MAX_STONE; stone++) { imagePaths.add(getImageForStone(stone, false)); } } final Position startPos = Position.createInitialPosition(); final List<List<String>> imagePathsPerRow = new LinkedList<>(); for (int row = Chess.NUM_OF_ROWS - 1; row >= 0; row final List<String> imagePathsForRow = new LinkedList<>(); for (int col = 0; col < Chess.NUM_OF_COLS; col++) { int sqi = Chess.coorToSqi(col, row); imagePathsForRow.add(getImageForStone(startPos.getStone(sqi), Chess.isWhiteSquare(sqi))); } imagePathsPerRow.add(imagePathsForRow); } final Map<String, Object> root = new HashMap<>(); root.put("game", game); root.put("plys", m_plyModels); root.put("lastMoveNumber", m_moveNumber - 1); root.put("posData", m_posData); root.put("lastData", m_lastData); root.put("options", options); root.put("imagePaths", imagePaths); root.put("imagePathsPerRow", imagePathsPerRow); final Configuration config = makeConfiguration(debugMode); final Template template = config.getTemplate("game.ftl"); template.process(root, new OutputStreamWriter(outStream)); } private Configuration makeConfiguration(boolean debugMode) { final Configuration config = new Configuration(); config.setIncompatibleImprovements(new Version(2, 3, 20)); config.setClassForTemplateLoading(HTMLGameBrowser.class, "freemarker"); config.setDefaultEncoding("UTF-8"); if (debugMode) { config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); } else { config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } return config; } public static void main(String[] args) { if (args.length < 1) { //args = new String[]{ "fischer_plain.pgn" }; System.out.println("Usage: java " + HTMLGameBrowser.class.getName() + " <PGN filename>"); System.exit(0); } boolean debugMode = true; HtmlGenerationOptions htmlGenerationOptions = new HtmlGenerationOptions(); //htmlGenerationOptions = makeBootstrap2HtmlGenerationOptions(); //htmlGenerationOptions.imagePrefix = "ugly/"; try { chesspresso.pgn.PGNReader pgn = new chesspresso.pgn.PGNReader( new FileReader(args[0]), "game"); final Game game = pgn.parseGame(); final HTMLGameBrowser html = new HTMLGameBrowser(); html.produceHtml(System.out, game, htmlGenerationOptions, debugMode); } catch (Exception ex) { ex.printStackTrace(); } } /** * Needs to be public for Freemarker. */ public static class PlyModel { boolean lineStart = false; boolean lineEnd = false; int plyNumber = 0; boolean showMoveNumber = true; int moveNumber = 0; int level = 0; Move move; List<String> nags = new LinkedList<>(); String comment; public boolean getLineStart() { return lineStart; } public boolean getLineEnd() { return lineEnd; } public int getPlyNumber() { return plyNumber; } public boolean isShowMoveNumber() { return showMoveNumber; } public int getMoveNumber() { return moveNumber; } public int getLevel() { return level; } public Move getMove() { return move; } public List<String> getNags() { return nags; } public String getComment() { return comment; } @Override public String toString() { return "PlyModel{" + "lineStart=" + lineStart + ", lineEnd=" + lineEnd + ", plyNumber=" + plyNumber + ", showMoveNumber=" + showMoveNumber + ", moveNumber=" + moveNumber + ", level=" + level + ", move=" + move + ", nags=" + nags + ", comment='" + comment + '\'' + '}'; } } /** * Returns the name of the image. * * @param stone the stone displayed * @param whiteSquare whether or not the square is white */ private String getImageForStone(int stone, boolean isWhite) { return (isWhite ? m_wimgs[stone - Chess.MIN_STONE] : m_bimgs[stone - Chess.MIN_STONE]); } private void addPosData(ImmutablePosition pos) { final int[] data = new int[Chess.NUM_OF_ROWS * Chess.NUM_OF_COLS]; int j = 0; for (int row = Chess.NUM_OF_ROWS - 1; row >= 0; row for (int col = 0; col < Chess.NUM_OF_COLS; col++) { int sqi = Chess.coorToSqi(col, row); data[j++] = pos.getStone(sqi) - Chess.MIN_STONE; } } m_posData.add(data); } private List<PlyModel> m_plyModels; private boolean m_isLineStart = false; private boolean m_isLineEnd = false; private List<int[]> m_posData; private List<Integer> m_lastData; private Game m_game; private int m_moveNumber; private boolean m_showMoveNumber; private int[] m_lasts; private String[] m_wimgs; private String[] m_bimgs; public static final String CHESSPRESSO_STYLE_HTML = "<style type=\"text/css\">\n" + " .chesspresso_centered { margin: 0 auto; }\n" + " #chesspresso_container { width: 272px; }\n" + " table.chesspresso_board { border-collapse: collapse; }\n" + " table.chesspresso_board td, { padding : 0; }\n" + " #chesspresso_tape_control { margin-top: 6px; text-align: center; }\n" + " .chesspresso_main { text-decoration: none }\n" + " .chesspresso_line { text-decoration: none }\n" + " a.chesspresso_main { font-weight: bold; color: black; }\n" + " a.chesspresso_line { color: black; }\n" + " span.chesspresso_comment { font-style: italic; }\n" + " .chesspresso_deselected_ply_link { background: white !important; color: black !important; }\n" + " .chesspresso_selected_ply_link { background: black !important; color: white !important; }\n" + "</style>"; public static final String BOOTSTRAP_2_STYLE_HTML = "<link href=\"https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css\" rel=\"stylesheet\" />\n"; public static final String BOOTSTRAP_3_STYLE_HTML = "<link href=\"https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css\" rel=\"stylesheet\" />\n"; public static final String DEFAULT_STYLE_HTML = BOOTSTRAP_3_STYLE_HTML + CHESSPRESSO_STYLE_HTML; public static final String JQUERY_SCRIPT_HTML = "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script>\n"; public static final String BOOTSTRAP_2_SCRIPT_HTML = "<script src=\"https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js\"></script>"; public static final String BOOTSTRAP_3_SCRIPT_HTML = "<script src=\"https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js\"></script>"; public static final String DEFAULT_SCRIPT_HTML = JQUERY_SCRIPT_HTML + BOOTSTRAP_3_SCRIPT_HTML; }