answer
stringlengths
17
10.2M
package com.exedio.cope.pattern; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.exedio.cope.Pattern; public abstract class HttpPath extends Pattern { private String urlPath = null; private String mediaRootUrl = null; public void initialize() { final String name = getName(); urlPath = getType().getID() + '/' + name + '/'; } final String getUrlPath() { if(urlPath==null) throw new RuntimeException("http entity not yet initialized"); return urlPath; } final String getMediaRootUrl() { if(mediaRootUrl==null) mediaRootUrl = getType().getModel().getProperties().getMediaRootUrl(); return mediaRootUrl; } abstract boolean serveContent(HttpServletRequest request, HttpServletResponse response, String pathInfo, int trailingSlash) throws ServletException, IOException; public abstract Date getStart(); public final static class Log { private int counter = 0; private final Object lock = new Object(); public final void increment() { synchronized(lock) { counter++; } } public final int get() { synchronized(lock) { return counter; } } final void reset() { synchronized(lock) { counter = 0; } } } }
package nl.topicus.jdbc; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.function.Function; import java.util.function.Supplier; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.UserCredentials; import com.google.cloud.Timestamp; import com.google.cloud.spanner.DatabaseAdminClient; import com.google.cloud.spanner.DatabaseClient; import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.Instance; import com.google.cloud.spanner.Operation; import com.google.cloud.spanner.ResultSets; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.SpannerOptions.Builder; import com.google.cloud.spanner.Struct; import com.google.cloud.spanner.Type; import com.google.cloud.spanner.Type.StructField; import com.google.cloud.spanner.Value; import com.google.common.annotations.VisibleForTesting; import com.google.rpc.Code; import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; import nl.topicus.jdbc.MetaDataStore.TableKeyMetaData; import nl.topicus.jdbc.exception.CloudSpannerSQLException; import nl.topicus.jdbc.resultset.CloudSpannerResultSet; import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement; import nl.topicus.jdbc.statement.CloudSpannerStatement; import nl.topicus.jdbc.transaction.CloudSpannerTransaction; /** * JDBC Driver for Google Cloud Spanner. * * @author loite * */ public class CloudSpannerConnection extends AbstractCloudSpannerConnection { public static class CloudSpannerDatabaseSpecification { public final String project; public final String instance; public final String database; public CloudSpannerDatabaseSpecification(String instance, String database) { this(null, instance, database); } public CloudSpannerDatabaseSpecification(String project, String instance, String database) { this.project = project; this.instance = instance; this.database = database; } } private final CloudSpannerDriver driver; private final CloudSpannerDatabaseSpecification database; private Spanner spanner; private String clientId; private DatabaseClient dbClient; private DatabaseAdminClient adminClient; private boolean autoCommit = true; private boolean closed; private boolean readOnly; private final RunningOperationsStore operations = new RunningOperationsStore(); private final String url; private final Properties suppliedProperties; private boolean originalAllowExtendedMode; private boolean allowExtendedMode; private boolean originalAsyncDdlOperations; private boolean asyncDdlOperations; private boolean originalAutoBatchDdlOperations; private boolean autoBatchDdlOperations; private List<String> autoBatchedDdlOperations = new ArrayList<>(); private boolean originalReportDefaultSchemaAsNull = true; private boolean reportDefaultSchemaAsNull = true; private String simulateProductName; private Integer simulateMajorVersion; private Integer simulateMinorVersion; private CloudSpannerTransaction transaction; private Timestamp lastCommitTimestamp; private MetaDataStore metaDataStore; private static int nextConnectionID = 1; private final Logger logger; private Map<String, Class<?>> typeMap = new HashMap<>(); @VisibleForTesting CloudSpannerConnection() { this.driver = null; this.database = null; this.url = null; this.suppliedProperties = null; this.logger = null; } CloudSpannerConnection(CloudSpannerDriver driver, String url, CloudSpannerDatabaseSpecification database, String credentialsPath, String oauthToken, Properties suppliedProperties) throws SQLException { this.driver = driver; this.database = database; this.url = url; this.suppliedProperties = suppliedProperties; int logLevel = CloudSpannerDriver.getLogLevel(); synchronized (CloudSpannerConnection.class) { logger = new Logger(nextConnectionID++); logger.setLogLevel(logLevel); } try { Builder builder = SpannerOptions.newBuilder(); if (database.project != null) builder.setProjectId(database.project); GoogleCredentials credentials = null; if (credentialsPath != null) { credentials = getCredentialsFromFile(credentialsPath); builder.setCredentials(credentials); } else if (oauthToken != null) { credentials = getCredentialsFromOAuthToken(oauthToken); builder.setCredentials(credentials); } if (credentials != null) { if (credentials instanceof UserCredentials) { clientId = ((UserCredentials) credentials).getClientId(); } if (credentials instanceof ServiceAccountCredentials) { clientId = ((ServiceAccountCredentials) credentials).getClientId(); } } SpannerOptions options = builder.build(); spanner = options.getService(); dbClient = spanner .getDatabaseClient(DatabaseId.of(options.getProjectId(), database.instance, database.database)); adminClient = spanner.getDatabaseAdminClient(); transaction = new CloudSpannerTransaction(dbClient, this); metaDataStore = new MetaDataStore(this); } catch (SpannerException e) { throw new CloudSpannerSQLException("Error when opening Google Cloud Spanner connection: " + e.getMessage(), e); } catch (IOException e) { throw new CloudSpannerSQLException("Error when opening Google Cloud Spanner connection: " + e.getMessage(), Code.UNKNOWN, e); } } public static GoogleCredentials getCredentialsFromOAuthToken(String oauthToken) { GoogleCredentials credentials = null; if (oauthToken != null && oauthToken.length() > 0) { credentials = GoogleCredentials.create(new AccessToken(oauthToken, null)); } return credentials; } public static GoogleCredentials getCredentialsFromFile(String credentialsPath) throws IOException { if (credentialsPath == null || credentialsPath.length() == 0) throw new IllegalArgumentException("credentialsPath may not be null or empty"); GoogleCredentials credentials = null; File credentialsFile = new File(credentialsPath); if (!credentialsFile.isFile()) { throw new IOException( String.format("Error reading credential file %s: File does not exist", credentialsPath)); } try (InputStream credentialsStream = new FileInputStream(credentialsFile)) { credentials = GoogleCredentials.fromStream(credentialsStream, CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY); } return credentials; } public static String getServiceAccountProjectId(String credentialsPath) { String project = null; if (credentialsPath != null) { try (InputStream credentialsStream = new FileInputStream(credentialsPath)) { JSONObject json = new JSONObject(new JSONTokener(credentialsStream)); project = json.getString("project_id"); } catch (IOException | JSONException ex) { // ignore } } return project; } Spanner getSpanner() { return spanner; } public String getSimulateProductName() { return simulateProductName; } @Override public void setSimulateProductName(String productName) { this.simulateProductName = productName; } public Integer getSimulateMajorVersion() { return simulateMajorVersion; } @Override public void setSimulateMajorVersion(Integer majorVersion) { this.simulateMajorVersion = majorVersion; } public Integer getSimulateMinorVersion() { return simulateMinorVersion; } @Override public void setSimulateMinorVersion(Integer minorVersion) { this.simulateMinorVersion = minorVersion; } /** * Execute one or more DDL-statements on the database and wait for it to * finish or return after syntax check (when running in async mode). Calling * this method will also automatically commit the currently running * transaction. * * @param inputSql * The DDL-statement(s) to execute. Some statements may end up * not being sent to Cloud Spanner if they contain IF [NOT] * EXISTS clauses. The driver will check whether the condition is * met, and only then will it be sent to Cloud Spanner. * @return Nothing * @throws SQLException * If an error occurs during the execution of the statement. */ public Void executeDDL(List<String> inputSql) throws SQLException { if (!getAutoCommit()) commit(); // Check for IF [NOT] EXISTS statements List<String> sql = getActualSql(inputSql); if (!sql.isEmpty()) { try { Operation<Void, UpdateDatabaseDdlMetadata> operation = adminClient.updateDatabaseDdl(database.instance, database.database, sql, null); if (asyncDdlOperations) { operations.addOperation(sql, operation); } else { do { operation = operation.waitFor(); } while (!operation.isDone()); } return operation.getResult(); } catch (SpannerException e) { throw new CloudSpannerSQLException( "Could not execute DDL statement(s) " + String.join("\n;\n", sql) + ": " + e.getMessage(), e); } } return null; } private List<String> getActualSql(List<String> sql) throws SQLException { List<DDLStatement> statements = DDLStatement.parseDdlStatements(sql); List<String> actualSql = new ArrayList<>(sql.size()); for (DDLStatement statement : statements) { if (statement.shouldExecute(this)) { actualSql.add(statement.getSql()); } } return actualSql; } /** * Clears the asynchronous DDL-operations that have finished. * * @return The number of operations that were cleared */ public int clearFinishedDDLOperations() { return operations.clearFinishedOperations(); } /** * Waits for all asynchronous DDL-operations that have been issued by this * connection to finish. * * @throws SQLException * If a database exception occurs while waiting for the * operations to finish * */ public void waitForDdlOperations() throws SQLException { operations.waitForOperations(); } /** * Returns a ResultSet containing all asynchronous DDL-operations started by * this connection. It does not contain DDL-operations that have been * started by other connections or by other means. * * @param statement * The statement that requested the operations * @return A ResultSet with the DDL-operations */ public ResultSet getRunningDDLOperations(CloudSpannerStatement statement) { return operations.getOperations(statement); } @Override public String getProductName() { if (getSimulateProductName() != null) return getSimulateProductName(); return "Google Cloud Spanner"; } @Override public CloudSpannerStatement createStatement() throws SQLException { checkClosed(); return new CloudSpannerStatement(this, dbClient); } @Override public CloudSpannerPreparedStatement prepareStatement(String sql) throws SQLException { checkClosed(); return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public CallableStatement prepareCall(String sql) throws SQLException { checkClosed(); throw new SQLFeatureNotSupportedException(); } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); return sql; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); this.autoCommit = autoCommit; } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return autoCommit; } @Override public void commit() throws SQLException { checkClosed(); lastCommitTimestamp = transaction.commit(); } @Override public void rollback() throws SQLException { checkClosed(); transaction.rollback(); } public CloudSpannerTransaction getTransaction() { return transaction; } @Override public void close() throws SQLException { if (closed) return; transaction.rollback(); closed = true; driver.closeConnection(this); } @Override public boolean isClosed() throws SQLException { return closed; } @Override public CloudSpannerDatabaseMetaData getMetaData() throws SQLException { checkClosed(); return new CloudSpannerDatabaseMetaData(this); } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (transaction.isRunning()) throw new CloudSpannerSQLException( "There is currently a transaction running. Commit or rollback the running transaction before changing read-only mode.", Code.FAILED_PRECONDITION); this.readOnly = readOnly; } @Override public boolean isReadOnly() throws SQLException { checkClosed(); return readOnly; } @Override public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (level != Connection.TRANSACTION_SERIALIZABLE) { throw new CloudSpannerSQLException( "Transaction level " + level + " is not supported. Only Connection.TRANSACTION_SERIALIZABLE is supported", Code.INVALID_ARGUMENT); } } @Override public int getTransactionIsolation() throws SQLException { checkClosed(); return Connection.TRANSACTION_SERIALIZABLE; } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return new CloudSpannerStatement(this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new CloudSpannerStatement(this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkClosed(); return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkClosed(); return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkClosed(); return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public String getUrl() { return url; } @Override public String getClientId() { return clientId; } @Override public boolean isValid(int timeout) throws SQLException { if (isClosed()) return false; Statement statement = createStatement(); statement.setQueryTimeout(timeout); try (ResultSet rs = statement.executeQuery("SELECT 1")) { if (rs.next()) return true; } return false; } @Override public CloudSpannerArray createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); return CloudSpannerArray.createArray(typeName, elements); } public TableKeyMetaData getTable(String name) throws SQLException { return metaDataStore.getTable(name); } @Override public Properties getSuppliedProperties() { return suppliedProperties; } @Override public boolean isAllowExtendedMode() { return allowExtendedMode; } @Override public int setAllowExtendedMode(boolean allowExtendedMode) { this.allowExtendedMode = allowExtendedMode; return 1; } boolean isOriginalAllowExtendedMode() { return originalAllowExtendedMode; } void setOriginalAllowExtendedMode(boolean allowExtendedMode) { this.originalAllowExtendedMode = allowExtendedMode; } @Override public boolean isAsyncDdlOperations() { return asyncDdlOperations; } @Override public int setAsyncDdlOperations(boolean asyncDdlOperations) { this.asyncDdlOperations = asyncDdlOperations; return 1; } boolean isOriginalAsyncDdlOperations() { return originalAsyncDdlOperations; } void setOriginalAsyncDdlOperations(boolean asyncDdlOperations) { this.originalAsyncDdlOperations = asyncDdlOperations; } @Override public boolean isAutoBatchDdlOperations() { return autoBatchDdlOperations; } @Override public int setAutoBatchDdlOperations(boolean autoBatchDdlOperations) { clearAutoBatchedDdlOperations(); this.autoBatchDdlOperations = autoBatchDdlOperations; return 1; } boolean isOriginalAutoBatchDdlOperations() { return originalAutoBatchDdlOperations; } void setOriginalAutoBatchDdlOperations(boolean autoBatchDdlOperations) { this.originalAutoBatchDdlOperations = autoBatchDdlOperations; } @Override public boolean isReportDefaultSchemaAsNull() { return reportDefaultSchemaAsNull; } @Override public int setReportDefaultSchemaAsNull(boolean reportDefaultSchemaAsNull) { this.reportDefaultSchemaAsNull = reportDefaultSchemaAsNull; return 1; } boolean isOriginalReportDefaultSchemaAsNull() { return originalReportDefaultSchemaAsNull; } void setOriginalReportDefaultSchemaAsNull(boolean reportDefaultSchemaAsNull) { this.originalReportDefaultSchemaAsNull = reportDefaultSchemaAsNull; } /** * Set a dynamic connection property, such as AsyncDdlOperations * * @param propertyName * The name of the dynamic connection property * @param propertyValue * The value to set * @return 1 if the property was set, 0 if not (this complies with the * normal behaviour of executeUpdate(...) methods) */ public int setDynamicConnectionProperty(String propertyName, String propertyValue) { return getPropertySetter(propertyName).apply(Boolean.valueOf(propertyValue)); } /** * Reset a dynamic connection property to its original value, such as * AsyncDdlOperations * * @param propertyName * The name of the dynamic connection property * @return 1 if the property was reset, 0 if not (this complies with the * normal behaviour of executeUpdate(...) methods) */ public int resetDynamicConnectionProperty(String propertyName) { return getPropertySetter(propertyName).apply(getOriginalValueGetter(propertyName).get()); } private Supplier<Boolean> getOriginalValueGetter(String propertyName) { if (propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE))) { return this::isOriginalAllowExtendedMode; } if (propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS))) { return this::isOriginalAsyncDdlOperations; } if (propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS))) { return this::isOriginalAutoBatchDdlOperations; } if (propertyName.equalsIgnoreCase( ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL))) { return this::isOriginalReportDefaultSchemaAsNull; } // Return a no-op to avoid null checks return () -> false; } private Function<Boolean, Integer> getPropertySetter(String propertyName) { if (propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE))) { return this::setAllowExtendedMode; } if (propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS))) { return this::setAsyncDdlOperations; } if (propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS))) { return this::setAutoBatchDdlOperations; } if (propertyName.equalsIgnoreCase( ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL))) { return this::setReportDefaultSchemaAsNull; } // Return a no-op to avoid null checks return x -> 0; } public ResultSet getDynamicConnectionProperties(CloudSpannerStatement statement) { return getDynamicConnectionProperty(statement, null); } public ResultSet getDynamicConnectionProperty(CloudSpannerStatement statement, String propertyName) { Map<String, String> values = new HashMap<>(); if (propertyName == null || propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE))) { values.put(ConnectionProperties.getPropertyName(ConnectionProperties.ALLOW_EXTENDED_MODE), String.valueOf(isAllowExtendedMode())); } if (propertyName == null || propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS))) { values.put(ConnectionProperties.getPropertyName(ConnectionProperties.ASYNC_DDL_OPERATIONS), String.valueOf(isAsyncDdlOperations())); } if (propertyName == null || propertyName .equalsIgnoreCase(ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS))) { values.put(ConnectionProperties.getPropertyName(ConnectionProperties.AUTO_BATCH_DDL_OPERATIONS), String.valueOf(isAutoBatchDdlOperations())); } if (propertyName == null || propertyName.equalsIgnoreCase( ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL))) { values.put(ConnectionProperties.getPropertyName(ConnectionProperties.REPORT_DEFAULT_SCHEMA_AS_NULL), String.valueOf(isReportDefaultSchemaAsNull())); } return createResultSet(statement, values); } private ResultSet createResultSet(CloudSpannerStatement statement, Map<String, String> values) { List<Struct> rows = new ArrayList<>(values.size()); for (Entry<String, String> entry : values.entrySet()) { rows.add(Struct.newBuilder().add("NAME", Value.string(entry.getKey())) .add("VALUE", Value.string(entry.getValue())).build()); } com.google.cloud.spanner.ResultSet rs = ResultSets.forRows( Type.struct(StructField.of("NAME", Type.string()), StructField.of("VALUE", Type.string())), rows); return new CloudSpannerResultSet(statement, rs); } /** * * @return The commit timestamp of the last transaction that committed * succesfully */ @Override public Timestamp getLastCommitTimestamp() { return lastCommitTimestamp; } /** * * @return A new connection with the same URL and properties as this * connection. You can use this method if you want to open a new * connection to the same database, for example to run a number of * statements in a different transaction than the transaction you * are currently using on this connection. * @throws SQLException * If an error occurs while opening the new connection */ public CloudSpannerConnection createCopyConnection() throws SQLException { return (CloudSpannerConnection) DriverManager.getConnection(getUrl(), getSuppliedProperties()); } public Logger getLogger() { return logger; } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return typeMap; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { checkClosed(); this.typeMap = map; } /** * * @return The number of nodes of this Cloud Spanner instance * @throws SQLException * If an exception occurs when trying to get the number of nodes */ public int getNodeCount() throws SQLException { try { if (database != null && database.instance != null) { Instance instance = getSpanner().getInstanceAdminClient().getInstance(database.instance); return instance == null ? 0 : instance.getNodeCount(); } return 0; } catch (SpannerException e) { throw new CloudSpannerSQLException(e); } } /** * Prepare the current transaction by writing the mutations to the * XA_TRANSACTIONS table instead of persisting them in the actual tables. * * @param xid * The id of the prepared transaction * @throws SQLException * If an exception occurs while saving the mutations to the * database for later commit */ public void prepareTransaction(String xid) throws SQLException { transaction.prepareTransaction(xid); } /** * Commit a previously prepared transaction. * * @param xid * The id of the prepared transaction * @throws SQLException * If an error occurs when writing the mutations to the database */ public void commitPreparedTransaction(String xid) throws SQLException { transaction.commitPreparedTransaction(xid); } /** * Rollback a previously prepared transaction. * * @param xid * The id of the prepared transaction to rollback * @throws SQLException * If an error occurs while rolling back the prepared * transaction */ public void rollbackPreparedTransaction(String xid) throws SQLException { transaction.rollbackPreparedTransaction(xid); } public List<String> getAutoBatchedDdlOperations() { return Collections.unmodifiableList(autoBatchedDdlOperations); } public void clearAutoBatchedDdlOperations() { autoBatchedDdlOperations.clear(); } public void addAutoBatchedDdlOperation(String sql) { autoBatchedDdlOperations.add(sql); } }
package org.blub.controller; import org.blub.domain.Document; import org.blub.repository.DocumentRepository; import org.blub.service.DocumentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.sql.Timestamp; import java.util.Date; @RestController @RequestMapping(value = "/api/documents") public class DocumentController { @Autowired private DocumentRepository documentRepository; @Autowired private DocumentService documentService; //shall only return the most recent document of each versioning path @RequestMapping(method = RequestMethod.GET) public Iterable<Document> listMostRecentDocumentsOfEachVersioningPath() { return documentRepository.allNewestDocumentVersions(); } @RequestMapping(method = RequestMethod.POST, consumes = "application/json") public Document create(@RequestBody Document document){ Timestamp timestamp = new Timestamp(new Date().getTime()); document.setWasVersionedAt(timestamp); documentRepository.save(document); return documentRepository.findOne(document.getId()); } @RequestMapping(method = RequestMethod.GET, value = "/{id}") public Document find(@PathVariable Long id){ return documentRepository.findOne(id); } @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") public void delete(@PathVariable Long id){ documentRepository.delete(id); } /* When updating a document without adding a file, then the path to the file shall remain and nothing in the repository changes. When updating a document and adding a file, then there shall be a new path and a changed repository. */ //// TODO: 30.01.16 move code into service(not that easy) @RequestMapping(value = "/{id}", method = RequestMethod.POST) public @ResponseBody Document update(@RequestParam("documentString") String documentString, @RequestParam(value= "file", required=false) MultipartFile file){ Document recievedDocument = documentService.deserializeDocumentString(documentString); Timestamp timestamp = new Timestamp(new Date().getTime()); Document oldDocument = documentRepository.findOne(recievedDocument.getId()); Document newDocument = new Document(); String filename = ""; String directoryWhereFileGetsSaved = "documentrepository/" + recievedDocument.getName() + timestamp; //example: /documentrepository/document12016-01-27 01:10:46.367/produktiv.ods String pathToFileForNewDocument; if (file != null && !file.isEmpty()) { filename = file.getOriginalFilename(); pathToFileForNewDocument = directoryWhereFileGetsSaved + "/" + filename; }else{ pathToFileForNewDocument = oldDocument.getPathToFile(); } //new document newDocument.setName(recievedDocument.getName()); newDocument.setExternalObjects(recievedDocument.getExternalObjects()); newDocument.setWasVersionedAt(timestamp); newDocument.setPathToFile(pathToFileForNewDocument); documentRepository.save(newDocument); //newDocument.id is generated here //reference from (old) --> (new) oldDocument.setSuccessorDocument(newDocument); documentRepository.save(oldDocument); documentService.uploadDocument(file, filename, directoryWhereFileGetsSaved); return newDocument; } @RequestMapping(value = "/download/{documentrepository}/{documentname}/{filename}.{fileending}", method = RequestMethod.GET) public void downloadFile(HttpServletResponse response, @PathVariable("documentrepository") String documentrepository, @PathVariable("documentname") String documentname, @PathVariable("filename") String filename, @PathVariable("fileending") String fileending){ documentService.downloadDocument(response, documentrepository, documentname, filename, fileending); } }
package com.slidingmenu.lib; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.VelocityTrackerCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewConfigurationCompat; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.util.TypedValue; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.Scroller; import com.slidingmenu.lib.SlidingMenu.OnCloseListener; import com.slidingmenu.lib.SlidingMenu.OnClosedListener; import com.slidingmenu.lib.SlidingMenu.OnOpenListener; import com.slidingmenu.lib.SlidingMenu.OnOpenedListener; public class CustomViewAbove extends ViewGroup { private static final String TAG = "CustomViewAbove"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = false; private static final int MAX_SETTLE_DURATION = 600; private static final int MIN_DISTANCE_FOR_FLING = 25; // dips private static final Interpolator sInterpolator = new Interpolator() { public float getInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } }; private FrameLayout mMenu; private FrameLayout mContent; private int mCurItem; private Scroller mScroller; private int mShadowWidth; private Drawable mShadowDrawable; private boolean mScrollingCacheEnabled; private boolean mScrolling; private boolean mIsBeingDragged; // private boolean mIsUnableToDrag; private int mTouchSlop; private float mInitialMotionX; /** * Position of the last motion event. */ private float mLastMotionX; private float mLastMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ protected int mActivePointerId = INVALID_POINTER; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; /** * Determines speed during touch scrolling */ protected VelocityTracker mVelocityTracker; private int mMinimumVelocity; protected int mMaximumVelocity; private int mFlingDistance; private boolean mLastTouchAllowed = false; private final int mSlidingMenuThreshold = 10; private CustomViewBehind mCustomViewBehind; private boolean mEnabled = true; private OnPageChangeListener mOnPageChangeListener; private OnPageChangeListener mInternalPageChangeListener; private OnCloseListener mCloseListener; private OnOpenListener mOpenListener; private OnClosedListener mClosedListener; private OnOpenedListener mOpenedListener; // private int mScrollState = SCROLL_STATE_IDLE; /** * Callback interface for responding to changing state of the selected page. */ public interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param positionOffset Value from [0, 1) indicating the offset from the page at position. * @param positionOffsetPixels Value in pixels indicating the offset from position. */ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); /** * This method will be invoked when a new page becomes selected. Animation is not * necessarily complete. * * @param position Position index of the new selected page. */ public void onPageSelected(int position); } /** * Simple implementation of the {@link OnPageChangeListener} interface with stub * implementations of each method. Extend this if you do not intend to override * every method of {@link OnPageChangeListener}. */ public static class SimpleOnPageChangeListener implements OnPageChangeListener { public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // This space for rent } public void onPageSelected(int position) { // This space for rent } public void onPageScrollStateChanged(int state) { // This space for rent } } public CustomViewAbove(Context context) { this(context, null); } public CustomViewAbove(Context context, AttributeSet attrs) { this(context, attrs, true); } public CustomViewAbove(Context context, AttributeSet attrs, boolean isAbove) { super(context, attrs); initCustomViewAbove(isAbove); } void initCustomViewAbove() { initCustomViewAbove(false); } void initCustomViewAbove(boolean isAbove) { setWillNotDraw(false); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); final Context context = getContext(); mScroller = new Scroller(context, sInterpolator); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); setInternalPageChangeListener(new SimpleOnPageChangeListener() { public void onPageSelected(int position) { if (mCustomViewBehind != null) { switch (position) { case 0: mCustomViewBehind.setChildrenEnabled(true); break; case 1: mCustomViewBehind.setChildrenEnabled(false); break; } } } }); final float density = context.getResources().getDisplayMetrics().density; mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); mMenu = new FrameLayout(getContext()); super.addView(mMenu); mContent = new FrameLayout(getContext()); super.addView(mContent); if (isAbove) { View v = new LinearLayout(getContext()); v.setBackgroundResource(android.R.color.transparent); setMenu(v); } } /** * Set the currently selected page. If the CustomViewPager has already been through its first * layout there will be a smooth animated transition between the current item and the * specified item. * * @param item Item index to select */ public void setCurrentItem(int item) { setCurrentItemInternal(item, true, false); } /** * Set the currently selected page. * * @param item Item index to select * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately */ public void setCurrentItem(int item, boolean smoothScroll) { setCurrentItemInternal(item, smoothScroll, false); } public int getCurrentItem() { return mCurItem; } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { setCurrentItemInternal(item, smoothScroll, always, 0); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { if (!always && mCurItem == item && mMenu != null && mContent != null) { setScrollingCacheEnabled(false); return; } if (item < 0) { item = 0; } else if (item >= 2) { item = 1; } final boolean dispatchSelected = mCurItem != item; mCurItem = item; final int destX = getChildLeft(mCurItem); if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } if (dispatchSelected && mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageSelected(item); } if (smoothScroll) { smoothScrollTo(destX, 0, velocity); } else { completeScroll(); scrollTo(destX, 0); } } /** * Set a listener that will be invoked whenever the page changes or is incrementally * scrolled. See {@link OnPageChangeListener}. * * @param listener Listener to set */ public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; } public void setOnOpenListener(OnOpenListener l) { mOpenListener = l; } public void setOnCloseListener(OnCloseListener l) { mCloseListener = l; } public void setOnOpenedListener(OnOpenedListener l) { mOpenedListener = l; } public void setOnClosedListener(OnClosedListener l) { mClosedListener = l; } /** * Set a separate OnPageChangeListener for internal use by the support library. * * @param listener Listener to set * @return The old listener that was set, if any. */ OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) { OnPageChangeListener oldListener = mInternalPageChangeListener; mInternalPageChangeListener = listener; return oldListener; } /** * Set the margin between pages. * * @param shadowWidth Distance between adjacent pages in pixels * @see #getShadowWidth() * @see #setShadowDrawable(Drawable) * @see #setShadowDrawable(int) */ public void setShadowWidth(int shadowWidth) { mShadowWidth = shadowWidth; invalidate(); } /** * Return the margin between pages. * * @return The size of the margin in pixels */ public int getShadowWidth() { return mShadowWidth; } /** * Set a drawable that will be used to fill the margin between pages. * * @param d Drawable to display between pages */ public void setShadowDrawable(Drawable d) { mShadowDrawable = d; if (d != null) refreshDrawableState(); setWillNotDraw(d == null); invalidate(); } /** * Set a drawable that will be used to fill the margin between pages. * * @param resId Resource ID of a drawable to display between pages */ public void setShadowDrawable(int resId) { setShadowDrawable(getContext().getResources().getDrawable(resId)); } @Override protected boolean verifyDrawable(Drawable who) { return super.verifyDrawable(who) || who == mShadowDrawable; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); final Drawable d = mShadowDrawable; if (d != null && d.isStateful()) { d.setState(getDrawableState()); } } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) FloatMath.sin(f); } public int getDestScrollX() { if (isMenuOpen()) { return getBehindWidth(); } else { return 0; } } public int getChildLeft(int i) { if (i <= 0) return 0; return getChildWidth(i-1) + getChildLeft(i-1); } public int getChildRight(int i) { return getChildLeft(i) + getChildWidth(i); } public boolean isMenuOpen() { return getCurrentItem() == 0; } public int getCustomWidth() { int i = isMenuOpen()? 0 : 1; return getChildWidth(i); } public int getChildWidth(int i) { if (i <= 0) { return getBehindWidth(); } else { return getChildAt(i).getWidth(); } } public int getBehindWidth() { if (mCustomViewBehind == null) { return 0; } else { return mCustomViewBehind.getWidth(); } } public boolean isSlidingEnabled() { return mEnabled; } public void setSlidingEnabled(boolean b) { mEnabled = b; } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis */ void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, 0); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis * @param velocity the velocity associated with a fling, if applicable. (0 otherwise) */ void smoothScrollTo(int x, int y, int velocity) { if (getChildCount() == 0) { // Nothing to do. setScrollingCacheEnabled(false); return; } int sx = getScrollX(); int sy = getScrollY(); int dx = x - sx; int dy = y - sy; if (dx == 0 && dy == 0) { completeScroll(); if (isMenuOpen()) { if (mOpenedListener != null) mOpenedListener.onOpened(); } else { if (mClosedListener != null) mClosedListener.onClosed(); } return; } setScrollingCacheEnabled(true); mScrolling = true; final int width = getCustomWidth(); final int halfWidth = width / 2; final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio); int duration = 0; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); } else { final float pageDelta = (float) Math.abs(dx) / (width + mShadowWidth); duration = (int) ((pageDelta + 1) * 100); duration = MAX_SETTLE_DURATION; } duration = Math.min(duration, MAX_SETTLE_DURATION); mScroller.startScroll(sx, sy, dx, dy, duration); invalidate(); } protected void setMenu(View v) { if (mMenu.getChildCount() > 0) { mMenu.removeAllViews(); } mMenu.addView(v); } public void setContent(View v) { if (mContent.getChildCount() > 0) { mContent.removeAllViews(); } mContent.addView(v); } public void setCustomViewBehind(CustomViewBehind cvb) { mCustomViewBehind = cvb; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = getDefaultSize(0, widthMeasureSpec); int height = getDefaultSize(0, heightMeasureSpec); setMeasuredDimension(width, height); final int contentWidth = getChildMeasureSpec(widthMeasureSpec, 0, width); final int contentHeight = getChildMeasureSpec(heightMeasureSpec, 0, height); mContent.measure(contentWidth, contentHeight); final int menuWidth = getChildMeasureSpec(widthMeasureSpec, 0, getBehindWidth()); mMenu.measure(menuWidth, contentHeight); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Make sure scroll position is set correctly. if (w != oldw) { // [ChrisJ] - This fixes the onConfiguration change for orientation issue.. // maybe worth having a look why the recomputeScroll pos is screwing completeScroll(); scrollTo(getChildLeft(mCurItem), getScrollY()); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int width = r - l; final int height = b - t; int contentLeft = getChildLeft(1); float percentOpen = getPercentOpen(); int offset = (int) (mScrollX * (1 - mScrollScale)); mMenu.layout(0, 0, width, height); mContent.layout(contentLeft, 0, contentLeft + width, height); } @Override public void computeScroll() { if (!mScroller.isFinished()) { if (mScroller.computeScrollOffset()) { if (DEBUG) Log.i(TAG, "computeScroll: still scrolling"); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); pageScrolled(x); } // Keep on drawing until the animation has finished. invalidate(); return; } } // Done with scroll, clean up state. completeScroll(); } private void pageScrolled(int xpos) { final int widthWithMargin = getChildWidth(mCurItem) + mShadowWidth; final int position = xpos / widthWithMargin; final int offsetPixels = xpos % widthWithMargin; final float offset = (float) offsetPixels / widthWithMargin; onPageScrolled(position, offset, offsetPixels); } /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * If you override this method you must call through to the superclass implementation * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled * returns. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param offset Value from [0, 1) indicating the offset from the page at position. * @param offsetPixels Value in pixels indicating the offset from position. */ protected void onPageScrolled(int position, float offset, int offsetPixels) { if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); } if (mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels); } } private void completeScroll() { boolean needPopulate = mScrolling; if (needPopulate) { // Done with scroll, no longer want to cache view drawing. setScrollingCacheEnabled(false); mScroller.abortAnimation(); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } if (isMenuOpen()) { if (mOpenedListener != null) mOpenedListener.onOpened(); } else { if (mClosedListener != null) mClosedListener.onClosed(); } } mScrolling = false; } protected int mTouchMode = SlidingMenu.TOUCHMODE_MARGIN; private int mTouchModeBehind = SlidingMenu.TOUCHMODE_MARGIN; public void setTouchMode(int i) { mTouchMode = i; } public int getTouchMode() { return mTouchMode; } protected void setTouchModeBehind(int i) { mTouchModeBehind = i; } protected int getTouchModeBehind() { return mTouchModeBehind; } private boolean thisTouchAllowed(MotionEvent ev) { if (isMenuOpen()) { switch (mTouchModeBehind) { case SlidingMenu.TOUCHMODE_FULLSCREEN: return true; case SlidingMenu.TOUCHMODE_MARGIN: return ev.getX() >= getBehindWidth() && ev.getX() <= getWidth(); default: return false; } } else { switch (mTouchMode) { case SlidingMenu.TOUCHMODE_FULLSCREEN: return true; case SlidingMenu.TOUCHMODE_MARGIN: int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, mSlidingMenuThreshold, getResources().getDisplayMetrics()); return ev.getX() >= 0 && ev.getX() <= pixels; default: return false; } } } private boolean mIsUnableToDrag; @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (!mEnabled) { return false; } final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { mIsBeingDragged = false; mIsUnableToDrag = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } return false; } if (action != MotionEvent.ACTION_DOWN) if (mIsBeingDragged) return true; else if (mIsUnableToDrag) return false; switch (action) { case MotionEvent.ACTION_MOVE: final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) break; final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float dx = x - mLastMotionX; final float xDiff = Math.abs(dx); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); if (xDiff > mTouchSlop && xDiff > yDiff) { Log.v(TAG, "Starting drag! from onInterceptTouch"); mIsBeingDragged = true; mLastMotionX = x; setScrollingCacheEnabled(true); } else { if (yDiff > mTouchSlop) { mIsUnableToDrag = true; } } break; case MotionEvent.ACTION_DOWN: mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mLastMotionX = mInitialMotionX = MotionEventCompat.getX(ev, mActivePointerId); mLastMotionY = MotionEventCompat.getY(ev, mActivePointerId); if (thisTouchAllowed(ev)) { mIsBeingDragged = false; mIsUnableToDrag = false; } if (isMenuOpen() && mInitialMotionX > getBehindWidth()) { Log.v(TAG, "Touch on content when menu open. Intercepting right away"); mIsBeingDragged = false; return true; } break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } if (!mIsBeingDragged) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); } return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { if (!mEnabled) { return false; } if (!mIsBeingDragged && !mLastTouchAllowed && !thisTouchAllowed(ev)) { return false; } final int action = ev.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_OUTSIDE) { mLastTouchAllowed = false; } else { mLastTouchAllowed = true; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ completeScroll(); // Remember where the motion event started mLastMotionX = mInitialMotionX = ev.getX(); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); break; case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float y = MotionEventCompat.getY(ev, pointerIndex); final float yDiff = Math.abs(y - mLastMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (xDiff > mTouchSlop && xDiff > yDiff) { Log.v(TAG, "Starting drag! from onTouch"); mIsBeingDragged = true; mLastMotionX = x; setScrollingCacheEnabled(true); } } if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = MotionEventCompat.findPointerIndex( ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final float deltaX = mLastMotionX - x; mLastMotionX = x; float oldScrollX = getScrollX(); float scrollX = oldScrollX + deltaX; final float leftBound = 0; final float rightBound = getBehindWidth(); if (scrollX < leftBound) { scrollX = leftBound; } else if (scrollX > rightBound) { scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); pageScrolled((int) scrollX); } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); final int widthWithMargin = getChildWidth(mCurItem) + mShadowWidth; final int scrollX = getScrollX(); final int currentPage = scrollX / widthWithMargin; final float pageOffset = (float) (scrollX % widthWithMargin) / widthWithMargin; final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final int totalDelta = (int) (x - mInitialMotionX); int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); mActivePointerId = INVALID_POINTER; endDrag(); } else if (isMenuOpen()) { // close the menu setCurrentItem(1); } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { setCurrentItemInternal(mCurItem, true, true); mActivePointerId = INVALID_POINTER; endDrag(); } break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); final float x = MotionEventCompat.getX(ev, index); mLastMotionX = x; mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } if (mActivePointerId == INVALID_POINTER) mLastTouchAllowed = false; return true; } private float mScrollScale; public float getScrollScale() { return mScrollScale; } public void setScrollScale(float f) { if (f < 0 && f > 1) throw new IllegalStateException("ScrollScale must be between 0 and 1"); mScrollScale = f; } @Override public void scrollTo(int x, int y) { super.scrollTo(x, y); mScrollX = x; if (mCustomViewBehind != null && mEnabled) { mCustomViewBehind.scrollTo((int)(x*mScrollScale), y); } requestLayout(); invalidate(); } private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) { int targetPage; if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { targetPage = velocity > 0 ? currentPage : currentPage + 1; } else { targetPage = (int) (currentPage + pageOffset + 0.5f); } return targetPage; } protected float getPercentOpen() { return (getBehindWidth() - mScrollX) / getBehindWidth(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); final int behindWidth = getBehindWidth(); // Draw the margin drawable if needed. if (mShadowWidth > 0 && mShadowDrawable != null) { final int left = behindWidth - mShadowWidth; mShadowDrawable.setBounds(left, 0, left + mShadowWidth, getHeight()); mShadowDrawable.draw(canvas); } if (mFadeEnabled) onDrawBehindFade(canvas, getPercentOpen()); if (mSelectorEnabled) onDrawMenuSelector(canvas, getPercentOpen()); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } // variables for drawing private float mScrollX = 0.0f; // for the fade private boolean mFadeEnabled; private float mFadeDegree = 1.0f; private final Paint mBehindFadePaint = new Paint(); // for the indicator private boolean mSelectorEnabled = true; private Bitmap mSelectorDrawable; private View mSelectedView; private void onDrawBehindFade(Canvas canvas, float openPercent) { final int alpha = (int) (mFadeDegree * 255 * Math.abs(1-openPercent)); if (alpha > 0) { mBehindFadePaint.setColor(Color.argb(alpha, 0, 0, 0)); canvas.drawRect(0, 0, getBehindWidth(), getHeight(), mBehindFadePaint); } } private void onDrawMenuSelector(Canvas canvas, float openPercent) { if (mSelectorDrawable != null && mSelectedView != null) { String tag = (String) mSelectedView.getTag(R.id.selected_view); if (tag.equals(TAG+"SelectedView")) { int right = getChildLeft(1); int left = (int) (right - mSelectorDrawable.getWidth() * openPercent); canvas.save(); canvas.clipRect(left, 0, right, getHeight()); canvas.drawBitmap(mSelectorDrawable, left, getSelectedTop(), null); canvas.restore(); } } } public void setBehindFadeEnabled(boolean b) { mFadeEnabled = b; } public void setBehindFadeDegree(float f) { if (f > 1.0f || f < 0.0f) throw new IllegalStateException("The BehindFadeDegree must be between 0.0f and 1.0f"); mFadeDegree = f; } public void setSelectorEnabled(boolean b) { mSelectorEnabled = b; } public void setSelectedView(View v) { if (mSelectedView != null) { mSelectedView.setTag(R.id.selected_view, null); mSelectedView = null; } if (v.getParent() != null) { mSelectedView = v; mSelectedView.setTag(R.id.selected_view, TAG+"SelectedView"); invalidate(); } } private int getSelectedTop() { int y = mSelectedView.getTop(); y += (mSelectedView.getHeight() - mSelectorDrawable.getHeight()) / 2; return y; } public void setSelectorDrawable(Bitmap b) { mSelectorDrawable = b; refreshDrawableState(); } private void onSecondaryPointerUp(MotionEvent ev) { if (DEBUG) Log.v(TAG, "onSecondaryPointerUp called"); final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void endDrag() { mIsBeingDragged = false; // mIsUnableToDrag = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void setScrollingCacheEnabled(boolean enabled) { if (mScrollingCacheEnabled != enabled) { mScrollingCacheEnabled = enabled; if (USE_CACHE) { final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(enabled); } } } } } /** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dx, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && ViewCompat.canScrollHorizontally(v, -dx); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (Build.VERSION.SDK_INT >= 11) { // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those devices. if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } } break; } } return handled; } public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; boolean handled = false; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { // If there is nothing to the left, or this is causing us to // jump to the right, then what we really want to do is page left. if (currentFocused != null && nextFocused.getLeft() >= currentFocused.getLeft()) { handled = pageLeft(); } else { handled = nextFocused.requestFocus(); } } else if (direction == View.FOCUS_RIGHT) { // If there is nothing to the right, or this is causing us to // jump to the left, then what we really want to do is page right. if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) { handled = pageRight(); } else { handled = nextFocused.requestFocus(); } } } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { // Trying to move left and nothing there; try to page. handled = pageLeft(); } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { // Trying to move right and nothing there; try to page. handled = pageRight(); } if (handled) { playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); } return handled; } boolean pageLeft() { if (mCurItem > 0) { setCurrentItem(mCurItem-1, true); return true; } return false; } boolean pageRight() { if (mCurItem < 1) { setCurrentItem(mCurItem+1, true); return true; } return false; } }
package org.devocative.adroit.sql.result; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.converters.collections.MapConverter; import java.util.LinkedHashMap; @XStreamConverter(MapConverter.class) public class RowVO extends LinkedHashMap<String, Object> { private static final long serialVersionUID = 8800701053699750620L; }
package de.klimek.scanner; import android.graphics.ImageFormat; import android.graphics.Rect; import android.hardware.Camera; import android.os.AsyncTask; import android.os.Handler; import android.util.Log; import com.google.zxing.MultiFormatReader; class Decoder implements Camera.PreviewCallback { private static final String TAG = Decoder.class.getSimpleName(); private Camera mCamera; private Camera.Size mPreviewSize; private int mCameraDisplayOrientation; private byte[] mPreviewBuffer; private byte[] mPreviewRotationBuffer; private float mReticleFraction; private Rect mBoundingRect; private volatile boolean mDecoding = false; private int mDecodeInterval; private Handler mDelayHandler = new Handler(); private DecodeTask mDecodeTask; private RequestPreviewFrameTask mRequestFrameTask; private MultiFormatReader mMultiFormatReader = new MultiFormatReader(); private OnDecodedCallback mCallback; Decoder(int decodeInterval, float reticleFraction) { mDecodeInterval = decodeInterval; mReticleFraction = reticleFraction; } void setOnDecodedCallback(OnDecodedCallback callback) { mCallback = callback; } void startDecoding(Camera camera, int cameraDisplayOrientation) { mDecoding = true; mCamera = camera; mCameraDisplayOrientation = cameraDisplayOrientation; mPreviewSize = camera.getParameters().getPreviewSize(); mBoundingRect = getBoundingRect(mPreviewSize, mReticleFraction); // add buffer to camera to prevent garbage collection spam mPreviewBuffer = createPreviewBuffer(mPreviewSize); // temp buffer to allow manipulating/rotating the first buffer mPreviewRotationBuffer = new byte[mPreviewBuffer.length]; camera.setPreviewCallbackWithBuffer(this); requestNextFrame(0); } void stopDecoding() { mDecoding = false; if (mRequestFrameTask != null) { mDelayHandler.removeCallbacks(mRequestFrameTask); } if (mDecodeTask != null) { mDecodeTask.cancel(true); } } private static Rect getBoundingRect(Camera.Size previewSize, double fraction) { int height = (int) (previewSize.height * fraction); int width = (int) (previewSize.width * fraction); int reticleDim = Math.min(height, width); int left = (previewSize.width - reticleDim) / 2; int top = (previewSize.height - reticleDim) / 2; int right = left + reticleDim; int bottom = top + reticleDim; return new Rect(left, top, right, bottom); } private static byte[] createPreviewBuffer(Camera.Size mPreviewSize) { int width = mPreviewSize.width; int height = mPreviewSize.height; int bitsPerPixel = ImageFormat.getBitsPerPixel(ImageFormat.NV21); // default camera format int sizeInBits = width * height * bitsPerPixel; int sizeInBytes = (int) Math.ceil((float) sizeInBits / Byte.SIZE); return new byte[sizeInBytes]; } /* * Called when the camera has a buffer, e.g. by calling * camera.addCallbackBuffer(buffer). This buffer is automatically removed, * but added again after decoding, resulting in a loop until stopDecoding() * is called. The data is not affected by Camera#setDisplayOrientation(), * so it may be rotated. */ @Override public void onPreviewFrame(byte[] data, Camera camera) { if (mDecoding) { mDecodeTask = new DecodeTask(this, mPreviewSize, mCameraDisplayOrientation, mBoundingRect, mMultiFormatReader, mPreviewRotationBuffer); mDecodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, data); } } /* * Called by mDecodeTask */ void onDecodeSuccess(String string) { Log.i(Decoder.TAG, "Decode success."); if (mDecoding) { mCallback.onDecoded(string); requestNextFrame(mDecodeInterval); } } /* * Called by mDecodeTask */ void onDecodeFail() { // Log.i(Decoder.TAG, "Decode fail."); if (mDecoding) { requestNextFrame(mDecodeInterval); } } private void requestNextFrame(int delay) { if (mRequestFrameTask != null) { mDelayHandler.removeCallbacks(mRequestFrameTask); } mRequestFrameTask = new RequestPreviewFrameTask(); mDelayHandler.postDelayed(mRequestFrameTask, delay); } private class RequestPreviewFrameTask implements Runnable { @Override public void run() { if (mDecoding) { // adding in other thread is okay as onPreviewFrame will be called on main thread mCamera.addCallbackBuffer(mPreviewBuffer); } } } }
package org.lightmare.deploy; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.lightmare.cache.MetaContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Manager class for application deployment * * @author levan * */ public class LoaderPoolManager { // Amount of deployment thread pool private static final int LOADER_POOL_SIZE = 5; // Name prefix of deployment threads private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-"; // Lock for pool reopening private static final Lock LOCK = new ReentrantLock(); /** * Gets class loader for existing {@link org.lightmare.deploy.MetaCreator} * instance * * @return {@link ClassLoader} */ protected static ClassLoader getCurrent() { ClassLoader current; MetaCreator creator = MetaContainer.getCreator(); ClassLoader creatorLoader; if (ObjectUtils.notNull(creator)) { // Gets class loader for this deployment creatorLoader = creator.getCurrent(); if (ObjectUtils.notNull(creatorLoader)) { current = creatorLoader; } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } return current; } /** * Implementation of {@link ThreadFactory} interface for application loading * * @author levan * */ private static final class LoaderThreadFactory implements ThreadFactory { /** * Constructs and sets thread name * * @param thread */ private void nameThread(Thread thread) { String name = StringUtils .concat(LOADER_THREAD_NAME, thread.getId()); thread.setName(name); } /** * Sets priority of {@link Thread} instance * * @param thread */ private void setPriority(Thread thread) { thread.setPriority(Thread.MAX_PRIORITY); } /** * Sets {@link ClassLoader} to passed {@link Thread} instance * * @param thread */ private void setContextClassLoader(Thread thread) { ClassLoader parent = getCurrent(); thread.setContextClassLoader(parent); } /** * Configures (sets name, priority and {@link ClassLoader}) passed * {@link Thread} instance * * @param thread */ private void configureThread(Thread thread) { nameThread(thread); setPriority(thread); setContextClassLoader(thread); } @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); configureThread(thread); return thread; } } // Thread pool for deploying and removal of beans and temporal resources private static ExecutorService LOADER_POOL; /** * Checks if loader {@link ExecutorService} is null or is shut down or is * terminated * * @return <code>boolean</code> */ private static boolean invalid() { return LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL.isTerminated(); } /** * Checks and if not valid reopens deploy {@link ExecutorService} instance * * @return {@link ExecutorService} */ protected static ExecutorService getLoaderPool() { if (invalid()) { LOCK.lock(); try { if (invalid()) { LOADER_POOL = Executors.newFixedThreadPool( LOADER_POOL_SIZE, new LoaderThreadFactory()); } } finally { LOCK.unlock(); } } return LOADER_POOL; } /** * Submit passed {@link Runnable} implementation in loader pool * * @param runnable */ public static void submit(Runnable runnable) { getLoaderPool().submit(runnable); } /** * Submits passed {@link Callable} implementation in loader pool * * @param callable * @return {@link Future}<code><T></code> */ public static <T> Future<T> submit(Callable<T> callable) { Future<T> future = getLoaderPool().submit(callable); return future; } /** * Clears existing {@link ExecutorService}s from loader threads */ public static void reload() { boolean locked = LOCK.tryLock(); while (ObjectUtils.notTrue(locked)) { try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } locked = LOCK.tryLock(); } try { if (locked) { if (ObjectUtils.notNull(LOADER_POOL)) { LOADER_POOL.shutdown(); LOADER_POOL = null; } } } finally { LOCK.unlock(); } getLoaderPool(); } }
package org.lightmare.deploy; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import org.lightmare.cache.MetaContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Manager class for application deployment * * @author levan * */ public class LoaderPoolManager { // Amount of deployment thread pool private static final int LOADER_POOL_SIZE = 5; // Name prefix of deployment threads private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-"; /** * Gets class loader for existing {@link org.lightmare.deploy.MetaCreator} * instance * * @return {@link ClassLoader} */ protected static ClassLoader getCurrent() { ClassLoader current; MetaCreator creator = MetaContainer.getCreator(); ClassLoader creatorLoader; if (ObjectUtils.notNull(creator)) { // Gets class loader for this deployment creatorLoader = creator.getCurrent(); if (ObjectUtils.notNull(creatorLoader)) { current = creatorLoader; } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } return current; } /** * Implementation of {@link ThreadFactory} interface for application loading * * @author levan * */ private static final class LoaderThreadFactory implements ThreadFactory { /** * Constructs and sets thread name * * @param thread */ private void nameThread(Thread thread) { String name = StringUtils .concat(LOADER_THREAD_NAME, thread.getId()); thread.setName(name); } /** * Sets priority of {@link Thread} instance * * @param thread */ private void setPriority(Thread thread) { thread.setPriority(Thread.MAX_PRIORITY); } /** * Sets {@link ClassLoader} to passed {@link Thread} instance * * @param thread */ private void setContextClassLoader(Thread thread) { ClassLoader parent = getCurrent(); thread.setContextClassLoader(parent); } /** * Configures (sets name, priority and {@link ClassLoader}) passed * {@link Thread} instance * * @param thread */ private void configureThread(Thread thread) { nameThread(thread); setPriority(thread); setContextClassLoader(thread); } @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); configureThread(thread); return thread; } } // Thread pool for deploying and removal of beans and temporal resources private static ExecutorService LOADER_POOL = Executors.newFixedThreadPool( LOADER_POOL_SIZE, new LoaderThreadFactory()); /** * Checks if loader {@link ExecutorService} is null or is shut down or is * terminated * * @return <code>boolean</code> */ private static boolean invalid() { return LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL.isTerminated(); } /** * Checks and if not valid reopens deploy {@link ExecutorService} instance * * @return {@link ExecutorService} */ protected static ExecutorService getLoaderPool() { if (invalid()) { synchronized (LoaderPoolManager.class) { if (invalid()) { LOADER_POOL = Executors.newFixedThreadPool( LOADER_POOL_SIZE, new LoaderThreadFactory()); } } } return LOADER_POOL; } /** * Submit passed {@link Runnable} implementation in loader pool * * @param runnable */ public static void submit(Runnable runnable) { getLoaderPool().submit(runnable); } /** * Submits passed {@link Callable} implementation in loader pool * * @param callable * @return {@link Future}<code><T></code> */ public static <T> Future<T> submit(Callable<T> callable) { Future<T> future = getLoaderPool().submit(callable); return future; } /** * Clears existing {@link ExecutorService}s from loader threads */ public static void reload() { synchronized (LoaderPoolManager.class) { if (ObjectUtils.notNull(LOADER_POOL)) { LOADER_POOL.shutdown(); LOADER_POOL = null; } } getLoaderPool(); } }
package org.lightmare.deploy; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.lightmare.cache.MetaContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Manager class for application deployment * * @author levan * */ public class LoaderPoolManager { // Amount of deployment thread pool private static final int LOADER_POOL_SIZE = 5; // Name prefix of deployment threads private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-"; // Lock for pool reopening private static final Lock LOCK = new ReentrantLock(); /** * Gets class loader for existing {@link org.lightmare.deploy.MetaCreator} * instance * * @return {@link ClassLoader} */ protected static ClassLoader getCurrent() { ClassLoader current; MetaCreator creator = MetaContainer.getCreator(); ClassLoader creatorLoader; if (ObjectUtils.notNull(creator)) { // Gets class loader for this deployment creatorLoader = creator.getCurrent(); if (ObjectUtils.notNull(creatorLoader)) { current = creatorLoader; } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } return current; } /** * Implementation of {@link ThreadFactory} interface for application loading * * @author levan * */ private static final class LoaderThreadFactory implements ThreadFactory { /** * Constructs and sets thread name * * @param thread */ private void nameThread(Thread thread) { String name = StringUtils .concat(LOADER_THREAD_NAME, thread.getId()); thread.setName(name); } /** * Sets priority of {@link Thread} instance * * @param thread */ private void setPriority(Thread thread) { thread.setPriority(Thread.MAX_PRIORITY); } /** * Sets {@link ClassLoader} to passed {@link Thread} instance * * @param thread */ private void setContextClassLoader(Thread thread) { ClassLoader parent = getCurrent(); thread.setContextClassLoader(parent); } /** * Configures (sets name, priority and {@link ClassLoader}) passed * {@link Thread} instance * * @param thread */ private void configureThread(Thread thread) { nameThread(thread); setPriority(thread); setContextClassLoader(thread); } @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); configureThread(thread); return thread; } } // Thread pool for deploying and removal of beans and temporal resources private static ExecutorService LOADER_POOL; /** * Checks if loader {@link ExecutorService} is null or is shut down or is * terminated * * @return <code>boolean</code> */ private static boolean invalid() { return LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL.isTerminated(); } /** * Checks and if not valid reopens deploy {@link ExecutorService} instance * * @return {@link ExecutorService} */ protected static ExecutorService getLoaderPool() { if (invalid()) { LOCK.lock(); try { if (invalid()) { LOADER_POOL = Executors.newFixedThreadPool( LOADER_POOL_SIZE, new LoaderThreadFactory()); } } finally { LOCK.unlock(); } } return LOADER_POOL; } /** * Submit passed {@link Runnable} implementation in loader pool * * @param runnable */ public static void submit(Runnable runnable) { getLoaderPool().submit(runnable); } /** * Submits passed {@link Callable} implementation in loader pool * * @param callable * @return {@link Future}<code><T></code> */ public static <T> Future<T> submit(Callable<T> callable) { Future<T> future = getLoaderPool().submit(callable); return future; } /** * Clears existing {@link ExecutorService}s from loader threads */ public static void reload() { synchronized (LoaderPoolManager.class) { if (ObjectUtils.notNull(LOADER_POOL)) { LOADER_POOL.shutdown(); LOADER_POOL = null; } } getLoaderPool(); } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionHolder; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { // Error messages for inappropriate use of user transactions private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ protected static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(entityTransactions); TransactionHolder.setTransaction(transaction); } else { // If entityTransactions array is available then adds it to // UserTransaction object UserTransactionFactory.join(transaction, entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(); TransactionHolder.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not begins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (ObjectUtils.notTrue(entityTransaction.isActive())) { entityTransaction.begin(); } } /** * Gets {@link EntityTransaction} from passed {@link EntityManager} and * begins it * * @param em * @return {@link EntityTransaction} */ private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } /** * Gets {@link EntityTransaction} for each {@link EntityManager} and begins * it * * @param ems * @return {@link Collection}<EntityTransaction> */ private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions; if (CollectionUtils.valid(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } else { entityTransactions = null; } return entityTransactions; } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransaction transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; TransactionManager.addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { TransactionManager.addEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == UserTransactionFactory.INSACTIVE_TRANSACTION_STATE) { TransactionManager.addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } } finally { TransactionManager.addEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { try { throw new NotYetImplementedException(SUPPORTS_ERROR); } finally { TransactionManager.addEntityManagers(transaction, ems); } } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { TransactionAttributeType type; MetaData metaData = handler.getMetaData(); type = getTransactionType(metaData, method); UserTransaction transaction = getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { TransactionManager.addEntityManagers(transaction, ems); } return type; } /** * Rollbacks passed {@link UserTransaction} by * {@link TransactionAttributeType} distinguishes only * {@link TransactionAttributeType#REQUIRES_NEW} case or uses standard * rollback for all other * * @param type * @param handler * @throws IOException */ private static void rollbackTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.rollbackReqNew(transaction); } else { TransactionManager.rollback(transaction); } } /** * Decides which rollback method to call of {@link UserTransaction} * implementation by {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { rollbackTransaction(type, handler); } else { closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ private static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = TransactionManager .checkCaller(transaction, handler); if (check) { TransactionManager.commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.commitReqNew(transaction); } else { TransactionManager.closeEntityManagers(transaction); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method call */ public static void closeEntityManagers() { UserTransaction transaction = getTransaction(); TransactionManager.closeEntityManagers(transaction); } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransaction transaction = getTransaction(); boolean check = TransactionManager.checkCaller(transaction, handler); if (check) { TransactionHolder.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in EJB injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { TransactionHolder.removeTransaction(); } } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionContainer; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ private static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionContainer.getTransaction(); if (transaction == null) { transaction = new UserTransactionImpl(entityTransactions); TransactionContainer.setTransaction(transaction); } // If entityTransactions array is available then adds it to // UserTransaction object if (ObjectUtils.available(entityTransactions)) { ((UserTransactionImpl) transaction) .addTransactions(entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionContainer.getTransaction(); if (transaction == null) { transaction = new UserTransactionImpl(); TransactionContainer.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); addEntityTransactions((UserTransactionImpl) transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not vegins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (!entityTransaction.isActive()) { entityTransaction.begin(); } } private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions = null; if (ObjectUtils.available(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } return entityTransactions; } private static void addEntityTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.addTransaction(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (ObjectUtils.available(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addEntityTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addEntityManager(UserTransactionImpl transaction, EntityManager em) { if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityManagers(UserTransactionImpl transaction, Collection<EntityManager> ems) { if (ObjectUtils.available(ems)) { for (EntityManager em : ems) { addEntityManager(transaction, em); } } } private static void addReqNewTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.pushReqNew(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.pushReqNewEm(em); } } private static void addReqNewTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (ObjectUtils.available(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addReqNewTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addCaller(UserTransactionImpl transaction, BeanHandler handler) { Object caller = transaction.getCaller(); if (caller == null) { transaction.setCaller(handler); } } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransactionImpl transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { addEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == 0) { addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } } finally { addEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { try { throw new NotYetImplementedException(SUPPORTS_ERROR); } finally { addEntityManagers(transaction, ems); } } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { MetaData metaData = handler.getMetaData(); TransactionAttributeType type = getTransactionType(metaData, method); UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { addEntityManagers(transaction, ems); } return type; } /** * Commits passed {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commit(UserTransaction transaction) throws IOException { try { transaction.commit(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Commits all {@link TransactionAttributeType.REQUIRES_NEW} transactions * for passed {@link UserTransactionImpl} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commitReqNew(UserTransactionImpl transaction) throws IOException { try { transaction.commitReqNew(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Calls {@link UserTransaction#rollback()} method of passed * {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void rollback(UserTransaction transaction) throws IOException { try { transaction.rollback(); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Decides whether rollback or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); try { if (ObjectUtils.notNull(type)) { rollback(transaction); } else { transaction.closeEntityManagers(); } } catch (IOException ex) { transaction.closeEntityManagers(); throw ex; } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ public static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = transaction.checkCaller(handler); if (check) { commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { commitReqNew(transaction); } else { transaction.closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method calll */ public static void closeEntityManagers() { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); transaction.closeEntityManagers(); } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); boolean check = transaction.checkCaller(handler); if (check) { TransactionContainer.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in ejb injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { TransactionContainer.removeTransaction(); } } }
package org.lightmare.utils.fs.codecs; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Collections; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.lightmare.jpa.ConfigLoader; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.lightmare.utils.fs.FileType; /** * Implementation of {@link ArchiveUtils} for jar files * * @author levan * @since 0.0.81-SNAPSHOT */ public class JarUtils extends ArchiveUtils { public static final FileType type = FileType.JAR; public JarUtils(String path) { super(path); } public JarUtils(File file) { super(file); } public JarUtils(URL url) throws IOException { super(url); } @Override public FileType getType() { return type; } @Override public InputStream earReader() throws IOException { return null; } @Override public void getEjbLibs() throws IOException { } @Override public void extractEjbJars(Set<String> jarNames) throws IOException { URL currentURL = realFile.toURI().toURL(); getEjbURLs().add(currentURL); boolean checkOnOrm = checkOnOrm(path); if (xmlFromJar && checkOnOrm) { String xmlPath = StringUtils.concat(currentURL.toString(), ARCHIVE_URL_DELIM, ConfigLoader.XML_PATH); URL xmlURL = new URL(JAR, StringUtils.EMPTY_STRING, xmlPath); getXmlFiles().put(realFile.getName(), xmlURL); getXmlURLs().put(currentURL, xmlURL); } } @Override public boolean checkOnOrm(String jarName) throws IOException { ZipFile zipFile = getEarFile(); ZipEntry xmlEntry = zipFile.getEntry(ConfigLoader.XML_PATH); return ObjectUtils.notNull(xmlEntry); } @Override protected void scanArchive(Object... args) throws IOException { if (CollectionUtils.valid(args)) { xmlFromJar = (Boolean) CollectionUtils.getFirst(args); } extractEjbJars(Collections.<String> emptySet()); } }
package simcity.Transportation; import java.util.List; import simcity.Market.MFoodOrder; import simcity.Transportation.CarAgent.carState; import simcity.interfaces.Car; import simcity.interfaces.Cook; import simcity.interfaces.DeliveryTruck; import simcity.interfaces.MarketCashier; import simcity.interfaces.MarketManager; import simcity.interfaces.Person; import simcity.test.mock.EventLog; import simcity.test.mock.LoggedEvent; import agent.Agent; import agent.Role; public class DeliveryTruckAgent extends Agent implements DeliveryTruck{ // public Person driver; public String destination; public List<MFoodOrder> supply; public Cook cook; public double check; public MarketManager manager; public MarketCashier mc; public EventLog log; public enum truckState {available, parked, receivedLocation, travelling, arrived}; public truckState state; public DeliveryTruckAgent(MarketManager m){ log = new EventLog(); manager = m; mc = null; cook = null; supply = null; destination = null; check = 0; state = truckState.available; } //Messages public void msgRestaurantClosed(){ //cannot deliver order must wait for the restaurant to open back up //check with a time stamp to try and deliver again in 10 hours? or constantly ask rest if they are back open or idk //note deliver was unsuccessful } public void msgGoToDestination(MarketCashier cashier, List<MFoodOrder>deliver, String location, double bill, Cook c) { mc = cashier; supply = deliver; destination = location; state = truckState.receivedLocation; cook = c; check = bill; stateChanged(); } @Override public void msgAtDestination() { state = truckState.arrived; stateChanged(); } //SCHEDULER public boolean pickAndExecuteAnAction(){ if(state==truckState.receivedLocation){ goToLocation(); return true; } Do("state is " + state); if(state==truckState.arrived){ HaveArrived(); state=truckState.parked; return true; } Do("here"); return false; } //Actions private void goToLocation(){ state=truckState.travelling; LoggedEvent e = new LoggedEvent("Going to destination"); log.add(e); Do("Go To Location"); state = truckState.arrived; //animation using destination } private void HaveArrived(){ LoggedEvent e = new LoggedEvent("Arrived at destination"); log.add(e); Do("Arrived at destination"); cook.msgHereIsDelivery(supply, check, manager, mc); //animation to go home manager.msgBackFromDelivery(); state = truckState.available; } }
package sk.feromakovi.ldatrainer.utils; import japa.parser.JavaParser; import japa.parser.ast.CompilationUnit; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Paths; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import uk.ac.open.crc.intt.IdentifierNameTokeniser; import uk.ac.open.crc.intt.IdentifierNameTokeniserFactory; import com.google.common.base.Charsets; import com.google.common.io.Files; public final class SourceCode { static Pattern mPackagePattern = Pattern.compile("package (.*?);"); public static final CompilationUnit parse(final File file){ CompilationUnit cu = null; try{ cu = JavaParser.parse(new FileInputStream(file)); return cu; }catch(Exception e){} return null; } public static final String representationOf(final String delimiter, final String... strings){ StringBuilder builder = new StringBuilder(); for(int i = 0; i < strings.length; i++){ builder.append(strings[i]); if(i < (strings.length -1)) builder.append(delimiter); } return builder.toString(); } public static final String[] tokenize(final File sourceFile){ String[] tokens = new String[0]; try { tokens = tokenize(Files.toString(sourceFile, Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); } return tokens; } public static final String extractPackage(final File sourceFile){ String extractedPackage = null; try { extractedPackage = extractPackage(Files.toString(sourceFile, Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); } return extractedPackage; } public static final String extractPackage(final String text){ Matcher matcher = mPackagePattern.matcher(text); if(matcher.find()) return matcher.group(1); return null; }
package som.primitives.arithmetic; import java.math.BigInteger; import com.oracle.truffle.api.ExactMath; import com.oracle.truffle.api.dsl.Specialization; public abstract class SubtractionPrim extends ArithmeticPrim { @Specialization(rewriteOn = ArithmeticException.class) public final long doLong(final long left, final long right) { return ExactMath.subtractExact(left, right); } @Specialization public final BigInteger doLongWithOverflow(final long left, final long right) { return BigInteger.valueOf(left).subtract(BigInteger.valueOf(right)); } @Specialization public final Object doBigInteger(final BigInteger left, final BigInteger right) { BigInteger result = left.subtract(right); return reduceToLongIfPossible(result); } @Specialization public final double doDouble(final double left, final double right) { return left - right; } @Specialization public final Object doLong(final long left, final BigInteger right) { return doBigInteger(BigInteger.valueOf(left), right); } @Specialization public final double doLong(final long left, final double right) { return doDouble(left, right); } @Specialization public final Object doBigInteger(final BigInteger left, final long right) { return doBigInteger(left, BigInteger.valueOf(right)); } @Specialization public final double doDouble(final double left, final long right) { return doDouble(left, (double) right); } }
package com.github.sormuras.listing; import static com.github.sormuras.listing.Compilation.compile; import static com.github.sormuras.listing.Name.of; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.expectThrows; import java.lang.annotation.ElementType; import java.util.Optional; import javax.lang.model.element.Modifier; import org.junit.jupiter.api.Test; class NameTest { @Test void apply() { assertEquals("byte", of(byte.class).apply(new Listing()).toString()); } @Test void enclosed() { assertEquals(false, of(byte.class).isEnclosed()); assertEquals(false, of(Object.class).isEnclosed()); assertEquals(false, of(Thread.class).isEnclosed()); assertEquals(true, of(Thread.State.class).isEnclosed()); } @Test void enclosing() { assertEquals(Optional.empty(), of(byte.class).getEnclosing()); assertEquals(Optional.empty(), of(Object.class).getEnclosing()); assertEquals(Optional.empty(), of(Thread.class).getEnclosing()); assertEquals(of(Thread.class), of(Thread.State.class).getEnclosing().get()); } @Test void equalsAndHashcode() { assertEquals(of(byte.class), of("", "byte")); assertEquals(of(Object.class), of("java.lang", "Object")); assertEquals(of(Thread.class), of("java.lang", "Thread")); assertEquals(of(Thread.State.class), of("java.lang", "Thread", "State")); // single instance Name integer = of(int.class); assertEquals(integer, integer); // falsify assertFalse(of(byte.class).equals(null)); assertFalse(of(byte.class).equals(byte.class)); assertFalse(of(byte.class).equals(of("a", "byte"))); } @Test void simpleNamesJoined() { assertEquals("Object", simpleNamesJoined(of(Object.class))); assertEquals("byte", simpleNamesJoined(of(byte.class))); assertEquals("Object[]", simpleNamesJoined(of(Object[].class))); assertEquals("Object[][]", simpleNamesJoined(of(Object[][].class))); assertEquals(Name.class.getSimpleName(), simpleNamesJoined(of(Name.class))); assertEquals("Character.Subset", simpleNamesJoined(of(Character.Subset.class))); assertEquals("Thread.State", simpleNamesJoined(of(Thread.State.class))); } private String simpleNamesJoined(Name name) { return String.join(".", name.getSimpleNames()); } @Test void packageName() { assertEquals("", of("", "Empty").getPackageName()); assertEquals("", of(compile("public class Nopack {}")).getPackageName()); } @Test void invalidIdentifier() { Exception e = expectThrows(IllegalArgumentException.class, () -> of()); assertTrue(e.toString().contains("non-empty names array expected")); } @Test void invalidIdentifierName() { Exception e = expectThrows(IllegalArgumentException.class, () -> of("test", "123")); assertTrue(e.toString().contains("123")); } @Test void isJavaLangObject() throws Exception { assertEquals(true, of(Object.class).isJavaLangObject()); assertEquals(false, of(Optional.class).isJavaLangObject()); assertEquals(false, of("", "A").isJavaLangObject()); } @Test void isJavaLangPackage() throws Exception { assertEquals(true, of(Object.class).isJavaLangPackage()); assertEquals(false, of(Optional.class).isJavaLangPackage()); assertEquals(false, of("", "A").isJavaLangPackage()); } @Test void modified() throws Exception { assertTrue(of(Object.class).isModified()); // public assertTrue(of(Thread.State.NEW).isModified()); // public static final Name name = of(getClass().getDeclaredMethod("modified")); assertFalse(name.isModified()); // <empty> name.addModifier(Modifier.SYNCHRONIZED); assertTrue(name.isModified()); // synchronized expectThrows(IllegalArgumentException.class, () -> of("", "A").addModifier(null)); } @Test void isStatic() throws Exception { assertEquals(false, of(Object.class).isStatic()); assertEquals(false, of(Object.class.getDeclaredConstructor()).isStatic()); assertEquals(false, of(Object.class.getDeclaredMethod("toString")).isStatic()); assertEquals(true, of(Object.class.getDeclaredMethod("registerNatives")).isStatic()); assertEquals(false, of(Object.class.getDeclaredMethod("clone")).isStatic()); assertEquals(false, of(Thread.class.getDeclaredMethod("start")).isStatic()); assertEquals(true, of(Math.class.getDeclaredField("PI")).isStatic()); assertEquals(false, of(byte.class).isStatic()); assertEquals(true, of(Character.Subset.class).isStatic()); assertEquals(true, of(Thread.State.class).isStatic()); assertEquals(true, of(Thread.State.NEW).isStatic()); } @Test void list() { assertEquals("a.b.X", of("a.b", "X").list()); } @Test void target() { assertEquals(ElementType.PACKAGE, of("a.b").getTarget().get()); assertEquals(ElementType.TYPE, of("a.b", "X").getTarget().get()); assertEquals(false, of("a.b", "X", "member").getTarget().isPresent()); assertEquals(ElementType.TYPE, of(Object.class).getTarget().get()); assertEquals(ElementType.TYPE, of(byte.class).getTarget().get()); assertEquals(ElementType.TYPE, of(Object[].class).getTarget().get()); assertEquals(ElementType.TYPE, of(Object[][].class).getTarget().get()); assertEquals(ElementType.TYPE, of(Name.class).getTarget().get()); assertEquals(ElementType.TYPE, of(Character.Subset.class).getTarget().get()); assertEquals(ElementType.TYPE, of(Thread.State.class).getTarget().get()); assertEquals(ElementType.FIELD, of(Thread.State.NEW).getTarget().get()); } @Test void testToString() { assertEquals("Name{a.b.X, target=Optional[TYPE], modifiers=[]}", of("a.b", "X").toString()); testToString(of(Object.class), "java.lang.Object", "public"); testToString(of(byte.class), "byte", "public, abstract, final"); testToString(of(Object[].class), "Object[]", "public, abstract, final"); testToString(of(Object[][].class), "Object[][]", "public, abstract, final"); testToString(of(Name.class), Name.class.getCanonicalName(), "public"); testToString(of(Character.Subset.class), "java.lang.Character.Subset", "public, static"); testToString(of(Thread.State.class), "java.lang.Thread.State", "public, static, final"); testToString( of(Thread.State.NEW), "java.lang.Thread.State.NEW", ElementType.FIELD, "public, static, final"); // TODO testToString(of(new ClassDeclaration().setName("Abc")), "Abc", ""); // TODO testToString(of(new JavaUnit("abc").declareClass("Abc")), "abc.Abc", ""); } private void testToString(Name name, String canonical, String modifiers) { testToString(name, canonical, ElementType.TYPE, modifiers); } private void testToString(Name name, String canonical, ElementType type, String modifiers) { assertEquals( "Name{" + canonical + ", target=Optional[" + type + "], modifiers=[" + modifiers + "]}", name.toString()); } }
package com.maxplus1.test.hbase; import com.maxplus1.hd_client.hbase.operations.HbaseAdmin; import com.maxplus1.hd_client.hbase.operations.PageInfo; import com.maxplus1.hd_client.hbase.operations.client.rtn_pojo.HbaseClient; import com.maxplus1.test.pojo.User; import com.maxplus1.test.base.BaseTest; import com.maxplus1.test.model.OrmModel; import com.maxplus1.test.utils.JacksonUtils; import lombok.extern.slf4j.Slf4j; import org.apache.hadoop.hbase.HTableDescriptor; import org.junit.Assert; import org.junit.Test; import javax.annotation.Resource; import java.util.List; import java.util.Random; /** * * 1HbaseAdminlistTables createTable deleteTable * 2HbaseClientput delete putList findListByPage deleteList */ @Slf4j public class OrmTest extends BaseTest{ @Resource private HbaseClient client; @Resource private HbaseAdmin admin; /** * TODO Fusion Insight HD junit testResult result = table.get(get); * webspring test * What the fuck! */ @Test public void test() { HTableDescriptor[] hTableDescriptors = admin.listTables(); for (HTableDescriptor hTableDescriptor : hTableDescriptors) { if(hTableDescriptor.getTableName().getNameAsString().equals("test:user")){ //delete table admin.deleteTable("test:user"); log.info("delete table :{}","test:user"); } } //create table admin.createTable("test:user","info"); log.info("create table :{},column family :{}","test:user","info"); //insert a new user User user = OrmModel.buildUser(); client.put(user); log.info("insert {}:{}", user.getUserName(),JacksonUtils.obj2Json(user)); //find user User findUser = client.find(user.getUuid(), User.class); log.info("find {}:{}",user.getUserName(),JacksonUtils.obj2Json(findUser)); Assert.assertEquals(user,findUser); //delete user client.delete(user.getUuid(),User.class); log.info("delete {}:{}",user.getUserName(),JacksonUtils.obj2Json(findUser)); Assert.assertEquals(null,client.find(user.getUuid(), User.class)); //insert user list List<User> userList = OrmModel.buildUsers(); client.putList(userList); log.info("insert {} user list success!",userList.size()); // find list List<String> rowKeyList = OrmModel.getRowkeyList(userList); List<User> findUserList = client.findList(rowKeyList, User.class); log.info("findUserList,size is {}",findUserList.size()); Assert.assertEquals(userList.size(),findUserList.size()); //scan user OrmModel.sortList(rowKeyList); String startRow = rowKeyList.get(0); String endRow = rowKeyList.get(rowKeyList.size()-1); List<User> scanUserList = client.findList(startRow, endRow, User.class); log.info("scan list,size is {}",scanUserList.size()); Assert.assertEquals(userList.size(),scanUserList.size()+1);//exclude // scan by page PageInfo<User> pageInfo = new PageInfo<>(User.class); pageInfo.setPageSize(10); pageInfo.setStartRow(startRow); pageInfo.setStopRow(endRow); PageInfo<User> scanPage = client.findListByPage(pageInfo); log.info("scan by page,size is {}",scanPage.getDataSet().size()); Assert.assertEquals(10,scanPage.getDataSet().size()); Assert.assertEquals(startRow,scanPage.getDataSet().get(0).getUuid()); Assert.assertEquals(rowKeyList.get(9),scanPage.getDataSet().get(9).getUuid()); Random random = new Random(); //TODO for(int i=0;i<500;i++){ boolean flag = random.nextBoolean(); if(flag&&pageInfo.getCurrentPage()>1){ pageInfo.setPrePageNo(pageInfo.getCurrentPage()); pageInfo.setCurrentPage(pageInfo.getCurrentPage()-1); PageInfo<User> scanLastPage = client.findListByPage(pageInfo); log.info("last page is {},size is {}",scanLastPage.getCurrentPage(),scanLastPage.getDataSet().size()); Assert.assertEquals(10,scanLastPage.getDataSet().size()); Assert.assertEquals(rowKeyList.subList((pageInfo.getCurrentPage()-1)*10,pageInfo.getCurrentPage()*10),OrmModel.getAllUUid(scanLastPage.getDataSet())); }else if(!flag&&pageInfo.getCurrentPage()<5){ pageInfo.setPrePageNo(pageInfo.getCurrentPage()); pageInfo.setCurrentPage(pageInfo.getCurrentPage()+1); PageInfo<User> scanNextPage = client.findListByPage(pageInfo); log.info("next page is {},size is {}",scanNextPage.getCurrentPage(),scanNextPage.getDataSet().size()); Assert.assertEquals(10,scanNextPage.getDataSet().size()); Assert.assertEquals(rowKeyList.subList((pageInfo.getCurrentPage()-1)*10,pageInfo.getCurrentPage()*10),OrmModel.getAllUUid(scanNextPage.getDataSet())); }else{ log.info("nothing to do!"); i } } log.info("findList by prerowkey starts!"); User preUser1 = new User("abcdefg1","test1",1); User preUser2 = new User("abcdefg2","test2",2); User preUser3= new User("abcdefg3","test3",3); client.put(preUser1); client.put(preUser2); client.put(preUser3); List<User> preUserList = client.findList("abcdefg", User.class); Assert.assertEquals(preUserList.size(),3); Assert.assertTrue(preUserList.contains(preUser1)); Assert.assertTrue(preUserList.contains(preUser2)); Assert.assertTrue(preUserList.contains(preUser3)); log.info("findList by prerowkey ends!"); // delete list client.deleteList(rowKeyList,User.class); log.info("deleteList,size is {}",rowKeyList.size()); //delete table admin.deleteTable("test:user"); log.info("delete table :{}","test:user"); } }
package com.nerodesk.om.mock; import java.io.File; import org.apache.commons.io.IOUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Tests for {@code MkDocs}. * @author Yuriy Alevohin (alevohin@mail.ru) * @version $Id$ * @since 0.2 */ public final class MkDocsTest { /** * Temporary folder. * @checkstyle VisibilityModifierCheck (5 lines) */ @Rule public final transient TemporaryFolder temp = new TemporaryFolder(); /** * MkDocs can return a list of docs. * @throws Exception If fails. * @todo 90:30min MkDocs creates files in directory * `new File(this.dir, this.user)` (see MkDoc). Method `names` * receives file's list from another directory (just dir). Don't * forget remove @Ignore after fix. */ @Test @Ignore public void returnsNames() throws Exception { final String[] files = new String[] {"a.txt", "b.txt"}; final File root = this.temp.newFolder(); final MkDocs docs = new MkDocs(root, "user1"); for (final String file : files) { docs.doc(file).write(IOUtils.toInputStream("content1")); } MatcherAssert.assertThat( docs.names(), Matchers.contains(files) ); } /** * MkDocs can return existed Doc. * @throws Exception If fails. */ @Test public void returnsExistedDoc() throws Exception { final File root = this.temp.newFolder(); final MkDocs docs = new MkDocs(root, "user2"); final String filename = "test2"; docs.doc(filename).write(IOUtils.toInputStream("content2")); MatcherAssert.assertThat( docs.doc(filename).exists(), Matchers.is(true) ); } }
package core.time; import org.junit.Test; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.format.DateTimeFormatter; import java.util.Locale; import static org.junit.Assert.assertEquals; public class DateTimeFormatterTest { @Test public void formatDate() { DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; LocalDate date = LocalDate.of(2015, Month.OCTOBER, 30); // Format date from formatter or from date assertEquals(formatter.format(date), "2015-10-30"); assertEquals(date.format(formatter), "2015-10-30"); } @Test public void formatTime() { DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; LocalTime time = LocalTime.of(10, 30, 15, 1000); // Format time from formatter or from time assertEquals(formatter.format(time), "10:30:15.000001"); assertEquals(time.format(formatter), "10:30:15.000001"); } @Test public void formatDateTime() { DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; LocalDateTime dateTime = LocalDateTime.of(2015, Month.OCTOBER, 30, 10, 30, 15, 1000); // Format dateTime from formatter or from dateTime assertEquals(formatter.format(dateTime), "2015-10-30T10:30:15.000001"); assertEquals(dateTime.format(formatter), "2015-10-30T10:30:15.000001"); } @Test public void parseDate() { DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; assertEquals(LocalDate.parse("2015-10-30", formatter), LocalDate.of(2015, Month.OCTOBER, 30)); } @Test public void parseTime() { DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; assertEquals(LocalTime.parse("10:30:15", formatter), LocalTime.of(10, 30, 15)); } @Test public void parseDateTime() { DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; LocalDateTime dateTime = LocalDateTime.of(2015, Month.OCTOBER, 30, 10, 30, 15); assertEquals(LocalDateTime.parse("2015-10-30T10:30:15", formatter), dateTime); } @Test public void formatDateWithCustomFormatter() { LocalDate date = LocalDate.of(2016, Month.JANUARY, 1); checkDateCustomFormatter(date, "yy/M/d", "16/1/1"); checkDateCustomFormatter(date, "yy/M/dd", "16/1/01"); checkDateCustomFormatter(date, "yy/MM/dd", "16/01/01"); checkDateCustomFormatter(date, "yyyy/MMM/dd", "2016/Jan/01"); } private void checkDateCustomFormatter(LocalDate date, String pattern, String expected) { DateTimeFormatter formatter = customLocalFormatter(pattern); assertEquals(date.format(formatter), expected); } @Test public void formatTimeWithCustomFormatter() { LocalTime time = LocalTime.of(1, 5, 5, 1000); checkCustomTimeFormatter(time, "h:m:s", "1:5:5"); checkCustomTimeFormatter(time, "h:m:ss", "1:5:05"); checkCustomTimeFormatter(time, "h:mm:ss", "1:05:05"); checkCustomTimeFormatter(time, "hh:mm:ss", "01:05:05"); checkCustomTimeFormatter(time, "hh:mm:ss.SSS", "01:05:05.000"); checkCustomTimeFormatter(time, "hh:mm:ss.SSSSSS", "01:05:05.000001"); } private void checkCustomTimeFormatter(LocalTime time, String pattern, String expected) { DateTimeFormatter formatter = customLocalFormatter(pattern); assertEquals(time.format(formatter), expected); } @Test public void formatDateTimeWithCustomFormatter() { LocalDateTime dateTime = LocalDateTime.of(2016, Month.JANUARY, 1, 1, 5, 5, 1000); checkCustomDateTimeFormatter(dateTime, "yy/M/d h:m:s", "16/1/1 1:5:5"); checkCustomDateTimeFormatter(dateTime, "yy/M/d h:m:ss", "16/1/1 1:5:05"); checkCustomDateTimeFormatter(dateTime, "yy/M/d h:mm:ss", "16/1/1 1:05:05"); checkCustomDateTimeFormatter(dateTime, "yy/M/d hh:mm:ss", "16/1/1 01:05:05"); checkCustomDateTimeFormatter(dateTime, "yy/M/dd hh:mm:ss", "16/1/01 01:05:05"); checkCustomDateTimeFormatter(dateTime, "yy/MM/dd hh:mm:ss", "16/01/01 01:05:05"); checkCustomDateTimeFormatter(dateTime, "yy/MMM/dd hh:mm:ss", "16/Jan/01 01:05:05"); checkCustomDateTimeFormatter(dateTime, "yyyy/MMM/dd hh:mm:ss", "2016/Jan/01 01:05:05"); checkCustomDateTimeFormatter(dateTime, "yyyy/MMM/dd hh:mm:ss.SSS", "2016/Jan/01 01:05:05.000"); checkCustomDateTimeFormatter(dateTime, "yyyy/MMM/dd hh:mm:ss.SSSSSS", "2016/Jan/01 01:05:05.000001"); } private void checkCustomDateTimeFormatter(LocalDateTime dateTime, String pattern, String expected) { DateTimeFormatter formatter = customLocalFormatter(pattern); assertEquals(dateTime.format(formatter), expected); } private DateTimeFormatter customLocalFormatter(String pattern) { return DateTimeFormatter.ofPattern(pattern, Locale.US); } }
package integration; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.WebDriverRunner; import net.lightbody.bmp.core.har.Har; import net.lightbody.bmp.core.har.HarEntry; import net.lightbody.bmp.proxy.ProxyServer; import net.lightbody.bmp.proxy.http.BrowserMobHttpRequest; import net.lightbody.bmp.proxy.http.BrowserMobHttpResponse; import net.lightbody.bmp.proxy.http.RequestInterceptor; import net.lightbody.bmp.proxy.http.ResponseInterceptor; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.net.UnknownHostException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.open; import static com.codeborne.selenide.WebDriverRunner.isPhantomjs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.net.PortProber.findFreePort; public class BrowserMobProxyTest extends IntegrationTest { private static final Logger log = Logger.getLogger(BrowserMobProxyTest.class.getName()); ProxyServer proxyServer; @Before public void closePreviousWebdriver() { assumeFalse(isPhantomjs()); WebDriverRunner.closeWebDriver(); server.uploadedFiles.clear(); } @Before public void startBrowserMobProxyServer() throws Exception { proxyServer = new ProxyServer(findFreePort()); proxyServer.start(); } @After public void stopBrowserMobProxyServer() throws Exception { if (proxyServer != null) { proxyServer.stop(); } } @After public void resetWebdriverProxySettings() { WebDriverRunner.setProxy(null); WebDriverRunner.closeWebDriver(); } private int requestCounter = 0; @Test public void canUseBrowserMobProxy() throws UnknownHostException { proxyServer.addRequestInterceptor(new RequestInterceptor() { @Override public void process(BrowserMobHttpRequest httpRequest, Har har) { String requestUri = httpRequest.getProxyRequest().getURI().toString(); log.info("request: " + requestUri); if (!requestUri.endsWith("/favicon.ico") && !requestUri.endsWith("/start_page.html") && !"http://ocsp.digicert.com/".equals(requestUri)) { requestCounter++; } } }); proxyServer.addResponseInterceptor(new ResponseInterceptor() { @Override public void process(BrowserMobHttpResponse response, Har har) { log.info("> " + response.getEntry().getRequest().getUrl()); log.info("< " + response.getRawResponse().getStatusLine().toString()); } }); proxyServer.newHar("some-har"); WebDriverRunner.setProxy(proxyServer.seleniumProxy()); open("/file_upload_form.html"); $("#cv").uploadFromClasspath("hello_world.txt"); $("#avatar").uploadFromClasspath("firebug-1.11.4.xpi"); $("#submit").click(); assertEquals(2, server.uploadedFiles.size()); assertEquals(2, requestCounter); List<HarEntry> harEntries = proxyServer.getHar().getLog().getEntries(); Set<String> requestedUrls = new HashSet<>(); for (HarEntry harEntry : harEntries) { requestedUrls.add(harEntry.getRequest().getUrl()); } assertTrue(requestedUrls.toString(), requestedUrls.contains(Configuration.baseUrl + "/file_upload_form.html")); assertTrue(requestedUrls.toString(), requestedUrls.contains(Configuration.baseUrl + "/upload")); } }
package io.craft.armor; import io.craft.armor.api.Armor; import org.springframework.stereotype.Service; /** * @author mindwind * @version 1.0, Dec 18, 2014 */ @Armor @Service("demoService2") public class DemoServiceImpl2 implements DemoService { @Override public String echo(String in) { return in + in; } @Override public String echoCascade(String in) { return null; } @Override public int echo(int i) { return 0; } @Override public boolean isOk() { return false; } @Override public void timeout(int timeoutInMillis) {} @Override public void throwException() throws IllegalAccessException {} }
package org.basex.test.cs; import static org.junit.Assert.*; import static org.basex.core.Text.*; import java.io.IOException; import java.util.LinkedList; import java.util.Random; import org.basex.BaseXServer; import org.basex.core.Session; import org.basex.core.Proc; import org.basex.core.proc.CreateDB; import org.basex.core.proc.DropDB; import org.basex.io.CachedOutput; import org.basex.server.ClientSession; import org.basex.util.Performance; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public final class SemaphoreTest { /** Create random number. */ static Random rand = new Random(); /** Test file. */ private static final String FILE = "etc/xml/factbook.xml"; /** Test queries. */ final String [] q = {"xquery for $n in doc('factbook')//province " + "return insert node <test/> into $n", "xquery for $n in 1 to 100000 where $n = 0 return $n" }; /** Number of performance tests. */ private static final int TESTS = 5; /** List to adminstrate the clients. */ final static LinkedList<ClientSession> sessions = new LinkedList<ClientSession>(); /** Server reference. */ static BaseXServer server; /** Socket reference. */ static Session sess; /** Number of done tests. */ static int tdone; /** Starts the server. */ @BeforeClass public static void start() { server = new BaseXServer(); sess = createSession(); } /** Stops the server. */ @AfterClass public static void stop() { closeSession(sess); for(ClientSession s : sessions) { closeSession(s); } // Stop server instance. new BaseXServer("stop"); } /** Runs a test for concurrent database creations. */ @Test public void createTest() { // drops database for clean test exec(new DropDB("factbook"), sess); // create database for clean test exec(new CreateDB(FILE), sess); for(int i = 0; i < TESTS; i++) { sessions.add(createSession()); } Performance.sleep(700); } /** Efficiency test. */ @Test public void runClients() { for (int n = 0; n < TESTS; n++) { final int j = n; try { Thread.sleep(500); } catch(final InterruptedException e1) { e1.printStackTrace(); } new Thread() { @Override public void run() { try { final int t = rand.nextInt(2); sessions.get(j).execute(q[t]); String w = "write"; if(t == 1) w = "read"; System.out.println("=== Client " + j + " with " + w + " query done ==="); tdone++; } catch(final IOException e) { e.printStackTrace(); } } }.start(); } // wait until all test have been finished while(tdone < TESTS) Performance.sleep(200); } /** * Creates a client session. * @return client session */ static ClientSession createSession() { try { return new ClientSession(server.context, ADMIN, ADMIN); } catch(final IOException ex) { fail(ex.toString()); } return null; } /** * Closes a client session. * @param s session to be closed */ static void closeSession(final Session s) { try { s.close(); } catch(final IOException ex) { fail(ex.toString()); } } /** * Returns query result. * @param pr process reference * @param session session * @return String result */ String checkRes(final Proc pr, final Session session) { final CachedOutput co = new CachedOutput(); try { session.execute(pr, co); } catch(final IOException ex) { fail(ex.toString()); } return co.toString(); } /** * Runs the specified process. * @param pr process reference * @param session Session * @return success flag */ String exec(final Proc pr, final Session session) { try { return session.execute(pr) ? null : session.info(); } catch(final IOException ex) { return ex.toString(); } } }
package org.gbif.dwc.terms; import org.junit.Test; import java.util.HashSet; import java.util.List; import static org.junit.Assert.*; public class GbifTermTest extends TermBaseTest { public GbifTermTest() { super(GbifTerm.class); } @Test public void testTerm() { assertEquals("taxonKey", GbifTerm.taxonKey.simpleName()); assertEquals("http://rs.gbif.org/terms/1.0/taxonKey", GbifTerm.taxonKey.qualifiedName()); assertEquals("lastInterpreted", GbifTerm.lastInterpreted.simpleName()); assertEquals("http://rs.gbif.org/terms/1.0/lastInterpreted", GbifTerm.lastInterpreted.qualifiedName()); } @Test public void testIsClass() { assertTrue(GbifTerm.VernacularName.isClass()); assertTrue(GbifTerm.Distribution.isClass()); assertFalse(GbifTerm.datasetKey.isClass()); } @Test public void testNumberOfGroups() { assertEquals(9, GbifTerm.GROUPS.length); } /** * Test each group contains the expected number of terms, and contains no duplicates. */ @Test public void testListByGroup() { List<GbifTerm> datasetTerms = GbifTerm.listByGroup(GbifTerm.GROUP_DATASET); assertEquals(2, datasetTerms.size()); assertEquals(2, new HashSet<GbifTerm>(datasetTerms).size()); List<GbifTerm> occurrenceTerms = GbifTerm.listByGroup(DwcTerm.GROUP_OCCURRENCE); assertEquals(13, occurrenceTerms.size()); assertEquals(13, new HashSet<GbifTerm>(occurrenceTerms).size()); List<GbifTerm> locationTerms = GbifTerm.listByGroup(DwcTerm.GROUP_LOCATION); assertEquals(6, locationTerms.size()); assertEquals(6, new HashSet<GbifTerm>(locationTerms).size()); List<GbifTerm> rowTerms = GbifTerm.listByGroup(GbifTerm.GROUP_ROW_TYPE); assertEquals(9, rowTerms.size()); assertEquals(9, new HashSet<GbifTerm>(rowTerms).size()); List<GbifTerm> distributionTerms = GbifTerm.listByGroup(GbifTerm.GROUP_SPECIES_DISTRIBUTION_EXTENSION); assertEquals(2, distributionTerms.size()); assertEquals(2, new HashSet<GbifTerm>(distributionTerms).size()); List<GbifTerm> profileTerms = GbifTerm.listByGroup(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION); assertEquals(10, profileTerms.size()); assertEquals(10, new HashSet<GbifTerm>(profileTerms).size()); List<GbifTerm> taxonTerms = GbifTerm.listByGroup(DwcTerm.GROUP_TAXON); assertEquals(16, taxonTerms.size()); assertEquals(16, new HashSet<GbifTerm>(taxonTerms).size()); List<GbifTerm> crawlingTerms = GbifTerm.listByGroup(GbifTerm.GROUP_CRAWLING); assertEquals(3, crawlingTerms.size()); assertEquals(3, new HashSet<GbifTerm>(crawlingTerms).size()); List<GbifTerm> vernacularTerms = GbifTerm.listByGroup(GbifTerm.GROUP_VERNACULAR_NAME_EXTENSION); assertEquals(3, vernacularTerms.size()); assertEquals(3, new HashSet<GbifTerm>(vernacularTerms).size()); } @Test public void testGroupCoverage() { HashSet<GbifTerm> arrayTerms = new HashSet<GbifTerm>(); for (GbifTerm t : GbifTerm.TAXONOMIC_TERMS) { arrayTerms.add(t); assertFalse(t.isClass()); assertEquals(DwcTerm.GROUP_TAXON, t.getGroup()); } for (GbifTerm t : GbifTerm.listByGroup(DwcTerm.GROUP_TAXON)) { if (!arrayTerms.contains(t)) { assertTrue("Missing taxonomic term in GbifTerm.TAXONOMIC_TERMS: " + t.qualifiedName(), arrayTerms.contains(t)); } } } @Test public void testDeprecated() { assertFalse(GbifTerm.gbifID.isDeprecated()); assertTrue(GbifTerm.coordinateAccuracy.isDeprecated()); } }
package org.lantern; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.lantern.httpseverywhere.HttpsEverywhere; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HttpsEverywhereTest { private final Logger log = LoggerFactory.getLogger(getClass()); @Test public void testHttpsEverywhereRegex() throws Exception { final String[] urls = new String[] { "http: "http://news.google.com/news", "http: "http: "http: "http: "http: "http: "http://platform.linkedin.com/", }; final String[] expecteds = new String[] { "https://mail.google.com/test", "https: // This should be the same -- it should match the *target* for "http: "https://balatarin.com/test", "https: "https://secure.flickr.com/newPicture.jpg", "https://encrypted.google.com/", "https://twitter.com/", "https://platform.linkedin.com/", }; final HttpsEverywhere he = new HttpsEverywhere(); for (int i = 0; i < urls.length; i++) { final String request = urls[i]; final String expected = expecteds[i]; final String converted = he.toHttps(request); log.info("Got converted: "+converted); assertEquals(expected, converted); } final String[] excluded = new String[] { "http://images.google.com/", "http://test.forums.wordpress.com/" }; for (int i = 0; i < excluded.length; i++) { final String request = excluded[i]; final String converted = he.toHttps(request); log.info("Got converted: "+converted); assertEquals(request, converted); } } }
package org.mariadb.jdbc; import org.junit.Assert; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import static org.junit.Assert.*; public class DataSourceTest extends BaseTest { protected static final String defConnectToIP = null; protected static String connectToIP; /** * Initialisation. */ @BeforeClass public static void beforeClassDataSourceTest() { connectToIP = System.getProperty("testConnectToIP", defConnectToIP); } @Test public void testDataSource() throws SQLException { MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); try (Connection connection = ds.getConnection(username, password)) { assertEquals(connection.isValid(0), true); } } @Test public void testDataSource2() throws SQLException { MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); try (Connection connection = ds.getConnection(username, password)) { assertEquals(connection.isValid(0), true); } } @Test public void testDataSourceEmpty() throws SQLException { MariaDbDataSource ds = new MariaDbDataSource(); ds.setDatabaseName(database); ds.setPort(port); ds.setServerName(hostname == null ? "localhost" : hostname); try (Connection connection = ds.getConnection(username, password)) { assertEquals(connection.isValid(0), true); } } /** * Conj-80. * * @throws SQLException exception */ @Test public void setDatabaseNameTest() throws SQLException { Assume.assumeFalse("MAXSCALE".equals(System.getenv("TYPE"))); MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); try (Connection connection = ds.getConnection(username, password)) { connection.createStatement().execute("CREATE DATABASE IF NOT EXISTS test2"); ds.setDatabaseName("test2"); try (Connection connection2 = ds.getConnection(username, password)) { assertEquals("test2", ds.getDatabaseName()); assertEquals(ds.getDatabaseName(), connection2.getCatalog()); connection2.createStatement().execute("DROP DATABASE IF EXISTS test2"); } } } /** * Conj-80. * * @throws SQLException exception */ @Test public void setServerNameTest() throws SQLException { Assume.assumeTrue(connectToIP != null); MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); try (Connection connection = ds.getConnection(username, password)) { ds.setServerName(connectToIP); try (Connection connection2 = ds.getConnection(username, password)) { //do nothing } } } /** * Conj-80. * * @throws SQLException exception */ @Test(timeout = 20000) // unless port 3307 can be used public void setPortTest() throws SQLException { Assume.assumeFalse("true".equals(System.getenv("AURORA"))); MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); try (Connection connection2 = ds.getConnection(username, password)) { //delete blacklist, because can failover on 3306 is filled assureBlackList(connection2); connection2.close(); } ds.setPort(3407); //must throw SQLException try { ds.getConnection(username, password); Assert.fail(); } catch (SQLException e) { //normal error } } /** * Conj-123:Session variables lost and exception if set via MariaDbDataSource.setProperties/setURL. * * @throws SQLException exception */ @Test public void setPropertiesTest() throws SQLException { MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); ds.setProperties("sessionVariables=sql_mode='PIPES_AS_CONCAT'"); try (Connection connection = ds.getConnection(username, password)) { ResultSet rs = connection.createStatement().executeQuery("SELECT @@sql_mode"); if (rs.next()) { assertEquals("PIPES_AS_CONCAT", rs.getString(1)); ds.setUrl(connUri + "&sessionVariables=sql_mode='ALLOW_INVALID_DATES'"); try (Connection connection2 = ds.getConnection()) { rs = connection2.createStatement().executeQuery("SELECT @@sql_mode"); assertTrue(rs.next()); assertEquals("ALLOW_INVALID_DATES", rs.getString(1)); } } else { fail(); } } } @Test public void setLoginTimeOut() throws SQLException { MariaDbDataSource ds = new MariaDbDataSource(hostname == null ? "localhost" : hostname, port, database); assertEquals(0, ds.getLoginTimeout()); ds.setLoginTimeout(10); assertEquals(10, ds.getLoginTimeout()); } }
package org.netmelody.citric; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.hamcrest.Matchers; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.collect.ImmutableSortedSet; public final class TargetTest { private final Mockery context = new Mockery(); @Test public void buildsNothingAtFirst() { final ArtefactStream stream = context.mock(ArtefactStream.class); final Target target = new Target(stream); context.checking(new Expectations() {{ allowing(stream).availableAt(Time.of(0)); will(returnValue(ImmutableSortedSet.of())); }}); assertThat(target.availableAt(Time.of(0)), is(Matchers.<Artefact>emptyIterable())); } @Test public void buildsParentArtefactWithGivenBuildDuration() { final ArtefactStream stream = context.mock(ArtefactStream.class); final Target target = new Target(stream); context.checking(new Expectations() {{ allowing(stream).availableAt(Time.of(1)); will(returnValue(ImmutableSortedSet.of(Artefact.number(1)))); allowing(stream).availableAt(Time.of(2)); will(returnValue(ImmutableSortedSet.of(Artefact.number(1)))); }}); assertThat(target.availableAt(Time.of(1)), is(Matchers.<Artefact>emptyIterable())); assertThat(target.availableAt(Time.of(2)), is(Matchers.contains(Artefact.number(1)))); } @Test public void delaysArtefactRateWhenBuildDurationIsLong() { final ArtefactStream stream = context.mock(ArtefactStream.class); final Target target = new Target(stream, Time.of(5)); context.checking(new Expectations() {{ allowing(stream).availableAt(Time.of(1)); will(returnValue(ImmutableSortedSet.of(Artefact.number(1)))); allowing(stream).availableAt(Time.of(6)); will(returnValue(ImmutableSortedSet.of(Artefact.number(1), Artefact.number(2)))); }}); assertThat(target.availableAt(Time.of(5)), is(Matchers.<Artefact>emptyIterable())); assertThat(target.availableAt(Time.of(6)), is(Matchers.contains(Artefact.number(1)))); } @Test public void realisticallySimulatesCommitBuilds() { final Target target = new Target(new CommitStream(), Time.of(2)); assertThat(target.availableAt(Time.of(0)), is(Matchers.<Artefact>emptyIterable())); assertThat(target.availableAt(Time.of(1)), is(Matchers.<Artefact>emptyIterable())); assertThat(target.availableAt(Time.of(2)), is(Matchers.<Artefact>emptyIterable())); assertThat(target.availableAt(Time.of(3)), is(Matchers.contains(Artefact.number(1)))); assertThat(target.availableAt(Time.of(4)), is(Matchers.contains(Artefact.number(1)))); assertThat(target.availableAt(Time.of(5)), is(Matchers.contains(Artefact.number(1), Artefact.number(3)))); assertThat(target.availableAt(Time.of(6)), is(Matchers.contains(Artefact.number(1), Artefact.number(3)))); } }
package org.threeten.extra; import static java.time.DayOfWeek.FRIDAY; import static java.time.DayOfWeek.MONDAY; import static java.time.DayOfWeek.SATURDAY; import static java.time.DayOfWeek.SUNDAY; import static java.time.DayOfWeek.THURSDAY; import static java.time.DayOfWeek.TUESDAY; import static java.time.DayOfWeek.WEDNESDAY; import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH; import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR; import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH; import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR; import static java.time.temporal.ChronoField.AMPM_OF_DAY; import static java.time.temporal.ChronoField.CLOCK_HOUR_OF_AMPM; import static java.time.temporal.ChronoField.CLOCK_HOUR_OF_DAY; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.EPOCH_DAY; import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.HOUR_OF_AMPM; import static java.time.temporal.ChronoField.HOUR_OF_DAY; import static java.time.temporal.ChronoField.INSTANT_SECONDS; import static java.time.temporal.ChronoField.MICRO_OF_DAY; import static java.time.temporal.ChronoField.MICRO_OF_SECOND; import static java.time.temporal.ChronoField.MILLI_OF_DAY; import static java.time.temporal.ChronoField.MILLI_OF_SECOND; import static java.time.temporal.ChronoField.MINUTE_OF_DAY; import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.NANO_OF_DAY; import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoField.OFFSET_SECONDS; import static java.time.temporal.ChronoField.PROLEPTIC_MONTH; import static java.time.temporal.ChronoField.SECOND_OF_DAY; import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; import static java.time.temporal.IsoFields.DAY_OF_QUARTER; import static java.time.temporal.IsoFields.QUARTER_OF_YEAR; import static java.time.temporal.IsoFields.WEEK_BASED_YEAR; import static java.time.temporal.IsoFields.WEEK_OF_WEEK_BASED_YEAR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.time.Clock; import java.time.DateTimeException; import java.time.DayOfWeek; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.chrono.IsoChronology; import java.time.chrono.ThaiBuddhistDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.ValueRange; import java.util.Locale; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test public class TestYearWeek { private static final YearWeek TEST_NON_LEAP = YearWeek.of(2014, 1); private static final YearWeek TEST = YearWeek.of(2015, 1); @DataProvider(name = "sampleYearWeeks") Object[][] provider_sampleYearWeeks() { return new Object[][]{ {2015, 1}, {2015, 2}, {2015, 3}, {2015, 4}, {2015, 5}, {2015, 6}, {2015, 7}, {2015, 8}, {2015, 9}, {2015, 10}, {2015, 11}, {2015, 12}, {2015, 13}, {2015, 14}, {2015, 15}, {2015, 16}, {2015, 17}, {2015, 18}, {2015, 19}, {2015, 20}, {2015, 21}, {2015, 22}, {2015, 21}, {2015, 22}, {2015, 23}, {2015, 23}, {2015, 24}, {2015, 25}, {2015, 26}, {2015, 27}, {2015, 28}, {2015, 29}, {2015, 30}, {2015, 31}, {2015, 32}, {2015, 33}, {2015, 34}, {2015, 35}, {2015, 36}, {2015, 37}, {2015, 38}, {2015, 39}, {2015, 40}, {2015, 41}, {2015, 42}, {2015, 43}, {2015, 44}, {2015, 45}, {2015, 46}, {2015, 47}, {2015, 48}, {2015, 49}, {2015, 50}, {2015, 51}, {2015, 52}, {2015, 53} }; } @DataProvider(name = "53WeekYear") Object[][] provider_53WeekYear() { return new Object[][]{ {4}, {9}, {15}, {20}, {26}, {32}, {37}, {43}, {48}, {54}, {60}, {65}, {71}, {76}, {82}, {88}, {93}, {99}, {105}, {111}, {116}, {122}, {128}, {133}, {139}, {144}, {150}, {156}, {161}, {167}, {172}, {178}, {184}, {189}, {195}, {201}, {207}, {212}, {218}, {224}, {229}, {235}, {240}, {246}, {252}, {257}, {263}, {268}, {274}, {280}, {285}, {291}, {296}, {303}, {308}, {314}, {320}, {325}, {331}, {336}, {342}, {348}, {353}, {359}, {364}, {370}, {376}, {381}, {387}, {392}, {398} }; } @DataProvider(name = "sampleAtDay") Object[][] provider_sampleAtDay() { return new Object[][]{ {2014, 52, MONDAY, 2014, 12, 22}, {2014, 52, TUESDAY, 2014, 12, 23}, {2014, 52, WEDNESDAY, 2014, 12, 24}, {2014, 52, THURSDAY, 2014, 12, 25}, {2014, 52, FRIDAY, 2014, 12, 26}, {2014, 52, SATURDAY, 2014, 12, 27}, {2014, 52, SUNDAY, 2014, 12, 28}, {2015, 1, MONDAY, 2014, 12, 29}, {2015, 1, TUESDAY, 2014, 12, 30}, {2015, 1, WEDNESDAY, 2014, 12, 31}, {2015, 1, THURSDAY, 2015, 1, 1}, {2015, 1, FRIDAY, 2015, 1, 2}, {2015, 1, SATURDAY, 2015, 1, 3}, {2015, 1, SUNDAY, 2015, 1, 4}, {2017, 1, MONDAY, 2017, 1, 2}, {2017, 1, TUESDAY, 2017, 1, 3}, {2017, 1, WEDNESDAY, 2017, 1, 4}, {2017, 1, THURSDAY, 2017, 1, 5}, {2017, 1, FRIDAY, 2017, 1, 6}, {2017, 1, SATURDAY, 2017, 1, 7}, {2017, 1, SUNDAY, 2017, 1, 8}, {2025, 1, MONDAY, 2024, 12, 30} }; } public void test_interfaces() { assertTrue(Serializable.class.isAssignableFrom(YearWeek.class)); assertTrue(Comparable.class.isAssignableFrom(YearWeek.class)); assertTrue(TemporalAdjuster.class.isAssignableFrom(YearWeek.class)); assertTrue(TemporalAccessor.class.isAssignableFrom(YearWeek.class)); } public void test_serialization() throws IOException, ClassNotFoundException { YearWeek test = YearWeek.of(2015, 1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(test); } ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( baos.toByteArray())); assertEquals(ois.readObject(), test); } // now() @Test public void test_now() { YearWeek expected = YearWeek.now(Clock.systemDefaultZone()); YearWeek test = YearWeek.now(); for (int i = 0; i < 100; i++) { if (expected.equals(test)) { return; } expected = YearWeek.now(Clock.systemDefaultZone()); test = YearWeek.now(); } assertEquals(test, expected); } // now(ZoneId) @Test(expectedExceptions = NullPointerException.class) public void now_ZoneId_nullZoneId() { YearWeek.now((ZoneId) null); } @Test public void now_ZoneId() { ZoneId zone = ZoneId.of("UTC+01:02:03"); YearWeek expected = YearWeek.now(Clock.system(zone)); YearWeek test = YearWeek.now(zone); for (int i = 0; i < 100; i++) { if (expected.equals(test)) { return; } expected = YearWeek.now(Clock.system(zone)); test = YearWeek.now(zone); } assertEquals(test, expected); } // now(Clock) @Test public void now_Clock() { Instant instant = LocalDateTime.of(2010, 12, 31, 0, 0).toInstant(ZoneOffset.UTC); Clock clock = Clock.fixed(instant, ZoneOffset.UTC); YearWeek test = YearWeek.now(clock); assertEquals(test.getYear(), 2010); assertEquals(test.getWeek(), 52); } @Test(expectedExceptions = NullPointerException.class) public void now_Clock_nullClock() { YearWeek.now((Clock) null); } // of(int, int) @Test(dataProvider = "sampleYearWeeks") public void test_of(int year, int week) { YearWeek yearWeek = YearWeek.of(year, week); assertEquals(yearWeek.getYear(), year); assertEquals(yearWeek.getWeek(), week); } public void test_carry() { assertTrue(YearWeek.of(2014, 53).equals(TEST)); } @Test(expectedExceptions = DateTimeException.class) public void test_of_year_tooLow() { YearWeek.of(Integer.MIN_VALUE, 1); } @Test(expectedExceptions = DateTimeException.class) public void test_of_year_tooHigh() { YearWeek.of(Integer.MAX_VALUE, 1); } @Test(expectedExceptions = DateTimeException.class) public void test_of_invalidWeekValue() { YearWeek.of(2015, 54); } @Test(expectedExceptions = DateTimeException.class) public void test_of_invalidWeekValueZero() { YearWeek.of(2015, 0); } // isSupported(TemporalField) public void test_isSupported_TemporalField() { assertEquals(TEST.isSupported((TemporalField) null), false); assertEquals(TEST.isSupported(NANO_OF_SECOND), false); assertEquals(TEST.isSupported(NANO_OF_DAY), false); assertEquals(TEST.isSupported(MICRO_OF_SECOND), false); assertEquals(TEST.isSupported(MICRO_OF_DAY), false); assertEquals(TEST.isSupported(MILLI_OF_SECOND), false); assertEquals(TEST.isSupported(MILLI_OF_DAY), false); assertEquals(TEST.isSupported(SECOND_OF_MINUTE), false); assertEquals(TEST.isSupported(SECOND_OF_DAY), false); assertEquals(TEST.isSupported(MINUTE_OF_HOUR), false); assertEquals(TEST.isSupported(MINUTE_OF_DAY), false); assertEquals(TEST.isSupported(HOUR_OF_AMPM), false); assertEquals(TEST.isSupported(CLOCK_HOUR_OF_AMPM), false); assertEquals(TEST.isSupported(HOUR_OF_DAY), false); assertEquals(TEST.isSupported(CLOCK_HOUR_OF_DAY), false); assertEquals(TEST.isSupported(AMPM_OF_DAY), false); assertEquals(TEST.isSupported(DAY_OF_WEEK), false); assertEquals(TEST.isSupported(ALIGNED_DAY_OF_WEEK_IN_MONTH), false); assertEquals(TEST.isSupported(ALIGNED_DAY_OF_WEEK_IN_YEAR), false); assertEquals(TEST.isSupported(DAY_OF_MONTH), false); assertEquals(TEST.isSupported(DAY_OF_YEAR), false); assertEquals(TEST.isSupported(EPOCH_DAY), false); assertEquals(TEST.isSupported(ALIGNED_WEEK_OF_MONTH), false); assertEquals(TEST.isSupported(ALIGNED_WEEK_OF_YEAR), false); assertEquals(TEST.isSupported(MONTH_OF_YEAR), false); assertEquals(TEST.isSupported(PROLEPTIC_MONTH), false); assertEquals(TEST.isSupported(YEAR_OF_ERA), false); assertEquals(TEST.isSupported(YEAR), false); assertEquals(TEST.isSupported(ERA), false); assertEquals(TEST.isSupported(INSTANT_SECONDS), false); assertEquals(TEST.isSupported(OFFSET_SECONDS), false); assertEquals(TEST.isSupported(QUARTER_OF_YEAR), false); assertEquals(TEST.isSupported(DAY_OF_QUARTER), false); assertEquals(TEST.isSupported(WEEK_BASED_YEAR), true); assertEquals(TEST.isSupported(WEEK_OF_WEEK_BASED_YEAR), true); } // atDay(DayOfWeek) @Test(dataProvider = "sampleAtDay") public void test_atDay(int weekBasedYear, int weekOfWeekBasedYear, DayOfWeek dayOfWeek, int year, int month, int dayOfMonth) { YearWeek yearWeek = YearWeek.of(weekBasedYear, weekOfWeekBasedYear); LocalDate expected = LocalDate.of(year, month, dayOfMonth); LocalDate actual = yearWeek.atDay(dayOfWeek); assertEquals(actual, expected); } @Test(expectedExceptions = NullPointerException.class) public void test_atDay_null() { TEST.atDay(null); } // is53WeekYear() @Test(dataProvider = "53WeekYear") public void test_is53WeekYear(int year) { YearWeek yearWeek = YearWeek.of(year, 1); assertTrue(yearWeek.is53WeekYear()); } // compareTo() public void test_compareTo() { for (int year1 = -100; year1 < 100; year1++) { for (int week1 = 1; week1 < 53; week1++) { YearWeek a = YearWeek.of(year1, week1); for (int year2 = -100; year2 < 100; year2++) { for (int week2 = 1; week2 < 53; week2++) { YearWeek b = YearWeek.of(year2, week2); if (year1 < year2) { assertEquals(a.compareTo(b) < 0, true); assertEquals(b.compareTo(a) > 0, true); assertEquals(a.isAfter(b), false); assertEquals(b.isBefore(a), false); assertEquals(b.isAfter(a), true); assertEquals(a.isBefore(b), true); } else if (year1 > year2) { assertEquals(a.compareTo(b) > 0, true); assertEquals(b.compareTo(a) < 0, true); assertEquals(a.isAfter(b), true); assertEquals(b.isBefore(a), true); assertEquals(b.isAfter(a), false); assertEquals(a.isBefore(b), false); } else { if (week1 < week2) { assertEquals(a.compareTo(b) < 0, true); assertEquals(b.compareTo(a) > 0, true); assertEquals(a.isAfter(b), false); assertEquals(b.isBefore(a), false); assertEquals(b.isAfter(a), true); assertEquals(a.isBefore(b), true); } else if (week1 > week2) { assertEquals(a.compareTo(b) > 0, true); assertEquals(b.compareTo(a) < 0, true); assertEquals(a.isAfter(b), true); assertEquals(b.isBefore(a), true); assertEquals(b.isAfter(a), false); assertEquals(a.isBefore(b), false); } else { assertEquals(a.compareTo(b), 0); assertEquals(b.compareTo(a), 0); assertEquals(a.isAfter(b), false); assertEquals(b.isBefore(a), false); assertEquals(b.isAfter(a), false); assertEquals(a.isBefore(b), false); } } } } } } } @Test(expectedExceptions = NullPointerException.class) public void test_compareTo_nullYearWeek() { TEST.compareTo(null); } // from(TemporalAccessor) @Test(dataProvider = "sampleAtDay") public void test_from(int weekBasedYear, int weekOfWeekBasedYear, DayOfWeek dayOfWeek, int year, int month, int dayOfMonth) { YearWeek expected = YearWeek.of(weekBasedYear, weekOfWeekBasedYear); LocalDate ld = LocalDate.of(year, month, dayOfMonth); assertEquals(YearWeek.from(ld), expected); assertEquals(YearWeek.from(ThaiBuddhistDate.from(ld)), expected); assertEquals(YearWeek.from(expected), expected); } @Test(expectedExceptions = DateTimeException.class) public void test_from_TemporalAccessor_noDerive() { YearWeek.from(LocalTime.NOON); } @Test(expectedExceptions = NullPointerException.class) public void test_from_TemporalAccessor_null() { YearWeek.from((TemporalAccessor) null); } // get(TemporalField) public void test_get() { assertEquals(TEST.get(WEEK_BASED_YEAR), 2015); assertEquals(TEST.get(WEEK_OF_WEEK_BASED_YEAR), 1); } @Test(expectedExceptions = UnsupportedTemporalTypeException.class) public void test_get_invalidField() { TEST.get(YEAR); } @Test(expectedExceptions = NullPointerException.class) public void test_get_null() { TEST.get((TemporalField) null); } // getLong(TemporalField) public void test_getLong() { assertEquals(TEST.getLong(WEEK_BASED_YEAR), 2015L); assertEquals(TEST.getLong(WEEK_OF_WEEK_BASED_YEAR), 1L); } @Test(expectedExceptions = UnsupportedTemporalTypeException.class) public void test_getLong_invalidField() { TEST.getLong(YEAR); } @Test(expectedExceptions = NullPointerException.class) public void test_getLong_null() { TEST.getLong((TemporalField) null); } // lengthOfYear() public void test_lengthOfYear() { assertEquals(YearWeek.of(2014, 1).lengthOfYear(), 364); assertEquals(YearWeek.of(2015, 1).lengthOfYear(), 371); } // toString() public void test_toString() { assertEquals(TEST.toString(), "2015-W01"); } // parse(CharSequence) public void test_parse_CharSequence() { assertEquals(YearWeek.parse("2015-W01"), TEST); } @Test(expectedExceptions = DateTimeParseException.class) public void test_parse_CharSequenceDate_invalidYear() { YearWeek.parse("12345-W7"); } @Test(expectedExceptions = DateTimeParseException.class) public void test_parse_CharSequenceDate_invalidWeek() { YearWeek.parse("2015-W54"); } @Test(expectedExceptions = NullPointerException.class) public void test_parse_CharSequenceDate_nullCharSequence() { YearWeek.parse((CharSequence) null); } // parse(CharSequence,DateTimeFormatter) public void test_parse_CharSequenceDateTimeFormatter() { DateTimeFormatter f = DateTimeFormatter.ofPattern("E 'W'w YYYY").withLocale(Locale.ENGLISH); assertEquals(YearWeek.parse("Mon W1 2015", f), TEST); } @Test(expectedExceptions = DateTimeParseException.class) public void test_parse_CharSequenceDateDateTimeFormatter_invalidWeek() { DateTimeFormatter f = DateTimeFormatter.ofPattern("E 'W'w YYYY").withLocale(Locale.ENGLISH); YearWeek.parse("Mon W99 2015", f); } @Test(expectedExceptions = NullPointerException.class) public void test_parse_CharSequenceDateTimeFormatter_nullCharSequence() { DateTimeFormatter f = DateTimeFormatter.ofPattern("E 'W'w YYYY").withLocale(Locale.ENGLISH); YearWeek.parse((CharSequence) null, f); } @Test(expectedExceptions = NullPointerException.class) public void test_parse_CharSequenceDateTimeFormatter_nullDateTimeFormatter() { YearWeek.parse("", (DateTimeFormatter) null); } // format() public void test_format() { DateTimeFormatter f = new DateTimeFormatterBuilder() .appendValue(WEEK_BASED_YEAR, 4) .appendLiteral('-') .appendValue(WEEK_OF_WEEK_BASED_YEAR, 2) .toFormatter(); assertEquals(TEST.format(f), "2015-01"); } // adjustInto() public void test_adjustInto() { YearWeek yw = YearWeek.of(2016, 1); LocalDate date = LocalDate.of(2015, 6, 20); assertEquals(yw.adjustInto(date), LocalDate.of(2016, 1, 9)); } @Test(expectedExceptions = DateTimeException.class) public void test_adjustInto_badChronology() { YearWeek yw = YearWeek.of(2016, 1); ThaiBuddhistDate date = ThaiBuddhistDate.from(LocalDate.of(2015, 6, 20)); yw.adjustInto(date); } // range(TemporalField) public void test_range() { assertEquals(TEST_NON_LEAP.range(WEEK_BASED_YEAR), WEEK_BASED_YEAR.range()); assertEquals(TEST.range(WEEK_BASED_YEAR), WEEK_BASED_YEAR.range()); assertEquals(TEST_NON_LEAP.range(WEEK_OF_WEEK_BASED_YEAR), ValueRange.of(1, 52)); assertEquals(TEST.range(WEEK_OF_WEEK_BASED_YEAR), ValueRange.of(1, 53)); } @Test(expectedExceptions = UnsupportedTemporalTypeException.class) public void test_range_invalidField() { TEST.range(YEAR); } @Test(expectedExceptions = NullPointerException.class) public void test_range_null() { TEST.range((TemporalField) null); } // withYear(int) public void test_withYear() { assertEquals(YearWeek.of(2015, 1).withYear(2014), YearWeek.of(2014, 1)); assertEquals(YearWeek.of(2015, 53).withYear(2009), YearWeek.of(2009, 53)); } public void test_withYear_sameYear() { assertEquals(YearWeek.of(2015, 1).withYear(2015), YearWeek.of(2015, 1)); } public void test_withYear_resolve() { assertEquals(YearWeek.of(2015, 53).withYear(2014), YearWeek.of(2014, 52)); } @Test(expectedExceptions = DateTimeException.class) public void test_withYear_int_max() { TEST.withYear(Integer.MAX_VALUE); } @Test(expectedExceptions = DateTimeException.class) public void test_withYear_int_min() { TEST.withYear(Integer.MIN_VALUE); } // withWeek(int) public void test_withWeek() { assertEquals(TEST.withWeek(52), YearWeek.of(2015, 52)); assertEquals(YearWeek.of(2014, 1).withWeek(53), TEST); } public void test_withWeek_sameWeek() { assertEquals(YearWeek.of(2014, 2).withWeek(2), YearWeek.of(2014, 2)); } @Test(expectedExceptions = DateTimeException.class) public void test_withWeek_int_max() { TEST.withWeek(Integer.MAX_VALUE); } @Test(expectedExceptions = DateTimeException.class) public void test_withWeek_int_min() { TEST.withWeek(Integer.MIN_VALUE); } // plusWeeks(long) public void test_plusWeeks() { assertEquals(TEST.plusWeeks(0), TEST); assertEquals(TEST.plusWeeks(1), YearWeek.of(2015, 2)); assertEquals(TEST.plusWeeks(2), YearWeek.of(2015, 3)); assertEquals(TEST.plusWeeks(51), YearWeek.of(2015, 52)); assertEquals(TEST.plusWeeks(52), YearWeek.of(2015, 53)); assertEquals(TEST.plusWeeks(53), YearWeek.of(2016, 1)); assertEquals(TEST.plusWeeks(314), YearWeek.of(2021, 1)); } public void test_plusWeeks_negative() { assertEquals(TEST.plusWeeks(0), TEST); assertEquals(TEST.plusWeeks(-1), YearWeek.of(2014, 52)); assertEquals(TEST.plusWeeks(-2), YearWeek.of(2014, 51)); assertEquals(TEST.plusWeeks(-51), YearWeek.of(2014, 2)); assertEquals(TEST.plusWeeks(-52), YearWeek.of(2014, 1)); assertEquals(TEST.plusWeeks(-53), YearWeek.of(2013, 52)); assertEquals(TEST.plusWeeks(-261), YearWeek.of(2009, 53)); } @Test(expectedExceptions = ArithmeticException.class) public void test_plusWeeks_max_long() { TEST.plusWeeks(Long.MAX_VALUE); } @Test(expectedExceptions = DateTimeException.class) public void test_plusWeeks_min_long() { TEST.plusWeeks(Long.MIN_VALUE); } // minusWeeks(long) public void test_minusWeeks() { assertEquals(TEST.minusWeeks(0), TEST); assertEquals(TEST.minusWeeks(1), YearWeek.of(2014, 52)); assertEquals(TEST.minusWeeks(2), YearWeek.of(2014, 51)); assertEquals(TEST.minusWeeks(51), YearWeek.of(2014, 2)); assertEquals(TEST.minusWeeks(52), YearWeek.of(2014, 1)); assertEquals(TEST.minusWeeks(53), YearWeek.of(2013, 52)); assertEquals(TEST.minusWeeks(261), YearWeek.of(2009, 53)); } public void test_minusWeeks_negative() { assertEquals(TEST.minusWeeks(0), TEST); assertEquals(TEST.minusWeeks(-1), YearWeek.of(2015, 2)); assertEquals(TEST.minusWeeks(-2), YearWeek.of(2015, 3)); assertEquals(TEST.minusWeeks(-51), YearWeek.of(2015, 52)); assertEquals(TEST.minusWeeks(-52), YearWeek.of(2015, 53)); assertEquals(TEST.minusWeeks(-53), YearWeek.of(2016, 1)); assertEquals(TEST.minusWeeks(-314), YearWeek.of(2021, 1)); } @Test(expectedExceptions = ArithmeticException.class) public void test_minWeeks_max_long() { TEST.plusWeeks(Long.MAX_VALUE); } @Test(expectedExceptions = DateTimeException.class) public void test_minWeeks_min_long() { TEST.plusWeeks(Long.MIN_VALUE); } // query(TemporalQuery) @Test public void test_query() { assertEquals(TEST.query(TemporalQueries.chronology()), IsoChronology.INSTANCE); assertEquals(TEST.query(TemporalQueries.localDate()), null); assertEquals(TEST.query(TemporalQueries.localTime()), null); assertEquals(TEST.query(TemporalQueries.offset()), null); assertEquals(TEST.query(TemporalQueries.precision()), null); assertEquals(TEST.query(TemporalQueries.zone()), null); assertEquals(TEST.query(TemporalQueries.zoneId()), null); } // equals() / hashCode() @Test(dataProvider = "sampleYearWeeks") public void test_equalsAndHashCodeContract(int year, int week) { YearWeek a = YearWeek.of(year, week); YearWeek b = YearWeek.of(year, week); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertTrue(a.hashCode() == b.hashCode()); } public void test_equals() { YearWeek a = YearWeek.of(2015, 4); YearWeek b = YearWeek.of(2015, 6); YearWeek c = YearWeek.of(2016, 6); assertFalse(a.equals(b)); assertFalse(a.equals(c)); assertFalse(b.equals(a)); assertFalse(b.equals(c)); assertFalse(c.equals(a)); assertFalse(c.equals(b)); } public void test_equals_incorrectType() { assertTrue(TEST.equals(null) == false); assertEquals(TEST.equals("Incorrect type"), false); } // toString() @DataProvider(name = "sampleToString") Object[][] provider_sampleToString() { return new Object[][]{ {2015, 1, "2015-W01"}, {2015, 10, "2015-W10"}, {999, 1, "0999-W01"}, {-999, 1, "-0999-W01"}, {10000, 1, "+10000-W01"}, {-10000, 1, "-10000-W01"},}; } @Test(dataProvider = "sampleToString") public void test_toString(int year, int week, String expected) { YearWeek yearWeek = YearWeek.of(year, week); String s = yearWeek.toString(); assertEquals(s, expected); } }
package seedu.address.testutil; import java.util.Optional; import seedu.address.model.tag.UniqueTagList; import seedu.address.model.task.*; /** * A mutable task object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private Location address; private Description description; private Optional<Time> time; private Period period; private UniqueTagList tags; private boolean isCompleted; public TestTask() { tags = new UniqueTagList(); } public void setName(Name name) { this.name = name; } public void setAddress(Location address) { this.address = address; } public void setDescription(Description description) { this.description = description; } public void setTime(Optional<Time> time) { this.time = time; } public void setPeriod(Period period) { this.period = period; } @Override public Name getName() { return name; } @Override public Optional<Time> getTime() { return time; } @Override public Description getDescription() { return description; } @Override public Location getLocation() { return address; } @Override public UniqueTagList getTags() { return tags; } @Override public Period getPeriod() { return period; } @Override public boolean getCompleted() { return isCompleted; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().taskName + " "); sb.append("t;" + this.getTime().get().value + " "); sb.append("et;" + this.getPeriod().value + " "); sb.append("d;" + this.getDescription().value + " "); sb.append("a;" + this.getLocation().value + " "); this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); return sb.toString(); } }
package org.mnilsen.weather.server; /** * * @author michaeln */ public enum AppProperty { USE_DATABASE("false"), MONGO_HOST("localhost"), MONGO_PORT("27017"), SENSOR_POLLING_PERIOD_MILLIS("60000"), DISPLAY_UPDATE_PERIOD("30000"), DISPLAY_ENABLED("true"), DISPLAY_HISTORY("true"), LOG_DIRECTORY("/home/pi/weather/logs"), HISTORY_LENGTH_DAYS("30"), DISPLAY_SCRIPT_NAME("display.py"), APPLICATION_HOME_DIR("/home/pi/weather"), AWS_CLIENT_ID("weather-station-1"), AWS_CLIENT_ENDPOINT("a2qgyw4trswo49.iot.us-east-1.amazonaws.com"), AWS_CERT_FILE("/home/pi/aws/WeatherStation1.cert.pem"), AWS_PK_FILE("/home/pi/aws/WeatherStation1.private.key"), AWS_UPDATE_TOPIC("$aws/things/WeatherStation1/shadow/update"), AWS_UPDATE_ACCEPTED_TOPIC("$aws/things/WeatherStation1/shadow/update/accepted"), AWS_UPDATE_REJECTED_TOPIC("$aws/things/WeatherStation1/shadow/update/rejected"), AWS_UPDATE_PERIOD("300000"), AWS_ACCESS_KEY("YOURKEYHERE"), AWS_SECRET_KEY("YOURKEYHERE"), WATER_SENSOR_PIN("4"), WATER_MONITOR_PERIOD("300000"), ALERT_SUPRESS_PERIOD(Long.toString(60 * 60 * 1000)); private final String defaultValue; private AppProperty(String defaultVal) { this.defaultValue = defaultVal; } public String getDefaultValue() { return defaultValue; } }
package assignment2; import be.ac.ua.ansymo.adbc.annotations.ensures; import be.ac.ua.ansymo.adbc.annotations.invariant; import be.ac.ua.ansymo.adbc.annotations.requires; @invariant("$this.height() != 0") public class BinTree implements IBinTree { protected long id; private IBinTree left; private IBinTree right; @requires("id != null") @ensures({"$this.left == null", "$this.right == null"}) public BinTree(long id) { this.id = id; } @Override public IBinTree getLeft() { return this.left; } @Override public IBinTree getRight() { return this.right; } @requires({"bt != null", "$this.left == null"}) @ensures({"$this.left != null", "$this.left == bt"}) @Override public void setLeft(IBinTree bt) { this.left = bt; } @requires({"bt != null", "$this.right == null"}) @ensures({"$this.right != null", "$this.right == bt"}) @Override public void setRight(IBinTree bt) { this.right = bt; } @requires({"left != null", "right != null", "$this.left == null", "$this.right == null"}) @ensures({"$this.left != null", "$this.right != null", "$this.left == left", "$this.right == right"}) public void setLeftRight(IBinTree left, IBinTree right) { this.left = left; this.right = right; } @Override public boolean hasLeft() { return this.left != null; } @Override public boolean hasRight() { return this.right != null; } @Override public int sumNodes() { int i = 1; if (this.left != null) { i += this.left.sumNodes(); } if (this.right != null) { i += this.right.sumNodes(); } return i; } @Override public int height() { int leftHeight = (this.left != null) ? this.left.height() : 0; int rightHeight = (this.right != null) ? this.right.height() : 0; return Math.max(leftHeight, rightHeight) + 1; } public boolean isBalanced() { int leftHeight = (this.left == null) ? 0 : this.left.height(); int rightHeight = (this.right == null) ? 0 : this.right.height(); return Math.abs(leftHeight - rightHeight) < 2; } public boolean isTwoOrNoLeaf() { if (this.left == null && this.right == null) { return true; } if (this.left != null && this.right != null) { return this.getLeft().isTwoOrNoLeaf() && this.getRight().isTwoOrNoLeaf(); } return false; } }
package seedu.address.testutil; import java.util.Optional; import seedu.address.model.booking.UniqueBookingList; import seedu.address.model.label.UniqueLabelList; import seedu.address.model.task.Deadline; import seedu.address.model.task.ReadOnlyTask; import seedu.address.model.task.Recurrence; import seedu.address.model.task.Title; /** * A mutable task object. For testing only. */ public class TestTask implements ReadOnlyTask { private Title title; private Optional<Deadline> startTime; private Optional<Deadline> deadline; private UniqueLabelList labels; private Boolean isCompleted; private UniqueBookingList bookings; private Boolean isRecurring; private Optional<Recurrence> recurrence; public TestTask() { labels = new UniqueLabelList(); bookings = new UniqueBookingList(); } /** * Creates a copy of {@code taskToCopy}. */ public TestTask(TestTask taskToCopy) { this.title = taskToCopy.getTitle(); this.startTime = taskToCopy.getStartTime(); this.deadline = taskToCopy.getDeadline(); this.labels = taskToCopy.getLabels(); this.isCompleted = taskToCopy.isCompleted(); this.bookings = taskToCopy.getBookings(); this.isRecurring = taskToCopy.isRecurring(); this.recurrence = taskToCopy.getRecurrence(); } public void setTitle(Title name) { this.title = name; } public void setDeadline(Optional<Deadline> deadline) { this.deadline = deadline; } public void setLabels(UniqueLabelList labels) { this.labels = labels; } @Override public Title getTitle() { return title; } @Override public Optional<Deadline> getDeadline() { return deadline == null ? Optional.empty() : deadline; } @Override public UniqueLabelList getLabels() { return labels; } @Override public String toString() { return getAsText(); } //@@author A0105287E /** * Returns an AddCommand that can be used to create this task. */ public String getAddCommand() { String addCommand; if (this.getStartTime().isPresent() && this.getDeadline().isPresent()) { addCommand = getAddCommandWithInterval(); } else if (this.getDeadline().isPresent()) { addCommand = getAddCommandWithDeadline(); } else { addCommand = getAddCommandWithoutDate(); } return addCommand; } //@@author A0105287E private String getAddCommandWithoutDate() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getTitle().title + " "); this.getLabels().asObservableList().stream().forEach(s -> sb.append("#" + s.labelName + " ")); return sb.toString(); } //@@author A0105287E private String getAddCommandWithDeadline() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getTitle().title + " "); sb.append(" by " + this.getDeadline().get().toString() + " "); this.getLabels().asObservableList().stream().forEach(s -> sb.append("#" + s.labelName + " ")); return sb.toString(); } //@@author A0105287E private String getAddCommandWithInterval() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getTitle().title + " "); sb.append(" from " + this.getStartTime().get().toString() + " "); sb.append(" to " + this.getDeadline().get().toString() + " "); this.getLabels().asObservableList().stream().forEach(s -> sb.append("#" + s.labelName + " ")); return sb.toString(); } public void setStartTime(Optional<Deadline> startTime) { this.startTime = startTime; } @Override public Optional<Deadline> getStartTime() { return startTime == null ? Optional.empty() : startTime; } public void setIsCompleted(Boolean isCompleted) { this.isCompleted = isCompleted; } @Override public Boolean isCompleted() { return isCompleted == null ? Boolean.FALSE : isCompleted; } @Override public UniqueBookingList getBookings() { return bookings; } public void setBookings(UniqueBookingList uniqueBookingList) { bookings = uniqueBookingList; } @Override public Boolean isRecurring() { return isRecurring == null ? Boolean.FALSE : isRecurring; } @Override public Optional<Recurrence> getRecurrence() { return recurrence == null ? Optional.empty() : recurrence; } public void setIsRecurring(Boolean isRecurring) { this.isRecurring = isRecurring; } public void setRecurrence (Optional<Recurrence> recurrence) { this.recurrence = recurrence; } }
package org.mtransit.parser; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.gtfs.GAgencyTools; import org.mtransit.parser.gtfs.GReader; import org.mtransit.parser.gtfs.data.GAgency; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GCalendarDatesExceptionType; import org.mtransit.parser.gtfs.data.GDropOffType; import org.mtransit.parser.gtfs.data.GFrequency; import org.mtransit.parser.gtfs.data.GPickupType; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GRouteType; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GStopTime; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.MGenerator; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MSpec; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; public class DefaultAgencyTools implements GAgencyTools { private static final int MAX_NEXT_LOOKUP_IN_DAYS = 60; private static final int MAX_LOOKUP_IN_DAYS = 60; private static final int MIN_CALENDAR_COVERAGE_TOTAL_IN_DAYS = 3; private static final int MIN_CALENDAR_DATE_COVERAGE_TOTAL_IN_DAYS = 14; private static final int MIN_PREVIOUS_NEXT_ADDED_DAYS = 2; public static final boolean EXPORT_PATH_ID; public static final boolean EXPORT_ORIGINAL_ID; public static final boolean EXPORT_DESCENT_ONLY; static { EXPORT_PATH_ID = false; EXPORT_ORIGINAL_ID = false; EXPORT_DESCENT_ONLY = false; } public static final boolean GOOD_ENOUGH_ACCEPTED; static { GOOD_ENOUGH_ACCEPTED = false; // GOOD_ENOUGH_ACCEPTED = true; // DEBUG } private static final Integer THREAD_POOL_SIZE; static { final String isCI = System.getenv("CI"); if (isCI != null && !isCI.isEmpty()) { THREAD_POOL_SIZE = 1; } else { THREAD_POOL_SIZE = 4; // THREAD_POOL_SIZE = 1; // DEBUG } } private static final Integer OVERRIDE_DATE; static { OVERRIDE_DATE = null; } private static final boolean TOMORROW; static { TOMORROW = false; } public static void main(String[] args) { new DefaultAgencyTools().start(args); } public void start(String[] args) { if (excludingAll()) { MGenerator.dumpFiles(null, args[0], args[1], args[2], true); return; } MTLog.log("Generating agency data..."); long start = System.currentTimeMillis(); GSpec gtfs = GReader.readGtfsZipFile(args[0], this, false, false); gtfs.cleanupExcludedData(); gtfs.generateTripStops(); if (args.length >= 4 && Boolean.parseBoolean(args[3])) { gtfs.generateStopTimesFromFrequencies(this); } gtfs.splitByRouteId(this); gtfs.clearRawData(); MSpec mSpec = MGenerator.generateMSpec(gtfs, this); MGenerator.dumpFiles(mSpec, args[0], args[1], args[2]); MTLog.log("Generating agency data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { MTLog.logFatal("NEED TO IMPLEMENT EXCLUDE ALL"); return false; } @Override public String getAgencyColor() { return null; } @Override public Integer getAgencyRouteType() { return null; } @Override public boolean excludeAgencyNullable(GAgency gAgency) { if (gAgency == null) { return true; // exclude } return excludeAgency(gAgency); } @Override public boolean excludeAgency(GAgency gAgency) { return false; // keep } @Override public String cleanServiceId(String serviceId) { return serviceId; } @Override public long getRouteId(GRoute gRoute) { try { return Long.parseLong(gRoute.getRouteId()); } catch (Exception e) { MTLog.logFatal(e, "Error while extracting route ID from %s!\n", gRoute); return -1; } } @Override public String getRouteShortName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteShortName())) { MTLog.logFatal("No default route short name for %s!\n", gRoute); return null; } return gRoute.getRouteShortName(); } @Override public String getRouteLongName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteLongName())) { MTLog.logFatal("No default route long name for %s!\n", gRoute); return null; } return CleanUtils.cleanLabel(gRoute.getRouteLongName()); } @Override public boolean mergeRouteLongName(MRoute mRoute, MRoute mRouteToMerge) { return mRoute.mergeLongName(mRouteToMerge); } @Override public String getRouteColor(GRoute gRoute) { if (gRoute.getRouteColor() == null) { return null; // use agency color } if (getAgencyColor() != null && getAgencyColor().equalsIgnoreCase(gRoute.getRouteColor())) { return null; } return ColorUtils.darkenIfTooLight(gRoute.getRouteColor()); } @Override public boolean excludeRouteNullable(GRoute gRoute) { if (gRoute == null) { return true; // exclude } return excludeRoute(gRoute); } @Override public boolean excludeRoute(GRoute gRoute) { if (getAgencyRouteType() == null) { MTLog.logFatal("ERROR: unspecified agency route type '%s'!\n", getAgencyRouteType()); return false; } if (GRouteType.isUnknown(gRoute.getRouteType())) { MTLog.logFatal("ERROR: unexpected route type '%s'!\n", gRoute.getRouteType()); return false; } if (!GRouteType.isSameType(getAgencyRouteType(), gRoute.getRouteType())) { return true; // exclude } return false; // keep } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { ArrayList<MTrip> mTrips = new ArrayList<MTrip>(); mTrips.add(new MTrip(mRoute.getId())); return mTrips; } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { return new Pair<Long[], Integer[]>(new Long[]{splitTrips.get(0).getId()}, new Integer[]{gTripStop.getStopSequence()}); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (gTrip.getDirectionId() == null || gTrip.getDirectionId() < 0 || gTrip.getDirectionId() > 1) { MTLog.logFatal("ERROR: default agency implementation required 'direction_id' field in 'trips.txt'!\n"); return; } try { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId()); } catch (NumberFormatException nfe) { MTLog.logFatal(nfe, "ERROR: default agency implementation not possible!\n"); } } @Override public String cleanTripHeadsign(String tripHeadsign) { return tripHeadsign; } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { return mTrip.mergeHeadsignValue(mTripToMerge); } @Override public boolean excludeStopTime(GStopTime gStopTime) { return GPickupType.NO_PICKUP.intValue() == gStopTime.getPickupType() && GDropOffType.NO_DROP_OFF.intValue() == gStopTime.getDropOffType(); } @Override public boolean excludeTripNullable(GTrip gTrip) { if (gTrip == null) { return true; // exclude } return excludeTrip(gTrip); } @Override public boolean excludeTrip(GTrip gTrip) { return false; // keep } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDate) { return false; } @Override public boolean excludeCalendar(GCalendar gCalendar) { return false; } @Override public String cleanStopName(String gStopName) { return CleanUtils.cleanLabel(gStopName); } @Override public String cleanStopHeadsign(String stopHeadsign) { return cleanTripHeadsign(stopHeadsign); } @Override public String getStopCode(GStop gStop) { return gStop.getStopCode(); } @Override public String getStopOriginalId(GStop gStop) { return null; // only if not stop code or stop ID } @Override public int getStopId(GStop gStop) { try { return Integer.parseInt(gStop.getStopId()); } catch (Exception e) { MTLog.logFatal(e, "Error while extracting stop ID from %s!\n", gStop); return -1; } } @Override public String cleanStopOriginalId(String gStopId) { return gStopId; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { return 0; // nothing } @Override public int compare(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { return 0; // nothing } @Override public boolean excludeStopNullable(GStop gStop) { if (gStop == null) { return true; // exclude } return excludeStop(gStop); } @Override public boolean excludeStop(GStop gStop) { return false; // keep } public boolean isGoodEnoughAccepted() { return GOOD_ENOUGH_ACCEPTED; } @Override public int getThreadPoolSize() { return THREAD_POOL_SIZE; } private static final int PRECISON_IN_SECONDS = 10; @Override public Pair<Integer, Integer> getTimes(long mRouteId, GStopTime gStopTime, GSpec routeGTFS, SimpleDateFormat gDateFormat, SimpleDateFormat mDateFormat) { if (StringUtils.isEmpty(gStopTime.getArrivalTime()) || StringUtils.isEmpty(gStopTime.getDepartureTime())) { return extractTimes(mRouteId, gStopTime, routeGTFS, gDateFormat, mDateFormat); } else { return new Pair<Integer, Integer>(cleanExtraSeconds(GSpec.parseTimeString(gStopTime.getArrivalTime())), cleanExtraSeconds(GSpec.parseTimeString(gStopTime.getDepartureTime()))); } } public static Pair<Integer, Integer> extractTimes(long mRouteId, GStopTime gStopTime, GSpec routeGTFS, SimpleDateFormat gDateFormat, SimpleDateFormat mDateFormat) { try { Pair<Long, Long> timesInMs = extractTimeInMs(gStopTime, routeGTFS, gDateFormat); long arrivalTimeInMs = timesInMs.first; Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(arrivalTimeInMs); Integer arrivalTime = Integer.parseInt(mDateFormat.format(calendar.getTime())); if (calendar.get(Calendar.DAY_OF_YEAR) > 1) { arrivalTime += 240000; } long departureTimeInMs = timesInMs.second; calendar.setTimeInMillis(departureTimeInMs); Integer departureTime = Integer.parseInt(mDateFormat.format(calendar.getTime())); if (calendar.get(Calendar.DAY_OF_YEAR) > 1) { departureTime += 240000; } return new Pair<Integer, Integer>(cleanExtraSeconds(arrivalTime), cleanExtraSeconds(departureTime)); } catch (Exception e) { MTLog.logFatal(e, "Error while interpolating times for %s!\n", gStopTime); return null; } } public static Pair<Long, Long> extractTimeInMs(GStopTime gStopTime, GSpec routeGTFS, SimpleDateFormat gDateFormat) throws ParseException { String previousArrivalTime = null; Integer previousArrivalTimeStopSequence = null; String previousDepartureTime = null; Integer previousDepartureTimeStopSequence = null; String nextArrivalTime = null; Integer nextArrivalTimeStopSequence = null; String nextDepartureTime = null; Integer nextDepartureTimeStopSequence = null; for (GStopTime aStopTime : routeGTFS.getStopTimes(null, gStopTime.getTripId(), null, null)) { if (!gStopTime.getTripId().equals(aStopTime.getTripId())) { continue; } if (aStopTime.getStopSequence() < gStopTime.getStopSequence()) { if (!StringUtils.isEmpty(aStopTime.getDepartureTime())) { if (previousDepartureTime == null || previousDepartureTimeStopSequence == null || previousDepartureTimeStopSequence < aStopTime.getStopSequence()) { previousDepartureTime = aStopTime.getDepartureTime(); previousDepartureTimeStopSequence = aStopTime.getStopSequence(); } } if (!StringUtils.isEmpty(aStopTime.getArrivalTime())) { if (previousArrivalTime == null || previousArrivalTimeStopSequence == null || previousArrivalTimeStopSequence < aStopTime.getStopSequence()) { previousArrivalTime = aStopTime.getArrivalTime(); previousArrivalTimeStopSequence = aStopTime.getStopSequence(); } } } else if (aStopTime.getStopSequence() > gStopTime.getStopSequence()) { if (!StringUtils.isEmpty(aStopTime.getDepartureTime())) { if (nextDepartureTime == null || nextDepartureTimeStopSequence == null || nextDepartureTimeStopSequence > aStopTime.getStopSequence()) { nextDepartureTime = aStopTime.getDepartureTime(); nextDepartureTimeStopSequence = aStopTime.getStopSequence(); } } if (!StringUtils.isEmpty(aStopTime.getArrivalTime())) { if (nextArrivalTime == null || nextArrivalTimeStopSequence == null || nextArrivalTimeStopSequence > aStopTime.getStopSequence()) { nextArrivalTime = aStopTime.getArrivalTime(); nextArrivalTimeStopSequence = aStopTime.getStopSequence(); } } } } long previousArrivalTimeInMs = gDateFormat.parse(previousArrivalTime).getTime(); long previousDepartureTimeInMs = gDateFormat.parse(previousDepartureTime).getTime(); long nextArrivalTimeInMs = gDateFormat.parse(nextArrivalTime).getTime(); long nextDepartureTimeInMs = gDateFormat.parse(nextDepartureTime).getTime(); long arrivalTimeDiffInMs = nextArrivalTimeInMs - previousArrivalTimeInMs; long departureTimeDiffInMs = nextDepartureTimeInMs - previousDepartureTimeInMs; int arrivalNbStop = nextArrivalTimeStopSequence - previousArrivalTimeStopSequence; int departureNbStop = nextDepartureTimeStopSequence - previousDepartureTimeStopSequence; long arrivalTimeBetweenStopInMs = arrivalTimeDiffInMs / arrivalNbStop; long departureTimeBetweenStopInMs = departureTimeDiffInMs / departureNbStop; long arrivalTime = previousArrivalTimeInMs + (arrivalTimeBetweenStopInMs * (gStopTime.getStopSequence() - previousArrivalTimeStopSequence)); long departureTime = previousDepartureTimeInMs + (departureTimeBetweenStopInMs * (gStopTime.getStopSequence() - previousDepartureTimeStopSequence)); return new Pair<Long, Long>(arrivalTime, departureTime); } private static int cleanExtraSeconds(Integer time) { int extraSeconds = time == null ? 0 : time % PRECISON_IN_SECONDS; if (extraSeconds > 0) { // IF too precise DO return cleanTime(time, extraSeconds); } return time; // GTFS standard } private static final String CLEAN_TIME_FORMAT = "%02d"; private static final String CLEAN_TIME_LEADING_ZERO = "0"; private static final String CLEAN_TIME_DEFAULT_MINUTES = "00"; private static final String CLEAN_TIME_DEFAULT_SECONDS = "00"; private static int cleanTime(Integer time, int extraSeconds) { try { String timeS = convertTimeToString(time); String newHours = timeS.substring(0, 2); String newMinutes = timeS.substring(2, 4); String newSeconds = timeS.substring(4, 6); int seconds = Integer.parseInt(newSeconds); if (extraSeconds < 5) { if (extraSeconds > seconds) { newSeconds = CLEAN_TIME_DEFAULT_SECONDS; } else { newSeconds = String.format(CLEAN_TIME_FORMAT, seconds - extraSeconds); } return Integer.parseInt(newHours + newMinutes + newSeconds); } int secondsToAdd = PRECISON_IN_SECONDS - extraSeconds; if (seconds + secondsToAdd < 60) { newSeconds = String.format(CLEAN_TIME_FORMAT, seconds + secondsToAdd); return Integer.parseInt(newHours + newMinutes + newSeconds); } newSeconds = CLEAN_TIME_DEFAULT_SECONDS; int minutes = Integer.parseInt(newMinutes); if (minutes + 1 < 60) { newMinutes = String.format(CLEAN_TIME_FORMAT, minutes + 1); return Integer.parseInt(newHours + newMinutes + newSeconds); } newMinutes = CLEAN_TIME_DEFAULT_MINUTES; newHours = String.valueOf(Integer.parseInt(newHours) + 1); return Integer.parseInt(newHours + newMinutes + newSeconds); } catch (Exception e) { MTLog.log("Error while cleaning time '%s' '%s' !\n", time, extraSeconds); e.printStackTrace(); System.exit(-1); return -1; } } protected static String convertTimeToString(Integer time) { StringBuilder sb = new StringBuilder(time.toString()); while (sb.length() < 6) { sb.insert(0, CLEAN_TIME_LEADING_ZERO); } return sb.toString(); } @Override public int getStartTime(GFrequency gFrequency) { return GSpec.parseTimeString(gFrequency.getStartTime()); // GTFS standard } @Override public int getEndTime(GFrequency gFrequency) { return GSpec.parseTimeString(gFrequency.getEndTime()); // GTFS standard } protected static class Period { Integer todayStringInt = null; Integer startDate = null; Integer endDate = null; @Override public String toString() { return Period.class.getSimpleName() + "{" + "todayStringInt: " + todayStringInt + ", " + "startDate: " + startDate + ", " + "endDate: " + endDate + ", " + "}"; } } @SuppressWarnings("unused") @Deprecated public static HashSet<String> extractUsefulServiceIds(String[] args, DefaultAgencyTools agencyTools) { return extractUsefulServiceIds(args, agencyTools, false); } private static Period usefulPeriod = null; public static HashSet<String> extractUsefulServiceIds(String[] args, DefaultAgencyTools agencyTools, boolean agencyFilter) { MTLog.log("Extracting useful service IDs..."); usefulPeriod = new Period(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); boolean isCurrent = "current_".equalsIgnoreCase(args[2]); boolean isNext = "next_".equalsIgnoreCase(args[2]); boolean isCurrentOrNext = isCurrent || isNext; Calendar c = Calendar.getInstance(); if (!isCurrentOrNext && TOMORROW) { c.add(Calendar.DAY_OF_MONTH, 1); // TOMORROW (too late to publish today's schedule) } usefulPeriod.todayStringInt = Integer.valueOf(DATE_FORMAT.format(c.getTime())); if (!isCurrentOrNext && OVERRIDE_DATE != null) { usefulPeriod.todayStringInt = OVERRIDE_DATE; } GSpec gtfs = GReader.readGtfsZipFile(args[0], agencyTools, !agencyFilter, agencyFilter); if (agencyFilter) { gtfs.cleanupExcludedServiceIds(); } List<GCalendar> gCalendars = gtfs.getAllCalendars(); List<GCalendarDate> gCalendarDates = gtfs.getAllCalendarDates(); printMinMaxDate(gCalendars, gCalendarDates); boolean hasCurrent = false; if (gCalendars != null && gCalendars.size() > 0) { parseCalendars(gCalendars, DATE_FORMAT, c, usefulPeriod, isCurrentOrNext); } else if (gCalendarDates != null && gCalendarDates.size() > 0) { parseCalendarDates(gCalendarDates, DATE_FORMAT, c, usefulPeriod, isCurrentOrNext); } else { MTLog.log("NO schedule available for %s! (1)\n", usefulPeriod.todayStringInt); System.exit(-1); return null; } if (!isNext && (usefulPeriod.startDate == null || usefulPeriod.endDate == null)) { if (isCurrent) { MTLog.log("No CURRENT schedules for %s. (start:%s|end:%s)", usefulPeriod.todayStringInt, usefulPeriod.startDate, usefulPeriod.endDate); System.exit(0); // keeping current schedule return null; } MTLog.log("NO schedule available for %s! (start:%s|end:%s) (isCurrent:%s|isNext:%s)\n", usefulPeriod.todayStringInt, usefulPeriod.startDate, usefulPeriod.endDate, isCurrent, isNext); System.exit(-1); return null; } if (usefulPeriod.todayStringInt != null && usefulPeriod.startDate != null && usefulPeriod.endDate != null) { hasCurrent = true; } MTLog.log("Generated on %s | Schedules from %s to %s.", usefulPeriod.todayStringInt, usefulPeriod.startDate, usefulPeriod.endDate); if (isNext) { if (hasCurrent && !diffLowerThan(DATE_FORMAT, c, usefulPeriod.todayStringInt, usefulPeriod.endDate, MAX_NEXT_LOOKUP_IN_DAYS)) { MTLog.log("Skipping NEXT schedules... (%d days from %s to %s)", TimeUnit.MILLISECONDS.toDays(diffInMs(DATE_FORMAT, c, usefulPeriod.todayStringInt, usefulPeriod.endDate)), usefulPeriod.todayStringInt, usefulPeriod.endDate); usefulPeriod.todayStringInt = null; // reset usefulPeriod.startDate = null; // reset usefulPeriod.endDate = null; // reset gtfs = null; return new HashSet<String>(); // non-null = service IDs } MTLog.log("Looking for NEXT schedules..."); if (hasCurrent) { usefulPeriod.todayStringInt = incDateDays(DATE_FORMAT, c, usefulPeriod.endDate, 1); // start from next to current last date } usefulPeriod.startDate = null; // reset usefulPeriod.endDate = null; // reset if (gCalendars != null && gCalendars.size() > 0) { parseCalendars(gCalendars, DATE_FORMAT, c, usefulPeriod, false); } else if (gCalendarDates != null && gCalendarDates.size() > 0) { parseCalendarDates(gCalendarDates, DATE_FORMAT, c, usefulPeriod, false); } if (usefulPeriod.startDate == null || usefulPeriod.endDate == null) { MTLog.log("NO NEXT schedule available for %s. (start:%s|end:%s)", usefulPeriod.todayStringInt, usefulPeriod.startDate, usefulPeriod.endDate); usefulPeriod.todayStringInt = null; // reset usefulPeriod.startDate = null; // reset usefulPeriod.endDate = null; // reset gtfs = null; return new HashSet<String>(); // non-null = service IDs } MTLog.log("Generated on %s | NEXT Schedules from %s to %s.", usefulPeriod.todayStringInt, usefulPeriod.startDate, usefulPeriod.endDate); } HashSet<String> serviceIds = getPeriodServiceIds(usefulPeriod.startDate, usefulPeriod.endDate, gCalendars, gCalendarDates); improveUsefulPeriod(DATE_FORMAT, c, gCalendars, gCalendarDates); MTLog.log("Extracting useful service IDs... DONE"); gtfs = null; return serviceIds; } private static void improveUsefulPeriod(SimpleDateFormat DATE_FORMAT, Calendar c, List<GCalendar> gCalendars, List<GCalendarDate> gCalendarDates) { if (gCalendars != null && gCalendars.size() > 0 && gCalendarDates != null && gCalendarDates.size() > 0) { boolean newDateFound = false; do { newDateFound = false; int minNewStartDate = incDateDays(DATE_FORMAT, c, usefulPeriod.startDate, -1); for (GCalendarDate gCalendarDate : gCalendarDates) { if (gCalendarDate.isBefore(usefulPeriod.startDate)) { if (gCalendarDate.isBetween(minNewStartDate, usefulPeriod.startDate)) { MTLog.log("new useful period start date '%s' because it's close to previous useful period start date '%s'.", gCalendarDate.getDate(), usefulPeriod.startDate); usefulPeriod.startDate = gCalendarDate.getDate(); newDateFound = true; break; } } } } while (newDateFound); do { newDateFound = false; int minNewEndDate = incDateDays(DATE_FORMAT, c, usefulPeriod.endDate, +1); for (GCalendarDate gCalendarDate : gCalendarDates) { if (gCalendarDate.isAfter(usefulPeriod.endDate)) { if (gCalendarDate.isBetween(usefulPeriod.endDate, minNewEndDate)) { MTLog.log("new useful end date '%s' because it's close to previous useful period end data '%s'.", gCalendarDate.getDate(), usefulPeriod.endDate); usefulPeriod.endDate = gCalendarDate.getDate(); newDateFound = true; break; } } } } while (newDateFound); } } private static void parseCalendarDates(List<GCalendarDate> gCalendarDates, SimpleDateFormat DATE_FORMAT, Calendar c, Period p, boolean keepToday) { HashSet<String> todayServiceIds = findTodayServiceIds(gCalendarDates, DATE_FORMAT, c, p, keepToday ? 0 : 1, 1); if (todayServiceIds == null || todayServiceIds.size() == 0) { MTLog.log("NO schedule available for %s in calendar dates.\n", p.todayStringInt); return; } refreshStartEndDatesFromCalendarDates(p, todayServiceIds, gCalendarDates); while (true) { MTLog.log("Schedules from %s to %s... ", p.startDate, p.endDate); for (GCalendarDate gCalendarDate : gCalendarDates) { if (gCalendarDate.isBetween(p.startDate, p.endDate)) { if (!gCalendarDate.isServiceIds(todayServiceIds)) { MTLog.log("> new service ID from calendar date active on %s between %s and %s: '%s'", gCalendarDate.getDate(), p.startDate, p.endDate, gCalendarDate.getServiceId()); todayServiceIds.add(gCalendarDate.getServiceId()); } } } boolean newDates = refreshStartEndDatesFromCalendarDates(p, todayServiceIds, gCalendarDates); if (newDates) { MTLog.log("> new start date '%s' & end date '%s' from calendar date active during service ID(s).", p.startDate, p.endDate); continue; } if (diffLowerThan(DATE_FORMAT, c, p.startDate, p.endDate, MIN_CALENDAR_DATE_COVERAGE_TOTAL_IN_DAYS)) { p.endDate = incDateDays(DATE_FORMAT, c, p.endDate, 1); // end++ MTLog.log("new end date because coverage lower than %s days: %s", MIN_CALENDAR_DATE_COVERAGE_TOTAL_IN_DAYS, p.endDate); continue; } Period pNext = new Period(); pNext.todayStringInt = incDateDays(DATE_FORMAT, c, p.endDate, 1); HashSet<String> nextDayServiceIds = findTodayServiceIds(gCalendarDates, DATE_FORMAT, c, pNext, 0, 1); refreshStartEndDatesFromCalendarDates(pNext, nextDayServiceIds, gCalendarDates); if (pNext.startDate != null && pNext.endDate != null && diffLowerThan(DATE_FORMAT, c, pNext.startDate, pNext.endDate, MIN_PREVIOUS_NEXT_ADDED_DAYS)) { p.endDate = pNext.endDate; MTLog.log("> new end date '%s' because next day has own service ID(s)", p.endDate); continue; } Period pPrevious = new Period(); pPrevious.todayStringInt = incDateDays(DATE_FORMAT, c, p.startDate, -1); HashSet<String> previousDayServiceIds = findTodayServiceIds(gCalendarDates, DATE_FORMAT, c, pPrevious, 0, -1); refreshStartEndDatesFromCalendarDates(pPrevious, previousDayServiceIds, gCalendarDates); if (pPrevious.startDate != null && pPrevious.endDate != null && diffLowerThan(DATE_FORMAT, c, pPrevious.startDate, pPrevious.endDate, MIN_PREVIOUS_NEXT_ADDED_DAYS)) { p.startDate = pPrevious.startDate; MTLog.log("> new start date '%s' because previous day has own service ID(s)", p.startDate); continue; } break; } } private static boolean refreshStartEndDatesFromCalendarDates(Period p, HashSet<String> todayServiceIds, List<GCalendarDate> gCalendarDates) { boolean newDates = false; for (GCalendarDate gCalendarDate : gCalendarDates) { if (gCalendarDate.isServiceIds(todayServiceIds)) { if (p.startDate == null || gCalendarDate.isBefore(p.startDate)) { p.startDate = gCalendarDate.getDate(); newDates = true; } if (p.endDate == null || gCalendarDate.isAfter(p.endDate)) { p.endDate = gCalendarDate.getDate(); newDates = true; } } } return newDates; } private static HashSet<String> findTodayServiceIds(List<GCalendarDate> gCalendarDates, SimpleDateFormat DATE_FORMAT, Calendar c, Period p, int minSize, int incDays) { HashSet<String> todayServiceIds = new HashSet<String>(); final int initialTodayStringInt = p.todayStringInt; while (true) { for (GCalendarDate gCalendarDate : gCalendarDates) { if (gCalendarDate.is(p.todayStringInt)) { if (!gCalendarDate.isServiceIds(todayServiceIds)) { todayServiceIds.add(gCalendarDate.getServiceId()); } } } if (todayServiceIds.size() < minSize && diffLowerThan(DATE_FORMAT, c, initialTodayStringInt, p.todayStringInt, MAX_LOOKUP_IN_DAYS)) { p.todayStringInt = incDateDays(DATE_FORMAT, c, p.todayStringInt, incDays); MTLog.log("new today because not enough service today: %s (initial today: %s, min: %s)", p.todayStringInt, initialTodayStringInt, minSize); continue; } break; } return todayServiceIds; } private static void parseCalendars(List<GCalendar> gCalendars, SimpleDateFormat DATE_FORMAT, Calendar c, Period p, boolean keepToday) { final int initialTodayStringInt = p.todayStringInt; boolean newDates; while (true) { for (GCalendar gCalendar : gCalendars) { if (gCalendar.containsDate(p.todayStringInt)) { if (p.startDate == null || gCalendar.startsBefore(p.startDate)) { MTLog.log("new start date from calendar active on %s: %s (was: %s)", p.todayStringInt, gCalendar.getStartDate(), p.startDate); p.startDate = gCalendar.getStartDate(); newDates = true; } if (p.endDate == null || gCalendar.endsAfter(p.endDate)) { MTLog.log("new end date from calendar active on %s: %s (was: %s)", p.todayStringInt, gCalendar.getEndDate(), p.endDate); p.endDate = gCalendar.getEndDate(); newDates = true; } } } if (!keepToday && (p.startDate == null || p.endDate == null) && diffLowerThan(DATE_FORMAT, c, initialTodayStringInt, p.todayStringInt, MAX_LOOKUP_IN_DAYS)) { p.todayStringInt = incDateDays(DATE_FORMAT, c, p.todayStringInt, 1); MTLog.log("new today because no service today: %s (initial today: %s)", p.todayStringInt, initialTodayStringInt); //noinspection UnnecessaryContinue continue; } else { break; } } if (p.startDate == null || p.endDate == null) { MTLog.log("NO schedule available for %s in calendars. (start:%s|end:%s)\n", p.todayStringInt, p.startDate, p.endDate); return; } while (true) { MTLog.log("Schedules from %s to %s... ", p.startDate, p.endDate); newDates = false; for (GCalendar gCalendar : gCalendars) { if (gCalendar.isOverlapping(p.startDate, p.endDate)) { if (p.startDate == null || gCalendar.startsBefore(p.startDate)) { MTLog.log("new start date from calendar active between %s and %s: %s (was: %s)", p.startDate, p.endDate, gCalendar.getStartDate(), p.startDate); p.startDate = gCalendar.getStartDate(); newDates = true; } if (p.endDate == null || gCalendar.endsAfter(p.endDate)) { MTLog.log("new end date from calendar active between %s and %s: %s (was: %s)", p.startDate, p.endDate, gCalendar.getEndDate(), p.endDate); p.endDate = gCalendar.getEndDate(); newDates = true; } } } if (newDates) { continue; } Period pNext = new Period(); pNext.todayStringInt = incDateDays(DATE_FORMAT, c, p.endDate, 1); findDayServiceIdsPeriod(gCalendars, pNext); if (pNext.startDate != null && pNext.endDate != null && diffLowerThan(DATE_FORMAT, c, pNext.startDate, pNext.endDate, MIN_PREVIOUS_NEXT_ADDED_DAYS)) { p.endDate = pNext.endDate; MTLog.log("new end date '%s' because next day has own service ID(s)", p.endDate); continue; } Period pPrevious = new Period(); pPrevious.todayStringInt = incDateDays(DATE_FORMAT, c, p.startDate, -1); findDayServiceIdsPeriod(gCalendars, pPrevious); if (keepToday // NOT next schedule, only current schedule can look behind && pPrevious.startDate != null && pPrevious.endDate != null && diffLowerThan(DATE_FORMAT, c, pPrevious.startDate, pPrevious.endDate, MIN_PREVIOUS_NEXT_ADDED_DAYS)) { p.startDate = pPrevious.startDate; MTLog.log("new start date '%s' because previous day has own service ID(s)", p.startDate); continue; } if (diffLowerThan(DATE_FORMAT, c, p.startDate, p.endDate, MIN_CALENDAR_COVERAGE_TOTAL_IN_DAYS)) { long nextPeriodCoverageInMs = pNext.startDate == null || pNext.endDate == null ? 0L : diffInMs(DATE_FORMAT, c, pNext.startDate, pNext.endDate); long previousPeriodCoverageInMs = pPrevious.startDate == null || pPrevious.endDate == null ? 0L : diffInMs(DATE_FORMAT, c, pPrevious.startDate, pPrevious.endDate); if (keepToday // NOT next schedule, only current schedule can look behind && previousPeriodCoverageInMs > 0L && previousPeriodCoverageInMs < nextPeriodCoverageInMs) { p.startDate = incDateDays(DATE_FORMAT, c, p.startDate, -1); // start-- MTLog.log("new start date because coverage lower than %s days: %s", MIN_CALENDAR_COVERAGE_TOTAL_IN_DAYS, p.startDate); } else { p.endDate = incDateDays(DATE_FORMAT, c, p.endDate, 1); // end++ MTLog.log("new end date because coverage lower than %s days: %s", MIN_CALENDAR_COVERAGE_TOTAL_IN_DAYS, p.endDate); } continue; } break; } } static void findDayServiceIdsPeriod(List<GCalendar> gCalendars, Period p) { boolean newDates; while (true) { newDates = false; for (GCalendar gCalendar : gCalendars) { if (gCalendar.containsDate(p.todayStringInt)) { if (p.startDate == null || gCalendar.startsBefore(p.startDate)) { MTLog.log(">> new start date from calendar active on %s: %s (was: %s)", p.todayStringInt, gCalendar.getStartDate(), p.startDate); p.startDate = gCalendar.getStartDate(); newDates = true; } if (p.endDate == null || gCalendar.endsAfter(p.endDate)) { MTLog.log(">> new end date from calendar active on %s: %s (was: %s)", p.todayStringInt, gCalendar.getEndDate(), p.endDate); p.endDate = gCalendar.getEndDate(); newDates = true; } } } if (newDates) { continue; } break; } if (p.startDate == null || p.endDate == null) { MTLog.log(">> NO schedule available for %s in calendars. (start:%s|end:%s)", p.todayStringInt, p.startDate, p.endDate); return; } while (true) { MTLog.log(">> Schedules from %s to %s... ", p.startDate, p.endDate); newDates = false; for (GCalendar gCalendar : gCalendars) { if (gCalendar.isOverlapping(p.startDate, p.endDate)) { if (p.startDate == null || gCalendar.startsBefore(p.startDate)) { MTLog.log(">> new start date from calendar active between %s and %s: %s (was: %s)", p.startDate, p.endDate, gCalendar.getStartDate(), p.startDate); p.startDate = gCalendar.getStartDate(); newDates = true; } if (p.endDate == null || gCalendar.endsAfter(p.endDate)) { MTLog.log(">> new end date from calendar active between %s and %s: %s (was: %s)", p.startDate, p.endDate, gCalendar.getEndDate(), p.endDate); p.endDate = gCalendar.getEndDate(); newDates = true; } } } if (newDates) { continue; } break; } } private static HashSet<String> getPeriodServiceIds(Integer startDate, Integer endDate, List<GCalendar> gCalendars, List<GCalendarDate> gCalendarDates) { HashSet<String> serviceIds = new HashSet<String>(); if (gCalendars != null) { for (GCalendar gCalendar : gCalendars) { if (gCalendar.isInside(startDate, endDate)) { if (!gCalendar.isServiceIds(serviceIds)) { MTLog.log("new service ID from calendar active between %s and %s: %s", startDate, endDate, gCalendar.getServiceId()); serviceIds.add(gCalendar.getServiceId()); } } } } if (gCalendarDates != null) { for (GCalendarDate gCalendarDate : gCalendarDates) { if (gCalendarDate.isBetween(startDate, endDate)) { if (!gCalendarDate.isServiceIds(serviceIds)) { if (gCalendarDate.getExceptionType() == GCalendarDatesExceptionType.SERVICE_REMOVED) { MTLog.log("ignored service ID from calendar date active between %s and %s: %s (SERVICE REMOVED)", startDate, endDate, gCalendarDate.getServiceId()); continue; } MTLog.log("new service ID from calendar date active between %s and %s: %s", startDate, endDate, gCalendarDate.getServiceId()); serviceIds.add(gCalendarDate.getServiceId()); } } } } MTLog.log("Service IDs: %s", serviceIds); return serviceIds; } private static void printMinMaxDate(List<GCalendar> gCalendars, List<GCalendarDate> gCalendarDates) { Period p = new Period(); if (gCalendars != null && gCalendars.size() > 0) { for (GCalendar gCalendar : gCalendars) { if (p.startDate == null || gCalendar.startsBefore(p.startDate)) { p.startDate = gCalendar.getStartDate(); } if (p.endDate == null || gCalendar.endsAfter(p.endDate)) { p.endDate = gCalendar.getEndDate(); } } } if (gCalendarDates != null && gCalendarDates.size() > 0) { for (GCalendarDate gCalendarDate : gCalendarDates) { if (p.startDate == null || gCalendarDate.isBefore(p.startDate)) { p.startDate = gCalendarDate.getDate(); } if (p.endDate == null || gCalendarDate.isAfter(p.endDate)) { p.endDate = gCalendarDate.getDate(); } } } MTLog.log("Schedule available from %s to %s.", p.startDate, p.endDate); } private static int incDateDays(SimpleDateFormat dateFormat, Calendar calendar, int dateInt, int numberOfDays) { try { calendar.setTime(dateFormat.parse(String.valueOf(dateInt))); calendar.add(Calendar.DAY_OF_MONTH, numberOfDays); return Integer.parseInt(dateFormat.format(calendar.getTime())); } catch (Exception e) { MTLog.log("Error while increasing end date!\n"); e.printStackTrace(); System.exit(-1); return -1; } } private static boolean diffLowerThan(SimpleDateFormat dateFormat, Calendar calendar, int startDateInt, int endDateInt, int diffInDays) { try { return diffInMs(dateFormat, calendar, startDateInt, endDateInt) < TimeUnit.DAYS.toMillis(diffInDays); } catch (Exception e) { MTLog.log("Error while checking date difference!\n"); e.printStackTrace(); System.exit(-1); return false; } } private static long diffInMs(SimpleDateFormat dateFormat, Calendar calendar, int startDateInt, int endDateInt) { try { calendar.setTime(dateFormat.parse(String.valueOf(startDateInt))); long startDateInMs = calendar.getTimeInMillis(); calendar.setTime(dateFormat.parse(String.valueOf(endDateInt))); long endDateInMs = calendar.getTimeInMillis(); return endDateInMs - startDateInMs; } catch (Exception e) { MTLog.log("Error while checking date difference!\n"); e.printStackTrace(); System.exit(-1); return -1L; } } public static boolean excludeUselessCalendar(GCalendar gCalendar, HashSet<String> serviceIds) { if (serviceIds != null) { boolean knownServiceId = gCalendar.isServiceIds(serviceIds); if (!knownServiceId) { return true; // exclude } } return false; // keep } public static boolean excludeUselessCalendarDate(GCalendarDate gCalendarDate, HashSet<String> serviceIds) { if (serviceIds != null) { boolean knownServiceId = gCalendarDate.isServiceIds(serviceIds); if (!knownServiceId) { return true; // exclude } } if (usefulPeriod != null) { if (gCalendarDate.getExceptionType() == GCalendarDatesExceptionType.SERVICE_ADDED) { if (gCalendarDate.isBefore(usefulPeriod.startDate) || gCalendarDate.isAfter(usefulPeriod.endDate)) { MTLog.log("Exclude calendar date \"%s\" because it's out of the useful period (start:%s|end:%s).", gCalendarDate, usefulPeriod.startDate, usefulPeriod.endDate); return true; // exclude } } } return false; // keep } public static boolean excludeUselessTrip(GTrip gTrip, HashSet<String> serviceIds) { if (serviceIds != null) { boolean knownServiceId = gTrip.isServiceIds(serviceIds); if (!knownServiceId) { return true; // exclude } } return false; // keep } }
package seedu.todo.guitests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import org.junit.Test; public class ConsoleTest extends GuiTest { @Test public void testValidCommand_consoleInputCleared() { console.runCommand("list"); assertEquals(console.getConsoleInputText(), ""); } @Test public void testInvalidCommand_consoleInputRemains() { console.runCommand("invalidcommand"); assertNotEquals(console.getConsoleInputText(), ""); } }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("JPET Store Application"); System.out.println("Class name: Calculate.java"); System.out.println("Hello World"); System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Thu Apr 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Tue Apr 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Sun Apr 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Thu Mar 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Tue Mar 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Sun Mar 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Fri Mar 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Wed Mar 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Mon Mar 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Sat Mar 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Thu Mar 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Tue Mar 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Sun Mar 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Fri Mar 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Wed Mar 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Mon Mar 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Sat Mar 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Thu Mar 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Tue Feb 28 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Sun Feb 26 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Fri Feb 24 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Wed Feb 22 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Mon Feb 20 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Sat Feb 18 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Thu Feb 16 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Tue Feb 14 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Sun Feb 12 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Fri Feb 10 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Wed Feb 8 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Mon Feb 6 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Sat Feb 4 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Thu Feb 2 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Mon Jan 30 11:00:00 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Sat Jan 28 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Thu Jan 26 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Tue Jan 24 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Sun Jan 22 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Fri Jan 20 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Wed Jan 18 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Mon Jan 16 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Sat Jan 14 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Thu Jan 12 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Tue Jan 10 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Sun Jan 8 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Fri Jan 6 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Wed Jan 4 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Mon Jan 2 11:00:15 UTC 2017"); System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Fri Dec 30 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Wed Dec 28 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Mon Dec 26 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Sat Dec 24 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Thu Dec 22 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Tue Dec 20 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Sun Dec 18 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Fri Dec 16 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Wed Dec 14 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Mon Dec 12 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Sat Dec 10 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Thu Dec 8 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Tue Dec 6 11:00:16 UTC 2016"); System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016"); System.out.println("Fri Dec 2 12:52:58 UTC 2016"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // 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 GNU // 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 net.sourceforge.jtds.jdbc; import java.sql.*; import java.math.BigDecimal; import junit.framework.TestSuite; import java.io.*; import net.sourceforge.jtds.util.Logger; /** * @author * Alin Sinpalean, Holger Rehn */ public class CSUnitTest extends DatabaseTestCase { static PrintStream output = null; public CSUnitTest( String name ) { super( name ); if( output == null ) { try { output = new PrintStream( new FileOutputStream( "nul" ) ); } catch( FileNotFoundException ex ) { throw new RuntimeException( "could not create device nul" ); } } } public static void main( String args[] ) { Logger.setActive( true ); if( args.length > 0 ) { output = System.out; junit.framework.TestSuite s = new TestSuite(); for( int i = 0; i < args.length; i++ ) { s.addTest( new CSUnitTest( args[i] ) ); } junit.textui.TestRunner.run( s ); } else { junit.textui.TestRunner.run( CSUnitTest.class ); } } public void testMaxRows0003() throws Exception { final int ROWCOUNT = 200; final int ROWLIMIT = 123; dropTable( "#t0003" ); Statement stmt = con.createStatement(); stmt.executeUpdate( "create table #t0003 ( i int )" ); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "insert into #t0003 values (?)" ); for( int i = 1; i <= ROWCOUNT; i ++ ) { pstmt.setInt( 1, i ); assertEquals( 1, pstmt.executeUpdate() ); } pstmt.close(); pstmt = con.prepareStatement( "select i from #t0003 order by i" ); pstmt.setMaxRows( ROWLIMIT ); assertEquals( ROWLIMIT, pstmt.getMaxRows() ); ResultSet rs = pstmt.executeQuery(); int count = 0; while( rs.next() ) { assertEquals( ++ count, rs.getInt( "i" ) ); } pstmt.close(); assertEquals( ROWLIMIT, count ); } public void testGetAsciiStream0018() throws Exception { Statement stmt = con.createStatement(); ResultSet rs; String bigtext1 = "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + "abcdefghijklmnop" + ""; String bigimage1 = "0x" + "0123456789abcdef" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + "fedcba9876543210" + ""; dropTable("#t0018"); String sql = "create table #t0018 ( " + " mybinary binary(5) not null, " + " myvarbinary varbinary(4) not null, " + " mychar char(10) not null, " + " myvarchar varchar(8) not null, " + " mytext text not null, " + " myimage image not null, " + " mynullbinary binary(3) null, " + " mynullvarbinary varbinary(6) null, " + " mynullchar char(10) null, " + " mynullvarchar varchar(40) null, " + " mynulltext text null, " + " mynullimage image null) "; assertEquals(stmt.executeUpdate(sql), 0); // Insert a row without nulls via a Statement sql = "insert into #t0018( " + " mybinary, " + " myvarbinary, " + " mychar, " + " myvarchar, " + " mytext, " + " myimage, " + " mynullbinary, " + " mynullvarbinary, " + " mynullchar, " + " mynullvarchar, " + " mynulltext, " + " mynullimage " + ") " + "values( " + " 0xffeeddccbb, " + // mybinary " 0x78, " + // myvarbinary " 'Z', " + // mychar " '', " + // myvarchar " '" + bigtext1 + "', " + // mytext " " + bigimage1 + ", " + // myimage " null, " + // mynullbinary " null, " + // mynullvarbinary " null, " + // mynullchar " null, " + // mynullvarchar " null, " + // mynulltext " null " + // mynullimage ")"; assertEquals(stmt.executeUpdate(sql), 1); sql = "select * from #t0018"; rs = stmt.executeQuery(sql); if (!rs.next()) { fail("should get Result"); } else { output.println("Getting the results"); output.println("mybinary is " + rs.getObject("mybinary")); output.println("myvarbinary is " + rs.getObject("myvarbinary")); output.println("mychar is " + rs.getObject("mychar")); output.println("myvarchar is " + rs.getObject("myvarchar")); output.println("mytext is " + rs.getObject("mytext")); output.println("myimage is " + rs.getObject("myimage")); output.println("mynullbinary is " + rs.getObject("mynullbinary")); output.println("mynullvarbinary is " + rs.getObject("mynullvarbinary")); output.println("mynullchar is " + rs.getObject("mynullchar")); output.println("mynullvarchar is " + rs.getObject("mynullvarchar")); output.println("mynulltext is " + rs.getObject("mynulltext")); output.println("mynullimage is " + rs.getObject("mynullimage")); } stmt.close(); } public void testMoneyHandling0019() throws Exception { java.sql.Statement stmt; int i; BigDecimal money[] = { new BigDecimal("922337203685477.5807"), new BigDecimal("-922337203685477.5807"), new BigDecimal("1.0000"), new BigDecimal("0.0000"), new BigDecimal("-1.0000") }; BigDecimal smallmoney[] = { new BigDecimal("214748.3647"), new BigDecimal("-214748.3648"), new BigDecimal("1.0000"), new BigDecimal("0.0000"), new BigDecimal("-1.0000") }; if (smallmoney.length != money.length) { throw new SQLException("Must have same number of elements in " + "money and smallmoney"); } stmt = con.createStatement(); dropTable("#t0019"); stmt.executeUpdate("create table #t0019 ( " + " i integer primary key, " + " mymoney money not null, " + " mysmallmoney smallmoney not null) " + ""); for (i=0; i<money.length; i++) { stmt.executeUpdate("insert into #t0019 values (" + i + ", " + money[i] + ", " + smallmoney[i] + ") "); } // long l = System.currentTimeMillis(); // while (l + 500 > System.currentTimeMillis()) ; ResultSet rs = stmt.executeQuery("select * from #t0019 order by i"); for (i=0; rs.next(); i++) { BigDecimal m; BigDecimal sm; m = (BigDecimal)rs.getObject("mymoney"); sm = (BigDecimal)rs.getObject("mysmallmoney"); assertEquals(m, money[i]); assertEquals(sm, smallmoney[i]); output.println(m + ", " + sm); } stmt.close(); } /* public void testBooleanAndCompute0026() throws Exception { Statement stmt = con.createStatement(); dropTable("#t0026"); int count = stmt.executeUpdate("create table #t0026 " + " (i integer, " + " b bit, " + " s char(5), " + " f float) "); output.println("Creating table affected " + count + " rows"); stmt.executeUpdate("insert into #t0026 values(0, 0, 'false', 0.0)"); stmt.executeUpdate("insert into #t0026 values(0, 0, 'N', 10)"); stmt.executeUpdate("insert into #t0026 values(1, 1, 'true', 7.0)"); stmt.executeUpdate("insert into #t0026 values(2, 1, 'Y', -5.0)"); ResultSet rs = stmt.executeQuery( "select * from #t0026 order by i compute sum(f) by i"); assertTrue(rs.next()); assertTrue(!(rs.getBoolean("i") || rs.getBoolean("b") || rs.getBoolean("s") || rs.getBoolean("f"))); assertTrue(rs.next()); assertTrue(!(rs.getBoolean("i") || rs.getBoolean("b") || rs.getBoolean("s") || rs.getBoolean("f"))); assertTrue(rs.next()); assertTrue(rs.getBoolean("i") && rs.getBoolean("b") && rs.getBoolean("s") && rs.getBoolean("f")); assertTrue(rs.next()); assertTrue(rs.getBoolean("i") && rs.getBoolean("b") && rs.getBoolean("s") && rs.getBoolean("f")); ResultSet rs = stmt.executeQuery( "select * from #t0026 order by i compute sum(f) by i"); if (!rs.next()) { throw new SQLException("Failed"); } passed = passed && (! (rs.getBoolean("i") || rs.getBoolean("b") || rs.getBoolean("s") || rs.getBoolean("f"))); if (!rs.next()) { throw new SQLException("Failed"); } passed = passed && (! (rs.getBoolean("i") || rs.getBoolean("b") || rs.getBoolean("s") || rs.getBoolean("f"))); if (!rs.next()) { throw new SQLException("Failed"); } passed = passed && (rs.getBoolean("i") && rs.getBoolean("b") && rs.getBoolean("s") && rs.getBoolean("f")); if (!rs.next()) { throw new SQLException("Failed"); } passed = passed && (rs.getBoolean("i") && rs.getBoolean("b") && rs.getBoolean("s") && rs.getBoolean("f")); assertTrue(passed); } */ public void testDataTypes0027() throws Exception { output.println("Test all the SQLServer datatypes in Statement\n" + "and PreparedStatement using the preferred getXXX()\n" + "instead of getObject like #t0017.java does."); output.println("!!!Note- This test is not fully implemented yet!!!"); Statement stmt = con.createStatement(); ResultSet rs; stmt.execute("set dateformat ymd"); dropTable("#t0027"); String sql = "create table #t0027 ( " + " mybinary binary(5) not null, " + " myvarbinary varbinary(4) not null, " + " mychar char(10) not null, " + " myvarchar varchar(8) not null, " + " mydatetime datetime not null, " + " mysmalldatetime smalldatetime not null, " + " mydecimal10_3 decimal(10,3) not null, " + " mynumeric5_4 numeric (5,4) not null, " + " myfloat6 float(6) not null, " + " myfloat14 float(6) not null, " + " myreal real not null, " + " myint int not null, " + " mysmallint smallint not null, " + " mytinyint tinyint not null, " + " mymoney money not null, " + " mysmallmoney smallmoney not null, " + " mybit bit not null, " + " mytimestamp timestamp not null, " + " mytext text not null, " + " myimage image not null, " + " mynullbinary binary(3) null, " + " mynullvarbinary varbinary(6) null, " + " mynullchar char(10) null, " + " mynullvarchar varchar(40) null, " + " mynulldatetime datetime null, " + " mynullsmalldatetime smalldatetime null, " + " mynulldecimal10_3 decimal(10,3) null, " + " mynullnumeric15_10 numeric(15,10) null, " + " mynullfloat6 float(6) null, " + " mynullfloat14 float(14) null, " + " mynullreal real null, " + " mynullint int null, " + " mynullsmallint smallint null, " + " mynulltinyint tinyint null, " + " mynullmoney money null, " + " mynullsmallmoney smallmoney null, " + " mynulltext text null, " + " mynullimage image null) "; assertEquals(stmt.executeUpdate(sql), 0); // Insert a row without nulls via a Statement sql = "insert into #t0027 " + " (mybinary, " + " myvarbinary, " + " mychar, " + " myvarchar, " + " mydatetime, " + " mysmalldatetime, " + " mydecimal10_3, " + " mynumeric5_4, " + " myfloat6, " + " myfloat14, " + " myreal, " + " myint, " + " mysmallint, " + " mytinyint, " + " mymoney, " + " mysmallmoney, " + " mybit, " + " mytimestamp, " + " mytext, " + " myimage, " + " mynullbinary, " + " mynullvarbinary, " + " mynullchar, " + " mynullvarchar, " + " mynulldatetime, " + " mynullsmalldatetime, " + " mynulldecimal10_3, " + " mynullnumeric15_10, " + " mynullfloat6, " + " mynullfloat14, " + " mynullreal, " + " mynullint, " + " mynullsmallint, " + " mynulltinyint, " + " mynullmoney, " + " mynullsmallmoney, " + " mynulltext, " + " mynullimage) " + " values " + " (0x1213141516, " + // mybinary, " 0x1718191A, " + // myvarbinary " '1234567890', " + // mychar " '12345678', " + // myvarchar " '19991015 21:29:59.01', " + // mydatetime " '19991015 20:45', " + // mysmalldatetime " 1234567.089, " + // mydecimal10_3 " 1.2345, " + // mynumeric5_4 " 65.4321, " + // myfloat6 " 1.123456789, " + // myfloat14 " 987654321.0, " + // myreal " 4097, " + // myint " 4094, " + // mysmallint " 200, " + // mytinyint " 19.95, " + // mymoney " 9.97, " + // mysmallmoney " 1, " + // mybit " null, " + // mytimestamp " 'abcdefg', " + // mytext " 0x0AAABB, " + // myimage " 0x123456, " + // mynullbinary " 0xAB, " + // mynullvarbinary " 'z', " + // mynullchar " 'zyx', " + // mynullvarchar " '1976-07-04 12:00:00.04', " + // mynulldatetime " '2000-02-29 13:46', " + // mynullsmalldatetime " 1.23, " + // mynulldecimal10_3 " 7.1234567891, " + // mynullnumeric15_10 " 987654, " + // mynullfloat6 " 0, " + // mynullfloat14 " -1.1, " + // mynullreal " -10, " + // mynullint " 126, " + // mynullsmallint " 7, " + // mynulltinyint " -19999.00, " + // mynullmoney " -9.97, " + // mynullsmallmoney " '1234', " + // mynulltext " 0x1200340056) " + // mynullimage) ""; assertEquals(stmt.executeUpdate(sql), 1); sql = "select * from #t0027"; rs = stmt.executeQuery(sql); assertTrue(rs.next()); output.println("mybinary is " + rs.getObject("mybinary")); output.println("myvarbinary is " + rs.getObject("myvarbinary")); output.println("mychar is " + rs.getString("mychar")); output.println("myvarchar is " + rs.getString("myvarchar")); output.println("mydatetime is " + rs.getTimestamp("mydatetime")); output.println("mysmalldatetime is " + rs.getTimestamp("mysmalldatetime")); output.println("mydecimal10_3 is " + rs.getObject("mydecimal10_3")); output.println("mynumeric5_4 is " + rs.getObject("mynumeric5_4")); output.println("myfloat6 is " + rs.getDouble("myfloat6")); output.println("myfloat14 is " + rs.getDouble("myfloat14")); output.println("myreal is " + rs.getDouble("myreal")); output.println("myint is " + rs.getInt("myint")); output.println("mysmallint is " + rs.getShort("mysmallint")); output.println("mytinyint is " + rs.getShort("mytinyint")); output.println("mymoney is " + rs.getObject("mymoney")); output.println("mysmallmoney is " + rs.getObject("mysmallmoney")); output.println("mybit is " + rs.getObject("mybit")); output.println("mytimestamp is " + rs.getObject("mytimestamp")); output.println("mytext is " + rs.getObject("mytext")); output.println("myimage is " + rs.getObject("myimage")); output.println("mynullbinary is " + rs.getObject("mynullbinary")); output.println("mynullvarbinary is " + rs.getObject("mynullvarbinary")); output.println("mynullchar is " + rs.getString("mynullchar")); output.println("mynullvarchar is " + rs.getString("mynullvarchar")); output.println("mynulldatetime is " + rs.getTimestamp("mynulldatetime")); output.println("mynullsmalldatetime is " + rs.getTimestamp("mynullsmalldatetime")); output.println("mynulldecimal10_3 is " + rs.getObject("mynulldecimal10_3")); output.println("mynullnumeric15_10 is " + rs.getObject("mynullnumeric15_10")); output.println("mynullfloat6 is " + rs.getDouble("mynullfloat6")); output.println("mynullfloat14 is " + rs.getDouble("mynullfloat14")); output.println("mynullreal is " + rs.getDouble("mynullreal")); output.println("mynullint is " + rs.getInt("mynullint")); output.println("mynullsmallint is " + rs.getShort("mynullsmallint")); output.println("mynulltinyint is " + rs.getByte("mynulltinyint")); output.println("mynullmoney is " + rs.getObject("mynullmoney")); output.println("mynullsmallmoney is " + rs.getObject("mynullsmallmoney")); output.println("mynulltext is " + rs.getObject("mynulltext")); output.println("mynullimage is " + rs.getObject("mynullimage")); stmt.close(); } public void testCallStoredProcedures0028() throws Exception { Statement stmt = con.createStatement(); ResultSet rs; boolean isResultSet; int updateCount; int resultSetCount=0; int rowCount=0; int numberOfUpdates=0; isResultSet = stmt.execute("EXEC sp_who"); output.println("execute(EXEC sp_who) returned: " + isResultSet); updateCount=stmt.getUpdateCount(); while (isResultSet || (updateCount!=-1)) { if (isResultSet) { resultSetCount++; rs = stmt.getResultSet(); ResultSetMetaData rsMeta = rs.getMetaData(); int columnCount = rsMeta.getColumnCount(); output.println("columnCount: " + Integer.toString(columnCount)); for (int n=1; n<= columnCount; n++) { output.println(Integer.toString(n) + ": " + rsMeta.getColumnName(n)); } while (rs.next()) { rowCount++; for (int n=1; n<= columnCount; n++) { output.println(Integer.toString(n) + ": " + rs.getString(n)); } } } else { numberOfUpdates += updateCount; output.println("UpdateCount: " + Integer.toString(updateCount)); } isResultSet=stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); } stmt.close(); output.println("resultSetCount: " + resultSetCount); output.println("Total rowCount: " + rowCount); output.println("Number of updates: " + numberOfUpdates); assertTrue((rowCount>=1) && (numberOfUpdates==0) && (resultSetCount==1)); } public void testxx0029() throws Exception { Statement stmt = con.createStatement(); ResultSet rs; boolean isResultSet; int updateCount; int resultSetCount=0; int rowCount=0; int numberOfUpdates=0; output.println("before execute DROP PROCEDURE"); try { isResultSet =stmt.execute("DROP PROCEDURE #t0029_p1"); updateCount = stmt.getUpdateCount(); do { output.println("DROP PROCEDURE isResultSet: " + isResultSet); output.println("DROP PROCEDURE updateCount: " + updateCount); isResultSet = stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); } while (((updateCount!=-1) && !isResultSet) || isResultSet); } catch (SQLException e) { } try { isResultSet =stmt.execute("DROP PROCEDURE #t0029_p2"); updateCount = stmt.getUpdateCount(); do { output.println("DROP PROCEDURE isResultSet: " + isResultSet); output.println("DROP PROCEDURE updateCount: " + updateCount); isResultSet = stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); } while (((updateCount!=-1) && !isResultSet) || isResultSet); } catch (SQLException e) { } dropTable("#t0029_t1"); isResultSet = stmt.execute( " create table #t0029_t1 " + " (t1 datetime not null, " + " t2 datetime null, " + " t3 smalldatetime not null, " + " t4 smalldatetime null, " + " t5 text null) "); updateCount = stmt.getUpdateCount(); do { output.println("CREATE TABLE isResultSet: " + isResultSet); output.println("CREATE TABLE updateCount: " + updateCount); isResultSet = stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); } while (((updateCount!=-1) && !isResultSet) || isResultSet); isResultSet = stmt.execute( "CREATE PROCEDURE #t0029_p1 AS " + " insert into #t0029_t1 values " + " ('1999-01-07', '1998-09-09 15:35:05', " + " getdate(), '1998-09-09 15:35:00', null) " + " update #t0029_t1 set t1='1999-01-01' " + " insert into #t0029_t1 values " + " ('1999-01-08', '1998-09-09 15:35:05', " + " getdate(), '1998-09-09 15:35:00','456') " + " update #t0029_t1 set t2='1999-01-02' " + " declare @ptr varbinary(16) " + " select @ptr=textptr(t5) from #t0029_t1 " + " where t1='1999-01-08' " + " writetext #t0029_t1.t5 @ptr with log '123' "); updateCount = stmt.getUpdateCount(); do { output.println("CREATE PROCEDURE isResultSet: " + isResultSet); output.println("CREATE PROCEDURE updateCount: " + updateCount); isResultSet = stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); } while (((updateCount!=-1) && !isResultSet) || isResultSet); isResultSet = stmt.execute( "CREATE PROCEDURE #t0029_p2 AS " + " set nocount on " + " EXEC #t0029_p1 " + " SELECT * FROM #t0029_t1 "); updateCount = stmt.getUpdateCount(); do { output.println("CREATE PROCEDURE isResultSet: " + isResultSet); output.println("CREATE PROCEDURE updateCount: " + updateCount); isResultSet = stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); } while (((updateCount!=-1) && !isResultSet) || isResultSet); isResultSet = stmt.execute( "EXEC #t0029_p2 "); output.println("execute(EXEC #t0029_p2) returned: " + isResultSet); updateCount=stmt.getUpdateCount(); while (isResultSet || (updateCount!=-1)) { if (isResultSet) { resultSetCount++; rs = stmt.getResultSet(); ResultSetMetaData rsMeta = rs.getMetaData(); int columnCount = rsMeta.getColumnCount(); output.println("columnCount: " + Integer.toString(columnCount)); for (int n=1; n<= columnCount; n++) { output.println(Integer.toString(n) + ": " + rsMeta.getColumnName(n)); } while (rs.next()) { rowCount++; for (int n=1; n<= columnCount; n++) { output.println(Integer.toString(n) + ": " + rs.getString(n)); } } } else { numberOfUpdates += updateCount; output.println("UpdateCount: " + Integer.toString(updateCount)); } isResultSet=stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); } stmt.close(); output.println("resultSetCount: " + resultSetCount); output.println("Total rowCount: " + rowCount); output.println("Number of updates: " + numberOfUpdates); assertTrue((resultSetCount==1) && (rowCount==2) && (numberOfUpdates==0)); } public void testDataTypesByResultSetMetaData0030() throws Exception { Statement stmt = con.createStatement(); ResultSet rs; String sql = ("select " + " convert(tinyint, 2), " + " convert(smallint, 5) "); rs = stmt.executeQuery(sql); if (!rs.next()) { fail("Expecting one row"); } else { ResultSetMetaData meta = rs.getMetaData(); if (meta.getColumnType(1)!=java.sql.Types.TINYINT) { fail("tinyint column was read as " + meta.getColumnType(1)); } if (meta.getColumnType(2)!=java.sql.Types.SMALLINT) { fail("smallint column was read as " + meta.getColumnType(2)); } if (rs.getInt(1) != 2) { fail("Bogus value read for tinyint"); } if (rs.getInt(2) != 5) { fail("Bogus value read for smallint"); } } stmt.close(); } public void testTextColumns0031() throws Exception { Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate( "create table #t0031 " + " (t_nullable text null, " + " t_notnull text not null, " + " i int not null) ")); stmt.executeUpdate("insert into #t0031 values(null, '', 1)"); stmt.executeUpdate("insert into #t0031 values(null, 'b1', 2)"); stmt.executeUpdate("insert into #t0031 values('', '', 3)"); stmt.executeUpdate("insert into #t0031 values('', 'b2', 4)"); stmt.executeUpdate("insert into #t0031 values('a1', '', 5)"); stmt.executeUpdate("insert into #t0031 values('a2', 'b3', 6)"); ResultSet rs = stmt.executeQuery("select * from #t0031 " + " order by i "); assertTrue(rs.next()); assertEquals(null, rs.getString(1)); assertEquals("", rs.getString(2)); assertEquals(1, rs.getInt(3)); assertTrue(rs.next()); assertEquals(null, rs.getString(1)); assertEquals("b1", rs.getString(2)); assertEquals(2, rs.getInt(3)); assertTrue(rs.next()); assertEquals("", rs.getString(1)); assertEquals("", rs.getString(2)); assertEquals(3, rs.getInt(3)); assertTrue(rs.next()); assertEquals("", rs.getString(1)); assertEquals("b2", rs.getString(2)); assertEquals(4, rs.getInt(3)); assertTrue(rs.next()); assertEquals("a1", rs.getString(1)); assertEquals("", rs.getString(2)); assertEquals(5, rs.getInt(3)); assertTrue(rs.next()); assertEquals("a2", rs.getString(1)); assertEquals("b3", rs.getString(2)); assertEquals(6, rs.getInt(3)); stmt.close(); } public void testSpHelpSysUsers0032() throws Exception { Statement stmt = con.createStatement(); boolean passed = true; boolean isResultSet; boolean done; int i; int updateCount; output.println("Starting test #t0032- test sp_help sysusers"); isResultSet = stmt.execute("sp_help sysusers"); output.println("Executed the statement. rc is " + isResultSet); do { if (isResultSet) { output.println("About to call getResultSet"); ResultSet rs = stmt.getResultSet(); ResultSetMetaData meta = rs.getMetaData(); updateCount = 0; while (rs.next()) { for (i=1; i<=meta.getColumnCount(); i++) { output.print(rs.getString(i) + "\t"); } output.println(""); } output.println("Done processing the result set"); } else { output.println("About to call getUpdateCount()"); updateCount = stmt.getUpdateCount(); output.println("Updated " + updateCount + " rows"); } output.println("About to call getMoreResults()"); isResultSet = stmt.getMoreResults(); done = !isResultSet && updateCount==-1; } while (!done); stmt.close(); assertTrue(passed); } static String longString(char ch) { int i; StringBuilder str255 = new StringBuilder( 255 ); for (i=0; i<255; i++) { str255.append(ch); } return str255.toString(); } public void testExceptionByUpdate0033() throws Exception { boolean passed; Statement stmt = con.createStatement(); output.println("Starting test #t0033- make sure Statement.executeUpdate() throws exception"); try { passed = false; stmt.executeUpdate("I am sure this is an error"); } catch (SQLException e) { output.println("The exception is " + e.getMessage()); passed = true; } stmt.close(); assertTrue(passed); } public void testInsertConflict0049() throws Exception { try { dropTable("jTDS_t0049b"); // important: first drop this because of foreign key dropTable("jTDS_t0049a"); Statement stmt = con.createStatement(); String query = "create table jTDS_t0049a( " + " a integer identity(1,1) primary key, " + " b char not null)"; assertEquals(0, stmt.executeUpdate(query)); query = "create table jTDS_t0049b( " + " a integer not null, " + " c char not null, " + " foreign key (a) references jTDS_t0049a(a)) "; assertEquals(0, stmt.executeUpdate(query)); query = "insert into jTDS_t0049b (a, c) values (?, ?)"; java.sql.PreparedStatement pstmt = con.prepareStatement(query); try { pstmt.setInt(1, 1); pstmt.setString(2, "a"); pstmt.executeUpdate(); fail("Was expecting INSERT to fail"); } catch (SQLException e) { assertEquals("23000", e.getSQLState()); } pstmt.close(); assertEquals(1, stmt.executeUpdate("insert into jTDS_t0049a (b) values ('a')")); pstmt = con.prepareStatement(query); pstmt.setInt(1, 1); pstmt.setString(2, "a"); assertEquals(1, pstmt.executeUpdate()); stmt.close(); pstmt.close(); } finally { dropTable("jTDS_t0049b"); // important: first drop this because of foreign key dropTable("jTDS_t0049a"); } } public void testxx0050() throws Exception { try { Statement stmt = con.createStatement(); dropTable("jTDS_t0050b"); dropTable("jTDS_t0050a"); String query = "create table jTDS_t0050a( " + " a integer identity(1,1) primary key, " + " b char not null)"; assertEquals(0, stmt.executeUpdate(query)); query = "create table jTDS_t0050b( " + " a integer not null, " + " c char not null, " + " foreign key (a) references jTDS_t0050a(a)) "; assertEquals(0, stmt.executeUpdate(query)); query = "create procedure #p0050 (@a integer, @c char) as " + " insert into jTDS_t0050b (a, c) values (@a, @c)"; assertEquals(0, stmt.executeUpdate(query)); query = "exec #p0050 ?, ?"; java.sql.CallableStatement cstmt = con.prepareCall(query); try { cstmt.setInt(1, 1); cstmt.setString(2, "a"); cstmt.executeUpdate(); fail("Expecting INSERT to fail"); } catch (SQLException e) { assertEquals("23000", e.getSQLState()); } assertEquals(1, stmt.executeUpdate( "insert into jTDS_t0050a (b) values ('a')")); assertEquals(1, cstmt.executeUpdate()); stmt.close(); cstmt.close(); } finally { dropTable("jTDS_t0050b"); dropTable("jTDS_t0050a"); } } public void testxx0051() throws Exception { boolean passed = true; try { String types[] = {"TABLE"}; DatabaseMetaData dbMetaData = con.getMetaData( ); ResultSet rs = dbMetaData.getTables( null, "%", "t%", types); while (rs.next()) { output.println("Table " + rs.getString(3)); output.println(" catalog " + rs.getString(1)); output.println(" schema " + rs.getString(2)); output.println(" name " + rs.getString(3)); output.println(" type " + rs.getString(4)); output.println(" remarks " + rs.getString(5)); } } catch (java.sql.SQLException e) { passed = false; output.println("Exception caught. " + e.getMessage()); e.printStackTrace(); } assertTrue(passed); } public void testxx0055() throws Exception { boolean passed = true; int i; try { String expectedNames[] = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS", "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "SELF_REFERENCING_COL_NAME", "REF_GENERATION" }; String types[] = {"TABLE"}; DatabaseMetaData dbMetaData = con.getMetaData(); ResultSet rs = dbMetaData.getTables( null, "%", "t%", types); ResultSetMetaData rsMetaData = rs.getMetaData(); if (rsMetaData.getColumnCount() != expectedNames.length) { passed = false; output.println("Bad column count. Should be " + expectedNames.length + ", was " + rsMetaData.getColumnCount()); } for (i=0; passed && i<expectedNames.length; i++) { if (! rsMetaData.getColumnName(i+1).equals(expectedNames[i])) { passed = false; output.println("Bad name for column " + (i+1) + ". " + "Was " + rsMetaData.getColumnName(i+1) + ", expected " + expectedNames[i]); } } } catch (java.sql.SQLException e) { passed = false; output.println("Exception caught. " + e.getMessage()); e.printStackTrace(); } assertTrue(passed); } public void testxx0052() throws Exception { boolean passed = true; // ugly, I know byte[] image = { (byte)0x47, (byte)0x49, (byte)0x46, (byte)0x38, (byte)0x39, (byte)0x61, (byte)0x0A, (byte)0x00, (byte)0x0A, (byte)0x00, (byte)0x80, (byte)0xFF, (byte)0x00, (byte)0xD7, (byte)0x3D, (byte)0x1B, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x2C, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0A, (byte)0x00, (byte)0x0A, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x08, (byte)0x84, (byte)0x8F, (byte)0xA9, (byte)0xCB, (byte)0xED, (byte)0x0F, (byte)0x63, (byte)0x2B, (byte)0x00, (byte)0x3B, }; int i; int count; Statement stmt = con.createStatement(); dropTable("#t0052"); try { String sql = "create table #t0052 ( " + " myvarchar varchar(2000) not null, " + " myvarbinary varbinary(2000) not null) "; stmt.executeUpdate(sql); sql = "insert into #t0052 " + " (myvarchar, " + " myvarbinary) " + " values " + " (\'This is a test with german umlauts \', " + " 0x4749463839610A000A0080FF00D73D1B0000002C000000000A000A00000208848FA9CBED0F632B003B" + " )"; stmt.executeUpdate(sql); sql = "select * from #t0052"; ResultSet rs = stmt.executeQuery(sql); if (!rs.next()) { passed = false; } else { output.println("Testing getAsciiStream()"); InputStream in = rs.getAsciiStream("myvarchar"); String expect = "This is a test with german umlauts ???"; byte[] toRead = new byte[expect.length()]; count = in.read(toRead); if (count == expect.length()) { for (i=0; i<expect.length(); i++) { if (expect.charAt(i) != toRead[i]) { passed = false; output.println("Expected "+expect.charAt(i) + " but was " + toRead[i]); } } } else { passed = false; output.println("Premature end in " + "getAsciiStream(\"myvarchar\") " + count + " instead of " + expect.length()); } in.close(); in = rs.getAsciiStream(2); toRead = new byte[41]; count = in.read(toRead); if (count == 41) { for (i=0; i<41; i++) { if (toRead[i] != (toRead[i] & 0x7F)) { passed = false; output.println("Non ASCII characters in getAsciiStream"); break; } } } else { passed = false; output.println("Premature end in getAsciiStream(1) " +count+" instead of 41"); } in.close(); output.println("Testing getUnicodeStream()"); Reader reader = rs.getCharacterStream("myvarchar"); expect = "This is a test with german umlauts "; char[] charsToRead = new char[expect.length()]; count = reader.read(charsToRead, 0, expect.length()); if (count == expect.length()) { String result = new String(charsToRead); if (!expect.equals(result)) { passed = false; output.println("Expected "+ expect + " but was " + result); } } else { passed = false; output.println("Premature end in " + "getUnicodeStream(\"myvarchar\") " + count + " instead of " + expect.length()); } reader.close(); /* Cannot think of a meaningfull test */ reader = rs.getCharacterStream(2); reader.close(); output.println("Testing getBinaryStream()"); /* Cannot think of a meaningfull test */ in = rs.getBinaryStream("myvarchar"); in.close(); in = rs.getBinaryStream(2); count = 0; toRead = new byte[image.length]; do { int actuallyRead = in.read(toRead, count, image.length-count); if (actuallyRead == -1) { passed = false; output.println("Premature end in " +" getBinaryStream(2) " + count +" instead of " + image.length); break; } count += actuallyRead; } while (count < image.length); for (i=0; i<count; i++) { if (toRead[i] != image[i]) { passed = false; output.println("Expected "+toRead[i] + "but was "+image[i]); break; } } in.close(); output.println("Testing getCharacterStream()"); try { reader = (Reader) UnitTestBase.invokeInstanceMethod( rs, "getCharacterStream", new Class[]{String.class}, new Object[]{"myvarchar"}); expect = "This is a test with german umlauts "; charsToRead = new char[expect.length()]; count = reader.read(charsToRead, 0, expect.length()); if (count == expect.length()) { String result = new String(charsToRead); if (!expect.equals(result)) { passed = false; output.println("Expected "+ expect + " but was " + result); } } else { passed = false; output.println("Premature end in " + "getCharacterStream(\"myvarchar\") " + count + " instead of " + expect.length()); } reader.close(); /* Cannot think of a meaningfull test */ reader = (Reader) UnitTestBase.invokeInstanceMethod( rs, "getCharacterStream", new Class[]{Integer.TYPE}, new Object[]{new Integer(2)}); reader.close(); } catch (RuntimeException e) { // FIXME - This will not compile under 1.3... /* if (e.getCause() instanceof NoSuchMethodException) { output.println("JDBC 2 only"); } else { */ throw e; } catch (Throwable t) { passed = false; output.println("Exception: "+t.getMessage()); } } rs.close(); } catch (java.sql.SQLException e) { passed = false; output.println("Exception caught. " + e.getMessage()); e.printStackTrace(); } assertTrue(passed); stmt.close(); } public void testxx0053() throws Exception { boolean passed = true; Statement stmt = con.createStatement(); dropTable("#t0053"); try { String sql = "create table #t0053 ( " + " myvarchar varchar(2000) not null, " + " mynchar nchar(2000) not null, " + " mynvarchar nvarchar(2000) not null, " + " myntext ntext not null " + " ) "; stmt.executeUpdate(sql); sql = "insert into #t0053 " + " (myvarchar, " + " mynchar, " + " mynvarchar, " + " myntext) " + " values " + " (\'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\', " + " \'\', " + " \'\', " + " \'\' " + " )"; stmt.executeUpdate(sql); sql = "select * from #t0053"; ResultSet rs = stmt.executeQuery(sql); if (!rs.next()) { passed = false; } else { System.err.print("Testing varchars > 255 chars: "); String test = rs.getString(1); if (test.length() == 270) { System.err.println("passed"); } else { System.err.println("failed"); passed = false; } System.err.print("Testing nchar: "); test = rs.getString(2); if (test.length() == 2000 && "".equals(test.trim())) { System.err.println("passed"); } else { System.err.print("failed, got \'"); System.err.print(test.trim()); System.err.println("\' instead of \'\'"); passed = false; } System.err.print("Testing nvarchar: "); test = rs.getString(3); if (test.length() == 6 && "".equals(test)) { System.err.println("passed"); } else { System.err.print("failed, got \'"); System.err.print(test); System.err.println("\' instead of \'\'"); passed = false; } System.err.print("Testing ntext: "); test = rs.getString(4); if (test.length() == 6 && "".equals(test)) { System.err.println("passed"); } else { System.err.print("failed, got \'"); System.err.print(test); System.err.println("\' instead of \'\'"); passed = false; } } } catch (java.sql.SQLException e) { passed = false; output.println("Exception caught. " + e.getMessage()); e.printStackTrace(); } assertTrue(passed); stmt.close(); } public void testxx005x() throws Exception { boolean passed = true; output.println("test getting a DECIMAL as a long from the database."); Statement stmt = con.createStatement(); ResultSet rs; rs = stmt.executeQuery("select convert(DECIMAL(4,0), 0)"); if (!rs.next()) { passed = false; } else { long l = rs.getLong(1); if (l != 0) { passed = false; } } rs = stmt.executeQuery("select convert(DECIMAL(4,0), 1)"); if (!rs.next()) { passed = false; } else { long l = rs.getLong(1); if (l != 1) { passed = false; } } rs = stmt.executeQuery("select convert(DECIMAL(4,0), -1)"); if (!rs.next()) { passed = false; } else { long l = rs.getLong(1); if (l != -1) { passed = false; } } assertTrue(passed); stmt.close(); } public void testxx0057() throws Exception { output.println("test putting a zero length string into a parameter"); // open the database int count; Statement stmt = con.createStatement(); dropTable("#t0057"); count = stmt.executeUpdate("create table #t0057 " + " (a varchar(10) not null, " + " b char(10) not null) "); stmt.close(); output.println("Creating table affected " + count + " rows"); PreparedStatement pstmt = con.prepareStatement( "insert into #t0057 values (?, ?)"); pstmt.setString(1, ""); pstmt.setString(2, ""); count = pstmt.executeUpdate(); output.println("Added " + count + " rows"); if (count != 1) { pstmt.close(); output.println("Failed to add rows"); fail(); } else { pstmt.close(); pstmt = con.prepareStatement("select a, b from #t0057"); ResultSet rs = pstmt.executeQuery(); if (!rs.next()) { output.println("Couldn't read rows from table."); fail(); } else { output.println("a is |" + rs.getString("a") + "|"); output.println("b is |" + rs.getString("b") + "|"); assertEquals("", rs.getString("a")); assertEquals(" ", rs.getString("b")); } pstmt.close(); } } public void testxx0059() throws Exception { try { DatabaseMetaData dbMetaData = con.getMetaData( ); ResultSet rs = dbMetaData.getSchemas(); ResultSetMetaData rsm = rs.getMetaData(); boolean JDBC3 = "1.4".compareTo(System.getProperty("java.specification.version")) <= 0; assertEquals(JDBC3 ? 2 : 1, rsm.getColumnCount()); assertTrue(rsm.getColumnName(1).equalsIgnoreCase("TABLE_SCHEM")); if (JDBC3) { assertTrue(rsm.getColumnName(2).equalsIgnoreCase("TABLE_CATALOG")); } while (rs.next()) { output.println("schema " + rs.getString(1)); } } catch (java.sql.SQLException e) { output.println("Exception caught. " + e.getMessage()); e.printStackTrace(); fail(); } } }
package org.opennars.control; import org.opennars.entity.*; import org.opennars.inference.TemporalRules; import org.opennars.inference.TruthFunctions; import org.opennars.io.Symbols; import org.opennars.io.events.Events; import org.opennars.io.events.OutputHandler; import org.opennars.language.*; import org.opennars.main.Parameters; import org.opennars.operator.FunctionOperator; import org.opennars.operator.Operation; import org.opennars.operator.Operator; import org.opennars.operator.mental.*; import org.opennars.plugin.mental.InternalExperience; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.opennars.inference.LocalRules.*; public class ConceptProcessing { /** * Directly process a new task. Called exactly once on each task. Using * local information and finishing in a constant time. Provide feedback in * the taskBudget value of the task. * <p> * called in Memory.immediateProcess only * * @param task The task to be processed * @return whether it was processed */ public static boolean processTask(final Concept concept, final DerivationContext nal, final Task task) { if(task.isInput()) { if(task.sentence.isJudgment() && !task.sentence.isEternal() && task.sentence.term instanceof Operation) { final Operation op = (Operation) task.sentence.term; final Operator o = (Operator) op.getPredicate(); //only consider these mental ops an operation to track when executed not already when generated as internal event if(!(o instanceof Believe) && !(o instanceof Want) && !(o instanceof Wonder) && !(o instanceof Evaluate) && !(o instanceof Anticipate)) { TemporalInferenceControl.NewOperationFrame(nal.memory, task); } } concept.observable = true; } final char type = task.sentence.punctuation; switch (type) { case Symbols.JUDGMENT_MARK: //memory.logic.JUDGMENT_PROCESS.commit(); processJudgment(concept, nal, task); break; case Symbols.GOAL_MARK: //memory.logic.GOAL_PROCESS.commit(); processGoal(concept, nal, task, true); break; case Symbols.QUESTION_MARK: case Symbols.QUEST_MARK: //memory.logic.QUESTION_PROCESS.commit(); processQuestion(concept, nal, task); break; default: return false; } maintainDisappointedAnticipations(concept); if (task.aboveThreshold()) { // still need to be processed //memory.logic.LINK_TO_TASK.commit(); concept.linkToTask(task,nal); } return true; } /** * To accept a new judgment as belief, and check for revisions and solutions * * @param judg The judgment to be accepted * @param task The task to be processed * @return Whether to continue the processing of the task */ protected static void processJudgment(final Concept concept, final DerivationContext nal, final Task task) { final Sentence judg = task.sentence; final boolean satisfiesAnticipation = task.isInput() && !task.sentence.isEternal() && concept.negConfirmation != null && task.sentence.getOccurenceTime() > concept.negConfirm_abort_mintime; final boolean isExpectactionAbliveThreshold = task.sentence.truth.getExpectation() > Parameters.DEFAULT_CONFIRMATION_EXPECTATION; if( satisfiesAnticipation && isExpectactionAbliveThreshold && ((Statement) concept.negConfirmation.sentence.term).getPredicate().equals(task.sentence.getTerm()) ) { nal.memory.emit(OutputHandler.CONFIRM.class, ((Statement)concept.negConfirmation.sentence.term).getPredicate()); concept.negConfirmation = null; // confirmed } final Task oldBeliefT = concept.selectCandidate(task, concept.beliefs); // only revise with the strongest -- how about projection? Sentence oldBelief = null; boolean wasRevised = false; if (oldBeliefT != null) { oldBelief = oldBeliefT.sentence; final Stamp newStamp = judg.stamp; final Stamp oldStamp = oldBelief.stamp; //when table is full, the latter check is especially important too if (newStamp.equals(oldStamp,false,false,true)) { //if (task.getParentTask() != null && task.getParentTask().sentence.isJudgment()) { ////task.budget.decPriority(0); // duplicated task //} //// else: activated belief concept.memory.removeTask(task, "Duplicated"); return; } else if (revisible(judg, oldBelief)) { nal.setTheNewStamp(newStamp, oldStamp, concept.memory.time()); final Sentence projectedBelief = oldBelief.projection(concept.memory.time(), newStamp.getOccurrenceTime()); if (projectedBelief!=null) { if (projectedBelief.getOccurenceTime()!=oldBelief.getOccurenceTime()) { // nal.singlePremiseTask(projectedBelief, task.budget); } nal.setCurrentBelief(projectedBelief); wasRevised = revision(judg, projectedBelief, false, nal); } } } if (!task.aboveThreshold()) { return; } final int nnq = concept.questions.size(); for (int i = 0; i < nnq; i++) { trySolution(judg, concept.questions.get(i), nal, true); } final int nng = concept.desires.size(); for (int i = 0; i < nng; i++) { trySolution(judg, concept.desires.get(i), nal, true); } concept.addToTable(task, false, concept.beliefs, Parameters.CONCEPT_BELIEFS_MAX, Events.ConceptBeliefAdd.class, Events.ConceptBeliefRemove.class); //if taskLink predicts this concept then add to predictive final Task target = task; final Term term = target.getTerm(); if(//!target.isObservablePrediction() || !target.sentence.isEternal() || !(term instanceof Implication) || term.hasVarIndep()) //Might be relaxed in the future!! { return; } final Implication imp = (Implication) term; if(imp.getTemporalOrder() != TemporalRules.ORDER_FORWARD) { return; } //also it has to be enactable, meaning the last entry of the sequence before the interval is an operation: final Term subj = imp.getSubject(); final Term pred = imp.getPredicate(); final Concept pred_conc = nal.memory.concept(pred); if(pred_conc != null /*&& !(pred instanceof Operation)*/ && (subj instanceof Conjunction)) { final Conjunction conj = (Conjunction) subj; if(!conj.isSpatial && conj.getTemporalOrder() == TemporalRules.ORDER_FORWARD && conj.term.length >= 4 && conj.term.length%2 == 0 && conj.term[conj.term.length-1] instanceof Interval && conj.term[conj.term.length-2] instanceof Operation) { //we do not add the target, instead the strongest belief in the target concept if(concept.beliefs.size() > 0) { Task strongest_target = null; //beliefs.get(0); //get the first eternal: for(final Task t : concept.beliefs) { if(t.sentence.isEternal()) { strongest_target = t; break; } } final int a = pred_conc.executable_preconditions.size(); //at first we have to remove the last one with same content from table int i_delete = -1; for(int i=0; i < pred_conc.executable_preconditions.size(); i++) { if(CompoundTerm.replaceIntervals(pred_conc.executable_preconditions.get(i).getTerm()).equals( CompoundTerm.replaceIntervals(strongest_target.getTerm()))) { i_delete = i; //even these with same term but different intervals are removed here break; } } if(i_delete != -1) { pred_conc.executable_preconditions.remove(i_delete); } final Term[] prec = ((Conjunction) ((Implication) strongest_target.getTerm()).getSubject()).term; for(int i=0;i<prec.length-2;i++) { if(prec[i] instanceof Operation) { //don't react to precondition with an operation before the last return; //for now, these can be decomposed into smaller such statements anyway } } //this way the strongest confident result of this content is put into table but the table ranked according to truth expectation pred_conc.addToTable(strongest_target, true, pred_conc.executable_preconditions, Parameters.CONCEPT_BELIEFS_MAX, Events.EnactableExplainationAdd.class, Events.EnactableExplainationRemove.class); } } } } /** * To accept a new goal, and check for revisions and realization, then * decide whether to actively pursue it, potentially executing in case of an operation goal * * @param judg The judgment to be accepted * @param task The task to be processed * @return Whether to continue the processing of the task */ protected static boolean processGoal(final Concept concept, final DerivationContext nal, final Task task, final boolean shortcut) { final Sentence goal = task.sentence; final Task oldGoalT = concept.selectCandidate(task, concept.desires); // revise with the existing desire values Sentence oldGoal = null; final Stamp newStamp = goal.stamp; if (oldGoalT != null) { oldGoal = oldGoalT.sentence; final Stamp oldStamp = oldGoal.stamp; if (newStamp.equals(oldStamp,false,false,true)) { return false; // duplicate } } Task beliefT = null; if(task.aboveThreshold()) { beliefT = concept.selectCandidate(task, concept.beliefs); // check if the Goal is already satisfied final int nnq = concept.quests.size(); for (int i = 0; i < nnq; i++) { trySolution(task.sentence, concept.quests.get(i), nal, true); } if (beliefT != null) { trySolution(beliefT.sentence, task, nal, true); // check if the Goal is already satisfied (manipulate budget) } } if (oldGoalT != null) { if (revisible(goal, oldGoal)) { final Stamp oldStamp = oldGoal.stamp; nal.setTheNewStamp(newStamp, oldStamp, concept.memory.time()); final Sentence projectedGoal = oldGoal.projection(task.sentence.getOccurenceTime(), newStamp.getOccurrenceTime()); if (projectedGoal!=null) { // if (goal.after(oldGoal, nal.memory.param.duration.get())) { //no need to project the old goal, it will be projected if selected anyway now // nal.singlePremiseTask(projectedGoal, task.budget); //return; nal.setCurrentBelief(projectedGoal); final boolean successOfRevision=revision(task.sentence, projectedGoal, false, nal); if(successOfRevision) { // it is revised, so there is a new task for which this function will be called return false; // with higher/lower desire } } } } final Stamp s2=goal.stamp.clone(); s2.setOccurrenceTime(concept.memory.time()); if(s2.after(task.sentence.stamp, Parameters.DURATION)) { //this task is not up to date we have to project it first final Sentence projGoal = task.sentence.projection(concept.memory.time(), Parameters.DURATION); if(projGoal!=null && projGoal.truth.getExpectation() > nal.narParameters.DECISION_THRESHOLD) { nal.singlePremiseTask(projGoal, task.budget.clone()); //keep goal updated // return false; //outcommented, allowing "roundtrips now", relevant for executing multiple steps of learned implication chains } } if (task.aboveThreshold()) { double AntiSatisfaction = 0.5f; //we dont know anything about that goal yet, so we pursue it to remember it because its maximally unsatisfied if (beliefT != null) { final Sentence belief = beliefT.sentence; final Sentence projectedBelief = belief.projection(task.sentence.getOccurenceTime(), Parameters.DURATION); AntiSatisfaction = task.sentence.truth.getExpDifAbs(projectedBelief.truth); } final double Satisfaction=1.0-AntiSatisfaction; task.setPriority(task.getPriority()* (float)AntiSatisfaction); if (!task.aboveThreshold()) { return false; } final TruthValue T=goal.truth.clone(); T.setFrequency((float) (T.getFrequency()-Satisfaction)); //decrease frequency according to satisfaction value final boolean fullfilled = AntiSatisfaction < Parameters.SATISFACTION_TRESHOLD; final Sentence projectedGoal = goal.projection(nal.memory.time(),nal.memory.time()); if (projectedGoal != null && task.aboveThreshold() && !fullfilled) { bestReactionForGoal(concept, nal, projectedGoal, task); questionFromGoal(task, nal); concept.addToTable(task, false, concept.desires, Parameters.CONCEPT_GOALS_MAX, Events.ConceptGoalAdd.class, Events.ConceptGoalRemove.class); InternalExperience.InternalExperienceFromTask(concept.memory,task,false); if(projectedGoal.truth.getExpectation() > nal.narParameters.DECISION_THRESHOLD && nal.memory.time() >= concept.memory.decisionBlock) { //see whether the goal evidence is fully included in the old goal, if yes don't execute //as execution for this reason already happened (or did not since there was evidence against it) final Set<Long> oldEvidence = new HashSet<>(); boolean Subset=false; if(oldGoalT != null) { Subset = true; for(final Long l: oldGoalT.sentence.stamp.evidentialBase) { oldEvidence.add(l); } for(final Long l: task.sentence.stamp.evidentialBase) { if(!oldEvidence.contains(l)) { Subset = false; break; } } } if(!Subset && !executeDecision(nal, task)) { concept.memory.emit(Events.UnexecutableGoal.class, task, concept, nal); return true; //it was made true by itself } } return false; } return fullfilled; } return false; } public static void questionFromGoal(final Task task, final DerivationContext nal) { if(Parameters.QUESTION_GENERATION_ON_DECISION_MAKING || Parameters.HOW_QUESTION_GENERATION_ON_DECISION_MAKING) { //ok, how can we achieve it? add a question of whether it is fullfilled final List<Term> qu= new ArrayList<>(); if(Parameters.HOW_QUESTION_GENERATION_ON_DECISION_MAKING) { if(!(task.sentence.term instanceof Equivalence) && !(task.sentence.term instanceof Implication)) { final Variable how=new Variable("?how"); //Implication imp=Implication.make(how, task.sentence.term, TemporalRules.ORDER_CONCURRENT); final Implication imp2=Implication.make(how, task.sentence.term, TemporalRules.ORDER_FORWARD); //qu.add(imp); if(!(task.sentence.term instanceof Operation)) { qu.add(imp2); } } } if(Parameters.QUESTION_GENERATION_ON_DECISION_MAKING) { qu.add(task.sentence.term); } for(final Term q : qu) { if(q!=null) { final Stamp st = new Stamp(task.sentence.stamp,nal.memory.time()); st.setOccurrenceTime(task.sentence.getOccurenceTime()); //set tense of question to goal tense final Sentence s = new Sentence( q, Symbols.QUESTION_MARK, null, st); if(s!=null) { final BudgetValue budget=new BudgetValue(task.getPriority()*Parameters.CURIOSITY_DESIRE_PRIORITY_MUL,task.getDurability()*Parameters.CURIOSITY_DESIRE_DURABILITY_MUL,1); nal.singlePremiseTask(s, budget); } } } } } /** * To answer a question by existing beliefs * * @param task The task to be processed * @return Whether to continue the processing of the task */ protected static void processQuestion(final Concept concept, final DerivationContext nal, final Task task) { Task quesTask = task; boolean newQuestion = true; List<Task> questions = concept.questions; if(task.sentence.punctuation == Symbols.QUEST_MARK) { questions = concept.quests; } for (final Task t : questions) { if (t.sentence.term.equals(quesTask.sentence.term)) { quesTask = t; newQuestion = false; break; } } if (newQuestion) { if (questions.size() + 1 > Parameters.CONCEPT_QUESTIONS_MAX) { final Task removed = questions.remove(0); // FIFO concept.memory.event.emit(Events.ConceptQuestionRemove.class, concept, removed); } questions.add(task); concept.memory.event.emit(Events.ConceptQuestionAdd.class, concept, task); } final Sentence ques = quesTask.sentence; final Task newAnswerT = (ques.isQuestion()) ? concept.selectCandidate(quesTask, concept.beliefs) : concept.selectCandidate(quesTask, concept.desires); if (newAnswerT != null) { trySolution(newAnswerT.sentence, task, nal, true); } else if(task.isInput() && !quesTask.getTerm().hasVarQuery() && quesTask.getBestSolution() != null) { // show previously found solution anyway in case of input concept.memory.emit(Events.Answer.class, quesTask, quesTask.getBestSolution()); } } /** * When a goal is processed, use the best memorized reaction * that is applicable to the current context (recent events) in case that it exists. * This is a special case of the choice rule and allows certain behaviors to be automated. */ protected static void bestReactionForGoal(final Concept concept, final DerivationContext nal, final Sentence projectedGoal, final Task task) { Operation bestop = null; float bestop_truthexp = 0.0f; TruthValue bestop_truth = null; Task executable_precond = null; long mintime = -1; long maxtime = -1; for(final Task t: concept.executable_preconditions) { final Term[] prec = ((Conjunction) ((Implication) t.getTerm()).getSubject()).term; final Term[] newprec = new Term[prec.length-3]; System.arraycopy(prec, 0, newprec, 0, prec.length - 3); final long add_tolerance = (long) (((Interval)prec[prec.length-1]).time*Parameters.ANTICIPATION_TOLERANCE); mintime = nal.memory.time(); maxtime = nal.memory.time() + add_tolerance; final Operation op = (Operation) prec[prec.length-2]; final Term precondition = Conjunction.make(newprec,TemporalRules.ORDER_FORWARD); final Concept preconc = nal.memory.concept(precondition); long newesttime = -1; Task bestsofar = null; if(preconc != null) { //ok we can look now how much it is fullfilled //check recent events in event bag for(final Task p : concept.memory.seq_current) { if(p.sentence.term.equals(preconc.term) && p.sentence.isJudgment() && !p.sentence.isEternal() && p.sentence.getOccurenceTime() > newesttime && p.sentence.getOccurenceTime() <= concept.memory.time()) { newesttime = p.sentence.getOccurenceTime(); bestsofar = p; //we use the newest for now } } if(bestsofar == null) { continue; } //ok now we can take the desire value: final TruthValue A = projectedGoal.getTruth(); //and the truth of the hypothesis: final TruthValue Hyp = t.sentence.truth; //overlap will almost never happen, but to make sure if(Stamp.baseOverlap(projectedGoal.stamp.evidentialBase, t.sentence.stamp.evidentialBase)) { continue; //base overlap } if(Stamp.baseOverlap(bestsofar.sentence.stamp.evidentialBase, t.sentence.stamp.evidentialBase)) { continue; //base overlap } if(Stamp.baseOverlap(projectedGoal.stamp.evidentialBase, bestsofar.sentence.stamp.evidentialBase)) { continue; //base overlap } //and the truth of the precondition: final Sentence projectedPrecon = bestsofar.sentence.projection(concept.memory.time() /*- distance*/, concept.memory.time()); if(projectedPrecon.isEternal()) { continue; //projection wasn't better than eternalization, too long in the past } //debug start //long timeA = memory.time(); //long timeOLD = bestsofar.sentence.stamp.getOccurrenceTime(); //long timeNEW = projectedPrecon.stamp.getOccurrenceTime(); //debug end final TruthValue precon = projectedPrecon.truth; //and derive the conjunction of the left side: final TruthValue leftside = TruthFunctions.desireDed(A, Hyp); //in order to derive the operator desire value: final TruthValue opdesire = TruthFunctions.desireDed(precon, leftside); final float expecdesire = opdesire.getExpectation(); if(expecdesire > bestop_truthexp) { bestop = op; bestop_truthexp = expecdesire; bestop_truth = opdesire; executable_precond = t; } } } if(bestop != null && bestop_truthexp > nal.narParameters.DECISION_THRESHOLD /*&& Math.random() < bestop_truthexp */) { final Sentence createdSentence = new Sentence( bestop, Symbols.JUDGMENT_MARK, bestop_truth, projectedGoal.stamp); final Task t = new Task(createdSentence, new BudgetValue(1.0f,1.0f,1.0f), false); //System.out.println("used " +t.getTerm().toString() + String.valueOf(memory.randomNumber.nextInt())); if(!task.sentence.stamp.evidenceIsCyclic()) { if(!executeDecision(nal, t)) { //this task is just used as dummy concept.memory.emit(Events.UnexecutableGoal.class, task, concept, nal); } else { concept.memory.decisionBlock = concept.memory.time() + Parameters.AUTOMATIC_DECISION_USUAL_DECISION_BLOCK_CYCLES; generatePotentialNegConfirmation(nal, executable_precond.sentence, executable_precond.budget, mintime, maxtime, 2); } } } } public static void generatePotentialNegConfirmation(final DerivationContext nal, final Sentence mainSentence, final BudgetValue budget, final long mintime, final long maxtime, final float priority) { //derivation was successful and it was a judgment event final Stamp stamp = new Stamp(nal.memory); stamp.setOccurrenceTime(Stamp.ETERNAL); //long serial = stamp.evidentialBase[0]; final Sentence s = new Sentence( mainSentence.term, mainSentence.punctuation, new TruthValue(0.0f, 0.0f), stamp); //s.producedByTemporalInduction = true; //also here to not go into sequence buffer final Task t = new Task(s, new BudgetValue(0.99f,0.1f,0.1f), false); //Budget for one-time processing final Concept c = nal.memory.concept(((Statement) mainSentence.term).getPredicate()); //put into consequence concept if(c != null /*&& mintime > nal.memory.time()*/ && c.observable && mainSentence.getTerm() instanceof Statement && mainSentence.getTerm().getTemporalOrder() == TemporalRules.ORDER_FORWARD) { if(c.negConfirmation == null || priority > c.negConfirmationPriority /*|| t.getPriority() > c.negConfirmation.getPriority() */) { c.negConfirmation = t; c.negConfirmationPriority = priority; c.negConfirm_abort_maxtime = maxtime; c.negConfirm_abort_mintime = mintime; if(c.negConfirmation.sentence.term instanceof Implication) { final Implication imp = (Implication) c.negConfirmation.sentence.term; final Concept ctarget = nal.memory.concept(imp.getPredicate()); if(ctarget != null && ctarget.getPriority()>=InternalExperience.MINIMUM_CONCEPT_PRIORITY_TO_CREATE_ANTICIPATION) { ((Anticipate)c.memory.getOperator("^anticipate")).anticipationFeedback(imp.getPredicate(), null, c.memory); } } nal.memory.emit(OutputHandler.ANTICIPATE.class,((Statement) c.negConfirmation.sentence.term).getPredicate()); //disappoint/confirm printed anyway } } } /** * Entry point for all potentially executable tasks. * Returns true if the Task has a Term which can be executed */ public static boolean executeDecision(final DerivationContext nal, final Task t) { //if (isDesired()) if(!nal.memory.allowExecution) { return false; } final Term content = t.getTerm(); if(!(content instanceof Operation)) { return false; } final Operation op=(Operation)content; final Operator oper = op.getOperator(); final Product prod = (Product) op.getSubject(); final Term arg = prod.term[0]; if(oper instanceof FunctionOperator) { for(int i=0;i<prod.term.length-1;i++) { //except last one, the output arg if(prod.term[i].hasVarDep() || prod.term[i].hasVarIndep()) { return false; } } } else { if(content.hasVarDep() || content.hasVarIndep()) { return false; } } if(!arg.equals(Term.SELF)) { //will be deprecated in the future return false; } op.setTask(t); if(!oper.call(op, nal.memory)) { return false; } if (Parameters.DEBUG) { System.out.println(t.toStringLong()); } //this.memory.sequenceTasks = new LevelBag<>(Parameters.SEQUENCE_BAG_LEVELS, Parameters.SEQUENCE_BAG_SIZE); return true; } public static void maintainDisappointedAnticipations(final Concept concept) { //here we can check the expiration of the feedback: if(concept.negConfirmation == null || concept.memory.time() <= concept.negConfirm_abort_maxtime) { return; } //at first search beliefs for input tasks: boolean cancelled = false; for(final TaskLink tl : concept.taskLinks) { //search for input in tasklinks (beliefs alone can not take temporality into account as the eternals will win) final Task t = tl.targetTask; if(t!= null && t.sentence.isJudgment() && t.isInput() && !t.sentence.isEternal() && t.sentence.truth.getExpectation() > Parameters.DEFAULT_CONFIRMATION_EXPECTATION && CompoundTerm.replaceIntervals(t.sentence.term).equals(CompoundTerm.replaceIntervals(concept.getTerm()))) { if(t.sentence.getOccurenceTime() >= concept.negConfirm_abort_mintime && t.sentence.getOccurenceTime() <= concept.negConfirm_abort_maxtime) { cancelled = true; break; } } } if(cancelled) { concept.memory.emit(OutputHandler.CONFIRM.class,((Statement) concept.negConfirmation.sentence.term).getPredicate()); concept.negConfirmation = null; //confirmed return; } final Term T = ((Statement)concept.negConfirmation.getTerm()).getPredicate(); final Sentence s1 = new Sentence(T, Symbols.JUDGMENT_MARK, new TruthValue(0.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(concept.memory)); final Sentence s2 = new Sentence(Negation.make(T), Symbols.JUDGMENT_MARK, new TruthValue(1.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(concept.memory)); final Task negated1 = new Task(s1,concept.negConfirmation.getBudget().clone(),true); final Task negated2 = new Task(s2,concept.negConfirmation.getBudget().clone(),true); concept.memory.inputTask(negated1, false); //disappointed concept.memory.inputTask(negated2, false); //disappointed concept.memory.emit(OutputHandler.DISAPPOINT.class,((Statement) concept.negConfirmation.sentence.term).getPredicate()); concept.negConfirmation = null; } public static void ProcessWhatQuestionAnswer(final Concept concept, final Task t, final DerivationContext nal) { if(!t.sentence.term.hasVarQuery() && t.sentence.isJudgment() || t.sentence.isGoal()) { //ok query var, search for(final TaskLink quess: concept.taskLinks) { final Task ques = quess.getTarget(); if(((ques.sentence.isQuestion() && t.sentence.isJudgment()) || (ques.sentence.isGoal() && t.sentence.isJudgment()) || (ques.sentence.isQuest() && t.sentence.isGoal())) && ques.getTerm().hasVarQuery()) { boolean newAnswer = false; final Term[] u = new Term[] { ques.getTerm(), t.getTerm() }; if(ques.sentence.term.hasVarQuery() && !t.getTerm().hasVarQuery() && Variables.unify(Symbols.VAR_QUERY, u)) { final Concept c = nal.memory.concept(t.getTerm()); final List<Task> answers = ques.sentence.isQuest() ? c.desires : c.beliefs; if(c != null && answers.size() > 0) { final Task taskAnswer = answers.get(0); if(taskAnswer!=null) { newAnswer |= trySolution(taskAnswer.sentence, ques, nal, false); //order important here } } } if(newAnswer && ques.isInput()) { nal.memory.emit(Events.Answer.class, ques, ques.getBestSolution()); } } } } } public static void ProcessWhatQuestion(final Concept concept, final Task ques, final DerivationContext nal) { if(!(ques.sentence.isJudgment()) && ques.getTerm().hasVarQuery()) { //ok query var, search boolean newAnswer = false; for(final TaskLink t : concept.taskLinks) { final Term[] u = new Term[] { ques.getTerm(), t.getTerm() }; if(!t.getTerm().hasVarQuery() && Variables.unify(Symbols.VAR_QUERY, u)) { final Concept c = nal.memory.concept(t.getTerm()); final List<Task> answers = ques.sentence.isQuest() ? c.desires : c.beliefs; if(c != null && answers.size() > 0) { final Task taskAnswer = answers.get(0); if(taskAnswer!=null) { newAnswer |= trySolution(taskAnswer.sentence, ques, nal, false); //order important here } } } } if(newAnswer && ques.isInput()) { nal.memory.emit(Events.Answer.class, ques, ques.getBestSolution()); } } } }
package org.smoothbuild.lang.parse.ast; import org.smoothbuild.lang.base.define.Location; import org.smoothbuild.lang.base.like.ReferencableLike; public class RefNode extends ExprNode { private final String name; private ReferencableLike referenced; public RefNode(String name, Location location) { super(location); this.name = name; } public String name() { return name; } public void setReferenced(ReferencableLike referenced) { this.referenced = referenced; } public ReferencableLike referenced() { return referenced; } @Override public String toString() { return RefNode.class.getName() + "(" + name + ")"; } }
package org.spongepowered.api.entity; import com.flowpowered.math.imaginary.Quaterniond; import com.flowpowered.math.matrix.Matrix4d; import com.flowpowered.math.vector.Vector3d; import org.spongepowered.api.GameRegistry; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.extent.Extent; public interface Transform<E extends Extent> { Location<E> getLocation(); E getExtent(); /** * Gets the coordinates of this transform. * * @return The coordinates */ Vector3d getPosition(); /** * Gets the rotation of this transform, as a {@link Vector3d}. * * <p>The format of the rotation is represented by:</p> * <ul> * <li><code>x -> pitch</code></li> * <li><code>y -> yaw</code></li> * <li><code>z -> roll</code></li> * </ul> * * @return The rotation vector */ Vector3d getRotation(); /** * Returns the rotation as a quaternion. * Quaternions are objectively better than * the Euler angles preferred by Minecraft. * This is for compatibility with * the flow-math library. * * @return The rotation */ Quaterniond getRotationAsQuaternion(); /** * Gets the pitch component of this transform rotation * * @return The pitch */ double getPitch(); /** * Gets the yaw component of this transform rotation * * @return The yaw */ double getYaw(); /** * Gets the roll component of this transform rotation * * @return The roll */ double getRoll(); /** * Gets the scale of the transform for each axis. * * @return The scale */ Vector3d getScale(); /** * "Adds" another transform to this one. * This is equivalent to adding the * translation, rotation and scale * individually. Returns the results * as a new copy. * * @param other The transform to add * @return A new transform */ Transform<E> add(Transform<E> other); /** * Adds a translation to this transform. * Returns the results as a new copy. * * @param translation The translation to add * @return A new transform */ Transform<E> addTranslation(Vector3d translation); /** * Adds a rotation to this transform. * Returns the results as a new copy. * * @param rotation The rotation to add * @return A new transform */ Transform<E> addRotation(Vector3d rotation); /** * Adds a rotation to this transform. * Quaternions are objectively better than * the Euler angles preferred by Minecraft. * This is the preferred method when * dealing with rotation additions. * This is for compatibility with * the flow-math library. * Returns the results as a new copy. * * @param rotation The rotation to add * @return A new transform */ Transform<E> addRotation(Quaterniond rotation); /** * "Adds" a scale to this transform. * Scales are multiplicative, so * this actually multiplies the * current scale. * Returns the results as a new copy. * * @param scale The scale to add * @return A new transform */ Transform<E> addScale(Vector3d scale); /** * Returns a matrix representation of this transform. * This includes the position, rotation and scale. * To apply the transform to a vector, use the following * * <p><pre>{@code * Vector3d original = ...; * Transform transform = ...; * * Vector3d transformed = transform.toMatrix().transform(original.toVector4(1)).toVector3(); * }</pre></p> * * <p>This converts the original 3D vector to 4D by appending 1 as the w coordinate, * applies the transformation, then converts it back to 3D by dropping the w coordinate.</p> * * <p>Using a 4D matrix and a w coordinate with value 1 is what allows for the position * to be included in the transformation applied by the matrix.</p> * * @return The transform as a matrix */ Matrix4d toMatrix(); boolean isValid(); /** * A builder for transforms. Create one from * {@link GameRegistry#createTransformBuilder()}. * The builder uses the default values for position and * rotation of (0, 0, 0) and scale of (1, 1, 1). * Only the extent must be set to build and not doing so * results in a state exception. * * @param <E> The type of extent */ interface Builder<E extends Extent> { /** * Sets the extent of this transform. * * @param extent The extent * @return This builder for chained calls */ Builder<E> extent(E extent); /** * Sets the position of this transform. * * @param position The position * @return This builder for chained calls */ Builder<E> position(Vector3d position); /** * Sets the rotation of this transform. * * @param rotation The rotation * @return This builder for chained calls */ Builder<E> rotation(Vector3d rotation); /** * Sets the rotation of this transform. * * @param rotation The extent * @return This builder for chained calls */ Builder<E> rotation(Quaterniond rotation); /** * Sets the scale of this transform. * * @param scale The scale * @return This builder for chained calls */ Builder<E> scale(Vector3d scale); Transform<E> build(); } }
package org.takes.facets.auth.social; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.response.JsonResponse; import com.jcabi.http.response.RestResponse; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Collections; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.json.JsonObject; import javax.xml.bind.DatatypeConverter; import lombok.EqualsAndHashCode; import org.takes.Request; import org.takes.Response; import org.takes.facets.auth.Identity; import org.takes.facets.auth.Pass; import org.takes.misc.Href; /** * Twitter OAuth landing/callback page. * * <p>The class is immutable and thread-safe. * * @author Prasath Premkumar (popprem@gmail.com) * @version $Id$ * @since * @checkstyle MultipleStringLiteralsCheck (500 lines) */ @EqualsAndHashCode(of = { "app", "key" }) public final class PsTwitter implements Pass { /** * App name. */ private final transient String app; /** * Key. */ private final transient String key; /** * Ctor. * @param gapp Twitter app * @param gkey Twitter key */ public PsTwitter(final String gapp, final String gkey) { this.app = gapp; this.key = gkey; } @Override public Iterator<Identity> enter(final Request request) throws IOException { return Collections.singleton( PsTwitter.fetch(this.token()) ).iterator(); } @Override public Response exit(final Response response, final Identity identity) { return response; } /** * Get user name from Twitter, with the token provided. * @param token Twitter access token * @return The user found in Twitter * @throws IOException If fails */ private static Identity fetch(final String token) throws IOException { final String uri = new Href( "https://api.twitter.com/1.1/account/verify_credentials.json" ) .with("access_token", token) .toString(); return PsTwitter.parse( new JdkRequest(uri) .header("accept", "application/json") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class).json().readObject() ); } /** * Retrieve Twitter access token. * @return The token * @throws IOException If failed */ private String token() throws IOException { final String uri = new Href("https://api.twitter.com/oauth2/token") .with("grant_type", "client_credentials") .toString(); return new JdkRequest(uri) .method("POST") .header( "Content-Type", "application/x-www-form-urlencoded;charset=UTF-8" ) .header( "Authorization", String.format( "Basic %s", DatatypeConverter.printBase64Binary( String.format("%s:%s", this.app, this.key) .getBytes() ) ) ) .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(JsonResponse.class) .json().readObject().getString("access_token"); } /** * Make identity from JSON object. * @param json JSON received from Twitter * @return Identity found */ private static Identity parse(final JsonObject json) { final ConcurrentMap<String, String> props = new ConcurrentHashMap<String, String>(json.size()); props.put("name", json.getString("name")); props.put("picture", json.getString("profile_image_url")); return new Identity.Simple( String.format("urn:twitter:%d", json.getInt("id")), props ); } }
package org.tinyj.lava; /** * Unchecked exception wrapping a checked exception. */ public final class WrappedCheckedException extends RuntimeException { /** * {@link WrappedCheckedException} cannot be instantiated directly. Use * {@code wrapCheckedException(Exception)} instead. * * @param e the wrapped checked exception */ private WrappedCheckedException(Exception e) { super(assertCheckedException(e)); } /** * @param e {@link Exception} to wrap * @return {@code e} if {@code e} is {@code null} or a {@link RuntimeException}, * a {@link WrappedCheckedException} wrapping {@code e} otherwise */ public static RuntimeException wrapCheckedException(Exception e) { return e == null || e instanceof RuntimeException ? (RuntimeException) e : new WrappedCheckedException(e); } /** * @param e {@link Exception} to unwrap * @return {@code e} if {@code e} is not a {@link WrappedCheckedException} or * {@code e.getCause()} otherwise */ public static Exception unwrapCheckedException(Exception e) { return e instanceof WrappedCheckedException ? (Exception) e.getCause() : e; } /** * Execute {@code task}, wrap and rethrow any checked exception raised during * execution. * * @param task {@link LavaRunnable} to execute * @throws RuntimeException Checked exception raised during {@code task.checkedRun()} * will be wrapped in a {@link WrappedCheckedException} */ public static void wrapCheckedException(LavaRunnable<?> task) { try { task.checkedRun(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new WrappedCheckedException(e); } } /** * Execute {@code task}, wrap and rethrow any checked exception raised during * execution. The result of {@code task.checkedGet()} is passed to the caller. * * @param task {@link LavaSupplier} to execute * @return Value returned by {@code task.checkedGet()} * @throws RuntimeException checked exception raised during {@code task.checkedGet()} * will be wrapped in a {@link WrappedCheckedException} */ public static <R> R wrapCheckedException(LavaSupplier<R, ?> task) { try { return task.checkedGet(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new WrappedCheckedException(e); } } /** * Raise {@code e}. If {@code e} is a checked exception a {@link WrappedCheckedException} * wrapping {@code e} is raised instead. */ public static <R> R raiseUnchecked(Exception e) { throw wrapCheckedException(e); } /** * Raise {@code e} if {@code e} is a unchecked exception or an instance of {@code limit}. * Otherwise raise a {@link WrappedCheckedException} wrapping {@code e} instead. */ public static <E extends Exception> void raiseCheckedLimit(Exception e, Class<? extends E> limit) throws E { if (limit.isInstance(e)) { throw limit.cast(e); } else throw wrapCheckedException(e); } private static Exception assertCheckedException(Exception cause) { assert cause != null && !(cause instanceof RuntimeException); return cause; } }
package org.yestech.episodic.util; import org.yestech.episodic.objectmodel.ErrorResponse; import org.yestech.episodic.objectmodel.CreateAssetResponse; import org.yestech.episodic.objectmodel.CreateEpisodeResponse; import org.yestech.episodic.objectmodel.Shows; import org.apache.commons.httpclient.NameValuePair; import org.joda.time.DateTime; import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import java.io.InputStream; import static java.lang.String.valueOf; import java.util.SortedSet; import java.util.Map; import java.util.TreeSet; import java.util.ArrayList; /** * @author A.J. Wright */ public final class EpisodicUtil { private EpisodicUtil() { } /** * Unmarshalls the input stream into an object from org.yestech.episodic.objectmodel. * * @param content input stream containing xml content. * @return The unmarshalled object. * @throws javax.xml.bind.JAXBException Thrown if there are issues with the xml stream passed in. */ public static Object unmarshall(InputStream content) throws JAXBException { JAXBContext ctx = JAXBContext.newInstance( ErrorResponse.class, CreateAssetResponse.class, CreateEpisodeResponse.class, Shows.class); Unmarshaller unmarshaller = ctx.createUnmarshaller(); return unmarshaller.unmarshal(content); } /** * A simple method for joining an array of strings to a comma seperated string. * * @param strings An array of strings. * @return The array as single string joined by commas */ public static String join(String[] strings) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < strings.length; i++) { builder.append(strings[i]); if (i + 1 < strings.length) builder.append(","); } return builder.toString(); } /** * Generates the expires value needed to add to episodic requests. * <p/> * The current number of seconds since epoch (January 1, 1970). * * Actually there is a 10 minute buffer on this so that it will not time out for long uploads. * * * @return The current number of seconds since the epoch; */ public static String expires() { DateTime dt = new DateTime().plusMinutes(15); return valueOf(dt.getMillis() / 1000L); } /** * Returns the keys for the map in a set sorted alphabetically. * <p/> * This is used to help build the signature. * * @param map The map to get the keys for. * @return The keys sorted alphabetically. */ public static SortedSet<String> sortedKeys(Map<String, String> map) { return new TreeSet<String>(map.keySet()); } public static NameValuePair[] toNameValuePairArray(Map<String,String> map) { NameValuePair[] pairs = new NameValuePair[map.size()]; int count = 0; for (Map.Entry<String, String> entry : map.entrySet()) { pairs[count] = new NameValuePair(entry.getKey(), entry.getValue()); count++; } return pairs; } }
package permafrost.tundra.server; import com.wm.app.b2b.server.*; import com.wm.app.b2b.server.Package; import com.wm.data.IData; import permafrost.tundra.data.IDataMap; import permafrost.tundra.io.FileHelper; import permafrost.tundra.lang.BooleanHelper; import permafrost.tundra.lang.IterableEnumeration; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; /** * A collection of convenience methods for working with webMethods Integration Server packages. */ public class PackageHelper { /** * Disallow instantiation of this class. */ private PackageHelper() {} /** * Returns true if a package with the given name exists on this Integration Server. * * @param packageName The name of the package to check existence of. * @return True if a package with the given name exists. */ public static boolean exists(String packageName) { return getPackage(packageName) != null; } /** * Returns the package with the given name if it exists on this Integration Server. * * @param packageName The name of the package. * @return The package with the given name, or null if no package with the given name exists. */ public static Package getPackage(String packageName) { if (packageName == null) return null; return PackageManager.getPackage(packageName); } /** * Returns the package with the given name if it exists on this Integration Server in an IData representation. * * @param packageName The name of the package. * @return The IData representation of the package with the given name, * or null if no package with the given name exists. */ public static IData getPackageAsIData(String packageName) { return toIData(getPackage(packageName)); } /** * Returns true if the package with the given name is enabled on this Integration Server. * * @param packageName The name of the package. * @return True if the package with the given name is enabled. */ public static boolean isEnabled(String packageName) { Package pkg = getPackage(packageName); return pkg != null && pkg.isEnabled(); } /** * Returns a list of packages on this Integration Server. * @return A list of packages on this Integration Server. */ public static Package[] list() { return list(false); } /** * Returns a list of packages on this Integration Server. * @param enabledOnly If true, only returns enabled packages. * @return A list of packages on this Integration Server. */ public static Package[] list(boolean enabledOnly) { Package[] packages = PackageManager.getAllPackages(); SortedSet<Package> packageSet = new TreeSet<Package>(PackageNameComparator.getInstance()); if (packages != null) { for (Package item : packages) { if (item != null && (!enabledOnly || (enabledOnly && item.isEnabled()))) packageSet.add(item); } } return packageSet.toArray(new Package[packageSet.size()]); } /** * Returns a list of packages on this Integration Server as an IData[]. * @return A list of packages on this Integration Server as an IData[]. */ public static IData[] listAsIDataArray() { return listAsIDataArray(false); } /** * Returns a list of packages on this Integration Server as an IData[]. * @param enabledOnly If true, only returns enabled packages. * @return A list of packages on this Integration Server as an IData[]. */ public static IData[] listAsIDataArray(boolean enabledOnly) { return toIDataArray(list(enabledOnly)); } /** * Reloads the package with the given name. * * @param packageName The name of the package to be reloaded. */ public static void reload(String packageName) { PackageManager.loadPackage(packageName, true); } /** * Converts the given Package to an IData document. * * @param pkg The package to be converted. * @return An IData representation of the given package. */ public static IData toIData(Package pkg) { if (pkg == null) return null; IDataMap map = new IDataMap(); map.put("name", pkg.getName()); map.merge(toIData(pkg.getManifest())); IDataMap services = IDataMap.of((IData)map.get("services")); services.merge(toIData(pkg.getState())); map.put("services", services); IDataMap directories = new IDataMap(); directories.merge(toIData(pkg.getStore())); directories.put("config", FileHelper.normalize(ServerAPI.getPackageConfigDir(pkg.getName()))); map.put("directories", directories); return map; } /** * Converts the given list of packages to an IData[]. * * @param packages The list of packages to convert. * @return The IData[] representation of the packages. */ public static IData[] toIDataArray(Package ... packages) { if (packages == null) return new IData[0]; IData[] output = new IData[packages.length]; for (int i = 0; i < packages.length; i++) { output[i] = toIData(packages[i]); } return output; } /** * Converts an Package[] to a String[] by calling getName on each package in the list. * * @param packages The list of packages to convert. * @return The String[] representation of the list. */ private static String[] toStringArray(Package ... packages) { if (packages == null) return new String[0]; List<String> output = new ArrayList<String>(packages.length); for (Package item : packages) { if (item != null) output.add(item.getName()); } return output.toArray(new String[output.size()]); } /** * Converts an Iterable object to a String[] by calling toString on each object returned by the iterator. * * @param iterable The object to convert. * @return The String[] representation of the object. */ private static String[] toStringArray(Iterable iterable) { if (iterable == null) return new String[0]; List<String> output = new ArrayList<String>(); for (Object item : iterable) { output.add(item == null ? null : item.toString()); } return output.toArray(new String[output.size()]); } /** * Converts the given Manifest object to an IData document representation. * @param manifest The object to be converted. * @return An IData representation of the object. */ @SuppressWarnings("unchecked") private static IData toIData(Manifest manifest) { if (manifest == null) return null; IDataMap map = new IDataMap(); map.put("version", manifest.getVersion()); map.put("enabled?", BooleanHelper.emit(manifest.isEnabled())); map.put("system?", BooleanHelper.emit(manifest.isSystemPkg())); IData[] packageDependencies = toIDataArray(manifest.getRequires()); map.put("dependencies", packageDependencies); map.put("dependencies.length", "" + packageDependencies.length); IDataMap services = new IDataMap(); String[] startupServices = toStringArray(manifest.getStartupServices()); services.put("startup", startupServices); services.put("startup.length", "" + startupServices.length); String[] shutdownServices = toStringArray(manifest.getShutdownServices()); services.put("shutdown", shutdownServices); services.put("shutdown.length", "" + shutdownServices.length); String[] replicationServices = toStringArray(manifest.getReplicationServices()); services.put("replication", replicationServices); services.put("replication.length", "" + replicationServices.length); map.put("services", services); return map; } /** * Convert the given list of package dependencies to an IData[]. * * @param packageDependencies The object to convert. * @return The IData[] representation of the object. */ private static IData[] toIDataArray(Iterable<Manifest.Requires> packageDependencies) { if (packageDependencies == null) return new IData[0]; List<IData> output = new ArrayList<IData>(); for (Manifest.Requires packageDependency : packageDependencies) { IDataMap map = new IDataMap(); map.put("package", packageDependency.getPackage()); map.put("version", packageDependency.getVersion()); output.add(map); } return output.toArray(new IData[output.size()]); } /** * Converts the given PackageState object to an IData document representation. * @param packageState The object to be converted. * @return An IData representation of the object. */ private static IData toIData(PackageState packageState) { if (packageState == null) return null; IDataMap map = new IDataMap(); String[] loadedServices = toStringArray(IterableEnumeration.of(packageState.getLoaded())); map.put("loaded", loadedServices); map.put("loaded.length", "" + loadedServices.length); return map; } /** * Converts the given PackageStore object to an IData document representation. * @param packageStore The object to be converted. * @return An IData representation of the object. */ private static IData toIData(PackageStore packageStore) { if (packageStore == null) return null; IDataMap map = new IDataMap(); map.put("root", FileHelper.normalize(packageStore.getPackageDir())); map.put("ns", FileHelper.normalize(packageStore.getNSDir())); map.put("pub", FileHelper.normalize(packageStore.getPubDir())); map.put("template", FileHelper.normalize(packageStore.getTemplateDir())); map.put("web", FileHelper.normalize(packageStore.getWebDir())); return map; } }
package pokeraidbot.domain.raid; import net.dv8tion.jda.core.entities.User; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import pokeraidbot.Utils; import pokeraidbot.domain.config.ClockService; import pokeraidbot.domain.config.LocaleService; import pokeraidbot.domain.errors.RaidExistsException; import pokeraidbot.domain.errors.RaidNotFoundException; import pokeraidbot.domain.errors.UserMessedUpException; import pokeraidbot.domain.errors.WrongNumberOfArgumentsException; import pokeraidbot.domain.gym.Gym; import pokeraidbot.domain.gym.GymRepository; import pokeraidbot.domain.pokemon.Pokemon; import pokeraidbot.domain.pokemon.PokemonRepository; import pokeraidbot.domain.raid.signup.SignUp; import pokeraidbot.infrastructure.jpa.config.Config; import pokeraidbot.infrastructure.jpa.raid.RaidEntity; import pokeraidbot.infrastructure.jpa.raid.RaidEntityRepository; import pokeraidbot.infrastructure.jpa.raid.RaidEntitySignUp; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.*; import static pokeraidbot.Utils.*; @Transactional public class RaidRepository { private static final Logger LOGGER = LoggerFactory.getLogger(RaidRepository.class); private ClockService clockService; private LocaleService localeService; private RaidEntityRepository raidEntityRepository; private PokemonRepository pokemonRepository; private GymRepository gymRepository; // Byte code instrumentation protected RaidRepository() { } @Autowired public RaidRepository(ClockService clockService, LocaleService localeService, RaidEntityRepository raidEntityRepository, PokemonRepository pokemonRepository, GymRepository gymRepository) { this.clockService = clockService; this.localeService = localeService; this.raidEntityRepository = raidEntityRepository; this.pokemonRepository = pokemonRepository; this.gymRepository = gymRepository; removeExpiredRaids(); } public String executeSignUpCommand(Config config, User user, Locale localeForUser, String[] args, String help) { String people = args[0]; String userName = user.getName(); if (args.length < 3 || args.length > 10) { throw new WrongNumberOfArgumentsException(userName, localeService, 3, args.length, help); } Integer numberOfPeople = Utils.assertNotTooManyOrNoNumber(user, localeService, people); String timeString = args[1]; StringBuilder gymNameBuilder = new StringBuilder(); for (int i = 2; i < args.length; i++) { gymNameBuilder.append(args[i]).append(" "); } String gymName = gymNameBuilder.toString().trim(); final Gym gym = gymRepository.search(userName, gymName, config.getRegion()); final Raid raid = getActiveRaidOrFallbackToExRaid(gym, config.getRegion()); LocalTime eta = Utils.parseTime(user, timeString); LocalDateTime realEta = LocalDateTime.of(raid.getEndOfRaid().toLocalDate(), eta); assertEtaNotAfterRaidEnd(user, raid, realEta, localeService); assertSignupTimeNotBeforeNow(user, realEta, localeService); raid.signUp(user, numberOfPeople, eta, this); final String currentSignupText = localeService.getMessageFor(LocaleService.CURRENT_SIGNUPS, localeForUser); final Set<SignUp> signUps = raid.getSignUps(); Set<String> signUpNames = Utils.getNamesOfThoseWithSignUps(signUps, true); final String allSignUpNames = StringUtils.join(signUpNames, ", "); final String signUpText = raid.getSignUps().size() > 1 ? currentSignupText + "\n" + allSignUpNames : ""; return localeService.getMessageFor(LocaleService.SIGNUPS, localeForUser, userName, gym.getName(), signUpText); } public void newRaid(String raidCreatorName, Raid raid) { RaidEntity raidEntity = getActiveOrFallbackToExRaidEntity(raid.getGym(), raid.getRegion()); final String pokemonName = raid.getPokemon().getName(); if (raidEntity != null) { final String existingEntityPokemon = raidEntity.getPokemon(); final boolean oneRaidIsEx = Utils.isRaidExPokemon(pokemonName) || Utils.isRaidExPokemon(existingEntityPokemon); if ((!oneRaidIsEx) || Utils.raidsCollide(raid.getEndOfRaid(), raidEntity.getEndOfRaid())) { throw new RaidExistsException(raidCreatorName, getRaidInstance(raidEntity), localeService, LocaleService.DEFAULT); } } saveRaid(raidCreatorName, raid); } private void saveRaid(String raidCreatorName, Raid raid) { final RaidEntity toBeSaved = new RaidEntity(UUID.randomUUID().toString(), raid.getPokemon().getName(), raid.getEndOfRaid(), raid.getGym().getName(), raidCreatorName, raid.getRegion()); raidEntityRepository.save(toBeSaved); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Created raid: " + toBeSaved); } } private Raid getRaidInstance(RaidEntity raidEntity) { Validate.notNull(raidEntity); final String region = raidEntity.getRegion(); final Raid raid = new Raid(pokemonRepository.getPokemon(raidEntity.getPokemon()), raidEntity.getEndOfRaid(), gymRepository.findByName(raidEntity.getGym(), region), localeService, region); raid.setCreator(raidEntity.getCreator()); raid.setId(raidEntity.getId()); Map<String, SignUp> signUps = new HashMap<>(); for (RaidEntitySignUp signUp : raidEntity.getSignUps()) { signUps.put(signUp.getResponsible(), new SignUp(signUp.getResponsible(), signUp.getNumberOfPeople(), LocalTime.parse(signUp.getEta(), Utils.timeParseFormatter))); } raid.setSignUps(signUps); return raid; } public Raid getActiveRaidOrFallbackToExRaid(Gym gym, String region) { RaidEntity raidEntity = getActiveOrFallbackToExRaidEntity(gym, region); if (raidEntity == null) { throw new RaidNotFoundException(gym, localeService); } final Raid raid = getRaidInstance(raidEntity); return raid; } private RaidEntity getActiveOrFallbackToExRaidEntity(Gym gym, String region) { RaidEntity raidEntity = null; List<RaidEntity> raidEntities = raidEntityRepository.findByGymAndRegionOrderByEndOfRaidAsc(gym.getName(), region); RaidEntity exEntity = null; for (RaidEntity entity : raidEntities) { if (entity.isExpired(clockService)) { raidEntityRepository.delete(entity); } else if (Utils.isRaidExPokemon(entity.getPokemon())) { exEntity = entity; break; } else { if (raidEntity != null) { throw new IllegalStateException("Raid state in database seems off. " + "Please notify the bot developer so it can be checked: " + raidEntity); } raidEntity = entity; } } if (raidEntity == null) { if (exEntity != null) { raidEntity = exEntity; } } return raidEntity; } public Set<Raid> getAllRaidsForRegion(String region) { removeExpiredRaids(); List<RaidEntity> raidEntityList = raidEntityRepository.findByRegionOrderByPokemonAscEndOfRaidAsc(region); Set<Raid> activeRaids = new LinkedHashSet<>(); for (RaidEntity entity : raidEntityList) { activeRaids.add(getRaidInstance(entity)); } return activeRaids; } private void removeExpiredRaids() { List<RaidEntity> raidEntityList = raidEntityRepository.findAll(); for (RaidEntity entity : raidEntityList) { removeRaidIfExpired(entity); } } private void removeRaidIfExpired(RaidEntity raidEntity) { if (raidEntity.isExpired(clockService)) { // Clean up expired raid raidEntityRepository.delete(raidEntity); } } public void addSignUp(String userName, Raid raid, SignUp theSignUp) { RaidEntity entity = getActiveOrFallbackToExRaidEntity(raid.getGym(), raid.getRegion()); RaidEntitySignUp entitySignUp = entity.getSignUp(userName); if (entitySignUp == null) { entity.addSignUp(new RaidEntitySignUp(userName, theSignUp.getHowManyPeople(), Utils.printTime(theSignUp.getArrivalTime()))); } else { entitySignUp.setNumberOfPeople(theSignUp.getHowManyPeople()); entitySignUp.setEta(Utils.printTime(theSignUp.getArrivalTime())); } raidEntityRepository.save(entity); } public void removeSignUp(String userName, Raid raid, SignUp theSignUp) { RaidEntity entity = getActiveOrFallbackToExRaidEntity(raid.getGym(), raid.getRegion()); entity.removeSignUp(new RaidEntitySignUp(userName, theSignUp.getHowManyPeople(), Utils.printTime(theSignUp.getArrivalTime()))); raidEntityRepository.save(entity); } public Set<Raid> getRaidsInRegionForPokemon(String region, Pokemon pokemon) { removeExpiredRaids(); List<RaidEntity> raidEntityList = raidEntityRepository.findByPokemonAndRegionOrderByEndOfRaidAsc(pokemon.getName(), region); Set<Raid> activeRaids = new LinkedHashSet<>(); for (RaidEntity entity : raidEntityList) { activeRaids.add(getRaidInstance(entity)); } return activeRaids; } public Raid changePokemon(Raid raid, Pokemon pokemon) { RaidEntity raidEntity = getActiveOrFallbackToExRaidEntity(raid.getGym(), raid.getRegion()); if (!raidEntity.getPokemon().equalsIgnoreCase(raid.getPokemon().getName())) { throw new IllegalStateException("Database issues. Please notify the developer: magnus.mickelsson@gmail.com and describe what happened."); } raidEntity.setPokemon(pokemon.getName()); raidEntity = raidEntityRepository.save(raidEntity); return getRaidInstance(raidEntity); } public Raid changeEndOfRaid(Raid raid, LocalDateTime newEndOfRaid) { RaidEntity raidEntity = getActiveOrFallbackToExRaidEntity(raid.getGym(), raid.getRegion()); if (!raidEntity.getPokemon().equalsIgnoreCase(raid.getPokemon().getName())) { throw new IllegalStateException("Database issues. Please notify the developer: magnus.mickelsson@gmail.com and describe what happened."); } raidEntity.setEndOfRaid(newEndOfRaid); raidEntity = raidEntityRepository.save(raidEntity); return getRaidInstance(raidEntity); } public boolean delete(Raid raid) { RaidEntity raidEntity = getActiveOrFallbackToExRaidEntity(raid.getGym(), raid.getRegion()); if (raidEntity != null) { raidEntityRepository.delete(raidEntity); return true; } else { return false; } } public Raid getById(String id) { return getRaidInstance(raidEntityRepository.getOne(id)); } public Raid modifySignUp(String raidId, User user, int mystic, int instinct, int valor, int plebs, LocalDateTime startAt) { RaidEntity raidEntity = raidEntityRepository.findOne(raidId); RaidEntitySignUp signUp = raidEntity.getSignUp(user.getName()); final String startAtTime = Utils.printTime(startAt.toLocalTime()); if (signUp == null) { final int sum = mystic + instinct + valor + plebs; assertSumNotLessThanOne(user, sum); raidEntity.addSignUp(new RaidEntitySignUp(user.getName(), sum, startAtTime)); } else { int sum = signUp.getNumberOfPeople(); if (startAt.toLocalTime().equals(Utils.parseTime(user, signUp.getEta()))) { sum = sum + mystic + instinct + valor + plebs; } else { signUp.setEta(startAtTime); // Reset number of signups to what the input gives since we changed time sum = mystic + instinct + valor + plebs; } assertSumNotLessThanOne(user, sum); signUp.setNumberOfPeople(sum); } raidEntity = raidEntityRepository.save(raidEntity); return getRaidInstance(raidEntity); } private void assertSumNotLessThanOne(User user, int sum) { if (sum <= 0) { throw new UserMessedUpException(user, localeService.getMessageFor(LocaleService.ERROR_PARSE_PLAYERS, localeService.getLocaleForUser(user.getName()), "" + sum, String.valueOf(HIGH_LIMIT_FOR_SIGNUPS))); } } public Raid removeFromSignUp(String raidId, User user, int mystic, int instinct, int valor, int plebs, LocalDateTime startAt) { RaidEntity raidEntity = raidEntityRepository.findOne(raidId); RaidEntitySignUp signUp = raidEntity.getSignUp(user.getName()); final String startAtTime = Utils.printTime(startAt.toLocalTime()); if (signUp == null) { // todo: i18n // Ignore this since there is apparantly no signup to remove users from } else if (startAtTime.equals(signUp.getEta())){ final int sum = signUp.getNumberOfPeople() - mystic - instinct - valor - plebs; if (sum <= 0) { // Remove signup raidEntity.removeSignUp(signUp); } else { signUp.setNumberOfPeople(sum); } raidEntity = raidEntityRepository.save(raidEntity); } else { // Ignore if they're trying to remove signups for a group they're no longer signed up for - we let them untick their emote } return getRaidInstance(raidEntity); } }
package ru.tehkode.permissions; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * * @author code */ public abstract class PermissionGroup extends PermissionEntity { public PermissionGroup(String groupName, PermissionManager manager) { super(groupName, manager); } public abstract String[] getOwnPermissions(String world); public abstract String getOwnOption(String option, String world, String defaultValue); public String getOwnOption(String option) { return this.getOwnOption(option, "", ""); } public String getOwnOption(String option, String world) { return this.getOwnOption(option, world, ""); } public boolean getOwnOptionBoolean(String optionName, String world, boolean defaultValue) { String option = this.getOwnOption(optionName, world, Boolean.toString(defaultValue)); if ("false".equalsIgnoreCase(option)) { return false; } else if ("true".equalsIgnoreCase(option)) { return true; } return defaultValue; } public int getOwnOptionInteger(String optionName, String world, int defaultValue) { String option = this.getOwnOption(optionName, world, Integer.toString(defaultValue)); try { return Integer.parseInt(option); } catch (NumberFormatException e) { } return defaultValue; } public double getOwnOptionDouble(String optionName, String world, double defaultValue) { String option = this.getOwnOption(optionName, world, Double.toString(defaultValue)); try { return Double.parseDouble(option); } catch (NumberFormatException e) { } return defaultValue; } protected abstract void removeGroup(); public abstract void setParentGroups(String[] parentGroups); public void setParentGroups(PermissionGroup[] parentGroups) { List<String> groups = new LinkedList<String>(); for (PermissionGroup group : parentGroups) { groups.add(group.getName()); } this.setParentGroups(groups.toArray(new String[0])); } public boolean isRanked() { return (this.getRank() > 0); } public int getRank() { return this.getOwnOptionInteger("rank", "", 0); } public void setRank(int rank) { if (rank > 0) { this.setOption("rank", Integer.toString(rank)); } else { this.setOption("rank", null); } } public String getRankLadder() { return this.getOption("rank-ladder", "", "default"); } public void setRankLadder(String rankGroup) { if (rankGroup.isEmpty() || rankGroup.equals("default")) { rankGroup = null; } this.setOption("rank-ladder", rankGroup); } @Override public String getPrefix() { String localPrefix = super.getPrefix(); if (localPrefix == null || localPrefix.isEmpty()) { for (PermissionGroup group : this.getParentGroups()) { localPrefix = group.getPrefix(); if (localPrefix != null && !localPrefix.isEmpty()) { break; } } } if (localPrefix == null) { // NPE safety localPrefix = ""; } return localPrefix; } @Override public String getSuffix() { String localSuffix = super.getSuffix(); if (localSuffix == null || localSuffix.isEmpty()) { for (PermissionGroup group : this.getParentGroups()) { localSuffix = group.getSuffix(); if (localSuffix != null && !localSuffix.isEmpty()) { break; } } } if (localSuffix == null) { // NPE safety localSuffix = ""; } return localSuffix; } @Override public String[] getPermissions(String world) { List<String> permissions = new LinkedList<String>(); this.getInheritedPermissions(world, permissions, true); return permissions.toArray(new String[0]); } protected void getInheritedPermissions(String world, List<String> permissions, boolean groupInheritance) { permissions.addAll(Arrays.asList(this.getTimedPermissions(world))); permissions.addAll(Arrays.asList(this.getOwnPermissions(world))); if (world != null) { // World inheritance for (String parentWorld : this.manager.getWorldInheritance(world)) { getInheritedPermissions(parentWorld, permissions, false); } this.getInheritedPermissions(null, permissions, false); } // Group inhertance if (groupInheritance) { for (PermissionGroup group : this.getParentGroups()) { group.getInheritedPermissions(world, permissions, true); } } } @Override public void addTimedPermission(String permission, String world, int lifeTime) { super.addTimedPermission(permission, world, lifeTime); this.clearMembersCache(); } @Override public void removeTimedPermission(String permission, String world) { super.removeTimedPermission(permission, world); this.clearMembersCache(); } protected void clearMembersCache() { for (PermissionUser user : this.manager.getUsers(this.getName(), true)) { user.clearCache(); } } public boolean isChildOf(String groupName, boolean checkInheritance) { return isChildOf(this.manager.getGroup(groupName), checkInheritance); } public boolean isChildOf(PermissionGroup group, boolean checkInheritance) { if (group == null) { return false; } for (PermissionGroup parentGroup : this.getParentGroups()) { if (group.equals(parentGroup)) { return true; } if (checkInheritance && parentGroup.isChildOf(group, checkInheritance)) { return true; } } return false; } public PermissionGroup[] getParentGroups() { Set<PermissionGroup> parentGroups = new HashSet<PermissionGroup>(); for (String parentGroup : this.getParentGroupsNamesImpl()) { // Yeah horrible thing, i know, that just safety from invoking empty named groups parentGroup = parentGroup.trim(); if (parentGroup.isEmpty()) { continue; } if (parentGroup.equals(this.getName())) { continue; } PermissionGroup group = this.manager.getGroup(parentGroup); if (!group.isChildOf(this, true)) { // To prevent cyclic inheritance parentGroups.add(group); } } return parentGroups.toArray(new PermissionGroup[0]); } public PermissionGroup[] getChildGroups() { return this.manager.getGroups(this.getName()); } public PermissionUser[] getUsers() { return this.manager.getUsers(this.getName()); } public String[] getParentGroupsNames() { List<String> groups = new LinkedList<String>(); for (PermissionGroup group : this.getParentGroups()) { groups.add(group.getName()); } return groups.toArray(new String[0]); } public boolean isChildOf(String groupName) { return this.isChildOf(groupName, false); } protected abstract String[] getParentGroupsNamesImpl(); @Override public final void remove() { for (PermissionGroup group : this.manager.getGroups(this.getName())) { List<PermissionGroup> parentGroups = new LinkedList<PermissionGroup>(Arrays.asList(group.getParentGroups())); parentGroups.remove(this); group.setParentGroups(parentGroups.toArray(new PermissionGroup[0])); } if (this.manager.getGroups(this.getName()).length > 0) { return; } for (PermissionUser user : this.manager.getUsers(this.getName())) { user.removeGroup(this); } this.removeGroup(); } public String getOwnPrefix() { return this.prefix; } public String getOwnSuffix() { return this.suffix; } }
package rx.javafx.sources; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import rx.Observable; import rx.functions.Func1; import rx.schedulers.JavaFxScheduler; import rx.subscriptions.JavaFxSubscriptions; import java.util.HashMap; public final class ObservableListSource { public static <T> Observable<ObservableList<T>> fromObservableList(final ObservableList<T> source) { return Observable.create((Observable.OnSubscribe<ObservableList<T>>) subscriber -> { ListChangeListener<T> listener = c -> subscriber.onNext(source); source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } public static <T> Observable<T> fromObservableListAdds(final ObservableList<T> source) { return Observable.create((Observable.OnSubscribe<T>) subscriber -> { ListChangeListener<T> listener = c -> { while (c.next()) { if (c.wasAdded()) { c.getAddedSubList().forEach(subscriber::onNext); } } }; source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } public static <T> Observable<T> fromObservableListRemovals(final ObservableList<T> source) { return Observable.create((Observable.OnSubscribe<T>) subscriber -> { ListChangeListener<T> listener = c -> { while (c.next()) { if (c.wasRemoved()) { c.getRemoved().forEach(subscriber::onNext); } } }; source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } public static <T> Observable<T> fromObservableListUpdates(final ObservableList<T> source) { return Observable.create((Observable.OnSubscribe<T>) subscriber -> { ListChangeListener<T> listener = c -> { while (c.next()) { if (c.wasUpdated()) { for (int i = c.getFrom(); i < c.getTo(); i++) { subscriber.onNext(c.getList().get(i)); } } } }; source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } public static <T> Observable<ListChange<T>> fromObservableListChanges(final ObservableList<T> source) { return Observable.create((Observable.OnSubscribe<ListChange<T>>) subscriber -> { ListChangeListener<T> listener = c -> { while (c.next()) { if (c.wasAdded()) { c.getAddedSubList().forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); } if (c.wasRemoved()) { c.getRemoved().forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); } if (c.wasUpdated()) { for (int i = c.getFrom(); i < c.getTo(); i++) { subscriber.onNext(ListChange.of(c.getList().get(i),Flag.UPDATED)); } } } }; source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } public static <T> Observable<ListChange<T>> fromObservableListDistinctChanges(final ObservableList<T> source) { return Observable.create((Observable.OnSubscribe<ListChange<T>>) subscriber -> { final DupeCounter<T> dupeCounter = new DupeCounter<>(); source.stream().forEach(dupeCounter::add); ListChangeListener<T> listener = c -> { while (c.next()) { if (c.wasAdded()) { c.getAddedSubList().stream().filter(v -> dupeCounter.add(v) == 1) .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); } if (c.wasRemoved()) { c.getRemoved().stream().filter(v -> dupeCounter.remove(v) == 0) .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); } } }; source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } public static <T,R> Observable<ListChange<T>> fromObservableListDistinctChanges(final ObservableList<T> source, Func1<T,R> mapper) { return Observable.create((Observable.OnSubscribe<ListChange<T>>) subscriber -> { final DupeCounter<R> dupeCounter = new DupeCounter<>(); source.stream().map(mapper::call).forEach(dupeCounter::add); ListChangeListener<T> listener = c -> { while (c.next()) { if (c.wasAdded()) { c.getAddedSubList().stream().filter(v -> dupeCounter.add(mapper.call(v)) == 1) .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); } if (c.wasRemoved()) { c.getRemoved().stream().filter(v -> dupeCounter.remove(mapper.call(v)) == 0) .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); } } }; source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } public static <T,R> Observable<ListChange<R>> fromObservableListDistinctMappings(final ObservableList<T> source, Func1<T,R> mapper) { return Observable.create((Observable.OnSubscribe<ListChange<R>>) subscriber -> { final DupeCounter<R> dupeCounter = new DupeCounter<>(); source.stream().map(mapper::call).forEach(dupeCounter::add); ListChangeListener<T> listener = c -> { while (c.next()) { if (c.wasAdded()) { c.getAddedSubList().stream().map(mapper::call) .filter(v -> dupeCounter.add(v) == 1) .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); } if (c.wasRemoved()) { c.getRemoved().stream().map(mapper::call) .filter(v -> dupeCounter.remove(v) == 0) .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); } } }; source.addListener(listener); subscriber.add(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); }).subscribeOn(JavaFxScheduler.getInstance()); } private static final class DupeCounter<T> { private final HashMap<T,Integer> counts = new HashMap<>(); public int add(T value) { Integer prev = counts.get(value); int newVal = 0; if (prev == null) { newVal = 1; counts.put(value, newVal); } else { newVal = prev + 1; counts.put(value, newVal); } return newVal; } public int remove(T value) { Integer prev = counts.get(value); if (prev != null && prev > 0) { int newVal = prev - 1; counts.put(value, newVal); return newVal; } else { throw new IllegalStateException(); } } } public static final class ListChange<T> { private final T value; private final Flag flag; private ListChange(T value, Flag flag) { this.value = value; this.flag = flag; } public static <T> ListChange<T> of(T value, Flag flag) { return new ListChange<>(value, flag); } public T getValue() { return value; } public Flag getFlag() { return flag; } @Override public String toString() { return flag + " " + value; } } public enum Flag { ADDED, REMOVED, UPDATED; } }
package seedu.task.logic.commands; import java.util.Optional; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import seedu.task.model.TaskManager; /** * Clears the task manager. */ public class ClearCommand extends Command { public static final String COMMAND_WORD = "clear"; public static final String MESSAGE_SUCCESS = "Task Manager has been cleared!"; public static final String MESSAGE_FAILURE = "Task Manager has not been cleared"; public static final String MESSAGE_NO_TASKS = "0 tasks listed!"; public ClearCommand() { } @Override public CommandResult execute() { assert model != null; try { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Clear all tasks"); alert.setHeaderText("Are you sure you want to clear all tasks in the task manager?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { model.resetData(TaskManager.getEmptyTaskManager()); return new CommandResult(MESSAGE_SUCCESS); } else { return new CommandResult(MESSAGE_FAILURE); } } catch (ExceptionInInitializerError | IllegalStateException e) { model.resetData(TaskManager.getEmptyTaskManager()); return new CommandResult(MESSAGE_SUCCESS); } } }
package seedu.tasklist.model.task; import seedu.tasklist.commons.util.CollectionUtil; import seedu.tasklist.model.tag.UniqueTagList; /** * Represents a Floating Task in the task list. * Guarantees: details are present and not null, field values are validated. */ public class FloatingTask extends Task implements ReadOnlyFloatingTask { private Name name; private Comment comment; private Priority priority; private Status status; private UniqueTagList tags; /** * Every field must be present and not null. */ public FloatingTask(Name name, Comment comment, Priority priority, Status status, UniqueTagList tags) { super(name, comment, priority, status, tags); assert !CollectionUtil.isAnyNull(name, comment, priority, status, tags); this.name = name; this.comment = comment; this.priority = priority; this.status = status; this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list } /** * Creates a copy of the given ReadOnlyFloatingTask. */ public FloatingTask(ReadOnlyFloatingTask source) { this(source.getName(), source.getComment(), source.getPriority(), source.getStatus(), source.getTags()); } public void setName(Name name) { assert name != null; this.name = name; } @Override public Name getName() { return name; } public void setComment(Comment comment) { assert comment != null; this.comment = comment; } @Override public Comment getComment() { return comment; } @Override public UniqueTagList getTags() { return tags; } public void setPriority(Priority priority){ assert priority != null; this.priority = priority; } public Priority getPriority() { return priority; } public void setStatus(Status status){ assert status != null; this.status = status; } public Status getStatus() { return status; } /** * Replaces this person's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } /** * Updates this person with the details of {@code replacement}. */ public void resetData(ReadOnlyFloatingTask replacement) { assert replacement != null; this.setName(replacement.getName()); this.setComment(replacement.getComment()); this.setPriority(replacement.getPriority()); this.setStatus(replacement.getStatus()); this.setTags(replacement.getTags()); } }
package tbax.baxshops.serialization; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import tbax.baxshops.BaxShop; import tbax.baxshops.Format; import tbax.baxshops.ShopPlugin; import tbax.baxshops.notification.Notification; import tbax.baxshops.serialization.states.State_00300; import tbax.baxshops.serialization.states.State_00421; import java.io.*; import java.text.DecimalFormat; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; public final class SavedState { static final String YAML_FILE_PATH = "shops.yml"; private static final double STATE_VERSION = State_00421.VERSION; // state file format version private static double loadedState; /** * A map of ids map to their shops */ ShopMap shops = new ShopMap(); /** * A map containing each player's notifications */ Map<UUID, Deque<Notification>> pending = new HashMap<>(); /** * A map containing each player's attributes for when they're offline */ PlayerMap players = new PlayerMap(); final ShopPlugin plugin; final Logger log; BaxConfig config; SavedState(@NotNull ShopPlugin plugin) { this.plugin = plugin; this.log = plugin.getLogger(); players.put(StoredPlayer.DUMMY); shops.put(BaxShop.DUMMY_UUID, BaxShop.DUMMY_SHOP); } public static double getLoadedState() { return loadedState; } public @Nullable BaxShop getShop(UUID uid) { return shops.get(uid); } public @Nullable BaxShop getShop(Location loc) { return shops.getShopByLocation(loc); } public static SavedState readFromDisk(@NotNull ShopPlugin plugin) { File stateLocation = new File(plugin.getDataFolder(), YAML_FILE_PATH); if (!stateLocation.exists()) { plugin.getLogger().info("YAML file did not exist"); return new SavedState(plugin); } double ver; if (plugin.getConfig().contains("StateVersion")) { ver = plugin.getConfig().getDouble("StateVersion", STATE_VERSION); } else { ver = State_00300.VERSION; // version 3.0 was the last version not to be in config.yml } loadedState = ver; StateLoader loader; try { loader = UpgradeableSerialization.getStateLoader(plugin, ver); } catch (ReflectiveOperationException e) { plugin.getLogger().warning("Unknown state file version. Starting from scratch..."); return new SavedState(plugin); } if (ver != STATE_VERSION) { plugin.getLogger().info("Converting state file version " + (new DecimalFormat("0.0")).format(ver)); } return loader.loadState(YamlConfiguration.loadConfiguration(stateLocation)); } private void deleteLatestBackup(File backupFolder) { File[] backups = backupFolder.listFiles((f, name) -> name.endsWith(".yml")); int nBaks = getConfig().getBackups(); if (backups == null || nBaks <= 0 || backups.length < nBaks) { return; } List<String> names = Arrays.stream(backups) .map(f -> f.getName().substring(0, f.getName().lastIndexOf('.'))) .filter(n -> Format.parseFileDate(n) != null) .sorted(Comparator.comparing(Format::parseFileDate)) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); while (names.size() >= nBaks) { File delete = new File(backupFolder, names.remove(names.size() - 1) + ".yml"); if (!delete.delete()) { log.warning(String.format("Unable to delete old backup %s", delete.getName())); } } } /** * Attempts to back up the shops.yml save file. * @return a boolean indicating success */ public boolean backup() { File stateLocation = new File(plugin.getDataFolder(), YAML_FILE_PATH); if (!stateLocation.exists()) { log.warning("Aborting backup: shops.yml not found"); return false; } File backupFolder = new File(plugin.getDataFolder(), "backups"); if (!backupFolder.exists() && !backupFolder.mkdirs()) { log.severe("Unable to create backups folder!"); return false; } deleteLatestBackup(backupFolder); try { String backupName = Format.FILE_DATE_FORMAT.format(new Date()) + ".yml"; File backup = new File(backupFolder, backupName); try (InputStream in = new FileInputStream(stateLocation)) { try (OutputStream out = new FileOutputStream(backup)) { byte[] buf = new byte[1024]; int i; while ((i = in.read(buf)) > 0) { out.write(buf, 0, i); } } } } catch (IOException e) { e.printStackTrace(); log.severe("Backup failed!"); return false; } return true; } public void addShop(BaxShop shop) { shops.put(shop.getId(), shop); } public boolean addLocation(BaxShop shop, Location loc) { BaxShop otherShop = shops.getShopByLocation(loc); if (otherShop == null) { shops.addLocation(shop.getId(), loc); return true; } return false; } /** * Gets a list of notifications for a player. * * @param player the player * @return the player's notifications */ public @NotNull Deque<Notification> getNotifications(OfflinePlayer player) { Deque<Notification> n = pending.get(player.getUniqueId()); if (n == null) pending.put(player.getUniqueId(), n = new ArrayDeque<>()); return n; } private void resaveConfig() { if (!config.backup()) plugin.getLogger().warning("Could not backup config. Configuration may be lost."); if (config.getStateVersion() != STATE_VERSION) config.getFileConfig().set("StateVersion", STATE_VERSION); config.save(); } /** * Saves all shops */ public void writeToDisk() { if (!backup()) { log.warning("Failed to back up BaxShops"); } if (config.getStateVersion() != STATE_VERSION || config.saveDefaults()) { resaveConfig(); } FileConfiguration state = new YamlConfiguration(); state.set("shops", new ArrayList<>(shops.values())); ConfigurationSection notes = state.createSection("notes"); for (Map.Entry<UUID, Deque<Notification>> entry : pending.entrySet()) { notes.set(entry.getKey().toString(), new ArrayList<>(entry.getValue())); } state.set("players", new ArrayList<>(players.values())); try { File dir = plugin.getDataFolder(); if (!dir.exists() && !dir.mkdirs()) { log.severe("Unable to make data folder!"); } else { state.save(new File(dir, YAML_FILE_PATH)); } } catch (IOException e) { log.severe("Save failed"); e.printStackTrace(); } } public @NotNull StoredPlayer getOfflinePlayer(UUID uuid) { StoredPlayer player = players.get(uuid); if (player == null) return StoredPlayer.ERROR; return player; } public @NotNull StoredPlayer getOfflinePlayerSafe(UUID uuid) { StoredPlayer player = players.get(uuid); if (player == null) { player = new StoredPlayer(uuid.toString(), uuid); players.put(player); } return player; } public List<StoredPlayer> getOfflinePlayer(String playerName) { return players.get(playerName); } public void joinPlayer(Player player) { StoredPlayer storedPlayer = players.convertLegacy(player); if (storedPlayer == null) { storedPlayer = new StoredPlayer(player); } else { Deque<Notification> notes = pending.remove(storedPlayer.getUniqueId()); players.remove(storedPlayer.getUniqueId()); if (notes != null) pending.put(storedPlayer.getUniqueId(), notes); } players.put(storedPlayer.getUniqueId(), storedPlayer); } public BaxConfig getConfig() { if (config == null) config = new BaxConfig(plugin); return config; } public void reload() { log.info("Reloading BaxShops..."); writeToDisk(); log.info("Clearing memory..."); shops.clear(); players.clear(); pending.clear(); log.info("Loading BaxShops..."); SavedState savedState = readFromDisk(plugin); shops = savedState.shops; players = savedState.players; pending = savedState.pending; config = savedState.config; log.info("BaxShops has finished reloading"); } public void removeLocation(UUID shopId, Location loc) { shops.removeLocation(shopId, loc); } public void removeShop(UUID shopId) { shops.remove(shopId); } public Collection<StoredPlayer> getRegisteredPlayers() { return players.values().stream() .filter(n -> !StoredPlayer.ERROR.equals(n)) .collect(Collectors.toList()); } public BaxShop getShop(String shortId) { return shops.getShopByAbbreviatedId(shortId); } }
package mod._cfgmgr2; import com.sun.star.configuration.backend.XLayer; import com.sun.star.configuration.backend.XLayerHandler; import com.sun.star.lang.XInitialization; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import java.io.PrintWriter; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.XLayerHandlerImpl; import util.XLayerImpl; public class SingleBackendAdapter extends TestCase { /** Called to create an instance of <code>TestEnvironment</code> with an * object to test and related objects. Subclasses should implement this * method to provide the implementation and related objects. The method is * called from <code>getTestEnvironment()</code>. * * @param tParam test parameters * @param log writer to log information while testing * * @see TestEnvironment * @see #getTestEnvironment() * */ protected TestEnvironment createTestEnvironment(TestParameters tParam, PrintWriter log) { XInterface oObj = null; XInterface backend = null; try { Object[] args = new Object[1]; args[0] = ((XMultiServiceFactory)tParam.getMSF()) .createInstance("com.sun.star.configuration.bootstrap.BootstrapContext"); backend = (XInterface) ((XMultiServiceFactory)tParam.getMSF()) .createInstanceWithArguments("com.sun.star.comp.configuration.backend.LocalSingleBackend",args); oObj = (XInterface) ((XMultiServiceFactory)tParam.getMSF()) .createInstance("com.sun.star.comp.configuration.backend.SingleBackendAdapter"); XInitialization xInit = (XInitialization) UnoRuntime.queryInterface( XInitialization.class, oObj); xInit.initialize(new Object[] { backend }); } catch (com.sun.star.uno.Exception e) { e.printStackTrace(); } log.println("Implementation name: "+ util.utils.getImplName(oObj)); TestEnvironment tEnv = new TestEnvironment(oObj); return tEnv; } }
package tigase.cluster; import tigase.cluster.api.ClusterControllerIfc; import tigase.cluster.api.ClusteredComponentIfc; import tigase.cluster.api.SessionManagerClusteredIfc; import tigase.cluster.strategy.ClusteringStrategyIfc; import tigase.server.Message; import tigase.server.Packet; import tigase.server.xmppsession.SessionManager; import tigase.stats.StatisticsList; import tigase.util.DNSResolver; import tigase.util.TigaseStringprepException; import tigase.xmpp.BareJID; import tigase.xmpp.JID; import tigase.xmpp.StanzaType; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.XMPPSession; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Map; import javax.script.Bindings; /** * Class SessionManagerClusteredOld * * * Created: Tue Nov 22 07:07:11 2005 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class SessionManagerClustered extends SessionManager implements ClusteredComponentIfc, SessionManagerClusteredIfc { /** Field description */ public static final String CLUSTER_STRATEGY_VAR = "clusterStrategy"; /** Field description */ public static final String MY_DOMAIN_NAME_PROP_KEY = "domain-name"; /** Field description */ public static final String STRATEGY_CLASS_PROP_KEY = "sm-cluster-strategy-class"; /** Field description */ public static final String STRATEGY_CLASS_PROP_VAL = "tigase.cluster.strategy.DefaultClusteringStrategy"; /** Field description */ public static final String STRATEGY_CLASS_PROPERTY = "--sm-cluster-strategy-class"; /** Field description */ public static final int SYNC_MAX_BATCH_SIZE = 1000; /** * Variable <code>log</code> is a class logger. */ private static final Logger log = Logger.getLogger(SessionManagerClustered.class .getName()); private ClusterControllerIfc clusterController = null; private JID my_address = null; private JID my_hostname = null; private int nodesNo = 0; private ClusteringStrategyIfc strategy = null; /** * The method checks whether the given JID is known to the installation, * either user connected to local machine or any of the cluster nodes. False * result does not mean the user is not connected. It means the method does * not know anything about the JID. Some clustering strategies may not cache * online users information. * * @param jid * a user's JID for whom we query information. * * @return true if the user is known as online to the installation, false if * the method does not know. */ @Override public boolean containsJid(BareJID jid) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Called for jid: {0}", jid); } return super.containsJid(jid) || strategy.containsJid(jid); } /** * Method description * * * @param packet * * @return */ @Override public boolean fastAddOutPacket(Packet packet) { return super.fastAddOutPacket(packet); } /** * Method description * * * @param packet * @param conn */ @Override public void handleLocalPacket(Packet packet, XMPPResourceConnection conn) { if (strategy != null) { strategy.handleLocalPacket(packet, conn); } } /** * Method description * * * @param userId * @param conn */ @Override public void handleLogin(BareJID userId, XMPPResourceConnection conn) { super.handleLogin(userId, conn); strategy.handleLocalUserLogin(userId, conn); } /** * Method description * * * @param binds */ @Override public void initBindings(Bindings binds) { super.initBindings(binds); binds.put(CLUSTER_STRATEGY_VAR, strategy); } /** * The method is called on cluster node connection event. This is a * notification to the component that a new node has connected to the system. * * @param node * is a hostname of a new cluster node connected to the system. */ @Override public void nodeConnected(String node) { log.log(Level.FINE, "Nodes connected: {0}", node); JID jid = JID.jidInstanceNS(getName(), node, null); strategy.nodeConnected(jid); sendAdminNotification("Cluster node '" + node + "' connected (" + (new Date()) + ")", "New cluster node connected: " + node, node); } /** * Method is called on cluster node disconnection event. This is a * notification to the component that there was network connection lost to one * of the cluster nodes. * * @param node * is a hostname of a cluster node generating the event. */ @Override public void nodeDisconnected(String node) { log.log(Level.FINE, "Nodes disconnected: {0}", node); JID jid = JID.jidInstanceNS(getName(), node, null); strategy.nodeDisconnected(jid); // Not sure what to do here, there might be still packets // from the cluster node waiting.... // delTrusted(jid); sendAdminNotification("Cluster node '" + node + "' disconnected (" + (new Date()) + ")", "Cluster node disconnected: " + node, node); } /** * Concurrency control method. Returns preferable number of threads set for * this component. * * * @return preferable number of threads set for this component. */ @Override public int processingInThreads() { return Math.max(nodesNo, super.processingInThreads()); } /** * Concurrency control method. Returns preferable number of threads set for * this component. * * * @return preferable number of threads set for this component. */ @Override public int processingOutThreads() { return Math.max(nodesNo, super.processingOutThreads()); } /** * This is a standard component method for processing packets. The method * takes care of cases where the packet cannot be processed locally, in such a * case it is forwarded to another node. * * * @param packet */ @Override public void processPacket(Packet packet) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Received packet: {0}", packet); } // long startTime = System.currentTimeMillis(); // int idx = tIdx; // tIdx = (tIdx + 1) % maxIdx; // long cmdTm = 0; // long clTm = 0; // long chTm = 0; // long smTm = 0; if (packet.isCommand() && processCommand(packet)) { packet.processedBy("SessionManager"); // cmdTm = System.currentTimeMillis() - startTime; } else { XMPPResourceConnection conn = getXMPPResourceConnection(packet); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Ressource connection found: {0}", conn); } boolean clusterOK = strategy.processPacket(packet, conn); // clTm = System.currentTimeMillis() - startTime; if (conn == null) { if (isBrokenPacket(packet) || processAdminsOrDomains(packet)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Ignoring/dropping packet: {0}", packet); } } else { // Process is as packet to offline user only if there are no other // nodes for the packet to be processed. if (!clusterOK) { // Process packet for offline user processPacket(packet, (XMPPResourceConnection) null); } } } else { processPacket(packet, conn); // smTm = System.currentTimeMillis() - startTime; } } // commandTime[idx] = cmdTm; // clusterTime[idx] = clTm; // checkingTime[idx] = chTm; // smTime[idx] = smTm; } /** * Method description * * * @param packet * @param conn */ @Override public void processPacket(Packet packet, XMPPResourceConnection conn) { super.processPacket(packet, conn); } /** * If the installation knows about user's JID, that he is connected to the * system, then this method returns all user's connection IDs. As an * optimization we can forward packets to all user's connections directly from * a single node. * * @param jid * a user's JID for whom we query information. * * @return a list of all user's connection IDs. */ @Override public JID[] getConnectionIdsForJid(BareJID jid) { JID[] ids = super.getConnectionIdsForJid(jid); if (ids == null) { ids = strategy.getConnectionIdsForJid(jid); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Called for jid: {0}, results: {1}", new Object[] { jid, Arrays.toString(ids) }); } return ids; } /** * Loads the component's default configuration to the configuration management * subsystem. * * @param params * is a Map with system-wide default settings found in * init.properties file or similar location. * * @return a Map with all default component settings generated from the * default parameters in init.properties file. */ @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> props = super.getDefaults(params); String strategy_class = (String) params.get(STRATEGY_CLASS_PROPERTY); if (strategy_class == null) { strategy_class = STRATEGY_CLASS_PROP_VAL; } props.put(STRATEGY_CLASS_PROP_KEY, strategy_class); try { ClusteringStrategyIfc strat_tmp = (ClusteringStrategyIfc) Class.forName( strategy_class).newInstance(); Map<String, Object> strat_defs = strat_tmp.getDefaults(params); if (strat_defs != null) { props.putAll(strat_defs); } } catch (Exception e) { log.log(Level.SEVERE, "Can not instantiate clustering strategy for class: " + strategy_class, e); } String[] local_domains = DNSResolver.getDefHostNames(); if (params.get(GEN_VIRT_HOSTS) != null) { local_domains = ((String) params.get(GEN_VIRT_HOSTS)).split(","); } // defs.put(LOCAL_DOMAINS_PROP_KEY, LOCAL_DOMAINS_PROP_VAL); props.put(MY_DOMAIN_NAME_PROP_KEY, local_domains[0]); if (params.get(CLUSTER_NODES) != null) { String[] cl_nodes = ((String) params.get(CLUSTER_NODES)).split(","); nodesNo = cl_nodes.length; } return props; } // private long calcAverage(long[] timings) { // long res = 0; // for (long ppt : timings) { // res += ppt; // long processingTime = res / timings.length; // return processingTime; /** * Method generates and returns component's statistics. * * @param list * is a collection with statistics to which this component can add * own metrics. */ @Override public void getStatistics(StatisticsList list) { super.getStatistics(list); strategy.getStatistics(list); // list.add(getName(), "Average commandTime on last " + commandTime.length // + " runs [ms]", calcAverage(commandTime), Level.FINE); // list.add(getName(), "Average clusterTime on last " + clusterTime.length // + " runs [ms]", calcAverage(clusterTime), Level.FINE); // list.add(getName(), "Average checkingTime on last " + checkingTime.length // + " runs [ms]", calcAverage(checkingTime), Level.FINE); // list.add(getName(), "Average smTime on last " + smTime.length + // " runs [ms]", // calcAverage(smTime), Level.FINE); } /** * Returns active clustering strategy object. * * @return active clustering strategy object. */ public ClusteringStrategyIfc getStrategy() { return strategy; } /** * Method description * * * * @param p * * @return */ @Override public XMPPResourceConnection getXMPPResourceConnection(Packet p) { return super.getXMPPResourceConnection(p); } /** * Method description * * * @return */ @Override public ConcurrentHashMap<JID, XMPPResourceConnection> getXMPPResourceConnections() { return connectionsByFrom; } /** * Method description * * * @return */ @Override public ConcurrentHashMap<BareJID, XMPPSession> getXMPPSessions() { return sessionsByNodeId; } /** * Method checks whether the clustering strategy has a complete JIDs info. * That is whether the strategy knows about all users connected to all nodes. * Some strategies may choose not to share this information among nodes, hence * the methods returns false. Other may synchronize this information and can * provide it to further optimize cluster traffic. * * * @return a true boolean value if the strategy has a complete information * about all users connected to all cluster nodes. */ @Override public boolean hasCompleteJidsInfo() { return strategy.hasCompleteJidsInfo(); } /** * Set's the configures the cluster controller object for cluster * communication and API. * * @param cl_controller */ @Override public void setClusterController(ClusterControllerIfc cl_controller) { clusterController = cl_controller; if (strategy != null) { strategy.setClusterController(clusterController); } // clusterController.removeCommandListener(USER_CONNECTED_CMD, userConnected); // clusterController.removeCommandListener(USER_DISCONNECTED_CMD, userDisconnected); // clusterController.removeCommandListener(USER_PRESENCE_CMD, userPresence); // clusterController.removeCommandListener(REQUEST_SYNCONLINE_CMD, requestSyncOnline); // clusterController.removeCommandListener(RESPOND_SYNCONLINE_CMD, respondSyncOnline); // clusterController.setCommandListener(USER_CONNECTED_CMD, userConnected); // clusterController.setCommandListener(USER_DISCONNECTED_CMD, userDisconnected); // clusterController.setCommandListener(USER_PRESENCE_CMD, userPresence); // clusterController.setCommandListener(REQUEST_SYNCONLINE_CMD, requestSyncOnline); // clusterController.setCommandListener(RESPOND_SYNCONLINE_CMD, respondSyncOnline); } /** * Standard component's configuration method. * * * @param props */ @Override public void setProperties(Map<String, Object> props) { super.setProperties(props); if (props.get(STRATEGY_CLASS_PROP_KEY) != null) { String strategy_class = (String) props.get(STRATEGY_CLASS_PROP_KEY); try { ClusteringStrategyIfc strategy_tmp = (ClusteringStrategyIfc) Class.forName( strategy_class).newInstance(); strategy_tmp.setProperties(props); // strategy_tmp.init(getName()); strategy = strategy_tmp; strategy.setSessionManagerHandler(this); log.log(Level.CONFIG, "Loaded SM strategy: " + strategy_class); // strategy.nodeConnected(getComponentId()); addTrusted(getComponentId()); if (clusterController != null) { strategy.setClusterController(clusterController); } } catch (Exception e) { log.log(Level.SEVERE, "Can not clustering strategy instance for class: " + strategy_class, e); } } try { if (props.get(MY_DOMAIN_NAME_PROP_KEY) != null) { my_hostname = JID.jidInstance((String) props.get(MY_DOMAIN_NAME_PROP_KEY)); my_address = JID.jidInstance(getName(), (String) props.get( MY_DOMAIN_NAME_PROP_KEY), null); } } catch (TigaseStringprepException ex) { log.log(Level.WARNING, "Creating component source address failed stringprep processing: {0}@{1}", new Object[] { getName(), my_hostname }); } } /** * The method intercept user's disconnect event. On user disconnect the method * takes a list of cluster nodes from the strategy and sends a notification to * all those nodes about the event. * * @see tigase.server.xmppsession.SessionManager#closeSession(tigase.xmpp. * XMPPResourceConnection, boolean) * * @param conn * @param closeOnly */ @Override protected void closeSession(XMPPResourceConnection conn, boolean closeOnly) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Called for conn: {0}, closeOnly: {1}", new Object[] { conn, closeOnly }); } // Exception here should not normally happen, but if it does, then // consequences might be severe, let's catch it then try { if (conn.isAuthorized() && conn.isResourceSet()) { BareJID userId = conn.getBareJID(); strategy.handleLocalUserLogout(userId, conn); } } catch (Exception ex) { log.log(Level.WARNING, "This should not happen, check it out!, ", ex); } // Exception here should not normally happen, but if it does, then // consequences might be severe, let's catch it then try { super.closeSession(conn, closeOnly); } catch (Exception ex) { log.log(Level.WARNING, "This should not happen, check it out!, ", ex); } } private void sendAdminNotification(String msg, String subject, String node) { String message = msg; if (node != null) { message = msg + "\n"; } int cnt = 0; message += node + " connected to " + getDefHostName(); Packet p_msg = Message.getMessage(my_address, my_hostname, StanzaType.normal, message, subject, "xyz", newPacketId(null)); sendToAdmins(p_msg); } } //~ Formatted in Tigase Code Convention on 13/07/06
package tigase.cluster; import tigase.annotations.TODO; import tigase.server.Message; //import tigase.cluster.methodcalls.SessionTransferMC; import tigase.server.Packet; import tigase.server.xmppsession.SessionManager; import tigase.stats.StatisticsList; import tigase.util.DNSResolver; import tigase.util.TigaseStringprepException; import tigase.xml.Element; import tigase.xmpp.BareJID; import tigase.xmpp.ConnectionStatus; import tigase.xmpp.JID; import tigase.xmpp.NoConnectionIdException; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.StanzaType; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.XMPPSession; import tigase.xmpp.impl.Presence; import java.util.ArrayDeque; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; /** * Class SessionManagerClusteredOld * * * Created: Tue Nov 22 07:07:11 2005 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class SessionManagerClustered extends SessionManager implements ClusteredComponent { private static final String AUTH_TIME = "auth-time"; private static final String CL_BR_INITIAL_PRESENCE = "cl-br-init-pres"; private static final String CL_BR_USER_CONNECTED = "cl-br-user_conn"; private static final String CONNECTION_ID = "connectionId"; private static final String CREATION_TIME = "creationTime"; private static final String ERROR_CODE = "errorCode"; /** Field description */ public static final String MY_DOMAIN_NAME_PROP_KEY = "domain-name"; private static final String PRIORITY = "priority"; private static final String RESOURCE = "resource"; private static final String SM_ID = "smId"; /** Field description */ public static final String STRATEGY_CLASS_PROPERTY = "--sm-cluster-strategy-class"; /** Field description */ public static final String STRATEGY_CLASS_PROP_KEY = "cluster-strategy-class"; /** Field description */ public static final String STRATEGY_CLASS_PROP_VAL = "tigase.cluster.strategy.SMNonCachingAllNodes"; /** Field description */ public static final int SYNC_MAX_BATCH_SIZE = 1000; private static final String SYNC_ONLINE_JIDS = "sync-jids"; private static final String TOKEN = "token"; private static final String TRANSFER = "transfer"; private static final String USER_ID = "userId"; private static final String XMPP_SESSION_ID = "xmppSessionId"; /** * Variable <code>log</code> is a class logger. */ private static final Logger log = Logger.getLogger(SessionManagerClustered.class.getName()); private JID my_address = null; private JID my_hostname = null; private int nodesNo = 0; private ClusteringStrategyIfc strategy = null; /** * Method description * * * @param jid * * @return */ @Override public boolean containsJid(JID jid) { return super.containsJid(jid) || strategy.containsJid(jid); } /** * Method description * * * @param jid * * @return */ @Override public JID[] getConnectionIdsForJid(JID jid) { JID[] ids = super.getConnectionIdsForJid(jid); if (ids == null) { ids = strategy.getConnectionIdsForJid(jid); } return ids; } /** * Method description * * * @param params * * @return */ @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> props = super.getDefaults(params); String strategy_class = (String) params.get(STRATEGY_CLASS_PROPERTY); if (strategy_class == null) { strategy_class = STRATEGY_CLASS_PROP_VAL; } props.put(STRATEGY_CLASS_PROP_KEY, strategy_class); try { ClusteringStrategyIfc strat_tmp = (ClusteringStrategyIfc) Class.forName(strategy_class).newInstance(); Map<String, Object> strat_defs = strat_tmp.getDefaults(params); if (strat_defs != null) { props.putAll(strat_defs); } } catch (Exception e) { log.log(Level.SEVERE, "Can not instantiate clustering strategy for class: " + strategy_class, e); } String[] local_domains = DNSResolver.getDefHostNames(); if (params.get(GEN_VIRT_HOSTS) != null) { local_domains = ((String) params.get(GEN_VIRT_HOSTS)).split(","); } // defs.put(LOCAL_DOMAINS_PROP_KEY, LOCAL_DOMAINS_PROP_VAL); props.put(MY_DOMAIN_NAME_PROP_KEY, local_domains[0]); if (params.get(CLUSTER_NODES) != null) { String[] cl_nodes = ((String) params.get(CLUSTER_NODES)).split(","); nodesNo = cl_nodes.length; } return props; } /** * * @param list */ @Override public void getStatistics(StatisticsList list) { super.getStatistics(list); strategy.getStatistics(list); } /** * Method description * * * @param conn */ @Override public void handlePresenceSet(XMPPResourceConnection conn) { super.handlePresenceSet(conn); if (conn.getConnectionStatus() == ConnectionStatus.REMOTE) { return; } if (conn.getSessionData(CL_BR_INITIAL_PRESENCE) == null) { conn.putSessionData(CL_BR_INITIAL_PRESENCE, CL_BR_INITIAL_PRESENCE); if (log.isLoggable(Level.FINEST)) { log.finest("Handle presence set for" + " Connection: " + conn); } List<JID> cl_nodes = strategy.getAllNodes(); broadcastUserPresence(conn, cl_nodes); } } /** * Method description * * * @param conn */ @Override public void handleResourceBind(XMPPResourceConnection conn) { super.handleResourceBind(conn); if (conn.getConnectionStatus() == ConnectionStatus.REMOTE) { return; } if (conn.getSessionData(CL_BR_USER_CONNECTED) == null) { conn.putSessionData(CL_BR_USER_CONNECTED, CL_BR_USER_CONNECTED); if (log.isLoggable(Level.FINEST)) { log.finest("Handle resource bind for" + " Connection:: " + conn); } List<JID> cl_nodes = strategy.getAllNodes(); try { Map<String, String> params = prepareBroadcastParams(conn, false); sendBroadcastPackets(null, params, ClusterMethods.USER_CONNECTED, cl_nodes.toArray(new JID[cl_nodes.size()])); } catch (Exception e) { log.log(Level.WARNING, "Problem with broadcast user connected for: " + conn, e); } } else { if (log.isLoggable(Level.WARNING)) { log.warning("User resourc-rebind - not implemented yet in the cluster." + " Connection: " + conn); } } } ///** // * // * @return // */ //@Override //public Set<String> getOnlineJids() { // return strategy.getOnlineJids(); /** * Method description * * * @return */ @Override public boolean hasCompleteJidsInfo() { return strategy.hasCompleteJidsInfo(); } /** * Method description * * * @param node */ @Override public void nodeConnected(String node) { log.log(Level.FINE, "Nodes connected: {0}", node); JID jid = JID.jidInstanceNS(getName(), node, null); addTrusted(jid); strategy.nodeConnected(jid); sendAdminNotification("Cluster node '" + node + "' connected (" + (new Date()) + ")", "New cluster node connected: " + node, node); if (strategy.needsSync()) { requestSync(jid); } } /** * Method description * * * @param node */ @Override public void nodeDisconnected(String node) { log.log(Level.FINE, "Nodes disconnected: {0}", node); JID jid = JID.jidInstanceNS(getName(), node, null); strategy.nodeDisconnected(jid); // Not sure what to do here, there might be still packets // from the cluster node waiting.... // delTrusted(jid); sendAdminNotification("Cluster node '" + node + "' disconnected (" + (new Date()) + ")", "Cluster node disconnected: " + node, node); } /** * Method description * * * @param packet */ @SuppressWarnings("unchecked") @Override public void processPacket(Packet packet) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Received packet: {0}", packet); } if ((packet.getElemName() == ClusterElement.CLUSTER_EL_NAME) && (packet.getElement().getXMLNS() == ClusterElement.XMLNS)) { if (isTrusted(packet.getStanzaFrom())) { try { processClusterPacket(packet); } catch (TigaseStringprepException ex) { log.log(Level.WARNING, "Packet processing stringprep problem: {0}", packet); } } else { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, "Cluster packet from untrusted source: {0}", packet); } } return; } if (packet.isCommand() && processCommand(packet)) { packet.processedBy("SessionManager"); // No more processing is needed for command packet return; } // end of if (pc.isCommand()) XMPPResourceConnection conn = getXMPPResourceConnection(packet); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Ressource connection found: {0}", conn); } if ((conn == null) && (isBrokenPacket(packet) || processAdminsOrDomains(packet) || sendToNextNode(packet))) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Ignoring/dropping packet: {0}", packet); } return; } processPacket(packet, conn); } /** * Method description * * * @return */ @Override public int processingThreads() { return Math.max(nodesNo, super.processingThreads()); } //@Override //public void release() { // //delayedTasks.cancel(); // super.release(); //@Override //public void start() { // super.start(); // //delayedTasks = new Timer("SM Cluster Delayed Tasks", true); /** * Method description * * * @param cl_controller */ @Override public void setClusterController(ClusterController cl_controller) {} /** * Method description * * * @param props */ @Override public void setProperties(Map<String, Object> props) { super.setProperties(props); String strategy_class = (String) props.get(STRATEGY_CLASS_PROP_KEY); try { ClusteringStrategyIfc strategy_tmp = (ClusteringStrategyIfc) Class.forName(strategy_class).newInstance(); strategy_tmp.setProperties(props); // strategy_tmp.init(getName()); strategy = strategy_tmp; strategy.nodeConnected(getComponentId()); addTrusted(getComponentId()); } catch (Exception e) { log.log(Level.SEVERE, "Can not clustering strategy instance for class: " + strategy_class, e); } try { my_hostname = JID.jidInstance((String) props.get(MY_DOMAIN_NAME_PROP_KEY)); my_address = JID.jidInstance(getName(), (String) props.get(MY_DOMAIN_NAME_PROP_KEY), null); } catch (TigaseStringprepException ex) { log.log(Level.WARNING, "Creating component source address failed stringprep processing: {0}@{1}", new Object[] { getName(), my_hostname }); } } @Override protected void closeSession(XMPPResourceConnection conn, boolean closeOnly) { if ((conn.getConnectionStatus() != ConnectionStatus.REMOTE) && conn.isAuthorized()) { try { JID connectionId = conn.getConnectionId(); BareJID userId = conn.getBareJID(); String resource = conn.getResource(); Map<String, String> params = new LinkedHashMap<String, String>(); params.put(CONNECTION_ID, connectionId.toString()); params.put(USER_ID, userId.toString()); params.put(RESOURCE, resource); List<JID> cl_nodes = strategy.getAllNodes(); for (JID node : cl_nodes) { if ( !node.equals(getComponentId())) { Element check_session_el = ClusterElement.createClusterMethodCall(getComponentId().toString(), node.toString(), StanzaType.set, ClusterMethods.USER_DISCONNECTED.toString(), params).getClusterElement(); fastAddOutPacket(Packet.packetInstance(check_session_el, getComponentId(), node)); } } } catch (Exception ex) { log.log(Level.WARNING, "Problem sending user disconnect broadcast for: " + conn, ex); } } XMPPSession parentSession = conn.getParentSession(); // Exception here should not normally happen, but if it does, then consequences might // be severe, let's catch it then try { super.closeSession(conn, closeOnly); } catch (Exception ex) { log.log(Level.WARNING, "This should not happen, check it out!, ", ex); } if ((conn.getConnectionStatus() != ConnectionStatus.REMOTE) && (parentSession != null) && (parentSession.getActiveResourcesSize() == parentSession.getResSizeForConnStatus(ConnectionStatus.REMOTE))) { List<XMPPResourceConnection> conns = parentSession.getActiveResources(); for (XMPPResourceConnection xrc : conns) { try { super.closeConnection(xrc.getConnectionId(), true); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Closed remote connection: {0}", xrc); } } catch (Exception ex) { log.log(Level.WARNING, "This should not happen, check it out!, ", ex); } } } } protected JID getFirstClusterNode(JID userJid) { JID cluster_node = null; List<JID> nodes = strategy.getNodesForJid(userJid); if (nodes != null) { for (JID node : nodes) { if ( !node.equals(getComponentId())) { cluster_node = node; break; } } } return cluster_node; } @TODO(note = "Possible performance bottleneck if there are many users with multiple " + "connections to different nodes.") protected void processClusterPacket(Packet packet) throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<Packet>(); final ClusterElement clel = new ClusterElement(packet.getElement()); ClusterMethods method = ClusterMethods.parseMethod(clel.getMethodName()); switch (packet.getType()) { case set : if (clel.getMethodName() == null) { processPacket(clel); } switch (method) { case USER_INITIAL_PRESENCE : { BareJID userId = BareJID.bareJIDInstanceNS(clel.getMethodParam(USER_ID)); String resource = clel.getMethodParam(RESOURCE); XMPPSession session = getSession(userId); if ((session != null) && (session.getResourceForResource(resource) == null)) { JID connectionId = JID.jidInstanceNS(clel.getMethodParam(CONNECTION_ID)); String xmpp_sessionId = clel.getMethodParam(XMPP_SESSION_ID); String domain = userId.getDomain(); XMPPResourceConnection res_con = loginUserSession(connectionId, domain, userId, resource, ConnectionStatus.REMOTE, xmpp_sessionId); if (res_con != null) { List<Element> packs = clel.getDataPackets(); for (Element elem : packs) { if (elem.getName() == Presence.PRESENCE_ELEMENT_NAME) { res_con.setPresence(elem); } } res_con.putSessionData(SM_ID, packet.getStanzaFrom()); // Send the presence from the new user connection to all local // (non-remote) user connections updateUserResources(res_con, results); for (XMPPResourceConnection xrc : session.getActiveResources()) { if ((xrc.getConnectionStatus() != ConnectionStatus.REMOTE) && (xrc.getPresence() != null)) { broadcastUserPresence(xrc, packet.getStanzaFrom()); } } if (log.isLoggable(Level.FINEST)) { log.finest("Added remote session for: " + userId + ", from: " + packet.getStanzaFrom()); } } else { if (log.isLoggable(Level.INFO)) { log.info("Couldn't create user session for: " + userId + ", resource: " + resource + ", connectionId: " + connectionId); } } } else { // Ignoring this, nothing special to do. if (log.isLoggable(Level.FINEST)) { if (session == null) { log.finest("Ignoring USER_INITIAL_PRESENCE for: " + userId + ", from: " + packet.getStanzaFrom() + ", there is no other session for the user on this node."); } else { if (session.getResourceForResource(resource) != null) { log.finest("Ignoring USER_INITIAL_PRESENCE for: " + userId + ", from: " + packet.getStanzaFrom() + ", there is already a session on this node for this resource."); } else { log.finest("Ignoring USER_INITIAL_PRESENCE for: " + userId + ", from: " + packet.getStanzaFrom() + ", reason unknown, please contact devs."); } } } } break; } case USER_CONNECTED : { BareJID userId = BareJID.bareJIDInstanceNS(clel.getMethodParam(USER_ID)); String resource = clel.getMethodParam(RESOURCE); JID connectionId = JID.jidInstanceNS(clel.getMethodParam(CONNECTION_ID)); strategy.usersConnected(packet.getStanzaFrom(), results, JID.jidInstanceNS(userId, resource + "#" + connectionId)); break; } case USER_DISCONNECTED : { BareJID userId = BareJID.bareJIDInstanceNS(clel.getMethodParam(USER_ID)); String resource = clel.getMethodParam(RESOURCE); strategy.userDisconnected(packet.getStanzaFrom(), results, JID.jidInstanceNS(userId, resource)); XMPPSession session = getSession(userId); if (session != null) { JID connectionId = JID.jidInstanceNS(clel.getMethodParam(CONNECTION_ID)); // Possible performance bottleneck if there are many users with // multiple connections to different nodes. If all disconnect at // the same time we might have a problem here. closeConnection(connectionId, true); if (log.isLoggable(Level.FINEST)) { log.finest("Removed remote session for: " + userId + ", from: " + packet.getStanzaFrom()); } } break; } } break; case get : switch (method) { case SYNC_ONLINE : // Send back all online users on this node Collection<XMPPResourceConnection> conns = connectionsByFrom.values(); int counter = 0; StringBuilder sb = new StringBuilder(40000); for (XMPPResourceConnection conn : conns) { String jid = null; // Exception would be thrown for all not-authenticated yet connection // We don't have to worry about them, just ignore all of them // They should be synchronized later on using standard cluster // notifications. try { jid = conn.getJID() + "#" + conn.getConnectionId(); } catch (Exception e) { jid = null; } if (jid != null) { if (sb.length() == 0) { sb.append(jid); } else { sb.append(',').append(jid); } if (++counter > SYNC_MAX_BATCH_SIZE) { // Send a new batch... ClusterElement resp = clel.createMethodResponse(getComponentId().toString(), StanzaType.result, null); resp.addMethodResult(SYNC_ONLINE_JIDS, sb.toString()); fastAddOutPacket(Packet.packetInstance(resp.getClusterElement())); counter = 0; // Not sure which is better, create a new StringBuilder instance // or clearing existing up...., let's clear it up for now. sb.delete(0, sb.length()); } } } if (sb.length() > 0) { // Send a new batch... ClusterElement resp = clel.createMethodResponse(getComponentId().toString(), StanzaType.result, null); resp.addMethodResult(SYNC_ONLINE_JIDS, sb.toString()); fastAddOutPacket(Packet.packetInstance(resp.getClusterElement())); } break; default : // Do nothing... } break; case result : switch (method) { case SYNC_ONLINE : // Notify clustering strategy about SYNC_ONLINE response String jids = clel.getMethodResultVal(SYNC_ONLINE_JIDS); if (jids != null) { String[] jidsa = jids.split(","); JID[] jid_j = new JID[jidsa.length]; int idx = 0; for (String jid : jidsa) { jid_j[idx++] = JID.jidInstanceNS(jid); } try { strategy.usersConnected(packet.getStanzaFrom(), results, jid_j); } catch (Exception e) { log.log(Level.WARNING, "Problem synchronizing cluster nodes for packet: " + packet, e); } } else { log.warning("Sync online packet with empty jids list! Please check this out: " + packet.toString()); } break; default : // Do nothing... } break; case error : JID from = packet.getStanzaFrom(); clel.addVisitedNode(from.toString()); processPacket(clel); break; default : break; } addOutPackets(results); } @SuppressWarnings("unchecked") protected void processPacket(ClusterElement packet) { List<Element> elems = packet.getDataPackets(); // String packet_from = packet.getDataPacketFrom(); if ((elems != null) && (elems.size() > 0)) { for (Element elem : elems) { try { Packet el_packet = Packet.packetInstance(elem); XMPPResourceConnection conn = getXMPPResourceConnection(el_packet); if ((conn != null) ||!sendToNextNode(packet, el_packet.getStanzaTo())) { processPacket(el_packet, conn); } } catch (TigaseStringprepException ex) { log.warning("Addressing problem, stringprep failed for packet: " + elem); } } } else { log.finest("Empty packets list in the cluster packet: " + packet.toString()); } } protected boolean sendToNextNode(ClusterElement clel, JID userId) throws TigaseStringprepException { ClusterElement next_clel = ClusterElement.createForNextNode(clel, strategy.getNodesForJid(userId), getComponentId()); if (next_clel != null) { fastAddOutPacket(Packet.packetInstance(next_clel.getClusterElement())); return true; } else { String first = clel.getFirstNode(); if ((first != null) &&!first.equals(getComponentId().toString())) { List<Element> packets = clel.getDataPackets(); Element elem = (((packets != null) && (packets.size() == 1)) ? packets.get(0) : null); Packet packet = ((elem != null) ? Packet.packetInstance(elem) : null); if ((packet == null) || ((packet.getType() != StanzaType.result) && (packet.getType() != StanzaType.available) && (packet.getType() != StanzaType.unavailable) && (packet.getType() != StanzaType.error) &&!((packet.getElemName() == "presence") && (packet.getType() == null)))) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Sending back to the first node: {0}", first); } ClusterElement result = clel.nextClusterNode(first); result.addVisitedNode(getComponentId().toString()); fastAddOutPacket(Packet.packetInstance(result.getClusterElement())); } return true; } else { return false; } } } protected boolean sendToNextNode(Packet packet) { JID cluster_node = getFirstClusterNode(packet.getStanzaTo()); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Cluster node found: {0}", cluster_node); } if (cluster_node != null) { JID sess_man_id = getComponentId(); ClusterElement clel = new ClusterElement(sess_man_id.toString(), cluster_node.toString(), StanzaType.set, packet); clel.addVisitedNode(sess_man_id.toString()); fastAddOutPacket(Packet.packetInstance(clel.getClusterElement(), sess_man_id, cluster_node)); return true; } return false; } protected void updateUserResources(XMPPResourceConnection res_con, Queue<Packet> results) { try { Element pres_update = res_con.getPresence(); for (XMPPResourceConnection conn : res_con.getActiveSessions()) { try { if (log.isLoggable(Level.FINER)) { log.finer("Update presence change to: " + conn.getjid()); } if ((conn != res_con) && conn.isResourceSet() && (conn.getConnectionStatus() != ConnectionStatus.REMOTE)) { if (pres_update != null) { pres_update = pres_update.clone(); } else { pres_update = new Element(Presence.PRESENCE_ELEMENT_NAME); } // Below code not needed anymore, packetInstance(...) takes care of it // pres_update.setAttribute("from", res_con.getJID().toString()); // pres_update.setAttribute("to", conn.getBareJID().toString()); Packet pack_update = Packet.packetInstance(pres_update, res_con.getJID(), conn.getJID().copyWithoutResource()); pack_update.setPacketTo(conn.getConnectionId()); results.offer(pack_update); } else { if (log.isLoggable(Level.FINER)) { log.finer("Skipping presence update to: " + conn.getjid()); } } // end of else } catch (NoConnectionIdException ex) { // This actually should not happen... might be a bug: log.log(Level.WARNING, "This should not happen, check it out!, ", ex); } catch (NotAuthorizedException ex) { log.warning("This should not happen, unless the connection has been " + "stopped in a concurrent thread or has not been authenticated yet: " + conn); } } // end of for (XMPPResourceConnection conn: sessions) } catch (NotAuthorizedException ex) { log.warning("User session from another cluster node authentication problem: " + res_con); } } private void broadcastUserPresence(XMPPResourceConnection conn, JID... cl_nodes) { try { Map<String, String> params = prepareBroadcastParams(conn, true); Element presence = conn.getPresence(); sendBroadcastPackets(presence, params, ClusterMethods.USER_INITIAL_PRESENCE, cl_nodes); } catch (Exception e) { log.log(Level.WARNING, "Problem with broadcast user initial presence message for: " + conn); } } private void broadcastUserPresence(XMPPResourceConnection conn, List<JID> cl_nodes) { try { Map<String, String> params = prepareBroadcastParams(conn, true); Element presence = conn.getPresence(); if (presence == null) { log.log(Level.WARNING, "Something wrong. Initial presence NULL!!", Thread.currentThread().getStackTrace()); } sendBroadcastPackets(presence, params, ClusterMethods.USER_INITIAL_PRESENCE, cl_nodes.toArray(new JID[cl_nodes.size()])); } catch (Exception e) { log.log(Level.WARNING, "Problem with broadcast user initial presence for: " + conn, e); } } private Map<String, String> prepareBroadcastParams(XMPPResourceConnection conn, boolean full_details) throws NotAuthorizedException, NoConnectionIdException { BareJID userId = conn.getBareJID(); String resource = conn.getResource(); JID connectionId = conn.getConnectionId(); Map<String, String> params = new LinkedHashMap<String, String>(); params.put(USER_ID, userId.toString()); params.put(RESOURCE, resource); params.put(CONNECTION_ID, connectionId.toString()); if (full_details) { String xmpp_sessionId = conn.getSessionId(); long authTime = conn.getAuthTime(); params.put(XMPP_SESSION_ID, xmpp_sessionId); params.put(AUTH_TIME, "" + authTime); if (log.isLoggable(Level.FINEST)) { log.finest("Sending user: " + userId + " session, resource: " + resource + ", xmpp_sessionId: " + xmpp_sessionId + ", connectionId: " + connectionId); } } else { if (log.isLoggable(Level.FINEST)) { log.finest("Sending user: " + userId + " session, resource: " + resource); } } return params; } private void requestSync(JID node) { ClusterElement clel = ClusterElement.createClusterMethodCall(getComponentId().toString(), node.toString(), StanzaType.get, ClusterMethods.SYNC_ONLINE.name(), null); fastAddOutPacket(Packet.packetInstance(clel.getClusterElement(), getComponentId(), node)); } private void sendAdminNotification(String msg, String subject, String node) { String message = msg; if (node != null) { message = msg + "\n"; } int cnt = 0; message += node + " connected to " + getDefHostName(); Packet p_msg = Message.getMessage(my_address, my_hostname, StanzaType.normal, message, subject, "xyz", newPacketId(null)); sendToAdmins(p_msg); } private void sendBroadcastPackets(Element data, Map<String, String> params, ClusterMethods methodCall, JID... nodes) { ClusterElement clel = ClusterElement.createClusterMethodCall(getComponentId().toString(), nodes[0].toString(), StanzaType.set, methodCall.toString(), params); if (data != null) { clel.addDataPacket(data); } Element check_session_el = clel.getClusterElement(); if ( !nodes[0].equals(getComponentId())) { fastAddOutPacket(Packet.packetInstance(check_session_el, getComponentId(), nodes[0])); } for (int i = 1; i < nodes.length; i++) { if ( !nodes[i].equals(getComponentId())) { Element elem = check_session_el.clone(); elem.setAttribute("to", nodes[i].toString()); fastAddOutPacket(Packet.packetInstance(elem, getComponentId(), nodes[i])); } } } } //~ Formatted in Sun Code Convention
package querqy.rewrite; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import querqy.model.ExpandedQuery; import querqy.model.Query; import querqy.infologging.InfoLoggingContext; /** * The chain of rewriters to manipulate a {@link Query}. * * @author rene * */ public class RewriteChain { final List<RewriterFactory> factories; @Deprecated final Map<String, RewriterFactory> factoriesByName; public RewriteChain() { this(Collections.emptyList()); } public RewriteChain(final List<RewriterFactory> factories) { this.factories = factories; factoriesByName = new HashMap<>(factories.size()); factories.forEach(factory -> { final String rewriterId = factory.getRewriterId(); if (rewriterId == null || rewriterId.trim().isEmpty()) { throw new IllegalArgumentException("Missing rewriter id for factory: " + factory.getClass().getName()); } if (factoriesByName.put(rewriterId, factory) != null) { throw new IllegalArgumentException("Duplicate rewriter id: " + rewriterId); } }); } public ExpandedQuery rewrite(final ExpandedQuery query, final SearchEngineRequestAdapter searchEngineRequestAdapter) { ExpandedQuery work = query; final Optional<InfoLoggingContext> loggingContext = searchEngineRequestAdapter.getInfoLoggingContext(); final String oldRewriterId = loggingContext.map(InfoLoggingContext::getRewriterId).orElse(null); try { for (final RewriterFactory factory : factories) { loggingContext.ifPresent(context -> context.setRewriterId(factory.getRewriterId())); final QueryRewriter rewriter = factory.createRewriter(work, searchEngineRequestAdapter); work = (rewriter instanceof ContextAwareQueryRewriter) ? ((ContextAwareQueryRewriter) rewriter).rewrite(work, searchEngineRequestAdapter) : rewriter.rewrite(work); } } finally { loggingContext.ifPresent(context -> context.setRewriterId(oldRewriterId)); } return work; } @Deprecated public List<RewriterFactory> getRewriterFactories() { return factories; } @Deprecated public RewriterFactory getFactory(final String rewriterId) { return factoriesByName.get(rewriterId); } }
package ui.components.pickers; import backend.resource.TurboLabel; import util.Utility; import java.util.*; import java.util.stream.Collectors; public class LabelPickerState { Set<String> addedLabels; Set<String> removedLabels; Set<String> initialLabels; List<String> matchedLabels; OptionalInt currentSuggestionIndex; private LabelPickerState(Set<String> initialLabels, Set<String> addedLabels, Set<String> removedLabels, List<String> matchedLabels, OptionalInt currentSuggestionIndex) { this.initialLabels = initialLabels; this.addedLabels = addedLabels; this.removedLabels = removedLabels; this.matchedLabels = matchedLabels; this.currentSuggestionIndex = currentSuggestionIndex; } private LabelPickerState(Set<String> initialLabels, Set<String> addedLabels, Set<String> removedLabels, List<String> matchedLabels) { this.initialLabels = initialLabels; this.addedLabels = addedLabels; this.removedLabels = removedLabels; this.matchedLabels = matchedLabels; this.currentSuggestionIndex = OptionalInt.empty(); } /* * Methods for Logic */ public LabelPickerState(Set<String> initialLabels) { this.initialLabels = initialLabels; this.addedLabels = new HashSet<>(); this.removedLabels = new HashSet<>(); this.matchedLabels = new ArrayList<>(); this.currentSuggestionIndex = OptionalInt.empty(); } public LabelPickerState clearMatchedLabels() { return new LabelPickerState(initialLabels, addedLabels, removedLabels, new ArrayList<>(), currentSuggestionIndex); } public LabelPickerState toggleLabel(Set<String> repoLabels, String keyword) { if (!hasExactlyOneMatchedLabel(repoLabels, keyword)) return this; String labelName = getMatchedLabelName(repoLabels, keyword); if (isAnInitialLabel(labelName)) { if (isARemovedLabel(labelName)) { // add back initial label removeConflictingLabels(labelName); removedLabels.remove(labelName); } else { removedLabels.add(labelName); } } else { if (isAnAddedLabel(labelName)) { addedLabels.remove(labelName); } else { // add new label removeConflictingLabels(labelName); addedLabels.add(labelName); } } return new LabelPickerState(initialLabels, addedLabels, removedLabels, new ArrayList<>()); } public LabelPickerState nextSuggestion() { if (canIncreaseIndex()) { return new LabelPickerState(initialLabels, removedLabels, addedLabels, matchedLabels, OptionalInt.of(currentSuggestionIndex.getAsInt() + 1)); } return this; } public LabelPickerState previousSuggestion() { if (canDecreaseIndex()) { return new LabelPickerState(initialLabels, removedLabels, addedLabels, matchedLabels, OptionalInt.of(currentSuggestionIndex.getAsInt() - 1)); } return this; } public LabelPickerState updateMatchedLabels(Set<String> repoLabels, String query) { List<String> newMatchedLabels = convertToList(repoLabels); newMatchedLabels = filterByName(newMatchedLabels, getName(query)); newMatchedLabels = filterByGroup(newMatchedLabels, getGroup(query)); OptionalInt newSuggestionIndex; if (query.equals("") || newMatchedLabels.isEmpty()) { newSuggestionIndex = OptionalInt.empty(); } else { newSuggestionIndex = OptionalInt.of(0); } return new LabelPickerState(initialLabels, addedLabels, removedLabels, newMatchedLabels, newSuggestionIndex); } /* * Methods for updating UI */ public List<String> getAssignedLabels() { List<String> assignedLabels = new ArrayList<>(); assignedLabels.addAll(initialLabels); assignedLabels.addAll(addedLabels); assignedLabels.removeAll(removedLabels); return assignedLabels; } public List<String> getInitialLabels() { return convertToList(initialLabels); } public List<String> getRemovedLabels() { return convertToList(removedLabels); } public List<String> getAddedLabels() { return convertToList(addedLabels); } public Optional<String> getCurrentSuggestion() { if (currentSuggestionIndex.isPresent() && isValidSuggestionIndex()) { return Optional.of(getSuggestedLabel()); } return Optional.empty(); } public List<String> getMatchedLabels() { return matchedLabels; } /* * Helper functions */ private String getMatchedLabelName(Set<String> repoLabels, String keyword) { List<String> newMatchedLabels = new ArrayList<>(); newMatchedLabels.addAll(repoLabels); newMatchedLabels = filterByName(newMatchedLabels, getName(keyword)); newMatchedLabels = filterByGroup(newMatchedLabels, getGroup(keyword)); return newMatchedLabels.get(0); } private boolean hasExactlyOneMatchedLabel(Set<String> repoLabels, String keyword) { List<String> newMatchedLabels = new ArrayList<>(); newMatchedLabels.addAll(repoLabels); newMatchedLabels = filterByName(newMatchedLabels, getName(keyword)); newMatchedLabels = filterByGroup(newMatchedLabels, getGroup(keyword)); return newMatchedLabels.size() == 1; } private void removeConflictingLabels(String name) { if (hasExclusiveGroup(name)) { String group = getGroup(name); // Remove from addedLabels addedLabels = addedLabels.stream() .filter(label -> { String labelGroup = getGroup(label); return !labelGroup.equals(group); }) .collect(Collectors.toSet()); // Add to removedLabels all initialLabels that have conflicting group removedLabels.addAll(initialLabels.stream() .filter(label -> { String labelGroup = getGroup(label); return labelGroup.equals(group) && !removedLabels.contains(name); }) .collect(Collectors.toSet())); } } private boolean hasExclusiveGroup(String name) { return TurboLabel.getDelimiter(name).isPresent() && TurboLabel.getDelimiter(name).get().equals("."); } private List<String> filterByName(List<String> repoLabels, String labelName) { return repoLabels .stream() .filter(name -> Utility.containsIgnoreCase(getName(name), labelName)) .collect(Collectors.toList()); } private List<String> filterByGroup(List<String> repoLabels, String labelGroup) { if (labelGroup.equals("")) { return repoLabels; } else { return repoLabels .stream() .filter(name -> { if (hasGroup(name)) { return Utility.containsIgnoreCase(getGroup(name), labelGroup); } else { return false; } }) .collect(Collectors.toList()); } } private String getGroup(String name) { if (hasGroup(name)) { return name.substring(0, name.indexOf(TurboLabel.getDelimiter(name).get())); } else { return ""; } } private String getName(String name) { if (hasGroup(name)) { return name.substring(name.indexOf(TurboLabel.getDelimiter(name).get()) + 1); } else { return name; } } private boolean hasGroup(String name) { return TurboLabel.getDelimiter(name).isPresent(); } private boolean isAnInitialLabel(String name) { return this.initialLabels.contains(name); } private boolean isAnAddedLabel(String name) { return this.addedLabels.contains(name); } private boolean isARemovedLabel(String name) { return this.removedLabels.contains(name); } private String getSuggestedLabel() { return matchedLabels.get(currentSuggestionIndex.getAsInt()); } private boolean isValidSuggestionIndex() { return currentSuggestionIndex.getAsInt() >= 0 && currentSuggestionIndex.getAsInt() < matchedLabels.size(); } private boolean canIncreaseIndex() { return currentSuggestionIndex.isPresent() && currentSuggestionIndex.getAsInt() < matchedLabels.size() - 1; } private boolean canDecreaseIndex() { return currentSuggestionIndex.isPresent() && currentSuggestionIndex.getAsInt() > 0; } private List<String> convertToList(Set<String> labelSet){ List<String> resultingList = new ArrayList<>(); resultingList.addAll(labelSet); return resultingList; } }
package uk.bl.odin.orcid.client; public enum OrcidAuthScope { AUTHENTICATE("/authenticate"), CREATE_WORKS("/orcid-works/create"), CREATE_EXTERNAL_ID("/orcid-bio/external-identifiers/create"), CREATE_PROFILE("/orcid-profile/create"), UPDATE_BIO("/orcid-bio/update"), UPDATE_WORKS("orcid-works/update"), READ_PROFILE("/orcid-profile/read-limited"), READ_BIO("/orcid-bio/read-limited"), READ_WORKS("/orcid-works/read-limited"), READPUBLIC("/read-public"); private final String stringValue; private OrcidAuthScope(final String s) { stringValue = s; } public String toString() { return stringValue; } }
package uk.co.jemos.podam.api; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jemos.podam.exceptions.PodamMockeryException; /** * The PODAM factory implementation * * @author mtedone * * @since 1.0.0 * */ @ThreadSafe @Immutable public class PodamFactoryImpl implements PodamFactory { private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; private static final String RAWTYPES_STR = "rawtypes"; private static final String UNCHECKED_STR = "unchecked"; private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; /** Application logger */ private static final Logger LOG = LoggerFactory .getLogger(PodamFactoryImpl.class.getName()); /** * The strategy to use to fill data. * <p> * The default is {@link RandomDataProviderStrategy}. * </p> */ private final DataProviderStrategy strategy; /** * A list of {@link Annotation}s for attributes that PODAM shouldn't * consider */ private List<Class<? extends Annotation>> excludeAnnotations; /** * Default constructor. */ public PodamFactoryImpl() { this(RandomDataProviderStrategy.getInstance()); } /** * Full constructor. * * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(DataProviderStrategy strategy) { super(); this.strategy = strategy; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass) { Type[] noTypes = new Type[0]; return this.manufacturePojo(pojoClass, noTypes); } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojoClass, 0); return this.manufacturePojoInternal(pojoClass, pojos, genericTypeArgs); } /** * {@inheritDoc} */ @Override public DataProviderStrategy getStrategy() { return strategy; } private Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap, final Class<?> pojoClass, final Type[] genericTypeArgs) { final TypeVariable<?>[] typeParameters = pojoClass.getTypeParameters(); if (typeParameters.length > genericTypeArgs.length) { String msg = pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters.length + " found " + genericTypeArgs.length + ". Returning null"; throw new IllegalStateException(msg); } int i; for (i = 0; i < typeParameters.length; i++) { typeArgsMap.put(typeParameters[i].getName(), genericTypeArgs[i]); } Type[] genericTypeArgsExtra; if (typeParameters.length < genericTypeArgs.length) { genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, genericTypeArgs.length); } else { genericTypeArgsExtra = null; } /* Adding types, which were specified during inheritance */ Class<?> clazz = pojoClass; while (clazz != null) { Type superType = clazz.getGenericSuperclass(); clazz = clazz.getSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) superType; Type[] actualParamTypes = paramType.getActualTypeArguments(); TypeVariable<?>[] paramTypes = clazz.getTypeParameters(); for (i = 0; i < actualParamTypes.length && i < paramTypes.length; i++) { if (actualParamTypes[i] instanceof Class) { typeArgsMap.put(paramTypes[i].getName(), actualParamTypes[i]); } } } } return genericTypeArgsExtra; } private Object createNewInstanceForClassWithoutConstructors( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> clazz, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length == 0 || Modifier.isAbstract(clazz.getModifiers())) { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); try { Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn(String.format("Lost %d generic type arguments", genericTypeArgsExtra.length)); } } catch (IllegalStateException e) { LOG.error(e.getMessage()); return null; } // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = clazz.getDeclaredMethods(); // A candidate factory method is a method which returns the // Class type // The parameters to pass to the method invocation Object[] parameterValues = null; Object[] noParams = new Object[] {}; for (Method candidateConstructor : declaredMethods) { if (!Modifier.isStatic(candidateConstructor.getModifiers()) || !candidateConstructor.getReturnType().equals(clazz)) { continue; } parameterValues = new Object[candidateConstructor .getParameterTypes().length]; Type[] parameterTypes = candidateConstructor .getGenericParameterTypes(); if (parameterTypes.length == 0) { parameterValues = noParams; } else { // This is a factory method with arguments Annotation[][] parameterAnnotations = candidateConstructor .getParameterAnnotations(); int idx = 0; for (Type paramType : parameterTypes) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(); Class<?> parameterType = resolveGenericParameter( paramType, typeArgsMap, methodGenericTypeArgs); List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); String attributeName = null; // It's a Collection type if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> listType = resolveCollectionType(parameterType); Class<?> elementType; if (paramType instanceof ParameterizedType) { elementType = (Class<?>) methodGenericTypeArgs .get()[0]; } else { elementType = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(elementType); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object attributeValue = manufactureAttributeValue( clazz, pojos, elementType, annotations, attributeName); listType.add(attributeValue); } parameterValues[idx] = listType; // It's a Map } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Class<?> keyClass; Class<?> valueClass; if (paramType instanceof ParameterizedType) { keyClass = (Class<?>) methodGenericTypeArgs .get()[0]; valueClass = (Class<?>) methodGenericTypeArgs .get()[1]; } else { keyClass = Object.class; valueClass = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(valueClass); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object keyValue = manufactureAttributeValue( clazz, pojos, keyClass, annotations, attributeName); Object elementValue = manufactureAttributeValue( clazz, pojos, valueClass, annotations, attributeName); mapType.put(keyValue, elementValue); } parameterValues[idx] = mapType; } else { // It's any other object parameterValues[idx] = manufactureAttributeValue( clazz, pojos, parameterType, annotations, attributeName, typeArgsMap, genericTypeArgs); } idx++; } } try { retValue = candidateConstructor.invoke(clazz, parameterValues); LOG.info("Could create an instance using " + candidateConstructor); break; } catch (Exception t) { LOG.warn("PODAM could not create an instance for constructor: " + candidateConstructor + ". Will try another one..."); } } } else { // There are public constructors. We want constructor with minumum // number of parameters to speed up the creation strategy.sort(constructors); for (Constructor<?> constructor : constructors) { try { Object[] constructorArgs = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); retValue = constructor.newInstance(constructorArgs); LOG.info("For class: " + clazz.getName() + " a valid constructor: " + constructor + " was found. PODAM will use it to create an instance."); break; } catch (Exception t) { LOG.warn("Couldn't create attribute with constructor: " + constructor + ". Will check if other constructors are available"); } } } if (retValue == null) { LOG.warn("For class: {} PODAM could not possibly create a value." + " This attribute will be returned as null.", clazz); } return retValue; } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter * type * @return value for class representing the generic parameter type */ private Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType; methodGenericTypeArgs.set(new Type[] {}); if (paramType instanceof TypeVariable<?>) { final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType; final Type type = typeArgsMap.get(typeVariable.getName()); if (type != null) { parameterType = resolveGenericParameter(type, typeArgsMap, methodGenericTypeArgs); } else { LOG.warn("Unrecognized type {}. Will use Object intead", typeVariable); parameterType = Object.class; } } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); methodGenericTypeArgs.set(pType.getActualTypeArguments()); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (bounds != null && bounds.length > 0) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (bounds != null && bounds.length > 0) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], typeArgsMap, methodGenericTypeArgs); } else { LOG.warn("Unrecognized type" + wType.toString() + ". Will use Object intead"); parameterType = Object.class; } } else if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } else { LOG.warn("Unrecognized type {}. Will use Object intead", paramType .getClass().getSimpleName()); parameterType = Object.class; } return parameterType; } private Object resolvePrimitiveValue(Class<?> primitiveClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (primitiveClass.equals(int.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (primitiveClass.equals(long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (primitiveClass.equals(float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (primitiveClass.equals(double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (primitiveClass.equals(boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (primitiveClass.equals(byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (primitiveClass.equals(short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (primitiveClass.equals(char.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } return retValue; } /** * It returns the boolean value indicated in the annotation. * * @param annotations * The collection of annotations for the annotated attribute * @return The boolean value indicated in the annotation */ private Boolean getBooleanValueForAnnotation(List<Annotation> annotations) { Boolean retValue = null; for (Annotation annotation : annotations) { if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; retValue = localStrategy.boolValue(); break; } } return retValue; } private Byte getByteValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Byte retValue = null; for (Annotation annotation : annotations) { if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { PodamByteValue intStrategy = (PodamByteValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Byte.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a byte type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { byte minValue = intStrategy.minValue(); byte maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getByteInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Short getShortValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Short retValue = null; for (Annotation annotation : annotations) { if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { PodamShortValue shortStrategy = (PodamShortValue) annotation; String numValueStr = shortStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Short.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a short type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { short minValue = shortStrategy.minValue(); short maxValue = shortStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getShortInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Character} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * @return A random {@link Character} value */ private Character getCharacterValueWithinRange( List<Annotation> annotations, AttributeMetadata attributeMetadata) { Character retValue = null; for (Annotation annotation : annotations) { if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { PodamCharValue annotationStrategy = (PodamCharValue) annotation; char charValue = annotationStrategy.charValue(); if (charValue != ' ') { retValue = charValue; } else { char minValue = annotationStrategy.minValue(); char maxValue = annotationStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getCharacterInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Integer getIntegerValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Integer retValue = null; for (Annotation annotation : annotations) { if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { PodamIntValue intStrategy = (PodamIntValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Integer.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to an Integer. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { int minValue = intStrategy.minValue(); int maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getIntegerInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Float getFloatValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Float retValue = null; for (Annotation annotation : annotations) { if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { PodamFloatValue floatStrategy = (PodamFloatValue) annotation; String numValueStr = floatStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Float.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Float. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { float minValue = floatStrategy.minValue(); float maxValue = floatStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getFloatInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Double} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * * @return a random {@link Double} value */ private Double getDoubleValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Double retValue = null; for (Annotation annotation : annotations) { if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; String numValueStr = doubleStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Double.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Double. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { double minValue = doubleStrategy.minValue(); double maxValue = doubleStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getDoubleInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Long getLongValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Long retValue = null; for (Annotation annotation : annotations) { if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { PodamLongValue longStrategy = (PodamLongValue) annotation; String numValueStr = longStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Long.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Long. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { long minValue = longStrategy.minValue(); long maxValue = longStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getLongInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It attempts to resolve the given class as a wrapper class and if this is * the case it assigns a random value * * * @param candidateWrapperClass * The class which might be a wrapper class * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return {@code null} if this is not a wrapper class, otherwise an Object * with the value for the wrapper class */ private Object resolveWrapperValue(Class<?> candidateWrapperClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (candidateWrapperClass.equals(Integer.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (candidateWrapperClass.equals(Long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (candidateWrapperClass.equals(Float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (candidateWrapperClass.equals(Double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (candidateWrapperClass.equals(Boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (candidateWrapperClass.equals(Byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (candidateWrapperClass.equals(Short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (candidateWrapperClass.equals(Character.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } return retValue; } @SuppressWarnings({ UNCHECKED_STR, RAWTYPES_STR }) private <T> T resolvePojoWithoutSetters(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { T retValue = null; Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors.length == 0) { retValue = (T) createNewInstanceForClassWithoutConstructors( pojoClass, pojos, pojoClass); } else { // There are public constructors. We want constructor with minumum // number of parameters to speed up the creation strategy.sort(constructors); for (Constructor<?> constructor : constructors) { Object[] parameterValues = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); // Being a generic method we cannot be sure on the identity of // T, therefore the mismatch between the newInstance() return // value (Object) and T is acceptable, thus the SuppressWarning // annotation try { if (!constructor.isAccessible()) { constructor.setAccessible(true); } retValue = (T) constructor.newInstance(parameterValues); if (retValue instanceof Collection && ((Collection) retValue).size() == 0) { LOG.info("We could create an instance with constructor: " + constructor + ", but collection is empty" + ". Will try with another one."); } else if (retValue instanceof Map && ((Map) retValue).size() == 0) { LOG.info("We could create an instance with constructor: " + constructor + ", but map is empty" + ". Will try with another one."); } else { LOG.info("We could create an instance with constructor: " + constructor); break; } } catch (Exception t) { LOG.warn("We couldn't create an instance for pojo: " + pojoClass + " for constructor: " + constructor + ". Will try with another one."); } } if (retValue == null) { LOG.warn( "For class: {} PODAM could not possibly create a value." + " This attribute will be returned as null.", pojoClass); } } return retValue; } /** * Generic method which returns an instance of the given class filled with * values dictated by the strategy * * @param <T> * The type for which a filled instance is required * * @param pojoClass * The name of the class for which an instance filled with values * is required * @param pojos * How many times {@code pojoClass} has been found. This will be * used for reentrant objects * @param genericTypeArgs * The generic type arguments for the current generic class * instance * @return An instance of <T> filled with dummy values * * @throws PodamMockeryException * if a problem occurred while creating a POJO instance or while * setting its state */ @SuppressWarnings(UNCHECKED_STR) private <T> T manufacturePojoInternal(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) { try { T retValue = null; if (pojoClass.isPrimitive()) { // For JDK POJOs we can't retrieve attribute name ArrayList<Annotation> annotations = new ArrayList<Annotation>(); String noName = null; return (T) resolvePrimitiveValue(pojoClass, annotations, new AttributeMetadata(noName, pojoClass, annotations)); } if (pojoClass.isInterface() || Modifier.isAbstract(pojoClass.getModifiers())) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojos, genericTypeArgs); } else { if (Modifier.isAbstract(pojoClass.getModifiers())) { return (T) createNewInstanceForClassWithoutConstructors( pojoClass, pojos, pojoClass, genericTypeArgs); } else { LOG.warn("Cannot instantiate an interface {}." + " Returning null.", pojoClass); } } } ClassInfo classInfo = PodamUtils.getClassInfo(pojoClass, excludeAnnotations); // If a public no-arg constructor can be found we use it, // otherwise we try to find a non-public one and we use that. If the // class does not have a no-arg constructor we search for a suitable // constructor. try { Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors == null || constructors.length == 0) { LOG.warn("No public constructors were found. " + "We'll look for a default, non-public constructor. "); Constructor<T> defaultConstructor = pojoClass .getDeclaredConstructor(new Class[] {}); LOG.info("Will use: " + defaultConstructor); // Security hack defaultConstructor.setAccessible(true); retValue = defaultConstructor.newInstance(); } else { retValue = resolvePojoWithoutSetters(pojoClass, pojos, genericTypeArgs); } } catch (SecurityException e) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } catch (NoSuchMethodException e1) { LOG.warn("No default (public or non-public) constructors were found. " + "Also no other public constructors were found. " + "Your last hope is that we find a non-public, non-default constructor."); Constructor<?>[] constructors = pojoClass .getDeclaredConstructors(); if (constructors == null || constructors.length == 0) { throw new IllegalStateException( "The POJO " + pojoClass + " appears without constructors. How is this possible? "); } LOG.info("Will use: " + constructors[0]); // It uses the first public constructor found Object[] parameterValuesForConstructor = getParameterValuesForConstructor( constructors[0], pojoClass, pojos, genericTypeArgs); constructors[0].setAccessible(true); retValue = (T) constructors[0] .newInstance(parameterValuesForConstructor); } /* Construction failed, no point to continue */ if (retValue == null) { return null; } Class<?>[] parameterTypes = null; Class<?> attributeType = null; // According to JavaBeans standards, setters should have only // one argument Object setterArg = null; for (Method setter : classInfo.getClassSetters()) { List<Annotation> pojoAttributeAnnotations = retrieveFieldAnnotations( pojoClass, setter); String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); parameterTypes = setter.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalStateException("A " + pojoClass.getSimpleName() + "." + setter.getName() + "() should have only one argument"); } // A class which has got an attribute to itself (e.g. // recursive hierarchies) attributeType = parameterTypes[0]; // If an attribute has been annotated with // PodamAttributeStrategy, it takes the precedence over any // other strategy. Additionally we don't pass the attribute // metadata for value customisation; if user went to the extent // of specifying a PodamAttributeStrategy annotation for an // attribute they are already customising the value assigned to // that attribute. PodamStrategyValue attributeStrategyAnnotation = containsAttributeStrategyAnnotation(pojoAttributeAnnotations); if (null != attributeStrategyAnnotation) { AttributeStrategy<?> attributeStrategy = attributeStrategyAnnotation .value().newInstance(); if (LOG.isDebugEnabled()) { LOG.debug("The attribute: " + attributeName + " will be filled using the following strategy: " + attributeStrategy); } setterArg = returnAttributeDataStrategyValue(attributeType, attributeStrategy); } else { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn(String.format( "Lost %d generic type arguments", genericTypeArgsExtra.length)); } Type[] typeArguments = new Type[] {}; // If the parameter is a generic parameterized type resolve // the actual type arguments if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) setter .getGenericParameterTypes()[0]; typeArguments = attributeParameterizedType .getActualTypeArguments(); } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { final TypeVariable<?> typeVariable = (TypeVariable<?>) setter .getGenericParameterTypes()[0]; Type type = typeArgsMap.get(typeVariable.getName()); if (type instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) type; typeArguments = attributeParameterizedType .getActualTypeArguments(); attributeType = (Class<?>) attributeParameterizedType .getRawType(); } else { attributeType = (Class<?>) type; } } setterArg = manufactureAttributeValue(pojoClass, pojos, attributeType, pojoAttributeAnnotations, attributeName, typeArgsMap, typeArguments); } if (setterArg != null) { // If the setter is not public we set it to accessible for // the sake of // usability. However this violates Javabean standards and // it's a security hack if (!setter.isAccessible()) { LOG.warn( "The setter: {} is not accessible.Setting it to accessible. " + "However this is a security hack and your code should really adhere to Javabean standards.", setter.getName()); setter.setAccessible(true); } setter.invoke(retValue, setterArg); } else { LOG.warn("Couldn't find a suitable value for attribute: {}" + ". This POJO attribute will be left to null.", attributeType); } } return retValue; } catch (InstantiationException e) { throw new PodamMockeryException( "An instantiation exception occurred", e); } catch (IllegalAccessException e) { throw new PodamMockeryException("An illegal access occurred", e); } catch (IllegalArgumentException e) { throw new PodamMockeryException("An illegal argument was passed", e); } catch (InvocationTargetException e) { throw new PodamMockeryException("Invocation Target Exception", e); } catch (ClassNotFoundException e) { throw new PodamMockeryException("ClassNotFoundException Exception", e); } } private Object manufactureAttributeValue(Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, List<Annotation> annotations, String attributeName, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); return manufactureAttributeValue(pojoClass, pojos, attributeType, annotations, attributeName, nullTypeArgsMap, genericTypeArgs); } @SuppressWarnings(RAWTYPES_STR) private Object manufactureAttributeValue(Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, List<Annotation> annotations, String attributeName, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object attributeValue = null; Class<?> realAttributeType; if (genericTypeArgs.length > 0 && genericTypeArgs[0] instanceof Class && attributeType.isAssignableFrom((Class) genericTypeArgs[0])) { realAttributeType = (Class) genericTypeArgs[0]; } else { realAttributeType = attributeType; } AttributeMetadata attributeMetadata = new AttributeMetadata( attributeName, realAttributeType, annotations); // Primitive type if (realAttributeType.isPrimitive()) { attributeValue = resolvePrimitiveValue(realAttributeType, annotations, attributeMetadata); // Wrapper type } else if (isWrapper(realAttributeType)) { attributeValue = resolveWrapperValue(realAttributeType, annotations, attributeMetadata); // String type } else if (realAttributeType.equals(String.class)) { attributeValue = resolveStringValue(annotations, attributeMetadata); } else if (realAttributeType.getName().startsWith("[")) { // Array type attributeValue = resolveArrayElementValue(realAttributeType, pojos, annotations, pojoClass, attributeName, typeArgsMap); // Otherwise it's a different type of Object (including // the Object class) } else if (Collection.class.isAssignableFrom(realAttributeType)) { // Collection type attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( pojoClass, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (Map.class.isAssignableFrom(realAttributeType)) { // Map type attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojoClass, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (realAttributeType.isEnum()) { // Enum type int enumConstantsLength = realAttributeType.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength, attributeMetadata) % enumConstantsLength; attributeValue = realAttributeType.getEnumConstants()[enumIndex]; } } else { // For any other type, we use the PODAM strategy Integer depth = pojos.get(realAttributeType); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(pojoClass)) { pojos.put(realAttributeType, depth + 1); if (realAttributeType.getName().startsWith("java.") || realAttributeType.getName().startsWith("javax.")) { // For classes in the Java namespace we attempt the no-args or the // factory constructor strategy attributeValue = createNewInstanceForClassWithoutConstructors( pojoClass, pojos, realAttributeType, genericTypeArgs); } else { attributeValue = this.manufacturePojoInternal( realAttributeType, pojos, genericTypeArgs); } pojos.put(realAttributeType, depth); } else { LOG.warn("Loop in {} production detected. Returning null.", realAttributeType); attributeValue = null; } } return attributeValue; } private String resolveStringValue(List<Annotation> annotations, AttributeMetadata attributeMetadata) throws InstantiationException, IllegalAccessException { String retValue = null; if (annotations == null || annotations.isEmpty()) { retValue = strategy.getStringValue(attributeMetadata); } else { for (Annotation annotation : annotations) { if (!PodamStringValue.class.isAssignableFrom(annotation .getClass())) { continue; } // A specific value takes precedence over the length PodamStringValue podamAnnotation = (PodamStringValue) annotation; if (podamAnnotation.strValue() != null && podamAnnotation.strValue().length() > 0) { retValue = podamAnnotation.strValue(); } else { retValue = strategy.getStringOfLength( podamAnnotation.length(), attributeMetadata); } } if (retValue == null) { retValue = strategy.getStringValue(attributeMetadata); } } return retValue; } /** * It returns a {@link PodamStrategyValue} if one was specified, or * {@code null} otherwise. * * @param annotations * The list of annotations * @return {@code true} if the list of annotations contains at least one * {@link PodamStrategyValue} annotation. */ private PodamStrategyValue containsAttributeStrategyAnnotation( List<Annotation> annotations) { PodamStrategyValue retValue = null; for (Annotation annotation : annotations) { if (PodamStrategyValue.class .isAssignableFrom(annotation.getClass())) { retValue = (PodamStrategyValue) annotation; break; } } return retValue; } /** * It returns {@code true} if this class is a wrapper class, {@code false} * otherwise * * @param candidateWrapperClass * The class to check * @return {@code true} if this class is a wrapper class, {@code false} * otherwise */ private boolean isWrapper(Class<?> candidateWrapperClass) { return candidateWrapperClass.equals(Byte.class) ? true : candidateWrapperClass.equals(Boolean.class) ? true : candidateWrapperClass.equals(Character.class) ? true : candidateWrapperClass.equals(Short.class) ? true : candidateWrapperClass .equals(Integer.class) ? true : candidateWrapperClass .equals(Long.class) ? true : candidateWrapperClass .equals(Float.class) ? true : candidateWrapperClass .equals(Double.class) ? true : false; } /** * Given the original class and the setter method, it returns all * annotations for the field or an empty collection if no custom annotations * were found on the field * * @param clazz * The class containing the annotated attribute * @param setter * The setter method * @return all annotations for the field * @throws NoSuchFieldException * If the field could not be found * @throws SecurityException * if a security exception occurred */ private List<Annotation> retrieveFieldAnnotations(Class<?> clazz, Method setter) { Class<?> workClass = clazz; List<Annotation> retValue = new ArrayList<Annotation>(); // Checks if the field has got any custom annotations String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); Field setterField = null; while (workClass != null) { try { setterField = workClass.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { // Low quality here derives by the JDK which throws // an exception if a field does not exist workClass = workClass.getSuperclass(); } } if (setterField != null) { Annotation[] annotations = setterField.getAnnotations(); if (annotations != null && annotations.length != 0) { retValue = Arrays.asList(annotations); } } return retValue; } @SuppressWarnings({ UNCHECKED_STR }) private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> collectionType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { // This needs to be generic because collections can be of any type Collection<? super Object> retValue = null; try { try { validateAttributeName(attributeName); // Checks whether the user initialized the collection in the // class // definition Object newInstance = pojoClass.newInstance(); Field field = null; Class<?> clazz = pojoClass; while (clazz != null) { try { field = clazz.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } } if (field == null) { throw new NoSuchFieldException(); } // It allows to invoke Field.get on private fields field.setAccessible(true); Collection<? super Object> coll = (Collection<? super Object>) field .get(newInstance); if (null != coll) { retValue = coll; } else { retValue = resolveCollectionType(collectionType); } } catch (Exception e) { // Name is empty or could not call an empty constructor // (probably this call is for a parameterized constructor) // Create a new Collection retValue = resolveCollectionType(collectionType); } Class<?> typeClass = null; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("The collection attribute: " + attributeName + " does not have a type. We will assume Object for you"); // Support for non-generified collections typeClass = Object.class; } else { Type actualTypeArgument = genericTypeArgs[0]; typeClass = resolveGenericParameter(actualTypeArgument, typeArgsMap, elementGenericTypeArgs); } fillCollection(pojoClass, pojos, attributeName, annotations, retValue, typeClass, elementGenericTypeArgs.get()); } catch (SecurityException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalArgumentException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InstantiationException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } return retValue; } private void fillCollection(Class<?> pojoClass, Map<Class<?>, Integer> pojos, String attributeName, List<Annotation> annotations, Collection<? super Object> collection, Class<?> collectionElementType, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy.getNumberOfCollectionElements(pojoClass); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass()) && Object.class.equals(collectionElementType)) { LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); collection.add(elementStrategy.getValue()); } else if (null != elementStrategy && !ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass())) { LOG.debug("Collection elements will be filled using the following strategy: " + elementStrategy); Object strategyValue = returnAttributeDataStrategyValue( collectionElementType, elementStrategy); collection.add(strategyValue); } else { collection.add(manufactureAttributeValue(pojoClass, pojos, collectionElementType, annotations, attributeName, genericTypeArgs)); } } } private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { Map<? super Object, ? super Object> retValue = null; try { try { validateAttributeName(attributeName); // Checks whether the user initialised the collection in the // class definition Class<?> workClass = pojoClass; Object newInstance = null; Field field = null; newInstance = pojoClass.newInstance(); while (workClass != null) { try { field = workClass.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { workClass = workClass.getSuperclass(); } } if (field == null) { throw new IllegalStateException( "It was not possible to retrieve field: " + attributeName); } // Will throw exception if invalid // It allows to invoke Field.get on private fields field.setAccessible(true); @SuppressWarnings(UNCHECKED_STR) Map<? super Object, ? super Object> coll = (Map<? super Object, ? super Object>) field .get(newInstance); if (null != coll) { retValue = coll; } else { retValue = resolveMapType(attributeType); } } catch (Exception e) { // Name is empty or could not call an empty constructor // (probably this call is for a parameterized constructor) // Create a new Map retValue = resolveMapType(attributeType); } Class<?> keyClass = null; Class<?> elementClass = null; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("Map attribute: " + attributeName + " is non-generic. We will assume a Map<Object, Object> for you."); keyClass = Object.class; elementClass = Object.class; } else { // Expected only key, value type if (genericTypeArgs.length != 2) { throw new IllegalStateException( "In a Map only key value generic type are expected."); } Type[] actualTypeArguments = genericTypeArgs; keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(retValue); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } catch (InstantiationException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (SecurityException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } return retValue; } private void fillMap(MapArguments mapArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> keyStrategy = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : mapArguments.getAnnotations()) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy.getNumberOfCollectionElements(mapArguments .getPojoClass()); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); keyStrategy = collectionAnnotation.mapKeyStrategy().newInstance(); elementStrategy = collectionAnnotation.mapElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { Object keyValue = null; Object elementValue = null; MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapArguments.getPojoClass()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); valueArguments.setCollectionAnnotation(collectionAnnotation); valueArguments.setElementStrategy(keyStrategy); valueArguments.setGenericTypeArgs(mapArguments .getKeyGenericTypeArgs()); keyValue = getMapKeyOrElementValue(valueArguments); valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapArguments.getPojoClass()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getElementClass()); valueArguments.setCollectionAnnotation(collectionAnnotation); valueArguments.setElementStrategy(elementStrategy); valueArguments.setGenericTypeArgs(mapArguments .getElementGenericTypeArgs()); elementValue = getMapKeyOrElementValue(valueArguments); mapArguments.getMapToBeFilled().put(keyValue, elementValue); } } private Object getMapKeyOrElementValue( MapKeyOrElementsArguments keyOrElementsArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; if (null != keyOrElementsArguments.getElementStrategy() && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass()) && Object.class.equals(keyOrElementsArguments .getKeyOrValueType())) { LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); retValue = keyOrElementsArguments.getElementStrategy().getValue(); } else if (null != keyOrElementsArguments.getElementStrategy() && !ObjectStrategy.class .isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass())) { LOG.debug("Map key or value will be filled using the following strategy: " + keyOrElementsArguments.getElementStrategy()); retValue = returnAttributeDataStrategyValue( keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getElementStrategy()); } else { retValue = manufactureAttributeValue( keyOrElementsArguments.getPojoClass(), keyOrElementsArguments.getPojos(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getAnnotations(), keyOrElementsArguments.getAttributeName(), keyOrElementsArguments.getGenericTypeArgs()); } return retValue; } private Object resolveArrayElementValue(Class<?> attributeType, Map<Class<?>, Integer> pojos, List<Annotation> annotations, Class<?> pojoClass, String attributeName, Map<String, Type> typeArgsMap) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> componentType = attributeType.getComponentType(); AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (null != attributeName) { try { final Type genericType = pojoClass.getDeclaredField( attributeName).getGenericType(); if (genericType instanceof GenericArrayType) { final Type type = ((GenericArrayType) genericType) .getGenericComponentType(); if (type instanceof TypeVariable<?>) { final Type typeVarType = typeArgsMap .get(((TypeVariable<?>) type).getName()); componentType = resolveGenericParameter(typeVarType, typeArgsMap, genericTypeArgs); } } } catch (NoSuchFieldException e) { LOG.info("Cannot get the declared field type for field " + attributeName + " of class " + pojoClass.getName()); } } // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements; if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } else { nbrElements = strategy.getNumberOfCollectionElements(attributeType); } Object arrayElement = null; Object array = Array.newInstance(componentType, nbrElements); for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy()) && Object.class.equals(componentType)) { LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); arrayElement = elementStrategy.getValue(); } else if (null != elementStrategy && !ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy())) { LOG.debug("Array elements will be filled using the following strategy: " + elementStrategy); arrayElement = returnAttributeDataStrategyValue(componentType, elementStrategy); } else { arrayElement = manufactureAttributeValue(pojoClass, pojos, componentType, annotations, attributeName, typeArgsMap, genericTypeArgs.get()); } Array.set(array, i, arrayElement); } return array; } /** * Given a collection type it returns an instance * <p> * <ul> * <li>The default type for a {@link List} is an {@link ArrayList}</li> * <li>The default type for a {@link Queue} is a {@link LinkedList}</li> * <li>The default type for a {@link Set} is a {@link HashSet}</li> * </ul> * * </p> * * @param collectionType * The collection type * * @return an instance of the collection type */ @SuppressWarnings({ RAWTYPES_STR, UNCHECKED_STR }) private Collection<? super Object> resolveCollectionType( Class<?> collectionType) { Collection<? super Object> retValue = null; // Default list and set are ArrayList and HashSet. If users // wants a particular collection flavour they have to initialise // the collection if (List.class.isAssignableFrom(collectionType) || collectionType.equals(Collection.class)) { retValue = new ArrayList(); } else if (Queue.class.isAssignableFrom(collectionType)) { retValue = new LinkedList(); } else if (Set.class.isAssignableFrom(collectionType)) { retValue = new HashSet(); } else { throw new IllegalArgumentException("Collection type: " + collectionType + " not supported"); } return retValue; } /** * It manufactures and returns a default instance for each map type * * <p> * The default implementation for a {@link ConcurrentMap} is * {@link ConcurrentHashMap} * </p> * * <p> * The default implementation for a {@link SortedMap} is a {@link TreeMap} * </p> * * <p> * The default Map is none of the above was recognised is a {@link HashMap} * </p> * * @param attributeType * The attribute type * @return A default instance for each map type * */ @SuppressWarnings({ UNCHECKED_STR, RAWTYPES_STR }) private Map<? super Object, ? super Object> resolveMapType( Class<?> attributeType) { Map<? super Object, ? super Object> retValue = null; if (SortedMap.class.isAssignableFrom(attributeType)) { retValue = new TreeMap(); } else if (ConcurrentMap.class.isAssignableFrom(attributeType)) { retValue = new ConcurrentHashMap(); } else { retValue = new HashMap(); } return retValue; } private void validateAttributeName(String attributeName) { if (attributeName == null || "".equals(attributeName)) { throw new IllegalArgumentException( "The field name must not be null or empty!"); } } private Object[] getParameterValuesForConstructor( Constructor<?> constructor, Class<?> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = null; genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Annotation[][] parameterAnnotations = constructor .getParameterAnnotations(); Object[] parameterValues = new Object[constructor.getParameterTypes().length]; // Found a constructor with @PodamConstructor annotation Class<?>[] parameterTypes = constructor.getParameterTypes(); int idx = 0; for (Class<?> parameterType : parameterTypes) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); String attributeName = null; if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> collection = resolveCollectionType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> collectionElementType; AtomicReference<Type[]> collectionGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type actualTypeArgument = pType.getActualTypeArguments()[0]; collectionElementType = resolveGenericParameter( actualTypeArgument, typeArgsMap, collectionGenericTypeArgs); } else { collectionElementType = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( collectionGenericTypeArgs.get(), genericTypeArgsExtra); fillCollection(pojoClass, pojos, attributeName, annotations, collection, collectionElementType, genericTypeArgsAll); parameterValues[idx] = collection; } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> keyClass; Class<?> elementClass; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type[] actualTypeArguments = pType.getActualTypeArguments(); keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter( actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } else { keyClass = Object.class; elementClass = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( elementGenericTypeArgs.get(), genericTypeArgsExtra); MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(mapType); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); fillMap(mapArguments); parameterValues[idx] = mapType; } else { parameterValues[idx] = manufactureAttributeValue(pojoClass, pojos, parameterType, annotations, attributeName, genericTypeArgs); } idx++; } return parameterValues; } /** * Utility method to merge two arrays * * @param original * The main array * @param extra * The additional array, optionally may be null * @return A merged array of original and extra arrays */ private Type[] mergeTypeArrays(Type[] original, Type[] extra) { Type[] merged; if (extra != null) { merged = new Type[original.length + extra.length]; System.arraycopy(original, 0, merged, 0, original.length); System.arraycopy(extra, 0, merged, original.length, extra.length); } else { merged = original; } return merged; } private Object returnAttributeDataStrategyValue(Class<?> attributeType, AttributeStrategy<?> attributeStrategy) throws InstantiationException, IllegalAccessException { Object retValue = null; Method attributeStrategyMethod = null; try { attributeStrategyMethod = attributeStrategy.getClass().getMethod( PodamConstants.PODAM_ATTRIBUTE_STRATEGY_METHOD_NAME, new Class<?>[] {}); if (!attributeType.isAssignableFrom(attributeStrategyMethod .getReturnType())) { String errMsg = "The type of the Podam Attribute Strategy is not " + attributeType.getName() + " but " + attributeStrategyMethod.getReturnType().getName() + ". An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } retValue = attributeStrategy.getValue(); } catch (SecurityException e) { throw new IllegalStateException( "A security issue occurred while retrieving the Podam Attribute Strategy details", e); } catch (NoSuchMethodException e) { throw new IllegalStateException( "It seems the Podam Attribute Annotation is of the wrong type", e); } return retValue; } }
package wepa.wepa.controller; import java.util.Arrays; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import wepa.wepa.domain.Person; import wepa.wepa.repository.PersonRepository; @Controller public class DefaultController { @Autowired private PasswordEncoder passwordEncoder; @Autowired private PersonRepository personRepository; @PostConstruct public void init() { List<Person> users = personRepository.findAll(); if (users.isEmpty()) { Person user = new Person(); user.setName("teach"); user.setStudentNumber("000000000"); user.setPassword(passwordEncoder.encode("teach")); user.setAuthorities(Arrays.asList("TEACHER")); personRepository.save(user); } } @RequestMapping("*") public String handleDefault() { return "index"; } }
package yokohama.unit.translator; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import lombok.AllArgsConstructor; import org.apache.commons.collections4.ListUtils; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import yokohama.unit.ast.Assertion; import yokohama.unit.ast.BooleanExpr; import yokohama.unit.ast.CharExpr; import yokohama.unit.ast.Definition; import yokohama.unit.ast.EqualToMatcher; import yokohama.unit.ast.Execution; import yokohama.unit.ast.FloatingPointExpr; import yokohama.unit.ast.FourPhaseTest; import yokohama.unit.ast.Group; import yokohama.unit.ast.Ident; import yokohama.unit.ast.InstanceOfMatcher; import yokohama.unit.ast.InstanceSuchThatMatcher; import yokohama.unit.ast.IntegerExpr; import yokohama.unit.ast.InvocationExpr; import yokohama.unit.ast.LetBindings; import yokohama.unit.ast.Matcher; import yokohama.unit.ast.MethodPattern; import yokohama.unit.ast.NullValueMatcher; import yokohama.unit.ast.Phase; import yokohama.unit.ast.Predicate; import yokohama.unit.ast.Proposition; import yokohama.unit.ast.Row; import yokohama.unit.ast.StringExpr; import yokohama.unit.ast.Table; import yokohama.unit.ast.TableExtractVisitor; import yokohama.unit.ast.TableRef; import yokohama.unit.ast.Test; import yokohama.unit.ast_junit.Annotation; import yokohama.unit.ast_junit.ArrayExpr; import yokohama.unit.ast_junit.BooleanLitExpr; import yokohama.unit.ast_junit.CatchClause; import yokohama.unit.ast_junit.CharLitExpr; import yokohama.unit.ast_junit.ClassDecl; import yokohama.unit.ast_junit.ClassType; import yokohama.unit.ast_junit.CompilationUnit; import yokohama.unit.ast_junit.DoubleLitExpr; import yokohama.unit.ast_junit.EqualToMatcherExpr; import yokohama.unit.ast_junit.FloatLitExpr; import yokohama.unit.ast_junit.InstanceOfMatcherExpr; import yokohama.unit.ast_junit.IntLitExpr; import yokohama.unit.ast_junit.InvokeExpr; import yokohama.unit.ast_junit.InvokeExpr.Instruction; import yokohama.unit.ast_junit.InvokeStaticExpr; import yokohama.unit.ast_junit.IsStatement; import yokohama.unit.ast_junit.LongLitExpr; import yokohama.unit.ast_junit.Method; import yokohama.unit.ast_junit.NonArrayType; import yokohama.unit.ast_junit.NullExpr; import yokohama.unit.ast_junit.NullValueMatcherExpr; import yokohama.unit.ast_junit.PrimitiveType; import yokohama.unit.ast_junit.Statement; import yokohama.unit.ast_junit.StrLitExpr; import yokohama.unit.ast_junit.TryStatement; import yokohama.unit.ast_junit.Type; import yokohama.unit.ast_junit.Var; import yokohama.unit.ast_junit.VarExpr; import yokohama.unit.ast_junit.VarInitStatement; import yokohama.unit.position.Position; import yokohama.unit.position.Span; import yokohama.unit.util.ClassResolver; import yokohama.unit.util.GenSym; import yokohama.unit.util.Lists; import yokohama.unit.util.Optionals; import yokohama.unit.util.Pair; import yokohama.unit.util.SUtils; @AllArgsConstructor public class AstToJUnitAst { private final String name; private final String packageName; ExpressionStrategy expressionStrategy; MockStrategy mockStrategy; GenSym genSym; ClassResolver classResolver; TableExtractVisitor tableExtractVisitor; public CompilationUnit translate(Group group) { List<Definition> definitions = group.getDefinitions(); final List<Table> tables = tableExtractVisitor.extractTables(group); List<Method> methods = definitions.stream() .flatMap(definition -> definition.accept( test -> translateTest(test, tables).stream(), fourPhaseTest -> translateFourPhaseTest( fourPhaseTest, tables).stream(), table -> Stream.empty())) .collect(Collectors.toList()); ClassDecl testClass = new ClassDecl(true, name, Optional.empty(), Arrays.asList(), methods); Stream<ClassDecl> auxClasses = Stream.concat( expressionStrategy.auxClasses(classResolver).stream(), mockStrategy.auxClasses(classResolver).stream()); List<ClassDecl> classes = Stream.concat(auxClasses, Stream.of(testClass)) .collect(Collectors.toList()); return new CompilationUnit(packageName, classes); } List<Method> translateTest(Test test, final List<Table> tables) { final String name = test.getName(); List<Assertion> assertions = test.getAssertions(); List<Method> methods = IntStream.range(0, assertions.size()) .mapToObj(Integer::new) .flatMap(i -> translateAssertion( assertions.get(i), i + 1, name, tables) .stream()) .collect(Collectors.toList()); return methods; } List<Method> translateAssertion( Assertion assertion, int index, String testName, List<Table> tables) { String methodName = SUtils.toIdent(testName) + "_" + index; List<Proposition> propositions = assertion.getPropositions(); return assertion.getFixture().accept( () -> { String env = genSym.generate("env"); return Arrays.asList(new Method( Arrays.asList(Annotation.TEST), methodName, Arrays.asList(), Optional.empty(), Arrays.asList( new ClassType( java.lang.Exception.class, Span.dummySpan())), ListUtils.union( expressionStrategy.env(env, classResolver), propositions.stream() .flatMap(proposition -> translateProposition( proposition, env)) .collect(Collectors.toList())))); }, tableRef -> { String env = genSym.generate("env"); List<List<Statement>> table = translateTableRef(tableRef, tables, env); return IntStream.range(0, table.size()) .mapToObj(Integer::new) .map(i -> { return new Method( Arrays.asList(Annotation.TEST), methodName + "_" + (i + 1), Arrays.asList(), Optional.empty(), Arrays.asList( new ClassType( java.lang.Exception.class, Span.dummySpan())), ListUtils.union( expressionStrategy.env(env, classResolver), ListUtils.union( table.get(i), propositions .stream() .flatMap(proposition -> translateProposition( proposition, env)) .collect(Collectors.toList())))); }) .collect(Collectors.toList()); }, bindings -> { String env = genSym.generate("env"); return Arrays.asList(new Method( Arrays.asList(Annotation.TEST), methodName, Arrays.asList(), Optional.empty(), Arrays.asList( new ClassType( java.lang.Exception.class, Span.dummySpan())), ListUtils.union( expressionStrategy.env(env, classResolver), Stream.concat( bindings.getBindings() .stream() .flatMap(binding -> translateBinding( binding, env)), propositions.stream() .flatMap(proposition -> translateProposition( proposition, env))) .collect(Collectors.toList())))); }); } Stream<Statement> translateProposition( Proposition proposition, String envVarName) { String actual = genSym.generate("actual"); String expected = genSym.generate("expected"); Predicate predicate = proposition.getPredicate(); Stream<Statement> subjectAndPredicate = predicate.<Stream<Statement>>accept( isPredicate -> { return Stream.concat( expressionStrategy.eval( actual, proposition.getSubject(), Object.class, envVarName).stream(), translateMatcher( isPredicate.getComplement(), expected, actual, envVarName)); }, isNotPredicate -> { // inhibit `is not instance e of Exception such that...` isNotPredicate.getComplement().accept( equalTo -> null, instanceOf -> null, instanceSuchThat -> { throw new TranslationException( "`instance _ of _ such that` cannot follow `is not`", instanceSuchThat.getSpan()); }, nullValue -> null); String unexpected = genSym.generate("unexpected"); return Stream.concat( expressionStrategy.eval( actual, proposition.getSubject(), Object.class, envVarName).stream(), Stream.concat( translateMatcher( isNotPredicate.getComplement(), unexpected, actual, envVarName), Stream.of(new VarInitStatement( Type.MATCHER, expected, new InvokeStaticExpr( ClassType.CORE_MATCHERS, Arrays.asList(), "not", Arrays.asList(Type.MATCHER), Arrays.asList(new Var(unexpected)), Type.MATCHER), predicate.getSpan())))); }, throwsPredicate -> { String __ = genSym.generate("tmp"); return Stream.concat( bindThrown( actual, expressionStrategy.eval( __, proposition.getSubject(), Object.class, envVarName), envVarName), translateMatcher( throwsPredicate.getThrowee(), expected, actual, envVarName)); } ); Matcher matcher = predicate.accept( isPredicate -> isPredicate.getComplement(), isNotPredicate -> isNotPredicate.getComplement(), throwsPredicate -> throwsPredicate.getThrowee()); return Stream.concat( subjectAndPredicate, matcher instanceof InstanceSuchThatMatcher ? Stream.empty() : Stream.of(new IsStatement( new Var(actual), new Var(expected), predicate.getSpan()))); } Stream<Statement> bindThrown( String actual, List<Statement> statements, String envVarName) { String e = genSym.generate("ex"); /* Throwable actual; try { // statements actual = null; } catch (XXXXException e) { // extract the cause if wrapped: inserted by the strategy actual = e.get...; } catch (Throwable e) { actual = e; } */ return Stream.of( new TryStatement( ListUtils.union( statements, Arrays.asList(new VarInitStatement( Type.THROWABLE, actual, new NullExpr(), Span.dummySpan()))), Stream.concat( Optionals.toStream( expressionStrategy.catchAndAssignCause(actual)), Stream.of(new CatchClause( ClassType.THROWABLE, new Var(e), Arrays.asList(new VarInitStatement( Type.THROWABLE, actual, new VarExpr(e), Span.dummySpan()))))) .collect(Collectors.toList()), Arrays.asList())); } private String lookupClassName(String name, Span span) { try { return classResolver.lookup(name).getCanonicalName(); } catch (ClassNotFoundException e) { throw new TranslationException(e.getMessage(), span, e); } } Stream<Statement> translateMatcher( Matcher matcher, String varName, String actual, String envVarName) { return matcher.<Stream<Statement>>accept( (EqualToMatcher equalTo) -> { Var objVar = new Var(genSym.generate("obj")); return Stream.concat( translateExpr( equalTo.getExpr(), objVar.getName(), Object.class, envVarName), Stream.of(new VarInitStatement( Type.MATCHER, varName, new EqualToMatcherExpr(objVar), Span.dummySpan()))); }, (InstanceOfMatcher instanceOf) -> { return Stream.of(new VarInitStatement( Type.MATCHER, varName, new InstanceOfMatcherExpr( lookupClassName( instanceOf.getClazz().getName(), instanceOf.getSpan())), instanceOf.getSpan())); }, (InstanceSuchThatMatcher instanceSuchThat) -> { String bindVarName = instanceSuchThat.getVar().getName(); yokohama.unit.ast.ClassType clazz = instanceSuchThat.getClazz(); List<Proposition> propositions = instanceSuchThat.getPropositions(); Span span = instanceSuchThat.getSpan(); String instanceOfVarName = genSym.generate("instanceOfMatcher"); Stream<Statement> instanceOfStatements = Stream.of( new VarInitStatement( Type.MATCHER, instanceOfVarName, new InstanceOfMatcherExpr( lookupClassName( clazz.getName(), clazz.getSpan())), clazz.getSpan()), new IsStatement( new Var(actual), new Var(instanceOfVarName), clazz.getSpan())); Stream<Statement> bindStatements = expressionStrategy.bind( envVarName, bindVarName, new Var(actual)).stream(); Stream<Statement> suchThatStatements = propositions .stream() .flatMap(proposition -> translateProposition(proposition, envVarName)); return Stream.concat( instanceOfStatements, Stream.concat( bindStatements, suchThatStatements)); }, (NullValueMatcher nullValue) -> { return Stream.of( new VarInitStatement( Type.MATCHER, varName, new NullValueMatcherExpr(), nullValue.getSpan())); }); } Stream<Statement> translateBinding( yokohama.unit.ast.Binding binding, String envVarName) { String name = binding.getName().getName(); String varName = genSym.generate(name); return Stream.concat( translateExpr( binding.getValue(), varName, Object.class, envVarName), expressionStrategy.bind( envVarName, name, new Var(varName)).stream()); } Stream<Statement> translateExpr( yokohama.unit.ast.Expr expr, String varName, Class<?> expectedType, String envVarName) { Var exprVar = new Var(genSym.generate("expr")); Stream<Statement> statements = expr.accept( quotedExpr -> { return expressionStrategy.eval( exprVar.getName(), quotedExpr, Type.fromClass(expectedType).box().toClass(), envVarName).stream(); }, stubExpr -> { return mockStrategy.stub( exprVar.getName(), stubExpr, this, envVarName, classResolver).stream(); }, invocationExpr -> { return translateInvocationExpr( invocationExpr, exprVar.getName(), envVarName); }, integerExpr -> { return translateIntegerExpr( integerExpr, exprVar.getName(), envVarName); }, floatingPointExpr -> { return translateFloatingPointExpr( floatingPointExpr, exprVar.getName(), envVarName); }, booleanExpr -> { return translateBooleanExpr( booleanExpr, exprVar.getName(), envVarName); }, charExpr -> { return translateCharExpr( charExpr, exprVar.getName(), envVarName); }, stringExpr -> { return translateStringExpr( stringExpr, exprVar.getName(), envVarName); }); // box or unbox if needed Stream<Statement> boxing = boxOrUnbox( Type.fromClass(expectedType), varName, typeOfExpr(expr), exprVar); return Stream.concat(statements, boxing); } Stream<Statement> translateInvocationExpr( InvocationExpr invocationExpr, String varName, String envVarName) { yokohama.unit.ast.ClassType classType = invocationExpr.getClassType(); Class<?> clazz = classType.toClass(classResolver); MethodPattern methodPattern = invocationExpr.getMethodPattern(); String methodName = methodPattern.getName(); List<yokohama.unit.ast.Type> argTypes = methodPattern.getParamTypes(); boolean isVararg = methodPattern.isVararg(); Optional<yokohama.unit.ast.Expr> receiver = invocationExpr.getReceiver(); List<yokohama.unit.ast.Expr> args = invocationExpr.getArgs(); Type returnType = typeOfExpr(invocationExpr); List<Pair<Var, Stream<Statement>>> setupArgs; if (isVararg) { int splitAt = argTypes.size() - 1; List<Pair<yokohama.unit.ast.Type, List<yokohama.unit.ast.Expr>>> typesAndArgs = Pair.zip( argTypes, Lists.split(args, splitAt).map((nonVarargs, varargs) -> ListUtils.union( Lists.map(nonVarargs, Arrays::asList), Arrays.asList(varargs)))); setupArgs = Lists.mapInitAndLast( typesAndArgs, typeAndArg -> typeAndArg.map((t, arg) -> { Var argVar = new Var(genSym.generate("arg")); Type paramType = Type.of(t, classResolver); Stream<Statement> expr = translateExpr( arg.get(0), argVar.getName(), paramType.toClass(), envVarName); return new Pair<>(argVar, expr); }), typeAndArg -> typeAndArg.map((t, varargs) -> { Type paramType = Type.of(t, classResolver); List<Pair<Var, Stream<Statement>>> exprs = varargs.stream().map( vararg -> { Var varargVar = new Var(genSym.generate("vararg")); Stream<Statement> expr = translateExpr( vararg, varargVar.getName(), paramType.toClass(), envVarName); return new Pair<>(varargVar, expr); }).collect(Collectors.toList()); List<Var> varargVars = Pair.unzip(exprs).getFirst(); Stream<Statement> varargStatements = exprs.stream().flatMap(Pair::getSecond); Var argVar = new Var(genSym.generate("arg")); Stream<Statement> arrayStatement = Stream.of( new VarInitStatement( paramType.toArray(), argVar.getName(), new ArrayExpr(paramType.toArray(), varargVars), Span.dummySpan())); return new Pair<>(argVar, Stream.concat(varargStatements, arrayStatement)); })); } else { List<Pair<yokohama.unit.ast.Type, yokohama.unit.ast.Expr>> pairs = Pair.<yokohama.unit.ast.Type, yokohama.unit.ast.Expr>zip( argTypes, args); setupArgs = pairs.stream().map(pair -> pair.map((t, arg) -> { // evaluate actual args and coerce to parameter types Var argVar = new Var(genSym.generate("arg")); Type paramType = Type.of(t, classResolver); Stream<Statement> expr = translateExpr( arg, argVar.getName(), paramType.toClass(), envVarName); return new Pair<>(argVar, expr); })).collect(Collectors.toList()); } List<Var> argVars = Pair.unzip(setupArgs).getFirst(); Stream<Statement> setupStatements = setupArgs.stream().flatMap(Pair::getSecond); Stream<Statement> invocation; if (receiver.isPresent()) { // invokevirtual Type receiverType = Type.fromClass(clazz); Var receiverVar = new Var(genSym.generate("receiver")); Stream<Statement> getReceiver = translateExpr( receiver.get(),receiverVar.getName(), clazz, envVarName); invocation = Stream.concat(getReceiver, Stream.of( new VarInitStatement( returnType, varName, new InvokeExpr( clazz.isInterface() ? Instruction.INTERFACE : Instruction.VIRTUAL, receiverVar, methodName, Lists.mapInitAndLast( Type.listOf(argTypes, classResolver), type -> type, type -> isVararg ? type.toArray(): type), argVars, returnType), Span.dummySpan()))); } else { // invokestatic invocation = Stream.of( new VarInitStatement( returnType, varName, new InvokeStaticExpr( ClassType.of(classType, classResolver), Collections.emptyList(), methodName, Lists.mapInitAndLast( Type.listOf(argTypes, classResolver), type -> type, type -> isVararg ? type.toArray(): type), argVars, returnType), Span.dummySpan())); } return Stream.concat(setupStatements,invocation); } Stream<Statement> translateIntegerExpr( IntegerExpr integerExpr, String varName, String envVarName) { return integerExpr.match( intValue -> { return Stream.<Statement>of( new VarInitStatement( Type.INT, varName, new IntLitExpr(intValue), integerExpr.getSpan())); }, longValue -> { return Stream.<Statement>of( new VarInitStatement( Type.LONG, varName, new LongLitExpr(longValue), integerExpr.getSpan())); }); } Stream<Statement> translateFloatingPointExpr( FloatingPointExpr floatingPointExpr, String varName, String envVarName) { return floatingPointExpr.match( floatValue -> { return Stream.<Statement>of( new VarInitStatement( Type.FLOAT, varName, new FloatLitExpr(floatValue), floatingPointExpr.getSpan())); }, doubleValue -> { return Stream.<Statement>of( new VarInitStatement( Type.DOUBLE, varName, new DoubleLitExpr(doubleValue), floatingPointExpr.getSpan())); }); } Stream<Statement> translateBooleanExpr( BooleanExpr booleanExpr, String varName, String envVarName) { boolean booleanValue = booleanExpr.getValue(); return Stream.<Statement>of( new VarInitStatement( Type.BOOLEAN, varName, new BooleanLitExpr(booleanValue), booleanExpr.getSpan())); } Stream<Statement> translateCharExpr( CharExpr charExpr, String varName, String envVarName) { char charValue = charExpr.getValue(); return Stream.<Statement>of( new VarInitStatement( Type.CHAR, varName, new CharLitExpr(charValue), charExpr.getSpan())); } Stream<Statement> translateStringExpr( StringExpr stringExpr, String varName, String envVarName) { String strValue = stringExpr.getValue(); return Stream.<Statement>of( new VarInitStatement( Type.STRING, varName, new StrLitExpr(strValue), stringExpr.getSpan())); } public Stream<Statement> boxOrUnbox( Type toType, String toVarName, Type fromType, Var fromVar) { return fromType.<Stream<Statement>>matchPrimitiveOrNot( primitiveType -> { return fromPrimitive( toType, toVarName, primitiveType, fromVar); }, nonPrimitiveType -> { return fromNonPrimtive(toType, toVarName, fromVar); }); } private Stream<Statement> fromPrimitive( Type toType, String toVarName, PrimitiveType fromType, Var fromVar) { return toType.<Stream<Statement>>matchPrimitiveOrNot( primitiveType -> { return Stream.of( new VarInitStatement( toType, toVarName, new VarExpr(fromVar.getName()), Span.dummySpan())); }, nonPrimitiveType -> { return Stream.of(new VarInitStatement( nonPrimitiveType, toVarName, new InvokeStaticExpr( fromType.box(), Arrays.asList(), "valueOf", Arrays.asList(fromType.toType()), Arrays.asList(fromVar), fromType.box().toType()), Span.dummySpan())); }); } private Stream<Statement> fromNonPrimtive( Type toType, String toVarName, Var fromVar) { // precondition: fromVar is not primitive return toType.<Stream<Statement>>matchPrimitiveOrNot( primitiveType -> { Var boxVar = new Var(genSym.generate("box")); Type boxType; String unboxMethodName; switch (primitiveType.getKind()) { case BOOLEAN: boxType = primitiveType.box().toType(); unboxMethodName = "booleanValue"; break; case BYTE: boxType = Type.fromClass(Number.class); unboxMethodName = "byteValue"; break; case SHORT: boxType = Type.fromClass(Number.class); unboxMethodName = "shortValue"; break; case INT: boxType = Type.fromClass(Number.class); unboxMethodName = "intValue"; break; case LONG: boxType = Type.fromClass(Number.class); unboxMethodName = "longValue"; break; case CHAR: boxType = primitiveType.box().toType(); unboxMethodName = "charValue"; break; case FLOAT: boxType = Type.fromClass(Number.class); unboxMethodName = "floatValue"; break; case DOUBLE: boxType = Type.fromClass(Number.class); unboxMethodName = "doubleValue"; break; default: throw new RuntimeException("should not reach here"); } return Stream.of( new VarInitStatement( boxType, boxVar.getName(), new VarExpr(fromVar.getName()), Span.dummySpan()), new VarInitStatement( toType, toVarName, new InvokeExpr( Instruction.VIRTUAL, fromVar, unboxMethodName, Collections.emptyList(), Collections.emptyList(), toType), Span.dummySpan())); }, nonPrimitiveType -> { return Stream.of( new VarInitStatement( nonPrimitiveType, toVarName, new VarExpr(fromVar.getName()), Span.dummySpan())); }); } private Type typeOfExpr(yokohama.unit.ast.Expr expr) { return expr.accept( quotedExpr -> Type.OBJECT, stubExpr -> Type.of( stubExpr.getClassToStub().toType(), classResolver), invocationExpr -> { MethodPattern mp = invocationExpr.getMethodPattern(); return Type.of( mp.getReturnType( invocationExpr.getClassType(), classResolver), classResolver); }, integerExpr -> integerExpr.match( intValue -> Type.INT, longValue -> Type.LONG), floatingPointExpr -> floatingPointExpr.match( floatValue -> Type.FLOAT, doubleValue -> Type.DOUBLE), booleanExpr -> Type.BOOLEAN, charExpr -> Type.CHAR, stringExpr -> Type.STRING); } Type translateType(yokohama.unit.ast.Type type) { return new Type( translateNonArrayType(type.getNonArrayType()), type.getDims()); } NonArrayType translateNonArrayType(yokohama.unit.ast.NonArrayType nonArrayType) { return nonArrayType.accept( primitiveType -> new PrimitiveType(primitiveType.getKind()), classType -> new ClassType( classType.toClass(classResolver), classType.getSpan())); } List<List<Statement>> translateTableRef( TableRef tableRef, List<Table> tables, String envVarName) { String name = tableRef.getName(); List<String> idents = Lists.map(tableRef.getIdents(), Ident::getName); try { switch(tableRef.getType()) { case INLINE: return translateTable( tables.stream() .filter(table -> table.getName().equals(name)) .findFirst() .get(), idents, envVarName); case CSV: return parseCSV( name, CSVFormat.DEFAULT.withHeader(), idents, envVarName); case TSV: return parseCSV( name, CSVFormat.TDF.withHeader(), idents, envVarName); case EXCEL: return parseExcel(name, idents, envVarName); } throw new IllegalArgumentException( "'" + Objects.toString(tableRef) + "' is not a table reference."); } catch (InvalidFormatException | IOException e) { throw new TranslationException(e.getMessage(), tableRef.getSpan(), e); } } List<List<Statement>> translateTable( Table table, List<String> idents, String envVarName) { return table.getRows() .stream() .map(row -> translateRow( row, table.getHeader() .stream() .map(Ident::getName) .collect(Collectors.toList()), idents, envVarName)) .collect(Collectors.toList()); } List<Statement> translateRow( Row row, List<String> header, List<String> idents, String envVarName) { return IntStream.range(0, header.size()) .filter(i -> idents.contains(header.get(i))) .mapToObj(Integer::new) .flatMap(i -> { String varName = genSym.generate(header.get(i)); return Stream.concat( translateExpr( row.getExprs().get(i), varName, Object.class, envVarName), expressionStrategy.bind( envVarName, header.get(i), new Var(varName)).stream()); }) .collect(Collectors.toList()); } List<List<Statement>> parseCSV( String fileName, CSVFormat format, List<String> idents, String envVarName) throws IOException { try ( final InputStream in = getClass().getResourceAsStream(fileName); final Reader reader = new InputStreamReader(in, "UTF-8"); final CSVParser parser = new CSVParser(reader, format)) { return StreamSupport.stream(parser.spliterator(), false) .map(record -> parser.getHeaderMap().keySet() .stream() .filter(key -> idents.contains(key)) .flatMap(name -> { String varName = genSym.generate(name); return Stream.concat(expressionStrategy.eval( varName, new yokohama.unit.ast.QuotedExpr( record.get(name), new yokohama.unit.position.Span( Optional.of(Paths.get(fileName)), new Position((int)parser.getCurrentLineNumber(), -1), new Position(-1, -1))), Object.class, envVarName).stream(), expressionStrategy.bind(envVarName, name, new Var(varName)).stream()); }) .collect(Collectors.toList())) .collect(Collectors.toList()); } } List<List<Statement>> parseExcel( String fileName, List<String> idents, String envVarName) throws InvalidFormatException, IOException { try (InputStream in = getClass().getResourceAsStream(fileName)) { final Workbook book = WorkbookFactory.create(in); final Sheet sheet = book.getSheetAt(0); final int top = sheet.getFirstRowNum(); final int left = sheet.getRow(top).getFirstCellNum(); List<String> names = StreamSupport.stream(sheet.getRow(top).spliterator(), false) .map(cell -> cell.getStringCellValue()) .collect(Collectors.toList()); return StreamSupport.stream(sheet.spliterator(), false) .skip(1) .map(row -> IntStream.range(0, names.size()) .filter(i -> idents.contains(names.get(i))) .mapToObj(Integer::new) .flatMap(i -> { String varName = genSym.generate(names.get(i)); return Stream.concat(expressionStrategy.eval( varName, new yokohama.unit.ast.QuotedExpr( row.getCell(left + i).getStringCellValue(), new yokohama.unit.position.Span( Optional.of(Paths.get(fileName)), new Position(row.getRowNum() + 1, left + i + 1), new Position(-1, -1))), Object.class, envVarName).stream(), expressionStrategy.bind(envVarName, names.get(i), new Var(varName)).stream()); }) .collect(Collectors.toList())) .collect(Collectors.toList()); } } List<Method> translateFourPhaseTest(FourPhaseTest fourPhaseTest, List<Table> tables) { String env = genSym.generate("env"); String testName = SUtils.toIdent(fourPhaseTest.getName()); Stream<Statement> bindings; if (fourPhaseTest.getSetup().isPresent()) { Phase setup = fourPhaseTest.getSetup().get(); if (setup.getLetBindings().isPresent()) { LetBindings letBindings = setup.getLetBindings().get(); bindings = letBindings.getBindings() .stream() .flatMap(binding -> { String varName = genSym.generate(binding.getName()); return Stream.concat( translateExpr(binding.getValue(), varName, Object.class, env), expressionStrategy.bind(env, binding.getName(), new Var(varName)).stream()); }); } else { bindings = Stream.empty(); } } else { bindings = Stream.empty(); } Optional<Stream<Statement>> setupActions = fourPhaseTest.getSetup() .map(Phase::getExecutions) .map(execition -> translateExecutions(execition, env)); Optional<Stream<Statement>> exerciseActions = fourPhaseTest.getExercise() .map(Phase::getExecutions) .map(execution -> translateExecutions(execution, env)); Stream<Statement> testStatements = fourPhaseTest.getVerify().getAssertions() .stream() .flatMap(assertion -> assertion.getPropositions() .stream() .flatMap(proposition -> translateProposition(proposition, env))); List<Statement> statements = Stream.concat( bindings, Stream.concat( Stream.concat( setupActions.isPresent() ? setupActions.get() : Stream.empty(), exerciseActions.isPresent() ? exerciseActions.get() : Stream.empty()), testStatements) ).collect(Collectors.toList()); List<Statement> actionsAfter; if (fourPhaseTest.getTeardown().isPresent()) { Phase teardown = fourPhaseTest.getTeardown().get(); actionsAfter = translateExecutions(teardown.getExecutions(), env) .collect(Collectors.toList()); } else { actionsAfter = Arrays.asList(); } return Arrays.asList(new Method( Arrays.asList(Annotation.TEST), testName, Arrays.asList(), Optional.empty(), Arrays.asList(ClassType.EXCEPTION), ListUtils.union( expressionStrategy.env(env, classResolver), actionsAfter.size() > 0 ? Arrays.asList( new TryStatement( statements, Arrays.asList(), actionsAfter)) : statements))); } Stream<Statement> translateExecutions( List<Execution> executions, String envVarName) { String __ = genSym.generate("__"); return executions.stream() .flatMap(execution -> execution.getExpressions() .stream() .flatMap(expression -> expressionStrategy.eval( __, expression, Object.class, envVarName).stream())); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.kirauks.pixelrunner.scene.base; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.Manifold; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import org.andengine.engine.camera.hud.HUD; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.entity.IEntity; import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.andengine.entity.modifier.MoveModifier; import org.andengine.entity.primitive.Rectangle; import org.andengine.entity.scene.IOnSceneTouchListener; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.AutoParallaxBackground; import org.andengine.entity.scene.background.ParallaxBackground; import org.andengine.entity.shape.Shape; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.text.Text; import org.andengine.entity.text.TextOptions; import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.andengine.extension.physics.box2d.PhysicsConnector; import org.andengine.extension.physics.box2d.PhysicsFactory; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.andengine.input.touch.TouchEvent; import org.andengine.util.adt.align.HorizontalAlign; import org.andengine.util.adt.color.Color; import org.andengine.util.debug.Debug; import org.andengine.util.modifier.IModifier; import net.kirauks.pixelrunner.GameActivity; import net.kirauks.pixelrunner.game.IPlayerListener; import net.kirauks.pixelrunner.scene.base.BaseScene; import net.kirauks.pixelrunner.game.descriptor.LevelDescriptor; import net.kirauks.pixelrunner.game.element.background.BackgroundElement; import net.kirauks.pixelrunner.game.element.level.LevelElement; import net.kirauks.pixelrunner.game.Player; import net.kirauks.pixelrunner.game.Trail; import net.kirauks.pixelrunner.manager.AudioManager; import net.kirauks.pixelrunner.manager.SceneManager; import net.kirauks.pixelrunner.scene.base.utils.ease.EaseBroadcast; /** * * @author Karl */ public abstract class BaseGameScene extends BaseScene implements IOnSceneTouchListener{ private final float RIGHT_SPAWN = 900; private final float PLAYER_X = 250; private final float GROUND_LEVEL = 50; private final float GROUND_WIDTH = 1000; private final float GROUND_THICKNESS = LevelElement.PLATFORM_THICKNESS; private final float BROADCAST_LEVEL = 240; private final float BROADCAST_LEFT = -100; private final float BROADCAST_RIGHT = 1000; public class BaseGamePlayerListener implements IPlayerListener{ @Override public void onJump() { BaseGameScene.this.activity.vibrate(30); } @Override public void onRoll() { BaseGameScene.this.activity.vibrate(30); } @Override public void onRollBackJump() { BaseGameScene.this.player.reset(); BaseGameScene.this.restart(); BaseGameScene.this.activity.vibrate(new long[]{100, 50, 100, 50, 100, 50, 100, 50, 100, 50, 100, 50, 100}); } @Override public void onBonus() { BaseGameScene.this.activity.vibrate(30); } }; private boolean isPaused = false; private boolean isStarted = false; private boolean isWin = false; //HUD protected HUD hud; //HUD Broadcast private Text chrono3; private Text chrono2; private Text chrono1; private Text chronoStart; //HUD - Pause private Text pause; //HUD - Win private Text win; //Level protected LevelDescriptor level; private TimerHandler levelReaderHandler; private ITimerCallback levelReaderAction; private TimerHandler levelWinHandler; //Background private AutoParallaxBackground autoParallaxBackground; private List<Sprite> backgroundParallaxLayers = new LinkedList<Sprite>(); private float parallaxFactor = 1f; //Graphics protected Player player; protected Trail playerTrail; private Rectangle ground; //Physic protected PhysicsWorld physicWorld; private Body groundBody; //Elements memory private ConcurrentLinkedQueue<Shape> levelElements = new ConcurrentLinkedQueue<Shape>(); public BaseGameScene(LevelDescriptor level){ this.level = level; this.createBackground(); this.createLevelSpwaner(); } @Override public void createScene() { this.initPhysics(); this.createPlayer(); this.createGround(); this.createHUD(); this.setOnSceneTouchListener(this); } public void initPhysics(){ this.physicWorld = new FixedStepPhysicsWorld(60, new Vector2(0, -50), false); this.physicWorld.setContactListener(new ContactListener(){ @Override public void beginContact(Contact contact){ final Fixture xA = contact.getFixtureA(); final Fixture xB = contact.getFixtureB(); //Player contacts if (xA.getBody().getUserData().equals("player") && xB.getBody().getUserData().equals("ground") || xB.getBody().getUserData().equals("player") && xA.getBody().getUserData().equals("ground")){ BaseGameScene.this.player.resetMovements(); } if(xA.getBody().getUserData().equals("player") && xB.getBody().getUserData() instanceof LevelElement){ LevelElement element = (LevelElement)xB.getBody().getUserData(); if(element.isPlatform()){ float playerY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2; float elementY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2; if (playerY >= elementY && xA.getBody().getLinearVelocity().y < 0.5) { element.doPlayerAction(BaseGameScene.this.player); BaseGameScene.this.player.resetMovements(); } } } if(xB.getBody().getUserData().equals("player") && xA.getBody().getUserData() instanceof LevelElement){ LevelElement element = (LevelElement)xB.getBody().getUserData(); if(element.isPlatform()){ float playerY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2; float elementY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2; if (playerY >= elementY && xB.getBody().getLinearVelocity().y < 0.5) { element.doPlayerAction(BaseGameScene.this.player); BaseGameScene.this.player.resetMovements(); } } } } @Override public void endContact(Contact contact){ } @Override public void preSolve(Contact contact, Manifold oldManifold){ final Fixture xA = contact.getFixtureA(); final Fixture xB = contact.getFixtureB(); if(xA.getBody().getUserData().equals("player") && xB.getBody().getUserData() instanceof LevelElement){ LevelElement element = (LevelElement)xB.getBody().getUserData(); if(element.isPlatform()){ float playerY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2; float elementY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2; if (playerY < elementY) { contact.setEnabled(false); } } else{ contact.setEnabled(false); element.doPlayerAction(BaseGameScene.this.player); } } if(xB.getBody().getUserData().equals("player") && xA.getBody().getUserData() instanceof LevelElement){ LevelElement element = (LevelElement)xA.getBody().getUserData(); if(element.isPlatform()){ float playerY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2; float elementY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2; if (playerY < elementY) { contact.setEnabled(false); } } else{ contact.setEnabled(false); element.doPlayerAction(BaseGameScene.this.player); } } } @Override public void postSolve(Contact contact, ContactImpulse impulse){ } }); this.registerUpdateHandler(this.physicWorld); /* DebugRenderer debug = new DebugRenderer(this.physicWorld, this.vbom); this.attachChild(debug); */ } private void createBackground(){ this.autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5){ @Override public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed * BaseGameScene.this.parallaxFactor); } }; this.setBackground(this.autoParallaxBackground); for(BackgroundElement layer : this.level.getBackgroundsElements()){ Sprite layerSprite = new Sprite(layer.x, GROUND_LEVEL + layer.y, this.resourcesManager.gameParallaxLayers.get(layer.getResourceName()), this.vbom); layerSprite.setColor(new Color(0.4f, 0.4f, 0.4f)); this.backgroundParallaxLayers.add(layerSprite); layerSprite.setOffsetCenter(-1.5f, -1.5f); layerSprite.setScale(4f); this.autoParallaxBackground.attachParallaxEntity(new ParallaxBackground.ParallaxEntity(-layer.speed, layerSprite)); } } private void createPlayer(){ this.player = new Player(PLAYER_X, GROUND_LEVEL + GROUND_THICKNESS/2 + 32, this.resourcesManager.player, this.vbom, this.physicWorld) { @Override protected void onUpdateColor(){ super.onUpdateColor(); if(BaseGameScene.this.playerTrail != null){ BaseGameScene.this.playerTrail.setColor(this.getColor()); } } }; this.player.getBody().setUserData("player"); this.player.registerPlayerListener(new BaseGamePlayerListener()); this.attachChild(this.player); this.playerTrail = new Trail(36, 0, 0, 64, -340, -300, -2, 2, 25, 30, 50, Trail.ColorMode.NORMAL, this.resourcesManager.trail, this.vbom); this.playerTrail.bind(this.player); this.attachChild(this.playerTrail); this.playerTrail.hide(); this.playerTrail.setZIndex(this.player.getZIndex() - 1); this.sortChildren(); Body retention = PhysicsFactory.createBoxBody(this.physicWorld, PLAYER_X - this.player.getWidth()/2, 250, 1, 400, BodyDef.BodyType.StaticBody, PhysicsFactory.createFixtureDef(0, 0, 0)); retention.setUserData("retention"); } private void createGround(){ this.ground = new Rectangle(400, GROUND_LEVEL, GROUND_WIDTH, GROUND_THICKNESS, this.vbom); this.ground.setColor(LevelElement.COLOR_DEFAULT); this.groundBody = PhysicsFactory.createBoxBody(this.physicWorld, this.ground, BodyDef.BodyType.StaticBody, PhysicsFactory.createFixtureDef(0, 0, 0)); this.groundBody.setUserData("ground"); this.attachChild(this.ground); } protected abstract void onWin(); private void createLevelSpwaner(){ //Level elements this.levelWinHandler = new TimerHandler(3f, new ITimerCallback(){ @Override public void onTimePassed(TimerHandler pTimerHandler) { BaseGameScene.this.unregisterUpdateHandler(pTimerHandler); BaseGameScene.this.isWin = true; BaseGameScene.this.onWin(); Sprite player = BaseGameScene.this.player; final PhysicsConnector physicsConnector = BaseGameScene.this.physicWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(player); physicsConnector.getBody().applyForce(135, 0, 0, 0); BaseGameScene.this.parallaxFactor = 2f; BaseGameScene.this.registerUpdateHandler(new TimerHandler(2f, new ITimerCallback(){ @Override public void onTimePassed(final TimerHandler pTimerHandler){ BaseGameScene.this.unregisterUpdateHandler(pTimerHandler); physicsConnector.getBody().applyForce(-135, 0, 0, 0); } })); BaseGameScene.this.win.setVisible(true); AudioManager.getInstance().stop(); AudioManager.getInstance().play("mfx/", "win.xm"); BaseGameScene.this.playerTrail.setColorMode(Trail.ColorMode.MULTICOLOR); } }); this.levelReaderAction = new ITimerCallback(){ @Override public void onTimePassed(final TimerHandler pTimerHandler){ if(!BaseGameScene.this.level.hasNext()){ BaseGameScene.this.unregisterUpdateHandler(pTimerHandler); BaseGameScene.this.registerUpdateHandler(BaseGameScene.this.levelWinHandler); } else{ //Level elements spawn final float baseY = GROUND_LEVEL + GROUND_THICKNESS/2; for(final LevelElement lvlElement : BaseGameScene.this.level.getNext()){ BaseGameScene.this.engine.runOnUpdateThread(new Runnable(){ public void run(){ lvlElement.build(RIGHT_SPAWN, baseY, BaseGameScene.this.vbom, BaseGameScene.this.player, BaseGameScene.this.physicWorld); BaseGameScene.this.attachChild(lvlElement.getBuildedShape()); lvlElement.getBuildedShape().setZIndex(BaseGameScene.this.player.getZIndex() - 2); BaseGameScene.this.sortChildren(); BaseGameScene.this.levelElements.add(lvlElement.getBuildedShape()); lvlElement.getBuildedBody().setUserData(lvlElement); lvlElement.getBuildedBody().setLinearVelocity(new Vector2(-15, 0)); BaseGameScene.this.registerUpdateHandler(new TimerHandler(6f, new ITimerCallback(){ @Override public void onTimePassed(final TimerHandler pTimerHandler){ BaseGameScene.this.unregisterUpdateHandler(pTimerHandler); BaseGameScene.this.disposeLevelElement(lvlElement.getBuildedShape()); } })); } }); } if(!BaseGameScene.this.level.hasNext()){ BaseGameScene.this.unregisterUpdateHandler(pTimerHandler); BaseGameScene.this.registerUpdateHandler(BaseGameScene.this.levelWinHandler); } } } }; } private void createHUD(){ this.hud = new HUD(); this.camera.setHUD(this.hud); //Broadcast messages this.chrono3 = new Text(0, 0, resourcesManager.fontPixel_200, "3", vbom); this.chrono2 = new Text(0, 0, resourcesManager.fontPixel_200, "2", vbom); this.chrono1 = new Text(0, 0, resourcesManager.fontPixel_200, "1", vbom); this.chronoStart = new Text(0, 0, resourcesManager.fontPixel_200, "GO!", vbom); this.chrono3.setVisible(false); this.chrono2.setVisible(false); this.chrono1.setVisible(false); this.chronoStart.setVisible(false); this.hud.attachChild(this.chrono3); this.hud.attachChild(this.chrono2); this.hud.attachChild(this.chrono1); this.hud.attachChild(this.chronoStart); //Pause message this.pause = new Text(GameActivity.CAMERA_WIDTH/2, GameActivity.CAMERA_HEIGHT/2, resourcesManager.fontPixel_200, "PAUSE", vbom); this.pause.setVisible(false); this.hud.attachChild(this.pause); //win message this.win = new Text(GameActivity.CAMERA_WIDTH/2, GameActivity.CAMERA_HEIGHT/2 + 130, resourcesManager.fontPixel_200, "EPIC", new TextOptions(HorizontalAlign.CENTER), vbom); this.win.setVisible(false); Text winSub = new Text(this.win.getWidth()/2, -25f, resourcesManager.fontPixel_200, "WIN!", new TextOptions(HorizontalAlign.CENTER), vbom); this.win.attachChild(winSub); this.hud.attachChild(this.win); } private void restart(){ this.isStarted = false; this.onRestartBegin(); this.unregisterUpdateHandler(this.levelWinHandler); this.unregisterUpdateHandler(this.levelReaderHandler); AudioManager.getInstance().stop(); this.player.resetBonus(); this.playerTrail.hide(); this.parallaxFactor = -10f; final Shape[] elements = this.levelElements.toArray(new Shape[this.levelElements.size()]); this.levelElements.clear(); this.engine.runOnUpdateThread(new Runnable() { @Override public void run() { for(Shape element : elements){ PhysicsConnector physicsConnector = BaseGameScene.this.physicWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(element); if (physicsConnector != null){ Body body = physicsConnector.getBody(); body.setActive(false); BaseGameScene.this.physicWorld.unregisterPhysicsConnector(physicsConnector); BaseGameScene.this.physicWorld.destroyBody(body); } element.detachSelf(); } BaseGameScene.this.registerUpdateHandler(new TimerHandler(1f, new ITimerCallback(){ @Override public void onTimePassed(final TimerHandler pTimerHandler){ BaseGameScene.this.engine.unregisterUpdateHandler(pTimerHandler); BaseGameScene.this.parallaxFactor = 1f; BaseGameScene.this.onRestartEnd(); BaseGameScene.this.start(); } })); } }); } protected abstract void onRestartBegin(); protected abstract void onRestartEnd(); public void start(){ if(!BaseGameScene.this.isPaused){ this.level.init(); this.onStartBegin(); this.broadcast(this.chrono3, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { BaseGameScene.this.broadcast(BaseGameScene.this.chrono2, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { BaseGameScene.this.broadcast(BaseGameScene.this.chrono1, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { BaseGameScene.this.broadcast(BaseGameScene.this.chronoStart, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { AudioManager.getInstance().play("mfx/", BaseGameScene.this.level.getMusic()); BaseGameScene.this.playerTrail.show(); BaseGameScene.this.registerUpdateHandler(BaseGameScene.this.levelReaderHandler = new TimerHandler(BaseGameScene.this.level.getSpawnTime(), true, BaseGameScene.this.levelReaderAction)); BaseGameScene.this.onStartEnd(); BaseGameScene.this.isStarted = true; } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { } }); } }); } }); } }); } } protected abstract void onStartBegin(); protected abstract void onStartEnd(); private void broadcast(final IEntity entity, final IEntityModifierListener listener){ entity.registerEntityModifier(new MoveModifier(0.5f, BROADCAST_RIGHT, BROADCAST_LEVEL, BROADCAST_LEFT, BROADCAST_LEVEL, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { entity.setVisible(true); listener.onModifierStarted(pModifier, pItem); } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { entity.setVisible(false); listener.onModifierFinished(pModifier, pItem); } }, EaseBroadcast.getInstance())); } @Override public void onBackKeyPressed() { AudioManager.getInstance().stop(); SceneManager.getInstance().unloadGameLevelScene(); } @Override public void onPause() { if(!this.isWin){ this.pause(); } else{ this.audioManager.pause(); } } public void pause(){ this.isPaused = true; this.chrono1.clearEntityModifiers(); this.chrono2.clearEntityModifiers(); this.chrono3.clearEntityModifiers(); this.chronoStart.clearEntityModifiers(); this.chrono1.setVisible(false); this.chrono2.setVisible(false); this.chrono3.setVisible(false); this.chronoStart.setVisible(false); this.setIgnoreUpdate(true); this.pause.setVisible(true); this.audioManager.pause(); } public void resume(){ this.isPaused = false; if(this.isStarted){ this.broadcast(this.chrono3, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { BaseGameScene.this.pause.setVisible(false); } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { BaseGameScene.this.broadcast(BaseGameScene.this.chrono2, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { BaseGameScene.this.broadcast(BaseGameScene.this.chrono1, new IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { BaseGameScene.this.setIgnoreUpdate(false); BaseGameScene.this.audioManager.resume(); } }); } }); } }); } else{ this.pause.setVisible(false); this.setIgnoreUpdate(false); this.audioManager.resume(); this.start(); } } @Override public void onResume() { if(this.isWin){ this.audioManager.resume(); } } @Override protected void onManagedUpdate(float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed * this.player.getSpeed()); } @Override public void disposeScene() { this.clearUpdateHandlers(); this.destroyPhysicsWorld(); this.camera.setHUD(null); this.chrono3.detachSelf(); this.chrono3.dispose(); this.chrono2.detachSelf(); this.chrono2.dispose(); this.chrono1.detachSelf(); this.chrono1.dispose(); this.pause.detachSelf(); this.pause.dispose(); this.win.detachSelf(); this.win.dispose(); this.chronoStart.detachSelf(); this.chronoStart.dispose(); this.ground.detachSelf(); this.ground.dispose(); this.playerTrail.detachSelf(); this.playerTrail.dispose(); this.player.detachSelf(); this.player.dispose(); for(Sprite layer : this.backgroundParallaxLayers){ layer.detachSelf(); layer.dispose(); } this.detachSelf(); this.dispose(); } private void destroyPhysicsWorld(){ this.levelElements.clear(); this.engine.runOnUpdateThread(new Runnable(){ public void run(){ PhysicsWorld world = BaseGameScene.this.physicWorld; Iterator<Body> localIterator = BaseGameScene.this.physicWorld.getBodies(); while (true){ if (!localIterator.hasNext()){ world.clearForces(); world.clearPhysicsConnectors(); world.reset(); world.dispose(); System.gc(); return; } try{ final Body localBody = (Body) localIterator.next(); world.destroyBody(localBody); } catch (Exception localException){ Debug.e(localException); } } } }); } private synchronized void disposeLevelElement(final Shape element){ if(this.levelElements.contains(element)){ this.levelElements.remove(element); this.engine.runOnUpdateThread(new Runnable() { @Override public void run() { final PhysicsConnector physicsConnector = BaseGameScene.this.physicWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(element); if (physicsConnector != null){ Body body = physicsConnector.getBody(); body.setActive(false); BaseGameScene.this.physicWorld.unregisterPhysicsConnector(physicsConnector); BaseGameScene.this.physicWorld.destroyBody(body); } element.detachSelf(); } }); } } public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown()){ if(this.isPaused){ this.resume(); } else if(this.isWin){ this.onBackKeyPressed(); } else{ if(pSceneTouchEvent.getY() >= 240){ //Jump this.player.jump(); } else if(pSceneTouchEvent.getY() < 240){ //Roll this.player.roll(); } } } return false; } }
package net.sourceforge.cilib.functions.continuous; import net.sourceforge.cilib.functions.ContinuousFunction; import net.sourceforge.cilib.type.types.Vector; /** * Characteristics: * <ul> * <li>Uni-modal</li> * </ul> * * f(x) = -1.0; x = (Pi, Pi); * * @author engel */ public class Easom extends ContinuousFunction { /** Creates a new instance of Easom */ public Easom() { //constraint.add(new DimensionValidator(2)); setDomain("R(-100, 100)^2"); } public Object getMinimum() { return new Double(-1.0); } /** Each function must provide an implementation which returns the function value * at the given position. The length of the position array should be the same * as the function dimension. * * @param x The position * */ public double evaluate(Vector x) { double powerTerm1 = -((x.getReal(0)-Math.PI)*(x.getReal(0)-Math.PI)); double powerTerm2 = -((x.getReal(1)-Math.PI)*(x.getReal(1)-Math.PI)); double power = powerTerm1 + powerTerm2; return - Math.cos(x.getReal(0)) * Math.cos(x.getReal(1)) * Math.exp(power); } }
package net.ssehub.kernel_haven.typechef.wrapper; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ProcessBuilder.Redirect; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.ssehub.kernel_haven.code_model.SourceFile; import net.ssehub.kernel_haven.typechef.ast.TypeChefBlock; import net.ssehub.kernel_haven.typechef.util.OutputVoider; import net.ssehub.kernel_haven.typechef.wrapper.comm.CommFactory; import net.ssehub.kernel_haven.typechef.wrapper.comm.IComm; import net.ssehub.kernel_haven.util.ExtractorException; import net.ssehub.kernel_haven.util.Logger; import net.ssehub.kernel_haven.util.Util; /** * A wrapper that provides a clean interface around the execution of Typechef in another process. * * @author Adam */ public class Wrapper { private static final Logger LOGGER = Logger.get(); private Configuration config; /** * Creates a Wrapper for Typechef with the given configuration. * * @param config The configuration for Typechef. */ public Wrapper(Configuration config) { this.config = config; } /** * Calculates the class path of the current JVM. This even works, if * additional jars are loaded at runtime, thus it is more reliable than * simply using <code>System.getProperty("java.class.path")</code>. * * @return The class path of the current JVM. */ private static String getClassPath() { // TODO: maybe move this to a Util class? // we can't simply do this: // return System.getProperty("java.class.path"); // this is because we load our plugin jars after the VM already started, // while java.class.path has the class path passed via the command line StringBuilder cp = new StringBuilder(); URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs(); for (URL url : urls) { cp.append(url.getFile()).append(File.pathSeparatorChar); } // remove last path separator if (cp.length() > 0) { cp.delete(cp.length() - 1, cp.length()); } return cp.toString(); } /** * Thread for communicating with the process that executes Typechef. * * @author Adam */ private static class CommThread extends Thread { private static int numRecieving = 0; private static Object numReceivingLock = new Object(); private ServerSocket serSock; private Socket socket; private Configuration config; private List<String> params; private TypeChefBlock result; private List<String> lexerErrors; private IOException commException; private ExtractorException extractorException; /** * Creates a communication thread. * * @param serSock The server socket to listen at. * @param config The configuration. * @param params The parameters to send to the other process. */ public CommThread(ServerSocket serSock, Configuration config, List<String> params) { super("Comm of " + Thread.currentThread().getName()); this.serSock = serSock; this.config = config; this.params = params; lexerErrors = new ArrayList<>(0); } /** * Returns the result that was sent to us. If this is null, then the extractor failed. * * @return The result, may be null. */ public TypeChefBlock getResult() { return result; } /** * Returns the list of lexer errors that was sent to us. * * @return The list of lexer errors, never null. */ public List<String> getLexerErrors() { return lexerErrors; } /** * Returns an exception if communication failed. * * @return The exception, null if no exception occured. */ public IOException getCommException() { return commException; } /** * Returns the exception that was sent to us. If this is not null then the extractor failed. * * @return The exception, may be null. */ public ExtractorException getExtractorException() { return extractorException; } /** * Closes all sockets that are open. */ public void close() { if (serSock != null) { try { serSock.close(); } catch (IOException e) { } } } /** * Checks whether we can receive data, without violating the receiving limit. If we can't receive now, wait * until we can. Also increases numReceiving. */ private void checkAndWaitReceivingLimit() { synchronized (numReceivingLock) { while (config.getMaxReceivingThreads() > 0 && numRecieving >= config.getMaxReceivingThreads()) { // other threads notify numReceivingLock, if they decrement numReceiving LOGGER.logDebug(numRecieving + " threads are currently recieving data; waiting until this is" + " lower than " + config.getMaxReceivingThreads()); try { numReceivingLock.wait(); } catch (InterruptedException e) { } } LOGGER.logDebug("Start receiving data"); numRecieving++; } } @Override @SuppressWarnings("unchecked") public void run() { boolean numReceivingIncreased = false; try { socket = serSock.accept(); ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); out.writeBoolean(config.isParseToAst()); out.writeUnshared(params); Message type; while ((type = (Message) in.readUnshared()) != Message.END) { LOGGER.logDebug("Got message: " + type); switch (type) { case RESULT: { checkAndWaitReceivingLimit(); numReceivingIncreased = true; Runtime rt = Runtime.getRuntime(); long usedMemoryBefore = rt.totalMemory() - rt.freeMemory(); IComm receiver = CommFactory.createComm(in, out); this.result = receiver.receiveResult(); long usedMemoryAfter = rt.totalMemory() - rt.freeMemory(); LOGGER.logDebug("Memory usage before we got the result: " + Util.formatBytes(usedMemoryBefore), "Memory usage after we got the result: " + Util.formatBytes(usedMemoryAfter)); break; } case LEXER_ERRORS: { lexerErrors = (List<String>) in.readUnshared(); break; } case EXCEPTION: { this.extractorException = (ExtractorException) in.readUnshared(); break; } case TIMINGS: { Map<String, Long> times = (Map<String, Long>) in.readUnshared(); LOGGER.logDebug("Timing reported by runner (in ms):", times.toString()); break; } default: throw new IOException("Invalid message type: " + type); } } } catch (EOFException e) { commException = new IOException("TypeChefRunner exited abruptly;" + " the sub-process probably crashed"); } catch (ClassNotFoundException | ClassCastException e) { commException = new IOException(e); } catch (IOException e) { commException = e; } finally { try { serSock.close(); } catch (IOException e) { } if (numReceivingIncreased) { synchronized (numReceivingLock) { numRecieving numReceivingLock.notify(); } } } } } /** * Runs the Typechef process. This method blocks until the process exited. * * @param port The port to pass to the process for communication. * @return Whether the execution was successful, or not. * * @throws IOException If running the process fails. */ private boolean runTypeChefProcess(int port) throws IOException { boolean success = false; if (config.callInSameVm()) { LOGGER.logWarning("Starting TypeChef in same JVM"); try { Runner.main(new String[] {String.valueOf(port)}); success = true; } catch (IOException e) { LOGGER.logException("Exception in TypeChefRunner", e); } } else { ProcessBuilder builder = new ProcessBuilder("java", "-DKH_Parent=" + Thread.currentThread().getName(), "-Xms" + config.getProcessRam(), "-Xmx" + config.getProcessRam(), "-cp", getClassPath(), Runner.class.getName(), String.valueOf(port)); LOGGER.logDebug("Starting Typechef process", builder.command().toString()); builder.redirectErrorStream(true); if (config.inheritOutput()) { builder.redirectOutput(Redirect.INHERIT); } else { builder.redirectOutput(Redirect.PIPE); } long start = System.currentTimeMillis(); Process process = builder.start(); if (!config.inheritOutput()) { new OutputVoider(process.getInputStream()).start(); } int returnValue = -1; try { returnValue = process.waitFor(); } catch (InterruptedException e) { LOGGER.logException("Exception while waiting", e); } long duration = System.currentTimeMillis() - start; LOGGER.logDebug("TypeChef runner took " + (duration / 1000) + "s"); success = returnValue == 0; } return success; } /** * Runs Typechef on the given source file inside the source tree specified in the configuration. * * @param file The file to run on. Relative to the source_tree in the configuration passed to * the constructor of this wrapper. * @return A {@link TypeChefBlock} representing the whole file (as an AST). * * @throws IOException If the TypeChef execution or communication with the sub-process throws an IOException. * @throws ExtractorException If Typechef or the output conversion fails. */ private TypeChefBlock runTypeChef(File file) throws IOException, ExtractorException { List<String> params = config.buildParameters(file); if (config.logCallParams()) { LOGGER.logDebug(params.toArray(new String[0])); } ServerSocket serSock = new ServerSocket(0); CommThread comm = new CommThread(serSock, config, params); comm.start(); boolean success = runTypeChefProcess(serSock.getLocalPort()); if (!success) { LOGGER.logWarning("TypeChef runner process returned non-zero exit status", "It will probably not have sent correct data to us"); } // if the process finished, then close the server socket // otherwise, if the process failed before the connection was established, we wait here forever comm.close(); try { comm.join(); } catch (InterruptedException e) { LOGGER.logException("Exception while waiting", e); } if (!comm.getLexerErrors().isEmpty()) { String[] errorStr = new String[comm.getLexerErrors().size() + 1]; errorStr[0] = "Lexer errors:"; for (int i = 1; i < errorStr.length; i++) { errorStr[i] = comm.getLexerErrors().get(i - 1); } LOGGER.logInfo(errorStr); } if (comm.getExtractorException() != null) { LOGGER.logExceptionDebug("Got extractor exception", comm.getExtractorException()); throw comm.getExtractorException(); } if (comm.getCommException() != null) { LOGGER.logExceptionDebug("Got comm exception", comm.getCommException()); throw comm.getCommException(); } TypeChefBlock result = comm.getResult(); if (result == null) { LOGGER.logDebug("Got neither exception nor result"); throw new ExtractorException("Runner didn't return result or exception"); } // manually set the location of the result, since Typechef creates a temporary command-line input so we // don't get proper filenames for the top-block result.setFile(file.getPath()); result.setLine(1); LOGGER.logDebug("Got result"); return result; } /** * Runs Typechef on the given source file inside the source tree specified in the configuration. * * @param file The file to run on. Relative to the source_tree in the configuration passed to * the constructor of this wrapper. * @return A {@link SourceFile} representing the file. * * @throws IOException If the TypeChef execution or communication with the sub-process throws an IOException. * @throws ExtractorException If Typechef or the output conversion fails. */ public SourceFile runOnFile(File file) throws IOException, ExtractorException { SourceFile result = new SourceFile(file); TypeChefBlock block = runTypeChef(file); result.addBlock(block); return result; } }
package net.x4a42.volksempfaenger.ui; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.text.DecimalFormat; import net.x4a42.volksempfaenger.R; import net.x4a42.volksempfaenger.Utils; import net.x4a42.volksempfaenger.data.DatabaseHelper; import net.x4a42.volksempfaenger.net.DescriptionImageDownloader; import net.x4a42.volksempfaenger.service.DownloadService; import net.x4a42.volksempfaenger.service.PlaybackService; import net.x4a42.volksempfaenger.service.PlaybackService.PlaybackBinder; import net.x4a42.volksempfaenger.service.PlaybackService.PlayerListener; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.ImageSpan; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; public class ViewEpisodeActivity extends BaseActivity implements OnClickListener, OnSeekBarChangeListener, ServiceConnection, PlayerListener { private SeekBar seekBar; private TextView textDuration; private TextView textPosition; private ImageButton buttonPlay, buttonBack, buttonForward; private boolean bound = false; private PlaybackService service; private boolean startedPlaying = false; private Handler updateHandler; private long id; private DatabaseHelper dbHelper; private ImageView podcastLogo; private TextView podcastTitle; private TextView podcastDescription; private TextView episodeTitle; private TextView episodeDescription; private String descriptionText; private SpannableStringBuilder descriptionSpanned; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Check if there is an ID Bundle extras = getIntent().getExtras(); if (extras == null) { finish(); return; } id = extras.getLong("id"); if (id <= 0) { finish(); return; } setContentView(R.layout.view_episode); dbHelper = DatabaseHelper.getInstance(this); podcastLogo = (ImageView) findViewById(R.id.podcast_logo); podcastTitle = (TextView) findViewById(R.id.podcast_title); podcastDescription = (TextView) findViewById(R.id.podcast_description); episodeTitle = (TextView) findViewById(R.id.episode_title); episodeDescription = (TextView) findViewById(R.id.episode_description); seekBar = (SeekBar) findViewById(R.id.seekBar1); buttonPlay = (ImageButton) findViewById(R.id.button_play); buttonBack = (ImageButton) findViewById(R.id.button_back); buttonForward = (ImageButton) findViewById(R.id.button_forward); textDuration = (TextView) findViewById(R.id.text_duration); textPosition = (TextView) findViewById(R.id.text_position); episodeDescription.setMovementMethod(LinkMovementMethod.getInstance()); seekBar.setEnabled(false); buttonBack.setEnabled(false); buttonForward.setEnabled(false); buttonPlay.setOnClickListener(this); buttonBack.setOnClickListener(this); buttonForward.setOnClickListener(this); seekBar.setOnSeekBarChangeListener(this); Intent intent = new Intent(this, PlaybackService.class); startService(intent); bindService(intent, this, Context.BIND_AUTO_CREATE); updateHandler = new Handler(); } @Override public void onPause() { super.onResume(); updateHandler.removeCallbacks(updateSliderTask); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (service != null && service.isPlaying()) { updateHandler.post(updateSliderTask); } Cursor c; // Update episode information c = dbHelper.getReadableDatabase().query(DatabaseHelper.Episode._TABLE, null, String.format("%s = ?", DatabaseHelper.Episode.ID), new String[] { String.valueOf(id) }, null, null, null); if (!c.moveToFirst()) { // ID does not exist finish(); return; } long podcastId = c.getLong(c .getColumnIndex(DatabaseHelper.Episode.PODCAST)); episodeTitle.setText(c.getString(c .getColumnIndex(DatabaseHelper.Episode.TITLE))); descriptionText = Utils.normalizeString(c.getString(c .getColumnIndex(DatabaseHelper.Episode.DESCRIPTION))); Spanned s = Html.fromHtml(descriptionText); if (s instanceof SpannableStringBuilder) { descriptionSpanned = (SpannableStringBuilder) s; } else { descriptionSpanned = new SpannableStringBuilder(s); } episodeDescription.setText(descriptionSpanned); new ImageLoadTask().execute(); c.close(); File podcastLogoFile = Utils.getPodcastLogoFile(this, podcastId); if (podcastLogoFile.isFile()) { Bitmap podcastLogoBitmap = BitmapFactory.decodeFile(podcastLogoFile .getAbsolutePath()); podcastLogo.setImageBitmap(podcastLogoBitmap); } // Update podcast information c = dbHelper.getReadableDatabase().query(DatabaseHelper.Podcast._TABLE, null, String.format("%s = ?", DatabaseHelper.Podcast.ID), new String[] { String.valueOf(podcastId) }, null, null, null, "1"); if (!c.moveToFirst()) { // ID does not exist finish(); return; } podcastTitle.setText(c.getString(c .getColumnIndex(DatabaseHelper.Podcast.TITLE))); podcastDescription.setText(c.getString(c .getColumnIndex(DatabaseHelper.Podcast.DESCRIPTION))); c.close(); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (service != null) { unbindService(this); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.view_episode, menu); addGlobalMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; Cursor cursor; ContentValues values = new ContentValues(); switch (item.getItemId()) { case R.id.item_download: intent = new Intent(this, DownloadService.class); cursor = dbHelper.getReadableDatabase().query( DatabaseHelper.Enclosure._TABLE, new String[] { DatabaseHelper.Enclosure.ID }, String.format("%s = ?", DatabaseHelper.Enclosure.EPISODE), new String[] { String.valueOf(id) }, null, null, null); long[] v = null; if (cursor.getCount() != 0) { v = new long[cursor.getCount()]; for (int i = 0; i < v.length; i++) { cursor.moveToNext(); v[i] = cursor.getLong(0); } } cursor.close(); intent.putExtra("id", v); startService(intent); Toast.makeText(this, R.string.message_download_queued, Toast.LENGTH_SHORT).show(); return true; case R.id.item_mark_listened: values.put(DatabaseHelper.Enclosure.STATE, DatabaseHelper.Enclosure.STATE_LISTENED); values.put(DatabaseHelper.Enclosure.DURATION_LISTENED, 0); dbHelper.getWritableDatabase().update( DatabaseHelper.Enclosure._TABLE, values, String.format("%s = ?", DatabaseHelper.Enclosure.EPISODE), new String[] { String.valueOf(id) }); return true; case R.id.item_delete: // TODO: confirmation dialog, AsyncTask cursor = dbHelper.getReadableDatabase().query( DatabaseHelper.Enclosure._TABLE, new String[] { DatabaseHelper.Enclosure.ID, DatabaseHelper.Enclosure.FILE }, String.format("%s = ?", DatabaseHelper.Enclosure.EPISODE), new String[] { String.valueOf(id) }, null, null, null); while (cursor.moveToNext()) { String filename = cursor.getString(1); try { if (filename != null) { File f = new File(new URI(filename)); if (f.isFile()) { f.delete(); } } } catch (URISyntaxException e) { Log.w(getClass().getSimpleName(), "Exception handled", e); } values.put(DatabaseHelper.Enclosure.FILE, (String) null); values.put(DatabaseHelper.Enclosure.STATE, DatabaseHelper.Enclosure.STATE_DELETED); dbHelper.getReadableDatabase().update( DatabaseHelper.Enclosure._TABLE, values, String.format("%s = ?", DatabaseHelper.Enclosure.ID), new String[] { String.valueOf(cursor.getLong(0)) }); } cursor.close(); return true; default: return handleGlobalMenu(item); } } public Drawable getDrawable(String src) { return null; } private Runnable updateSliderTask = new Runnable() { public void run() { seekBar.setProgress(service.getCurrentPosition()); updateHandler.postDelayed(this, 500); updateTime(); } }; public void onClick(View v) { switch (v.getId()) { case R.id.button_play: if (bound) { if (startedPlaying) { togglePlayPause(); } else { try { // TODO change to actual file name service.playFile("/mnt/sdcard/test.mp3"); startedPlaying = true; } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } break; case R.id.button_back: if (bound) { int newPosition = service.getCurrentPosition() - 30000; if (newPosition < 0) { newPosition = 0; } service.seekTo(newPosition); } break; case R.id.button_forward: if (bound) { int newPosition = service.getCurrentPosition() + 30000; int duration = service.getDuration(); if (newPosition > duration) { newPosition = duration - 1000; } service.seekTo(newPosition); } break; } } private void togglePlayPause() { if (service.isPlaying()) { setButtonPlay(); service.pause(); } else { setButtonPause(); buttonPlay.setImageResource(android.R.drawable.ic_media_pause); service.play(); } } private void setPlaying() { startedPlaying = true; setButtonPause(); textDuration.setText(formatTime(service.getDuration())); seekBar.setMax(service.getDuration()); seekBar.setEnabled(true); buttonBack.setEnabled(true); buttonForward.setEnabled(true); updateHandler.removeCallbacks(updateSliderTask); updateHandler.post(updateSliderTask); } private void setButtonPlay() { buttonPlay.setImageResource(android.R.drawable.ic_media_play); } private void setButtonPause() { buttonPlay.setImageResource(android.R.drawable.ic_media_pause); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser && startedPlaying) { updateHandler.removeCallbacks(updateSliderTask); service.seekTo(progress); updateTime(); updateHandler.post(updateSliderTask); } } public void onStartTrackingTouch(SeekBar seekBar) { updateHandler.removeCallbacks(updateSliderTask); } public void onStopTrackingTouch(SeekBar seekBar) { } private void updateTime() { textPosition.setText(formatTime(service.getCurrentPosition())); } private String formatTime(int milliseconds) { int seconds = milliseconds / 1000; int hours = seconds / 3600; int minutes = (seconds / 60) - (hours * 60); int seconds2 = seconds - (minutes * 60) - (hours * 3600); DecimalFormat format = new DecimalFormat("00"); return format.format(hours) + ":" + format.format(minutes) + ":" + format.format(seconds2); } public void onServiceConnected(ComponentName name, IBinder binder) { service = ((PlaybackBinder) binder).getService(); service.setPlayerListener(this); if (service.isPlaying()) { setPlaying(); } bound = true; } public void onServiceDisconnected(ComponentName name) { Log.e(TAG, "Service disconnected"); bound = false; } public void onPlayerPaused() { setButtonPlay(); } public void onPlayerStopped() { // TODO clean up setButtonPlay(); seekBar.setEnabled(false); buttonBack.setEnabled(false); buttonForward.setEnabled(false); textPosition.setText("00:00:00"); textDuration.setText("00:00:00"); } public void onPlayerPrepared() { service.play(); setPlaying(); } private class ImageLoadTask extends AsyncTask<Void, ImageSpan, Void> { private DescriptionImageDownloader imageDownloader; DisplayMetrics metrics = new DisplayMetrics(); @Override protected void onPreExecute() { imageDownloader = new DescriptionImageDownloader( ViewEpisodeActivity.this); getWindowManager().getDefaultDisplay().getMetrics(metrics); } @Override protected Void doInBackground(Void... params) { for (ImageSpan img : descriptionSpanned.getSpans(0, descriptionSpanned.length(), ImageSpan.class)) { if (!getImageFile(img).isFile()) { try { imageDownloader.fetchImage(img.getSource()); } catch (Exception e) { // Who cares? Log.d(getClass().getSimpleName(), "Exception handled", e); } } publishProgress(img); } return null; } @Override protected void onProgressUpdate(ImageSpan... values) { ImageSpan img = values[0]; File cache = getImageFile(img); String src = img.getSource(); if (cache.isFile()) { Drawable d = new BitmapDrawable(getResources(), cache.getAbsolutePath()); int width, height; int originalWidthScaled = (int) (d.getIntrinsicWidth() * metrics.density); int originalHeightScaled = (int) (d.getIntrinsicHeight() * metrics.density); if (originalWidthScaled > metrics.widthPixels) { height = d.getIntrinsicHeight() * metrics.widthPixels / d.getIntrinsicWidth(); width = metrics.widthPixels; } else { height = originalHeightScaled; width = originalWidthScaled; } d.setBounds(0, 0, width, height); ImageSpan newImg = new ImageSpan(d, src); int start = descriptionSpanned.getSpanStart(img); int end = descriptionSpanned.getSpanEnd(img); descriptionSpanned.removeSpan(img); descriptionSpanned.setSpan(newImg, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // explicitly update description episodeDescription.setText(descriptionSpanned); } } private File getImageFile(ImageSpan img) { return getImageFile(img.getSource()); } private File getImageFile(String url) { return Utils.getDescriptionImageFile(ViewEpisodeActivity.this, url); } } }
package rhogenwizard.sdk.task; import java.io.IOException; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.IStreamListener; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.core.model.IStreamMonitor; import rhogenwizard.Activator; import rhogenwizard.ConsoleHelper; import rhogenwizard.ILogDevice; import rhogenwizard.OSHelper; import rhogenwizard.SysCommandExecutor; public class RubyDebugTask extends RubyTask implements IDebugTask { private final ILaunch m_launch; private final String m_appName; private final ConsoleHelper.Console m_console; private IProcess m_debugProcess; public RubyDebugTask(ILaunch launch, String appName, String workDir, SysCommandExecutor.Decorator decorator, String... args) { super(workDir, decorator, args); m_launch = launch; m_appName = appName; m_console = ConsoleHelper.getBuildConsole(); m_debugProcess = null; } @Override public boolean isOk() { return m_debugProcess != null; } @Override public IProcess getDebugProcess() { return m_debugProcess; } @Override public void exec() { m_console.show(); m_console.getStream().print(showCommand()); SysCommandExecutor executor = new SysCommandExecutor(); executor.setOutputLogDevice(getLogDevice(m_console.getOutputStream())); executor.setErrorLogDevice(getLogDevice(m_console.getErrorStream())); executor.setWorkingDirectory(m_workDir); Process process; try { process = executor.startCommand(m_decorator, m_cmdLine, null); } catch (IOException e) { Activator.logError(e); return; } m_debugProcess = DebugPlugin.newProcess(m_launch, process, m_appName); if (m_debugProcess != null) { attachConsole(m_debugProcess, m_console); } new Job("Bring console back.") { @Override protected IStatus run(IProgressMonitor monitor) { m_console.show(); return Status.OK_STATUS; } }.schedule(1000); } public static void attachConsole(IProcess process, ConsoleHelper.Console console) { process.getStreamsProxy().getErrorStreamMonitor() .addListener(getStreamListener(console.getErrorStream())); process.getStreamsProxy().getOutputStreamMonitor() .addListener(getStreamListener(console.getOutputStream())); } private static IStreamListener getStreamListener(final ConsoleHelper.Stream stream) { return new IStreamListener() { @Override public void streamAppended(String text, IStreamMonitor monitor) { stream.println(text); } }; } private static ILogDevice getLogDevice(final ConsoleHelper.Stream stream) { return new ILogDevice() { @Override public void log(String str) { stream.println(str.replaceAll("\\p{Cntrl}", " ")); } }; } }
package openblocks.common.tileentity; import java.util.Random; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraftforge.common.FakePlayer; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; import openblocks.Config; import openblocks.Log; import openblocks.OpenBlocks; import openblocks.common.GenericInventory; import openblocks.common.api.IAwareTile; import openblocks.common.api.ISurfaceAttachment; import openblocks.utils.BlockUtils; import openblocks.utils.InventoryUtils; public class TileEntitySprinkler extends OpenTileEntity implements IAwareTile, ISurfaceAttachment, IFluidHandler, IInventory { // erpppppp private FluidStack water = new FluidStack(FluidRegistry.WATER, 1); private ItemStack bonemeal = new ItemStack(Item.dyePowder, 1, 15); private FluidTank tank = new FluidTank(FluidContainerRegistry.BUCKET_VOLUME); private GenericInventory inventory = new GenericInventory("sprinkler", true, 9); private boolean hasBonemeal = false; private void attemptFertilize() { if (worldObj == null || worldObj.isRemote) return; if (worldObj.rand.nextDouble() < 1.0 / (hasBonemeal ? Config.sprinklerBonemealFertizizeChance : Config.sprinklerFertilizeChance)) { Random random = worldObj.rand; int x = (random.nextInt(Config.sprinklerEffectiveRange) + 1) * (random.nextBoolean() ? 1 : -1) + xCoord; int z = (random.nextInt(Config.sprinklerEffectiveRange) + 1) * (random.nextBoolean() ? 1 : -1) + zCoord; /* What? Okay think about this. * i = -1 y = yCoord - 1 * i = 0 y = yCoord - 1 * i = 1 y = yCoord * * Is this the intended operation? I've changed it for now -NC */ for (int i = -1; i <= 1; i++) { int y = yCoord + i; try { for (int a = 0; a < 10; a++) { // Mikee, why do we try to apply it 10 times? Is it likely to fail? -NC if (ItemDye.applyBonemeal(bonemeal.copy(), worldObj, x, y, z, new FakePlayer(worldObj, "sprinkler"))) { break; } } } catch(Exception e) { Log.warn(e, "Exception during bonemeal applying"); } } } } private void sprayParticles() { if (worldObj == null || !worldObj.isRemote) return; for (int i = 0; i < 6; i++) { float offset = (i - 2.5f) / 5f; ForgeDirection rotation = getRotation(); OpenBlocks.proxy.spawnLiquidSpray(worldObj, water, xCoord + 0.5 + (offset * 0.6 * rotation.offsetX), yCoord, zCoord + 0.5 + (offset * 0.6 * rotation.offsetZ), rotation, getSprayPitch(), 2 * offset); } } @Override public void updateEntity() { super.updateEntity(); if (!worldObj.isRemote) { if (tank.getFluid() == null || tank.getFluid().amount == 0) { TileEntity below = worldObj.getBlockTileEntity(xCoord, yCoord - 1, zCoord); if (below instanceof IFluidHandler) { IFluidHandler belowTank = (IFluidHandler)below; FluidStack drained = belowTank.drain(ForgeDirection.UP, tank.getCapacity(), false); if (drained != null && drained.isFluidEqual(water)) { drained = belowTank.drain(ForgeDirection.UP, tank.getCapacity(), true); if (drained != null) { tank.fill(drained, true); } } } } // every 60 ticks drain from the tank // if there's nothing to drain, disable it if (OpenBlocks.proxy.getTicks(worldObj) % 1200 == 0) { hasBonemeal = InventoryUtils.consumeInventoryItem(inventory, bonemeal); } if (OpenBlocks.proxy.getTicks(worldObj) % 60 == 0) { setEnabled(tank.drain(1, true) != null); sync(); } // if it's enabled.. } // simplified this action because only one of these will execute // depending on worldObj.isRemote if (isEnabled()) { attemptFertilize(); sprayParticles(); } } private void setEnabled(boolean b) { setFlag1(b); } private boolean isEnabled() { return getFlag1(); } @Override public int getSizeInventory() { return inventory.getSizeInventory(); } @Override public ItemStack getStackInSlot(int i) { return inventory.getStackInSlot(i); } @Override public ItemStack decrStackSize(int i, int j) { return inventory.decrStackSize(i, j); } @Override public ItemStack getStackInSlotOnClosing(int i) { return inventory.getStackInSlotOnClosing(i); } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { inventory.setInventorySlotContents(i, itemstack); } @Override public String getInvName() { return inventory.getInvName(); } @Override public boolean isInvNameLocalized() { return inventory.isInvNameLocalized(); } @Override public int getInventoryStackLimit() { return inventory.getInventoryStackLimit(); } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return inventory.isUseableByPlayer(entityplayer); } @Override public void openChest() {} @Override public void closeChest() {} @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return itemstack != null && itemstack.isItemEqual(bonemeal); } @Override public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { if (resource != null && resource.isFluidEqual(water)) { return tank.fill(resource, doFill); } return 0; } @Override public ForgeDirection getSurfaceDirection() { return ForgeDirection.DOWN; } @Override public void onBlockBroken() { if (!worldObj.isRemote && !worldObj.isAirBlock(xCoord, yCoord, zCoord)) { BlockUtils.dropItemStackInWorld(worldObj, xCoord, yCoord, zCoord, new ItemStack(OpenBlocks.Blocks.sprinkler)); } } @Override public void onBlockAdded() {} @Override public boolean onBlockActivated(EntityPlayer player, int side, float hitX, float hitY, float hitZ) { if (player.isSneaking()) { return false; } if (!worldObj.isRemote) { openGui(player, OpenBlocks.Gui.Sprinkler); } return true; } @Override public void onNeighbourChanged(int blockId) {} @Override public void onBlockPlacedBy(EntityPlayer player, ForgeDirection side, ItemStack stack, float hitX, float hitY, float hitZ) { setRotation(BlockUtils.get2dOrientation(player)); sync(); } @Override public boolean onBlockEventReceived(int eventId, int eventParam) { return false; } public float getSprayPitch() { return (float)(getSprayAngle() * Math.PI); } public float getSprayAngle() { if (isEnabled()) { return MathHelper.sin(OpenBlocks.proxy.getTicks(worldObj) * 0.02f) * (float)Math.PI * 0.035f; } return 0; } @Override public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); inventory.writeToNBT(tag); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); inventory.readFromNBT(tag); if (tag.hasKey("rotation")) { byte ordinal = tag.getByte("rotation"); setRotation(ForgeDirection.getOrientation(ordinal)); sync(); } } @Override public boolean canFill(ForgeDirection from, Fluid fluid) { return true; } @Override public boolean canDrain(ForgeDirection from, Fluid fluid) { return false; } @Override public FluidTankInfo[] getTankInfo(ForgeDirection from) { return new FluidTankInfo[] { tank.getInfo() }; } @Override public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { return null; } @Override public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { return null; } }
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.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; /** * 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 // 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 private Hashtable fIdDefs = null; private Hashtable fIdRefs = null; private Object fNullValue = null; // attribute validators // REVISIT: Validation. A validator per element declaration and // attribute declaration is required to accomodate // Schema facets on simple types. private AttributeValidator fAttValidatorCDATA = null; private AttributeValidator fAttValidatorID = new AttValidatorID(); private AttributeValidator fAttValidatorIDREF = new AttValidatorIDREF(); private AttributeValidator fAttValidatorIDREFS = new AttValidatorIDREFS(); 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; // declarations private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); //REVISIT: validation private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementTypeStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private int[] fElementLocalPartStack = new int[8]; 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 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; // 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; // 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); 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 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(); } 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(); fElementTypeStack[fElementDepth] = fCurrentElement.rawname; fElementLocalPartStack[fElementDepth]=fCurrentElement.localpart; fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementTypeStack.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; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementTypeStack, 0, newStack, 0, newElementDepth); fElementTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy( this.fElementLocalPartStack , 0, newStack, 0, newElementDepth); fElementLocalPartStack = newStack; 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; } } /** 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; // REVISIT: Validation 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); reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex));// REVISIT: getContentSpecAsString(elementIndex)); } } 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 && fIdRefs != null) { checkIdRefs(); } 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 = fElementLocalPartStack[fElementDepth]; } else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off fCurrentElement.localpart = fElementTypeStack[fElementDepth]; } fCurrentElement.rawname = fElementTypeStack[fElementDepth]; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; //REVISIT: Validation 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. */ /** Normalize attribute value. */ /** 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 = getContentModel(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; } /** addId. */ protected boolean addId(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs == null) { fIdDefs = new Hashtable(); } else if (fIdDefs.containsKey(key)) { return false; } if (fNullValue == null) { fNullValue = new Object(); } fIdDefs.put(key, fNullValue/*new Integer(elementType)*/); return true; } // addId(int):boolean /** addIdRef. */ protected void addIdRef(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs != null && fIdDefs.containsKey(key)) { return; } if (fIdRefs == null) { fIdRefs = new Hashtable(); } else if (fIdRefs.containsKey(key)) { return; } if (fNullValue == null) { fNullValue = new Object(); } fIdRefs.put(key, fNullValue/*new Integer(elementType)*/); } // addIdRef(int) // 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 // content models /** * This method will handle the querying of the content model for a * particular element. If the element does not have a content model, then * it will be created. */ private XMLContentModel getContentModel(int elementIndex) throws CMException { // See if a content model already exists first XMLContentModel cmRet = getElementContentModel(elementIndex); // If we have one, just return that. Otherwise, gotta create one if (cmRet != null) { return cmRet; } // Get the type of content this element has final int contentSpec = getContentSpecType(elementIndex); // And create the content model according to the spec type if (contentSpec == XMLElementDecl.TYPE_MIXED) { // Just create a mixel content model object. This type of // content model is optimized for mixed content validation. //REVISIT, could not compile // XMLContentSpec specNode = new XMLContentSpec(); // int contentSpecIndex = getContentSpecHandle(elementIndex); // makeContentList(contentSpecIndex, specNode); // cmRet = new MixedContentModel(fCount, fContentList); } else if (contentSpec == XMLElementDecl.TYPE_CHILDREN) { // This method will create an optimal model for the complexity // of the element's defined model. If its simple, it will create // a SimpleContentModel object. If its a simple list, it will // create a SimpleListContentModel object. If its complex, it // will create a DFAContentModel object. //REVISIT: couldnot compile //cmRet = createChildModel(elementIndex); } else if (contentSpec == fDATATYPESymbol) { // cmRet = fSchemaImporter.createDatatypeContentModel(elementIndex); } else { throw new CMException(ImplementationMessages.VAL_CST); } // Add the new model to the content model for this element //REVISIT setContentModel(elementIndex, cmRet); return cmRet; } // getContentModel(int):XMLContentModel // initialization /** Reset pool. */ private void poolReset() { if (fIdDefs != null) { fIdDefs.clear(); } if (fIdRefs != null) { fIdRefs.clear(); } } // 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; 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"); /** fEMPTYSymbol = XMLElementDecl.TYPE_EMPTY; fANYSymbol = XMLElementDecl.TYPE_ANY; fMIXEDSymbol = XMLElementDecl.TYPE_MIXED; fCHILDRENSymbol = XMLElementDecl.TYPE_CHILDREN; fCDATASymbol = XMLAttributeDecl.TYPE_CDATA; fIDSymbol = XMLAttributeDecl.TYPE_ID; fIDREFSymbol = XMLAttributeDecl.TYPE_IDREF; fIDREFSSymbol = XMLAttributeDecl.TYPE_IDREF; fENTITYSymbol = XMLAttributeDecl.TYPE_ENTITY; fENTITIESSymbol = XMLAttributeDecl.TYPE_ENTITY; fNMTOKENSymbol = XMLAttributeDecl.TYPE_NMTOKEN; fNMTOKENSSymbol = XMLAttributeDecl.TYPE_NMTOKEN; fNOTATIONSymbol = XMLAttributeDecl.TYPE_NOTATION; fENUMERATIONSymbol = XMLAttributeDecl.TYPE_ENUMERATION; fREQUIREDSymbol = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED; fFIXEDSymbol = XMLAttributeDecl.DEFAULT_TYPE_FIXED; fDATATYPESymbol = XMLElementDecl.TYPE_SIMPLE; **/ } // 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); //System.out.println("addDefaultAttributes: " + fStringPool.toString(fTempElementDecl.name.localpart)+ // "," + attrIndex + "," + validationEnabled); 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 /** Queries the content model for the specified element index. */ /** Sets the content model for the specified element index. */ /*if (elementIndex < 0 || elementIndex >= fElementCount) { return; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; fContentModel[chunk][index] = cm; */ } // query attribute information /** Returns the validatator for an attribute type. */ private AttributeValidator getValidatorForAttType(int attType, boolean list) { if (attType == XMLAttributeDecl.TYPE_CDATA) { if (fAttValidatorCDATA == null) { fAttValidatorCDATA = new AttValidatorCDATA(); } return fAttValidatorCDATA; } if (attType == XMLAttributeDecl.TYPE_ID) { if (fAttValidatorID == null) { fAttValidatorID = new AttValidatorID(); } return fAttValidatorID; } if (attType == XMLAttributeDecl.TYPE_IDREF) { if (!list) { if (fAttValidatorIDREF == null) { fAttValidatorIDREF = new AttValidatorIDREF(); } return fAttValidatorIDREF; } else { if (fAttValidatorIDREFS == null) { fAttValidatorIDREFS = new AttValidatorIDREFS(); } return fAttValidatorIDREFS; } } if (attType == XMLAttributeDecl.TYPE_ENTITY) { if (!list) { if (fAttValidatorENTITY == null) { fAttValidatorENTITY = new AttValidatorENTITY(); } return fAttValidatorENTITY; } else{ if (fAttValidatorENTITIES == null) { fAttValidatorENTITIES = new AttValidatorENTITIES(); } return fAttValidatorENTITIES; } } if (attType == XMLAttributeDecl.TYPE_NMTOKEN) { if (!list) { if (fAttValidatorNMTOKEN == null) { fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); } return fAttValidatorNMTOKEN; } else{ if (fAttValidatorNMTOKENS == null) { fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); } return fAttValidatorNMTOKENS; } } if (attType == XMLAttributeDecl.TYPE_NOTATION) { if (fAttValidatorNOTATION == null) { fAttValidatorNOTATION = new AttValidatorNOTATION(); } return fAttValidatorNOTATION; } if (attType == XMLAttributeDecl.TYPE_ENUMERATION) { if (fAttValidatorENUMERATION == null) { fAttValidatorENUMERATION = new AttValidatorENUMERATION(); } return fAttValidatorENUMERATION; } if (attType == XMLAttributeDecl.TYPE_SIMPLE) { if (fAttValidatorDATATYPE == null) { fAttValidatorDATATYPE = null; //REVISIT : !!! used to be fSchemaImporter.createDatatypeAttributeValidator(); } //return fAttValidatorDATATYPE; } return null; //throw new RuntimeException("getValidatorForAttType(" + fStringPool.toString(attType) + ")"); } /** Returns an attribute definition for an element type. */ // this is only used by DTD validation. private int getAttDef(QName element, QName attribute) { if (fGrammar != null) { int scope = fCurrentScope; if (element.uri > -1) { scope = TOP_LEVEL_SCOPE; } int elementIndex = fGrammar.getElementDeclIndex(element,scope); if (elementIndex == -1) { return -1; } int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); while (attDefIndex != -1) { fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl); if (fTempAttDecl.name.localpart == attribute.localpart && fTempAttDecl.name.uri == attribute.uri ) { return attDefIndex; } attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex); } } return -1; } // getAttDef(QName,QName) /** Returns an attribute definition for an element type. */ private int getAttDefByElementIndex(int elementIndex, QName attribute) { if (fGrammar != null && elementIndex > -1) { if (elementIndex == -1) { return -1; } int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); while (attDefIndex != -1) { fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl); if (fTempAttDecl.name.localpart == attribute.localpart && fTempAttDecl.name.uri == attribute.uri ) { return attDefIndex; } attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex); } } return -1; } // getAttDef(QName,QName) // validation /** Root element specified. */ private void rootElementSpecified(QName rootElement) throws Exception { // this is what it used to be //if (fDynamicValidation && !fSeenDoctypeDecl) { //fValidating = false; if (fValidating) { // initialize the grammar to be the default one. if (fGrammar == null) { fGrammar = fGrammarResolver.getGrammar(""); //TO DO, for ericye debug only if (fGrammar == null && DEBUG_SCHEMA_VALIDATION) { System.out.println("Oops! no grammar is found for validation"); } if (fDynamicValidation && fGrammar==null) { fValidating = false; } if (fGrammar != null) { if (fGrammar instanceof DTDGrammar) { fGrammarIsDTDGrammar = true; fGrammarIsSchemaGrammar = false; } else if ( fGrammar instanceof SchemaGrammar ) { fGrammarIsSchemaGrammar = true; fGrammarIsDTDGrammar = false; } fGrammarNameSpaceIndex = fEmptyURI; } } if ( fGrammarIsDTDGrammar && ((DTDGrammar) fGrammar).getRootElementQName(fRootElement) ) { String root1 = fStringPool.toString(fRootElement.rawname); String root2 = fStringPool.toString(rootElement.rawname); if (!root1.equals(root2)) { reportRecoverableXMLError(XMLMessages.MSG_ROOT_ELEMENT_TYPE, XMLMessages.VC_ROOT_ELEMENT_TYPE, fRootElement.rawname, rootElement.rawname); } } } if (fNamespacesEnabled) { if (fNamespacesScope == null) { fNamespacesScope = new NamespacesScope(this); fNamespacesPrefix = fStringPool.addSymbol("xmlns"); fNamespacesScope.setNamespaceForPrefix(fNamespacesPrefix, -1); int xmlSymbol = fStringPool.addSymbol("xml"); int xmlNamespace = fStringPool.addSymbol("http: fNamespacesScope.setNamespaceForPrefix(xmlSymbol, xmlNamespace); } } } // rootElementSpecified(QName) /** Switchs to correct validating symbol tables when Schema changes.*/ private void switchGrammar(int newGrammarNameSpaceIndex) { Grammar tempGrammar = fGrammarResolver.getGrammar(fStringPool.toString(newGrammarNameSpaceIndex)); if (tempGrammar == null) { System.out.println(fStringPool.toString(newGrammarNameSpaceIndex) + " grammar not found"); //TO DO report error here } else { fGrammar = tempGrammar; if (fGrammar instanceof DTDGrammar) { fGrammarIsDTDGrammar = true; fGrammarIsSchemaGrammar = false; } else if ( fGrammar instanceof SchemaGrammar ) { fGrammarIsSchemaGrammar = true; fGrammarIsDTDGrammar = false; } } } /** Binds namespaces to the element and attributes. */ private void bindNamespacesToElementAndAttributes(QName element, XMLAttrList attrList) throws Exception { fNamespacesScope.increaseDepth(); //Vector schemaCandidateURIs = null; Hashtable locationUriPairs = null; if (fAttrListHandle != -1) { int index = attrList.getFirstAttr(fAttrListHandle); while (index != -1) { int attName = attrList.getAttrName(index); int attPrefix = attrList.getAttrPrefix(index); if (fStringPool.equalNames(attName, fXMLLang)) { /** 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 = getContentModel(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; try { // REVISIT: this might not be right //cmElem = getContentModel(elementIndex); //fTempQName.rawname = fTempQName.localpart = fStringPool.addString(fDatatypeBuffer.toString()); //return cmElem.validateContent(1, new QName[] { fTempQName }); fGrammar.getElementDecl(elementIndex, fTempElementDecl); DatatypeValidator dv = fTempElementDecl.datatypeValidator; 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 (CMException cme) { // System.out.println("Internal Error in datatype validation"); 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 /** * Check that all ID references were to ID attributes present in the document. * <p> * This method is a convenience call that allows the validator to do any id ref * checks above and beyond those done by the scanner. The scanner does the checks * specificied in the XML spec, i.e. that ID refs refer to ids which were * eventually defined somewhere in the document. * <p> * If the validator is for a Schema perhaps, which defines id semantics beyond * those of the XML specificiation, this is where that extra checking would be * done. For most validators, this is a no-op. * * @exception Exception Thrown on error. */ private void checkIdRefs() throws Exception { if (fIdRefs == null) return; Enumeration en = fIdRefs.keys(); while (en.hasMoreElements()) { Integer key = (Integer)en.nextElement(); if (fIdDefs == null || !fIdDefs.containsKey(key)) { Object[] args = { fStringPool.toString(key.intValue()) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_WITH_ID_REQUIRED, XMLMessages.VC_IDREF, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } // checkIdRefs() /** * 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 // 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 /** * AttValidatorID. */ final class AttValidatorID 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.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_ID_INVALID, XMLMessages.VC_ID, fStringPool.toString(attribute.rawname), newAttValue); } // ID - check that the id value is unique within the document (V_TAG8) if (element.rawname != -1 && !addId(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ID_NOT_UNIQUE, XMLMessages.VC_ID, 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 standalong 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 AttValidatorID /** * AttValidatorIDREF. */ final class AttValidatorIDREF 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.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_IDREF_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attribute.rawname), newAttValue); } // IDREF - remember the id value if (element.rawname != -1) addIdRef(attValueHandle); } 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 AttValidatorIDREF /** * AttValidatorIDREFS. */ final class AttValidatorIDREFS 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 idName = tokenizer.nextToken(); if (fValidating) { if (!XMLCharacterProperties.validName(idName)) { ok = false; } // IDREFS - remember the id values if (element.rawname != -1) { addIdRef(fStringPool.addSymbol(idName)); } } sb.append(idName); if (!tokenizer.hasMoreTokens()) break; sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID, XMLMessages.VC_IDREF, 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 AttValidatorIDREFS /** * 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 org.cloudbus.cloudsim.simulate; import org.cloudbus.cloudsim.Log; public class PartnerInfomation { private int partnerId; private double ratio; private double requested; private double satified; /** * L in argithorm */ private double lenghtRatio; /** * l in argithorm */ private double kRatio; public PartnerInfomation(int partnerId, double ratio, double requested, double satified,double lenghtRatio, double kRatio) { super(); this.partnerId = partnerId; this.ratio = ratio; this.requested = requested; this.satified = satified; this.lenghtRatio = lenghtRatio; this.kRatio = kRatio; } public PartnerInfomation(int partnerId) { super(); this.partnerId = partnerId; this.ratio = 1; this.requested = 0; this.satified = 0; this.lenghtRatio = 0; this.kRatio = 0; } public PartnerInfomation(int partnerId, double ratio) { super(); this.partnerId = partnerId; this.ratio = ratio; this.requested = 100000; this.satified = 100000; this.lenghtRatio = 1; this.kRatio = 0; } @Override public String toString() { return "PartnerInfomation [partnerId=" + partnerId + ", ratio=" + ratio + ", requested=" + requested + ", satified=" + satified + "lenghtRatio= " + lenghtRatio + "]"; } /** * deviation = ti so tong do dai dung dung i goi cho j tren tong do dai j goi cho i * @param request_lenght * @param satify_lenght * @return */ public double updateLenghtRatio(double request_lenght,double satify_lenght){ double deviation; deviation = calcLenghtRatio(this.getRequested(),this.getSatified()); setLenghtRatio(deviation); return deviation; } public double updateLenghtRatio(){ double deviation; deviation = calcLenghtRatio(0,0); setLenghtRatio(deviation); return deviation; } public double updateRequested(double request_lenght){ setRequested(getRequested()+request_lenght); return getRequested()+request_lenght; } public double updateSatified(double satify_lenght){ setSatified(getSatified()+satify_lenght); return getSatified()+satify_lenght; } public double updateKRatio(){ setkRatio(getKRatio()); return getKRatio(); } public double calcLenghtRatio(double request_lenght,double satify_lenght){ double deviation; if(this.getSatified() != 0 ){ deviation = (getSatified()+satify_lenght)/(this.getRequested()+request_lenght); } else { deviation = 0; } return deviation; } /** * K ratio = L/init_ratio * @return */ public double getKRatio() { double k; if(this.getRatio() == 0 ){ k = 1; } else { k = Math.abs(getLenghtRatio()/getRatio()-1); } return k; } public double getKRatioWithCurrentTask(double request_lenght,double satify_lenght) { double k; if(this.getRatio() == 0 ){ k = 1; } else { k = Math.abs((getLenghtRatio()+calcLenghtRatio(request_lenght, satify_lenght))/getRatio()-1); } return k; } /** * Getter & Setter Area * @return */ public int getPartnerId() { return partnerId; } public void setPartnerId(int partnerId) { this.partnerId = partnerId; } public double getRatio() { return ratio; } public void setRatio(double ratio) { this.ratio = ratio; } public double getRequested() { return requested; } public void setRequested(double requested) { this.requested = requested; updateLenghtRatio(); } public double getSatified() { return satified; } public void setSatified(double satified) { this.satified = satified; updateLenghtRatio(); } public double getLenghtRatio() { return lenghtRatio; } public void setLenghtRatio(double lenghtRatio) { this.lenghtRatio = lenghtRatio; } /** * @return the kRatio */ public double getkRatio() { return kRatio; } /** * @param kRatio the kRatio to set */ public double setkRatio(double kRatio) { this.kRatio = kRatio; return this.kRatio; } }
package org.griphyn.cPlanner.engine; import org.griphyn.cPlanner.classes.FileTransfer; import org.griphyn.cPlanner.classes.LRC; import org.griphyn.cPlanner.classes.NameValue; import org.griphyn.cPlanner.classes.SiteInfo; import org.griphyn.cPlanner.classes.Profile; import org.griphyn.cPlanner.classes.ReplicaLocation; import org.griphyn.cPlanner.classes.ReplicaStore; import org.griphyn.cPlanner.classes.ADag; import org.griphyn.cPlanner.classes.SubInfo; import org.griphyn.cPlanner.classes.PlannerOptions; import org.griphyn.cPlanner.common.LogManager; import org.griphyn.cPlanner.common.PegasusProperties; import org.griphyn.cPlanner.namespace.ENV; import org.griphyn.common.catalog.ReplicaCatalog; import org.griphyn.common.catalog.TransformationCatalogEntry; import org.griphyn.common.catalog.replica.ReplicaFactory; import org.griphyn.common.catalog.transformation.TCMode; import org.griphyn.common.classes.TCType; import org.griphyn.common.util.Separator; import java.io.File; import java.io.FileWriter; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; /** * This coordinates the look up to the Replica Location Service, to determine * the logical to physical mappings. * * @author Karan Vahi * @author Gaurang Mehta * @version $Revision$ * */ public class ReplicaCatalogBridge extends Engine //for the time being. { /** * The transformation namespace for the regostration jobs. */ public static final String RC_TRANSFORMATION_NS = "pegasus"; /** * The logical name of the transformation used. */ public static final String RC_TRANSFORMATION_NAME = "rc-client"; /** * The logical name of the transformation used. */ public static final String RC_TRANSFORMATION_VERSION = null; /** * The derivation namespace for the transfer jobs. */ public static final String RC_DERIVATION_NS = "pegasus"; /** * The derivation name for the transfer jobs. */ public static final String RC_DERIVATION_NAME = "rc-client"; /** * The version number for the derivations for registration jobs. */ public static final String RC_DERIVATION_VERSION = "1.0"; /** * The name of the Replica Catalog Implementer that serves as the source for * cache files. */ public static final String CACHE_REPLICA_CATALOG_IMPLEMENTER = "SimpleFile"; /** * The name of the source key for Replica Catalog Implementer that serves as * cache */ public static final String CACHE_REPLICA_CATALOG_KEY = "file"; /** * The name of the URL key for the replica catalog impelementer to be picked * up. */ public static final String REPLICA_CATALOG_URL_KEY = "url"; /** * The handle to the main Replica Catalog. */ private ReplicaCatalog mReplicaCatalog; /** * Contains the various options to the Planner as passed by the user at * runtime. */ private PlannerOptions mPOptions; /** * The Vector of <code>String</code> objects containing the logical * filenames of the files whose locations are to be searched in the * Replica Catalog. */ protected Set mSearchFiles ; /** * A boolean variable to desingnate whether the RLI queried was down or not. * By default it is up, unless it is set to true explicitly. */ private boolean mRCDown; /** * The replica store in which we store all the results that are queried from * the main replica catalog. */ private ReplicaStore mReplicaStore; /** * The replica store in which we store all the results that are queried from * the cache replica catalogs. */ private ReplicaStore mCacheStore; /** * A boolean indicating whether the cache file needs to be treated as a * replica catalog or not. */ private boolean mTreatCacheAsRC; /** * The namespace object holding the environment variables for local * pool. */ private ENV mLocalEnv; /** * The default tc entry. */ private TransformationCatalogEntry mDefaultTCRCEntry; /** * A boolean indicating whether the attempt to create a default tc entry * has happened or not. */ private boolean mDefaultTCRCCreated; /** * The overloaded constructor. * * @param dag the workflow that is being worked on. * @param properties the properties passed to the planner. * @param options the options passed to the planner at runtime. * * */ public ReplicaCatalogBridge( ADag dag , PegasusProperties properties, PlannerOptions options ) { super( properties ); this.initialize( dag, properties, options); } /** * Intialises the refiner. * * @param dag the workflow that is being worked on. * @param properties the properties passed to the planner. * @param options the options passed to the planner at runtime. * */ public void initialize( ADag dag , PegasusProperties properties, PlannerOptions options ){ mProps = properties; mPOptions = options; mRCDown = false; mCacheStore = new ReplicaStore(); mTreatCacheAsRC = mProps.treatCacheAsRC(); mDefaultTCRCCreated = false; //converting the Vector into vector of //strings just containing the logical //filenames mSearchFiles = dag.dagInfo.getLFNs( options.getForce() ); //load the local environment variable //from pool config and property file mLocalEnv = loadLocalEnvVariables(); try { //make sure that RLS can be loaded from local environment //Karan May 1 2007 mReplicaCatalog = null; if ( mSearchFiles != null && !mSearchFiles.isEmpty() ){ mReplicaCatalog = ReplicaFactory.loadInstance(properties); } //load all the mappings. mReplicaStore = new ReplicaStore( mReplicaCatalog.lookup( mSearchFiles ) ); } catch ( Exception ex ) { String msg = "Problem while connecting with the Replica Catalog: "; mLogger.log( msg + ex.getMessage(),LogManager.ERROR_MESSAGE_LEVEL ); //set the flag to denote RLI is down mRCDown = true; mReplicaStore = new ReplicaStore(); //exit if there is no cache overloading specified. if ( options.getCacheFiles().isEmpty() ) { throw new RuntimeException( msg , ex ); } } mTCHandle = TCMode.loadInstance(); //incorporate the caching if any if ( !options.getCacheFiles().isEmpty() ) { loadCacheFiles( options.getCacheFiles() ); } } /** * To close the connection to replica services. This must be defined in the * case where one has not done a singleton implementation. In other * cases just do an empty implementation of this method. */ public void closeConnection() { if ( mReplicaCatalog != null ) { mReplicaCatalog.close(); } } /** * Closes the connection to the rli. */ public void finalize() { this.closeConnection(); } /** * This returns the files for which mappings exist in the Replica Catalog. * This should return a subset of the files which are * specified in the mSearchFiles, while getting an instance to this. * * @return a <code>Set</code> of logical file names as String objects, for * which logical to physical mapping exists. * * @see #mSearchFiles */ public Set getFilesInReplica() { //check if any exist in the cache Set lfnsFound = mCacheStore.getLFNs( mSearchFiles ); mLogger.log(lfnsFound.size() + " entries found in cache of total " + mSearchFiles.size(), LogManager.DEBUG_MESSAGE_LEVEL); //check in the main replica catalog if ( mRCDown || mReplicaCatalog == null ) { mLogger.log("Replica Catalog is either down or connection to it was never opened ", LogManager.WARNING_MESSAGE_LEVEL); return lfnsFound; } //look up from the the main replica catalog lfnsFound.addAll( mReplicaStore.getLFNs() ); return lfnsFound; } /** * Returns all the locations as returned from the Replica Lookup Mechanism. * * @param lfn The name of the logical file whose PFN mappings are * required. * * @return ReplicaLocation containing all the locations for that LFN * * @see org.griphyn.cPlanner.classes.ReplicaLocation */ public ReplicaLocation getFileLocs( String lfn ) { ReplicaLocation rl = retrieveFromCache( lfn ); //first check from cache if(rl != null && !mTreatCacheAsRC){ mLogger.log( "Location of file " + lfn + " retrieved from cache" , LogManager.DEBUG_MESSAGE_LEVEL); return rl; } ReplicaLocation rcEntry = mReplicaStore.getReplicaLocation( lfn ); if (rl == null) { rl = rcEntry; } else{ //merge with the ones found in cache rl.merge(rcEntry); } return rl; } /** * Returns a boolean indicating whether all input files of the workflow * are in the collection of LFNs passed. * * @param lfns collection of LFNs in which to search for existence. * * @return boolean. */ /* public boolean allIPFilesInCollection( Collection lfns ){ boolean result = true; String lfn; String type; for (Iterator it = mLFNMap.keySet().iterator(); it.hasNext(); ) { lfn = (String) it.next(); type = (String) mLFNMap.get( lfn ); //search for existence of input file in lfns if ( type.equals("i") && !lfns.contains( lfn ) ) { mLogger.log("Input LFN not found in collection " + lfn, LogManager.DEBUG_MESSAGE_LEVEL); return false; } } return result; } */ /** * It constructs the SubInfo object for the registration node, which * registers the materialized files on the output pool in the RLS. * Note that the relations corresponding to this node should already have * been added to the concerned <code>DagInfo</code> object. * * @param regJobName The name of the job which registers the files in the * Replica Location Service. * @param job The job whose output files are to be registered in * the Replica Location Service. * * @param files Collection of <code>FileTransfer</code> objects * containing the information about source and * destination URLs. The destination * URLs would be our PFNs. * * @return SubInfo corresponding to the new registration node. */ public SubInfo makeRCRegNode( String regJobName, SubInfo job, Collection files ) { //making the files string SubInfo newJob = new SubInfo(); newJob.setName( regJobName ); newJob.setTransformation( this.RC_TRANSFORMATION_NS, this.RC_TRANSFORMATION_NAME, this.RC_TRANSFORMATION_VERSION ); newJob.setDerivation( this.RC_DERIVATION_NS, this.RC_DERIVATION_NAME, this.RC_DERIVATION_VERSION ); SiteInfo site = mPoolHandle.getPoolEntry( mOutputPool, "vanilla" ); //change this function List tcentries = null; try { tcentries = mTCHandle.getTCEntries( newJob.getTXNamespace(), newJob.getTXName(), newJob.getTXVersion(), "local", TCType.INSTALLED ); } catch ( Exception e ) { mLogger.log( "While retrieving entries from TC " + e.getMessage(), LogManager.ERROR_MESSAGE_LEVEL); } TransformationCatalogEntry tc; if ( tcentries == null || tcentries.isEmpty() ) { mLogger.log( "Unable to find in entry for " + newJob.getCompleteTCName() + " in transformation catalog on site local", LogManager.DEBUG_MESSAGE_LEVEL ); mLogger.log( "Constructing a default entry for it " , LogManager.DEBUG_MESSAGE_LEVEL ); tc = defaultTCRCEntry( ); if( tc == null ){ throw new RuntimeException( "Unable to create an entry for " + newJob.getCompleteTCName() + " on site local"); } } else{ tc = (TransformationCatalogEntry) tcentries.get(0); } newJob.setRemoteExecutable( tc.getPhysicalTransformation() ); newJob.setArguments( this.generateRepJobArgumentString( site, regJobName, files ) ); newJob.setUniverse( Engine.REGISTRATION_UNIVERSE ); newJob.setSiteHandle( tc.getResourceId() ); newJob.setJobType( SubInfo.REPLICA_REG_JOB ); newJob.setVDSSuperNode( job.getName() ); //the profile information from the pool catalog needs to be //assimilated into the job. newJob.updateProfiles( mPoolHandle.getPoolProfile( newJob.getSiteHandle() ) ); //the profile information from the transformation //catalog needs to be assimilated into the job //overriding the one from pool catalog. newJob.updateProfiles( tc ); //the profile information from the properties file //is assimilated overidding the one from transformation //catalog. newJob.updateProfiles( mProps ); return newJob; } /** * Returns a default TC entry to be used in case entry is not found in the * transformation catalog. * * * * @return the default entry. */ private TransformationCatalogEntry defaultTCRCEntry( ){ String site = "local"; //generate only once. if( !mDefaultTCRCCreated ){ //check if PEGASUS_HOME is set String home = mProps.getPegasusHome( ); //if PEGASUS_HOME is not set, use VDS_HOME //home = ( home == null )? mPoolHandle.getVDS_HOME( site ): home; //if home is still null if ( home == null ){ //cannot create default TC mLogger.log( "Unable to create a default entry for " + Separator.combine( this.RC_TRANSFORMATION_NS, this.RC_TRANSFORMATION_NAME, this.RC_TRANSFORMATION_VERSION ), LogManager.DEBUG_MESSAGE_LEVEL ); //set the flag back to true mDefaultTCRCCreated = true; return mDefaultTCRCEntry; } //remove trailing / if specified home = ( home.charAt( home.length() - 1 ) == File.separatorChar )? home.substring( 0, home.length() - 1 ): home; //construct the path to it StringBuffer path = new StringBuffer(); path.append( home ).append( File.separator ). append( "bin" ).append( File.separator ). append( "rc-client" ); //create Profiles for JAVA_HOME and CLASSPATH String jh = mProps.getProperty( "java.home" ); mLogger.log( "JAVA_HOME set to " + jh, LogManager.DEBUG_MESSAGE_LEVEL ); Profile javaHome = new Profile( Profile.ENV, "JAVA_HOME", jh ); Profile classpath = this.getClassPath( home ); if( classpath == null ){ return mDefaultTCRCEntry ; } mDefaultTCRCEntry = new TransformationCatalogEntry( this.RC_TRANSFORMATION_NS, this.RC_TRANSFORMATION_NAME, this.RC_TRANSFORMATION_VERSION ); mDefaultTCRCEntry.setPhysicalTransformation( path.toString() ); mDefaultTCRCEntry.setResourceId( site ); mDefaultTCRCEntry.setProfile( classpath ); mDefaultTCRCEntry.setProfile( javaHome ); mDefaultTCRCEntry.setProfile( new Profile( Profile.ENV, "PEGASUS_HOME", mProps.getPegasusHome() )); //set the flag back to true mDefaultTCRCCreated = true; } return mDefaultTCRCEntry; } /** * Returns the classpath for the default rc-client entry. * * @param home the home directory where we need to check for lib directory. * * @return the classpath in an environment profile. */ private Profile getClassPath( String home ){ Profile result = null ; //create the CLASSPATH from home String classpath = mProps.getProperty( "java.class.path" ); if( classpath == null || classpath.trim().length() == 0 ){ return result; } mLogger.log( "JAVA CLASSPATH SET IS " + classpath , LogManager.DEBUG_MESSAGE_LEVEL ); StringBuffer cp = new StringBuffer(); String prefix = home + File.separator + "lib"; for( StringTokenizer st = new StringTokenizer( classpath, ":" ); st.hasMoreTokens(); ){ String token = st.nextToken(); if( token.startsWith( prefix ) ){ //this is a valid lib jar to put in cp.append( token ).append( ":" ); } } if ( cp.length() == 0 ){ //unable to create a valid classpath mLogger.log( "Unable to create a sensible classpath from " + home, LogManager.DEBUG_MESSAGE_LEVEL ); return result; } //we have everything now result = new Profile( Profile.ENV, "CLASSPATH", cp.toString() ); return result; } /** * Generates the argument string to be given to the replica registration job. * At present by default it would be picking up the file containing the * mappings. * * @param site the <code>SiteInfo</code> object/ * @param regJob The name of the registration job. * * @param files Collection of <code>FileTransfer</code> objects containing the * information about source and destURLs. The destination * URLs would be our PFNs. * * @return the argument string. */ private String generateRepJobArgumentString( SiteInfo site, String regJob, Collection files ) { StringBuffer arguments = new StringBuffer(); //select a LRC. disconnect here. It should be select a RC. LRC lrc = (site == null) ? null : site.selectLRC(true); if (lrc == null || lrc.getURL() == null || lrc.getURL().length() == 0) { throw new RuntimeException( "The LRC URL is not specified in site catalog for site " + mOutputPool ); } //get any command line properties that may need specifying arguments.append( this.getCommandLineProperties( mProps ) ); //we have a lrc selected . construct vds.rc.url property arguments.append( "-D" ).append( ReplicaCatalog.c_prefix ).append( "." ). append( this.REPLICA_CATALOG_URL_KEY).append( "=" ).append( lrc.getURL() ). append( " " ); //append the insert option arguments.append( "--insert" ).append( " " ). append( this.generateMappingsFile( regJob, files ) ); return arguments.toString(); } /** * Returns the properties that need to be passed to the the rc-client * invocation on the command line . It is of the form * "-Dprop1=value1 -Dprop2=value2 .." * * @param properties the properties object * * @return the properties list, else empty string. */ protected String getCommandLineProperties( PegasusProperties properties ){ StringBuffer sb = new StringBuffer(); appendProperty( sb, "pegasus.user.properties", properties.getPropertiesInSubmitDirectory( )); return sb.toString(); } /** * Appends a property to the StringBuffer, in the java command line format. * * @param sb the StringBuffer to append the property to. * @param key the property. * @param value the property value. */ protected void appendProperty( StringBuffer sb, String key, String value ){ sb.append("-D").append( key ).append( "=" ).append( value ).append( " "); } /** * Generates the registration mappings in a text file that is generated in the * dax directory (the directory where all the condor submit files are * generated). The pool value for the mapping is the output pool specified * by the user when running Pegasus. The name of the file is regJob+.in * * @param regJob The name of the registration job. * @param files Collection of <code>FileTransfer</code>objects containing the * information about source and destURLs. The destination * URLs would be our PFNs. * * @return String corresponding to the path of the the file containig the * mappings in the appropriate format. */ private String generateMappingsFile( String regJob, Collection files ) { String fileName = regJob + ".in"; File f = null; String submitFileDir = mPOptions.getSubmitDirectory(); //writing the stdin file try { f = new File( submitFileDir, fileName ); FileWriter stdIn = new FileWriter( f ); for(Iterator it = files.iterator();it.hasNext();){ FileTransfer ft = ( FileTransfer ) it.next(); //checking for transient flag if ( !ft.getTransientRegFlag() ) { stdIn.write( ftToRC( ft ) ); stdIn.flush(); } } stdIn.close(); } catch ( Exception e ) { throw new RuntimeException( "While writing out the registration file for job " + regJob, e ); } return fileName; } /** * Converts a <code>FileTransfer</code> to a RC compatible string representation. * * @param ft the <code>FileTransfer</code> object * * @return the RC version. */ private String ftToRC( FileTransfer ft ){ StringBuffer sb = new StringBuffer(); NameValue destURL = ft.getDestURL(); sb.append( ft.getLFN() ).append( " " ); sb.append( destURL.getValue() ).append( " " ); sb.append( "pool=\"" ).append( destURL.getKey() ).append( "\"" ); sb.append( "\n" ); return sb.toString(); } /** * Retrieves a location from the cache table, that contains the contents * of the cache files specified at runtime. * * @param lfn the logical name of the file. * * @return <code>ReplicaLocation</code> object corresponding to the entry * if found, else null. */ private ReplicaLocation retrieveFromCache( String lfn ){ return mCacheStore.getReplicaLocation( lfn ); } private void loadCacheFiles( Set cacheFiles ) { Properties cacheProps = mProps.getVDSProperties().matchingSubset( ReplicaCatalog.c_prefix, false ); mLogger.log("Loading transient cache files", LogManager.INFO_MESSAGE_LEVEL); ReplicaCatalog simpleFile; Map wildcardConstraint = null; for ( Iterator it = cacheFiles.iterator(); it.hasNext() ; ) { //read each of the cache file and load in memory String file = ( String ) it.next(); //set the appropriate property to designate path to file cacheProps.setProperty( this.CACHE_REPLICA_CATALOG_KEY, file ); mLogger.log("Loading cache file: " + file, LogManager.DEBUG_MESSAGE_LEVEL); try{ simpleFile = ReplicaFactory.loadInstance( CACHE_REPLICA_CATALOG_IMPLEMENTER, cacheProps ); } catch( Exception e ){ mLogger.log( "Unable to load cache file " + file, e, LogManager.ERROR_MESSAGE_LEVEL ); continue; } //suck in all the entries into the cache replica store. //returns an unmodifiable collection. so merging an issue.. mCacheStore.add( simpleFile.lookup( mSearchFiles ) ); //no wildcards as we only want to load mappings for files that //we require //mCacheStore.add( simpleFile.lookup( wildcardConstraint ) ); //close connection simpleFile.close(); } mLogger.logCompletion("Loading transient cache files", LogManager.INFO_MESSAGE_LEVEL ); } /** * Reads in the environment variables into memory from the properties file * and the pool catalog. * * @return the <code>ENV</code> namespace object holding the environment * variables. */ private ENV loadLocalEnvVariables() { //assumes that pool handle, and property handle are initialized. ENV env = new ENV(); //load from the pool.config env.checkKeyInNS( mPoolHandle.getPoolProfile( "local", Profile.ENV ) ); //load from property file env.checkKeyInNS( mProps.getLocalPoolEnvVar() ); // the new RC API has a different key. if that is specified use that. //mProps.getProperty( ReplicaCatalog.c_prefix ) return env; } }
package org.inaturalist.android; import java.util.ArrayList; import org.inaturalist.android.INaturalistService.LoginType; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.MenuItem; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.Session.StatusCallback; import com.facebook.UiLifecycleHelper; import com.facebook.widget.LoginButton; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Paint; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class INaturalistPrefsActivity extends SherlockActivity { private static final String TAG = "INaturalistPrefsActivity"; public static final String REAUTHENTICATE_ACTION = "reauthenticate_action"; private static final int REQUEST_CODE_LOGIN = 0x1000; private static final int REQUEST_CODE_ADD_ACCOUNT = 0x1001; private static final String GOOGLE_AUTH_TOKEN_TYPE = "oauth2:https: private LinearLayout mSignInLayout; private LinearLayout mSignOutLayout; private TextView mUsernameTextView; private TextView mPasswordTextView; private TextView mSignOutLabel; private Button mSignInButton; private Button mSignOutButton; private Button mSignUpButton; private SharedPreferences mPreferences; private SharedPreferences.Editor mPrefEditor; private ProgressDialog mProgressDialog; private ActivityHelper mHelper; private LoginButton mFacebookLoginButton; private Button mGoogleLogin; private View mFBSeparator; private RadioGroup rbPreferredLocaleSelector; private INaturalistApp mApp; private UiLifecycleHelper mUiHelper; private String mGoogleUsername; private int formerSelectedRadioButton; private Session.StatusCallback mCallback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { onSessionStateChange(session, state, exception); } }; private TextView mHelp; private void onSessionStateChange(Session session, SessionState state, Exception exception) { // Log.d(TAG, "onSessionStateChange: " + session.toString() + ":" + state.toString()); if ((state == SessionState.CLOSED) || (state == SessionState.CLOSED_LOGIN_FAILED)) { signOut(); } } private void askForGoogleEmail() { final EditText input = new EditText(INaturalistPrefsActivity.this); new AlertDialog.Builder(INaturalistPrefsActivity.this) .setTitle(R.string.google_login) .setMessage(R.string.email_address) .setView(input) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String username = input.getText().toString(); if (username.trim().length() == 0) { return; } signIn(LoginType.GOOGLE, username.trim().toLowerCase(), null); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }).show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mApp == null) { mApp = (INaturalistApp) getApplicationContext(); } ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); // try { // Log.d("KeyHash:", "ENTER"); // PackageInfo info = getPackageManager().getPackageInfo( // "org.inaturalist.android", // PackageManager.GET_SIGNATURES); // for (Signature signature : info.signatures) { // MessageDigest md = MessageDigest.getInstance("SHA"); // md.update(signature.toByteArray()); // Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); // } catch (NameNotFoundException e) { // Log.d("NameNotFoundException: ", e.toString()); // } catch (NoSuchAlgorithmException e) { // Log.d("NoSuchAlgorithmException: ", e.toString()); mUiHelper = new UiLifecycleHelper(this, mCallback); mUiHelper.onCreate(savedInstanceState); setContentView(R.layout.preferences); mPreferences = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); mPrefEditor = mPreferences.edit(); mHelper = new ActivityHelper(this); mSignInLayout = (LinearLayout) findViewById(R.id.signIn); mSignOutLayout = (LinearLayout) findViewById(R.id.signOut); mUsernameTextView = (TextView) findViewById(R.id.username); mPasswordTextView = (TextView) findViewById(R.id.password); mSignOutLabel = (TextView) findViewById(R.id.signOutLabel); mSignInButton = (Button) findViewById(R.id.signInButton); mSignOutButton = (Button) findViewById(R.id.signOutButton); mSignUpButton = (Button) findViewById(R.id.signUpButton); mHelp = (TextView) findViewById(R.id.tutorial_link); mHelp.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG); rbPreferredLocaleSelector = (RadioGroup)findViewById(R.id.radioLang); RadioButton rbDeviceLanguage = (RadioButton)findViewById(R.id.rbDeviceLang); rbDeviceLanguage.setText( rbDeviceLanguage.getText() + " (" + mApp.getFormattedDeviceLocale() + ")" ); mHelp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(INaturalistPrefsActivity.this, TutorialActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra("first_time", false); startActivity(intent); } }); mFacebookLoginButton = (LoginButton) findViewById(R.id.facebook_login_button); mGoogleLogin = (Button) findViewById(R.id.google_login_button); mFBSeparator = (View) findViewById(R.id.facebook_login_button_separator); mGoogleLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { signIn(LoginType.GOOGLE, null, null); } }); ArrayList<String> permissions = new ArrayList<String>(); permissions.add("email"); mFacebookLoginButton.setReadPermissions(permissions); mFacebookLoginButton.setSessionStatusCallback(new StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { // Log.d(TAG, "onSessionStateChange: " + state.toString()); if ((state == SessionState.OPENED) || (state == SessionState.OPENED_TOKEN_UPDATED)) { String username = mPreferences.getString("username", null); if (username == null) { // First time login String accessToken = session.getAccessToken(); // Log.d(TAG, "FB Login: " + accessToken); new SignInTask(INaturalistPrefsActivity.this).execute(null, accessToken, LoginType.FACEBOOK.toString()); } } } }); toggle(); mSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = mUsernameTextView.getText().toString().trim().toLowerCase(); String password = mPasswordTextView.getText().toString().trim(); signIn(LoginType.PASSWORD, username, password); } }); mSignOutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signOut(); } }); mSignUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mHelper.confirm(getString(R.string.ready_to_signup), getString(R.string.about_to_signup), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(INaturalistService.HOST + "/users/new")); startActivity(i); } }); } }); if (getIntent().getAction() != null && getIntent().getAction().equals(REAUTHENTICATE_ACTION)) { signOut(); mHelper.alert(getString(R.string.username_invalid)); } updateRadioButtonState(); } private void updateRadioButtonState(){ String pref_locale = mPreferences.getString("pref_locale", ""); if(pref_locale.equalsIgnoreCase("eu")){ rbPreferredLocaleSelector.check(R.id.rbDeviceEu); formerSelectedRadioButton = R.id.rbDeviceEu; }else if(pref_locale.equalsIgnoreCase("gl")){ rbPreferredLocaleSelector.check(R.id.rbDeviceGl); formerSelectedRadioButton = R.id.rbDeviceGl; }else{ rbPreferredLocaleSelector.check(R.id.rbDeviceLang); formerSelectedRadioButton = R.id.rbDeviceLang; } } public void onRadioButtonClicked(View view){ final boolean checked = ((RadioButton) view).isChecked(); final int selectedRadioButtonId = view.getId(); //Toast.makeText(getApplicationContext(), getString(R.string.language_restart), Toast.LENGTH_LONG).show(); DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: switch(selectedRadioButtonId) { case R.id.rbDeviceEu: if (checked){ mPrefEditor.putString("pref_locale", "eu"); mPrefEditor.commit(); } break; case R.id.rbDeviceGl: if (checked){ mPrefEditor.putString("pref_locale", "gl"); mPrefEditor.commit(); } break; default: if(checked){ mPrefEditor.putString("pref_locale", ""); mPrefEditor.commit(); } break; } formerSelectedRadioButton = selectedRadioButtonId; mApp.applyLocaleSettings(); mApp.restart(); break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked rbPreferredLocaleSelector.check(formerSelectedRadioButton); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.language_restart)) .setPositiveButton(getString(R.string.restart_now), dialogClickListener) .setNegativeButton(getString(R.string.cancel), dialogClickListener).show(); } @Override protected void onResume() { super.onResume(); mHelper = new ActivityHelper(this); mUiHelper.onResume(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mUiHelper.onSaveInstanceState(outState); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Log.d(TAG, "onActivityResult " + requestCode + ":" + resultCode + ":" + data); mUiHelper.onActivityResult(requestCode, resultCode, data); if ((requestCode == REQUEST_CODE_ADD_ACCOUNT) && (resultCode == Activity.RESULT_OK)) { // User finished adding his account signIn(LoginType.GOOGLE, mGoogleUsername, null); } else if ((requestCode == REQUEST_CODE_LOGIN) && (resultCode == Activity.RESULT_OK)) { // User finished entering his password signIn(LoginType.GOOGLE, mGoogleUsername, null); } } @Override public void onPause() { super.onPause(); mUiHelper.onPause(); } @Override public void onDestroy() { super.onDestroy(); mUiHelper.onDestroy(); } private void toggle() { LoginType loginType = LoginType.valueOf(mPreferences.getString("login_type", LoginType.PASSWORD.toString())); String username = mPreferences.getString("username", null); if (username == null) { mSignInLayout.setVisibility(View.VISIBLE); mSignOutLayout.setVisibility(View.GONE); mFacebookLoginButton.setVisibility(View.VISIBLE); mFBSeparator.setVisibility(View.VISIBLE); mGoogleLogin.setVisibility(View.VISIBLE); } else { mSignInLayout.setVisibility(View.GONE); mSignOutLayout.setVisibility(View.VISIBLE); mSignOutLabel.setText(String.format(getString(R.string.signed_in_as), username)); if (loginType == LoginType.FACEBOOK) { mSignOutButton.setVisibility(View.GONE); mFacebookLoginButton.setVisibility(View.VISIBLE); mFBSeparator.setVisibility(View.VISIBLE); mGoogleLogin.setVisibility(View.GONE); } else { mSignOutButton.setVisibility(View.VISIBLE); mFacebookLoginButton.setVisibility(View.GONE); mFBSeparator.setVisibility(View.GONE); mGoogleLogin.setVisibility(View.GONE); } } } private class SignInTask extends AsyncTask<String, Void, String> { private String mUsername; private String mPassword; private LoginType mLoginType; private Activity mActivity; private boolean mInvalidated; public SignInTask(Activity activity) { mActivity = activity; } protected String doInBackground(String... pieces) { mUsername = pieces[0]; mPassword = pieces[1]; mLoginType = LoginType.valueOf(pieces[2]); if (pieces.length > 3) { mInvalidated = (pieces[3] == "invalidated"); } else { mInvalidated = false; } // Log.d(TAG, String.format("Verifying credentials for %s login with %s:%s", // mLoginType.toString(), (mUsername != null ? mUsername : "<null>"), mPassword)); // TODO - Support for OAuth2 login with Google/Facebook if (mLoginType == LoginType.PASSWORD) { String result = INaturalistService.verifyCredentials(mUsername, mPassword); if (result != null) { mUsername = result; return "true"; } else { return null; } } else { String[] results = INaturalistService.verifyCredentials(mPassword, mLoginType); if (results == null) { return null; } // Upgrade from FB/Google email to iNat username mUsername = results[1]; return results[0]; } } protected void onPreExecute() { mProgressDialog = ProgressDialog.show(mActivity, "", getString(R.string.signing_in), true); } protected void onPostExecute(String result) { try { mProgressDialog.dismiss(); } catch (Exception exc) { // Ignore } if (result != null) { Toast.makeText(mActivity, getString(R.string.signed_in), Toast.LENGTH_SHORT).show(); } else { if (mLoginType == LoginType.FACEBOOK) { // Login failed - need to sign-out of Facebook as well Session session = Session.getActiveSession(); session.closeAndClearTokenInformation(); } else if (mLoginType == LoginType.GOOGLE && !mInvalidated) { AccountManager.get(mActivity).invalidateAuthToken("com.google", mPassword); INaturalistPrefsActivity a = (INaturalistPrefsActivity) mActivity; a.signIn(LoginType.GOOGLE, mUsername, null, true); return; } mHelper.alert(getString(R.string.signed_in_failed)); return; } mPrefEditor.putString("username", mUsername); String credentials; if (mLoginType == LoginType.PASSWORD) { credentials = Base64.encodeToString( (mUsername + ":" + mPassword).getBytes(), Base64.URL_SAFE|Base64.NO_WRAP ); } else { credentials = result; // Access token } mPrefEditor.putString("credentials", credentials); mPrefEditor.putString("password", mPassword); mPrefEditor.putString("login_type", mLoginType.toString()); mPrefEditor.commit(); toggle(); // Run the first observation sync Intent serviceIntent = new Intent(INaturalistService.ACTION_FIRST_SYNC, null, INaturalistPrefsActivity.this, INaturalistService.class); startService(serviceIntent); } } public void signIn(LoginType loginType, String username, String password) { signIn(loginType, username, password, false); } public void signIn(LoginType loginType, String username, String password, boolean invalidated) { boolean googleLogin = (loginType == LoginType.GOOGLE); if (googleLogin) { String googleUsername = null; Account account = null; // See if given account exists Account[] availableAccounts = AccountManager.get(this).getAccountsByType("com.google"); boolean accountFound = false; if (username != null) { googleUsername = username.toLowerCase(); for (int i = 0; i < availableAccounts.length; i++) { if (availableAccounts[i].name.equalsIgnoreCase(googleUsername)) { // Found the account // Log.d(TAG, "googleUsername: " + googleUsername); accountFound = true; break; } } } if (availableAccounts.length > 0) { accountFound = true; account = availableAccounts[0]; } else if (googleUsername == null) { askForGoogleEmail(); return; } else { // Redirect user to add account dialog mGoogleUsername = googleUsername; startActivityForResult(new Intent(Settings.ACTION_ADD_ACCOUNT), REQUEST_CODE_ADD_ACCOUNT); return; } // Google account login final String boundUsername = googleUsername; final String boundInvalidated = invalidated ? "invalidated" : null; final AccountManagerCallback<Bundle> cb = new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { final Bundle result = future.getResult(); final String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME); final String authToken = result.getString(AccountManager.KEY_AUTHTOKEN); final Intent authIntent = result.getParcelable(AccountManager.KEY_INTENT); if (accountName != null && authToken != null) { // Log.d(TAG, String.format("Token: %s", authToken)); new SignInTask(INaturalistPrefsActivity.this).execute(boundUsername, authToken, LoginType.GOOGLE.toString(), boundInvalidated); } else if (authIntent != null) { int flags = authIntent.getFlags(); flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; authIntent.setFlags(flags); INaturalistPrefsActivity.this.startActivityForResult(authIntent, REQUEST_CODE_LOGIN); } else { Log.e(TAG, "AccountManager was unable to obtain an authToken."); } } catch (Exception e) { Log.e(TAG, "Auth Error", e); } } }; if (account == null) { account = new Account(googleUsername, "com.google"); } AccountManager.get(this).getAuthToken(account, GOOGLE_AUTH_TOKEN_TYPE, null, INaturalistPrefsActivity.this, cb, null); } else { // "Regular" login new SignInTask(this).execute(username, password, LoginType.PASSWORD.toString()); } } private void signOut() { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String login = prefs.getString("username", null); mPrefEditor.remove("username"); mPrefEditor.remove("credentials"); mPrefEditor.remove("password"); mPrefEditor.remove("login_type"); mPrefEditor.remove("last_sync_time"); mPrefEditor.commit(); int count1 = getContentResolver().delete(Observation.CONTENT_URI, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL)) AND user_login = '" + login + "'", null); int count2 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL))", null); int count3 = getContentResolver().delete(ProjectObservation.CONTENT_URI, "(is_new = 1) OR (is_deleted = 1)", null); int count4 = getContentResolver().delete(ProjectFieldValue.CONTENT_URI, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL))", null); Log.d(TAG, String.format("Deleted %d / %d / %d/ %d unsynced observations", count1, count2, count3, count4)); toggle(); } }
package org.openbmap.unifiedNlp.Geocoder; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.location.Location; import android.net.wifi.ScanResult; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import org.openbmap.unifiedNlp.Preferences; import org.openbmap.unifiedNlp.services.Cell; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class OfflineProvider extends AbstractProvider implements ILocationProvider { // Default accuracy for wifi results (in meter) public static final int DEFAULT_WIFI_ACCURACY = 30; // Default accuracy for cell results (in meter) public static final int DEFAULT_CELL_ACCURACY = 3000; private static final String TAG = OfflineProvider.class.getName(); private ILocationCallback mListener; /** * Keeps the SharedPreferences. */ private SharedPreferences prefs = null; /** * Database containing well-known wifis from openbmap.org. */ private SQLiteDatabase mCatalog; public OfflineProvider(final Context ctx, final ILocationCallback listener) { mListener = listener; prefs = PreferenceManager.getDefaultSharedPreferences(ctx); // Open catalog database String path = prefs.getString(Preferences.KEY_DATA_FOLDER, ctx.getExternalFilesDir(null).getAbsolutePath()) + File.separator + prefs.getString(Preferences.KEY_OFFLINE_CATALOG_FILE, Preferences.VAL_CATALOG_FILE); mCatalog = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY); } @SuppressWarnings("unchecked") @Override public void getLocation(final List<ScanResult> wifiList, final List<Cell> cellsList) { LocationQueryParams params = new LocationQueryParams(wifiList, cellsList); new AsyncTask<LocationQueryParams, Void, Location>() { private static final int WIFIS_MASK = 0x0f; // mask for wifi flags private static final int CELLS_MASK = 0xf0; // mask for cell flags private static final int EMPTY_WIFIS_QUERY = 0x01; // no wifis were passed private static final int EMPTY_CELLS_QUERY = 0x10; // no cells were passed private static final int WIFIS_NOT_FOUND = 0x02; // none of the wifis in the list was found in the database private static final int CELLS_NOT_FOUND = 0x20; // none of the cells in the list was found in the database private static final int WIFIS_MATCH = 0x04; // matching wifis were found private static final int CELLS_MATCH = 0x40; // matching cells were found private static final int CELLS_DATABASE_NA = 0x80; // the database contains no cell data private int state; @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @SuppressLint("DefaultLocale") @Override protected Location doInBackground(LocationQueryParams... params) { long now = SystemClock.elapsedRealtime(); if (params == null) { throw new IllegalArgumentException("Wifi list was null"); } if (prefs.getString(Preferences.KEY_OFFLINE_CATALOG_FILE, Preferences.CATALOG_NONE).equals(Preferences.CATALOG_NONE)) { throw new IllegalArgumentException("No catalog database was specified"); } List<ScanResult> wifiListRaw = ((LocationQueryParams) params[0]).wifiList; List<Cell> cellsListRaw = ((LocationQueryParams) params[0]).cellsList; HashMap<String, ScanResult> wifiList = new HashMap<String, ScanResult>(); List<Cell> cellsList = new ArrayList<Cell>(); HashMap<String, Location> locations = new HashMap<String, Location>(); String[] resultIds = new String[0]; ArrayList<String> cellResults = new ArrayList<String>(); Location result = null; if (wifiListRaw != null) { // Generates a list of wifis from scan results for (ScanResult r : wifiListRaw) { long age = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) // determine age (elapsedRealtime is in milliseconds, timestamp is in microseconds) age = now - (r.timestamp / 1000); /* * Any filtering of scan results can be done here. Examples include: * empty or bogus BSSIDs, SSIDs with "_nomap" suffix, blacklisted wifis */ if (r.BSSID == null) Log.w(TAG, "skipping wifi with empty BSSID"); else if (r.SSID.endsWith("_nomap")) { // BSSID with _nomap suffix, user does not want it to be mapped or used for geolocation } else { if (age >= 2000) Log.w(TAG, String.format("wifi %s is stale (%d ms), using it anyway", r.BSSID, age)); // wifi is OK to use for geolocation, add it to list wifiList.put(r.BSSID.replace(":", "").toUpperCase(), r); } } Log.i(TAG, "Using " + wifiList.size() + " wifis for geolocation"); } else Log.i(TAG, "No wifis supplied for geolocation"); String[] wifiQueryArgs = wifiList.keySet().toArray(new String[0]); if (cellsListRaw != null) { for (Cell r : cellsListRaw) { Log.d(TAG, "Evaluating " + r.toString()); if ((r.mcc <= 0) || (r.mnc <= 0) || (r.area <= 0) || (r.cellId <= 0)) { Log.i(TAG, String.format("Cell %s has incomplete data, skipping", r.toString())); } else { cellsList.add(r); } } } state &= ~WIFIS_MASK & ~CELLS_MASK; if (wifiQueryArgs.length < 1) { Log.i(TAG, "Query contained no bssids"); state |= EMPTY_WIFIS_QUERY; } if (cellsList.size() == 0) { Log.w(TAG, "Query contained no cell infos"); state |= EMPTY_CELLS_QUERY; } if ((state & (EMPTY_WIFIS_QUERY | EMPTY_CELLS_QUERY)) == 0) { Cursor c; if ((state & EMPTY_WIFIS_QUERY) == 0) { Log.d(TAG, "Looking up wifis"); String whereClause = ""; for (String k : wifiQueryArgs) { if (whereClause.length() > 1) { whereClause += " OR "; } whereClause += " bssid = ?"; } final String wifiSql = "SELECT latitude, longitude, bssid FROM wifi_zone WHERE " + whereClause; //Log.d(TAG, sql); c = mCatalog.rawQuery(wifiSql, wifiQueryArgs); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { Location location = new Location(TAG); location.setLatitude(c.getDouble(0)); location.setLongitude(c.getDouble(1)); location.setAccuracy(0); location.setTime(System.currentTimeMillis()); Bundle b = new Bundle(); b.putString("source", "wifis"); b.putString("bssid", c.getString(2)); location.setExtras(b); locations.put(c.getString(2), location); state |= WIFIS_MATCH; } c.close(); if ((state & WIFIS_MATCH) != WIFIS_MATCH) { state |= WIFIS_NOT_FOUND; Log.i(TAG, "No known wifis found"); } } if ((state & EMPTY_CELLS_QUERY) == 0) { Log.d(TAG, "Looking up cells"); if (!haveCellTables()) { Log.w(TAG, "Cell tables not available. Check your database"); state |= CELLS_DATABASE_NA; } String whereClause = ""; List<String> cellQueryArgs = new ArrayList<String>(); for (Cell k : cellsList) { if (whereClause.length() > 1) { whereClause += " OR "; } Log.d(TAG, "Using " + k.toString()); whereClause += " (cid = ? AND mcc = ? AND mnc = ? AND area = ?)"; cellQueryArgs.add(String.valueOf(k.cellId)); cellQueryArgs.add(String.valueOf(k.mcc)); cellQueryArgs.add(String.valueOf(k.mnc)); cellQueryArgs.add(String.valueOf(k.area)); } // Ignore the cell technology for the time being, using cell technology causes problems when cell supports different protocols, e.g. // UMTS and HSUPA and HSUPA+ // final String cellSql = "SELECT AVG(latitude), AVG(longitude) FROM cell_zone WHERE cid = ? AND mcc = ? AND mnc = ? AND area = ? and technology = ?"; final String cellSql = "SELECT AVG(latitude), AVG(longitude), mcc, mnc, area, cid FROM cell_zone WHERE " + whereClause + " GROUP BY mcc, mnc, area, cid"; try { c = mCatalog.rawQuery(cellSql, cellQueryArgs.toArray(new String[0])); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { Location location = new Location(TAG); location.setLatitude(c.getDouble(0)); location.setLongitude(c.getDouble(1)); location.setAccuracy(0); // or DEFAULT_CELL_ACCURACY? location.setTime(System.currentTimeMillis()); Bundle b = new Bundle(); b.putString("source", "cells"); b.putString("cell", c.getInt(2) + "|" + c.getInt(3) + "|" + c.getInt(4) + "|" + c.getInt(5)); location.setExtras(b); locations.put(c.getInt(2) + "|" + c.getInt(3) + "|" + c.getInt(4) + "|" + c.getInt(5), location); cellResults.add(c.getInt(2) + "|" + c.getInt(3) + "|" + c.getInt(4) + "|" + c.getInt(5)); state |= CELLS_MATCH; } c.close(); if ((state & CELLS_MATCH) != CELLS_MATCH) { state |= CELLS_NOT_FOUND; Log.i(TAG, "No known cells found"); } } catch (SQLiteException e) { Log.e(TAG, "SQLiteException! Update your database!"); state |= CELLS_DATABASE_NA; } } resultIds = locations.keySet().toArray(new String[0]); if (resultIds.length == 0) { return null; } else if (resultIds.length == 1) { // We have just one location, pass it result = locations.get(resultIds[0]); if (resultIds[0].contains("|")) // the only result is a cell, assume default result.setAccuracy(DEFAULT_CELL_ACCURACY); else // the only result is a wifi, estimate accuracy based on RSSI result.setAccuracy(getWifiRxDist(wifiList.get(resultIds[0]).level) / 10); Bundle b = new Bundle(); b.putString("source", "wifis"); b.putStringArrayList("bssids", new ArrayList<String>(Arrays.asList(wifiQueryArgs))); result.setExtras(b); return result; } else { for (int i = 0; i < resultIds.length; i++) { // for now, assume static speed (20 m/s = 72 km/h) // TODO get a better speed estimate final float speed = 20.0f; // RSSI-based distance float rxdist = (resultIds[i].contains("|")) ? DEFAULT_CELL_ACCURACY * 10 : getWifiRxDist(wifiList.get(resultIds[i]).level) ; // distance penalty for stale wifis (supported only on Jellybean MR1 and higher) // for cells this value is always zero (cell scans are always current) float ageBasedDist = 0.0f; // penalize stale entries (wifis only, supported only on Jellybean MR1 and higher) if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) && !resultIds[i].contains("|")) { // elapsedRealtime is in milliseconds, timestamp is in microseconds ageBasedDist = (now - (wifiList.get(resultIds[i]).timestamp / 1000)) * speed / 1000; } for (int j = i + 1; j < resultIds.length; j++) { float[] distResults = new float[1]; float jAgeBasedDist = 0.0f; Location.distanceBetween(locations.get(resultIds[i]).getLatitude(), locations.get(resultIds[i]).getLongitude(), locations.get(resultIds[j]).getLatitude(), locations.get(resultIds[j]).getLongitude(), distResults); // subtract distance between device and each transmitter to get "disagreement" if (resultIds[j].contains("|")) distResults[0] -= rxdist + DEFAULT_CELL_ACCURACY * 10; else { distResults[0] -= rxdist + getWifiRxDist(wifiList.get(resultIds[j]).level); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) jAgeBasedDist = (now - (wifiList.get(resultIds[j]).timestamp / 1000)) * speed / 1000; } /* * Consider the distance traveled between the two locations. This avoids * penalizing two locations that differ in time. */ distResults[0] -= Math.abs(ageBasedDist - jAgeBasedDist); // apply penalty only if disagreement is greater than zero if (distResults[0] > 0) { // take the square of the distance distResults[0] *= distResults[0]; // add to the penalty count for both locations locations.get(resultIds[i]).setAccuracy(locations.get(resultIds[i]).getAccuracy() + distResults[0]); locations.get(resultIds[j]).setAccuracy(locations.get(resultIds[j]).getAccuracy() + distResults[0]); } } locations.get(resultIds[i]).setAccuracy(locations.get(resultIds[i]).getAccuracy() / (resultIds.length - 1)); // correct distance from transmitter to a realistic value rxdist /= 7; Log.v(TAG, String.format("%s: disagreement = %.5f, rxdist = %.5f, age = %d ms, ageBasedDist = %.5f", resultIds[i], Math.sqrt(locations.get(resultIds[i]).getAccuracy()), rxdist, now - (wifiList.get(resultIds[i]).timestamp / 1000), ageBasedDist)); // add additional error sources: RSSI-based (distance from transmitter) and age-based (distance traveled since) locations.get(resultIds[i]).setAccuracy(locations.get(resultIds[i]).getAccuracy() + rxdist * rxdist + ageBasedDist * ageBasedDist); if (i == 0) result = locations.get(resultIds[i]); else { float k = result.getAccuracy() / (result.getAccuracy() + locations.get(resultIds[i]).getAccuracy()); result.setLatitude((1 - k) * result.getLatitude() + k * locations.get(resultIds[i]).getLatitude()); result.setLongitude((1 - k) * result.getLongitude() + k * locations.get(resultIds[i]).getLongitude()); result.setAccuracy((1 - k) * result.getAccuracy()); } } // finally, set actual accuracy (square root of the interim value) result.setAccuracy((float) Math.sqrt(result.getAccuracy())); // FIXME what do we want to reflect in results? transmitters we tried to look up, or only those which returned a location? Bundle b = new Bundle(); if ((state & (WIFIS_MATCH | CELLS_MATCH)) == (WIFIS_MATCH | CELLS_MATCH)) b.putString("source", "cells; wifis"); else if ((state & WIFIS_MATCH) != 0) b.putString("source", "wifis"); else if ((state & CELLS_MATCH) != 0) b.putString("source", "cells"); if ((state & WIFIS_MATCH) != 0) b.putStringArrayList("bssids", new ArrayList<String>(Arrays.asList(wifiQueryArgs))); if ((state & CELLS_MATCH) != 0) b.putStringArrayList("cells", cellResults); result.setExtras(b); return result; } } else { return null; } } /** * Check whether cell zone table exists */ private boolean haveCellTables() { final String sql = "SELECT count(name) FROM sqlite_master WHERE type='table' AND name='cell_zone'"; final Cursor c = mCatalog.rawQuery(sql, null); c.moveToFirst(); if (!c.isAfterLast()) { if (c.getLong(0) == 0) { c.close(); return false; } } c.close(); return true; } @Override protected void onPostExecute(Location result) { if (result == null) { Log.w(TAG, "Location was null"); return; } if (plausibleLocationUpdate(result)) { Log.d(TAG, "Broadcasting location" + result.toString()); setLastLocation(result); setLastFix(System.currentTimeMillis()); mListener.onLocationReceived(result); } } }.execute(params); } /** * @brief Obtains a wifi receiver's maximum distance from the transmitter based on signal strength. * * Distance is calculated based on the assumption that the signal level is -100 dBm at a distance of * 1000 m, and that the signal level will increase by 6 dBm as the distance is halved. This model * does not consider additional signal degradation caused by obstacles, thus real distances will * almost always be lower than the result of this function. This "worst-case" approach is * intentional and consumers should apply any corrections they deem appropriate. * * @param rxlev Received signal strength (RSSI) in dBm * * @return Upper boundary for the distance between transmitter and receiver in meters */ private static float getWifiRxDist(int rxlev) { final int refRxlev = -100; final float refDist = 1000.0f; float factor = (float) Math.pow(2.0f, 6.0f / (refRxlev - rxlev)); return refDist * factor; } private static class LocationQueryParams { List<ScanResult> wifiList; List<Cell> cellsList; LocationQueryParams(List<ScanResult> wifiList, List<Cell> cellsList) { this.wifiList = wifiList; this.cellsList = cellsList; } } }
package com.s3auth.relay; import com.s3auth.hosts.Hosts; import java.net.Socket; import java.util.concurrent.BlockingQueue; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Single FTP processing thread. * * <p>The class is responsible for getting a new socket from a blocking * queue, processing it, and closing the socket. The class is instantiated * by {@link FtpFacade} and is executed by Services Executor routinely. * * <p>The class is thread-safe. * * @author Felipe Pina (felipe.pina@gmail.com) * @version $Id$ * @since 0.0.1 * @see FtpFacade * @todo #213:30min Implement authentication based on the USER and PASS * commands. * @todo #213:30min Implement relay functionality to fetch resource upon * receival of the RETR command with valid authorization. Return an error * in case of other commands (unsupported for now). Remove PMD suppressions * from fields 'sockets' and 'hosts'. */ @ToString @EqualsAndHashCode(of = { "hosts", "sockets" }) final class FtpThread { /** * Queue of sockets to get from. */ @SuppressWarnings({ "PMD.SingularField", "PMD.UnusedPrivateField" }) private final transient BlockingQueue<Socket> sockets; /** * Hosts to work with. */ @SuppressWarnings({ "PMD.SingularField", "PMD.UnusedPrivateField" }) private final transient Hosts hosts; /** * Public ctor. * @param sckts Sockets to read from * @param hsts Hosts */ FtpThread(@NotNull final BlockingQueue<Socket> sckts, @NotNull final Hosts hsts) { this.sockets = sckts; this.hosts = hsts; } /** * Dispatch one request from the encapsulated queue. * @return Amount of bytes sent to socket * @throws InterruptedException If interrupted while waiting for the queue */ public long dispatch() throws InterruptedException { return 0L; } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc1073.robot17.commands; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc1073.robot17.Logger; import org.usfirst.frc1073.robot17.Robot; public class DriveInches extends Command { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS private double m_inches; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS private final double SPEED = .5; private final double ANG_MOD_VAL = 20; private final double ENC_MOD_VAL = .005; private double currentLeft,currentRight,currentSpeed,destination,currentAvg,currentAng,currentMod,isNeg; private double encDif; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR public DriveInches(double inches) { // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING m_inches = inches; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING destination = m_inches*1440; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.driveTrain); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { Robot.driveTrain.setLeftPos(0); Robot.driveTrain.setRightPos(0); Robot.driveTrain.resetGyro(); if(destination < 0) isNeg = -1; else isNeg = 1; } // Called repeatedly when this Command is scheduled to run protected void execute() { currentLeft = Robot.driveTrain.getLeftPos()*Math.PI*3.9; currentRight = Robot.driveTrain.getRightPos()*Math.PI*3.9; currentAvg = (currentLeft+currentRight)/2; currentAng = Robot.driveTrain.getDegrees(); currentMod = currentAng/ANG_MOD_VAL; currentSpeed = isNeg*-1*Math.abs((currentAvg/destination)-SPEED) + SPEED; if(isNeg > 0 && currentSpeed <= .25) currentSpeed = .25; if(isNeg < 0 && currentSpeed >= -.25) currentSpeed = -.25; Logger.setLog("Left pos: " + Double.toString(Robot.driveTrain.getLeftPos())); Logger.setLog("Right pos: " + Double.toString(Robot.driveTrain.getRightPos()*-1)); Logger.setLog("Robot heading: " + Double.toString(Robot.driveTrain.getDegrees())); encDif = Robot.driveTrain.getLeftPos() - Robot.driveTrain.getRightPos(); encDif *= ENC_MOD_VAL; //Robot.driveTrain.basicDrive(-1*(currentSpeed-currentMod), -1*(currentSpeed+currentMod)); Robot.driveTrain.basicDrive(-1*(currentSpeed-encDif), -1*(currentSpeed+encDif)); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { if((currentLeft+currentRight)/2 >= destination) return true; else return false; } // Called once after isFinished returns true protected void end() { Robot.driveTrain.basicDrive(0, 0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { Robot.driveTrain.basicDrive(0, 0); } }
//FILE: MMStudioMainFrame.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // Modifications by Arthur Edelstein, Nico Stuurman // 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. //CVS: $Id$ package org.micromanager; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.Line; import ij.gui.Roi; import ij.process.ImageProcessor; import ij.process.ImageStatistics; import ij.process.ShortProcessor; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; import java.util.Timer; import java.util.TimerTask; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SpringLayout; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.LineBorder; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.MMCoreJ; import mmcorej.MMEventCallback; import mmcorej.Metadata; import mmcorej.StrVector; import org.json.JSONObject; import org.micromanager.acquisition.AcquisitionManager; import org.micromanager.acquisition.MMImageCache; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.Autofocus; import org.micromanager.api.DeviceControlGUI; import org.micromanager.api.MMPlugin; import org.micromanager.api.ScriptInterface; import org.micromanager.api.MMListenerInterface; import org.micromanager.conf.ConfiguratorDlg; import org.micromanager.conf.MMConfigFileException; import org.micromanager.conf.MicroscopeModel; import org.micromanager.graph.ContrastPanel; import org.micromanager.graph.GraphData; import org.micromanager.graph.GraphFrame; import org.micromanager.navigation.CenterAndDragListener; import org.micromanager.navigation.PositionList; import org.micromanager.navigation.XYZKeyListener; import org.micromanager.navigation.ZWheelListener; import org.micromanager.utils.AutofocusManager; import org.micromanager.utils.CfgFileFilter; import org.micromanager.utils.ContrastSettings; import org.micromanager.utils.GUIColors; import org.micromanager.utils.GUIUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMImageWindow; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.TextUtils; import org.micromanager.utils.WaitDialog; import bsh.EvalError; import bsh.Interpreter; import com.swtdesigner.SwingResourceManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.process.ColorProcessor; import java.awt.Cursor; import java.awt.FileDialog; import java.awt.Graphics; import java.awt.image.DirectColorModel; import java.util.Collections; import mmcorej.TaggedImage; import org.micromanager.acquisition.AcquisitionVirtualStack; import org.micromanager.api.AcquisitionInterface; import org.micromanager.acquisition.AcquisitionWrapperEngine; import org.micromanager.acquisition.MetadataPanel; import org.micromanager.acquisition.engine.SequenceSettings; import org.micromanager.api.ImageFocusListener; import org.micromanager.utils.ReportingUtils; /* * Main panel and application class for the MMStudio. */ public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface { private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4"; private static final String VERSION = "1.4.0 "; private static final long serialVersionUID = 3556500289598574541L; private static final String MAIN_FRAME_X = "x"; private static final String MAIN_FRAME_Y = "y"; private static final String MAIN_FRAME_WIDTH = "width"; private static final String MAIN_FRAME_HEIGHT = "height"; private static final String MAIN_EXPOSURE = "exposure"; private static final String SYSTEM_CONFIG_FILE = "sysconfig_file"; private static final String MAIN_STRETCH_CONTRAST = "stretch_contrast"; private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN"; private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX"; private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN"; private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX"; private static final String OPEN_ACQ_DIR = "openDataDir"; private static final String SCRIPT_CORE_OBJECT = "mmc"; private static final String SCRIPT_ACQENG_OBJECT = "acq"; private static final String SCRIPT_GUI_OBJECT = "gui"; private static final String AUTOFOCUS_DEVICE = "autofocus_device"; private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage"; // cfg file saving private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4} // GUI components private JComboBox comboBinning_; private JComboBox shutterComboBox_; private JTextField textFieldExp_; private SpringLayout springLayout_; private JLabel labelImageDimensions_; private JToggleButton toggleButtonLive_; private JCheckBox autoShutterCheckBox_; private boolean autoShutterOrg_; private boolean shutterOrg_; private MMOptions options_; private boolean runsAsPlugin_; private JCheckBoxMenuItem centerAndDragMenuItem_; private JButton buttonSnap_; private JButton buttonAutofocus_; private JButton buttonAutofocusTools_; private JToggleButton toggleButtonShutter_; private GUIColors guiColors_; private GraphFrame profileWin_; private PropertyEditor propertyBrowser_; private CalibrationListDlg calibrationListDlg_; private AcqControlDlg acqControlWin_; private ArrayList<PluginItem> plugins_; private List<MMListenerInterface> MMListeners_ = (List<MMListenerInterface>) Collections.synchronizedList(new ArrayList<MMListenerInterface>()); private List<Component> MMFrames_ = (List<Component>) Collections.synchronizedList(new ArrayList<Component>()); private AutofocusManager afMgr_; private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg"; private ArrayList<String> MRUConfigFiles_; private static final int maxMRUCfgs_ = 5; private String sysConfigFile_; private String startupScriptFile_; private String sysStateFile_ = "MMSystemState.cfg"; private ConfigGroupPad configPad_; private ContrastPanel contrastPanel_; // Timer interval - image display interval private double liveModeInterval_ = 40; private Timer liveModeTimer_; private LiveModeTimerTask liveModeTimerTask_; private GraphData lineProfileData_; private Object img_; // labels for standard devices private String cameraLabel_; private String zStageLabel_; private String shutterLabel_; private String xyStageLabel_; // applications settings private Preferences mainPrefs_; private Preferences systemPrefs_; // MMcore private CMMCore core_; private AcquisitionEngine engine_; private PositionList posList_; private PositionListDlg posListDlg_; private String openAcqDirectory_ = ""; private boolean running_; private boolean liveRunning_ = false; private boolean configChanged_ = false; private StrVector shutters_ = null; private JButton saveConfigButton_; private ScriptPanel scriptPanel_; //private SplitView splitView_; private CenterAndDragListener centerAndDragListener_; private ZWheelListener zWheelListener_; private XYZKeyListener xyzKeyListener_; private AcquisitionManager acqMgr_; private static MMImageWindow imageWin_; private int snapCount_ = -1; private boolean liveModeSuspended_; public Font defaultScriptFont_ = null; // Our instance private MMStudioMainFrame gui_; // Callback private CoreEventCallback cb_; private JMenuBar menuBar_; private ConfigPadButtonPanel configPadButtonPanel_; private boolean virtual_ = false; private final JMenu switchConfigurationMenu_; private final MetadataPanel metadataPanel_; public ImageWindow getImageWin() { return imageWin_; } public static MMImageWindow getLiveWin() { return imageWin_; } private void updateSwitchConfigurationMenu() { switchConfigurationMenu_.removeAll(); for (final String configFile : MRUConfigFiles_) { if (! configFile.equals(sysConfigFile_)) { JMenuItem configMenuItem = new JMenuItem(); configMenuItem.setText(configFile); configMenuItem.addActionListener(new ActionListener() { String theConfigFile = configFile; public void actionPerformed(ActionEvent e) { sysConfigFile_ = theConfigFile; loadSystemConfiguration(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); } }); switchConfigurationMenu_.add(configMenuItem); } } } /** * Allows MMListeners to register themselves */ public void addMMListener(MMListenerInterface newL) { if (MMListeners_.contains(newL)) return; MMListeners_.add(newL); } /** * Allows MMListeners to remove themselves */ public void removeMMListener(MMListenerInterface oldL) { if (!MMListeners_.contains(oldL)) return; MMListeners_.remove(oldL); } /** * Lets JComponents register themselves so that their background can be * manipulated */ public void addMMBackgroundListener(Component comp) { if (MMFrames_.contains(comp)) return; MMFrames_.add(comp); } /** * Lets JComponents remove themselves from the list whose background gets * changes */ public void removeMMBackgroundListener(Component comp) { if (!MMFrames_.contains(comp)) return; MMFrames_.remove(comp); } public void setAcquisitionEngine(String acqName, AcquisitionEngine eng) { this.acqMgr_.setAcquisitionEngine(acqName, eng); } public void updateContrast(ImagePlus iplus) { contrastPanel_.updateContrast(iplus); } public void setAcquisitionCache(String acqName, MMImageCache imageCache) { this.acqMgr_.setAcquisitionCache(acqName, imageCache); } public void runBurstAcquisition() throws MMScriptException { throw new UnsupportedOperationException("Not supported yet."); } public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException { throw new UnsupportedOperationException("Not supported yet."); } public void runBurstAcquisition(int nr) throws MMScriptException { throw new UnsupportedOperationException("Not supported yet."); } public void startBurstAcquisition() throws MMScriptException { throw new UnsupportedOperationException("Not supported yet."); } public boolean isBurstAcquisitionRunning() throws MMScriptException { throw new UnsupportedOperationException("Not supported yet."); } /** * Callback to update GUI when a change happens in the MMCore. */ public class CoreEventCallback extends MMEventCallback { public CoreEventCallback() { super(); } @Override public void onPropertiesChanged() { // TODO: remove test once acquisition engine is fully multithreaded if (engine_ != null && engine_.isAcquisitionRunning()) { core_.logMessage("Notification from MMCore ignored because acquistion is running!"); } else { updateGUI(true); // update all registered listeners for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.propertiesChangedAlert(); } core_.logMessage("Notification from MMCore!"); } } @Override public void onPropertyChanged(String deviceName, String propName, String propValue) { core_.logMessage("Notification for Device: " + deviceName + " Property: " + propName + " changed to value: " + propValue); // update all registered listeners for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.propertyChangedAlert(deviceName, propName, propValue); } } @Override public void onConfigGroupChanged(String groupName, String newConfig) { try { configPad_.refreshGroup(groupName, newConfig); } catch (Exception e) { } } @Override public void onPixelSizeChanged(double newPixelSizeUm) { updatePixSizeUm (newPixelSizeUm); } @Override public void onStagePositionChanged(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) updateZPos(pos); } @Override public void onStagePositionChangedRelative(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) updateZPosRelative(pos); } @Override public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) updateXYPos(xPos, yPos); } @Override public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) updateXYPosRelative(xPos, yPos); } } private class PluginItem { public Class<?> pluginClass = null; public String menuItem = "undefined"; public MMPlugin plugin = null; public String className = ""; public void instantiate() { try { if (plugin == null) { plugin = (MMPlugin) pluginClass.newInstance(); } } catch (InstantiationException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } plugin.setApp(MMStudioMainFrame.this); } } /* * Simple class used to cache static info */ private class StaticInfo { public long width_; public long height_; public long bytesPerPixel_; public long imageBitDepth_; public double pixSizeUm_; public double zPos_; public double x_; public double y_; } private StaticInfo staticInfo_ = new StaticInfo(); /** * Main procedure for stand alone operation. */ public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); MMStudioMainFrame frame = new MMStudioMainFrame(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } catch (Throwable e) { ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit."); System.exit(1); } } public MMStudioMainFrame(boolean pluginStatus) { super(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { ReportingUtils.showError(e, "An uncaught exception was thrown in thread " + t.getName() + "."); } }); options_ = new MMOptions(); options_.loadSettings(); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem>(); gui_ = this; runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; // !!! contrastSettings8_ = new ContrastSettings(); // contrastSettings16_ = new ContrastSettings(); acqMgr_ = new AcquisitionManager(); sysConfigFile_ = new String(System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME); if (options_.startupScript.length() > 0) { startupScriptFile_ = new String(System.getProperty("user.dir") + "/" + options_.startupScript); } else { startupScriptFile_ = ""; } ReportingUtils.SetContainingFrame(gui_); // set the location for app preferences mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); systemPrefs_ = mainPrefs_; // check system preferences try { Preferences p = Preferences.systemNodeForPackage(this.getClass()); if (null != p) { // if we can not write to the systemPrefs, use AppPrefs instead if (JavaUtils.backingStoreAvailable(p)) { systemPrefs_ = p; } } } catch (Exception e) { ReportingUtils.logError(e); } // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!userReg) { boolean systemReg = systemPrefs_.getBoolean( RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(systemPrefs_); dlg.setVisible(true); } } liveModeTimer_ = new Timer(); // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems // with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580); int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 451); boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); setBounds(x, y, width, height); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); springLayout_ = new SpringLayout(); getContentPane().setLayout(springLayout_); setTitle(MICRO_MANAGER_TITLE); setBackground(guiColors_.background.get((options_.displayBackground))); // Snap button buttonSnap_ = new JButton(); buttonSnap_.setIconTextGap(6); buttonSnap_.setText("Snap"); buttonSnap_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera.png")); buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonSnap_.setToolTipText("Snap single image"); buttonSnap_.setMaximumSize(new Dimension(0, 0)); buttonSnap_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSnap(); } }); getContentPane().add(buttonSnap_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonSnap_, 4, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonSnap_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonSnap_, 7, SpringLayout.WEST, getContentPane()); // Initialize // Exposure field final JLabel label_1 = new JLabel(); label_1.setFont(new Font("Arial", Font.PLAIN, 10)); label_1.setText("Exposure [ms]"); getContentPane().add(label_1); springLayout_.putConstraint(SpringLayout.EAST, label_1, 198, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, label_1, 111, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, label_1, 39, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, label_1, 23, SpringLayout.NORTH, getContentPane()); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent fe) { setExposure(); } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setExposure(); } }); getContentPane().add(textFieldExp_); springLayout_.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, textFieldExp_, 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, textFieldExp_, 276, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, textFieldExp_, 203, SpringLayout.WEST, getContentPane()); // Live button toggleButtonLive_ = new JToggleButton(); toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2)); toggleButtonLive_.setIconTextGap(1); toggleButtonLive_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setIconTextGap(6); toggleButtonLive_.setToolTipText("Continuous live view"); toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10)); toggleButtonLive_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!IsLiveModeOn()) { // Display interval for Live Mode changes as well setLiveModeInterval(); } enableLiveMode(!IsLiveModeOn()); } }); toggleButtonLive_.setText("Live"); getContentPane().add(toggleButtonLive_); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7, SpringLayout.WEST, getContentPane()); // Acquire button JButton acquireButton = new JButton(); acquireButton.setMargin(new Insets(2, 2, 2, 2)); acquireButton.setIconTextGap(1); acquireButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/snapAppend.png")); acquireButton.setIconTextGap(6); acquireButton.setToolTipText("Acquire single frame"); acquireButton.setFont(new Font("Arial", Font.PLAIN, 10)); acquireButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { snapAndAddToImage5D(null); } }); acquireButton.setText("Acquire"); getContentPane().add(acquireButton); springLayout_.putConstraint(SpringLayout.SOUTH, acquireButton, 69, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, acquireButton, 48, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, acquireButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, acquireButton, 7, SpringLayout.WEST, getContentPane()); // Shutter button toggleButtonShutter_ = new JToggleButton(); toggleButtonShutter_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { try { if (toggleButtonShutter_.isSelected()) { setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { ReportingUtils.showError(e1); } } }); toggleButtonShutter_.setToolTipText("Open/close the shutter"); toggleButtonShutter_.setIconTextGap(6); toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonShutter_.setText("Open"); getContentPane().add(toggleButtonShutter_); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonShutter_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonShutter_, 203, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_, 138 - 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonShutter_, 117 - 21, SpringLayout.NORTH, getContentPane()); // Active shutter label final JLabel activeShutterLabel = new JLabel(); activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10)); activeShutterLabel.setText("Shutter"); getContentPane().add(activeShutterLabel); springLayout_.putConstraint(SpringLayout.SOUTH, activeShutterLabel, 108 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, activeShutterLabel, 95 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, activeShutterLabel, 160 - 2, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, activeShutterLabel, 113 - 2, SpringLayout.WEST, getContentPane()); // Active shutter Combo Box shutterComboBox_ = new JComboBox(); shutterComboBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) { core_.setShutterDevice((String) shutterComboBox_.getSelectedItem()); } } catch (Exception e) { ReportingUtils.showError(e); } return; } }); getContentPane().add(shutterComboBox_); springLayout_.putConstraint(SpringLayout.SOUTH, shutterComboBox_, 114 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, shutterComboBox_, 92 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, shutterComboBox_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, shutterComboBox_, 170, SpringLayout.WEST, getContentPane()); menuBar_ = new JMenuBar(); setJMenuBar(menuBar_); final JMenu fileMenu = new JMenu(); fileMenu.setText("File"); menuBar_.add(fileMenu); final JMenuItem openMenuItem = new JMenuItem(); openMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { new Thread() { @Override public void run() { openAcquisitionData(); } }.start(); } }); openMenuItem.setText("Open Acquisition Data..."); fileMenu.add(openMenuItem); fileMenu.addSeparator(); final JMenuItem loadState = new JMenuItem(); loadState.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadSystemState(); } }); loadState.setText("Load System State..."); fileMenu.add(loadState); final JMenuItem saveStateAs = new JMenuItem(); fileMenu.add(saveStateAs); saveStateAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveSystemState(); } }); saveStateAs.setText("Save System State As..."); fileMenu.addSeparator(); final JMenuItem exitMenuItem = new JMenuItem(); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeSequence(); } }); fileMenu.add(exitMenuItem); exitMenuItem.setText("Exit"); /* final JMenu image5dMenu = new JMenu(); image5dMenu.setText("Image5D"); menuBar_.add(image5dMenu); final JMenuItem closeAllMenuItem = new JMenuItem(); closeAllMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { WindowManager.closeAllWindows(); } }); closeAllMenuItem.setText("Close All"); image5dMenu.add(closeAllMenuItem); final JMenuItem duplicateMenuItem = new JMenuItem(); duplicateMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Duplicate_Image5D duplicate = new Duplicate_Image5D(); duplicate.run(""); } }); duplicateMenuItem.setText("Duplicate"); image5dMenu.add(duplicateMenuItem); final JMenuItem cropMenuItem = new JMenuItem(); cropMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Crop_Image5D crop = new Crop_Image5D(); crop.run(""); } }); cropMenuItem.setText("Crop"); image5dMenu.add(cropMenuItem); final JMenuItem makeMontageMenuItem = new JMenuItem(); makeMontageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Make_Montage makeMontage = new Make_Montage(); makeMontage.run(""); } }); makeMontageMenuItem.setText("Make Montage"); image5dMenu.add(makeMontageMenuItem); final JMenuItem zProjectMenuItem = new JMenuItem(); zProjectMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Z_Project projection = new Z_Project(); projection.run(""); } }); zProjectMenuItem.setText("Z Project"); image5dMenu.add(zProjectMenuItem); final JMenuItem convertToRgbMenuItem = new JMenuItem(); convertToRgbMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB(); stackToRGB.run(""); } }); convertToRgbMenuItem.setText("Copy to RGB Stack(z)"); image5dMenu.add(convertToRgbMenuItem); final JMenuItem convertToRgbtMenuItem = new JMenuItem(); convertToRgbtMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t(); stackToRGB_t.run(""); } }); convertToRgbtMenuItem.setText("Copy to RGB Stack(t)"); image5dMenu.add(convertToRgbtMenuItem); final JMenuItem convertToStackMenuItem = new JMenuItem(); convertToStackMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_Stack image5DToStack = new Image5D_to_Stack(); image5DToStack.run(""); } }); convertToStackMenuItem.setText("Copy to Stack"); image5dMenu.add(convertToStackMenuItem); final JMenuItem convertToStacksMenuItem = new JMenuItem(); convertToStacksMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks(); image5DToStacks.run(""); } }); convertToStacksMenuItem.setText("Copy to Stacks (channels)"); image5dMenu.add(convertToStacksMenuItem); final JMenuItem volumeViewerMenuItem = new JMenuItem(); volumeViewerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer(); volumeViewer.run(""); } }); volumeViewerMenuItem.setText("VolumeViewer"); image5dMenu.add(volumeViewerMenuItem); final JMenuItem splitImageMenuItem = new JMenuItem(); splitImageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Split_Image5D splitImage = new Split_Image5D(); splitImage.run(""); } }); splitImageMenuItem.setText("SplitView"); image5dMenu.add(splitImageMenuItem); */ final JMenu toolsMenu = new JMenu(); toolsMenu.setText("Tools"); menuBar_.add(toolsMenu); final JMenuItem refreshMenuItem = new JMenuItem(); refreshMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/arrow_refresh.png")); refreshMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshMenuItem.setText("Refresh GUI"); toolsMenu.add(refreshMenuItem); final JMenuItem rebuildGuiMenuItem = new JMenuItem(); rebuildGuiMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { initializeGUI(); } }); rebuildGuiMenuItem.setText("Rebuild GUI"); toolsMenu.add(rebuildGuiMenuItem); toolsMenu.addSeparator(); final JMenuItem scriptPanelMenuItem = new JMenuItem(); toolsMenu.add(scriptPanelMenuItem); scriptPanelMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createScriptPanel(); } }); scriptPanelMenuItem.setText("Script Panel..."); final JMenuItem propertyEditorMenuItem = new JMenuItem(); toolsMenu.add(propertyEditorMenuItem); propertyEditorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createPropertyEditor(); } }); propertyEditorMenuItem.setText("Device/Property Browser..."); toolsMenu.addSeparator(); final JMenuItem xyListMenuItem = new JMenuItem(); xyListMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showXYPositionList(); } }); xyListMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/application_view_list.png")); xyListMenuItem.setText("XY List..."); toolsMenu.add(xyListMenuItem); final JMenuItem acquisitionMenuItem = new JMenuItem(); acquisitionMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); acquisitionMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film.png")); acquisitionMenuItem.setText("Multi-Dimensional Acquisition..."); toolsMenu.add(acquisitionMenuItem); /* final JMenuItem splitViewMenuItem = new JMenuItem(); splitViewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { splitViewDialog(); } }); splitViewMenuItem.setText("Split View..."); toolsMenu.add(splitViewMenuItem); */ centerAndDragMenuItem_ = new JCheckBoxMenuItem(); centerAndDragMenuItem_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (centerAndDragListener_ == null) { centerAndDragListener_ = new CenterAndDragListener(core_, gui_); } if (!centerAndDragListener_.isRunning()) { centerAndDragListener_.start(); centerAndDragMenuItem_.setSelected(true); } else { centerAndDragListener_.stop(); centerAndDragMenuItem_.setSelected(false); } mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected()); } }); centerAndDragMenuItem_.setText("Mouse Moves Stage"); centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false)); toolsMenu.add(centerAndDragMenuItem_); final JMenuItem calibrationMenuItem = new JMenuItem(); toolsMenu.add(calibrationMenuItem); calibrationMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createCalibrationListDlg(); } }); calibrationMenuItem.setText("Pixel Size Calibration..."); toolsMenu.add(calibrationMenuItem); toolsMenu.addSeparator(); final JMenuItem configuratorMenuItem = new JMenuItem(); configuratorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } configChanged_ = false; } // unload all devices before starting configurator core_.reset(); GUIUtils.preventDisplayAdapterChangeExceptions(); // run Configurator ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_); configurator.setVisible(true); GUIUtils.preventDisplayAdapterChangeExceptions(); // re-initialize the system with the new configuration file sysConfigFile_ = configurator.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); GUIUtils.preventDisplayAdapterChangeExceptions(); } catch (Exception e) { ReportingUtils.showError(e); return; } } }); configuratorMenuItem.setText("Hardware Configuration Wizard..."); toolsMenu.add(configuratorMenuItem); final JMenuItem loadSystemConfigMenuItem = new JMenuItem(); toolsMenu.add(loadSystemConfigMenuItem); loadSystemConfigMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadConfiguration(); initializeGUI(); } }); loadSystemConfigMenuItem.setText("Load Hardware Configuration..."); switchConfigurationMenu_ = new JMenu(); for (int i=0; i<5; i++) { JMenuItem configItem = new JMenuItem(); configItem.setText(Integer.toString(i)); switchConfigurationMenu_.add(configItem); } switchConfigurationMenu_.setText("Switch Hardware Configuration"); toolsMenu.add(switchConfigurationMenu_); final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem(); saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); updateChannelCombos(); } }); saveConfigurationPresetsMenuItem.setText("Save Configuration Settings..."); toolsMenu.add(saveConfigurationPresetsMenuItem); toolsMenu.addSeparator(); final MMStudioMainFrame thisInstance = this; final JMenuItem optionsMenuItem = new JMenuItem(); optionsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { int oldBufsize = options_.circularBufferSizeMB; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB) { try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception exc) { ReportingUtils.showError(exc); } } } }); optionsMenuItem.setText("Options..."); toolsMenu.add(optionsMenuItem); final JLabel binningLabel = new JLabel(); binningLabel.setFont(new Font("Arial", Font.PLAIN, 10)); binningLabel.setText("Binning"); getContentPane().add(binningLabel); springLayout_.putConstraint(SpringLayout.SOUTH, binningLabel, 64, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, binningLabel, 43, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1, SpringLayout.WEST, getContentPane()); labelImageDimensions_ = new JLabel(); labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(labelImageDimensions_); springLayout_.putConstraint(SpringLayout.SOUTH, labelImageDimensions_, -5, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, labelImageDimensions_, -25, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, labelImageDimensions_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, labelImageDimensions_, 5, SpringLayout.WEST, getContentPane()); comboBinning_ = new JComboBox(); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeBinning(); } }); getContentPane().add(comboBinning_); springLayout_.putConstraint(SpringLayout.EAST, comboBinning_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, comboBinning_, 200, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, comboBinning_, 66, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, comboBinning_, 43, SpringLayout.NORTH, getContentPane()); final JLabel cameraSettingsLabel = new JLabel(); cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11)); cameraSettingsLabel.setText("Camera settings"); getContentPane().add(cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, cameraSettingsLabel, 211, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, cameraSettingsLabel, 109, SpringLayout.WEST, getContentPane()); configPad_ = new ConfigGroupPad(); configPad_.setFont(new Font("", Font.PLAIN, 10)); getContentPane().add(configPad_); springLayout_.putConstraint(SpringLayout.EAST, configPad_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPad_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPad_, 156, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPad_, 21, SpringLayout.NORTH, getContentPane()); configPadButtonPanel_ = new ConfigPadButtonPanel(); configPadButtonPanel_.setConfigPad(configPad_); configPadButtonPanel_.setGUI(this); getContentPane().add(configPadButtonPanel_); springLayout_.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, 158, SpringLayout.NORTH, getContentPane()); final JLabel stateDeviceLabel = new JLabel(); stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11)); stateDeviceLabel.setText("Configuration settings"); getContentPane().add(stateDeviceLabel); springLayout_.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0, SpringLayout.SOUTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0, SpringLayout.NORTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150, SpringLayout.WEST, configPad_); springLayout_.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0, SpringLayout.WEST, configPad_); final JButton buttonAcqSetup = new JButton(); buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2)); buttonAcqSetup.setIconTextGap(1); buttonAcqSetup.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/film.png")); buttonAcqSetup.setToolTipText("Open Acquistion dialog"); buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAcqSetup.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); buttonAcqSetup.setText("Multi-D Acq."); getContentPane().add(buttonAcqSetup); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7, SpringLayout.WEST, getContentPane()); autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { core_.setAutoShutter(autoShutterCheckBox_.isSelected()); if (shutterLabel_.length() > 0) { try { setShutterButton(core_.getShutterOpen()); } catch (Exception e1) { ReportingUtils.showError(e1); } } if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); getContentPane().add(autoShutterCheckBox_); springLayout_.putConstraint(SpringLayout.EAST, autoShutterCheckBox_, 202 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autoShutterCheckBox_, 110 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_, 141 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_, 118 - 22, SpringLayout.NORTH, getContentPane()); final JButton refreshButton = new JButton(); refreshButton.setMargin(new Insets(2, 2, 2, 2)); refreshButton.setIconTextGap(1); refreshButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_refresh.png")); refreshButton.setFont(new Font("Arial", Font.PLAIN, 10)); refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware"); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshButton.setText("Refresh"); getContentPane().add(refreshButton); springLayout_.putConstraint(SpringLayout.SOUTH, refreshButton, 113, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, refreshButton, 92, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, refreshButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, refreshButton, 7, SpringLayout.WEST, getContentPane()); // add window listeners addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { running_ = false; closeSequence(); } @Override public void windowOpened(WindowEvent e) { // initialize hardware try { core_ = new CMMCore(); } catch(UnsatisfiedLinkError ex) { ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib"); return; } ReportingUtils.setCore(core_); core_.enableDebugLog(options_.debugLogEnabled); core_.logMessage("MM Studio version: " + getVersion()); core_.logMessage(core_.getVersionInfo()); core_.logMessage(core_.getAPIVersionInfo()); core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version")); cameraLabel_ = ""; shutterLabel_ = ""; zStageLabel_ = ""; xyStageLabel_ = ""; engine_ = new AcquisitionWrapperEngine(); // register callback for MMCore notifications, this is a global // to avoid garbage collection cb_ = new CoreEventCallback(); core_.registerCallback(cb_); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception e2) { ReportingUtils.showError(e2); } MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) { engine_.setParentGUI(parent); } loadMRUConfigFiles(); if (!options_.doNotAskForConfigFile) { MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_); introDlg.setConfigFile(sysConfigFile_); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } saveMRUConfigFiles(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); paint(MMStudioMainFrame.this.getGraphics()); afMgr_ = new AutofocusManager(core_); engine_.setCore(core_, afMgr_); posList_ = new PositionList(); engine_.setPositionList(posList_); // if an error occurred during config loading, // do not display more errors than needed if (!loadSystemConfiguration()) ReportingUtils.showErrorOn(false); executeStartupScript(); loadPlugins(); toFront(); // Create Multi-D window here but do not show it. // This window needs to be created in order to properly set the "ChannelGroup" // based on the Multi-D parameters acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this); addMMBackgroundListener(acqControlWin_); configPad_.setCore(core_); if (parent != null) { configPad_.setParentGUI(parent); } configPadButtonPanel_.setCore(core_); // initialize controls initializeGUI(); initializePluginMenu(); String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, ""); if (afMgr_.hasDevice(afDevice)) { try { afMgr_.selectDevice(afDevice); } catch (MMException e1) { // this error should never happen ReportingUtils.showError(e1); } } // switch error reporting back on ReportingUtils.showErrorOn(true); } }); final JButton setRoiButton = new JButton(); setRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/shape_handles.png")); setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle"); setRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setROI(); } }); getContentPane().add(setRoiButton); springLayout_.putConstraint(SpringLayout.EAST, setRoiButton, 37, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, setRoiButton, 7, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, setRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, setRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JButton clearRoiButton = new JButton(); clearRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_out.png")); clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); clearRoiButton.setToolTipText("Reset Region of Interest to full frame"); clearRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearROI(); } }); getContentPane().add(clearRoiButton); springLayout_.putConstraint(SpringLayout.EAST, clearRoiButton, 70, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, clearRoiButton, 40, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, clearRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JLabel regionOfInterestLabel = new JLabel(); regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel.setText("ROI"); getContentPane().add(regionOfInterestLabel); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel, 71, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel, 8, SpringLayout.WEST, getContentPane()); contrastPanel_ = new ContrastPanel(); contrastPanel_.setFont(new Font("", Font.PLAIN, 10)); contrastPanel_.setContrastStretch(stretch); contrastPanel_.setBorder(new LineBorder(Color.black, 1, false)); getContentPane().add(contrastPanel_); springLayout_.putConstraint(SpringLayout.SOUTH, contrastPanel_, -26, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, contrastPanel_, 176, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, contrastPanel_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, contrastPanel_, 7, SpringLayout.WEST, getContentPane()); metadataPanel_ = new MetadataPanel(); metadataPanel_.setVisible(false); getContentPane().add(metadataPanel_); springLayout_.putConstraint(SpringLayout.SOUTH, metadataPanel_, -26, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, metadataPanel_, 176, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, metadataPanel_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, metadataPanel_, 7, SpringLayout.WEST, getContentPane()); metadataPanel_.setBorder(new LineBorder(Color.black, 1, false)); GUIUtils.registerImageFocusListener(new ImageFocusListener() { public void focusReceived(ImageWindow focusedWindow) { if (focusedWindow == null) { contrastPanel_.setVisible(true); metadataPanel_.setVisible(false); } else if (focusedWindow instanceof MMImageWindow) { contrastPanel_.setVisible(true); metadataPanel_.setVisible(false); } else if (focusedWindow.getImagePlus().getStack() instanceof AcquisitionVirtualStack) { contrastPanel_.setVisible(false); metadataPanel_.setVisible(true); } } }); final JLabel regionOfInterestLabel_1 = new JLabel(); regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel_1.setText("Zoom"); getContentPane().add(regionOfInterestLabel_1); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel_1, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel_1, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1, 139, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1, 81, SpringLayout.WEST, getContentPane()); final JButton zoomInButton = new JButton(); zoomInButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomIn(); } }); zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_in.png")); zoomInButton.setToolTipText("Zoom in"); zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomInButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomInButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomInButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomInButton, 110, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomInButton, 80, SpringLayout.WEST, getContentPane()); final JButton zoomOutButton = new JButton(); zoomOutButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomOut(); } }); zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_out.png")); zoomOutButton.setToolTipText("Zoom out"); zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomOutButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomOutButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomOutButton, 143, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomOutButton, 113, SpringLayout.WEST, getContentPane()); // Profile final JLabel profileLabel_ = new JLabel(); profileLabel_.setFont(new Font("Arial", Font.BOLD, 11)); profileLabel_.setText("Profile"); getContentPane().add(profileLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, profileLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, profileLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, profileLabel_, 217, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, profileLabel_, 154, SpringLayout.WEST, getContentPane()); final JButton buttonProf = new JButton(); buttonProf.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/chart_curve.png")); buttonProf.setFont(new Font("Arial", Font.PLAIN, 10)); buttonProf.setToolTipText("Open line profile window (requires line selection)"); buttonProf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openLineProfileWindow(); } }); // buttonProf.setText("Profile"); getContentPane().add(buttonProf); springLayout_.putConstraint(SpringLayout.SOUTH, buttonProf, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonProf, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonProf, 183, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonProf, 153, SpringLayout.WEST, getContentPane()); // Autofocus final JLabel autofocusLabel_ = new JLabel(); autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11)); autofocusLabel_.setText("Autofocus"); getContentPane().add(autofocusLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, autofocusLabel_, 274, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autofocusLabel_, 194, SpringLayout.WEST, getContentPane()); buttonAutofocus_ = new JButton(); buttonAutofocus_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/find.png")); buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocus_.setToolTipText("Autofocus now"); buttonAutofocus_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (afMgr_.getDevice() != null) { try { afMgr_.getDevice().fullFocus(); // or any other method from Autofocus.java API } catch (MMException mE) { ReportingUtils.showError(mE); } } } }); getContentPane().add(buttonAutofocus_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193, SpringLayout.WEST, getContentPane()); buttonAutofocusTools_ = new JButton(); buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/wrench_orange.png")); buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocusTools_.setToolTipText("Set autofocus options"); buttonAutofocusTools_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAutofocusDialog(); } }); getContentPane().add(buttonAutofocusTools_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226, SpringLayout.WEST, getContentPane()); saveConfigButton_ = new JButton(); saveConfigButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); } }); saveConfigButton_.setToolTipText("Save current presets to the configuration file"); saveConfigButton_.setText("Save"); saveConfigButton_.setEnabled(false); getContentPane().add(saveConfigButton_); springLayout_.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, saveConfigButton_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, saveConfigButton_, -80, SpringLayout.EAST, getContentPane()); } private void handleException(Exception e, String msg) { String errText = "Exception occurred: "; if (msg.length() > 0) { errText += msg + " } if (options_.debugLogEnabled) { errText += e.getMessage(); } else { errText += e.toString() + "\n"; ReportingUtils.showError(e); } handleError(errText); } private void handleException(Exception e) { handleException(e, ""); } private void handleError(String message) { if (IsLiveModeOn()) { // Should we always stop live mode on any error? enableLiveMode(false); } JOptionPane.showMessageDialog(this, message); core_.logMessage(message); } public void makeActive() { toFront(); } private void setExposure() { try { core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText())); // Display the new exposure time double exposure = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); // Interval for Live Mode changes as well setLiveModeInterval(); } catch (Exception exp) { // Do nothing. } } private void updateTitle() { this.setTitle("System: " + sysConfigFile_); } private void updateLineProfile() { if (!isImageWindowOpen() || profileWin_ == null || !profileWin_.isShowing()) { return; } calculateLineProfileData(imageWin_.getImagePlus()); profileWin_.setData(lineProfileData_); } private void openLineProfileWindow() { if (imageWin_ == null || imageWin_.isClosed()) { return; } calculateLineProfileData(imageWin_.getImagePlus()); if (lineProfileData_ == null) { return; } profileWin_ = new GraphFrame(); profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); profileWin_.setData(lineProfileData_); profileWin_.setAutoScale(); profileWin_.setTitle("Live line profile"); profileWin_.setBackground(guiColors_.background.get((options_.displayBackground))); addMMBackgroundListener(profileWin_); profileWin_.setVisible(true); } public Rectangle getROI() throws Exception { // ROI values are give as x,y,w,h in individual one-member arrays (pointers in C++): int[][] a = new int[4][1]; core_.getROI(a[0], a[1], a[2], a[3]); // Return as a single array with x,y,w,h: return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]); } private void calculateLineProfileData(ImagePlus imp) { // generate line profile Roi roi = imp.getRoi(); if (roi == null || !roi.isLine()) { // if there is no line ROI, create one Rectangle r = imp.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iXROI += iWidth / 2; iYROI += iHeight / 2; } roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI + iWidth / 4, iYROI + iHeight / 4); imp.setRoi(roi); roi = imp.getRoi(); } ImageProcessor ip = imp.getProcessor(); ip.setInterpolate(true); Line line = (Line) roi; if (lineProfileData_ == null) { lineProfileData_ = new GraphData(); } lineProfileData_.setData(line.getPixels()); } public void setROI(Rectangle r) throws Exception { boolean liveRunning = false; if (liveRunning_) { liveRunning = liveRunning_; enableLiveMode(false); } core_.setROI(r.x, r.y, r.width, r.height); updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } private void setROI() { ImagePlus curImage = WindowManager.getCurrentImage(); if (curImage == null) { return; } Roi roi = curImage.getRoi(); try { if (roi == null) { // if there is no ROI, create one Rectangle r = curImage.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iWidth /= 2; iHeight /= 2; iXROI += iWidth / 2; iYROI += iHeight / 2; } curImage.setRoi(iXROI, iYROI, iWidth, iHeight); roi = curImage.getRoi(); } if (roi.getType() != Roi.RECTANGLE) { handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI."); return; } Rectangle r = roi.getBoundingRect(); // Stop (and restart) live mode if it is running setROI(r); } catch (Exception e) { ReportingUtils.showError(e); } } private void clearROI() { try { boolean liveRunning = false; if (liveRunning_) { liveRunning = liveRunning_; enableLiveMode(false); } core_.clearROI(); updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } private BooleanLock creatingImageWindow_ = new BooleanLock(false); private static long waitForCreateImageWindowTimeout_ = 5000; private MMImageWindow createImageWindow() { if (creatingImageWindow_.isTrue()) { try { creatingImageWindow_.waitToSetFalse(waitForCreateImageWindowTimeout_); } catch (Exception e) { ReportingUtils.showError(e); } return imageWin_; } creatingImageWindow_.setValue(true); MMImageWindow win = imageWin_; removeMMBackgroundListener(imageWin_); imageWin_ = null; try { if (win != null) { win.saveAttributes(); // WindowManager.removeWindow(win); // win.close(); win.dispose(); win = null; } win = new MMImageWindow(core_, this); core_.logMessage("createImageWin1"); win.setBackground(guiColors_.background.get((options_.displayBackground))); addMMBackgroundListener(win); setIJCal(win); // listeners if (centerAndDragListener_ != null && centerAndDragListener_.isRunning()) { centerAndDragListener_.attach(win.getImagePlus().getWindow()); } if (zWheelListener_ != null && zWheelListener_.isRunning()) { zWheelListener_.attach(win.getImagePlus().getWindow()); } if (xyzKeyListener_ != null && xyzKeyListener_.isRunning()) { xyzKeyListener_.attach(win.getImagePlus().getWindow()); } win.getCanvas().requestFocus(); imageWin_ = win; } catch (Exception e) { if (win != null) { win.saveAttributes(); WindowManager.removeWindow(win); win.dispose(); } ReportingUtils.showError(e); } creatingImageWindow_.setValue(false); return imageWin_; } /** * Returns instance of the core uManager object; */ public CMMCore getMMCore() { return core_; } public void saveConfigPresets() { MicroscopeModel model = new MicroscopeModel(); try { model.loadFromFile(sysConfigFile_); model.createSetupConfigsFromHardware(core_); model.createResolutionsFromHardware(core_); JFileChooser fc = new JFileChooser(); boolean saveFile = true; File f; do { fc.setSelectedFile(new File(model.getFileName())); int retVal = fc.showSaveDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { f = fc.getSelectedFile(); // check if file already exists if (f.exists()) { int sel = JOptionPane.showConfirmDialog(this, "Overwrite " + f.getName(), "File Save", JOptionPane.YES_NO_OPTION); if (sel == JOptionPane.YES_OPTION) { saveFile = true; } else { saveFile = false; } } } else { return; } } while (saveFile == false); model.saveToFile(f.getAbsolutePath()); sysConfigFile_ = f.getAbsolutePath(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); updateTitle(); } catch (MMConfigFileException e) { ReportingUtils.showError(e); } } protected void setConfigSaveButtonStatus(boolean changed) { saveConfigButton_.setEnabled(changed); } private File runAcquisitionBrowser() { File selectedFile = null; if (JavaUtils.isMac()) { System.setProperty("apple.awt.fileDialogForDirectories", "true"); FileDialog fd = new FileDialog(this); fd.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); if (fd.getFile() != null) { selectedFile = new File(fd.getDirectory() + "/" + fd.getFile()); } } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = fc.getSelectedFile(); } } return selectedFile; } /** * Open an existing acquisition directory and build image5d window. * */ protected void openAcquisitionData() { // choose the directory File f = runAcquisitionBrowser(); if (f != null) { if (f.isDirectory()) { openAcqDirectory_ = f.getAbsolutePath(); } else { openAcqDirectory_ = f.getParent(); } String rootDir = new File(openAcqDirectory_).getAbsolutePath(); String name = new File(openAcqDirectory_).getName(); rootDir= rootDir.substring(0, rootDir.length() - (name.length() + 1)); try { if (acquisitionExists(name)) name = acqMgr_.getUniqueAcquisitionName(name); acqMgr_.openAcquisition(name, rootDir, true, true, true); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } } } protected void zoomOut() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomOut(r.width / 2, r.height / 2); } } protected void zoomIn() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomIn(r.width / 2, r.height / 2); } } protected void changeBinning() { try { boolean liveRunning = false; if (liveRunning_) { liveRunning = liveRunning_; enableLiveMode(false); } if (isCameraAvailable()) { Object item = comboBinning_.getSelectedItem(); if (item != null) { core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString()); } } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } private void createPropertyEditor() { if (propertyBrowser_ != null) { propertyBrowser_.dispose(); } propertyBrowser_ = new PropertyEditor(); propertyBrowser_.setGui(this); propertyBrowser_.setVisible(true); propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); propertyBrowser_.setCore(core_); } private void createCalibrationListDlg() { if (calibrationListDlg_ != null) { calibrationListDlg_.dispose(); } calibrationListDlg_ = new CalibrationListDlg(core_); calibrationListDlg_.setVisible(true); calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); calibrationListDlg_.setParentGUI(this); } public CalibrationListDlg getCalibrationListDlg() { if (calibrationListDlg_ == null) { createCalibrationListDlg(); } return calibrationListDlg_; } private void createScriptPanel() { if (scriptPanel_ == null) { scriptPanel_ = new ScriptPanel(core_, options_, this); scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_); scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_); scriptPanel_.setParentGUI(this); scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground))); addMMBackgroundListener(scriptPanel_); } scriptPanel_.setVisible(true); } /** * Updates Status line in main window from cached values */ private void updateStaticInfoFromCache() { String dimText = "Image size: " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X " + staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits"; dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix"; if (zStageLabel_.length() > 0) { dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um"; } if (xyStageLabel_.length() > 0) { dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um"; } labelImageDimensions_.setText(dimText); } public void updateXYPos(double x, double y) { staticInfo_.x_ = x; staticInfo_.y_ = y; updateStaticInfoFromCache(); } public void updateZPos(double z) { staticInfo_.zPos_ = z; updateStaticInfoFromCache(); } public void updateXYPosRelative(double x, double y) { staticInfo_.x_ += x; staticInfo_.y_ += y; updateStaticInfoFromCache(); } public void updateZPosRelative(double z) { staticInfo_.zPos_ += z; updateStaticInfoFromCache(); } public void updateXYStagePosition(){ double x[] = new double[1]; double y[] = new double[1]; try { if (xyStageLabel_.length() > 0) core_.getXYPosition(xyStageLabel_, x, y); } catch (Exception e) { ReportingUtils.showError(e); } staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } private void updatePixSizeUm (double pixSizeUm) { staticInfo_.pixSizeUm_ = pixSizeUm; updateStaticInfoFromCache(); } private void updateStaticInfo() { double zPos = 0.0; double x[] = new double[1]; double y[] = new double[1]; try { if (zStageLabel_.length() > 0) { zPos = core_.getPosition(zStageLabel_); } if (xyStageLabel_.length() > 0) { core_.getXYPosition(xyStageLabel_, x, y); } } catch (Exception e) { handleException(e); } staticInfo_.width_ = core_.getImageWidth(); staticInfo_.height_ = core_.getImageHeight(); staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel(); staticInfo_.imageBitDepth_ = core_.getImageBitDepth(); staticInfo_.pixSizeUm_ = core_.getPixelSizeUm(); staticInfo_.zPos_ = zPos; staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } private void setShutterButton(boolean state) { if (state) { toggleButtonShutter_.setSelected(true); toggleButtonShutter_.setText("Close"); } else { toggleButtonShutter_.setSelected(false); toggleButtonShutter_.setText("Open"); } } // public interface available for scripting access public void snapSingleImage() { doSnap(); } public Object getPixels() { if (imageWin_ != null) { return imageWin_.getImagePlus().getProcessor().getPixels(); } return null; } public void setPixels(Object obj) { if (imageWin_ == null) { return; } imageWin_.getImagePlus().getProcessor().setPixels(obj); } public int getImageHeight() { if (imageWin_ != null) { return imageWin_.getImagePlus().getHeight(); } return 0; } public int getImageWidth() { if (imageWin_ != null) { return imageWin_.getImagePlus().getWidth(); } return 0; } public int getImageDepth() { if (imageWin_ != null) { return imageWin_.getImagePlus().getBitDepth(); } return 0; } public ImageProcessor getImageProcessor() { if (imageWin_ == null) { return null; } return imageWin_.getImagePlus().getProcessor(); } private boolean isCameraAvailable() { return cameraLabel_.length() > 0; } public boolean isImageWindowOpen() { boolean ret = imageWin_ != null; ret = ret && !imageWin_.isClosed(); if (ret) { try { Graphics g = imageWin_.getGraphics(); if (null != g) { int ww = imageWin_.getWidth(); g.clearRect(0, 0, ww, 40); imageWin_.drawInfo(g); } else { // explicitly clean up if Graphics is null, rather // than cleaning up in the exception handler below.. WindowManager.removeWindow(imageWin_); imageWin_.saveAttributes(); imageWin_.dispose(); imageWin_ = null; ret = false; } } catch (Exception e) { WindowManager.removeWindow(imageWin_); imageWin_.saveAttributes(); imageWin_.dispose(); imageWin_ = null; ReportingUtils.showError(e); ret = false; } } return ret; } boolean IsLiveModeOn() { return liveModeTimerTask_ != null && liveModeTimerTask_.isRunning(); } // Timer task that displays the live image class LiveModeTimerTask extends TimerTask { public boolean running_ = false; private boolean cancelled_ = false; public synchronized boolean isRunning() { return running_; } @Override public synchronized boolean cancel() { running_ = false; return super.cancel(); } public void run() { Thread.currentThread().setPriority(3); running_ = true; if (!isImageWindowOpen()) { // stop live acquisition if user closed the window enableLiveMode(false); return; } if (!isNewImageAvailable()) { return; } try { if (core_.getRemainingImageCount() > 0) { Object img = core_.getLastImage(); if (img != img_) { img_ = img; displayImage(img_); Thread.yield(); } } } catch (Exception e) { ReportingUtils.showError(e); return; } } }; public void enableLiveMode(boolean enable) { if (enable) { if (IsLiveModeOn()) { return; } try { if (!isImageWindowOpen() && creatingImageWindow_.isFalse()) { imageWin_ = createImageWindow(); } // this is needed to clear the subtitle, should be folded into // drawInfo imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40); imageWin_.drawInfo(imageWin_.getGraphics()); imageWin_.toFront(); // turn off auto shutter and open the shutter autoShutterOrg_ = core_.getAutoShutter(); if (shutterLabel_.length() > 0) { shutterOrg_ = core_.getShutterOpen(); } core_.setAutoShutter(false); // Hide the autoShutter Checkbox autoShutterCheckBox_.setEnabled(false); shutterLabel_ = core_.getShutterDevice(); // only open the shutter when we have one and the Auto shutter // checkbox was checked if ((shutterLabel_.length() > 0) && autoShutterOrg_) { core_.setShutterOpen(true); } // attach mouse wheel listener to control focus: if (zWheelListener_ == null) { zWheelListener_ = new ZWheelListener(core_, this); } zWheelListener_.start(imageWin_); // attach key listener to control the stage and focus: if (xyzKeyListener_ == null) { xyzKeyListener_ = new XYZKeyListener(core_, this); } xyzKeyListener_.start(imageWin_); // Do not display more often than dictated by the exposure time setLiveModeInterval(); core_.startContinuousSequenceAcquisition(0.0); liveModeTimerTask_ = new LiveModeTimerTask(); liveModeTimer_.schedule(liveModeTimerTask_, (long)0, (long) liveModeInterval_); // Only hide the shutter checkbox if we are in autoshuttermode buttonSnap_.setEnabled(false); if (autoShutterOrg_) { toggleButtonShutter_.setEnabled(false); } imageWin_.setSubTitle("Live (running)"); liveRunning_ = true; } catch (Exception err) { ReportingUtils.showError(err, "Failed to enable live mode."); if (imageWin_ != null) { imageWin_.saveAttributes(); WindowManager.removeWindow(imageWin_); imageWin_.dispose(); imageWin_ = null; } } } else { if (!IsLiveModeOn()) { return; } try { liveModeTimerTask_.cancel(); core_.stopSequenceAcquisition(); if (zWheelListener_ != null) { zWheelListener_.stop(); } if (xyzKeyListener_ != null) { xyzKeyListener_.stop(); } // restore auto shutter and close the shutter if (shutterLabel_.length() > 0) { core_.setShutterOpen(shutterOrg_); } core_.setAutoShutter(autoShutterOrg_); if (autoShutterOrg_) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } liveRunning_ = false; buttonSnap_.setEnabled(true); autoShutterCheckBox_.setEnabled(true); // TODO: add timeout so that we can not hang here while (liveModeTimerTask_.isRunning()); // Make sure Timer properly stops. // This is here to avoid crashes when changing ROI in live mode // with Sensicam // Should be removed when underlying problem is dealt with Thread.sleep(100); imageWin_.setSubTitle("Live (stopped)"); liveModeTimerTask_ = null; } catch (Exception err) { ReportingUtils.showError(err, "Failed to disable live mode."); if (imageWin_ != null) { WindowManager.removeWindow(imageWin_); imageWin_.dispose(); imageWin_ = null; } } } toggleButtonLive_.setIcon(liveRunning_ ? SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/cancel.png") : SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setSelected(liveRunning_); toggleButtonLive_.setText(liveRunning_ ? "Stop Live" : "Live"); } public boolean getLiveMode() { return liveRunning_; } public boolean updateImage() { try { if (!isImageWindowOpen()) { // stop live acquistion if the window is not open if (IsLiveModeOn()) { enableLiveMode(false); return true; // nothing to do } } core_.snapImage(); Object img; img = core_.getImage(); if (imageWin_.windowNeedsResizing()) { createImageWindow(); } if (!isCurrentImageFormatSupported()) { return false; } imageWin_.newImage(img); updateLineProfile(); } catch (Exception e) { ReportingUtils.showError(e); return false; } return true; } public boolean displayImage(Object pixels) { try { if (!isImageWindowOpen() || imageWin_.windowNeedsResizing() && creatingImageWindow_.isFalse()) { createImageWindow(); } imageWin_.newImage(pixels); updateLineProfile(); } catch (Exception e) { ReportingUtils.logError(e); return false; } return true; } public boolean displayImageWithStatusLine(Object pixels, String statusLine) { try { if (!isImageWindowOpen() || imageWin_.windowNeedsResizing() && creatingImageWindow_.isFalse()) { createImageWindow(); } imageWin_.newImageWithStatusLine(pixels, statusLine); updateLineProfile(); } catch (Exception e) { ReportingUtils.logError(e); return false; } return true; } public void displayStatusLine(String statusLine) { try { if (isImageWindowOpen()) { imageWin_.displayStatusLine(statusLine); } } catch (Exception e) { ReportingUtils.logError(e); return; } } private boolean isCurrentImageFormatSupported() { boolean ret = false; long channels = core_.getNumberOfComponents(); long bpp = core_.getBytesPerPixel(); if (channels > 1 && channels != 4 && bpp != 1) { handleError("Unsupported image format."); } else { ret = true; } return ret; } private void doSnap() { try { Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR); setCursor(waitCursor); if (!isImageWindowOpen()) { imageWin_ = createImageWindow(); } imageWin_.toFront(); setIJCal(imageWin_); // this is needed to clear the subtite, should be folded into // drawInfo imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40); imageWin_.drawInfo(imageWin_.getGraphics()); imageWin_.setSubTitle("Snap"); String expStr = textFieldExp_.getText(); if (expStr.length() > 0) { core_.setExposure(NumberUtils.displayStringToDouble(expStr)); updateImage(); } else { handleError("Exposure field is empty!"); } } catch (Exception e) { ReportingUtils.showError(e); } Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); setCursor(defaultCursor); } public void initializeGUI() { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); engine_.setZStageDevice(zStageLabel_); if (cameraLabel_.length() > 0) { ActionListener[] listeners; // binning combo if (comboBinning_.getItemCount() > 0) { comboBinning_.removeAllItems(); } StrVector binSizes = core_.getAllowedPropertyValues( cameraLabel_, MMCoreJ.getG_Keyword_Binning()); listeners = comboBinning_.getActionListeners(); for (int i = 0; i < listeners.length; i++) { comboBinning_.removeActionListener(listeners[i]); } for (int i = 0; i < binSizes.size(); i++) { comboBinning_.addItem(binSizes.get(i)); } comboBinning_.setMaximumRowCount((int) binSizes.size()); if (binSizes.size() == 0) { comboBinning_.setEditable(true); } else { comboBinning_.setEditable(false); } for (int i = 0; i < listeners.length; i++) { comboBinning_.addActionListener(listeners[i]); } } // active shutter combo try { shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice); } catch (Exception e) { ReportingUtils.logError(e); } if (shutters_ != null) { String items[] = new String[(int) shutters_.size()]; for (int i = 0; i < shutters_.size(); i++) { items[i] = shutters_.get(i); } GUIUtils.replaceComboContents(shutterComboBox_, items); String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // Autofocus buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null); buttonAutofocus_.setEnabled(afMgr_.getDevice() != null); // Rebuild stage list in XY PositinList if (posListDlg_ != null) { posListDlg_.rebuildAxisList(); } // Mouse moves stage centerAndDragListener_ = new CenterAndDragListener(core_, gui_); if (centerAndDragMenuItem_.isSelected()) { centerAndDragListener_.start(); } updateGUI(true); } catch (Exception e) { ReportingUtils.showError(e); } } public String getVersion() { return VERSION; } private void initializePluginMenu() { // add plugin menu items if (plugins_.size() > 0) { final JMenu pluginMenu = new JMenu(); pluginMenu.setText("Plugins"); menuBar_.add(pluginMenu); for (int i = 0; i < plugins_.size(); i++) { final JMenuItem newMenuItem = new JMenuItem(); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { ReportingUtils.logMessage("Plugin command: " + e.getActionCommand()); // find the coresponding plugin for (int i = 0; i < plugins_.size(); i++) { if (plugins_.get(i).menuItem.equals(e.getActionCommand())) { PluginItem plugin = plugins_.get(i); plugin.instantiate(); plugin.plugin.show(); break; } } } }); newMenuItem.setText(plugins_.get(i).menuItem); pluginMenu.add(newMenuItem); } } // add help menu item final JMenu helpMenu = new JMenu(); helpMenu.setText("Help"); menuBar_.add(helpMenu); final JMenuItem usersGuideMenuItem = new JMenuItem(); usersGuideMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/documentation.php?object=Userguide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); usersGuideMenuItem.setText("User's Guide..."); helpMenu.add(usersGuideMenuItem); final JMenuItem configGuideMenuItem = new JMenuItem(); configGuideMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/documentation.php?object=Configguide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); configGuideMenuItem.setText("Configuration Guide..."); helpMenu.add(configGuideMenuItem); if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) { final JMenuItem registerMenuItem = new JMenuItem(); registerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_); regDlg.setVisible(true); } catch (Exception e1) { ReportingUtils.showError(e1); } } }); registerMenuItem.setText("Register your copy of Micro-Manager..."); helpMenu.add(registerMenuItem); } final JMenuItem aboutMenuItem = new JMenuItem(); aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MMAboutDlg dlg = new MMAboutDlg(); String versionInfo = "MM Studio version: " + VERSION; versionInfo += "\n" + core_.getVersionInfo(); versionInfo += "\n" + core_.getAPIVersionInfo(); versionInfo += "\nUser: " + core_.getUserId(); versionInfo += "\nHost: " + core_.getHostName(); dlg.setVersionInfo(versionInfo); dlg.setVisible(true); } }); aboutMenuItem.setText("About..."); helpMenu.add(aboutMenuItem); } public void updateGUI(boolean updateConfigPadStructure) { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); afMgr_.refresh(); // camera settings if (isCameraAvailable()) { double exp = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp)); String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); GUIUtils.setComboSelection(comboBinning_, binSize); long bitDepth = 8; if (imageWin_ != null) { long hsz = imageWin_.getRawHistogramSize(); bitDepth = (long) Math.log(hsz); } bitDepth = core_.getImageBitDepth(); contrastPanel_.setPixelBitDepth((int) bitDepth, false); } if (liveModeTimerTask_ == null || !liveModeTimerTask_.isRunning()) { autoShutterCheckBox_.setSelected(core_.getAutoShutter()); boolean shutterOpen = core_.getShutterOpen(); setShutterButton(shutterOpen); if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } autoShutterOrg_ = core_.getAutoShutter(); } // active shutter combo if (shutters_ != null) { String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // state devices if (updateConfigPadStructure && (configPad_ != null)) { configPad_.refreshStructure(); } // update Channel menus in Multi-dimensional acquisition dialog updateChannelCombos(); } catch (Exception e) { ReportingUtils.logError(e); } updateStaticInfo(); updateTitle(); } public boolean okToAcquire() { return !liveModeTimerTask_.isRunning(); } public void stopAllActivity() { enableLiveMode(false); } public void refreshImage() { if (imageWin_ != null) { imageWin_.getImagePlus().updateAndDraw(); } } private void cleanupOnClose() { // NS: Save config presets if they were changed. if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } } if (liveModeTimerTask_ != null) liveModeTimerTask_.cancel(); try{ if (imageWin_ != null) { if (!imageWin_.isClosed()) imageWin_.close(); imageWin_.dispose(); imageWin_ = null; } } catch( Throwable t){ ReportingUtils.logError(t, "closing ImageWin_"); } if (profileWin_ != null) { removeMMBackgroundListener(profileWin_); profileWin_.dispose(); } if (scriptPanel_ != null) { removeMMBackgroundListener(scriptPanel_); scriptPanel_.closePanel(); } if (propertyBrowser_ != null) { removeMMBackgroundListener(propertyBrowser_); propertyBrowser_.dispose(); } if (acqControlWin_ != null) { removeMMBackgroundListener(acqControlWin_); acqControlWin_.close(); } if (engine_ != null) { engine_.shutdown(); } if (afMgr_ != null) { afMgr_.closeOptionsDialog(); } // dispose plugins for (int i = 0; i < plugins_.size(); i++) { MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin; if (plugin != null) { plugin.dispose(); } } try { if (core_ != null) core_.reset(); } catch (Exception err) { ReportingUtils.showError(err); } } private void saveSettings() { Rectangle r = this.getBounds(); mainPrefs_.putInt(MAIN_FRAME_X, r.x); mainPrefs_.putInt(MAIN_FRAME_Y, r.y); mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width); mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height); mainPrefs_.putBoolean(MAIN_STRETCH_CONTRAST, contrastPanel_.isContrastStretch()); mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_); // save field values from the main window // NOTE: automatically restoring these values on startup may cause // problems mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText()); // NOTE: do not save auto shutter state if (afMgr_ != null && afMgr_.getDevice() != null) { mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName()); } } private void loadConfiguration() { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new CfgFileFilter()); fc.setSelectedFile(new File(sysConfigFile_)); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); sysConfigFile_ = f.getAbsolutePath(); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); } } private void loadSystemState() { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new CfgFileFilter()); fc.setSelectedFile(new File(sysStateFile_)); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); sysStateFile_ = f.getAbsolutePath(); try { // WaitDialog waitDlg = new // WaitDialog("Loading saved state, please wait..."); // waitDlg.showDialog(); core_.loadSystemState(sysStateFile_); GUIUtils.preventDisplayAdapterChangeExceptions(); // waitDlg.closeDialog(); initializeGUI(); } catch (Exception e) { ReportingUtils.showError(e); return; } } } private void saveSystemState() { JFileChooser fc = new JFileChooser(); boolean saveFile = true; File f; do { fc.setSelectedFile(new File(sysStateFile_)); int retVal = fc.showSaveDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { f = fc.getSelectedFile(); // check if file already exists if (f.exists()) { int sel = JOptionPane.showConfirmDialog(this, "Overwrite " + f.getName(), "File Save", JOptionPane.YES_NO_OPTION); if (sel == JOptionPane.YES_OPTION) { saveFile = true; } else { saveFile = false; } } } else { return; } } while (saveFile == false); sysStateFile_ = f.getAbsolutePath(); try { core_.saveSystemState(sysStateFile_); } catch (Exception e) { ReportingUtils.showError(e); return; } } public void closeSequence() { if (engine_ != null && engine_.isAcquisitionRunning()) { int result = JOptionPane.showConfirmDialog( this, "Acquisition in progress. Are you sure you want to exit and discard all data?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.NO_OPTION) { return; } } stopAllActivity(); cleanupOnClose(); saveSettings(); try { configPad_.saveSettings(); options_.saveSettings(); } catch (NullPointerException e) { this.logError(e); } dispose(); if (!runsAsPlugin_) { System.exit(0); } else { ImageJ ij = IJ.getInstance(); if (ij != null) { ij.quit(); } } } public void applyContrastSettings(ContrastSettings contrast8, ContrastSettings contrast16) { contrastPanel_.applyContrastSettings(contrast8, contrast16); } public ContrastSettings getContrastSettings() { return contrastPanel_.getContrastSettings(); } public boolean is16bit() { if (isImageWindowOpen() && imageWin_.getImagePlus().getProcessor() instanceof ShortProcessor) { return true; } return false; } public boolean isRunning() { return running_; } /** * Executes the beanShell script. This script instance only supports * commands directed to the core object. */ private void executeStartupScript() { // execute startup script File f = new File(startupScriptFile_); if (startupScriptFile_.length() > 0 && f.exists()) { WaitDialog waitDlg = new WaitDialog( "Executing startup script, please wait..."); waitDlg.showDialog(); Interpreter interp = new Interpreter(); try { // insert core object only interp.set(SCRIPT_CORE_OBJECT, core_); interp.set(SCRIPT_ACQENG_OBJECT, engine_); interp.set(SCRIPT_GUI_OBJECT, this); // read text file and evaluate interp.eval(TextUtils.readTextFile(startupScriptFile_)); } catch (IOException exc) { ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ")."); } catch (EvalError exc) { ReportingUtils.showError(exc); } finally { waitDlg.closeDialog(); } } else { if (startupScriptFile_.length() > 0) ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present."); } } /** * Loads sytem configuration from the cfg file. */ private boolean loadSystemConfiguration() { boolean result = true; saveMRUConfigFiles(); final WaitDialog waitDlg = new WaitDialog( "Loading system configuration, please wait..."); waitDlg.setAlwaysOnTop(true); waitDlg.showDialog(); this.setEnabled(false); try { if (sysConfigFile_.length() > 0) { GUIUtils.preventDisplayAdapterChangeExceptions(); core_.waitForSystem(); core_.loadSystemConfiguration(sysConfigFile_); GUIUtils.preventDisplayAdapterChangeExceptions(); waitDlg.closeDialog(); } else { waitDlg.closeDialog(); } } catch (final Exception err) { GUIUtils.preventDisplayAdapterChangeExceptions(); waitDlg.closeDialog(); ReportingUtils.showError(err); result = false; } this.setEnabled(true); this.initializeGUI(); updateSwitchConfigurationMenu(); return result; } private void saveMRUConfigFiles() { if (0 < sysConfigFile_.length()) { if (MRUConfigFiles_.contains(sysConfigFile_)) { MRUConfigFiles_.remove(sysConfigFile_); } if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); // save the MRU list to the preferences for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) { String value = ""; if (null != MRUConfigFiles_.get(icfg)) { value = MRUConfigFiles_.get(icfg).toString(); } mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value); } } } private void loadMRUConfigFiles() { sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_); // startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE, // startupScriptFile_); MRUConfigFiles_ = new ArrayList<String>(); for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) { String value = ""; value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value); if (0 < value.length()) { File ruFile = new File(value); if (ruFile.exists()) { if (!MRUConfigFiles_.contains(value)) { MRUConfigFiles_.add(value); } } } } // initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE if (0 < sysConfigFile_.length()) { if (!MRUConfigFiles_.contains(sysConfigFile_)) { // in case persistant data is inconsistent if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); } } } /** * Opens Acquisition dialog. */ private void openAcqControlDialog() { try { if (acqControlWin_ == null) { acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this); } if (acqControlWin_.isActive()) { acqControlWin_.setTopPosition(); } acqControlWin_.setVisible(true); // TODO: this call causes a strange exception the first time the // dialog is created // something to do with the order in which combo box creation is // performed // acqControlWin_.updateGroupsCombo(); } catch (Exception exc) { ReportingUtils.showError(exc, "\nAcquistion window failed to open due to invalid or corrupted settings.\n" + "Try resetting registry settings to factory defaults (Menu Tools|Options)."); } } /** * Opens Split View dialog. */ /* protected void splitViewDialog() { try { if (splitView_ == null) { splitView_ = new SplitView(core_, this, options_); } splitView_.setVisible(true); } catch (Exception exc) { ReportingUtils.showError(exc, "\nSplit View Window failed to open due to internal error."); } } */ * /** Opens a dialog to record stage positions */ public void showXYPositionList() { if (posListDlg_ == null) { posListDlg_ = new PositionListDlg(core_, this, posList_, options_); } posListDlg_.setVisible(true); } private void updateChannelCombos() { if (this.acqControlWin_ != null) { this.acqControlWin_.updateChannelAndGroupCombo(); } } public void setConfigChanged(boolean status) { configChanged_ = status; setConfigSaveButtonStatus(configChanged_); } /** * Returns the current background color * @return */ public Color getBackgroundColor() { return guiColors_.background.get((options_.displayBackground)); } /* * Changes background color of this window and all other MM windows */ public void setBackgroundStyle(String backgroundType) { setBackground(guiColors_.background.get((options_.displayBackground))); paint(MMStudioMainFrame.this.getGraphics()); // sets background of all registered Components for (Component comp:MMFrames_) { if (comp != null) comp.setBackground(guiColors_.background.get((options_.displayBackground))); } } public String getBackgroundStyle() { return options_.displayBackground; } // Set ImageJ pixel calibration private void setIJCal(MMImageWindow imageWin) { if (imageWin != null) { imageWin.setIJCal(); } } // Scripting interface private class ExecuteAcq implements Runnable { public ExecuteAcq() { } public void run() { if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); } } } private class LoadAcq implements Runnable { private String filePath_; public LoadAcq(String path) { filePath_ = path; } public void run() { // stop current acquisition if any engine_.shutdown(); // load protocol if (acqControlWin_ != null) { acqControlWin_.loadAcqSettingsFromFile(filePath_); } } } private class RefreshPositionList implements Runnable { public RefreshPositionList() { } public void run() { if (posListDlg_ != null) { posListDlg_.setPositionList(posList_); engine_.setPositionList(posList_); } } } private void testForAbortRequests() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } } } public void startAcquisition() throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new ExecuteAcq()); } public void runAcquisition() throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(50); } } catch (InterruptedException e) { ReportingUtils.showError(e); } } else { throw new MMScriptException( "Acquisition window must be open for this command to work."); } } public void runAcquisition(String name, String root) throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { acqControlWin_.runAcquisition(name, root); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(100); } } catch (InterruptedException e) { ReportingUtils.showError(e); } } else { throw new MMScriptException( "Acquisition window must be open for this command to work."); } } public void runAcqusition(String name, String root) throws MMScriptException { runAcquisition(name, root); } public void loadAcquisition(String path) throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new LoadAcq(path)); } public void setPositionList(PositionList pl) throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object posList_ = PositionList.newInstance(pl); SwingUtilities.invokeLater(new RefreshPositionList()); } public PositionList getPositionList() throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object return PositionList.newInstance(posList_); } public void sleep(long ms) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.sleep(ms); } } public void openAcquisition(String name, String rootDir) throws MMScriptException { openAcquisition(name, rootDir, true); } public void openAcquisition(String name, String rootDir, boolean show) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir, show); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, true, false); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices) throws MMScriptException { openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir, show, virtual); AcquisitionInterface acq = acqMgr_.getAcquisition(name); acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show, boolean virtual) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual); } private void openAcquisitionSnap(String name, String rootDir, boolean show) throws MMScriptException { /* AcquisitionInterface acq = acqMgr_.openAcquisitionSnap(name, rootDir, this, show); acq.setDimensions(0, 1, 1, 1); try { // acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm()); acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm())); } catch (Exception e) { ReportingUtils.showError(e); } * */ } public void initializeAcquisition(String name, int width, int height, int depth) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(name); acq.setImagePhysicalDimensions(width, height, depth); acq.initialize(); } public int getAcquisitionImageWidth(String acqName) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(acqName); return acq.getWidth(); } public int getAcquisitionImageHeight(String acqName) throws MMScriptException{ AcquisitionInterface acq = acqMgr_.getAcquisition(acqName); return acq.getHeight(); } public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{ AcquisitionInterface acq = acqMgr_.getAcquisition(acqName); return acq.getDepth(); } public Boolean acquisitionExists(String name) { return acqMgr_.acquisitionExists(name); } public void closeAcquisition(String name) throws MMScriptException { acqMgr_.closeAcquisition(name); } public void closeAcquisitionImage5D(String title) throws MMScriptException { acqMgr_.closeImage5D(title); } public void loadBurstAcquisition(String path) { // TODO Auto-generated method stub } public void refreshGUI() { updateGUI(true); } public void setAcquisitionProperty(String acqName, String propertyName, String value) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(acqName); acq.setProperty(propertyName, value); } public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException { acqMgr_.getAcquisition(acqName).setSystemState(md); } public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException { acqMgr_.getAcquisition(acqName).setSummaryProperties(md); } public void setImageProperty(String acqName, int frame, int channel, int slice, String propName, String value) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(acqName); acq.setProperty(frame, channel, slice, propName, value); } public void snapAndAddImage(String name, int frame, int channel, int slice) throws MMScriptException { snapAndAddImage(name, frame, channel, slice, 0); } public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException { Metadata md = new Metadata(); try { Object img; if (core_.isSequenceRunning()) { img = core_.getLastImage(); core_.getLastImageMD(0, 0, md); //img = core_.getLastTaggedImage(); } else { core_.snapImage(); img = core_.getImage(); } AcquisitionInterface acq = acqMgr_.getAcquisition(name); long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); if (!acq.isInitialized()) { acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth); acq.initialize(); } acq.insertImage(img, frame, channel, slice, position); // Insert exposure in metadata // acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure())); // Add pixel size calibration /* double pixSizeUm = core_.getPixelSizeUm(); if (pixSizeUm > 0) { acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); } // generate list with system state JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache()); // and insert into metadata acq.setSystemState(frame, channel, slice, state); */ } catch (Exception e) { ReportingUtils.showError(e); } } public void addToSnapSeries(Object img, String acqName) { try { // boolean liveRunning = liveRunning_; // if (liveRunning) // enableLiveMode(false); if (acqName == null) { acqName = "Snap" + snapCount_; } Boolean newSnap = false; core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText())); long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); //MMAcquisitionSnap acq = null; if (acqMgr_.hasActiveImage5D(acqName)) { // acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName); // newSnap = !acq.isCompatibleWithCameraSettings(); ; } else { newSnap = true; } if (newSnap) { snapCount_++; acqName = "Snap" + snapCount_; this.openAcquisitionSnap(acqName, null, true); // (dir=null) -> // keep in // memory; don't // save to file. initializeAcquisition(acqName, (int) width, (int) height, (int) depth); } setChannelColor(acqName, 0, Color.WHITE); setChannelName(acqName, 0, "Snap"); // acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName); // acq.appendImage(img); // add exposure to metadata // acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure())); // Add pixel size calibration double pixSizeUm = core_.getPixelSizeUm(); if (pixSizeUm > 0) { // acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); // acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); } // generate list with system state // JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache()); // and insert into metadata // acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state); // closeAcquisition(acqName); } catch (Exception e) { ReportingUtils.showError(e); } } public void addImage(String name, Object img, int frame, int channel, int slice) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(name); acq.insertImage(img, frame, channel, slice); } public void addImage(String name, TaggedImage taggedImg) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg); } public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay); } public void closeAllAcquisitions() { acqMgr_.closeAll(); } private class ScriptConsoleMessage implements Runnable { String msg_; public ScriptConsoleMessage(String text) { msg_ = text; } public void run() { scriptPanel_.message(msg_); } } public void message(String text) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } SwingUtilities.invokeLater(new ScriptConsoleMessage(text)); } } public void clearMessageWindow() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.clearOutput(); } } public void clearOutput() throws MMScriptException { clearMessageWindow(); } public void clear() throws MMScriptException { clearMessageWindow(); } public void setChannelContrast(String title, int channel, int min, int max) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setChannelContrast(channel, min, max); } public void setChannelName(String title, int channel, String name) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setChannelName(channel, name); } public void setChannelColor(String title, int channel, Color color) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setChannelColor(channel, color.getRGB()); } public void setContrastBasedOnFrame(String title, int frame, int slice) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setContrastBasedOnFrame(frame, slice); } public void setStagePosition(double z) throws MMScriptException { try { core_.setPosition(core_.getFocusDevice(),z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setRelativeStagePosition(double z) throws MMScriptException { try { cb_.onStagePositionChangedRelative(core_.getFocusDevice(), z); core_.setRelativePosition(core_.getFocusDevice(), z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setXYStagePosition(double x, double y) throws MMScriptException { try { core_.setXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setRelativeXYStagePosition(double x, double y) throws MMScriptException { try { cb_.onXYStagePositionChangedRelative(core_.getXYStageDevice(), x, y); core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public Point2D.Double getXYStagePosition() throws MMScriptException { String stage = core_.getXYStageDevice(); if (stage.length() == 0) { throw new MMScriptException("XY Stage device is not available"); } double x[] = new double[1]; double y[] = new double[1]; try { core_.getXYPosition(stage, x, y); Point2D.Double pt = new Point2D.Double(x[0], y[0]); return pt; } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public String getXYStageName() { return core_.getXYStageDevice(); } public void setXYOrigin(double x, double y) throws MMScriptException { String xyStage = core_.getXYStageDevice(); try { core_.setAdapterOriginXY(xyStage, x, y); } catch (Exception e) { throw new MMScriptException(e); } } public AcquisitionEngine getAcquisitionEngine() { return engine_; } public String installPlugin(Class<?> cl) { String className = cl.getSimpleName(); String msg = new String(className + " module loaded."); try { for (PluginItem plugin : plugins_) { if (plugin.className.contentEquals(className)) { return className + " already loaded."; } } PluginItem pi = new PluginItem(); pi.className = className; try { // Get this static field from the class implementing MMPlugin. pi.menuItem = (String) cl.getDeclaredField("menuName").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); pi.menuItem = className; } catch (NoSuchFieldException e) { pi.menuItem = className; ReportingUtils.logError(className + " fails to implement static String menuName."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } if (pi.menuItem == null) { pi.menuItem = className; //core_.logMessage(className + " fails to implement static String menuName."); } pi.pluginClass = cl; plugins_.add(pi); } catch (NoClassDefFoundError e) { msg = className + " class definition not found."; ReportingUtils.logError(e, msg); } return msg; } public String installPlugin(String className, String menuName) { String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead."; core_.logMessage(msg); installPlugin(className); return msg; } public String installPlugin(String className) { String msg = ""; try { return installPlugin(Class.forName(className)); } catch (ClassNotFoundException e) { msg = className + " plugin not found."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(String className) { try { return installAutofocusPlugin(Class.forName(className)); } catch (ClassNotFoundException e) { String msg = "Internal error: AF manager not instantiated."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(Class<?> autofocus) { String msg = new String(autofocus.getSimpleName() + " module loaded."); if (afMgr_ != null) { try { afMgr_.refresh(); } catch (MMException e) { msg = e.getMessage(); ReportingUtils.logError(e); } afMgr_.setAFPluginClassName(autofocus.getSimpleName()); } else { msg = "Internal error: AF manager not instantiated."; } return msg; } public CMMCore getCore() { return core_; } public void snapAndAddToImage5D(String acqName) { /* Object img; try { boolean liveRunning = liveRunning_; if (liveRunning) { img = core_.getLastImage(); } else { core_.snapImage(); img = core_.getImage(); } addToSnapSeries(img, acqName); } catch (Exception e) { ReportingUtils.showError(e); }*/ SequenceSettings acquisitionSettings = new SequenceSettings(); AcquisitionWrapperEngine eng = new AcquisitionWrapperEngine(); eng.setCore(core_, afMgr_); eng.setParentGUI(this); eng.acquire(acquisitionSettings); } public void setAcquisitionEngine(AcquisitionEngine eng) { engine_ = eng; } //Returns true if there is a newer image to display that can be get from MMCore //Implements "optimistic" approach: returns true even //if there was an error while getting the image time stamp private boolean isNewImageAvailable() { boolean ret = true; /* disabled until metadata-related methods in MMCoreJ can handle exceptions Metadata md = new Metadata(); MetadataSingleTag tag = null; try { core_.getLastImageMD(0, 0, md); String strTag=MMCoreJ.getG_Keyword_Elapsed_Time_ms(); tag = md.GetSingleTag(strTag); if(tag != null) { double newFrameTimeStamp = Double.valueOf(tag.GetValue()); ret = newFrameTimeStamp > lastImageTimeMs_; if (ret) { lastImageTimeMs_ = newFrameTimeStamp; } } } catch(Exception e) { ReportingUtils.logError(e); } */ return ret; } ; public void suspendLiveMode() { liveModeSuspended_ = IsLiveModeOn(); enableLiveMode(false); } public void resumeLiveMode() { if (liveModeSuspended_) { enableLiveMode(true); } } public Autofocus getAutofocus() { return afMgr_.getDevice(); } public void showAutofocusDialog() { if (afMgr_.getDevice() != null) { afMgr_.showOptionsDialog(); } } public AutofocusManager getAutofocusManager() { return afMgr_; } public void selectConfigGroup(String groupName) { configPad_.setGroup(groupName); } private void loadPlugins() { ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>(); ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>(); List<Class<?>> classes; try { classes = JavaUtils.findClasses(new File("mmplugins"), 2); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == MMPlugin.class) { pluginClasses.add(clazz); } } } classes = JavaUtils.findClasses(new File("mmautofocus"), 2); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == Autofocus.class) { autofocusClasses.add(clazz); } } } } catch (ClassNotFoundException e1) { ReportingUtils.logError(e1); } for (Class<?> plugin : pluginClasses) { try { installPlugin(plugin); } catch (Exception e) { ReportingUtils.logError(e, "Attempted to install the \"" + plugin.getName() + "\" plugin ."); } } for (Class<?> autofocus : autofocusClasses) { try { installAutofocusPlugin(autofocus.getName()); } catch (Exception e) { ReportingUtils.logError("Attempted to install the \"" + autofocus.getName() + "\" autofocus plugin."); } } } private void setLiveModeInterval() { double interval = 33.0; try { if (core_.getExposure() > 33.0) { interval = core_.getExposure(); } } catch (Exception ex) { ReportingUtils.showError(ex); } liveModeInterval_ = interval; //liveModeTimer_.setDelay((int) liveModeInterval_); //liveModeTimer_.setInitialDelay(liveModeTimer_.getDelay()); } public void logMessage(String msg) { ReportingUtils.logMessage(msg); } public void showMessage(String msg) { ReportingUtils.showMessage(msg); } public void logError(Exception e, String msg) { ReportingUtils.logError(e, msg); } public void logError(Exception e) { ReportingUtils.logError(e); } public void logError(String msg) { ReportingUtils.logError(msg); } public void showError(Exception e, String msg) { ReportingUtils.showError(e, msg); } public void showError(Exception e) { ReportingUtils.showError(e); } public void showError(String msg) { ReportingUtils.showError(msg); } } class BooleanLock extends Object { private boolean value; public BooleanLock(boolean initialValue) { value = initialValue; } public BooleanLock() { this(false); } public synchronized void setValue(boolean newValue) { if (newValue != value) { value = newValue; notifyAll(); } } public synchronized boolean waitToSetTrue(long msTimeout) throws InterruptedException { boolean success = waitUntilFalse(msTimeout); if (success) { setValue(true); } return success; } public synchronized boolean waitToSetFalse(long msTimeout) throws InterruptedException { boolean success = waitUntilTrue(msTimeout); if (success) { setValue(false); } return success; } public synchronized boolean isTrue() { return value; } public synchronized boolean isFalse() { return !value; } public synchronized boolean waitUntilTrue(long msTimeout) throws InterruptedException { return waitUntilStateIs(true, msTimeout); } public synchronized boolean waitUntilFalse(long msTimeout) throws InterruptedException { return waitUntilStateIs(false, msTimeout); } public synchronized boolean waitUntilStateIs( boolean state, long msTimeout) throws InterruptedException { if (msTimeout == 0L) { while (value != state) { wait(); } return true; } long endTime = System.currentTimeMillis() + msTimeout; long msRemaining = msTimeout; while ((value != state) && (msRemaining > 0L)) { wait(msRemaining); msRemaining = endTime - System.currentTimeMillis(); } return (value == state); } }
package jesg; import jesg.avro.SecondarySortKey; import org.apache.avro.mapred.AvroKey; import org.apache.avro.mapreduce.AvroJob; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class SecondarySortDriver extends Configured implements Tool { @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.err.printf( "Usage: %s [generic options] <input> <output> \n", getClass().getSimpleName()); ToolRunner.printGenericCommandUsage(System.err); return -1; } Job job = new Job(getConf()); job.setJobName("Secondary Sort"); job.setJarByClass(getClass()); AvroJob.setMapOutputKeySchema(job, SecondarySortKey.getClassSchema()); AvroJob.setOutputKeySchema(job, SecondarySortKey.getClassSchema()); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(SecondarySortMapper.class); job.setReducerClass(Reducer.class); // identity reducer job.setPartitionerClass(SecondarySortPartitioner.class); job.setMapOutputKeyClass(AvroKey.class); job.setMapOutputValueClass(LongWritable.class); job.setOutputKeyClass(AvroKey.class); job.setOutputValueClass(LongWritable.class); return job.waitForCompletion(true) ? 0 : 1; } public static void main(String[] args) throws Exception { int exitCode = ToolRunner.run(new SecondarySortDriver(), args); System.exit(exitCode); } }
//FILE: MMStudioMainFrame.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //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. //CVS: $Id$ package org.micromanager; import ij.ImagePlus; import ij.ImageJ; import ij.IJ; import ij.WindowManager; import ij.gui.Line; import ij.gui.Roi; import ij.measure.Calibration; import ij.process.ByteProcessor; import ij.process.ColorProcessor; import ij.process.ImageProcessor; import ij.process.ImageStatistics; import ij.process.ShortProcessor; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.geom.Point2D; import java.awt.image.ColorModel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.prefs.Preferences; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SpringLayout; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.LineBorder; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.MMCoreJ; import mmcorej.MMEventCallback; import mmcorej.StrVector; import org.micromanager.acquisition.AcquisitionManager; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.Autofocus; import org.micromanager.api.MMPlugin; import org.micromanager.api.DeviceControlGUI; import org.micromanager.api.ScriptInterface; import org.micromanager.conf.ConfiguratorDlg; import org.micromanager.conf.MMConfigFileException; import org.micromanager.conf.MicroscopeModel; import org.micromanager.graph.ContrastPanel; import org.micromanager.graph.GraphData; import org.micromanager.graph.GraphFrame; import org.micromanager.image5d.ChannelCalibration; import org.micromanager.image5d.ChannelControl; import org.micromanager.image5d.ChannelDisplayProperties; import org.micromanager.image5d.Crop_Image5D; import org.micromanager.image5d.Duplicate_Image5D; import org.micromanager.image5d.Image5D; import org.micromanager.image5d.Image5DWindow; import org.micromanager.image5d.Image5D_Channels_to_Stacks; import org.micromanager.image5d.Image5D_Stack_to_RGB; import org.micromanager.image5d.Image5D_Stack_to_RGB_t; import org.micromanager.image5d.Image5D_to_Stack; import org.micromanager.image5d.Image5D_to_VolumeViewer; import org.micromanager.image5d.Make_Montage; import org.micromanager.image5d.Split_Image5D; import org.micromanager.image5d.Z_Project; import org.micromanager.metadata.AcquisitionData; import org.micromanager.metadata.DisplaySettings; import org.micromanager.metadata.MMAcqDataException; import org.micromanager.metadata.WellAcquisitionData; import org.micromanager.navigation.CenterListener; import org.micromanager.navigation.DragListener; import org.micromanager.navigation.PositionList; import org.micromanager.navigation.ZWheelListener; import org.micromanager.utils.CfgFileFilter; import org.micromanager.utils.ContrastSettings; import org.micromanager.utils.GUIColors; import org.micromanager.utils.GUIUtils; import org.micromanager.utils.LargeMessageDlg; import org.micromanager.utils.MMImageWindow; import org.micromanager.utils.MMLogger; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ProgressBar; import org.micromanager.utils.TextUtils; import org.micromanager.utils.WaitDialog; import bsh.EvalError; import bsh.Interpreter; import com.swtdesigner.SwingResourceManager; /* * Main panel and application class for the MMStudio. */ public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface { public static String LIVE_WINDOW_TITLE = "AcqWindow"; private static final String MICRO_MANAGER_TITLE = "Micro-Manager-S 1.2"; private static final String VERSION = "1.2.12S (alpha)"; private static final long serialVersionUID = 3556500289598574541L; private static final String MAIN_FRAME_X = "x"; private static final String MAIN_FRAME_Y = "y"; private static final String MAIN_FRAME_WIDTH = "width"; private static final String MAIN_FRAME_HEIGHT = "height"; private static final String MAIN_EXPOSURE = "exposure"; private static final String MAIN_PIXEL_TYPE = "pixel_type"; private static final String SYSTEM_CONFIG_FILE = "sysconfig_file"; private static final String MAIN_STRETCH_CONTRAST = "stretch_contrast"; private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN"; private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX"; private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN"; private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX"; private static final String OPEN_ACQ_DIR = "openDataDir"; private static final String SCRIPT_CORE_OBJECT = "mmc"; private static final String SCRIPT_ACQENG_OBJECT = "acq"; private static final String SCRIPT_GUI_OBJECT = "gui"; // GUI components // private JTextField textFieldGain_; private JComboBox comboBinning_; private JComboBox shutterComboBox_; private JTextField textFieldExp_; private SpringLayout springLayout_; private JLabel labelImageDimensions_; private JToggleButton toggleButtonLive_; private JCheckBox autoShutterCheckBox_; private boolean autoShutterOrg_; private boolean shutterOrg_; private MMOptions options_; private boolean runsAsPlugin_; private JToggleButton toggleButtonShutter_; private JComboBox comboPixelType_; // display settings private ContrastSettings contrastSettings8_; private ContrastSettings contrastSettings16_; private GUIColors guiColors_; private ColorModel currentColorModel_; private MMImageWindow imageWin_; private GraphFrame profileWin_; private PropertyEditor propertyBrowser_; private CalibrationListDlg calibrationListDlg_; private AcqControlDlg acqControlWin_; private ArrayList<PluginItem> plugins_; private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg"; private final static String DEFAULT_SCRIPT_FILE_NAME = "MMStartup.bsh"; private String sysConfigFile_; private String startupScriptFile_; private String sysStateFile_ = "MMSystemState.cfg"; private ConfigGroupPad configPad_; private ContrastPanel contrastPanel_; private double interval_; private Timer timer_; private GraphData lineProfileData_; // labels for standard devices private String cameraLabel_; private String zStageLabel_; private String shutterLabel_; private String xyStageLabel_; // applications settings private Preferences mainPrefs_; // MMcore private CMMCore core_; private AcquisitionEngine engine_; private PositionList posList_; private PositionListDlg posListDlg_; private String openAcqDirectory_ = ""; private boolean running_; private boolean liveRunning_ = false; private boolean configChanged_ = false; private StrVector shutters_ = null; private JButton saveConfigButton_; private FastAcqDlg fastAcqWin_; private ScriptPanel scriptPanel_; private SplitView splitView_; private CenterListener centerListener_; private DragListener dragListener_; private ZWheelListener zWheelListener_; private AcquisitionManager acqMgr_; private JMenuBar menuBar_; /** * Callback to update GUI when a change happens in the MMCore. */ public class CoreEventCallback extends MMEventCallback { public CoreEventCallback() { super(); } public void onPropertiesChanged() { updateGUI(true); if (propertyBrowser_ != null) propertyBrowser_.updateStatus(); MMLogger.getLogger().info("Notification from MMCore!"); } } private class PluginItem { public String menuItem = "undefined"; public MMPlugin plugin = null; } /** * Main procedure for stand alone operation. */ public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); MMStudioMainFrame frame = new MMStudioMainFrame(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public MMStudioMainFrame(boolean pluginStatus) { super(); options_ = new MMOptions(); options_.loadSettings(); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem> (); runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; contrastSettings8_ = new ContrastSettings(); contrastSettings16_ = new ContrastSettings(); acqMgr_ = new AcquisitionManager(); sysConfigFile_ = new String(System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME); startupScriptFile_ = new String(System.getProperty("user.dir") + "/" + DEFAULT_SCRIPT_FILE_NAME); // set the location for app preferences mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false); if (!userReg) { // now check system preferences Preferences systemPrefs = Preferences.systemNodeForPackage(this.getClass()); boolean systemReg = systemPrefs.getBoolean(RegistrationDlg.REGISTRATION, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(); dlg.setVisible(true); } } // initialize timer interval_ = 30; ActionListener timerHandler = new ActionListener() { public void actionPerformed(ActionEvent evt) { if (!isImageWindowOpen()) { // stop live acquisition if user closed the window enableLiveMode(false); toggleButtonLive_.doClick(); return; } snapSingleImage(); } }; timer_ = new Timer((int)interval_, timerHandler); timer_.stop(); // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true); contrastSettings8_.min = mainPrefs_.getDouble(CONTRAST_SETTINGS_8_MIN, 0.0); contrastSettings8_.max = mainPrefs_.getDouble(CONTRAST_SETTINGS_8_MAX, 0.0); contrastSettings16_.min = mainPrefs_.getDouble(CONTRAST_SETTINGS_16_MIN, 0.0); contrastSettings16_.max = mainPrefs_.getDouble(CONTRAST_SETTINGS_16_MAX, 0.0); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); setBounds(x, y, 580, 451); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); springLayout_ = new SpringLayout(); getContentPane().setLayout(springLayout_); setTitle(MICRO_MANAGER_TITLE); setBackground(guiColors_.background.get((options_.displayBackground))); // Snap button final JButton buttonSnap = new JButton(); buttonSnap.setIconTextGap(6); buttonSnap.setText("Snap"); buttonSnap.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera.png")); buttonSnap.setFont(new Font("", Font.PLAIN, 10)); buttonSnap.setToolTipText("Snap single image"); buttonSnap.setMaximumSize(new Dimension(0, 0)); buttonSnap.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSnap(); } }); getContentPane().add(buttonSnap); springLayout_.putConstraint(SpringLayout.SOUTH, buttonSnap, 25, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonSnap, 4, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonSnap, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonSnap, 7, SpringLayout.WEST, getContentPane()); // Initialize // Exposure field final JLabel label_1 = new JLabel(); label_1.setFont(new Font("Arial", Font.PLAIN, 10)); label_1.setText("Exposure [ms]"); getContentPane().add(label_1); springLayout_.putConstraint(SpringLayout.EAST, label_1, 198, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, label_1, 111, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, label_1, 39, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, label_1, 23, SpringLayout.NORTH, getContentPane()); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent fe) { try { core_.setExposure(Double.parseDouble(textFieldExp_.getText())); } catch (Exception exp) { handleException(exp); } } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { core_.setExposure(Double.parseDouble(textFieldExp_.getText())); } catch (Exception exp) { handleException(exp); } } }); getContentPane().add(textFieldExp_); springLayout_.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, textFieldExp_, 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, textFieldExp_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, textFieldExp_, 203, SpringLayout.WEST, getContentPane()); // Live button toggleButtonLive_ = new JToggleButton(); toggleButtonLive_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setIconTextGap(6); toggleButtonLive_.setToolTipText("Continuously acquire images"); toggleButtonLive_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonLive_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (toggleButtonLive_.isSelected()){ if (interval_ < 30.0) interval_ = 30.0; // limit the interval to 30ms or more timer_.setDelay((int)interval_); enableLiveMode(true); toggleButtonLive_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/cancel.png")); } else { enableLiveMode(false); toggleButtonLive_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); } } }); toggleButtonLive_.setText("Live"); getContentPane().add(toggleButtonLive_); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7, SpringLayout.WEST, getContentPane()); // Shutter button toggleButtonShutter_ = new JToggleButton(); toggleButtonShutter_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { try { if (toggleButtonShutter_.isSelected()){ setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); toggleButtonShutter_.setToolTipText("Open/close the shutter"); toggleButtonShutter_.setIconTextGap(6); toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonShutter_.setText("Open"); getContentPane().add(toggleButtonShutter_); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonShutter_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonShutter_, 203, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_, 138, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonShutter_, 117, SpringLayout.NORTH, getContentPane()); // Active shutter label final JLabel activeShutterLabel = new JLabel(); activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10)); activeShutterLabel.setText("Shutter"); getContentPane().add(activeShutterLabel); springLayout_.putConstraint(SpringLayout.SOUTH, activeShutterLabel, 108, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, activeShutterLabel, 95, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, activeShutterLabel, 160, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, activeShutterLabel, 113, SpringLayout.WEST, getContentPane()); // Active shutter Combo Box shutterComboBox_ = new JComboBox(); shutterComboBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) core_.setShutterDevice( (String)shutterComboBox_.getSelectedItem()); } catch (Exception e) { handleException(e); } return; } }); getContentPane().add(shutterComboBox_); springLayout_.putConstraint(SpringLayout.SOUTH, shutterComboBox_, 114, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, shutterComboBox_, 92, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, shutterComboBox_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, shutterComboBox_, 170, SpringLayout.WEST, getContentPane()); // Profile final JButton buttonProf = new JButton(); buttonProf.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/chart_curve.png")); buttonProf.setFont(new Font("Arial", Font.PLAIN, 10)); buttonProf.setToolTipText("Open line profile window (requires line selection)"); buttonProf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openLineProfileWindow(); } }); buttonProf.setText("Profile"); getContentPane().add(buttonProf); springLayout_.putConstraint(SpringLayout.SOUTH, buttonProf, 69, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonProf, 48, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonProf, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonProf, 7, SpringLayout.WEST, getContentPane()); menuBar_ = new JMenuBar(); setJMenuBar(menuBar_); final JMenu fileMenu = new JMenu(); fileMenu.setText("File"); menuBar_.add(fileMenu); final JMenuItem openMenuItem = new JMenuItem(); openMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { openAcquisitionData(); } }); openMenuItem.setText("Open Acquisition Data as Image5D......"); fileMenu.add(openMenuItem); fileMenu.addSeparator(); final JMenuItem loadState = new JMenuItem(); loadState.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadSystemState(); } }); loadState.setText("Load System State..."); fileMenu.add(loadState); final JMenuItem saveStateAs = new JMenuItem(); fileMenu.add(saveStateAs); saveStateAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveSystemState(); } }); saveStateAs.setText("Save System State As..."); fileMenu.addSeparator(); final JMenuItem exitMenuItem = new JMenuItem(); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeSequence(); } }); fileMenu.add(exitMenuItem); exitMenuItem.setText("Exit"); final JMenu image5dMenu = new JMenu(); image5dMenu.setText("Image5D"); menuBar_.add(image5dMenu); final JMenuItem closeAllMenuItem = new JMenuItem(); closeAllMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { WindowManager.closeAllWindows(); } }); closeAllMenuItem.setText("Close All"); image5dMenu.add(closeAllMenuItem); final JMenuItem duplicateMenuItem = new JMenuItem(); duplicateMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Duplicate_Image5D duplicate = new Duplicate_Image5D(); duplicate.run(""); } }); duplicateMenuItem.setText("Duplicate"); image5dMenu.add(duplicateMenuItem); final JMenuItem cropMenuItem = new JMenuItem(); cropMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Crop_Image5D crop = new Crop_Image5D(); crop.run(""); } }); cropMenuItem.setText("Crop"); image5dMenu.add(cropMenuItem); final JMenuItem makeMontageMenuItem = new JMenuItem(); makeMontageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Make_Montage makeMontage = new Make_Montage(); makeMontage.run(""); } }); makeMontageMenuItem.setText("Make Montage"); image5dMenu.add(makeMontageMenuItem); final JMenuItem zProjectMenuItem = new JMenuItem(); zProjectMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { //IJ.runPlugIn("Z_Project", ""); Z_Project projection = new Z_Project(); projection.run(""); } }); zProjectMenuItem.setText("Z Project"); image5dMenu.add(zProjectMenuItem); final JMenuItem convertToRgbMenuItem = new JMenuItem(); convertToRgbMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { //IJ.runPlugIn("org/micromanager/Image5D_Stack_to_RGB", ""); Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB(); stackToRGB.run(""); } }); convertToRgbMenuItem.setText("Copy to RGB Stack(z)"); image5dMenu.add(convertToRgbMenuItem); final JMenuItem convertToRgbtMenuItem = new JMenuItem(); convertToRgbtMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { //IJ.runPlugIn("Image5D_Stack_to_RGB_t", ""); Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t(); stackToRGB_t.run(""); } }); convertToRgbtMenuItem.setText("Copy to RGB Stack(t)"); image5dMenu.add(convertToRgbtMenuItem); final JMenuItem convertToStackMenuItem = new JMenuItem(); convertToStackMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { //IJ.runPlugIn("Image5D_to_Stack", ""); Image5D_to_Stack image5DToStack = new Image5D_to_Stack(); image5DToStack.run(""); } }); convertToStackMenuItem.setText("Copy to Stack"); image5dMenu.add(convertToStackMenuItem); final JMenuItem convertToStacksMenuItem = new JMenuItem(); convertToStacksMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { //IJ.runPlugIn("Image5D_to_Stack", ""); Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks(); image5DToStacks.run(""); } }); convertToStacksMenuItem.setText("Copy to Stacks (channels)"); image5dMenu.add(convertToStacksMenuItem); final JMenuItem volumeViewerMenuItem = new JMenuItem(); volumeViewerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer(); volumeViewer.run(""); } }); volumeViewerMenuItem.setText("VolumeViewer"); image5dMenu.add(volumeViewerMenuItem); final JMenuItem splitImageMenuItem = new JMenuItem(); splitImageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Split_Image5D splitImage = new Split_Image5D(); splitImage.run(""); } }); splitImageMenuItem.setText("SplitView"); image5dMenu.add(splitImageMenuItem); final JMenu toolsMenu = new JMenu(); toolsMenu.setText("Tools"); menuBar_.add(toolsMenu); final JMenuItem refreshMenuItem = new JMenuItem(); refreshMenuItem.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "icons/arrow_refresh.png")); refreshMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshMenuItem.setText("Refresh GUI"); toolsMenu.add(refreshMenuItem); final JMenuItem rebuildGuiMenuItem = new JMenuItem(); rebuildGuiMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { initializeGUI(); } }); rebuildGuiMenuItem.setText("Rebuild GUI"); toolsMenu.add(rebuildGuiMenuItem); toolsMenu.addSeparator(); // final JMenuItem scriptingConsoleMenuItem = new JMenuItem(); // toolsMenu.add(scriptingConsoleMenuItem); // scriptingConsoleMenuItem.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // createScriptingConsole(); // scriptingConsoleMenuItem.setText("Scripting Console..."); final JMenuItem scriptPanelMenuItem = new JMenuItem(); toolsMenu.add(scriptPanelMenuItem); scriptPanelMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createScriptPanel(); } }); scriptPanelMenuItem.setText("Script Panel"); final JMenuItem propertyEditorMenuItem = new JMenuItem(); toolsMenu.add(propertyEditorMenuItem); propertyEditorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createPropertyEditor(); } }); propertyEditorMenuItem.setText("Device/Property Browser..."); toolsMenu.addSeparator(); final JMenuItem xyListMenuItem = new JMenuItem(); xyListMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showXYPositionList(); } }); xyListMenuItem.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "icons/application_view_list.png")); xyListMenuItem.setText("XY List..."); toolsMenu.add(xyListMenuItem); final JMenuItem acquisitionMenuItem = new JMenuItem(); acquisitionMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); acquisitionMenuItem.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "icons/film.png")); acquisitionMenuItem.setText("Acquisition..."); toolsMenu.add(acquisitionMenuItem); final JMenuItem sequenceMenuItem = new JMenuItem(); sequenceMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openSequenceDialog(); } }); sequenceMenuItem.setText("Burst Acquisition..."); toolsMenu.add(sequenceMenuItem); final JMenuItem splitViewMenuItem = new JMenuItem(); splitViewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { splitViewDialog(); } }); splitViewMenuItem.setText("Split View..."); toolsMenu.add(splitViewMenuItem); final JCheckBoxMenuItem centerMenuItem = new JCheckBoxMenuItem(); final JCheckBoxMenuItem dragMenuItem = new JCheckBoxMenuItem(); centerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (centerListener_ == null) centerListener_ = new CenterListener(core_); if (!centerListener_.isRunning()) { if (dragListener_ != null && dragListener_.isRunning()) { dragListener_.stop(); dragMenuItem.setSelected(false); } centerListener_.start(); centerMenuItem.setSelected(true); } else { centerListener_.stop(); centerMenuItem.setSelected(false); } } }); centerMenuItem.setText("Click to Center..."); centerMenuItem.setSelected(false); toolsMenu.add(centerMenuItem); dragMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (dragListener_ == null) dragListener_ = new DragListener(core_); if (!dragListener_.isRunning()) { if (centerListener_ != null && centerListener_.isRunning()) { centerListener_.stop(); centerMenuItem.setSelected(false); } dragListener_.start(); dragMenuItem.setSelected(true); } else { dragListener_.stop(); dragMenuItem.setSelected(false); } } }); dragMenuItem.setText("Drag to Move..."); dragMenuItem.setSelected(false); toolsMenu.add(dragMenuItem); toolsMenu.addSeparator(); final JMenuItem configuratorMenuItem = new JMenuItem(); configuratorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { // unload all devices before starting configurator // NS: Save config presets if they were changed. if (configChanged_) { Object[] options = {"Yes","No"}; int n = JOptionPane.showOptionDialog(null,"Save Changed Configuration?","Micro-Manager",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) saveConfigPresets(); configChanged_ = false; } core_.reset(); // run Configurator ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_); configurator.setVisible(true); // re-initialize the system with the new configuration file sysConfigFile_ = configurator.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); initializeGUI(); } catch (Exception e) { handleException(e); return; } } }); configuratorMenuItem.setText("Hardware Configuration Wizard..."); toolsMenu.add(configuratorMenuItem); final JMenuItem calibrationMenuItem = new JMenuItem(); toolsMenu.add(calibrationMenuItem); calibrationMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createCalibrationListDlg(); } }); calibrationMenuItem.setText("Pixel Size Calibration..."); toolsMenu.add(calibrationMenuItem); final JMenuItem loadSystemConfigMenuItem = new JMenuItem(); toolsMenu.add(loadSystemConfigMenuItem); loadSystemConfigMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadConfiguration(); updateTitle(); initializeGUI(); } }); loadSystemConfigMenuItem.setText("Load Hardware Configuration..."); final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem(); saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); updateChannelCombos(); } }); saveConfigurationPresetsMenuItem.setText("Save Configuration Presets"); toolsMenu.add(saveConfigurationPresetsMenuItem); final JMenuItem optionsMenuItem = new JMenuItem(); final MMStudioMainFrame thisInstance = this; optionsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { int oldBufsize = options_.circularBufferSizeMB; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB) try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception exc) { handleException(exc); } } }); optionsMenuItem.setText("Options..."); toolsMenu.add(optionsMenuItem); final JLabel binningLabel = new JLabel(); binningLabel.setFont(new Font("Arial", Font.PLAIN, 10)); binningLabel.setText("Binning"); getContentPane().add(binningLabel); springLayout_.putConstraint(SpringLayout.SOUTH, binningLabel, 88, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, binningLabel, 69, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, binningLabel, 200, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, binningLabel, 112, SpringLayout.WEST, getContentPane()); labelImageDimensions_ = new JLabel(); labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(labelImageDimensions_); springLayout_.putConstraint(SpringLayout.SOUTH, labelImageDimensions_, -5, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, labelImageDimensions_, -25, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, labelImageDimensions_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, labelImageDimensions_, 5, SpringLayout.WEST, getContentPane()); final JLabel pixelTypeLabel = new JLabel(); pixelTypeLabel.setFont(new Font("Arial", Font.PLAIN, 10)); pixelTypeLabel.setText("Pixel type"); getContentPane().add(pixelTypeLabel); springLayout_.putConstraint(SpringLayout.SOUTH, pixelTypeLabel, 64, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, pixelTypeLabel, 43, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, pixelTypeLabel, 197, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, pixelTypeLabel, 111, SpringLayout.WEST, getContentPane()); comboPixelType_ = new JComboBox(); comboPixelType_.setFont(new Font("Arial", Font.PLAIN, 10)); comboPixelType_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changePixelType(); } }); getContentPane().add(comboPixelType_); springLayout_.putConstraint(SpringLayout.SOUTH, comboPixelType_, 66, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, comboPixelType_, 43, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, comboPixelType_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, comboPixelType_, 200, SpringLayout.WEST, getContentPane()); comboBinning_ = new JComboBox(); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeBinning(); } }); getContentPane().add(comboBinning_); springLayout_.putConstraint(SpringLayout.EAST, comboBinning_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, comboBinning_, 200, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, comboBinning_, 91, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, comboBinning_, 68, SpringLayout.NORTH, getContentPane()); configPad_ = new ConfigGroupPad(); //configPad_.setDisplayStyle(options_.displayBackground, guiColors_); configPad_.setFont(new Font("", Font.PLAIN, 10)); getContentPane().add(configPad_); springLayout_.putConstraint(SpringLayout.EAST, configPad_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPad_, 5, SpringLayout.EAST, comboBinning_); final JLabel cameraSettingsLabel = new JLabel(); cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11)); cameraSettingsLabel.setText("Camera settings"); getContentPane().add(cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, cameraSettingsLabel, 211, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, cameraSettingsLabel, 109, SpringLayout.WEST, getContentPane()); final JLabel stateDeviceLabel = new JLabel(); stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11)); stateDeviceLabel.setText("Configuration Presets"); getContentPane().add(stateDeviceLabel); springLayout_.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 5, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, stateDeviceLabel, 455, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, stateDeviceLabel, 305, SpringLayout.WEST, getContentPane()); final JButton buttonAcqSetup = new JButton(); buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2)); buttonAcqSetup.setIconTextGap(1); buttonAcqSetup.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/film.png")); buttonAcqSetup.setToolTipText("Open Acquistion dialog"); buttonAcqSetup.setFont(new Font("Arial", Font.BOLD, 10)); buttonAcqSetup.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); buttonAcqSetup.setText("Acquisition"); getContentPane().add(buttonAcqSetup); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7, SpringLayout.WEST, getContentPane()); autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { core_.setAutoShutter(autoShutterCheckBox_.isSelected()); if (shutterLabel_.length() > 0) try { setShutterButton(core_.getShutterOpen()); } catch (Exception e1) { // do not complain here } if (autoShutterCheckBox_.isSelected()) toggleButtonShutter_.setEnabled(false); else toggleButtonShutter_.setEnabled(true); } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); getContentPane().add(autoShutterCheckBox_); springLayout_.putConstraint(SpringLayout.EAST, autoShutterCheckBox_, 202, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autoShutterCheckBox_, 110, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_, 141, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_, 118, SpringLayout.NORTH, getContentPane()); final JButton refreshButton = new JButton(); refreshButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/arrow_refresh.png")); refreshButton.setFont(new Font("Arial", Font.PLAIN, 10)); refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware"); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshButton.setText("Refresh"); getContentPane().add(refreshButton); springLayout_.putConstraint(SpringLayout.SOUTH, refreshButton, 113, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, refreshButton, 92, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, refreshButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, refreshButton, 7, SpringLayout.WEST, getContentPane()); // add window listeners addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { running_ = false; closeSequence(); } public void windowOpened(WindowEvent e) { // initialize hardware core_ = new CMMCore(); core_.enableDebugLog(options_.debugLogEnabled); // core_.clearLog(); cameraLabel_ = new String(""); shutterLabel_ = new String(""); zStageLabel_ = new String(""); xyStageLabel_ = new String(""); engine_ = new MMAcquisitionEngineMT(); // register callback for MMCore notifications CoreEventCallback cb = new CoreEventCallback(); core_.registerCallback(cb); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception exc) { handleException(exc); } engine_.setCore(core_); posList_ = new PositionList(); engine_.setPositionList(posList_); MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) engine_.setParentGUI(parent); // load configuration from the file sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_); //startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE, startupScriptFile_); if (!options_.doNotAskForConfigFile) { MMIntroDlg introDlg = new MMIntroDlg(VERSION); introDlg.setConfigFile(sysConfigFile_); //introDlg.setScriptFile(startupScriptFile_); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } //startupScriptFile_ = introDlg.getScriptFile(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); //mainPrefs_.put(STARTUP_SCRIPT_FILE, startupScriptFile_); paint(MMStudioMainFrame.this.getGraphics()); // TODO: If there is an error loading the config file, make sure we prompt next time at startup loadSystemConfiguration(); executeStartupScript(); configPad_.setCore(core_); if (parent != null) configPad_.setParentGUI(parent); // initialize controls initializeGUI(); initializePluginMenu(); } }); final JButton setRoiButton = new JButton(); setRoiButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/shape_handles.png")); setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle"); setRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setROI(); } }); getContentPane().add(setRoiButton); springLayout_.putConstraint(SpringLayout.EAST, setRoiButton, 48, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, setRoiButton, 7, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, setRoiButton, 172, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, setRoiButton, 152, SpringLayout.NORTH, getContentPane()); final JButton clearRoiButton = new JButton(); clearRoiButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/arrow_out.png")); clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); clearRoiButton.setToolTipText("Reset Region of Interest to full frame"); clearRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearROI(); } }); getContentPane().add(clearRoiButton); springLayout_.putConstraint(SpringLayout.EAST, clearRoiButton, 93, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, clearRoiButton, 51, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, clearRoiButton, 172, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, clearRoiButton, 152, SpringLayout.NORTH, getContentPane()); final JLabel regionOfInterestLabel = new JLabel(); regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel.setText("ROI"); getContentPane().add(regionOfInterestLabel); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel, 152, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel, 138, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel, 71, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel, 8, SpringLayout.WEST, getContentPane()); /* final JLabel gainLabel = new JLabel(); gainLabel.setFont(new Font("Arial", Font.PLAIN, 10)); gainLabel.setText("Gain"); getContentPane().add(gainLabel); springLayout_.putConstraint(SpringLayout.SOUTH, gainLabel, 108, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, gainLabel, 95, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, gainLabel, 136, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, gainLabel, 113, SpringLayout.WEST, getContentPane()); textFieldGain_ = new JTextField(); textFieldGain_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldGain_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (isCameraAvailable()) { core_.setProperty(core_.getCameraDevice(), MMCoreJ.getG_Keyword_Gain(), textFieldGain_.getText()); } } catch (Exception exp) { handleException(exp); } } }); getContentPane().add(textFieldGain_); springLayout_.putConstraint(SpringLayout.SOUTH, textFieldGain_, 112, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, textFieldGain_, 93, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, textFieldGain_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, textFieldGain_, 203, SpringLayout.WEST, getContentPane()); */ contrastPanel_ = new ContrastPanel(); contrastPanel_.setFont(new Font("", Font.PLAIN, 10)); contrastPanel_.setContrastStretch(stretch); contrastPanel_.setBorder(new LineBorder(Color.black, 1, false)); getContentPane().add(contrastPanel_); springLayout_.putConstraint(SpringLayout.SOUTH, contrastPanel_, -26, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, contrastPanel_, 176, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, contrastPanel_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, contrastPanel_, 7, SpringLayout.WEST, getContentPane()); final JLabel regionOfInterestLabel_1 = new JLabel(); regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel_1.setText("Zoom"); getContentPane().add(regionOfInterestLabel_1); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel_1, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel_1, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1, 177, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1, 114, SpringLayout.WEST, getContentPane()); final JButton zoomInButton = new JButton(); zoomInButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomIn(); } }); zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_in.png")); zoomInButton.setToolTipText("Set Region Of Interest to selected rectangle"); zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomInButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomInButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomInButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomInButton, 154, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomInButton, 113, SpringLayout.WEST, getContentPane()); final JButton zoomOutButton = new JButton(); zoomOutButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomOut(); } }); zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_out.png")); zoomOutButton.setToolTipText("Reset Region of Interest to full frame"); zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomOutButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomOutButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomOutButton, 199, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomOutButton, 157, SpringLayout.WEST, getContentPane()); final JButton addGroupButton_ = new JButton(); addGroupButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (configPad_.addGroup()) { configChanged_ = true; setConfigSaveButtonStatus(configChanged_); } updateGUI(true); } }); addGroupButton_.setToolTipText("Add new group of presets"); if (System.getProperty("os.name").indexOf("Mac OS X") != -1) addGroupButton_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/plus.png")); else addGroupButton_.setText("+"); getContentPane().add(addGroupButton_); springLayout_.putConstraint(SpringLayout.EAST, addGroupButton_, 337, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, addGroupButton_, 295, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, addGroupButton_, 173, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, addGroupButton_, 155, SpringLayout.NORTH, getContentPane()); final JButton removeGroupButton_ = new JButton(); removeGroupButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (configPad_.removeGroup()) { configChanged_ = true; updateGUI(true); setConfigSaveButtonStatus(configChanged_); } } }); removeGroupButton_.setToolTipText("Remove selected group of presets"); if (System.getProperty("os.name").indexOf("Mac OS X") != -1) removeGroupButton_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/minus.png")); else removeGroupButton_.setText("-"); getContentPane().add(removeGroupButton_); springLayout_.putConstraint(SpringLayout.SOUTH, removeGroupButton_, 173, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, removeGroupButton_, 155, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, removeGroupButton_, 382, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, removeGroupButton_, 340, SpringLayout.WEST, getContentPane()); final JButton editPreset_ = new JButton(); editPreset_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (configPad_.editPreset()) { configChanged_ = true; updateGUI(true); setConfigSaveButtonStatus(configChanged_); } } }); editPreset_.setToolTipText("Edit selected preset"); editPreset_.setText("Edit"); getContentPane().add(editPreset_); springLayout_.putConstraint(SpringLayout.EAST, editPreset_, -2, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, editPreset_, -72, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, configPad_, 0, SpringLayout.NORTH, editPreset_); springLayout_.putConstraint(SpringLayout.NORTH, configPad_, 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, editPreset_, 173, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, editPreset_, 155, SpringLayout.NORTH, getContentPane()); final JButton addPresetButton_ = new JButton(); addPresetButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(configPad_.addPreset()) { configChanged_ = true; updateGUI(true); setConfigSaveButtonStatus(configChanged_); } } }); addPresetButton_.setToolTipText("Add preset"); if (System.getProperty("os.name").indexOf("Mac OS X") != -1) addPresetButton_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/plus.png")); else addPresetButton_.setText("+"); getContentPane().add(addPresetButton_); springLayout_.putConstraint(SpringLayout.EAST, addPresetButton_, -114, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, addPresetButton_, -156, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, addPresetButton_, 173, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, addPresetButton_, 155, SpringLayout.NORTH, getContentPane()); final JButton removePresetButton_ = new JButton(); removePresetButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (configPad_.removePreset()) { configChanged_ = true; updateGUI(true); setConfigSaveButtonStatus(configChanged_); } } }); removePresetButton_.setToolTipText("Remove currently selected preset"); if (System.getProperty("os.name").indexOf("Mac OS X") != -1) removePresetButton_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/minus.png")); else removePresetButton_.setText("-"); getContentPane().add(removePresetButton_); springLayout_.putConstraint(SpringLayout.EAST, removePresetButton_, -72, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, removePresetButton_, -114, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, removePresetButton_, 173, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, removePresetButton_, 155, SpringLayout.NORTH, getContentPane()); saveConfigButton_ = new JButton(); saveConfigButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); } }); saveConfigButton_.setToolTipText("Save current presets to the configuration file"); saveConfigButton_.setText("Save"); saveConfigButton_.setEnabled(false); getContentPane().add(saveConfigButton_); springLayout_.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, saveConfigButton_, 510, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, saveConfigButton_, 435, SpringLayout.WEST, getContentPane()); final JButton xyListButton_ = new JButton(); xyListButton_.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "icons/application_view_list.png")); xyListButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showXYPositionList(); } }); xyListButton_.setToolTipText("Refresh all GUI controls directly from the hardware"); xyListButton_.setFont(new Font("Arial", Font.PLAIN, 10)); xyListButton_.setText("XY List"); getContentPane().add(xyListButton_); springLayout_.putConstraint(SpringLayout.EAST, xyListButton_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, xyListButton_, 7, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, xyListButton_, 136, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, xyListButton_, 115, SpringLayout.NORTH, getContentPane()); } private void handleException (Exception e) { String errText = ""; if (options_.debugLogEnabled) errText = "Exception occurred: " + e.getMessage(); else { errText = "Exception occrred: " + e.toString() + "\n"; e.printStackTrace(); } handleError(errText); } private void handleError(String message) { if (timer_ != null) { enableLiveMode(false); } // if (toggleButtonLive_ != null) // toggleButtonLive_.setSelected(false); JOptionPane.showMessageDialog(this, message); } private void updateTitle() { this.setTitle("System: " + sysConfigFile_); } private void updateHistogram(){ if (isImageWindowOpen()) { //ImagePlus imp = IJ.getImage(); ImagePlus imp = imageWin_.getImagePlus(); if (imp != null) { contrastPanel_.setImagePlus(imp); contrastPanel_.setContrastSettings(contrastSettings8_, contrastSettings16_); contrastPanel_.update(); } //contrastPanel_.setImagePlus(imageWin_.getImagePlus()); // ContrastSettings cs = imageWin_.getCurrentContrastSettings(); } } private void updateLineProfile(){ if (!isImageWindowOpen() || profileWin_ == null || !profileWin_.isShowing()) return; calculateLineProfileData(imageWin_.getImagePlus()); profileWin_.setData(lineProfileData_); } private void openLineProfileWindow(){ if (imageWin_ == null || imageWin_.isClosed()) return; calculateLineProfileData(imageWin_.getImagePlus()); if (lineProfileData_ == null) return; profileWin_ = new GraphFrame(); profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); profileWin_.setData(lineProfileData_); profileWin_.setAutoScale(); profileWin_.setTitle("Live line profile"); profileWin_.setBackground(guiColors_.background.get((options_.displayBackground))); profileWin_.setVisible(true); } private void calculateLineProfileData(ImagePlus imp){ // generate line profile Roi roi = imp.getRoi(); if (roi==null || !roi.isLine()) { // if there is no line ROI, create one Rectangle r = imp.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi==null) { iXROI += iWidth/2; iYROI += iHeight/2; } roi = new Line(iXROI-iWidth/4, iYROI-iWidth/4, iXROI + iWidth/4, iYROI + iHeight/4); imp.setRoi(roi); roi = imp.getRoi(); } ImageProcessor ip = imp.getProcessor(); ip.setInterpolate(true); Line line = (Line)roi; if (lineProfileData_ == null) lineProfileData_ = new GraphData(); lineProfileData_.setData(line.getPixels()); } private void setROI() { if (imageWin_ == null || imageWin_.isClosed()) return; Roi roi = imageWin_.getImagePlus().getRoi(); try { if (roi==null) { // if there is no ROI, create one ImagePlus imp = imageWin_.getImagePlus(); Rectangle r = imp.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi==null) { iWidth /= 2; iHeight /= 2; iXROI += iWidth/2; iYROI += iHeight/2; } imp.setRoi(iXROI, iYROI, iWidth, iHeight); roi = imp.getRoi(); } if (roi.getType() != Roi.RECTANGLE) { handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI."); return; } Rectangle r = roi.getBoundingRect(); core_.setROI(r.x, r.y, r.width, r.height); updateStaticInfo(); } catch (Exception e) { handleException(e); } } private void clearROI() { try { core_.clearROI(); updateStaticInfo(); } catch (Exception e) { handleException(e); } } private boolean openImageWindow(){ try { ImageProcessor ip; long byteDepth = core_.getBytesPerPixel(); long channels = core_.getNumberOfChannels(); if (byteDepth == 1 && channels == 1){ ip = new ByteProcessor((int)core_.getImageWidth(), (int)core_.getImageHeight()); if (contrastSettings8_.getRange() == 0.0) ip.setMinAndMax(0, 255); else ip.setMinAndMax(contrastSettings8_.min, contrastSettings8_.max); } else if (byteDepth == 2 && channels == 1) { ip = new ShortProcessor((int)core_.getImageWidth(), (int)core_.getImageHeight()); if (contrastSettings16_.getRange() == 0.0) ip.setMinAndMax(0, 65535); else ip.setMinAndMax(contrastSettings16_.min, contrastSettings16_.max); } else if (byteDepth == 0) { handleError("Imaging device not initialized"); return false; } else if (byteDepth ==1 && channels==4){ // assuming RGB32 format ip = new ColorProcessor((int)core_.getImageWidth(), (int)core_.getImageHeight()); if (contrastSettings8_.getRange() == 0.0) ip.setMinAndMax(0, 255); else ip.setMinAndMax(contrastSettings8_.min, contrastSettings8_.max); }else { handleError("Unsupported pixel depth: " + core_.getBytesPerPixel() + " byte(s) and " + channels + " channel(s)."); return false; } ip.setColor(Color.black); if (currentColorModel_ != null) ip.setColorModel(currentColorModel_); ip.fill(); ImagePlus imp = new ImagePlus(LIVE_WINDOW_TITLE, ip); if (imageWin_ != null) { imageWin_.dispose(); imageWin_.savePosition(); imageWin_ = null; } imageWin_ = new MMImageWindow(imp); imageWin_.setContrastSettings(contrastSettings8_, contrastSettings16_); imageWin_.setBackground(guiColors_.background.get((options_.displayBackground))); setIJCal(imageWin_); // notify processes that need to attach to this acquisition window: if (centerListener_ != null && centerListener_.isRunning()) centerListener_.attach(imp); if (dragListener_ != null && dragListener_.isRunning()) dragListener_.attach(imp); // add listener to the IJ window to detect when it closes WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { // remember LUT so that a new window can be opened with the same LUT if (imageWin_.getImagePlus().getProcessor().isPseudoColorLut()) currentColorModel_ = imageWin_.getImagePlus().getProcessor().getColorModel(); imageWin_ = null; contrastPanel_.setImagePlus(null); } }; WindowListener wndFocus = new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { updateHistogram(); } }; WindowListener wndActive = new WindowAdapter() { public void windowActivated(WindowEvent e) { updateHistogram(); } }; imageWin_.addWindowListener(wndCloser); imageWin_.addWindowListener(wndFocus); imageWin_.addWindowListener(wndActive); } catch (Exception e){ handleException(e); return false; } return true; } /** * Returns instance of the core uManager object; */ public CMMCore getMMCore() { return core_; } protected void saveConfigPresets() { MicroscopeModel model = new MicroscopeModel(); try { model.loadFromFile(sysConfigFile_); model.createSetupConfigsFromHardware(core_); model.createResolutionsFromHardware(core_); JFileChooser fc = new JFileChooser(); boolean saveFile = true; File f; do { fc.setSelectedFile(new File(model.getFileName())); int retVal = fc.showSaveDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { f = fc.getSelectedFile(); // check if file already exists if( f.exists() ) { int sel = JOptionPane.showConfirmDialog(this, "Overwrite " + f.getName(), "File Save", JOptionPane.YES_NO_OPTION); if(sel == JOptionPane.YES_OPTION) saveFile = true; else saveFile = false; } } else { return; } } while (saveFile == false); model.saveToFile(f.getAbsolutePath()); sysConfigFile_ = f.getAbsolutePath(); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); } catch (MMConfigFileException e) { handleException(e); } } protected void setConfigSaveButtonStatus(boolean changed) { saveConfigButton_.setEnabled(changed); } /** * Open an existing acquisition directory and build image5d window. * */ protected void openAcquisitionData() { // choose the directory JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fc.setSelectedFile(new File(openAcqDirectory_)); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); if (f.isDirectory()) { openAcqDirectory_ = f.getAbsolutePath(); } else { openAcqDirectory_ = f.getParent(); } ProgressBar progressBar = null; AcquisitionData ad = new AcquisitionData(); try { // attempt to open metafile ad.load(openAcqDirectory_); // create image 5d Image5D img5d = new Image5D(openAcqDirectory_, ad.getImageJType(), ad.getImageWidth(), ad.getImageHeight(), ad.getNumberOfChannels(), ad.getNumberOfSlices(), ad.getNumberOfFrames(), false); img5d.setCalibration(ad.ijCal()); Color colors[] = ad.getChannelColors(); String names[] = ad.getChannelNames(); if (colors != null && names != null) for (int i=0; i<ad.getNumberOfChannels(); i++) { ChannelCalibration chcal = new ChannelCalibration(); // set channel name chcal.setLabel(names[i]); img5d.setChannelCalibration(i+1, chcal); // set color img5d.setChannelColorModel(i+1, ChannelDisplayProperties.createModelFromColor(colors[i])); } progressBar = new ProgressBar ("Opening File...", 0, ad.getNumberOfChannels() * ad.getNumberOfFrames() * ad.getNumberOfSlices() ); // set pixels int singleImageCounter = 0; for (int i=0; i<ad.getNumberOfFrames(); i++) { for (int j=0; j<ad.getNumberOfChannels(); j++) { for (int k=0; k<ad.getNumberOfSlices(); k++) { img5d.setCurrentPosition(0, 0, j, k, i); // read the file // insert pixels into the 5d image Object img = ad.getPixels(i, j, k); if (img != null) { img5d.setPixels(img); // set display settings for channels if (k==0 && i==0) { DisplaySettings ds[] = ad.getChannelDisplaySettings(); if (ds != null) { // display properties are recorded in metadata use them... double min = ds[j].min; double max = ds[j].max; img5d.setChannelMinMax(j+1, min, max); } else { // ...if not, autoscale channels based on the first slice of the first frame ImageStatistics stats = img5d.getStatistics(); // get uncalibrated stats double min = stats.min; double max = stats.max; img5d.setChannelMinMax(j+1, min, max); } } } else { // gap detected, let's try to fill in by using the most recent channel data // NOTE: we assume that the gap is only in the frame dimension // we don't know how to deal with z-slice gaps !!!! // TODO: handle the case with Z-position gaps if (i>0) { Object previousImg = img5d.getPixels(j+1, k+1, i); if (previousImg != null) img5d.setPixels(previousImg, j+1, k+1, i + 1); } } } } singleImageCounter++; progressBar.setProgress(singleImageCounter); progressBar.update(progressBar.getGraphics()); } // pop-up 5d image window Image5DWindow i5dWin = new Image5DWindow(img5d); i5dWin.setBackground(guiColors_.background.get((options_.displayBackground))); if (ad.getNumberOfChannels()==1) img5d.setDisplayMode(ChannelControl.ONE_CHANNEL_COLOR); else img5d.setDisplayMode(ChannelControl.OVERLAY); i5dWin.setAcquitionEngine(engine_); i5dWin.setAcquisitionData(ad); i5dWin.setAcqSavePath(openAcqDirectory_); img5d.changes = false; } catch (MMAcqDataException e) { handleError(e.getMessage()); } finally { if (progressBar != null) { progressBar.setVisible(false); progressBar = null; } } } } protected void zoomOut() { if (!isImageWindowOpen()) return; Rectangle r = imageWin_.getCanvas().getBounds(); imageWin_.getCanvas().zoomOut(r.width/2, r.height/2); } protected void zoomIn() { if (!isImageWindowOpen()) return; Rectangle r = imageWin_.getCanvas().getBounds(); imageWin_.getCanvas().zoomIn(r.width/2, r.height/2); } protected void changeBinning() { try { if (isCameraAvailable()) { Object item = comboBinning_.getSelectedItem(); if (item != null) core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString()); } } catch (Exception e) { handleException(e); } updateStaticInfo(); } private void createPropertyEditor() { if (propertyBrowser_ != null) propertyBrowser_.dispose(); propertyBrowser_ = new PropertyEditor(); propertyBrowser_.setVisible(true); propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); propertyBrowser_.setCore(core_); propertyBrowser_.setParentGUI(this); } private void createCalibrationListDlg() { if (calibrationListDlg_ != null) calibrationListDlg_.dispose(); calibrationListDlg_ = new CalibrationListDlg(core_, options_); calibrationListDlg_.setVisible(true); calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //calibrationListDlg_.setCore(core_); calibrationListDlg_.setParentGUI(this); } private void createScriptPanel() { if (scriptPanel_ == null) { scriptPanel_ = new ScriptPanel(core_, options_); scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_); scriptPanel_.setParentGUI(this); scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground))); } scriptPanel_.setVisible(true); } private void updateStaticInfo(){ try { double zPos = 0.0; String dimText = "Image size: " + core_.getImageWidth() + " X " + core_.getImageHeight() + " X " + core_.getBytesPerPixel() + ", Intensity range: " + core_.getImageBitDepth() + " bits"; double pixSizeUm = core_.getPixelSizeUm(); if (pixSizeUm > 0.0) dimText += ", " + TextUtils.FMT0.format(pixSizeUm*1000) + "nm/pix"; //dimText += ", " + TextUtils.FMT3.format(pixSizeUm) + "um/pix"; else dimText += ", uncalibrated"; if (zStageLabel_.length() > 0) { zPos = core_.getPosition(zStageLabel_); dimText += ", Z=" + TextUtils.FMT2.format(zPos) + "um"; } if(xyStageLabel_.length() > 0) { double x[] = new double[1]; double y[] = new double[1]; core_.getXYPosition(xyStageLabel_, x, y); dimText += ", XY=(" + TextUtils.FMT2.format(x[0]) + "," + TextUtils.FMT2.format(y[0]) + ")um"; } labelImageDimensions_.setText(dimText); } catch (Exception e){ handleException(e); } } private void setShutterButton(boolean state) { if (state) { toggleButtonShutter_.setSelected(true); toggleButtonShutter_.setText("Close"); } else { toggleButtonShutter_.setSelected(false); toggleButtonShutter_.setText("Open"); } } private void changePixelType() { try { if (isCameraAvailable()) { Object item = comboPixelType_.getSelectedItem(); if (item != null) core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_PixelType(), item.toString()); long bitDepth = core_.getImageBitDepth(); contrastPanel_.setPixelBitDepth((int)bitDepth, true); } } catch (Exception e) { handleException(e); } updateStaticInfo(); } // public interface available for scripting access public void snapSingleImage(){ try { core_.setExposure(Double.parseDouble(textFieldExp_.getText())); updateImage(); } catch (Exception e){ handleException(e); } } public Object getPixels(){ if (imageWin_ != null) return imageWin_.getImagePlus().getProcessor().getPixels(); return null; } public void setPixels(Object obj){ if (imageWin_ == null) { return; } imageWin_.getImagePlus().getProcessor().setPixels(obj); } public int getImageHeight(){ if (imageWin_ != null) return imageWin_.getImagePlus().getHeight(); return 0; } public int getImageWidth(){ if (imageWin_ != null) return imageWin_.getImagePlus().getWidth(); return 0; } public int getImageDepth(){ if (imageWin_ != null) return imageWin_.getImagePlus().getBitDepth(); return 0; } public ImageProcessor getImageProcessor(){ if (imageWin_ == null) return null; return imageWin_.getImagePlus().getProcessor(); } private boolean isCameraAvailable() { return cameraLabel_.length() > 0; } public boolean isImageWindowOpen() { if (imageWin_ == null || imageWin_.isClosed()) return false; else return true; } public void updateImageGUI() { updateHistogram(); } public void enableLiveMode(boolean enable){ try { if (enable){ if (timer_.isRunning()) return; if (!isImageWindowOpen()) openImageWindow(); // Set ImageJ pixel calibration setIJCal(imageWin_); // this is needed to clear the subtite, should be folded into drawInfo imageWin_.getGraphics().clearRect(0,0,imageWin_.getWidth(),40); imageWin_.drawInfo(imageWin_.getGraphics()); imageWin_.toFront(); // turn off auto shutter and open the shutter autoShutterOrg_ = core_.getAutoShutter(); if (shutterLabel_.length() > 0) shutterOrg_ = core_.getShutterOpen(); core_.setAutoShutter(false); // Hide the autoShutter Checkbox autoShutterCheckBox_.setEnabled(false); shutterLabel_ = core_.getShutterDevice(); // only open the shutter when we have one and the Auto shutter checkbox was checked if ((shutterLabel_.length() > 0) && autoShutterOrg_) core_.setShutterOpen(true); // attch mouse wheel listener to control focus: if (zWheelListener_ == null) zWheelListener_ = new ZWheelListener(core_); zWheelListener_.start(); timer_.start(); toggleButtonLive_.setText("Stop"); // Only hide the shutter checkbox if we are in autoshuttermode if (autoShutterOrg_) toggleButtonShutter_.setEnabled(false); liveRunning_ = true; } else { if (!timer_.isRunning()) return; timer_.stop(); if (zWheelListener_ != null) zWheelListener_.stop(); toggleButtonLive_.setText("Live"); // restore auto shutter and close the shutter if (shutterLabel_.length() > 0) core_.setShutterOpen(shutterOrg_); core_.setAutoShutter(autoShutterOrg_); if (autoShutterOrg_) toggleButtonShutter_.setEnabled(false); else toggleButtonShutter_.setEnabled(true); liveRunning_ = false; autoShutterCheckBox_.setEnabled(true); } } catch (Exception err) { JOptionPane.showMessageDialog(this, err.getMessage()); } } public boolean getLiveMode() { return liveRunning_; } public boolean updateImage() { try { if (!isImageWindowOpen()){ // stop live acquistion if the window is not open enableLiveMode(false); return true; // nothing to do } long channels = core_.getNumberOfChannels(); long bpp = core_.getBytesPerPixel(); // warn the user if image dimensions do not match the current window if (imageWin_.getImagePlus().getProcessor().getWidth() != core_.getImageWidth() || imageWin_.getImagePlus().getProcessor().getHeight() != core_.getImageHeight() || imageWin_.getImagePlus().getBitDepth() != bpp * 8 * channels) { // 32-bit RGB image format is a special case with 24-bit pixel depth but physically // using 32-bit pixels if (!(channels == 4 && bpp == 1 && imageWin_.getImagePlus().getBitDepth() == 24)) { // open a new window, remember old colormodel if (imageWin_.getImagePlus().getProcessor().isPseudoColorLut()) currentColorModel_ = imageWin_.getImagePlus().getProcessor().getColorModel(); imageWin_.close(); openImageWindow(); } } // update image window if (channels > 1) { if (channels != 4 && bpp != 1) { handleError("Unsupported image format."); return false; } } core_.snapImage(); Object img; if (channels == 1) img = core_.getImage(); else { img = core_.getRGB32Image(); } imageWin_.getImagePlus().getProcessor().setPixels(img); // update related windows updateHistogram(); updateLineProfile(); imageWin_.getImagePlus().updateAndDraw(); imageWin_.getCanvas().paint(imageWin_.getCanvas().getGraphics()); // update coordinate and pixel info in imageJ by simulating mouse move Point pt = imageWin_.getCanvas().getCursorLoc(); imageWin_.getImagePlus().mouseMoved(pt.x, pt.y); } catch (Exception e){ handleException(e); return false; } return true; } public boolean displayImage(Object pixels) { try { if (!isImageWindowOpen()){ openImageWindow(); } int byteLength = 0; if (pixels instanceof byte[]) { byte bytePixels[] = (byte[])pixels; byteLength = bytePixels.length; } else if (pixels instanceof short[]) { short bytePixels[] = (short[])pixels; byteLength = bytePixels.length * 2; } else return false; // can't handle // warn the user if image dimensions do not match the current window if (imageWin_.getImagePlus().getProcessor().getWidth() * imageWin_.getImagePlus().getProcessor().getHeight() * imageWin_.getImagePlus().getBitDepth()/8 != byteLength) { openImageWindow(); } // update image window imageWin_.getImagePlus().getProcessor().setPixels(pixels); imageWin_.getImagePlus().updateAndDraw(); imageWin_.getCanvas().paint(imageWin_.getCanvas().getGraphics()); // update related windows updateHistogram(); updateLineProfile(); // update coordinate and pixel info in imageJ by simulating mouse move Point pt = imageWin_.getCanvas().getCursorLoc(); imageWin_.getImagePlus().mouseMoved(pt.x, pt.y); } catch (Exception e){ handleException(e); return false; } return true; } private void doSnap() { try { if (!isImageWindowOpen()) if (!openImageWindow()) handleError("Image window open failed"); imageWin_.toFront(); setIJCal(imageWin_); // this is needed to clear the subtite, should be folded into drawInfo imageWin_.getGraphics().clearRect(0,0,imageWin_.getWidth(),40); imageWin_.drawInfo(imageWin_.getGraphics()); String expStr = textFieldExp_.getText(); if (expStr.length() > 0) { core_.setExposure(Double.parseDouble(expStr)); updateImage(); } else handleError("Exposure field is empty!"); } catch (Exception e){ handleException(e); } } public void initializeGUI(){ try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); engine_.setZStageDevice(zStageLabel_); if (cameraLabel_.length() > 0) { // pixel type combo if (comboPixelType_.getItemCount() > 0) comboPixelType_.removeAllItems(); StrVector pixTypes = core_.getAllowedPropertyValues(cameraLabel_, MMCoreJ.getG_Keyword_PixelType()); ActionListener[] listeners = comboPixelType_.getActionListeners(); for (int i=0; i<listeners.length; i++) comboPixelType_.removeActionListener(listeners[i]); for (int i=0; i<pixTypes.size(); i++){ comboPixelType_.addItem(pixTypes.get(i)); } for (int i=0; i<listeners.length; i++) comboPixelType_.addActionListener(listeners[i]); // binning combo if (comboBinning_.getItemCount() > 0) comboBinning_.removeAllItems(); StrVector binSizes = core_.getAllowedPropertyValues(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); listeners = comboBinning_.getActionListeners(); for (int i=0; i<listeners.length; i++) comboBinning_.removeActionListener(listeners[i]); for (int i=0; i<binSizes.size(); i++){ comboBinning_.addItem(binSizes.get(i)); } comboBinning_.setMaximumRowCount((int)binSizes.size()); if (binSizes.size() == 0) { comboBinning_.setEditable(true); } else { comboBinning_.setEditable(false); } for (int i=0; i<listeners.length; i++) comboBinning_.addActionListener(listeners[i]); } // active shutter combo try { shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice); } catch (Exception e){ //System.println(DeviceType.ShutterDevice); e.printStackTrace(); handleException(e); } if (shutters_ != null) { String items[] = new String[(int)shutters_.size()]; //items[0] = ""; for (int i=0; i<shutters_.size(); i++) items[i] = shutters_.get(i); GUIUtils.replaceComboContents(shutterComboBox_, items); String activeShutter = core_.getShutterDevice(); if (activeShutter != null) shutterComboBox_.setSelectedItem(activeShutter); else shutterComboBox_.setSelectedItem(""); } updateGUI(true); } catch (Exception e){ handleException(e); } } private void initializePluginMenu() { // add plugin menu items if (plugins_.size() > 0) { final JMenu pluginMenu = new JMenu(); pluginMenu.setText("Plugins"); menuBar_.add(pluginMenu); for (int i=0; i<plugins_.size(); i++) { final JMenuItem newMenuItem = new JMenuItem(); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { System.out.println("Plugin command: " + e.getActionCommand()); // find the coresponding plugin for (int i=0; i<plugins_.size(); i++) if (plugins_.get(i).menuItem.equals(e.getActionCommand())) { plugins_.get(i).plugin.show(); break; } // if (plugins_.get(i).plugin == null) { // hcsPlateEditor_ = new PlateEditor(MMStudioMainFrame.this); // hcsPlateEditor_.setVisible(true); } }); newMenuItem.setText(plugins_.get(i).menuItem); pluginMenu.add(newMenuItem); } } // add help menu item final JMenu helpMenu = new JMenu(); helpMenu.setText("Help"); menuBar_.add(helpMenu); final JMenuItem aboutMenuItem = new JMenuItem(); aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MMAboutDlg dlg = new MMAboutDlg(); String versionInfo = "MM Studio version: " + VERSION; versionInfo += "\n" + core_.getVersionInfo(); versionInfo += "\n" + core_.getAPIVersionInfo(); versionInfo += "\nUser: " + core_.getUserId(); versionInfo += "\nHost: " + core_.getHostName(); dlg.setVersionInfo(versionInfo); dlg.setVisible(true); } }); aboutMenuItem.setText("About..."); helpMenu.add(aboutMenuItem); } public void updateGUI(boolean updateConfigPadStructure){ try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); // camera settings if (isCameraAvailable()) { double exp = core_.getExposure(); textFieldExp_.setText(Double.toString(exp)); // textFieldGain_.setText(core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Gain())); String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); GUIUtils.setComboSelection(comboBinning_, binSize); String pixType = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_PixelType()); GUIUtils.setComboSelection(comboPixelType_, pixType); long bitDepth = core_.getImageBitDepth(); contrastPanel_.setPixelBitDepth((int)bitDepth, false); } if (!timer_.isRunning()) { autoShutterCheckBox_.setSelected(core_.getAutoShutter()); boolean shutterOpen = core_.getShutterOpen(); setShutterButton(shutterOpen); if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } autoShutterOrg_ = core_.getAutoShutter(); } // active shutter combo if (shutters_ != null) { String activeShutter = core_.getShutterDevice(); if (activeShutter != null) shutterComboBox_.setSelectedItem(activeShutter); else shutterComboBox_.setSelectedItem(""); } // state devices if (updateConfigPadStructure && (configPad_ != null)) configPad_.refreshStructure(); // update Channel menus in Multi-dimensional acquisition dialog updateChannelCombos (); } catch (Exception e){ handleException(e); } updateStaticInfo(); updateTitle(); } public boolean okToAcquire() { return !timer_.isRunning(); } public void stopAllActivity(){ enableLiveMode(false); } public void refreshImage(){ if (imageWin_ != null) imageWin_.getImagePlus().updateAndDraw(); } private void cleanupOnClose() { // NS: Save config presets if they were changed. if (configChanged_) { Object[] options = {"Yes","No"}; int n = JOptionPane.showOptionDialog(null,"Save Changed Configuration?","Micro-Manager",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) saveConfigPresets(); } timer_.stop(); if (imageWin_ != null) { imageWin_.close(); imageWin_.dispose(); } //if (histWin_ != null) // histWin_.dispose(); if (profileWin_ != null) profileWin_.dispose(); // if (scriptFrame_ != null) // scriptFrame_.dispose(); if (scriptPanel_ != null) scriptPanel_.closePanel(); if (propertyBrowser_ != null) propertyBrowser_.dispose(); if (acqControlWin_ != null) acqControlWin_.dispose(); if (engine_ != null) engine_.shutdown(); // dispose plugins for (int i=0; i<plugins_.size(); i++) plugins_.get(i).plugin.dispose(); try { core_.reset(); } catch(Exception err) { handleException(err); } } private void saveSettings() { Rectangle r = this.getBounds(); mainPrefs_.putInt(MAIN_FRAME_X, r.x); mainPrefs_.putInt(MAIN_FRAME_Y, r.y); mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width); mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height); mainPrefs_.putDouble(CONTRAST_SETTINGS_8_MIN, contrastSettings8_.min); mainPrefs_.putDouble(CONTRAST_SETTINGS_8_MAX, contrastSettings8_.max); mainPrefs_.putDouble(CONTRAST_SETTINGS_16_MIN, contrastSettings16_.min); mainPrefs_.putDouble(CONTRAST_SETTINGS_16_MAX, contrastSettings16_.max); mainPrefs_.putBoolean(MAIN_STRETCH_CONTRAST, contrastPanel_.isContrastStretch()); mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_); // save field values from the main window // NOTE: automatically restoring these values on startup may cause problems mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText()); if (comboPixelType_.getSelectedItem() != null) mainPrefs_.put(MAIN_PIXEL_TYPE, comboPixelType_.getSelectedItem().toString()); // NOTE: do not save auto shutter state // mainPrefs_.putBoolean(MAIN_AUTO_SHUTTER, autoShutterCheckBox_.isSelected()); } private void loadConfiguration() { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new CfgFileFilter()); fc.setSelectedFile(new File(sysConfigFile_)); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); sysConfigFile_ = f.getAbsolutePath(); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); } } private void loadSystemState() { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new CfgFileFilter()); fc.setSelectedFile(new File(sysStateFile_)); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); sysStateFile_ = f.getAbsolutePath(); try { //WaitDialog waitDlg = new WaitDialog("Loading saved state, please wait..."); //waitDlg.showDialog(); core_.loadSystemState(sysStateFile_); //waitDlg.closeDialog(); initializeGUI(); } catch (Exception e) { handleException(e); return; } } } private void saveSystemState() { JFileChooser fc = new JFileChooser(); boolean saveFile = true; File f; do { fc.setSelectedFile(new File(sysStateFile_)); int retVal = fc.showSaveDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { f = fc.getSelectedFile(); // check if file already exists if( f.exists() ) { int sel = JOptionPane.showConfirmDialog( this, "Overwrite " + f.getName(), "File Save", JOptionPane.YES_NO_OPTION); if(sel == JOptionPane.YES_OPTION) saveFile = true; else saveFile = false; } } else { return; } } while (saveFile == false); sysStateFile_ = f.getAbsolutePath(); try { core_.saveSystemState(sysStateFile_); } catch (Exception e) { handleException(e); return; } } public void closeSequence() { if (engine_ != null && engine_.isAcquisitionRunning()) { int result = JOptionPane.showConfirmDialog(this, "Acquisition in progress. Are you sure you want to exit and discard all data?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.NO_OPTION) return; } cleanupOnClose(); saveSettings(); configPad_.saveSettings(); options_.saveSettings(); dispose(); if (!runsAsPlugin_) System.exit(0); else { ImageJ ij = IJ.getInstance(); if (ij != null) ij.quit(); } } public void applyContrastSettings(ContrastSettings contrast8, ContrastSettings contrast16) { contrastPanel_.applyContrastSettings(contrast8, contrast16); } public ContrastSettings getContrastSettings() { // TODO Auto-generated method stub return null; } public boolean is16bit() { if (isImageWindowOpen() && imageWin_.getImagePlus().getProcessor() instanceof ShortProcessor) return true; return false; } public boolean isRunning() { return running_; } /** * Executes the beanShell script. * This script instance only supports commands directed to the core object. */ private void executeStartupScript() { // execute startup script File f = new File(startupScriptFile_); if (startupScriptFile_.length() > 0 && f.exists()) { WaitDialog waitDlg = new WaitDialog("Executing startup script, please wait..."); waitDlg.showDialog(); Interpreter interp = new Interpreter(); try { // insert core object only interp.set(SCRIPT_CORE_OBJECT, core_); interp.set(SCRIPT_ACQENG_OBJECT, engine_); interp.set(SCRIPT_GUI_OBJECT, this); // read text file and evaluate interp.eval(TextUtils.readTextFile(startupScriptFile_)); } catch (IOException exc) { handleException(exc); } catch (EvalError exc) { handleException(exc); } finally { waitDlg.closeDialog(); } } } /** * Loads sytem configuration from the cfg file. */ private void loadSystemConfiguration() { WaitDialog waitDlg = new WaitDialog("Loading system configuration, please wait..."); waitDlg.showDialog(); try { if (sysConfigFile_.length() > 0) { // remember the selected file name core_.loadSystemConfiguration(sysConfigFile_); //waitDlg.closeDialog(); } } catch (Exception err) { //handleException(err); // handle long error messages waitDlg.closeDialog(); LargeMessageDlg dlg = new LargeMessageDlg("Configuration error log", err.getMessage()); dlg.setVisible(true); } waitDlg.closeDialog(); } /** * Opens Acquisition dialog. */ private void openAcqControlDialog() { try { if (acqControlWin_ == null) { acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this); } if (acqControlWin_.isActive()) acqControlWin_.setTopPosition(); acqControlWin_.setVisible(true); // TODO: this call causes a strange exception the first time the dialog is created // something to do with the order in which combo box creation is performed //acqControlWin_.updateGroupsCombo(); } catch(Exception exc) { exc.printStackTrace(); handleError(exc.getMessage() + "\nAcquistion window failed to open due to invalid or corrupted settings.\n" + "Try resetting registry settings to factory defaults (Menu Tools|Options)."); } } /** * Opens streaming sequence acquisition dialog. */ protected void openSequenceDialog() { try { if (fastAcqWin_ == null) { fastAcqWin_ = new FastAcqDlg(core_, this); } fastAcqWin_.setVisible(true); } catch(Exception exc) { exc.printStackTrace(); handleError(exc.getMessage() + "\nSequence window failed to open due to internal error."); } } /** * Opens Split View dialog. */ protected void splitViewDialog() { try { if (splitView_ == null) { splitView_ = new SplitView(core_, options_); } splitView_.setVisible(true); } catch(Exception exc) { exc.printStackTrace(); handleError(exc.getMessage() + "\nSplit View Window failed to open due to internal error."); } } /** * Opens a dialog to record stage positions */ public void showXYPositionList() { if (posListDlg_ == null) { posListDlg_ = new PositionListDlg(core_, posList_, options_); posListDlg_.setBackground(guiColors_.background.get((options_.displayBackground))); } posListDlg_.setVisible(true); } private void updateChannelCombos () { if (this.acqControlWin_ != null) this.acqControlWin_.updateChannelAndGroupCombo(); } public void setConfigChanged(boolean status) { configChanged_ = status; setConfigSaveButtonStatus(configChanged_); } /* * Changes background color of this window */ public void setBackgroundStyle(String backgroundType) { setBackground(guiColors_.background.get((options_.displayBackground))); paint(MMStudioMainFrame.this.getGraphics()); //configPad_.setDisplayStyle(options_.displayBackground, guiColors_); if (acqControlWin_ != null) acqControlWin_.setBackgroundStyle(options_.displayBackground); if (profileWin_ != null) profileWin_.setBackground(guiColors_.background.get((options_.displayBackground))); if (posListDlg_ != null) posListDlg_.setBackground(guiColors_.background.get((options_.displayBackground))); if (imageWin_ != null) imageWin_.setBackground(guiColors_.background.get((options_.displayBackground))); if (fastAcqWin_ != null) fastAcqWin_.setBackground(guiColors_.background.get((options_.displayBackground))); if (scriptPanel_ != null) scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground))); if (splitView_ != null) splitView_.setBackground(guiColors_.background.get((options_.displayBackground))); } public String getBackgroundStyle() { return options_.displayBackground; } // Set ImageJ pixel calibration private void setIJCal(MMImageWindow imageWin) { if (imageWin != null) { ImagePlus imp = imageWin_.getImagePlus(); if (imp != null) { double pixSizeUm = core_.getPixelSizeUm(); Calibration cal = new Calibration(); if (pixSizeUm > 0) { cal.setUnit("um"); cal.pixelWidth = pixSizeUm; cal.pixelHeight = pixSizeUm; } imp.setCalibration(cal); } } } // Scripting interface private class ExecuteAcq implements Runnable { public ExecuteAcq() { } public void run() { if (acqControlWin_ != null) acqControlWin_.runAcquisition(); } } private class LoadAcq implements Runnable { private String filePath_; public LoadAcq(String path) { filePath_ = path; } public void run() { // stop current acquisition if any engine_.shutdown(); // load protocol if (acqControlWin_ != null) acqControlWin_.loadAcqSettingsFromFile(filePath_); } } private class RefreshPositionList implements Runnable { public RefreshPositionList() { } public void run() { if (posListDlg_ != null) { posListDlg_.setPositionList(posList_); engine_.setPositionList(posList_); } } } private void testForAbortRequests() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) throw new MMScriptException("Script interrupted by the user!"); } } public void startBurstAcquisition() throws MMScriptException { testForAbortRequests(); if (fastAcqWin_ != null) { fastAcqWin_.start(); } } public void runBurstAcquisition() throws MMScriptException { testForAbortRequests(); if (fastAcqWin_ == null) return; fastAcqWin_.start(); try { while (fastAcqWin_.isBusy()) { Thread.sleep(20); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public boolean isBurstAcquisitionRunning() throws MMScriptException { testForAbortRequests(); if (fastAcqWin_ != null) return fastAcqWin_.isBusy(); else return false; } public void startAcquisition() throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new ExecuteAcq()); } public void runAcquisition() throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(50); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { throw new MMScriptException("Acquisition window must be open for this command to work."); } } public void runAcqusition(String name, String root) throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { acqControlWin_.runAcquisition(name, root); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(100); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { throw new MMScriptException("Acquisition window must be open for this command to work."); } } public void loadAcquisition(String path) throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new LoadAcq(path)); } public void setPositionList(PositionList pl) throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object posList_ = PositionList.newInstance(pl); SwingUtilities.invokeLater(new RefreshPositionList()); } public void sleep (long ms) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) throw new MMScriptException("Script interrupted by the user!"); scriptPanel_.sleep(ms); } } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir); MMAcquisition acq = acqMgr_.getAcquisition(name); acq.setDimensions(nrFrames, nrChannels, nrSlices); } public void closeAcquisition(String name) throws MMScriptException { acqMgr_.closeAcquisition(name); } public void closeAcquisitionImage5D(String title) throws MMScriptException { acqMgr_.closeImage5D(title); } public void loadBurstAcquisition(String path) { // TODO Auto-generated method stub } public void refreshGUI() { updateGUI(true); } public void setAcquisitionProperty(String acqName, String propertyName, String value) { // TODO Auto-generated method stub } public void setImageProperty(String acqName, int frame, int channel, int slice, String propName, String value) { // TODO Auto-generated method stub } public void snapAndAddImage(String name, int frame, int channel, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); Object img; try { core_.snapImage(); img = core_.getImage(); } catch (Exception e) { throw new MMScriptException(e); } if (!acq.isInitialized()) { long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); acq.setImagePhysicalDimensions((int)width, (int)height, (int)depth); acq.initialize(); } acq.insertImage(img, frame, channel, slice); } public void closeAllAcquisitions() { acqMgr_.closeAll(); } private class ScriptConsoleMessage implements Runnable { String msg_; public ScriptConsoleMessage(String text) { msg_ = text; } public void run() { scriptPanel_.message(msg_); } } public void message(String text) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) throw new MMScriptException("Script interrupted by the user!"); SwingUtilities.invokeLater(new ScriptConsoleMessage(text)); } } public void clearMessageWindow() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) throw new MMScriptException("Script interrupted by the user!"); scriptPanel_.clearOutput(); } } public void clearOutput() throws MMScriptException { clearMessageWindow(); } public void clear() throws MMScriptException { clearMessageWindow(); } public void setChannelContrast(String title, int channel, int min, int max) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelContrast(channel, min, max); } public void setChannelName(String title, int channel, String name) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelName(channel, name); } public void setChannelColor(String title, int channel, Color color) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelColor(channel, color.getRGB()); } public void setContrastBasedOnFrame(String title, int frame, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setContrastBasedOnFrame(frame, slice); } public void runWellScan(WellAcquisitionData wad) throws MMScriptException { testForAbortRequests(); if (acqControlWin_ == null) openAcqControlDialog(); engine_.setPositionList(posList_); if (acqControlWin_.runWellScan(wad) == false) throw new MMScriptException("Scanning error."); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(500); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setXYStagePosition(double x, double y) throws MMScriptException { try { core_.setXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public Point2D.Double getXYStagePosition() throws MMScriptException { String stage = core_.getXYStageDevice(); if (stage.length() == 0) return null; double x[] = new double[1]; double y[] = new double[1]; try { core_.getXYPosition(stage, x, y); Point2D.Double pt = new Point2D.Double(x[0], y[0]); return pt; } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void autofocus() throws MMScriptException { Autofocus af = engine_.getAutofocus(); if (af == null) throw new MMScriptException("Autofocus plugin not installed!"); af.setMMCore(core_); af.fullFocus(); } public void autofocus(double coarseStep, int numCoarse, double fineStep, int numFine) throws MMScriptException { Autofocus af = engine_.getAutofocus(); if (af == null) throw new MMScriptException("Autofocus plugin not installed!"); af.setMMCore(core_); af.focus(coarseStep, numCoarse, fineStep, numFine); } public String getXYStageName() { return core_.getXYStageDevice(); } public void setXYOrigin(double x, double y) throws MMScriptException { String xyStage = core_.getXYStageDevice(); try { core_.setAdapterOriginXY(xyStage, x, y); } catch (Exception e) { throw new MMScriptException(e); } } public String installPlugin(String className, String menuName) { // instantiate auto-focusing module String msg = new String(className + " module loaded."); try { Class cl = Class.forName(className); PluginItem pi = new PluginItem(); pi.menuItem = menuName; pi.plugin = (MMPlugin) cl.newInstance(); pi.plugin.setApp(this); plugins_.add(pi); } catch (ClassNotFoundException e) { msg = className + " plugin not found."; } catch (InstantiationException e) { msg = className + " instantiation to MMPlugin interface failed."; } catch (IllegalAccessException e) { msg = "Illegal access exception!"; } catch (NoClassDefFoundError e) { msg = className + " class definition nor found."; } System.out.println(msg); return msg; } }
package com.cs.simpleproject; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Activity_Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button_exit=(Button) findViewById(R.id.button_Exit); button_exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package org.jivesoftware.smackx.debugger; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.text.*; import java.util.Date; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.debugger.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.util.*; /** * The EnhancedDebugger is a debugger that allows to debug sent, received and interpreted messages * but also provides the ability to send ad-hoc messages composed by the user.<p> * * A new EnhancedDebugger will be created for each connection to debug. All the EnhancedDebuggers * will be shown in the same debug window provided by the class EnhancedDebuggerWindow. * * @author Gaston Dombiak */ public class EnhancedDebugger implements SmackDebugger { private static final String NEWLINE = "\n"; private static ImageIcon packetReceivedIcon; private static ImageIcon packetSentIcon; private static ImageIcon presencePacketIcon; private static ImageIcon iqPacketIcon; private static ImageIcon messagePacketIcon; private static ImageIcon unknownPacketTypeIcon; { URL url; // Load the image icons url = Thread.currentThread().getContextClassLoader().getResource("images/nav_left_blue.png"); if (url != null) { packetReceivedIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/nav_right_red.png"); if (url != null) { packetSentIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/photo_portrait.png"); if (url != null) { presencePacketIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource( "images/question_and_answer.png"); if (url != null) { iqPacketIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/message.png"); if (url != null) { messagePacketIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/unknown.png"); if (url != null) { unknownPacketTypeIcon = new ImageIcon(url); } } private DefaultTableModel messagesTable = null; private JTextArea messageTextArea = null; private JFormattedTextField userField = null; private JFormattedTextField statusField = null; private XMPPConnection connection = null; private PacketListener packetReaderListener = null; private PacketListener packetWriterListener = null; private ConnectionListener connListener = null; private Writer writer; private Reader reader; private ReaderListener readerListener; private WriterListener writerListener; private Date creationTime = new Date(); // Statistics variables private DefaultTableModel statisticsTable = null; private int sentPackets = 0; private int receivedPackets = 0; private int sentIQPackets = 0; private int receivedIQPackets = 0; private int sentMessagePackets = 0; private int receivedMessagePackets = 0; private int sentPresencePackets = 0; private int receivedPresencePackets = 0; private int sentOtherPackets = 0; private int receivedOtherPackets = 0; JTabbedPane tabbedPane; public EnhancedDebugger(XMPPConnection connection, Writer writer, Reader reader) { this.connection = connection; this.writer = writer; this.reader = reader; createDebug(); EnhancedDebuggerWindow.addDebugger(this); } /** * Creates the debug process, which is a GUI window that displays XML traffic. */ private void createDebug() { // Use the native look and feel. try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } // We'll arrange the UI into six tabs. The first tab contains all data, the second // client generated XML, the third server generated XML, the fourth allows to send // ad-hoc messages and the fifth contains connection information. tabbedPane = new JTabbedPane(); // Add the All Packets, Sent, Received and Interpreted panels addBasicPanels(); // Add the panel to send ad-hoc messages addAdhocPacketPanel(); // Add the connection information panel addInformationPanel(); // Create a thread that will listen for all incoming packets and write them to // the GUI. This is what we call "interpreted" packet data, since it's the packet // data as Smack sees it and not as it's coming in as raw XML. packetReaderListener = new PacketListener() { SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss aaa"); public void processPacket(Packet packet) { addReadPacketToTable(dateFormatter, packet); } }; // Create a thread that will listen for all outgoing packets and write them to // the GUI. packetWriterListener = new PacketListener() { SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss aaa"); public void processPacket(Packet packet) { addSentPacketToTable(dateFormatter, packet); } }; // Create a thread that will listen for any connection closed event connListener = new ConnectionListener() { public void connectionClosed() { statusField.setValue("Closed"); EnhancedDebuggerWindow.connectionClosed(EnhancedDebugger.this); } public void connectionClosedOnError(Exception e) { statusField.setValue("Closed due to an exception"); EnhancedDebuggerWindow.connectionClosedOnError(EnhancedDebugger.this, e); } }; } private void addBasicPanels() { JPanel allPane = new JPanel(); allPane.setLayout(new GridLayout(2, 1)); tabbedPane.add("All Packets", allPane); tabbedPane.setToolTipTextAt(0, "Sent and received packets processed by Smack"); messagesTable = new DefaultTableModel( new Object[] { "Hide", "Timestamp", "", "", "Message", "Id", "Type", "To", "From" }, 0) { public boolean isCellEditable(int rowIndex, int mColIndex) { return false; } public Class getColumnClass(int columnIndex) { if (columnIndex == 2 || columnIndex == 3) { return Icon.class; } return super.getColumnClass(columnIndex); } }; JTable table = new JTable(messagesTable); // Allow only single a selection table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Hide the first column table.getColumnModel().getColumn(0).setMaxWidth(0); table.getColumnModel().getColumn(0).setMinWidth(0); table.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0); table.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0); // Set the column "timestamp" size table.getColumnModel().getColumn(1).setMaxWidth(300); table.getColumnModel().getColumn(1).setPreferredWidth(70); // Set the column "direction" icon size table.getColumnModel().getColumn(2).setMaxWidth(50); table.getColumnModel().getColumn(2).setPreferredWidth(30); // Set the column "packet type" icon size table.getColumnModel().getColumn(3).setMaxWidth(50); table.getColumnModel().getColumn(3).setPreferredWidth(30); // Set the column "Id" size table.getColumnModel().getColumn(5).setMaxWidth(100); table.getColumnModel().getColumn(5).setPreferredWidth(55); // Set the column "type" size table.getColumnModel().getColumn(6).setMaxWidth(200); table.getColumnModel().getColumn(6).setPreferredWidth(50); // Set the column "to" size table.getColumnModel().getColumn(7).setMaxWidth(300); table.getColumnModel().getColumn(7).setPreferredWidth(90); // Set the column "from" size table.getColumnModel().getColumn(8).setMaxWidth(300); table.getColumnModel().getColumn(8).setPreferredWidth(90); // Create a table listener that listen for row selection events SelectionListener selectionListener = new SelectionListener(table); table.getSelectionModel().addListSelectionListener(selectionListener); table.getColumnModel().getSelectionModel().addListSelectionListener(selectionListener); allPane.add(new JScrollPane(table)); messageTextArea = new JTextArea(); messageTextArea.setEditable(false); // Add pop-up menu. JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // Set the sent text as the new content of the clipboard clipboard.setContents(new StringSelection(messageTextArea.getText()), null); } }); menu.add(menuItem1); // Add listener to the text area so the popup menu can come up. messageTextArea.addMouseListener(new PopupListener(menu)); allPane.add(new JScrollPane(messageTextArea)); // Create UI elements for client generated XML traffic. final JTextArea sentText = new JTextArea(); sentText.setEditable(false); sentText.setForeground(new Color(112, 3, 3)); tabbedPane.add("Raw Sent Packets", new JScrollPane(sentText)); tabbedPane.setToolTipTextAt(1, "Raw text of the sent packets"); // Add pop-up menu. menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // Set the sent text as the new content of the clipboard clipboard.setContents(new StringSelection(sentText.getText()), null); } }); JMenuItem menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sentText.setText(""); } }); // Add listener to the text area so the popup menu can come up. sentText.addMouseListener(new PopupListener(menu)); menu.add(menuItem1); menu.add(menuItem2); // Create UI elements for server generated XML traffic. final JTextArea receivedText = new JTextArea(); receivedText.setEditable(false); receivedText.setForeground(new Color(6, 76, 133)); tabbedPane.add("Raw Received Packets", new JScrollPane(receivedText)); tabbedPane.setToolTipTextAt( 2, "Raw text of the received packets before Smack process them"); // Add pop-up menu. menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // Set the sent text as the new content of the clipboard clipboard.setContents(new StringSelection(receivedText.getText()), null); } }); menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { receivedText.setText(""); } }); // Add listener to the text area so the popup menu can come up. receivedText.addMouseListener(new PopupListener(menu)); menu.add(menuItem1); menu.add(menuItem2); // Create a special Reader that wraps the main Reader and logs data to the GUI. ObservableReader debugReader = new ObservableReader(reader); readerListener = new ReaderListener() { public void read(String str) { int index = str.lastIndexOf(">"); if (index != -1) { receivedText.append(str.substring(0, index + 1)); receivedText.append(NEWLINE); if (str.length() > index) { receivedText.append(str.substring(index + 1)); } } else { receivedText.append(str); } } }; debugReader.addReaderListener(readerListener); // Create a special Writer that wraps the main Writer and logs data to the GUI. ObservableWriter debugWriter = new ObservableWriter(writer); writerListener = new WriterListener() { public void write(String str) { sentText.append(str); if (str.endsWith(">")) { sentText.append(NEWLINE); } } }; debugWriter.addWriterListener(writerListener); // Assign the reader/writer objects to use the debug versions. The packet reader // and writer will use the debug versions when they are created. reader = debugReader; writer = debugWriter; } private void addAdhocPacketPanel() { // Create UI elements for sending ad-hoc messages. final JTextArea adhocMessages = new JTextArea(); adhocMessages.setEditable(true); adhocMessages.setForeground(new Color(1, 94, 35)); tabbedPane.add("Ad-hoc message", new JScrollPane(adhocMessages)); tabbedPane.setToolTipTextAt(3, "Panel that allows you to send adhoc packets"); // Add pop-up menu. JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Message"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<message to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"><body></body></message>"); } }); menu.add(menuItem); menuItem = new JMenuItem("IQ Get"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<iq type=\"get\" to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"><query xmlns=\"\"></query></iq>"); } }); menu.add(menuItem); menuItem = new JMenuItem("IQ Set"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<iq type=\"set\" to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"><query xmlns=\"\"></query></iq>"); } }); menu.add(menuItem); menuItem = new JMenuItem("Presence"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<presence to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"/>"); } }); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Send"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!"".equals(adhocMessages.getText())) { AdHocPacket packetToSend = new AdHocPacket(adhocMessages.getText()); connection.sendPacket(packetToSend); } } }); menu.add(menuItem); menuItem = new JMenuItem("Clear"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText(null); } }); menu.add(menuItem); // Add listener to the text area so the popup menu can come up. adhocMessages.addMouseListener(new PopupListener(menu)); } private void addInformationPanel() { // Create UI elements for connection information. JPanel informationPanel = new JPanel(); informationPanel.setLayout(new BorderLayout()); // Add the Host information JPanel connPanel = new JPanel(); connPanel.setLayout(new GridBagLayout()); connPanel.setBorder(BorderFactory.createTitledBorder("Connection information")); JLabel label = new JLabel("Host: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); JFormattedTextField field = new JFormattedTextField(connection.getHost()); field.setMinimumSize(new java.awt.Dimension(150, 20)); field.setMaximumSize(new java.awt.Dimension(150, 20)); field.setEditable(false); field.setBorder(null); connPanel.add( field, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the Port information label = new JLabel("Port: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); field = new JFormattedTextField(new Integer(connection.getPort())); field.setMinimumSize(new java.awt.Dimension(150, 20)); field.setMaximumSize(new java.awt.Dimension(150, 20)); field.setEditable(false); field.setBorder(null); connPanel.add( field, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection's User information label = new JLabel("User: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); userField = new JFormattedTextField(); userField.setMinimumSize(new java.awt.Dimension(150, 20)); userField.setMaximumSize(new java.awt.Dimension(150, 20)); userField.setEditable(false); userField.setBorder(null); connPanel.add( userField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection's creationTime information label = new JLabel("Creation time: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); field = new JFormattedTextField(new SimpleDateFormat("yyyy.MM.dd hh:mm:ss aaa")); field.setMinimumSize(new java.awt.Dimension(150, 20)); field.setMaximumSize(new java.awt.Dimension(150, 20)); field.setValue(creationTime); field.setEditable(false); field.setBorder(null); connPanel.add( field, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection's creationTime information label = new JLabel("Status: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); statusField = new JFormattedTextField(); statusField.setMinimumSize(new java.awt.Dimension(150, 20)); statusField.setMaximumSize(new java.awt.Dimension(150, 20)); statusField.setValue("Active"); statusField.setEditable(false); statusField.setBorder(null); connPanel.add( statusField, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection panel to the information panel informationPanel.add(connPanel, BorderLayout.NORTH); // Add the Number of sent packets information JPanel packetsPanel = new JPanel(); packetsPanel.setLayout(new GridLayout(1, 1)); packetsPanel.setBorder(BorderFactory.createTitledBorder("Transmitted Packets")); statisticsTable = new DefaultTableModel(new Object[][] { { "IQ", new Integer(0), new Integer(0)}, { "Message", new Integer(0), new Integer(0) }, { "Presence", new Integer(0), new Integer(0) }, { "Other", new Integer(0), new Integer(0) }, { "Total", new Integer(0), new Integer(0) } }, new Object[] { "Type", "Received", "Sent" }) { public boolean isCellEditable(int rowIndex, int mColIndex) { return false; } }; JTable table = new JTable(statisticsTable); // Allow only single a selection table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); packetsPanel.add(new JScrollPane(table)); // Add the packets panel to the information panel informationPanel.add(packetsPanel, BorderLayout.CENTER); tabbedPane.add("Information", new JScrollPane(informationPanel)); tabbedPane.setToolTipTextAt(4, "Information and statistics about the debugged connection"); } public void userHasLogged(String user) { userField.setText(user); EnhancedDebuggerWindow.userHasLogged(this, user); // Add the connection listener to the connection so that the debugger can be notified // whenever the connection is closed. connection.addConnectionListener(connListener); } public Reader getReader() { return reader; } public Writer getWriter() { return writer; } public PacketListener getReaderListener() { return packetReaderListener; } public PacketListener getWriterListener() { return packetWriterListener; } /** * Updates the statistics table */ private void updateStatistics() { statisticsTable.setValueAt(new Integer(receivedIQPackets), 0, 1); statisticsTable.setValueAt(new Integer(sentIQPackets), 0, 2); statisticsTable.setValueAt(new Integer(receivedMessagePackets), 1, 1); statisticsTable.setValueAt(new Integer(sentMessagePackets), 1, 2); statisticsTable.setValueAt(new Integer(receivedPresencePackets), 2, 1); statisticsTable.setValueAt(new Integer(sentPresencePackets), 2, 2); statisticsTable.setValueAt(new Integer(receivedOtherPackets), 3, 1); statisticsTable.setValueAt(new Integer(sentOtherPackets), 3, 2); statisticsTable.setValueAt(new Integer(receivedPackets), 4, 1); statisticsTable.setValueAt(new Integer(sentPackets), 4, 2); } /** * Adds the received packet detail to the messages table. * * @param dateFormatter the SimpleDateFormat to use to format Dates * @param packet the read packet to add to the table */ private void addReadPacketToTable(SimpleDateFormat dateFormatter, Packet packet) { String messageType = null; String from = packet.getFrom(); String type = ""; Icon packetTypeIcon; receivedPackets++; if (packet instanceof IQ) { packetTypeIcon = iqPacketIcon; messageType = "IQ Received (class=" + packet.getClass().getName() + ")"; type = ((IQ) packet).getType().toString(); receivedIQPackets++; } else if (packet instanceof Message) { packetTypeIcon = messagePacketIcon; messageType = "Message Received"; type = ((Message) packet).getType().toString(); receivedMessagePackets++; } else if (packet instanceof Presence) { packetTypeIcon = presencePacketIcon; messageType = "Presence Received"; type = ((Presence) packet).getType().toString(); receivedPresencePackets++; } else { packetTypeIcon = unknownPacketTypeIcon; messageType = packet.getClass().getName() + " Received"; receivedOtherPackets++; } messagesTable.addRow( new Object[] { formatXML(packet.toXML()), dateFormatter.format(new Date()), packetReceivedIcon, packetTypeIcon, messageType, packet.getPacketID(), type, "", from }); // Update the statistics table updateStatistics(); } /** * Adds the sent packet detail to the messages table. * * @param dateFormatter the SimpleDateFormat to use to format Dates * @param packet the sent packet to add to the table */ private void addSentPacketToTable(SimpleDateFormat dateFormatter, Packet packet) { String messageType = null; String to = packet.getTo(); String type = ""; Icon packetTypeIcon; sentPackets++; if (packet instanceof IQ) { packetTypeIcon = iqPacketIcon; messageType = "IQ Sent (class=" + packet.getClass().getName() + ")"; type = ((IQ) packet).getType().toString(); sentIQPackets++; } else if (packet instanceof Message) { packetTypeIcon = messagePacketIcon; messageType = "Message Sent"; type = ((Message) packet).getType().toString(); sentMessagePackets++; } else if (packet instanceof Presence) { packetTypeIcon = presencePacketIcon; messageType = "Presence Sent"; type = ((Presence) packet).getType().toString(); sentPresencePackets++; } else { packetTypeIcon = unknownPacketTypeIcon; messageType = packet.getClass().getName() + " Sent"; sentOtherPackets++; } messagesTable.addRow( new Object[] { formatXML(packet.toXML()), dateFormatter.format(new Date()), packetSentIcon, packetTypeIcon, messageType, packet.getPacketID(), type, to, "" }); // Update the statistics table updateStatistics(); } private String formatXML(String str) { try { // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Transform the requested string into a nice formatted XML string StreamSource source = new StreamSource(new StringReader(str)); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); transformer.transform(source, result); return sw.toString(); } catch (TransformerConfigurationException tce) { // Error generated by the parser System.out.println("\n** Transformer Factory error"); System.out.println(" " + tce.getMessage()); // Use the contained exception, if any Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); } catch (TransformerException te) { // Error generated by the parser System.out.println("\n** Transformation error"); System.out.println(" " + te.getMessage()); // Use the contained exception, if any Throwable x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); } return str; } /** * Stops debugging the connection. Removes any listener on the connection. * */ void cancel() { connection.removeConnectionListener(connListener); connection.removePacketListener(packetReaderListener); connection.removePacketWriterListener(packetWriterListener); ((ObservableReader)reader).removeReaderListener(readerListener); ((ObservableWriter)writer).removeWriterListener(writerListener); messagesTable = null; } /** * An ad-hoc packet is like any regular packet but with the exception that it's intention is * to be used only <b>to send packets</b>.<p> * * The whole text to send must be passed to the constructor. This implies that the client of * this class is responsible for sending a valid text to the constructor. * */ private class AdHocPacket extends Packet { private String text; /** * Create a new AdHocPacket with the text to send. The passed text must be a valid text to * send to the server, no validation will be done on the passed text. * * @param text the whole text of the packet to send */ public AdHocPacket(String text) { this.text = text; } public String toXML() { return text; } } /** * Listens for debug window popup dialog events. */ private class PopupListener extends MouseAdapter { JPopupMenu popup; PopupListener(JPopupMenu popupMenu) { popup = popupMenu; } public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } private class SelectionListener implements ListSelectionListener { JTable table; // It is necessary to keep the table since it is not possible // to determine the table from the event's source SelectionListener(JTable table) { this.table = table; } public void valueChanged(ListSelectionEvent e) { if (table.getSelectedRow() == -1) { // Clear the messageTextArea since there is none packet selected messageTextArea.setText(null); } else { // Set the detail of the packet in the messageTextArea messageTextArea.setText( (String) table.getModel().getValueAt(table.getSelectedRow(), 0)); // Scroll up to the top messageTextArea.setCaretPosition(0); } } } }
package com.thoughtworks.xstream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.NotActiveException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.util.ArrayList; import java.util.BitSet; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import com.thoughtworks.xstream.alias.ClassMapper; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.basic.BigDecimalConverter; import com.thoughtworks.xstream.converters.basic.BigIntegerConverter; import com.thoughtworks.xstream.converters.basic.BooleanConverter; import com.thoughtworks.xstream.converters.basic.ByteConverter; import com.thoughtworks.xstream.converters.basic.CharConverter; import com.thoughtworks.xstream.converters.basic.DateConverter; import com.thoughtworks.xstream.converters.basic.DoubleConverter; import com.thoughtworks.xstream.converters.basic.FloatConverter; import com.thoughtworks.xstream.converters.basic.IntConverter; import com.thoughtworks.xstream.converters.basic.LongConverter; import com.thoughtworks.xstream.converters.basic.NullConverter; import com.thoughtworks.xstream.converters.basic.ShortConverter; import com.thoughtworks.xstream.converters.basic.StringBufferConverter; import com.thoughtworks.xstream.converters.basic.StringConverter; import com.thoughtworks.xstream.converters.basic.URLConverter; import com.thoughtworks.xstream.converters.collections.ArrayConverter; import com.thoughtworks.xstream.converters.collections.BitSetConverter; import com.thoughtworks.xstream.converters.collections.CharArrayConverter; import com.thoughtworks.xstream.converters.collections.CollectionConverter; import com.thoughtworks.xstream.converters.collections.MapConverter; import com.thoughtworks.xstream.converters.collections.PropertiesConverter; import com.thoughtworks.xstream.converters.collections.TreeMapConverter; import com.thoughtworks.xstream.converters.collections.TreeSetConverter; import com.thoughtworks.xstream.converters.extended.ColorConverter; import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter; import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; import com.thoughtworks.xstream.converters.extended.FileConverter; import com.thoughtworks.xstream.converters.extended.FontConverter; import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter; import com.thoughtworks.xstream.converters.extended.JavaClassConverter; import com.thoughtworks.xstream.converters.extended.JavaMethodConverter; import com.thoughtworks.xstream.converters.extended.LocaleConverter; import com.thoughtworks.xstream.converters.extended.SqlDateConverter; import com.thoughtworks.xstream.converters.extended.SqlTimeConverter; import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter; import com.thoughtworks.xstream.converters.extended.TextAttributeConverter; import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker; import com.thoughtworks.xstream.converters.reflection.SerializableConverter; import com.thoughtworks.xstream.core.BaseException; import com.thoughtworks.xstream.core.DefaultConverterLookup; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.MapBackedDataHolder; import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy; import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy; import com.thoughtworks.xstream.core.TreeMarshallingStrategy; import com.thoughtworks.xstream.core.util.ClassLoaderReference; import com.thoughtworks.xstream.core.util.CompositeClassLoader; import com.thoughtworks.xstream.core.util.CustomObjectInputStream; import com.thoughtworks.xstream.core.util.CustomObjectOutputStream; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.StatefulWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.mapper.ArrayMapper; import com.thoughtworks.xstream.mapper.AttributeAliasingMapper; import com.thoughtworks.xstream.mapper.AttributeMapper; import com.thoughtworks.xstream.mapper.CachingMapper; import com.thoughtworks.xstream.mapper.ClassAliasingMapper; import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper; import com.thoughtworks.xstream.mapper.DefaultMapper; import com.thoughtworks.xstream.mapper.DynamicProxyMapper; import com.thoughtworks.xstream.mapper.EnumMapper; import com.thoughtworks.xstream.mapper.FieldAliasingMapper; import com.thoughtworks.xstream.mapper.ImmutableTypesMapper; import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.mapper.OuterClassMapper; import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper; /** * Simple facade to XStream library, a Java-XML serialization tool. <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * XStream xstream = new XStream(); * String xml = xstream.toXML(myObject); // serialize to XML * Object myObject2 = xstream.fromXML(xml); // deserialize from XML * </pre> * * </blockquote> * <hr> * <p/> * <h3>Aliasing classes</h3> * <p/> * <p> * To create shorter XML, you can specify aliases for classes using the <code>alias()</code> * method. For example, you can shorten all occurences of element * <code>&lt;com.blah.MyThing&gt;</code> to <code>&lt;my-thing&gt;</code> by registering an * alias for the class. * <p> * <hr> * <blockquote> * * <pre> * xstream.alias(&quot;my-thing&quot;, MyThing.class); * </pre> * * </blockquote> * <hr> * <p/> * <h3>Converters</h3> * <p/> * <p> * XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each * of which acts as a strategy for converting a particular type of class to XML and back again. Out * of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc) * and collections (Map, List, Set, Properties, etc). For other objects reflection is used to * serialize each field recursively. * </p> * <p/> * <p> * Extra converters can be registered using the <code>registerConverter()</code> method. Some * non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended} * package and you can create your own by implementing the * {@link com.thoughtworks.xstream.converters.Converter} interface. * </p> * <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new SqlTimestampConverter()); * xstream.registerConverter(new DynamicProxyConverter()); * </pre> * * </blockquote> * <hr> * <p> * The default converter, ie the converter which will be used if no other registered converter is * suitable, can be configured by either one of the constructors or can be changed using the * <code>changeDefaultConverter()</code> method. If not set, XStream uses * {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the initial default * converter. * </p> * <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.changeDefaultConverter(new ACustomDefaultConverter()); * </pre> * * </blockquote> * <hr> * <p/> * <h3>Object graphs</h3> * <p/> * <p> * XStream has support for object graphs; a deserialized object graph will keep references intact, * including circular references. * </p> * <p/> * <p> * XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using * <code>setMode()</code>: * </p> * <p/> <table border="1"> * <tr> * <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td> * <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML * with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate * references. This produces XML with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td> * <td>Uses ID references to signify duplicate references. In some scenarios, such as when using * hand-written XML, this is easier to work with.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td> * <td>This disables object graph support and treats the object structure like a tree. Duplicate * references are treated as two seperate objects and circular references cause an exception. This * is slightly faster and uses less memory than the other two modes.</td> * </tr> * </table> * <h3>Thread safety</h3> * <p> * The XStream instance is thread-safe. That is, once the XStream instance has been created and * configured, it may be shared across multiple threads allowing objects to be * serialized/deserialized concurrently. * <h3>Implicit collections</h3> * <p/> * <p> * To avoid the need for special tags for collections, you can define implicit collections using one * of the <code>addImplicitCollection</code> methods. * </p> * * @author Joe Walnes * @author J&ouml;rg Schaible * @author Mauro Talevi * @author Guilherme Silveira */ public class XStream { // CAUTION: The sequence of the fields is intentional for an optimal XML output of a // self-serializaion! private ReflectionProvider reflectionProvider; private HierarchicalStreamDriver hierarchicalStreamDriver; private ClassLoaderReference classLoaderReference; private MarshallingStrategy marshallingStrategy; private Mapper mapper; private DefaultConverterLookup converterLookup; private ClassAliasingMapper classAliasingMapper; private FieldAliasingMapper fieldAliasingMapper; private AttributeAliasingMapper attributeAliasingMapper; private AttributeMapper attributeMapper; private DefaultImplementationsMapper defaultImplementationsMapper; private ImmutableTypesMapper immutableTypesMapper; private ImplicitCollectionMapper implicitCollectionMapper; private transient JVM jvm = new JVM(); public static final int NO_REFERENCES = 1001; public static final int ID_REFERENCES = 1002; public static final int XPATH_RELATIVE_REFERENCES = 1003; public static final int XPATH_ABSOLUTE_REFERENCES = 1004; /** * @deprecated since 1.2, use {@link #XPATH_RELATIVE_REFERENCES} or * {@link #XPATH_ABSOLUTE_REFERENCES} instead. */ public static final int XPATH_REFERENCES = XPATH_RELATIVE_REFERENCES; public static final int PRIORITY_VERY_HIGH = 10000; public static final int PRIORITY_NORMAL = 0; public static final int PRIORITY_LOW = -10; public static final int PRIORITY_VERY_LOW = -20; /** * Constructs a default XStream. The instance will use the {@link XppDriver} as default and tries to determin the best * match for the {@link ReflectionProvider} on its own. * * @throws InitializationException in case of an initialization problem */ public XStream() { this(null, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link ReflectionProvider}. The instance will use the {@link XppDriver} as default. * * @throws InitializationException in case of an initialization problem */ public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will tries to determin the best * match for the {@link ReflectionProvider} on its own. * * @throws InitializationException in case of an initialization problem */ public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}. * * @throws InitializationException in case of an initialization problem */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver); } /** * @deprecated As of 1.2, use * {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} */ public XStream( ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver) { this(reflectionProvider, (Mapper)classMapper, driver); } /** * @deprecated As of 1.2, use * {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} and * register classAttributeIdentifier as alias */ public XStream( ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver, String classAttributeIdentifier) { this(reflectionProvider, (Mapper)classMapper, driver); aliasAttribute(classAttributeIdentifier, "class"); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}. * * @throws InitializationException in case of an initialization problem */ public XStream( ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { jvm = new JVM(); if (reflectionProvider == null) { reflectionProvider = jvm.bestReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader()); this.mapper = mapper == null ? buildMapper() : mapper; this.converterLookup = new DefaultConverterLookup(this.mapper); setupMappers(); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_RELATIVE_REFERENCES); } private Mapper buildMapper() { Mapper mapper = new DefaultMapper(classLoaderReference); if ( useXStream11XmlFriendlyMapper() ){ mapper = new XStream11XmlFriendlyMapper(mapper); } mapper = new ClassAliasingMapper(mapper); mapper = new FieldAliasingMapper(mapper); mapper = new AttributeAliasingMapper(mapper); mapper = new AttributeMapper(mapper); mapper = new ImplicitCollectionMapper(mapper); if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) { mapper = buildMapperDynamically( "com.thoughtworks.xstream.mapper.CGLIBMapper", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new DynamicProxyMapper(mapper); if (JVM.is15()) { mapper = new EnumMapper(mapper); } mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); mapper = new ImmutableTypesMapper(mapper); mapper = wrapMapper((MapperWrapper)mapper); mapper = new CachingMapper(mapper); return mapper; } private Mapper buildMapperDynamically( String className, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); return (Mapper)constructor.newInstance(constructorParamValues); } catch (Exception e) { throw new InitializationException("Could not instatiate mapper : " + className, e); } } protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } protected boolean useXStream11XmlFriendlyMapper() { return false; } private void setupMappers() { classAliasingMapper = (ClassAliasingMapper)this.mapper .lookupMapperOfType(ClassAliasingMapper.class); fieldAliasingMapper = (FieldAliasingMapper)this.mapper .lookupMapperOfType(FieldAliasingMapper.class); attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class); attributeAliasingMapper = (AttributeAliasingMapper)this.mapper .lookupMapperOfType(AttributeAliasingMapper.class); implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper .lookupMapperOfType(ImplicitCollectionMapper.class); defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper .lookupMapperOfType(DefaultImplementationsMapper.class); immutableTypesMapper = (ImmutableTypesMapper)this.mapper .lookupMapperOfType(ImmutableTypesMapper.class); // should use ctor, but converterLookup is not yet initialized instantiating this mapper if (attributeMapper != null) { attributeMapper.setConverterLookup(converterLookup); } } protected void setupAliases() { if (classAliasingMapper == null) { return; } alias("null", Mapper.Null.class); alias("int", Integer.class); alias("float", Float.class); alias("double", Double.class); alias("long", Long.class); alias("short", Short.class); alias("char", Character.class); alias("byte", Byte.class); alias("boolean", Boolean.class); alias("number", Number.class); alias("object", Object.class); alias("big-int", BigInteger.class); alias("big-decimal", BigDecimal.class); alias("string-buffer", StringBuffer.class); alias("string", String.class); alias("java-class", Class.class); alias("method", Method.class); alias("constructor", Constructor.class); alias("date", Date.class); alias("url", URL.class); alias("bit-set", BitSet.class); alias("map", Map.class); alias("entry", Map.Entry.class); alias("properties", Properties.class); alias("list", List.class); alias("set", Set.class); alias("linked-list", LinkedList.class); alias("vector", Vector.class); alias("tree-map", TreeMap.class); alias("tree-set", TreeSet.class); alias("hashtable", Hashtable.class); if(jvm.supportsAWT()) { // Instantiating these two classes starts the AWT system, which is undesirable. Calling // loadClass ensures a reference to the class is found but they are not instantiated. alias("awt-color", jvm.loadClass("java.awt.Color")); alias("awt-font", jvm.loadClass("java.awt.Font")); alias("awt-text-attribute", jvm.loadClass("java.awt.font.TextAttribute")); } if(jvm.supportsSQL()) { alias("sql-timestamp", jvm.loadClass("java.sql.Timestamp")); alias("sql-time", jvm.loadClass("java.sql.Time")); alias("sql-date", jvm.loadClass("java.sql.Date")); } alias("file", File.class); alias("locale", Locale.class); alias("gregorian-calendar", Calendar.class); // since jdk 1.4 included, but previously available as separate package ... Class type = jvm.loadClass("javax.security.auth.Subject"); if (type != null) { alias("auth-subject", type); } // since jdk 1.5 included, but available separately in JAXB ... type = jvm.loadClass("javax.xml.datatype.Duration"); if (type != null) { alias("duration", type); } if (JVM.is14()) { alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap")); alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet")); alias("trace", jvm.loadClass("java.lang.StackTraceElement")); alias("currency", jvm.loadClass("java.util.Currency")); aliasType("charset", jvm.loadClass("java.nio.charset.Charset")); } if (JVM.is15()) { alias("enum-set", jvm.loadClass("java.util.EnumSet")); alias("enum-map", jvm.loadClass("java.util.EnumMap")); } } protected void setupDefaultImplementations() { if (defaultImplementationsMapper == null) { return; } addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } protected void setupConverters() { // use different ReflectionProvider depending on JDK final ReflectionConverter reflectionConverter; if (JVM.is15()) { Class annotationProvider = jvm .loadClass("com.thoughtworks.xstream.annotations.AnnotationProvider"); dynamicallyRegisterConverter( "com.thoughtworks.xstream.annotations.AnnotationReflectionConverter", PRIORITY_VERY_LOW, new Class[]{ Mapper.class, ReflectionProvider.class, annotationProvider}, new Object[]{ mapper, reflectionProvider, reflectionProvider.newInstance(annotationProvider)}); reflectionConverter = (ReflectionConverter)converterLookup .lookupConverterForType(Object.class); } else { reflectionConverter = new ReflectionConverter(mapper, reflectionProvider); registerConverter(reflectionConverter, PRIORITY_VERY_LOW); } registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW); registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW); registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter((Converter)new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new MapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); if(jvm.supportsSQL()) { registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); } registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL); if(jvm.supportsAWT()) { registerConverter(new FontConverter(), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); // since JDK 1.4 included, but previously available as separate package ... if (jvm.loadClass("javax.security.auth.Subject") != null) { dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.SubjectConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); } // since JDK 1.5 included, bas as part of JAXB previously available ... if (jvm.loadClass("javax.xml.datatype.Duration") != null) { dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.DurationConverter", PRIORITY_NORMAL, null, null); } if (JVM.is14()) { // late bound converters - allows XStream to be compiled on earlier JDKs dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.ThrowableConverter", PRIORITY_NORMAL, new Class[]{Converter.class}, new Object[]{reflectionConverter}); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL, new Class[]{Converter.class}, new Object[]{reflectionConverter}); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.CharsetConverter", PRIORITY_NORMAL, null, null); } if (JVM.is15()) { // late bound converters - allows XStream to be compiled on earlier JDKs dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); } if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) { dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.reflection.CGLIBEnhancedConverter", PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class}, new Object[]{mapper, reflectionProvider}); } registerConverter(new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL); } private void dynamicallyRegisterConverter( String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Object instance = constructor.newInstance(constructorParamValues); if (instance instanceof Converter) { registerConverter((Converter)instance, priority); } else if (instance instanceof SingleValueConverter) { registerConverter((SingleValueConverter)instance, priority); } } catch (Exception e) { throw new InitializationException("Could not instatiate converter : " + className, e); } } protected void setupImmutableTypes() { if (immutableTypesMapper == null) { return; } // primitives are always immutable addImmutableType(boolean.class); addImmutableType(Boolean.class); addImmutableType(byte.class); addImmutableType(Byte.class); addImmutableType(char.class); addImmutableType(Character.class); addImmutableType(double.class); addImmutableType(Double.class); addImmutableType(float.class); addImmutableType(Float.class); addImmutableType(int.class); addImmutableType(Integer.class); addImmutableType(long.class); addImmutableType(Long.class); addImmutableType(short.class); addImmutableType(Short.class); // additional types addImmutableType(Mapper.Null.class); addImmutableType(BigDecimal.class); addImmutableType(BigInteger.class); addImmutableType(String.class); addImmutableType(URL.class); addImmutableType(File.class); addImmutableType(Class.class); if(jvm.supportsAWT()) { addImmutableType(jvm.loadClass("java.awt.font.TextAttribute")); } if (JVM.is14()) { // late bound types - allows XStream to be compiled on earlier JDKs Class type = jvm.loadClass("com.thoughtworks.xstream.converters.extended.CharsetConverter"); addImmutableType(type); } } public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } /** * Serialize an object to a pretty-printed XML String. * @throws BaseException if the object cannot be serialized */ public String toXML(Object obj) { Writer writer = new StringWriter(); toXML(obj, writer); return writer.toString(); } /** * Serialize an object to the given Writer as pretty-printed XML. * @throws BaseException if the object cannot be serialized */ public void toXML(Object obj, Writer out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); marshal(obj, writer); writer.flush(); } /** * Serialize an object to the given OutputStream as pretty-printed XML. * @throws BaseException if the object cannot be serialized */ public void toXML(Object obj, OutputStream out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); marshal(obj, writer); writer.flush(); } /** * Serialize and object to a hierarchical data structure (such as XML). * @throws BaseException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } /** * Serialize and object to a hierarchical data structure (such as XML). * * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If * not present, XStream shall create one lazily as needed. * @throws BaseException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder); } /** * Deserialize an object from an XML String. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } /** * Deserialize an object from an XML Reader. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(Reader xml) { return unmarshal(hierarchicalStreamDriver.createReader(xml), null); } /** * Deserialize an object from an XML InputStream. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(InputStream input) { return unmarshal(hierarchicalStreamDriver.createReader(input), null); } /** * Deserialize an object from an XML String, populating the fields of the given root object * instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } /** * Deserialize an object from an XML Reader, populating the fields of the given root object * instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from an XML InputStream, populating the fields of the given root object * instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(InputStream xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from a hierarchical data structure (such as XML). * @throws BaseException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } /** * Deserialize an object from a hierarchical data structure (such as XML), populating the fields * of the given root object instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @param root If present, the passed in object will have its fields populated, as opposed to * XStream creating a new instance. * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If * not present, XStream shall create one lazily as needed. * @throws BaseException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type) { if (classAliasingMapper == null) { throw new InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addClassAlias(name, type); } /** * Alias a type to a shorter name to be used in XML elements. * Any class that is assignable to this type will be aliased to the same name. * * @param name Short name * @param type Type to be aliased * @since 1.2 * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void aliasType(String name, Class type) { if (classAliasingMapper == null) { throw new InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addTypeAlias(name, type); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @param defaultImplementation Default implementation of type to use if no other specified. * @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } /** * Create an alias for a field name. * * @param alias the alias itself * @param type the type that declares the field * @param fieldName the name of the field * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void aliasField(String alias, Class type, String fieldName) { if (fieldAliasingMapper == null) { throw new InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.addFieldAlias(alias, type, fieldName); } /** * Create an alias for an attribute * * @param alias the alias itself * @param attributeName the name of the attribute * @throws InitializationException if no {@link AttributeAliasingMapper} is available */ public void aliasAttribute(String alias, String attributeName) { if (attributeAliasingMapper == null) { throw new InitializationException("No " + AttributeAliasingMapper.class.getName() + " available"); } attributeAliasingMapper.addAliasFor(attributeName, alias); } /** * Create an alias for an attribute. * * @param configurableClass the type where the attribute is defined * @param attributeName the name of the attribute * @param alias the alias itself * @throws InitializationException if no {@link AttributeAliasingMapper} is available */ public void aliasAttribute(Class configurableClass, String attributeName, String alias) { if (attributeAliasingMapper == null) { throw new InitializationException("No " + AttributeAliasingMapper.class.getName() + " available"); } attributeAliasingMapper.addAliasFor(configurableClass, attributeName, alias); } /** * Use an XML attribute for a field or a specific type. * * @param fieldName the name of the field * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(String fieldName, Class type) { if (attributeMapper == null) { throw new InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(fieldName, type); } /** * Use an XML attribute for a field declared in a specific type. * * @param fieldName the name of the field * @param definedIn the Class containing such field * @throws InitializationException if no {@link AttributeMapper} is available * since 1.2.2 */ public void useAttributeFor(Class definedIn, String fieldName) { if (attributeMapper == null) { throw new InitializationException("No " + AttributeMapper.class.getName() + " available"); } try { final Field field = definedIn.getDeclaredField(fieldName); attributeMapper.addAttributeFor(field); } catch (SecurityException e) { throw new InitializationException("Unable to access field " + fieldName + "@" + definedIn.getName()); } catch (NoSuchFieldException e) { throw new InitializationException("Unable to find field " + fieldName + "@" + definedIn.getName()); } } /** * Use an XML attribute for an arbitrary type. * * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(Class type) { if (attributeMapper == null) { throw new InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(type); } /** * Associate a default implementation of a class with an object. Whenever XStream encounters an * instance of this type, it will use the default implementation instead. For example, * java.util.ArrayList is the default implementation of java.util.List. * * @param defaultImplementation * @param ofType * @throws InitializationException if no {@link DefaultImplementationsMapper} is available */ public void addDefaultImplementation(Class defaultImplementation, Class ofType) { if (defaultImplementationsMapper == null) { throw new InitializationException("No " + DefaultImplementationsMapper.class.getName() + " available"); } defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } /** * Add immutable types. The value of the instances of these types will always be written into * the stream even if they appear multiple times. * @throws InitializationException if no {@link ImmutableTypesMapper} is available */ public void addImmutableType(Class type) { if (immutableTypesMapper == null) { throw new InitializationException("No " + ImmutableTypesMapper.class.getName() + " available"); } immutableTypesMapper.addImmutableType(type); } public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(Converter converter, int priority) { converterLookup.registerConverter(converter, priority); } public void registerConverter(SingleValueConverter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(SingleValueConverter converter, int priority) { converterLookup.registerConverter(new SingleValueConverterWrapper(converter), priority); } /** * @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance * @deprecated As of 1.2, use {@link #getMapper} */ public ClassMapper getClassMapper() { if (mapper instanceof ClassMapper) { return (ClassMapper)mapper; } else { return (ClassMapper)Proxy.newProxyInstance(getClassLoader(), new Class[]{ClassMapper.class}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(mapper, args); } }); } } /** * Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}. * * @return the mapper * @since 1.2 */ public Mapper getMapper() { return mapper; } /** * Retrieve the {@link ReflectionProvider} in use. * * @return the mapper * @since 1.2.1 */ public ReflectionProvider getReflectionProvider() { return reflectionProvider; } public ConverterLookup getConverterLookup() { return converterLookup; } public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE)); break; case XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE)); break; default: throw new IllegalArgumentException("Unknown mode : " + mode); } } /** * Adds a default implicit collection which is used for any unmapped xml tag. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be an * <code>java.util.ArrayList</code>. */ public void addImplicitCollection(Class ownerType, String fieldName) { if (implicitCollectionMapper == null) { throw new InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, null, Object.class); } /** * Adds implicit collection which is used for all items of the given itemType. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be an * <code>java.util.ArrayList</code>. * @param itemType type of the items to be part of this collection. * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { if (implicitCollectionMapper == null) { throw new InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, null, itemType); } /** * Adds implicit collection which is used for all items of the given element name defined by * itemFieldName. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be an * <code>java.util.ArrayList</code>. * @param itemFieldName element name of the implicit collection * @param itemType item type to be aliases be the itemFieldName * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection( Class ownerType, String fieldName, String itemFieldName, Class itemType) { if (implicitCollectionMapper == null) { throw new InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType); } /** * Create a DataHolder that can be used to pass data to the converters. The DataHolder is provided with a * call to {@link #marshal(Object, HierarchicalStreamWriter, DataHolder)} or * {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)}. * * @return a new {@link DataHolder} */ public DataHolder newDataHolder() { return new MapBackedDataHolder(); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * Because an ObjectOutputStream can contain multiple items and XML only allows a single root * node, the stream must be written inside an enclosing node. * </p> * <p> * It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be * incomplete. * </p> * <h3>Example</h3> * * <pre> * ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, &quot;things&quot;); * out.writeInt(123); * out.writeObject(&quot;Hello&quot;); * out.writeObject(someObject) * out.close(); * </pre> * * @param writer The writer to serialize the objects to. * @param rootNodeName The name of the root node enclosing the stream of objects. * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream( final HierarchicalStreamWriter writer, String rootNodeName) throws IOException { final StatefulWriter statefulWriter = new StatefulWriter(writer); statefulWriter.startNode(rootNodeName, null); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(Object object) { marshal(object, statefulWriter); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void flush() { statefulWriter.flush(); } public void close() { if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) { statefulWriter.endNode(); statefulWriter.close(); } } }); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using * XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using * XStream. * <h3>Example</h3> * * <pre> * ObjectInputStream in = xstream.createObjectOutputStream(aReader); * int a = out.readInt(); * Object b = out.readObject(); * Object c = out.readObject(); * </pre> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); Object result = unmarshal(reader); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException("not in call to readObject"); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException("not in call to readObject"); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException("stream inactive"); } public void close() { reader.close(); } }); } /** * Change the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } /** * Change the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } /** * Prevents a field from being serialized. To omit a field you must always provide the declaring * type and not necessarily the type that is converted. * * @since 1.1.3 * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void omitField(Class type, String fieldName) { if (fieldAliasingMapper == null) { throw new InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.omitField(type, fieldName); } public static class InitializationException extends BaseException { public InitializationException(String message, Throwable cause) { super(message, cause); } public InitializationException(String message) { super(message); } } private Object readResolve() { jvm = new JVM(); return this; } }
package org.skyve.impl.util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.apache.commons.io.FilenameUtils; import org.skyve.CORE; import org.skyve.content.MimeType; import org.skyve.metadata.model.document.DynamicImage.ImageFormat; import org.skyve.metadata.repository.Repository; import org.skyve.util.FileUtil; import org.skyve.util.Util; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.util.exif.ExifFilterUtils; import net.coobird.thumbnailator.util.exif.ExifUtils; import net.coobird.thumbnailator.util.exif.Orientation; /** * Image Utility methods. */ public class ImageUtil { private static final int FIRST_IMAGE_INDEX = 0; private static final Color TRANSPARENT = new Color(0, 0, 0, 0); /** * Just like javax.imageio.ImageIO.read() but will subs-sample pixels for large images * to constrain memory usage and apply EXIF rotation. * * @param is input stream * @param subsamplingMinimumTargetSize If the images smallest dimension is twice or more this value * the image will be sub-sampled as its loaded to conserve memory. * @return The buffered image. * @throws IOException */ public static final BufferedImage read(InputStream is, int subsamplingMinimumTargetSize) throws IOException { BufferedImage result = null; try (ImageInputStream iis = ImageIO.createImageInputStream(is)) { Iterator<ImageReader> i = ImageIO.getImageReaders(iis); if (i.hasNext()) { ImageReader ir = i.next(); try { ir.setInput(iis); ImageReadParam irp = ir.getDefaultReadParam(); int smallestDimension = Math.min(ir.getWidth(FIRST_IMAGE_INDEX), ir.getHeight(FIRST_IMAGE_INDEX)); int subsampling = smallestDimension / subsamplingMinimumTargetSize; Orientation orientation = null; try { orientation = ExifUtils.getExifOrientation(ir, FIRST_IMAGE_INDEX); } catch (@SuppressWarnings("unused") Exception e) { // do nothing - could not get orientation information so just continue on } if (subsampling > 1) { irp.setSourceSubsampling(subsampling, subsampling, 0, 0); } result = ir.read(FIRST_IMAGE_INDEX, irp); // Set EXIF if ((orientation != null) && (! Orientation.TOP_LEFT.equals(orientation))) { result = ExifFilterUtils.getFilterForOrientation(orientation).apply(result); } } finally { ir.dispose(); } } } return result; } /** * Return UTF-8 byte array for an SVG representing the type of the file. * * @param fileName The filename suffix is used to get the svg file type icon * @param imageWidth The requested width. * @param imageHeight The requested height. * @return A byte[] to stream to a client. * @throws IOException */ public static byte[] svg(String fileName, int imageWidth, int imageHeight) throws IOException { String suffix = Util.processStringValue(FilenameUtils.getExtension(fileName)); Repository repository = CORE.getRepository(); File svgFile = null; if (suffix == null) { svgFile = repository.findResourceFile("files/blank.svg", null, null); } else { suffix = suffix.toLowerCase(); svgFile = repository.findResourceFile(String.format("files/%s.svg", suffix) , null, null); if (! svgFile.exists()) { svgFile = repository.findResourceFile("files/blank.svg", null, null); } } // Add the requested width and height to the SVG so that it can be scaled // and keep its aspect ratio in the browser <img/>. String xml = FileUtil.getFileAsString(svgFile); xml = String.format("<svg width=\"%dpx\" height=\"%dpx\" %s", Integer.valueOf(imageWidth), Integer.valueOf(imageHeight), xml.substring(5)); return xml.getBytes(Util.UTF8); } /** * Read the bytes from an image file. * * @param file The file to read. * @return the bytes. * @throws IOException */ public static byte[] image(File file) throws IOException { try (FileInputStream fis = new FileInputStream(file)) { return image(fis); } } /** * Read the bytes from an image InputStream. * * @param is The input stream to read. * @return the bytes. * @throws IOException */ public static byte[] image(InputStream is) throws IOException { try (BufferedInputStream bis = new BufferedInputStream(is)) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { byte[] bytes = new byte[1024]; int bytesRead = 0; while ((bytesRead = bis.read(bytes)) > 0) { baos.write(bytes, 0, bytesRead); } return baos.toByteArray(); } } } public static byte[] signature(String json, int width, int height, String rgbHexBackgroundColour, String rgbHexForegroundColour) throws IOException { List<List<Point>> lines = new ArrayList<>(); Matcher lineMatcher = Pattern.compile("(\\[(?:,?\\[-?[\\d\\.]+,-?[\\d\\.]+\\])+\\])").matcher(json); while (lineMatcher.find()) { Matcher pointMatcher = Pattern.compile("\\[(-?[\\d\\.]+),(-?[\\d\\.]+)\\]").matcher(lineMatcher.group(1)); List<Point> line = new ArrayList<>(); lines.add(line); while (pointMatcher.find()) { line.add(new Point(Math.round(Float.parseFloat(pointMatcher.group(1))), Math.round(Float.parseFloat(pointMatcher.group(2))))); } } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor((rgbHexBackgroundColour == null) ? TRANSPARENT : Color.decode(rgbHexBackgroundColour)); g.fillRect(0, 0, width, height); g.setColor((rgbHexForegroundColour == null) ? Color.BLACK : Color.decode(rgbHexForegroundColour)); g.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Point lastPoint = null; for (List<Point> line : lines) { for (Point point : line) { if (lastPoint != null) { g.drawLine(lastPoint.x, lastPoint.y, point.x, point.y); } lastPoint = point; } lastPoint = null; } try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { ImageIO.write(image, ImageFormat.png.toString(), output); return output.toByteArray(); } } public static byte[] reduceImageSize(MimeType mimeType, byte[] bytes) throws Exception { // Convert max image upload size from MegaBytes to Bytes (/1024^2) Integer maxImageSizeBytes = UtilImpl.UPLOADS_IMAGE_MAXIMUM_SIZE_IN_MB / 1048576; if (MimeType.jpeg.equals(mimeType) || MimeType.png.equals(mimeType)) { if (bytes.length > maxImageSizeBytes) { try (InputStream is = new ByteArrayInputStream(bytes)) { BufferedImage image = ImageUtil.read(is, UtilImpl.THUMBNAIL_SUBSAMPLING_MINIMUM_TARGET_SIZE); int width = image.getWidth(); int height = image.getHeight(); // change width and height to a fraction of it width and height somehow (keeping aspect ratio) image = Thumbnails.of(image).size(width, height).keepAspectRatio(true).asBufferedImage(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { // Create the thumb nail Thumbnails.of(image).scale(1.0).outputFormat(MimeType.jpeg.getStandardFileSuffix()).toOutputStream(baos); return baos.toByteArray(); } } } } return bytes; } }
package com.tealcube.slots1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import java.util.Random; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private static final Random RANDOM = new Random(); private ImageView flower1View; private ImageView flower2View; private ImageView flower3View; private int moneyInTheBank = Constants.STARTING_SPINS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); flower1View = (ImageView) findViewById(R.id.flower_1); flower2View = (ImageView) findViewById(R.id.flower_2); flower3View = (ImageView) findViewById(R.id.flower_3); ((TextView) findViewById(R.id.dollar_amount)).setText(getString(R.string.dollar_text, moneyInTheBank)); final ImageView resetButton = (ImageView) findViewById(R.id.reset_button); final ImageView goButton = (ImageView) findViewById(R.id.go_button); resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { moneyInTheBank = Constants.STARTING_SPINS; flower1View.setImageResource(R.drawable.f1); flower2View.setImageResource(R.drawable.f2); flower3View.setImageResource(R.drawable.f3); ((TextView) findViewById(R.id.dollar_amount)).setText(getString(R.string.dollar_text, moneyInTheBank)); resetButton.setVisibility(View.INVISIBLE); resetButton.setClickable(false); goButton.setVisibility(View.VISIBLE); goButton.setClickable(true); Log.d(TAG, "resets on resets"); } }); goButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (resetButton.getVisibility() == View.INVISIBLE) { resetButton.setVisibility(View.VISIBLE); resetButton.setClickable(true); } if (moneyInTheBank <= Constants.MINIMUM_SPINS) { Log.d(TAG, "money in the bank is less than minimum spins"); goButton.setVisibility(View.INVISIBLE); goButton.setClickable(false); return; } moneyInTheBank = Math.max(moneyInTheBank - Constants.COST_PER_SPIN, Constants.MINIMUM_SPINS); ((TextView) findViewById(R.id.dollar_amount)).setText(getString(R.string.dollar_text, moneyInTheBank)); Log.d(TAG, "taking money from the spinner"); Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { if (flower1View != null) { flower1View.setImageResource(R.drawable.tmp); } if (flower2View != null) { flower2View.setImageResource(R.drawable.tmp); } if (flower3View != null) { flower3View.setImageResource(R.drawable.tmp); } } @Override public void onAnimationEnd(Animation animation) { int flower1Int = RANDOM.nextInt(Constants.NUMBER_OF_FLOWERS); int flower2Int = RANDOM.nextInt(Constants.NUMBER_OF_FLOWERS); int flower3Int = RANDOM.nextInt(Constants.NUMBER_OF_FLOWERS); if (flower1Int == flower2Int && flower2Int == flower3Int) { // all three match moneyInTheBank += Constants.MATCH_3; } else if (flower1Int == flower2Int || flower2Int == flower3Int || flower1Int == flower3Int) { // two match moneyInTheBank += Constants.MATCH_2; } else { // no match moneyInTheBank += Constants.MATCH_0; } moneyInTheBank = Math.max(moneyInTheBank, Constants.MINIMUM_SPINS); ((TextView) findViewById(R.id.dollar_amount)).setText(getString(R.string.dollar_text, moneyInTheBank)); if (moneyInTheBank <= Constants.MINIMUM_SPINS) { Log.d(TAG, "money in the bank is less than minimum spins"); goButton.setVisibility(View.INVISIBLE); goButton.setClickable(false); } flower1View.setImageResource(getFlower(flower1Int)); flower2View.setImageResource(getFlower(flower2Int)); flower3View.setImageResource(getFlower(flower3Int)); } @Override public void onAnimationRepeat(Animation animation) { } }); flower1View.startAnimation(animation); flower2View.startAnimation(animation); flower3View.startAnimation(animation); Log.d(TAG, "spin to win"); } }); } protected int getFlower(int i) { switch (i) { case 1: return R.drawable.f1; case 2: return R.drawable.f2; default: return R.drawable.f3; } } }
package storm2014.commands.autonomous; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import edu.wpi.first.wpilibj.command.PrintCommand; import edu.wpi.first.wpilibj.command.WaitCommand; import storm2014.Robot; import storm2014.commands.DriveForward; import storm2014.commands.Launch; import storm2014.commands.PreFire; import storm2014.commands.Reset; import storm2014.commands.SetArmPosition; import storm2014.commands.Shift; import storm2014.commands.SpinRoller; import storm2014.commands.WaitForEncoder; import storm2014.subsystems.Catapult; /** * * @author Tim */ public class DriveAndShoot2Ball extends CommandGroup{ private Command _waitAndRoll() { CommandGroup _waitAndRoll = new CommandGroup("Waits then rolls in the spinner"); _waitAndRoll.addSequential(new WaitCommand(1.25)); _waitAndRoll.addSequential(new SpinRoller(-1)); return _waitAndRoll; } public DriveAndShoot2Ball() { addSequential(new Shift(true)); addSequential(new SetArmPosition(2)); addParallel(new SpinRoller((float) -0.4)); addSequential(new WaitCommand(0.3)); addSequential(new Shift(false)); addParallel(new PreFire()); addSequential(new DriveForward(1, 4000)); addSequential(new SpinRoller(0)); addSequential(new Launch()); addParallel(_waitAndRoll()); addSequential(new Reset()); addParallel(new PreFire()); addSequential(new WaitCommand(1.5)); addSequential(new SpinRoller(0)); addSequential(new WaitCommand(0.5)); addSequential(new Launch()); addSequential(new Reset()); } }
package storm2014.commands.autonomous; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import edu.wpi.first.wpilibj.command.PrintCommand; import edu.wpi.first.wpilibj.command.WaitCommand; import edu.wpi.first.wpilibj.command.WaitForChildren; import storm2014.Robot; import storm2014.commands.DriveForward; import storm2014.commands.Launch; import storm2014.commands.PreFire; import storm2014.commands.Reset; import storm2014.commands.SetArmPosition; import storm2014.commands.Shift; import storm2014.commands.SpinRoller; import storm2014.commands.WaitForEncoder; import storm2014.subsystems.Catapult; /** * * @author Tim */ public class DriveAndShoot2Ball extends CommandGroup{ private Command _waitAndRoll() { CommandGroup _waitAndRoll = new CommandGroup("Waits then rolls in the spinner"); _waitAndRoll.addSequential(new WaitCommand(1.25)); _waitAndRoll.addSequential(new SpinRoller(-1)); return _waitAndRoll; } private Command _waitAndLetRoll(){ CommandGroup _waitAndMoveArms = new CommandGroup(); _waitAndMoveArms.addSequential(new WaitForEncoder(4200 - 1000)); _waitAndMoveArms.addSequential(new SetArmPosition(0)); _waitAndMoveArms.addSequential(new WaitCommand(0.75)); _waitAndMoveArms.addSequential(new SetArmPosition(2)); CommandGroup _waitAndPrefire = new CommandGroup(); _waitAndPrefire.addSequential(new WaitCommand(0.75)); _waitAndPrefire.addParallel(new PreFire()); CommandGroup _waitAndLetRoll = new CommandGroup("rolls ball out of way"); _waitAndLetRoll.addParallel(_waitAndPrefire); _waitAndLetRoll.addParallel(_waitAndMoveArms); _waitAndLetRoll.addSequential(new WaitForEncoder(4200 - 300)); _waitAndLetRoll.addSequential(new SpinRoller(0)); return _waitAndLetRoll; } public DriveAndShoot2Ball() { addSequential(new Shift(true)); addSequential(new SetArmPosition(2)); addParallel(new SpinRoller((float) -0.6)); addSequential(new WaitCommand(0.3)); addParallel(_waitAndLetRoll()); addSequential(new DriveForward(1, 4200)); addSequential(new WaitCommand(1.0)); addSequential(new Launch()); addParallel(_waitAndRoll()); addSequential(new Reset()); addParallel(new PreFire()); addSequential(new WaitCommand(0.5)); addSequential(new SpinRoller(0)); addSequential(new SetArmPosition(0)); addSequential(new WaitCommand(0.75)); addSequential(new SetArmPosition(2)); addSequential(new WaitCommand(1.0)); addSequential(new Launch()); addSequential(new Reset()); } }
package com.cloudant.tests; import static org.junit.Assert.assertNotNull; import java.util.List; import java.util.Properties; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.lightcouch.CouchDbException; import com.cloudant.client.api.CloudantClient; import com.cloudant.client.api.model.ApiKey; import com.cloudant.client.api.model.Membership; import com.cloudant.client.api.model.Task; import com.cloudant.tests.util.Utils; public class CloudantClientTests { private static final Log log = LogFactory.getLog(CloudantClientTests.class); private static CloudantClient account; public static CloudantClient cookieBasedClient; private static Properties props; @BeforeClass public static void setUpClass() { props = Utils.getProperties("cloudant.properties", log); account = new CloudantClient(props.getProperty("cloudant.account"), props.getProperty("cloudant.username"), props.getProperty("cloudant.password")); String cookie = account.getCookie(); cookieBasedClient = new CloudantClient( props.getProperty("cloudant.account"), cookie); } @AfterClass public static void tearDownClass() { account.shutdown(); } @Test public void apiKey() { ApiKey key = account.generateApiKey(); assertNotNull(key); assertNotNull(key.getKey()); assertNotNull(key.getPassword()); } @Test public void activeTasks() { List<Task> tasks = account.getActiveTasks(); assertNotNull(tasks); } @Test public void membership() { Membership mship = account.getMembership(); assertNotNull(mship); assertNotNull(mship.getClusterNodes()); assertNotNull(mship.getClusterNodes().hasNext()); assertNotNull(mship.getAllNodes()); assertNotNull(mship.getAllNodes().hasNext()); } @Test public void cookieTest() { Membership membership = cookieBasedClient.getMembership(); assertNotNull(membership); } @Test public void cookieAPITest() { try { cookieBasedClient.generateApiKey(); Assert.fail("Passed cloudant.com based generateapikey without creds"); } catch(IllegalArgumentException e) { } } @Test public void cookieNegativeTest() { String cookie = account.getCookie() + "XXX"; boolean exceptionRaised = true; try { new CloudantClient( props.getProperty("cloudant.account"), cookie).getAllDbs(); exceptionRaised = false; } catch (CouchDbException e) { if ( e.getMessage().contains("Forbidden") ) { exceptionRaised = true; } } if (exceptionRaised == false) { Assert.fail("could connect to cloudant with random AuthSession cookie"); } } }
package com.flowlikeariver.kakuro2; import static com.flowlikeariver.kakuro2.Kakuro.a; import static com.flowlikeariver.kakuro2.Kakuro.allDifferent; import static com.flowlikeariver.kakuro2.Kakuro.concatLists; import static com.flowlikeariver.kakuro2.Kakuro.d; import static com.flowlikeariver.kakuro2.Kakuro.da; import static com.flowlikeariver.kakuro2.Kakuro.drawRow; import static com.flowlikeariver.kakuro2.Kakuro.e; import static com.flowlikeariver.kakuro2.Kakuro.gatherValues; import static com.flowlikeariver.kakuro2.Kakuro.solvePair; import static com.flowlikeariver.kakuro2.Kakuro.solver; import static com.flowlikeariver.kakuro2.Kakuro.takeWhile; import static com.flowlikeariver.kakuro2.Kakuro.transpose; import static com.flowlikeariver.kakuro2.Kakuro.v; import java.util.Arrays; import static java.util.Arrays.asList; import java.util.List; import static java.util.stream.Collectors.toList; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TestKakuro2 { @Test public void testDrawRow() { List<Cell> line = asList(da(3, 4), v(), v(1, 2), d(4), e(), a(5), v(4), v(1)); String result = drawRow(line); System.out.println(result); assertEquals(" 3\\ 4 123456789 12....... 4\\ } @Test public void testPermute() { List<ValueCell> vs = asList(v(), v(), v()); List<List<Integer>> results = Kakuro.permuteAll(vs, 6); System.out.println(results); assertEquals(10, results.size()); List<List<Integer>> diff = results.stream() .filter(p -> allDifferent(p)) .collect(toList()); assertEquals(6, diff.size()); } @Test public void testTranspose() { List<List<Integer>> ints = IntStream.range(0, 3) .mapToObj(i -> IntStream.range(0, 4) .boxed() .collect(toList())) .collect(toList()); List<List<Integer>> tr = transpose(ints); System.out.println(ints); System.out.println(tr); assertEquals(ints.size(), tr.get(0).size()); assertEquals(ints.get(0).size(), tr.size()); } @Test public void testTakeWhile() { List<Integer> result = takeWhile(n -> n < 4, IntStream.range(0, 10).mapToObj(i -> i).collect(toList())); System.out.println(result); assertEquals(4, result.size()); } @Test public void testConcat() { List<Integer> a = asList(1, 2, 3); List<Integer> b = asList(4, 5, 6, 1, 2, 3); List<Integer> result = concatLists(a, b); System.out.println(result); assertEquals(9, result.size()); } @Test public void testDrop() { List<Integer> a = asList(1, 2, 3, 4, 5, 6); List<Integer> result = Kakuro.drop(4, a); System.out.println(result); assertEquals(2, result.size()); } @Test public void testTake() { List<Integer> a = asList(1, 2, 3, 4, 5, 6); List<Integer> result = Kakuro.take(4, a); System.out.println(result); assertEquals(4, result.size()); } @Test public void testPartBy() { List<Integer> data = asList(1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9); List<List<Integer>> result = Kakuro.partitionBy(n -> 0 == (n % 2), data); System.out.println(result); assertEquals(9, result.size()); } @Test public void testPartAll() { List<Integer> data = Arrays.asList(1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9); List<List<Integer>> result = Kakuro.partitionAll(5, 3, data); System.out.println(result); assertEquals(5, result.size()); } @Test public void testPartN() { List<Integer> data = Arrays.asList(1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9); List<List<Integer>> result = Kakuro.partitionN(5, data); System.out.println(result); assertEquals(3, result.size()); } @Test public void testSolveStep() { List<ValueCell> result = Kakuro.solveStep(Arrays.asList(v(1, 2), v()), 5); System.out.println("solve step " + result); assertEquals(v(1, 2), result.get(0)); assertEquals(v(3, 4), result.get(1)); } @Test public void testGatherValues() { List<Cell> line = Arrays.asList(da(3, 4), v(), v(), d(4), e(), a(4), v(), v()); List<List<Cell>> result = gatherValues(line); System.out.println("gather " + result); assertEquals(4, result.size()); assertEquals(da(3, 4), result.get(0).get(0)); assertEquals(d(4), result.get(2).get(0)); assertEquals(e(), result.get(2).get(1)); assertEquals(a(4), result.get(2).get(2)); } @Test public void testPairTargets() { List<Cell> line = asList(da(3, 4), v(), v(), d(4), e(), a(4), v(), v()); List<SimplePair<List<Cell>>> result = Kakuro.pairTargetsWithValues(line); System.out.println("pair " + result); assertEquals(2, result.size()); assertEquals(da(3, 4), result.get(0).left.get(0)); assertEquals(d(4), result.get(1).left.get(0)); assertEquals(e(), result.get(1).left.get(1)); assertEquals(a(4), result.get(1).left.get(2)); } @Test public void testSolvePair() { List<Cell> line = asList(da(3, 4), v(), v(), d(4), e(), a(4), v(), v()); List<SimplePair<List<Cell>>> pairs = Kakuro.pairTargetsWithValues(line); SimplePair<List<Cell>> pair = pairs.get(0); List<Cell> result = solvePair(cell -> ((Down) cell).getDown(), pair); System.out.println("solvePair " + result); assertEquals(3, result.size()); assertEquals(v(1, 2), result.get(1)); assertEquals(v(1, 2), result.get(2)); } @Test public void testSolveLine() { List<Cell> line = asList(da(3, 4), v(), v(), d(4), e(), a(5), v(), v()); List<Cell> result = Kakuro.solveLine(line, v -> solvePair(x -> ((Across) x).getAcross(), v)); System.out.println("solve line " + result); assertEquals(8, result.size()); assertEquals(v(1, 3), result.get(1)); assertEquals(v(1, 3), result.get(2)); assertEquals(v(1, 2, 3, 4), result.get(6)); assertEquals(v(1, 2, 3, 4), result.get(7)); } @Test public void testSolveRow() { List<Cell> result = Kakuro.solveRow(asList(a(3), v(1, 2, 3), v(1))); System.out.println("solve row " + result); assertEquals(v(2), result.get(1)); assertEquals(v(1), result.get(2)); } @Test public void testSolveCol() { List<Cell> result = Kakuro.solveColumn(asList(da(3, 12), v(1, 2, 3), v(1))); System.out.println("solve col " + result); assertEquals(v(2), result.get(1)); assertEquals(v(1), result.get(2)); } @Test public void testSolver() { List<List<Cell>> grid1 = asList( asList(e(), d(4), d(22), e(), d(16), d(3)), asList(a(3), v(), v(), da(16, 6), v(), v()), asList(a(18), v(), v(), v(), v(), v()), asList(e(), da(17, 23), v(), v(), v(), d(14)), asList(a(9), v(), v(), a(6), v(), v()), asList(a(15), v(), v(), a(12), v(), v())); List<List<Cell>> result = solver(grid1); assertEquals(" --\\ 3 1 2 16\\ 6 4 2 \n", drawRow(result.get(1))); assertEquals(" --\\18 3 5 7 2 1 \n", drawRow(result.get(2))); assertEquals(" assertEquals(" --\\ 9 8 1 --\\ 6 1 5 \n", drawRow(result.get(4))); assertEquals(" --\\15 9 6 --\\12 3 9 \n", drawRow(result.get(5))); } }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.border.LineBorder; import com.esri.core.geometry.Envelope; import com.esri.core.map.Graphic; import com.esri.core.map.ResamplingProcessType; import com.esri.core.raster.FileRasterSource; import com.esri.core.renderer.Colormap; import com.esri.core.renderer.ColormapRenderer; import com.esri.core.renderer.RGBRenderer; import com.esri.core.renderer.StretchParameters; import com.esri.core.symbol.SimpleLineSymbol; import com.esri.core.symbol.Symbol; import com.esri.map.ArcGISTiledMapServiceLayer; import com.esri.map.GraphicsLayer; import com.esri.map.JMap; import com.esri.map.Layer; import com.esri.map.RasterLayer; public class LocalRasterApp { private JMap map; private JButton button; private JLayeredPane contentPane; private static final String FSP = System.getProperty("file.separator"); private List<Layer> rasters; private FileRasterSource rasterSource = null; public LocalRasterApp() { rasters = new ArrayList<>(); } /** * Checks a folder for files matching an extension * * @throws Exception */ private void addRaster() throws Exception { GraphicsLayer gLayer = new GraphicsLayer(); map.getLayers().add(gLayer); //Add graphics layer to the array rasters.add(gLayer); gLayer.setName("Raster Layer"); // Open the folder containing the images String baseFolder = "D:" + FSP + "Landsat_p114r75"; System.out.println(baseFolder); File folder = new File(baseFolder); //Define footprints Symbol symbol = new SimpleLineSymbol(Color.magenta, 2); /* Create a graphics layer, add rasters to the graphics layer, * add graphics layer to the map. */ for (File rasterFile : folder.listFiles()) { try { if (!rasterFile.getName().endsWith(".tif")) { continue; } //New raster from file rasterSource = new FileRasterSource(rasterFile.getAbsolutePath()); rasterSource.project(map.getSpatialReference()); // new raster layer RasterLayer rasterLayer = new RasterLayer(rasterSource); rasterLayer.setName(rasterFile.getName()); // Create a raster layer graphic. Add the raster and footprint Graphic g = new Graphic(rasterLayer.getFullExtent(), symbol); gLayer.addGraphic(g); //Make sure it's not null or not in the map already if ((rasterLayer == null) || (!rasterLayer.isVisible())) { return; } //Apply an RGBRenderer addRgbRenderer(rasterLayer, true); //Populate the layer array for looping (optional) rasters.add(rasterLayer); // Add the layer array to the map. map.getLayers().add(rasterLayer); //Zoom to the newly added raster layers. map.zoomTo(rasterLayer.getFullExtent()); } catch (FileNotFoundException e) { e.printStackTrace(); } } //Do something with the optional array of layers System.out.println("Layers added:"); for (Layer layer : rasters) { System.out.println("\t" + layer.getName()); } } public void addRgbRenderer(RasterLayer mRasterLayer, boolean isDefault) throws Exception{ //Basic stretch renderer usage RGBRenderer renderer=new RGBRenderer(); if(isDefault){ renderer.setBandIds(new int[]{0,1,2}); } else { renderer.setBandIds(new int[]{0,2,1}); } StretchParameters.MinMaxStretchParameters stretchParameters = new StretchParameters.MinMaxStretchParameters(); stretchParameters.setGamma(1); renderer.setStretchParameters(stretchParameters); mRasterLayer.setRenderer(renderer); mRasterLayer.setBrightness(75.0f); mRasterLayer.setContrast(75.0f); mRasterLayer.setGamma(10.0f); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { // instance of this application LocalRasterApp rasterApp = new LocalRasterApp(); // create the UI, including the map, for the application. JFrame appWindow = createWindow(); appWindow.add(rasterApp.createUI()); } catch (Exception e) { // on any error, display the stack trace. e.printStackTrace(); } } }); } /** GUI Components **/ public JComponent createUI() { // application content contentPane = createContentPane(); // UI elements JPanel buttonPanel = createUserPanel(); contentPane.add(buttonPanel); // map map = createMap(); map.setHidingNoDataTiles(true); contentPane.add(map); return contentPane; } private JMap createMap() { final JMap jMap = new JMap(); ArcGISTiledMapServiceLayer tiledLayer = new ArcGISTiledMapServiceLayer("http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"); jMap.getLayers().add(tiledLayer); jMap.setExtent(new Envelope(-19856505, -8827900, 18574809, 16806021)); return jMap; } private JPanel createUserPanel() { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout(0, 0)); panel.setSize(140, 35); panel.setLocation(10, 10); // button button = createButton(); panel.add(button, BorderLayout.SOUTH); panel.setBackground(new Color(0, 0, 0, 0)); panel.setBorder(new LineBorder(new Color(0, 0, 0, 80), 5, false)); return panel; } private JButton createButton() { JButton button1 = new JButton("Add Raster"); button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { addRaster(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return button1; } private static JFrame createWindow() { JFrame window = new JFrame(); window.setBounds(100, 100, 1000, 700); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().setLayout(new BorderLayout(0, 0)); window.setVisible(true); return window; } private static JLayeredPane createContentPane() { JLayeredPane contentPane = new JLayeredPane(); contentPane.setBounds(100, 100, 1000, 700); contentPane.setLayout(new BorderLayout(0, 0)); contentPane.setVisible(true); return contentPane; } }
package com.torstling.tdop.fluid.json; import com.torstling.tdop.core.*; import com.torstling.tdop.fluid.Language; import com.torstling.tdop.fluid.LanguageBuilder2; import com.torstling.tdop.fluid.TokenDefinition; import com.torstling.tdop.fluid.TokenDefinitionBuilder; import com.torstling.tdop.fluid.json.nodes.*; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class JsonTest { @Test public void simpleStringLiteral() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(stringLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("\"hello\""); assertEquals(new StringLiteralNode("hello"), ast); } @Test public void stringWithQuoteEscape() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(stringLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("\"\\\"hello\""); assertEquals(new StringLiteralNode("\\\"hello"), ast); } @Test public void stringWithInvalidEscape() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(stringLiteral()) .completeLanguage(); ParseResult<JsonNode> pr = l.getParser().tryParse("\"\\phello\""); assertEquals(ParsingFailedInformation.forFailedLexing(new LexingFailedInformation("No matching rule for char-range starting at 0: '\"\\phello\"'", new LexingPosition(0, "\"\\phello\""))), pr.getErrorMessage()); } @Test public void positiveInteger() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(numberLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("1"); assertEquals(new NumberLiteralNode(1), ast); } @Test public void negativeExponent() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(numberLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("-0.5e-5"); assertEquals(new NumberLiteralNode(-0.5e-5f), ast); } @Test public void leadingZeroesForbidden() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(numberLiteral()) .completeLanguage(); try { l.getParser().parse("01.5"); fail("Expected exception"); } catch (ParsingFailedException e) { assertEquals(ParsingFailedInformation.forFailedAfterLexing("Expected a token of type 'EndTokenType', but got 'number_literal(1.5)'", new ParsingPosition(4, "1.5")), e.getParsingFailedInformation()); } } @Test public void bool() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(boolLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("true"); assertEquals(new BooleanLiteralNode(true), ast); } @Test public void nul() { Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(nullLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("null"); assertEquals(NullLiteral.get(), ast); } @Test public void emptyArray() { TokenDefinition<JsonNode> rbracket = rbracket(); Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(rbracket).addToken(lbracket(rbracket, comma())).newLevel().addToken(numberLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("[]"); assertEquals(new ArrayNode(Collections.emptyList()), ast); } @Test public void singleElementArray() { TokenDefinition<JsonNode> rbracket = rbracket(); Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(rbracket).addToken(lbracket(rbracket, comma())).newLevel().addToken(numberLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("[3]"); assertEquals(new ArrayNode(Arrays.asList(new NumberLiteralNode(3))), ast); } @Test public void multipleElementArray() { TokenDefinition<JsonNode> rbracket = rbracket(); TokenDefinition<JsonNode> comma = comma(); Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(comma).addToken(rbracket).addToken(lbracket(rbracket, comma)).newLevel().addToken(numberLiteral()) .completeLanguage(); JsonNode ast = l.getParser().parse("[3,2,4]"); assertEquals(new ArrayNode(Arrays.asList(new NumberLiteralNode(3), new NumberLiteralNode(2), new NumberLiteralNode(4))), ast); } @Test public void emptyObject() { TokenDefinition<JsonNode> rcurly = rcurly(); TokenDefinition<JsonNode> comma = comma(); TokenDefinition<JsonNode> string = stringLiteral(); Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(comma).addToken(rcurly).addToken(lcurly(rcurly, comma, colon(), string)).newLevel().addToken(numberLiteral()) .addToken(string).completeLanguage(); JsonNode ast = l.getParser().parse("{}"); assertEquals(new ObjectNode(Collections.emptyMap()), ast); } @Test public void simpleObject() { TokenDefinition<JsonNode> rcurly = rcurly(); TokenDefinition<JsonNode> comma = comma(); TokenDefinition<JsonNode> string = stringLiteral(); TokenDefinition<JsonNode> colon = colon(); Language<JsonNode> l = new LanguageBuilder2<JsonNode>() .newLevel().addToken(comma).addToken(colon).addToken(rcurly).addToken(lcurly(rcurly, comma, colon, string)).newLevel().addToken(numberLiteral()) .addToken(string).completeLanguage(); JsonNode ast = l.getParser().parse("{\"a\":3}"); LinkedHashMap<StringLiteralNode, JsonNode> expected = new LinkedHashMap<>(); expected.put(new StringLiteralNode("a"), new NumberLiteralNode(3)); assertEquals(new ObjectNode(expected), ast); } @NotNull private TokenDefinition<JsonNode> rbracket() { return new TokenDefinitionBuilder<JsonNode>().named("rbracket").matchesString("]") .build(); } @NotNull private TokenDefinition<JsonNode> rcurly() { return new TokenDefinitionBuilder<JsonNode>().named("rculry").matchesString("}") .build(); } @NotNull private TokenDefinition<JsonNode> comma() { return new TokenDefinitionBuilder<JsonNode>().named("comma").matchesString(",") .build(); } @NotNull private TokenDefinition<JsonNode> colon() { return new TokenDefinitionBuilder<JsonNode>().named("colon").matchesString(":") .build(); } @NotNull private TokenDefinition<JsonNode> lbracket(TokenDefinition<JsonNode> rbracket, TokenDefinition<JsonNode> comma) { return new TokenDefinitionBuilder<JsonNode>().named("lbracket").matchesString("[") .prefixParseAs((previous, match, parser) -> { ArrayList<JsonNode> expressions = new ArrayList<>(); while (!parser.nextIs(rbracket)) { expressions.add(parser.expression(previous)); if (!parser.nextIs(rbracket)) { parser.expectSingleToken(comma); } } parser.expectSingleToken(rbracket); return new ArrayNode(expressions); }).build(); } @NotNull private TokenDefinition<JsonNode> lcurly(TokenDefinition<JsonNode> rcurly, TokenDefinition<JsonNode> comma, TokenDefinition<JsonNode> colon, TokenDefinition<JsonNode> string) { return new TokenDefinitionBuilder<JsonNode>().named("lcurly").matchesString("{") .prefixParseAs((previous, match, parser) -> { LinkedHashMap<StringLiteralNode, JsonNode> pairs = new LinkedHashMap<>(); while (!parser.nextIs(rcurly)) { StringLiteralNode key = (StringLiteralNode) parser.parseSingleToken(previous, string); parser.expectSingleToken(colon); JsonNode value = parser.expression(previous); pairs.put(key, value); if (!parser.nextIs(rcurly)) { parser.expectSingleToken(comma); } } parser.expectSingleToken(rcurly); return new ObjectNode(pairs); }).build(); } private TokenDefinition<JsonNode> nullLiteral() { return new TokenDefinitionBuilder<JsonNode>().named("null_literal").matchesString("null") .standaloneParseAs((previous, match) -> NullLiteral.get()).build(); } @NotNull private TokenDefinition<JsonNode> boolLiteral() { return new TokenDefinitionBuilder<JsonNode>().named("bool_literal").matchesPattern("(true)|(false)") .standaloneParseAs((previous, match) -> new BooleanLiteralNode(Boolean.valueOf(match.getText()))).build(); } @NotNull private TokenDefinition<JsonNode> stringLiteral() { @org.intellij.lang.annotations.Language("RegExp") String pattern = "\"((?:[^\"\\\\]|\\\\(?:[\"\\/bnrft]|u[0-9A-F]{4}))*)\""; return new TokenDefinitionBuilder<JsonNode>().named("string_literal").matchesPattern(pattern) .standaloneParseAs((previous, match) -> { String withinQuotationMarks = match.group(1); return new StringLiteralNode(withinQuotationMarks); }).build(); } @NotNull private TokenDefinition<JsonNode> numberLiteral() { return new TokenDefinitionBuilder<JsonNode>().named("number_literal").matchesPattern("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE]([+-])?[0-9]+)?") .standaloneParseAs((previous, match) -> new NumberLiteralNode(Float.valueOf(match.getText()))).build(); } }
package com.zeroq6.moehelper.test; import com.zeroq6.moehelper.config.Configuration; import com.zeroq6.moehelper.test.help.*; import com.zeroq6.moehelper.utils.MyLogUtils; import org.apache.commons.io.FileUtils; import org.junit.Test; import java.io.File; import java.util.Collection; import java.util.List; public class PostSyncTest { private final static String WORK_FILE_CONTAINS_404 = "_404_"; private final static String WORK_FILE_CONTAINS_MD5_ERR = "_md5_err_"; @Test public void test() throws Exception { String srcWorkSpaceDir = "C:\\Users\\yuuki asuna\\Desktop\\workspace"; String[] targetStorePostDirArray = new String[]{"H:\\post"}; for (String item : targetStorePostDirArray) { syncAndCheck(srcWorkSpaceDir, item); } } public static void syncAndCheck(String srcWorkSpaceDir, String targetStorePostDir) throws Exception { FileFilter fileFilter = new FileFilter(srcWorkSpaceDir); WorkSpaceValidator.checkAndSetReadOnlyWorkSpaceDir(srcWorkSpaceDir); MyLogUtils.stdOut(srcWorkSpaceDir + "\t"); File[] files = new File(targetStorePostDir).listFiles(); if (null == files || files.length == 0) { return; } MyLogUtils.stdOut(" for (File item : files) { String name = item.getName(); final EndStringType endStringType; if (!name.contains("_-_Pack_")) { continue; } if (item.isFile()) { continue; } if (name.startsWith(Configuration.HOST_KONA)) { endStringType = EndStringType.KONA_All; } else if (name.startsWith(Configuration.HOST_MOE)) { if (name.endsWith(EndStringType.MOE_IN_POOL.getEndString())) { endStringType = EndStringType.MOE_IN_POOL; } else if (name.endsWith(EndStringType.MOE_NOT_IN_POOL.getEndString())) { endStringType = EndStringType.MOE_NOT_IN_POOL; } else { throw new RuntimeException("" + name); } } else { throw new RuntimeException("" + name); } String[] splitArray = name.split("[_()]"); int start = Integer.valueOf(splitArray[4]); int end = Integer.valueOf(splitArray[5]); // md5 List<File> md5FileList = fileFilter.filter(file -> file.getName().startsWith(endStringType.getHost()) && file.getName().contains("_" + start + "_" + end) && file.getName().endsWith(endStringType.getEndStringInMd5File()), 1); if (md5FileList.size() != 1) { throw new RuntimeException("md5File.size() != 1, " + item.getName()); } File md5File = md5FileList.get(0); if (md5File.exists()) { md5File.setReadable(true); } FileUtils.copyFileToDirectory(md5File, item); MyLogUtils.stdOut("MD5" + md5FileList.get(0).getCanonicalPath()); // work List<File> workFileList = fileFilter.filter(file -> file.getName().startsWith(endStringType.getHost()) && file.getName().contains("_" + start + "_" + end)); int predictCount = 11; for (File f : workFileList) { String fileName = f.getName(); if (fileName.contains(WORK_FILE_CONTAINS_404)) { predictCount++; } else if (fileName.contains(WORK_FILE_CONTAINS_MD5_ERR)) { predictCount++; } } if (workFileList.size() != predictCount) { throw new RuntimeException(String.format("workFileList.size(%s) != predictCount(%s)", workFileList.size(), predictCount)); } File zipFile = new File(item, item.getName() + "_data.zip"); if (zipFile.exists()) { zipFile.setReadable(true); } ZipUtils.zipFileFolders(zipFile, workFileList, item.getName() + "_data"); MyLogUtils.stdOut("(" + workFileList.size() + "): " + zipFile.getCanonicalPath()); Collection<File> imageFileList = FileUtils.listFiles(item, new String[]{"jpg", "jpeg", "gif", "png", "swf"}, false); Collection<File> imageFileWithMd5ZipList = FileUtils.listFiles(item, null, true); if (imageFileList.size() + 2 != imageFileWithMd5ZipList.size()) { throw new RuntimeException("imageFileList.size + 2 != imageFileWithMd5ZipList.size"); } // MD5,,zip imageFileWithMd5ZipList.stream().forEach(file -> file.setReadOnly()); PostStatistics postStatistics = new PostStatistics(srcWorkSpaceDir + File.separator + endStringType.getHost() + File.separator + "post", start, end); // 404 int imageCountInLogFile = postStatistics.getDetailAllCountSuccessJson() + postStatistics.getDetailAllCountSuccessDocPostDeleted(); if (endStringType == EndStringType.MOE_IN_POOL) { imageCountInLogFile = postStatistics.getPoolCountSuccessJsonInPool(); } else if (endStringType == EndStringType.MOE_NOT_IN_POOL) { imageCountInLogFile = postStatistics.getPoolCountSuccessJsonNotInPool() + postStatistics.getPoolCountSuccessDocPostDeletedInPool() + postStatistics.getPoolCountSuccessDocPostDeletedNotInPool(); } if (endStringType == EndStringType.KONA_All || endStringType == EndStringType.MOE_NOT_IN_POOL) { List<File> file404List = fileFilter.filter(file -> file.getName().startsWith(endStringType.getHost()) && file.getName().contains(WORK_FILE_CONTAINS_404) && file.getName().contains("_" + start + "_" + end)); if (file404List.size() == 1) { String file404Name = file404List.get(0).getName(); imageCountInLogFile -= Integer.valueOf(file404Name.substring(file404Name.lastIndexOf("_") + 1, file404Name.lastIndexOf("."))); } else if (file404List.size() != 0) { throw new RuntimeException("file404List.size() != 0 and != 1"); } } if (imageFileList.size() != imageCountInLogFile) { throw new RuntimeException("imageFile in disk = " + imageFileList.size() + ", in log file = " + imageCountInLogFile); } MyLogUtils.stdOut("(" + imageFileList.size() + ") = (" + imageCountInLogFile + ")"); MyLogUtils.stdOut("" + name); } MyLogUtils.stdOut(" } }
package net.snowflake.client.jdbc; import net.minidev.json.JSONObject; import net.snowflake.client.ConditionalIgnoreRule.ConditionalIgnore; import net.snowflake.client.RunningOnTravisCI; import net.snowflake.client.jdbc.telemetryOOB.TelemetryEvent; import net.snowflake.client.jdbc.telemetryOOB.TelemetryService; import net.snowflake.common.core.SqlState; import org.apache.commons.codec.binary.Base64; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import static net.snowflake.client.core.SessionUtil.CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Connection integration tests */ public class ConnectionIT extends BaseJDBCTest { // create a local constant for this code for testing purposes (already defined in GS) private static final int INVALID_CONNECTION_INFO_CODE = 390100; private boolean defaultState; @Before public void setUp() { TelemetryService service = TelemetryService.getInstance(); service.updateContextForIT(getConnectionParameters()); defaultState = service.isEnabled(); service.setNumOfRetryToTriggerTelemetry(3); service.disableRunFlushBeforeException(); service.enable(); } @After public void tearDown() throws InterruptedException { TelemetryService service = TelemetryService.getInstance(); service.flush(); // wait 5 seconds while the service is flushing TimeUnit.SECONDS.sleep(5); if (defaultState) { service.enable(); } else { service.disable(); } service.resetNumOfRetryToTriggerTelemetry(); service.enableRunFlushBeforeException(); } @Test public void testSimpleConnection() throws SQLException { Connection con = getConnection(); Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("show parameters"); assertTrue(resultSet.next()); assertFalse(con.isClosed()); statement.close(); con.close(); assertTrue(con.isClosed()); con.close(); // ensure no exception } /** * Test that login timeout kick in when connect through datasource * * @throws SQLException if any SQL error occurs */ @Test public void testLoginTimeoutViaDataSource() throws SQLException { SnowflakeBasicDataSource ds = new SnowflakeBasicDataSource(); ds.setUrl("jdbc:snowflake://fakeaccount.snowflakecomputing.com"); ds.setUser("fakeUser"); ds.setPassword("fakePassword"); ds.setAccount("fakeAccount"); ds.setLoginTimeout(10); long startLoginTime = System.currentTimeMillis(); try { ds.getConnection(); fail(); } catch (SQLException e) { assertThat(e.getErrorCode(), is(ErrorCode.NETWORK_ERROR.getMessageCode())); } long endLoginTime = System.currentTimeMillis(); assertTrue(endLoginTime - startLoginTime < 30000); } /** * Test production connectivity in case cipher suites or tls protocol change * Use fake username and password but correct url * Expectation is receiving incorrect username or password response from server */ @Test public void testProdConnectivity() throws SQLException { String[] deploymentUrls = { "jdbc:snowflake://sfcsupport.snowflakecomputing.com", "jdbc:snowflake://sfcsupportva.us-east-1.snowflakecomputing.com", "jdbc:snowflake://sfcsupporteu.eu-central-1.snowflakecomputing.com"}; Properties properties = new Properties(); properties.put("user", "fakesuer"); properties.put("password", "fakepwd"); properties.put("account", "fakeaccount"); for (String url : deploymentUrls) { try { DriverManager.getConnection(url, properties); fail(); } catch (SQLException e) { assertThat(e.getErrorCode(), is(INVALID_CONNECTION_INFO_CODE)); } } } @Test public void testSetCatalogSchema() throws Throwable { try (Connection connection = getConnection()) { String db = connection.getCatalog(); String schema = connection.getSchema(); connection.setCatalog(db); connection.setSchema("PUBLIC"); // get the current schema ResultSet rst = connection.createStatement().executeQuery("select current_schema()"); assertTrue(rst.next()); assertEquals("PUBLIC", rst.getString(1)); assertEquals(db, connection.getCatalog()); assertEquals("PUBLIC", connection.getSchema()); // get the current schema connection.setSchema(schema); rst = connection.createStatement().executeQuery("select current_schema()"); assertTrue(rst.next()); assertEquals(schema, rst.getString(1)); rst.close(); } } @Test @ConditionalIgnore(condition = RunningOnTravisCI.class) public void testConnectionGetAndSetDBAndSchema() throws SQLException { Connection con = getConnection(); final String database = System.getenv("SNOWFLAKE_TEST_DATABASE").toUpperCase(); final String schema = System.getenv("SNOWFLAKE_TEST_SCHEMA").toUpperCase(); assertEquals(database, con.getCatalog()); assertEquals(schema, con.getSchema()); final String SECOND_DATABASE = "SECOND_DATABASE"; final String SECOND_SCHEMA = "SECOND_SCHEMA"; Statement statement = con.createStatement(); statement.execute(String.format("create or replace database %s", SECOND_DATABASE)); statement.execute(String.format("create or replace schema %s", SECOND_SCHEMA)); statement.execute(String.format("use database %s", database)); // TODO: use the other database and schema con.setCatalog(SECOND_DATABASE); assertEquals(SECOND_DATABASE, con.getCatalog()); assertEquals("PUBLIC", con.getSchema()); con.setSchema(SECOND_SCHEMA); assertEquals(SECOND_SCHEMA, con.getSchema()); statement.execute(String.format("use database %s", database)); statement.execute(String.format("use schema %s", schema)); assertEquals(database, con.getCatalog()); assertEquals(schema, con.getSchema()); statement.execute(String.format("drop database if exists %s", SECOND_DATABASE)); con.close(); } @Test public void testConnectionClientInfo() throws SQLException { try (Connection con = getConnection()) { Properties property = con.getClientInfo(); assertEquals(0, property.size()); Properties clientInfo = new Properties(); clientInfo.setProperty("name", "Peter"); clientInfo.setProperty("description", "SNOWFLAKE JDBC"); try { con.setClientInfo(clientInfo); fail("setClientInfo should fail for any parameter."); } catch (SQLClientInfoException e) { assertEquals(SqlState.INVALID_PARAMETER_VALUE, e.getSQLState()); assertEquals(200047, e.getErrorCode()); assertEquals(2, e.getFailedProperties().size()); } try { con.setClientInfo("ApplicationName", "valueA"); fail("setClientInfo should fail for any parameter."); } catch (SQLClientInfoException e) { assertEquals(SqlState.INVALID_PARAMETER_VALUE, e.getSQLState()); assertEquals(200047, e.getErrorCode()); assertEquals(1, e.getFailedProperties().size()); } } } // only support get and set @Test public void testNetworkTimeout() throws SQLException { Connection con = getConnection(); int millis = con.getNetworkTimeout(); assertEquals(0, millis); con.setNetworkTimeout(null, 200); assertEquals(200, con.getNetworkTimeout()); con.close(); } @Test public void testAbort() throws SQLException { Connection con = getConnection(); assertTrue(!con.isClosed()); con.abort(null); assertTrue(con.isClosed()); } @Test public void testSetQueryTimeoutInConnectionStr() throws SQLException { Properties properties = new Properties(); properties.put("queryTimeout", "5"); Connection connection = getConnection(properties); Statement statement = connection.createStatement(); try { statement.executeQuery("select count(*) from table(generator(timeLimit => 1000000))"); } catch (SQLException e) { assertTrue(true); assertEquals(SqlState.QUERY_CANCELED, e.getSQLState()); assertEquals("SQL execution canceled", e.getMessage()); } statement.close(); connection.close(); } @Test public void testHttpsLoginTimeoutWithSSL() throws SQLException { long connStart = 0, conEnd; Properties properties = new Properties(); properties.put("account", "wrongaccount"); properties.put("loginTimeout", "20"); properties.put("user", "fakeuser"); properties.put("password", "fakepassword"); // only when ssl is on can trigger the login timeout // ssl is off will trigger 404 properties.put("ssl", "on"); try { connStart = System.currentTimeMillis(); Map<String, String> params = getConnectionParameters(); // use wrongaccount in url String host = params.get("host"); String[] hostItems = host.split("\\."); String wrongUri = params.get("uri").replace("://" + hostItems[0], "://wrongaccount"); DriverManager.getConnection(wrongUri, properties); } catch (SQLException e) { assertThat("Communication error", e.getErrorCode(), equalTo(ErrorCode.NETWORK_ERROR.getMessageCode())); conEnd = System.currentTimeMillis(); assertThat("Login time out not taking effective", conEnd - connStart < 60000); if (TelemetryService.getInstance().isDeploymentEnabled()) { assertThat( "Telemetry Service queue size", TelemetryService.getInstance().size(), greaterThanOrEqualTo(1)); TelemetryEvent te = TelemetryService.getInstance().peek(); JSONObject values = (JSONObject) te.get("Value"); assertThat("Communication error", values.get("errorCode").toString().compareTo( ErrorCode.NETWORK_ERROR.getMessageCode().toString()) == 0); } return; } fail(); } @Test public void testHttpsLoginTimeoutWithOutSSL() throws SQLException { Properties properties = new Properties(); properties.put("account", "wrongaccount"); properties.put("loginTimeout", "20"); properties.put("user", "fakeuser"); properties.put("password", "fakepassword"); properties.put("ssl", "off"); int queueSize = TelemetryService.getInstance().size(); try { Map<String, String> params = getConnectionParameters(); // use wrongaccount in url String host = params.get("host"); String[] hostItems = host.split("\\."); String wrongUri = params.get("uri").replace("://" + hostItems[0], "://wrongaccount"); DriverManager.getConnection(wrongUri, properties); } catch (SQLException e) { if (TelemetryService.getInstance().getServerDeploymentName().equals( TelemetryService.TELEMETRY_SERVER_DEPLOYMENT.DEV.getName()) || TelemetryService.getInstance().getServerDeploymentName().equals( TelemetryService.TELEMETRY_SERVER_DEPLOYMENT.REG.getName())) { // a connection error response (wrong user and password) // with status code 200 is returned in RT assertThat("Communication error", e.getErrorCode(), equalTo(INVALID_CONNECTION_INFO_CODE)); // since it returns normal response, // the telemetry does not create new event if (TelemetryService.getInstance().isDeploymentEnabled()) { assertEquals(0, TelemetryService.getInstance().size() - queueSize); } } else { // in qa1 and others, 404 http status code should be returned assertThat("Communication error", e.getErrorCode(), equalTo(ErrorCode.NETWORK_ERROR.getMessageCode())); /* if (TelemetryService.getInstance().isDeploymentEnabled()) { assertThat( "Telemetry Service queue size", TelemetryService.getInstance().size(), greaterThanOrEqualTo(1)); TelemetryEvent te = TelemetryService.getInstance().peek(); String name = (String) te.get("Name"); int statusCode = (int) ((JSONObject) te.get("Value")).get("responseStatusCode"); assertEquals(name, "HttpError404"); assertEquals(statusCode, 404); } */ } return; } fail(); } @Test public void testWrongHostNameTimeout() throws SQLException { long connStart = 0, conEnd; Properties properties = new Properties(); properties.put("account", "testaccount"); properties.put("loginTimeout", "20"); properties.put("user", "fakeuser"); properties.put("password", "fakepassword"); int queueSize = TelemetryService.getInstance().size(); try { connStart = System.currentTimeMillis(); Map<String, String> params = getConnectionParameters(); // use wrongaccount in url String host = params.get("host"); String[] hostItems = host.split("\\."); String wrongUri = params.get("uri").replace( "." + hostItems[hostItems.length - 2] + ".", ".wronghostname."); DriverManager.getConnection(wrongUri, properties); } catch (SQLException e) { assertThat("Communication error", e.getErrorCode(), equalTo(ErrorCode.NETWORK_ERROR.getMessageCode())); conEnd = System.currentTimeMillis(); assertThat("Login time out not taking effective", conEnd - connStart < 60000); if (TelemetryService.getInstance().isDeploymentEnabled()) { assertEquals(TelemetryService.getInstance().size(), queueSize + 2); TelemetryEvent te = TelemetryService.getInstance().peek(); JSONObject values = (JSONObject) te.get("Value"); assertThat("Communication error", values.get("errorCode").toString().compareTo( ErrorCode.NETWORK_ERROR.getMessageCode().toString()) == 0); } return; } fail(); } @Ignore("invalid db, schema or role no longer raises SQLWarnigs") @Test public void testInvalidDbOrSchemaOrRole() throws SQLException { Properties properties = new Properties(); properties.put("db", "invalid_db"); properties.put("schema", "invalid_schema"); Connection connection = getConnection(properties); SQLWarning warning = connection.getWarnings(); assertEquals("01000", warning.getSQLState()); warning = warning.getNextWarning(); assertEquals("01000", warning.getSQLState()); assertEquals(null, warning.getNextWarning()); connection.clearWarnings(); assertEquals(null, connection.getWarnings()); } @Test public void testConnectViaDataSource() throws SQLException { SnowflakeBasicDataSource ds = new SnowflakeBasicDataSource(); Map<String, String> params = getConnectionParameters(); String account = params.get("account"); String host = params.get("host"); String port = params.get("port"); String user = params.get("user"); String password = params.get("password"); String ssl = params.get("ssl"); String connectStr = String.format("jdbc:snowflake://%s:%s", host, port); ds.setUrl(connectStr); ds.setAccount(account); ds.setSsl("on".equals(ssl)); Connection connection = ds.getConnection(user, password); ResultSet resultSet = connection.createStatement() .executeQuery("select 1"); resultSet.next(); assertThat("select 1", resultSet.getInt(1), equalTo(1)); connection.close(); // get connection by server name // this is used by ibm cast iron studio ds = new SnowflakeBasicDataSource(); ds.setServerName(params.get("host")); ds.setSsl("on".equals(ssl)); ds.setAccount(account); ds.setPortNumber(Integer.parseInt(port)); connection = ds.getConnection(params.get("user"), params.get("password")); resultSet = connection.createStatement() .executeQuery("select 1"); resultSet.next(); assertThat("select 1", resultSet.getInt(1), equalTo(1)); connection.close(); } @Test @ConditionalIgnore(condition = RunningOnTravisCI.class) public void testConnectUsingKeyPair() throws Exception { Map<String, String> parameters = getConnectionParameters(); String testUser = parameters.get("user"); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyPairGenerator.initialize(2048, random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Connection connection = getConnection(); Statement statement = connection.createStatement(); statement.execute("use role accountadmin"); String encodePublicKey = Base64.encodeBase64String(publicKey.getEncoded()); statement.execute(String.format( "alter user %s set rsa_public_key='%s'", testUser, encodePublicKey)); connection.close(); String uri = parameters.get("uri"); Properties properties = new Properties(); properties.put("account", parameters.get("account")); properties.put("user", testUser); properties.put("ssl", parameters.get("ssl")); properties.put("port", parameters.get("port")); // test correct private key one properties.put("privateKey", privateKey); connection = DriverManager.getConnection(uri, properties); connection.close(); // test wrong private key keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey2 = keyPair.getPublic(); PrivateKey privateKey2 = keyPair.getPrivate(); properties.put("privateKey", privateKey2); try { DriverManager.getConnection(uri, properties); fail(); } catch (SQLException e) { Assert.assertEquals(390144, e.getErrorCode()); } // test multiple key pair connection = getConnection(); statement = connection.createStatement(); statement.execute("use role accountadmin"); String encodePublicKey2 = Base64.encodeBase64String(publicKey2.getEncoded()); statement.execute(String.format( "alter user %s set rsa_public_key_2='%s'", testUser, encodePublicKey2)); connection.close(); connection = DriverManager.getConnection(uri, properties); // clean up statement = connection.createStatement(); statement.execute("use role accountadmin"); statement.execute(String.format("alter user %s unset rsa_public_key", testUser)); statement.execute(String.format("alter user %s unset rsa_public_key_2", testUser)); connection.close(); } @Test public void testBadPrivateKey() throws Exception { Map<String, String> parameters = getConnectionParameters(); String testUser = parameters.get("user"); String uri = parameters.get("uri"); Properties properties = new Properties(); properties.put("account", parameters.get("account")); properties.put("user", testUser); properties.put("ssl", parameters.get("ssl")); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); PrivateKey dsaPrivateKey = keyPairGenerator.generateKeyPair().getPrivate(); try { properties.put("privateKey", "bad string"); DriverManager.getConnection(uri, properties); fail(); } catch (SQLException e) { assertThat(e.getErrorCode(), is( ErrorCode.INVALID_PARAMETER_TYPE.getMessageCode())); } try { properties.put("privateKey", dsaPrivateKey); DriverManager.getConnection(uri, properties); fail(); } catch (SQLException e) { assertThat(e.getErrorCode(), is( ErrorCode.INVALID_OR_UNSUPPORTED_PRIVATE_KEY.getMessageCode())); } } @Test @ConditionalIgnore(condition = RunningOnTravisCI.class) public void testDifferentKeyLength() throws Exception { Map<String, String> parameters = getConnectionParameters(); String testUser = parameters.get("user"); Integer[] testCases = {2048, 4096, 8192}; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); for (Integer keyLength : testCases) { keyPairGenerator.initialize(keyLength, random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Connection connection = getConnection(); Statement statement = connection.createStatement(); statement.execute("use role accountadmin"); String encodePublicKey = Base64.encodeBase64String(publicKey.getEncoded()); statement.execute(String.format( "alter user %s set rsa_public_key='%s'", testUser, encodePublicKey)); connection.close(); String uri = parameters.get("uri"); Properties properties = new Properties(); properties.put("account", parameters.get("account")); properties.put("user", testUser); properties.put("ssl", parameters.get("ssl")); properties.put("port", parameters.get("port")); properties.put("role", "accountadmin"); // test correct private key one properties.put("privateKey", privateKey); connection = DriverManager.getConnection(uri, properties); connection.createStatement().execute( String.format("alter user %s unset rsa_public_key", testUser)); connection.close(); } } /** * Test production connectivity with insecure mode disabled. */ @Test public void testInsecureMode() throws SQLException { String deploymentUrl = "jdbc:snowflake://sfcsupport.snowflakecomputing.com"; Properties properties = new Properties(); properties.put("user", "fakesuer"); properties.put("password", "fakepwd"); properties.put("account", "fakeaccount"); properties.put("insecureMode", false); try { DriverManager.getConnection(deploymentUrl, properties); fail(); } catch (SQLException e) { assertThat(e.getErrorCode(), is(INVALID_CONNECTION_INFO_CODE)); } deploymentUrl = "jdbc:snowflake://sfcsupport.snowflakecomputing.com?insecureMode=false"; properties = new Properties(); properties.put("user", "fakesuer"); properties.put("password", "fakepwd"); properties.put("account", "fakeaccount"); try { DriverManager.getConnection(deploymentUrl, properties); fail(); } catch (SQLException e) { assertThat(e.getErrorCode(), is(INVALID_CONNECTION_INFO_CODE)); } } /** * Verify the passed memory parameters are set in the session */ @Test public void testClientMemoryParameters() throws Exception { Properties paramProperties = new Properties(); paramProperties.put("CLIENT_PREFETCH_THREADS", "6"); paramProperties.put("CLIENT_RESULT_CHUNK_SIZE", 48); paramProperties.put("CLIENT_MEMORY_LIMIT", 1000); Connection connection = getConnection(paramProperties); for (Enumeration<?> enums = paramProperties.propertyNames(); enums.hasMoreElements(); ) { String key = (String) enums.nextElement(); ResultSet rs = connection.createStatement().executeQuery( String.format("show parameters like '%s'", key)); rs.next(); String value = rs.getString("value"); assertThat(key, value, equalTo(paramProperties.get(key).toString())); } } /** * Verify the JVM memory parameters are set in the session */ @Test public void testClientMemoryJvmParameteres() throws Exception { Properties paramProperties = new Properties(); paramProperties.put("CLIENT_PREFETCH_THREADS", "6"); paramProperties.put("CLIENT_RESULT_CHUNK_SIZE", 48); paramProperties.put("CLIENT_MEMORY_LIMIT", 1000L); // set JVM parameters System.setProperty("net.snowflake.jdbc.clientPrefetchThreads", paramProperties.get("CLIENT_PREFETCH_THREADS").toString()); System.setProperty("net.snowflake.jdbc.clientResultChunkSize", paramProperties.get("CLIENT_RESULT_CHUNK_SIZE").toString()); System.setProperty("net.snowflake.jdbc.clientMemoryLimit", paramProperties.get("CLIENT_MEMORY_LIMIT").toString()); try { Connection connection = getConnection(); for (Enumeration<?> enums = paramProperties.propertyNames(); enums.hasMoreElements(); ) { String key = (String) enums.nextElement(); ResultSet rs = connection.createStatement().executeQuery( String.format("show parameters like '%s'", key)); rs.next(); String value = rs.getString("value"); assertThat(key, value, equalTo(paramProperties.get(key).toString())); } } finally { System.clearProperty("net.snowflake.jdbc.clientPrefetchThreads"); System.clearProperty("net.snowflake.jdbc.clientResultChunkSize"); System.clearProperty("net.snowflake.jdbc.clientMemoryLimit"); } } /** * Verify the connection and JVM memory parameters are set in the session. * The connection parameters take precedence over JVM. */ @Test public void testClientMixedMemoryJvmParameteres() throws Exception { Properties paramProperties = new Properties(); paramProperties.put("CLIENT_PREFETCH_THREADS", "6"); paramProperties.put("CLIENT_RESULT_CHUNK_SIZE", 48); paramProperties.put("CLIENT_MEMORY_LIMIT", 1000L); // set JVM parameters System.setProperty("net.snowflake.jdbc.clientPrefetchThreads", paramProperties.get("CLIENT_PREFETCH_THREADS").toString()); System.setProperty("net.snowflake.jdbc.clientResultChunkSize", paramProperties.get("CLIENT_RESULT_CHUNK_SIZE").toString()); System.setProperty("net.snowflake.jdbc.clientMemoryLimit", paramProperties.get("CLIENT_MEMORY_LIMIT").toString()); paramProperties.put("CLIENT_PREFETCH_THREADS", "8"); paramProperties.put("CLIENT_RESULT_CHUNK_SIZE", 64); paramProperties.put("CLIENT_MEMORY_LIMIT", 2000L); try { Connection connection = getConnection(paramProperties); for (Enumeration<?> enums = paramProperties.propertyNames(); enums.hasMoreElements(); ) { String key = (String) enums.nextElement(); ResultSet rs = connection.createStatement().executeQuery( String.format("show parameters like '%s'", key)); rs.next(); String value = rs.getString("value"); assertThat(key, value, equalTo(paramProperties.get(key).toString())); } } finally { System.clearProperty("net.snowflake.jdbc.clientPrefetchThreads"); System.clearProperty("net.snowflake.jdbc.clientResultChunkSize"); System.clearProperty("net.snowflake.jdbc.clientMemoryLimit"); } } /** * Verify the passed heartbeat frequency, which is too small, is changed to * the smallest valid value. */ @Test public void testHeartbeatFrequencyTooSmall() throws Exception { Properties paramProperties = new Properties(); paramProperties.put(CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY, 2); Connection connection = getConnection(paramProperties); connection.getClientInfo(CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY); for (Enumeration<?> enums = paramProperties.propertyNames(); enums.hasMoreElements(); ) { String key = (String) enums.nextElement(); ResultSet rs = connection.createStatement().executeQuery( String.format("show parameters like '%s'", key)); rs.next(); String value = rs.getString("value"); assertThat(key, value, equalTo("900")); } } /** * Verify the passed heartbeat frequency, which is too large, is changed to * the maximum valid value. */ @Test public void testHeartbeatFrequencyTooLarge() throws Exception { Properties paramProperties = new Properties(); paramProperties.put(CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY, 4000); Connection connection = getConnection(paramProperties); connection.getClientInfo(CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY); for (Enumeration<?> enums = paramProperties.propertyNames(); enums.hasMoreElements(); ) { String key = (String) enums.nextElement(); ResultSet rs = connection.createStatement().executeQuery( String.format("show parameters like '%s'", key)); rs.next(); String value = rs.getString("value"); assertThat(key, value, equalTo("3600")); } } /** * Verify the passed heartbeat frequency matches the output value if the * input is valid (between 900 and 3600). */ @Test public void testHeartbeatFrequencyValidValue() throws Exception { Properties paramProperties = new Properties(); paramProperties.put(CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY, 1800); Connection connection = getConnection(paramProperties); connection.getClientInfo(CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY); for (Enumeration<?> enums = paramProperties.propertyNames(); enums.hasMoreElements(); ) { String key = (String) enums.nextElement(); ResultSet rs = connection.createStatement().executeQuery( String.format("show parameters like '%s'", key)); rs.next(); String value = rs.getString("value"); assertThat(key, value, equalTo(paramProperties.get(key).toString())); } } @Test public void testReadOnly() throws Throwable { try (Connection connection = getConnection()) { try { connection.setReadOnly(true); fail("must raise SQLFeatureNotSupportedException"); } catch (SQLFeatureNotSupportedException ex) { // nop } connection.setReadOnly(false); connection.createStatement().execute("create or replace table readonly_test(c1 int)"); assertFalse(connection.isReadOnly()); connection.createStatement().execute("drop table if exists readonly_test"); } } @Test public void testNativeSQL() throws Throwable { try (Connection connection = getConnection()) { // today returning the source SQL. assertEquals("select 1", connection.nativeSQL("select 1")); } } @Test public void testGetTypeMap() throws Throwable { try (Connection connection = getConnection()) { // return an empty type map. setTypeMap is not supported. assertEquals(Collections.emptyMap(), connection.getTypeMap()); } } @Test public void testHolderbility() throws Throwable { try (Connection connection = getConnection()) { try { connection.setHoldability(0); } catch (SQLFeatureNotSupportedException ex) { // nop } // return an empty type map. setTypeMap is not supported. assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, connection.getHoldability()); } } @Test public void testIsValid() throws Throwable { try (Connection connection = getConnection()) { assertTrue(connection.isValid(10)); try { assertTrue(connection.isValid(-10)); fail("must fail"); } catch (SQLException ex) { // nop, no specific error code is provided. } } } @Test public void testUnwrapper() throws Throwable { try (Connection connection = getConnection()) { boolean canUnwrap = connection.isWrapperFor(SnowflakeConnectionV1.class); assertTrue(canUnwrap); if (canUnwrap) { SnowflakeConnectionV1 sfconnection = connection.unwrap(SnowflakeConnectionV1.class); sfconnection.createStatement(); } else { fail("should be able to unwrap"); } try { connection.unwrap(SnowflakeDriver.class); fail("should fail to cast"); } catch (SQLException ex) { // nop } } } @Test public void testStatementsAndResultSetsClosedByConnection() throws SQLException { Connection connection = getConnection(); Statement statement1 = connection.createStatement(); Statement statement2 = connection.createStatement(); ResultSet rs1 = statement2.executeQuery("select 2;"); ResultSet rs2 = statement2.executeQuery("select 2;"); ResultSet rs3 = statement2.executeQuery("select 2;"); PreparedStatement statement3 = connection.prepareStatement("select 2;"); connection.close(); assertTrue(statement1.isClosed()); assertTrue(statement2.isClosed()); assertTrue(statement3.isClosed()); assertTrue(rs1.isClosed()); assertTrue(rs2.isClosed()); assertTrue(rs3.isClosed()); } @Test public void testResultSetsClosedByStatement() throws SQLException { Connection connection = getConnection(); Statement statement2 = connection.createStatement(); ResultSet rs1 = statement2.executeQuery("select 2;"); ResultSet rs2 = statement2.executeQuery("select 2;"); ResultSet rs3 = statement2.executeQuery("select 2;"); PreparedStatement statement3 = connection.prepareStatement("select 2;"); ResultSet rs4 = statement3.executeQuery(); assertFalse(rs1.isClosed()); assertFalse(rs2.isClosed()); assertFalse(rs3.isClosed()); assertFalse(rs4.isClosed()); statement2.close(); statement3.close(); assertTrue(rs1.isClosed()); assertTrue(rs2.isClosed()); assertTrue(rs3.isClosed()); assertTrue(rs4.isClosed()); connection.close(); } @Test @Ignore @ConditionalIgnore(condition = RunningOnTravisCI.class) public void testOKTAConnection() throws Throwable { Map<String, String> params = getConnectionParameters(); Properties properties = new Properties(); properties.put("user", params.get("ssoUser")); properties.put("password", params.get("ssoPassword")); properties.put("ssl", params.get("ssl")); properties.put("authenticator", "https://snowflakecomputing.okta.com/"); DriverManager.getConnection(String.format( "jdbc:snowflake://%s.reg.snowflakecomputing.com:%s/", params.get("account"), params.get("port")), properties); } @Test @Ignore @ConditionalIgnore(condition = RunningOnTravisCI.class) public void testOKTAConnectionWithOktauserParam() throws Throwable { Map<String, String> params = getConnectionParameters(); Properties properties = new Properties(); properties.put("user", "test"); properties.put("password", params.get("ssoPassword")); properties.put("ssl", params.get("ssl")); properties.put("authenticator", String.format("https://snowflakecomputing.okta.com;oktausername=%s;", params.get("ssoUser"))); DriverManager.getConnection(String.format( "jdbc:snowflake://%s.reg.snowflakecomputing.com:%s/", params.get("account"), params.get("port")), properties); } }
package com.tapad.sample; import android.app.Activity; import android.os.Bundle; import com.tapad.adserving.AdSize; import com.tapad.adserving.ui.AdView; public class AdViewActivity extends Activity { private AdView adViewTop; private AdView adViewBottom; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.managed_ad_view); adViewTop = (AdView) findViewById(R.id.ad_view_top); adViewBottom = (AdView) findViewById(R.id.ad_view_bottom); } @Override protected void onResume() { super.onResume(); adViewTop.start("108", AdSize.S320x50, 10); adViewBottom.start("108", AdSize.S300x250, 10); } @Override protected void onPause() { adViewTop.stopRefreshTimer(); adViewBottom.stopRefreshTimer(); super.onPause(); } }
package org.commcare.util.engine; import org.commcare.modern.reference.ArchiveFileRoot; import org.commcare.modern.reference.JavaFileRoot; import org.commcare.modern.reference.JavaHttpRoot; import org.commcare.resources.ResourceManager; import org.commcare.resources.model.InstallCancelledException; import org.commcare.resources.model.InstallerFactory; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.resources.model.TableStateListener; import org.commcare.resources.model.UnresolvedResourceException; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DetailField; import org.commcare.suite.model.EntityDatum; import org.commcare.suite.model.Entry; import org.commcare.suite.model.FormIdDatum; import org.commcare.suite.model.Menu; import org.commcare.suite.model.OfflineUserRestore; import org.commcare.suite.model.Profile; import org.commcare.suite.model.PropertySetter; import org.commcare.suite.model.SessionDatum; import org.commcare.suite.model.Suite; import org.commcare.util.CommCarePlatform; import org.javarosa.core.io.BufferedInputStream; import org.javarosa.core.io.StreamsUtil; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.reference.ResourceReferenceFactory; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.storage.*; import org.javarosa.core.services.storage.util.DummyIndexedStorageUtility; import org.javarosa.core.util.externalizable.LivePrototypeFactory; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.javarosa.xpath.XPathMissingInstanceException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Hashtable; import java.util.Vector; import java.util.zip.ZipFile; /** * @author ctsims */ public class CommCareConfigEngine { private final ResourceTable table; private final ResourceTable updateTable; private final ResourceTable recoveryTable; private final CommCarePlatform platform; private final PrintStream print; private ArchiveFileRoot mArchiveRoot; private static IStorageIndexedFactory storageFactory; public static final int MAJOR_VERSION = 2; public static final int MINOR_VERSION = 41; public CommCareConfigEngine() { this(new LivePrototypeFactory()); } public CommCareConfigEngine(PrototypeFactory prototypeFactory) { this(setupDummyStorageFactory(prototypeFactory), new InstallerFactory()); } public CommCareConfigEngine(IStorageIndexedFactory storageFactory, InstallerFactory installerFactory) { this.print = new PrintStream(System.out); this.platform = new CommCarePlatform(MAJOR_VERSION, MINOR_VERSION); setStorageFactory(storageFactory); setRoots(); table = ResourceTable.RetrieveTable(storageFactory.newStorage("GLOBAL_RESOURCE_TABLE", Resource.class), installerFactory); updateTable = ResourceTable.RetrieveTable(storageFactory.newStorage("GLOBAL_UPGRADE_TABLE", Resource.class), installerFactory); recoveryTable = ResourceTable.RetrieveTable(storageFactory.newStorage("GLOBAL_RECOVERY_TABLE", Resource.class), installerFactory); //All of the below is on account of the fact that the installers //aren't going through a factory method to handle them differently //per device. StorageManager.forceClear(); StorageManager.setStorageFactory(storageFactory); PropertyManager.initDefaultPropertyManager(); StorageManager.registerStorage(Profile.STORAGE_KEY, Profile.class); StorageManager.registerStorage(Suite.STORAGE_KEY, Suite.class); StorageManager.registerStorage(FormDef.STORAGE_KEY, FormDef.class); StorageManager.registerStorage(FormInstance.STORAGE_KEY, FormInstance.class); StorageManager.registerStorage(OfflineUserRestore.STORAGE_KEY, OfflineUserRestore.class); } private static IStorageIndexedFactory setupDummyStorageFactory(final PrototypeFactory prototypeFactory) { return new IStorageIndexedFactory() { @Override public IStorageUtilityIndexed newStorage(String name, Class type) { return new DummyIndexedStorageUtility(type, prototypeFactory); } }; } public static void setStorageFactory(IStorageIndexedFactory storageFactory) { CommCareConfigEngine.storageFactory = storageFactory; } protected void setRoots() { ReferenceManager.instance().addReferenceFactory(new JavaHttpRoot()); this.mArchiveRoot = new ArchiveFileRoot(); ReferenceManager.instance().addReferenceFactory(mArchiveRoot); ReferenceManager.instance().addReferenceFactory(new ResourceReferenceFactory()); } public void initFromArchive(String archiveURL) throws InstallCancelledException, UnresolvedResourceException, UnfullfilledRequirementsException { String fileName; if (archiveURL.startsWith("http")) { fileName = downloadToTemp(archiveURL); } else { fileName = archiveURL; } ZipFile zip; try { zip = new ZipFile(fileName); } catch (IOException e) { print.println("File at " + archiveURL + ": is not a valid CommCare Package. Downloaded to: " + fileName); e.printStackTrace(print); return; } String archiveGUID = this.mArchiveRoot.addArchiveFile(zip); init("jr://archive/" + archiveGUID + "/profile.ccpr"); } private String downloadToTemp(String resource) { try { URL url = new URL(resource); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setInstanceFollowRedirects(true); //you still need to handle redirect manully. HttpURLConnection.setFollowRedirects(true); File file = File.createTempFile("commcare_", ".ccz"); FileOutputStream fos = new FileOutputStream(file); StreamsUtil.writeFromInputToOutput(new BufferedInputStream(conn.getInputStream()), fos); return file.getAbsolutePath(); } catch (IOException e) { print.println("Issue downloading or create stream for " + resource); e.printStackTrace(print); System.exit(-1); return null; } } public void initFromLocalFileResource(String resource) throws InstallCancelledException, UnresolvedResourceException, UnfullfilledRequirementsException { String reference = setFileSystemRootFromResourceAndReturnRelativeRef(resource); init(reference); } private String setFileSystemRootFromResourceAndReturnRelativeRef(String resource) { int lastSeparator = resource.lastIndexOf(File.separator); String rootPath; String filePart; if (lastSeparator == -1) { rootPath = new File("").getAbsolutePath(); filePart = resource; } else { //Get the location of the file. In the future, we'll treat this as the resource root rootPath = resource.substring(0, resource.lastIndexOf(File.separator)); //cut off the end filePart = resource.substring(resource.lastIndexOf(File.separator) + 1); } //(That root now reads as jr://file/) ReferenceManager.instance().addReferenceFactory(new JavaFileRoot(rootPath)); //Now build the testing reference we'll use return "jr://file/" + filePart; } private void init(String profileRef) throws InstallCancelledException, UnresolvedResourceException, UnfullfilledRequirementsException { installAppFromReference(profileRef); } public void installAppFromReference(String profileReference) throws UnresolvedResourceException, UnfullfilledRequirementsException, InstallCancelledException { ResourceManager.installAppResources(platform, profileReference, this.table, true, Resource.RESOURCE_AUTHORITY_LOCAL); } public void initEnvironment() { Localization.init(true); try { table.initializeResources(platform, false); } catch (RuntimeException e) { print.println("Error while initializing one of the resolved resources"); e.printStackTrace(print); System.exit(-1); } //Make sure there's a default locale, since the app doesn't necessarily use the //localization engine Localization.getGlobalLocalizerAdvanced().addAvailableLocale("default"); Localization.setDefaultLocale("default"); print.println("Locales defined: "); for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) { System.out.println("* " + locale); } setDefaultLocale(); } private void setDefaultLocale() { String defaultLocale = "default"; for (PropertySetter prop : platform.getCurrentProfile().getPropertySetters()) { if ("cur_locale".equals(prop.getKey())) { defaultLocale = prop.getValue(); break; } } print.println("Setting locale to: " + defaultLocale); Localization.setLocale(defaultLocale); } public void describeApplication() { print.println("Locales defined: "); for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) { System.out.println("* " + locale); } Localization.setDefaultLocale("default"); Vector<Menu> root = new Vector<>(); Hashtable<String, Vector<Menu>> mapping = new Hashtable<>(); mapping.put("root", new Vector<Menu>()); for (Suite s : platform.getInstalledSuites()) { for (Menu m : s.getMenus()) { if (m.getId().equals("root")) { root.add(m); } else { Vector<Menu> menus = mapping.get(m.getRoot()); if (menus == null) { menus = new Vector<>(); } menus.add(m); mapping.put(m.getRoot(), menus); } } } for (String locale : Localization.getGlobalLocalizerAdvanced().getAvailableLocales()) { Localization.setLocale(locale); print.println("Application details for locale: " + locale); print.println("CommCare"); for (Menu m : mapping.get("root")) { print.println("|- " + m.getName().evaluate()); for (String command : m.getCommandIds()) { for (Suite s : platform.getInstalledSuites()) { if (s.getEntries().containsKey(command)) { print(s, s.getEntries().get(command), 2); } } } } for (Menu m : root) { for (String command : m.getCommandIds()) { for (Suite s : platform.getInstalledSuites()) { if (s.getEntries().containsKey(command)) { print(s, s.getEntries().get(command), 1); } } } } } } public CommCarePlatform getPlatform() { return platform; } public FormDef loadFormByXmlns(String xmlns) { IStorageUtilityIndexed<FormDef> formStorage = storageFactory.newStorage(FormDef.STORAGE_KEY, FormDef.class); return formStorage.getRecordForValue("XMLNS", xmlns); } private void print(Suite s, Entry e, int level) { String head = ""; String emptyhead = ""; for (int i = 0; i < level; ++i) { head += "|- "; emptyhead += " "; } if (e.isView()) { print.println(head + "View: " + e.getText().evaluate()); } else { print.println(head + "Entry: " + e.getText().evaluate()); } for (SessionDatum datum : e.getSessionDataReqs()) { if (datum instanceof FormIdDatum) { print.println(emptyhead + "Form: " + datum.getValue()); } else if (datum instanceof EntityDatum) { String shortDetailId = ((EntityDatum)datum).getShortDetail(); if (shortDetailId != null) { Detail d = s.getDetail(shortDetailId); try { print.println(emptyhead + "|Select: " + d.getTitle().getText().evaluate(new EvaluationContext(null))); } catch (XPathMissingInstanceException ex) { print.println(emptyhead + "|Select: " + "(dynamic title)"); } print.print(emptyhead + "| "); for (DetailField f : d.getFields()) { print.print(f.getHeader().evaluate() + " | "); } print.print("\n"); } } } } final static private class QuickStateListener implements TableStateListener { int lastComplete = 0; @Override public void simpleResourceAdded() { } @Override public void compoundResourceAdded(ResourceTable table) { } @Override public void incrementProgress(int complete, int total) { int diff = complete - lastComplete; lastComplete = complete; for (int i = 0; i < diff; ++i) { System.out.print("."); } } } public void attemptAppUpdate(String updateTarget) { ResourceTable global = table; // Ok, should figure out what the state of this bad boy is. Resource profileRef = global.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID); Profile profileObj = this.getPlatform().getCurrentProfile(); global.setStateListener(new QuickStateListener()); updateTable.setStateListener(new QuickStateListener()); // When profileRef points is http, add appropriate dev flags String authRef = profileObj.getAuthReference(); try { URL authUrl = new URL(authRef); // profileRef couldn't be parsed as a URL, so don't worry // about adding dev flags to the url's query // If we want to be using/updating to the latest build of the // app (instead of latest release), add it to the query tags of // the profile reference if (updateTarget != null && ("https".equals(authUrl.getProtocol()) || "http".equals(authUrl.getProtocol()))) { if (authUrl.getQuery() != null) { // If the profileRef url already have query strings // just add a new one to the end authRef = authRef + "&target=" + updateTarget; } else { // otherwise, start off the query string with a ? authRef = authRef + "?target" + updateTarget; } } } catch (MalformedURLException e) { System.out.print("Warning: Unrecognized URL format: " + authRef); } try { // This populates the upgrade table with resources based on // binary files, starting with the profile file. If the new // profile is not a newer version, statgeUpgradeTable doesn't // actually pull in all the new references System.out.println("Checking for updates...."); ResourceManager resourceManager = new ResourceManager(platform, global, updateTable, recoveryTable); resourceManager.stageUpgradeTable(authRef, true); Resource newProfile = updateTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID); if (!newProfile.isNewer(profileRef)) { System.out.println("Your app is up to date!"); return; } System.out.println("Update found. New Version: " + newProfile.getVersion()); System.out.println("Downloading / Preparing Update"); resourceManager.prepareUpgradeResources(); System.out.print("Installing update"); // Replaces global table with temporary, or w/ recovery if // something goes wrong resourceManager.upgrade(); } catch (UnresolvedResourceException e) { System.out.println("Update Failed! Couldn't find or install one of the remote resources"); e.printStackTrace(); return; } catch (UnfullfilledRequirementsException e) { System.out.println("Update Failed! This CLI host is incompatible with the app"); e.printStackTrace(); return; } catch (Exception e) { System.out.println("Update Failed! There is a problem with one of the resources"); e.printStackTrace(); return; } // Initializes app resources and the app itself, including doing a check to see if this // app record was converted by the db upgrader initEnvironment(); } }
package ru.stqa.pft.sandbox; public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello, world!"); } }
package org.usfirst.frc.team1719.robot; import org.usfirst.frc.team1719.robot.autonomousSelections.DoNothing; import org.usfirst.frc.team1719.robot.autonomousSelections.LowBarAuton; import org.usfirst.frc.team1719.robot.autonomousSelections.MoatAuton; import org.usfirst.frc.team1719.robot.autonomousSelections.PortcullisAuton; import org.usfirst.frc.team1719.robot.autonomousSelections.RampartsAuton; import org.usfirst.frc.team1719.robot.autonomousSelections.RockWallAuton; import org.usfirst.frc.team1719.robot.autonomousSelections.RoughTerrainAuton; import org.usfirst.frc.team1719.robot.commands.AimAndFire; import org.usfirst.frc.team1719.robot.commands.AutoSenseTower; import org.usfirst.frc.team1719.robot.commands.TurnToAngle; import org.usfirst.frc.team1719.robot.settings.PIDData; import org.usfirst.frc.team1719.robot.subsystems.Arm; import org.usfirst.frc.team1719.robot.subsystems.Display; import org.usfirst.frc.team1719.robot.subsystems.DriveSubsystem; import org.usfirst.frc.team1719.robot.subsystems.DualShooter; import org.usfirst.frc.team1719.robot.subsystems.ExampleSubsystem; import org.usfirst.frc.team1719.robot.subsystems.FlyWheel; import org.usfirst.frc.team1719.robot.subsystems.PhotonCannon; import com.ni.vision.NIVision; import com.ni.vision.NIVision.Image; import com.ni.vision.VisionException; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { // degrees final double PHOTON_CANNON_ANGLE = 60; final String CAMERA_NAME = "cam0"; public static final double GET_VALUE_FROM_SMARTDASHBOARD = -1337.0D; public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; public static Display display; public static PhotonCannon photonCannon; public static DriveSubsystem drive; public static FlyWheel rightFlywheel; public static FlyWheel leftFlywheel; public static DualShooter shooter; PIDData rightFlywheelPIDData; PIDData leftFlywheelPIDData; public static Arm arm; public int autonomousMode = 0; final boolean VOLTAGEDISPLAY = true; final boolean AUTONDISPLAY = false; boolean currentDisplayMode = VOLTAGEDISPLAY; final double TOLERANCE = 0.01; double maxPotValue = .274; double scalingFactor; double minPotValue = .255; boolean foundCamera = false; Command autonomousCommand; SendableChooser chooser; Command DisplayVoltage; Image frame; int session; NIVision.Rect crosshair; public static boolean isAuton = false; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { // Hardware Initialization // Allocate Hardware RobotMap.init(); // Initialize Subsystems rightFlywheelPIDData = new PIDData(0, 0, 0); leftFlywheelPIDData = new PIDData(0, 0, 0); drive = new DriveSubsystem(RobotMap.leftDriveController, RobotMap.rightDriveController, RobotMap.leftDriveEncoder, RobotMap.rightDriveEncoder); rightFlywheel = new FlyWheel(RobotMap.rightFlyWheelController, RobotMap.rightFlyWheelEncoder, rightFlywheelPIDData); leftFlywheel = new FlyWheel(RobotMap.leftFlyWheelController, RobotMap.leftFlyWheelEncoder, leftFlywheelPIDData); shooter = new DualShooter(leftFlywheel, rightFlywheel, RobotMap.innerLeftShooterWheelController, RobotMap.innerRightShooterWheelController); arm = new Arm(RobotMap.armController, RobotMap.armPot); display = new Display(RobotMap.buttonA, RobotMap.buttonB, RobotMap.dial); photonCannon = new PhotonCannon(); oi = new OI(); isAuton = false; frame = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0); try { session = NIVision.IMAQdxOpenCamera("cam0", NIVision.IMAQdxCameraControlMode.CameraControlModeController); NIVision.IMAQdxConfigureGrab(session); foundCamera = true; } catch (VisionException e) { foundCamera = false; System.out.println("Can't find the camera, failing with style"); } smartDashboardInit(); RobotMap.gyro.initGyro(); RobotMap.gyro.calibrate(); } /** * Initialize SmartDashboard values */ public void smartDashboardInit() { chooser = new SendableChooser(); // Move forwards command chooser.addDefault("Do nothing", new DoNothing()); chooser.addObject("Go Under Low Bar", new LowBarAuton()); chooser.addObject("Go over Rough Terrain", new RoughTerrainAuton()); chooser.addObject("Go over Moat", new MoatAuton()); chooser.addObject("Go over Ramparts", new RampartsAuton()); chooser.addObject("Go over Rock Wall", new RockWallAuton()); chooser.addObject("Go through the Portcullis", new PortcullisAuton()); chooser.addObject("Shoot at tower", new AimAndFire()); chooser.addObject("Turn 90 degrees", new TurnToAngle(90, true)); rightFlywheelPIDData = new PIDData(); chooser.addObject("Sense Tower High Goals", new AutoSenseTower()); // chooser.addObject("My Auto", new MyAutoCommand()); SmartDashboard.putData("Auto mode", chooser); SmartDashboard.putNumber("Right flywheel kP: ", rightFlywheelPIDData.kP); SmartDashboard.putNumber("Right flywheel kI: ", rightFlywheelPIDData.kI); SmartDashboard.putNumber("Right flywheel kD: ", rightFlywheelPIDData.kD); SmartDashboard.putNumber("Drive kP", 0.02); SmartDashboard.putNumber("Drive kI", 0.003); SmartDashboard.putNumber("Drive kD", 0.003); SmartDashboard.putNumber("Turn kP", 0.1); SmartDashboard.putNumber("Turn kI", 0.0); SmartDashboard.putNumber("Turn kD", 0.65); SmartDashboard.putNumber("Arm steady kP", (0.2 / 90)); SmartDashboard.putNumber("Move arm to pos kP", .03); SmartDashboard.putNumber("Move arm to pos kI", .001); SmartDashboard.putNumber("Move arm to pos kD", .001); SmartDashboard.putNumber("Arm steady kP", 0.3D); SmartDashboard.putNumber("Arm steady kI", 0.001D); SmartDashboard.putNumber("Arm steady kD", 0.002D); SmartDashboard.putNumber("Arm steady integral range", 7.0D); } /** * This function is called once each time the robot enters Disabled mode. * You can use it to reset any subsystem information you want to clear when * the robot is disabled. */ public void disabledInit() { // Make sure everything gets disabled isAuton = false; rightFlywheel.spin(0); leftFlywheel.spin(0); if (foundCamera) { NIVision.IMAQdxStopAcquisition(session); } } public void disabledPeriodic() { if (display.buttonAPressed()) { currentDisplayMode = AUTONDISPLAY; } else if (display.buttonBPressed()) { currentDisplayMode = VOLTAGEDISPLAY; } if (currentDisplayMode == AUTONDISPLAY) { // System.out.println("displayingAuton"); Double dialPos = display.getDialReading(); if (dialPos - .25 <= TOLERANCE) { autonomousMode = 0; display.displayString("A 0"); } else if (dialPos - .255 <= TOLERANCE) { autonomousMode = 1; display.displayString("A 1"); } else if (dialPos - .26 <= TOLERANCE) { autonomousMode = 2; display.displayString("A 2"); } else if (dialPos - .265 <= TOLERANCE) { autonomousMode = 3; display.displayString("A 3"); } } else if (currentDisplayMode == VOLTAGEDISPLAY) { String voltage = Double.toString(DriverStation.getInstance().getBatteryVoltage()); display.displayString(voltage); } Scheduler.getInstance().run(); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable * chooser code works with the Java SmartDashboard. If you prefer the * LabVIEW Dashboard, remove all of the chooser code and uncomment the * getString code to get the auto name from the text box below the Gyro * * You can add additional auto modes by adding additional commands to the * chooser code above (like the commented example) or additional comparisons * to the switch structure below with additional strings and commands. */ public void autonomousInit() { autonomousCommand = (Command) chooser.getSelected(); isAuton = true; /* * String autoSelected = SmartDashboard.getString("Auto Selector", * "Default"); switch(autoSelected) { case "My Auto": autonomousCommand * = new MyAutoCommand(); break; case "Default Auto": default: * autonomousCommand = new ExampleCommand(); break; } */ if (foundCamera) { NIVision.IMAQdxStartAcquisition(session); } // schedule the autonomous command (example) if (autonomousCommand != null) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { /* * This makes sure that the autonomous stops running when teleop starts * running. If you want the autonomous to continue until interrupted by * another command, remove this line or comment it out. */ isAuton = false; if (autonomousCommand != null) autonomousCommand.cancel(); if (foundCamera) { NIVision.IMAQdxStartAcquisition(session); } RobotMap.gyro.reset(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { // System.out.println("Angle: "+RobotMap.gyro.getAngle()); // System.out.println("meh" + RobotMap.dial.get()); Scheduler.getInstance().run(); if (foundCamera) { NIVision.IMAQdxGrab(session, frame, 1); CameraServer.getInstance().setImage(frame); } } /** * This function is called periodically during test mode */ public void testPeriodic() { isAuton = false; LiveWindow.run(); } }
package bammerbom.ultimatecore.bukkit.commands; import bammerbom.ultimatecore.bukkit.UltimateCommand; import bammerbom.ultimatecore.bukkit.r; import bammerbom.ultimatecore.bukkit.resources.databases.EffectDatabase; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CmdEffect implements UltimateCommand { @Override public String getName() { return "effect"; } @Override public String getPermission() { return "uc.effect"; } @Override public List<String> getAliases() { return Arrays.asList(); } @Override public void run(final CommandSender cs, String label, String[] args) { if (!r.perm(cs, "uc.effect", false, true)) { return; } if (!r.checkArgs(args, 1)) { r.sendMes(cs, "effectUsage"); return; } Player t = r.searchPlayer(args[0]); if (t == null) { r.sendMes(cs, "playerNotFound", "%Player", args[0]); return; } PotionEffectType ef = EffectDatabase.getByName(args[1]); if (ef == null) { if (args[1].equalsIgnoreCase("clear")) { for (PotionEffect effect : t.getActivePotionEffects()) { t.removePotionEffect(effect.getType()); } r.sendMes(cs, "effectClear", "%Target", t.getName()); return; } r.sendMes(cs, "effectNotFound", "%Effect", args[1]); return; } Integer dur = 120; Integer lev = 1; if (r.checkArgs(args, 2)) { if (!r.isInt(args[2])) { r.sendMes(cs, "numberFormat", "%Number", args[2]); return; } dur = Integer.parseInt(args[2]); } if (r.checkArgs(args, 3)) { if (!r.isInt(args[3])) { r.sendMes(cs, "numberFormat", "%Number", args[3]); return; } lev = Integer.parseInt(args[3]); } lev = r.normalize(lev, 0, 999999); dur = r.normalize(dur, 0, 999999); if (lev == 0 || dur == 0) { t.removePotionEffect(ef); r.sendMes(cs, "effectSucces", "%Effect", ef.getName().toLowerCase(), "%Target", t.getName(), "%Duration", dur, "%Level", lev); return; } t.removePotionEffect(ef); PotionEffect effect = new PotionEffect(ef, dur * 20, lev - 1); t.addPotionEffect(effect, true); r.sendMes(cs, "effectSucces", "%Effect", ef.getName().toLowerCase(), "%Target", t.getName(), "%Duration", dur, "%Level", lev); } @Override public List<String> onTabComplete(CommandSender cs, Command cmd, String alias, String[] args, String curs, Integer curn) { if (curn == 0) { return null; } else if (curn == 1) { ArrayList<String> s = new ArrayList<>(); for (PotionEffectType t : EffectDatabase.values()) { if (t == null || t.getName() == null) { continue; } s.add(t.getName().toLowerCase().replaceAll("_", "")); } return s; } else { return new ArrayList<>(); } } }
package ru.stqa.pft.sandbox; public class MyFirstProgram { public static void main(String[] args) { String someText = "world"; System.out.println("Hello, " + someText + "!"); double l = 8.0; double s = l * l; System.out.println("Площадь квадрата со стороной " + l + " = " + s); } }
package com.ceco.gm2.gravitybox.preference; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.ceco.gm2.gravitybox.R; import com.ceco.gm2.gravitybox.adapters.IIconListAdapterItem; import com.ceco.gm2.gravitybox.adapters.IconListAdapter; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.preference.DialogPreference; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; public class AppPickerPreference extends DialogPreference implements OnItemClickListener { private static final String SEPARATOR = "#C3C0#"; private Context mContext; private ListView mListView; private ArrayList<IIconListAdapterItem> mListData; private EditText mSearch; private ProgressBar mProgressBar; private AsyncTask<Void,Void,Void> mAsyncTask; public AppPickerPreference(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; setDialogLayoutResource(R.layout.app_picker_preference); setPositiveButtonText(null); } @Override protected void onBindDialogView(View view) { mListView = (ListView) view.findViewById(R.id.icon_list); mListView.setOnItemClickListener(this); mSearch = (EditText) view.findViewById(R.id.input_search); mSearch.setVisibility(View.GONE); mSearch.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { if(mListView.getAdapter() == null) return; ((IconListAdapter)mListView.getAdapter()).getFilter().filter(arg0); } }); mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar); super.onBindView(view); setData(); } @Override public void onDismiss(DialogInterface dialog) { if (mAsyncTask != null && mAsyncTask.getStatus() == AsyncTask.Status.RUNNING) { mAsyncTask.cancel(true); mAsyncTask = null; } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getString(index); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if (restoreValue) { String value = getPersistedString(null); String appName = getAppNameFromValue(value); setSummary(appName == null ? mContext.getString(R.string.app_picker_none) : appName); } else { setValue(null); setSummary(mContext.getString(R.string.app_picker_none)); } } private void setData() { mAsyncTask = new AsyncTask<Void,Void,Void>() { @Override protected void onPreExecute() { super.onPreExecute(); mProgressBar.setVisibility(View.VISIBLE); mProgressBar.refreshDrawableState(); mListData = new ArrayList<IIconListAdapterItem>(); } @Override protected Void doInBackground(Void... arg0) { Intent mainIntent = new Intent(Intent.ACTION_MAIN); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); PackageManager pm = mContext.getPackageManager(); List<ResolveInfo> appList = pm.queryIntentActivities(mainIntent, 0); Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm)); Resources res = mContext.getResources(); int sizePx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, res.getDisplayMetrics()); mListData.add(new AppItem(null, null, mContext.getString(R.string.app_picker_none), null)); for (ResolveInfo ri : appList) { if (this.isCancelled()) break; String appName = ri.loadLabel(pm).toString(); Bitmap appIcon = ((BitmapDrawable)ri.loadIcon(pm)).getBitmap(); Bitmap scaledIcon = Bitmap.createScaledBitmap(appIcon, sizePx, sizePx, true); AppItem ai = new AppItem(ri.activityInfo.packageName, ri.activityInfo.name, appName, new BitmapDrawable(res, scaledIcon)); mListData.add(ai); } return null; } @Override protected void onPostExecute(Void result) { mProgressBar.setVisibility(View.GONE); mSearch.setVisibility(View.VISIBLE); mListView.setAdapter(new IconListAdapter(mContext, mListData)); ((IconListAdapter)mListView.getAdapter()).notifyDataSetChanged(); } }.execute(); } private void setValue(String value){ persistString(value); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { AppItem item = (AppItem) parent.getItemAtPosition(position); setValue(item.getValue()); setSummary(item.getAppName()); getDialog().dismiss(); } private String getAppNameFromValue(String value) { if (value == null) return null; try { PackageManager pm = mContext.getPackageManager(); String[] splitValue = value.split(SEPARATOR); ComponentName cn = new ComponentName(splitValue[0], splitValue[1]); ActivityInfo ai = pm.getActivityInfo(cn, 0); return (ai.loadLabel(pm).toString()); } catch (Exception e) { e.printStackTrace(); return null; } } class AppItem implements IIconListAdapterItem { private String mPackageName; private String mClassName; private String mAppName; private Drawable mAppIcon; public AppItem(String packageName, String className, String appName, Drawable appIcon) { mPackageName = packageName; mClassName = className; mAppName = appName; mAppIcon = appIcon; } public String getPackageName() { return mPackageName; } public String getClassName() { return mClassName; } public String getAppName() { return mAppName; } public String getValue() { if (mPackageName == null || mClassName == null) return null; return String.format("%1$s%2$s%3$s", mPackageName, SEPARATOR, mClassName); } @Override public String getText() { return mAppName; } @Override public String getSubText() { return null; } @Override public Drawable getIconLeft() { return mAppIcon; } @Override public Drawable getIconRight() { return null; } } }
package org.springframework.util; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.util.visitor.ReflectiveVisitorSupport; import org.springframework.util.visitor.Visitor; /** * Visitor that encapsulates value string styling algorithms. * * @author Keith Donald */ public class DefaultObjectStyler implements Visitor, ObjectStyler { private ReflectiveVisitorSupport visitorSupport = new ReflectiveVisitorSupport(); /** * Styles the string form of this object using the reflective visitor * pattern. The reflective help removes the need to define a vistable class * for each type of styled valued. * * @param o * The object to be styled. * @return The styled string. */ public String style(Object o) { return (String)visitorSupport.invokeVisit(this, o); } public String visit(String value) { return ('\'' + value + '\''); } public String visit(Number value) { return String.valueOf(value); } public String visit(Class clazz) { return ClassUtils.getShortName(clazz); } public String visit(Method method) { return method.getName() + "@" + ClassUtils.getShortName(method.getDeclaringClass()); } public String visit(Map value) { StringBuffer buffer = new StringBuffer(value.size() * 8 + 16); buffer.append("<map = { "); for (Iterator i = value.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); buffer.append(style(entry)); if (i.hasNext()) { buffer.append(',').append(' '); } } if (value.isEmpty()) { buffer.append("<none>"); } buffer.append(" }>"); return buffer.toString(); } public String visit(Map.Entry value) { return style(value.getKey()) + " -> " + style(value.getValue()); } public String visit(Set value) { StringBuffer buffer = new StringBuffer(value.size() * 8 + 16); buffer.append("<set = { "); for (Iterator i = value.iterator(); i.hasNext();) { buffer.append(style(i.next())); if (i.hasNext()) { buffer.append(',').append(' '); } } if (value.isEmpty()) { buffer.append("<none>"); } buffer.append(" }>"); return buffer.toString(); } public String visit(List value) { StringBuffer buffer = new StringBuffer(value.size() * 8 + 16); buffer.append("<list = { "); for (Iterator i = value.iterator(); i.hasNext();) { buffer.append(style(i.next())); if (i.hasNext()) { buffer.append(',').append(' '); } } if (value.isEmpty()) { buffer.append("<none>"); } buffer.append(" }>"); return buffer.toString(); } public String visit(Object value) { if (value.getClass().isArray()) { return styleArray(getObjectArray(value)); } else { return String.valueOf(value); } } public String visitNull() { return "[null]"; } private String styleArray(Object[] array) { StringBuffer buffer = new StringBuffer(array.length * 8 + 16); buffer.append("<array = { "); for (int i = 0; i < array.length - 1; i++) { buffer.append(style(array[i])); buffer.append(',').append(' '); } if (array.length > 0) { buffer.append(style(array[array.length - 1])); } else { buffer.append("<none>"); } buffer.append(" }>"); return buffer.toString(); } private Object[] getObjectArray(Object value) { if (value.getClass().getComponentType().isPrimitive()) { return ArrayUtils.toObjectArrayFromPrimitive(value); } else { return (Object[])value; } } }
package com.daveme.intellij.organizephpimports; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.jetbrains.php.codeInsight.PhpCodeInsightUtil; import com.jetbrains.php.lang.psi.PhpFile; import com.jetbrains.php.lang.psi.elements.PhpPsiElement; import com.jetbrains.php.lang.psi.elements.PhpUse; import com.jetbrains.php.lang.psi.elements.PhpUseList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class OrganizeImports extends AnAction { @Override public void update(AnActionEvent e) { super.update(e); Object psiFile = e.getData(CommonDataKeys.PSI_FILE); boolean enabled = psiFile instanceof PhpFile; e.getPresentation().setVisible(enabled); e.getPresentation().setEnabled(enabled); } @Override public void actionPerformed(AnActionEvent e) { Object psiFile = e.getData(CommonDataKeys.PSI_FILE); final PhpFile file = (PhpFile)psiFile; final Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor == null || psiFile == null) { return; } new WriteCommandAction.Simple(file.getProject(), file) { @Override protected void run() throws Throwable { int offset = editor.getCaretModel().getOffset(); PsiElement element = file.findElementAt(offset); if (element == null) { return; } PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(element); if (scopeForUseOperator == null) { return; } List imports = PhpCodeInsightUtil.collectImports(scopeForUseOperator); Integer startingOffset = removeUseStatements(imports, editor); if (startingOffset != null) { StringBuilder useStatements = generateUseStatements(imports); editor.getDocument().insertString(startingOffset, useStatements); } } }.execute(); } @Nullable private Integer removeUseStatements(List imports, Editor editor) { int modifyOffset = 0; Integer startingOffset = null; for (Object useListObject : imports) { PhpUseList useList = (PhpUseList)useListObject; TextRange textRange = useList.getTextRange(); if (startingOffset == null) { startingOffset = textRange.getStartOffset(); } // get the newline character after this use statement if there is one: PsiElement subsequentElement = useList.getNextSibling(); modifyOffset = removeElement(modifyOffset, textRange, editor); if (subsequentElement instanceof PsiWhiteSpace) { PsiElement nextElement = subsequentElement.getNextSibling(); if (nextElement instanceof PhpUseList) { modifyOffset = removeElement(modifyOffset, subsequentElement.getTextRange(), editor); } else { TextRange oldRange = subsequentElement.getTextRange(); TextRange newRange = new TextRange(oldRange.getStartOffset(), oldRange.getStartOffset() + 1); modifyOffset = removeElement(modifyOffset, newRange, editor); } } } return startingOffset; } @NotNull private StringBuilder generateUseStatements(List imports) { // replace the use statements: StringBuilder useStatements = new StringBuilder(); useStatements.append("use "); int totalUses = 0; for (Object useListObject : imports) { PhpUseList useList = (PhpUseList)useListObject; for (PhpUse use : useList.getDeclarations()) { if (totalUses > 0) { useStatements.append(",\n\t"); } useStatements.append(use.getFQN()); totalUses++; } } useStatements.append(";\n"); return useStatements; } private int removeElement(int modifyOffset, TextRange textRange, Editor editor) { editor.getDocument().deleteString(textRange.getStartOffset() - modifyOffset, textRange.getEndOffset() - modifyOffset); return modifyOffset + textRange.getEndOffset() - textRange.getStartOffset(); } }
package com.akiban.server.expression.std; import com.akiban.qp.operator.QueryContext; import com.akiban.server.error.InvalidOperationException; import com.akiban.server.error.InvalidParameterValueException; import com.akiban.server.error.WrongExpressionArityException; import com.akiban.server.expression.Expression; import com.akiban.server.expression.ExpressionComposer; import com.akiban.server.expression.ExpressionEvaluation; import com.akiban.server.expression.ExpressionType; import com.akiban.server.expression.TypesList; import com.akiban.server.service.functions.Scalar; import com.akiban.server.types.AkType; import com.akiban.server.types.NullValueSource; import com.akiban.server.types.ValueSource; import com.akiban.sql.StandardException; import java.util.HashSet; import java.util.Set; public class UnhexExpression extends AbstractUnaryExpression { @Scalar("unhex") public static final ExpressionComposer COMPOSER = new UnaryComposer() { @Override protected Expression compose(Expression argument) { return new UnhexExpression(argument); } @Override public ExpressionType composeType(TypesList argumentTypes) throws StandardException { if (argumentTypes.size() != 1) throw new WrongExpressionArityException(1, argumentTypes.size()); argumentTypes.setType(0, AkType.VARCHAR); return ExpressionTypes.varchar(argumentTypes.get(0).getPrecision() / 2 + 1); } }; private static class InnerEvaluation extends AbstractUnaryExpressionEvaluation { private static final int BASE_CHAR = 10 -'a'; private static final Set<Character> LEGAL = new HashSet<Character>(); static { for (char ch = 'a'; ch <= 'f'; ++ch) LEGAL.add(ch); for (char ch = '0'; ch <= '9'; ++ch) LEGAL.add(ch); } InnerEvaluation(ExpressionEvaluation arg) { super(arg); } /** * It is assumed that if c is a character, it's a lowercase one * * @param c: character with this (ASCII) code * @return the HEX value of this char * * Eg., 97 (or 'a') would return 10 * 45 (or '0') would return 0 */ private static int getHexVal (int c) { return c > 'a' ? c + BASE_CHAR : c - '0'; } private static char parseByte(char highChar, char lowChar) { // convert all to lowercase highChar |= 32; lowChar |= 32; if (!LEGAL.contains(highChar) || !LEGAL.contains(lowChar)) throw new InvalidParameterValueException("Invalid HEX digit(s): " + highChar + " " + lowChar); return (char)((getHexVal(highChar) << 4) + getHexVal(lowChar)); } @Override public ValueSource eval() { ValueSource source = operand(); if (source.isNull()) return NullValueSource.only(); String st = source.getString(); if (st.isEmpty()) valueHolder().putString(st); else try { StringBuilder out = new StringBuilder(); int start, end; // check if the hex string can be evenly divided into pairs // if so, the firt two digits will make a byte (a character) if (st.length() % 2 == 0) { out.append(parseByte(st.charAt(0) ,st.charAt(1))); start = 2; } else // if not, only the first char will { out.append(parseByte('0', st.charAt(0))); start = 1; } // starting from here, all characters should be evenly divided into pairs end = st.length() -1; for (; start < end; ++start) out.append(parseByte(st.charAt(start), st.charAt(++start))); valueHolder().putString(out.toString()); } catch (InvalidOperationException e) { QueryContext qc = queryContext(); if (qc != null) qc.warnClient(e); return NullValueSource.only(); } return valueHolder(); } } UnhexExpression (Expression arg) { super(AkType.VARCHAR, arg); } @Override protected String name() { return "UNHEX"; } @Override public ExpressionEvaluation evaluation() { return new InnerEvaluation(operandEvaluation()); } }
package org.recap.route; import org.apache.camel.ProducerTemplate; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.recap.BaseTestCase; import org.recap.model.jpa.BibliographicEntity; import org.recap.model.jpa.XmlRecordEntity; import org.recap.repository.BibliographicDetailsRepository; import org.recap.repository.HoldingsDetailsRepository; import org.recap.repository.ItemDetailsRepository; import org.recap.repository.XmlRecordRepository; import org.springframework.beans.factory.annotation.Autowired; import java.io.File; import java.net.URL; import java.util.Date; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class EtlDataLoadProcessorUT extends BaseTestCase{ @Autowired XmlRecordRepository xmlRecordRepository; @Autowired EtlDataLoadProcessor etlDataLoadProcessor; @Autowired RecordProcessor recordProcessor; @Autowired BibliographicDetailsRepository bibliographicDetailsRepository; @Autowired HoldingsDetailsRepository holdingsDetailsRepository; @Autowired ItemDetailsRepository itemDetailsRepository; @Autowired ProducerTemplate producer; @Test public void testStartLoadProcessWithXmlFileName() throws Exception { assertNotNull(etlDataLoadProcessor); assertNotNull(recordProcessor); assertNotNull(xmlRecordRepository); assertNotNull(bibliographicDetailsRepository); assertNotNull(holdingsDetailsRepository); assertNotNull(itemDetailsRepository); assertNotNull(producer); XmlRecordEntity xmlRecordEntity = new XmlRecordEntity(); String xmlFileName = "sampleRecordForEtlLoadTest.xml"; xmlRecordEntity.setXmlFileName(xmlFileName); xmlRecordEntity.setOwningInstBibId(".b100006279"); xmlRecordEntity.setOwningInst("NYPL"); xmlRecordEntity.setDataLoaded(new Date()); URL resource = getClass().getResource(xmlFileName); assertNotNull(resource); File file = new File(resource.toURI()); String content = FileUtils.readFileToString(file, "UTF-8"); xmlRecordEntity.setXml(content.getBytes()); xmlRecordRepository.save(xmlRecordEntity); etlDataLoadProcessor.setFileName(xmlFileName); etlDataLoadProcessor.setBatchSize(10); etlDataLoadProcessor.setRecordProcessor(recordProcessor); etlDataLoadProcessor.setXmlRecordRepository(xmlRecordRepository); etlDataLoadProcessor.setBibliographicDetailsRepository(bibliographicDetailsRepository); etlDataLoadProcessor.setHoldingsDetailsRepository(holdingsDetailsRepository); etlDataLoadProcessor.setItemDetailsRepository(itemDetailsRepository); etlDataLoadProcessor.setProducer(producer); etlDataLoadProcessor.setInstitutionName("NYPL"); assertNotNull(etlDataLoadProcessor.getXmlRecordRepository()); assertEquals(etlDataLoadProcessor.getBatchSize(), new Integer(10)); assertEquals(etlDataLoadProcessor.getRecordProcessor(), recordProcessor); assertEquals(etlDataLoadProcessor.getFileName(), xmlFileName); etlDataLoadProcessor.startLoadProcess(); assertEquals(recordProcessor.getXmlFileName(),xmlFileName); BibliographicEntity bibliographicEntity = bibliographicDetailsRepository.findByOwningInstitutionIdAndOwningInstitutionBibId(3,xmlRecordEntity.getOwningInstBibId()); assertNotNull(bibliographicEntity); } }
package org.restcomm.sbc.media; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.channels.DatagramChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import org.mobicents.media.server.impl.rtp.crypto.RawPacket; import org.mobicents.media.server.io.sdp.SessionDescription; import org.restcomm.sbc.ConfigurationCache; import org.restcomm.sbc.media.srtp.RtpConnection; /** * @author ocarriles@eolos.la (Oscar Andres Carriles) * @date 28 nov. 2016 22:12:36 * @class MediaZone.java * */ public class MediaZone { protected static final int BUFFER= 8 * 1024; private static transient Logger LOG = Logger.getLogger(MediaZone.class); protected int originalRtpPort; protected int originalRtcpPort; protected boolean canMux; protected int rtpCountLog=ConfigurationCache.getRtpCountLog(); protected String originalHost; protected String proxyHost; protected String mediaType; protected int logCounter=0; protected boolean running; protected boolean suspended; protected MediaZone mediaZonePeer; protected ExecutorService executorService; protected ExecutorService rtcpService; protected DatagramChannel channel; protected DatagramChannel rtcpChannel; protected DatagramSocket socket; protected DatagramSocket rtcpSocket; protected int packetsSentCounter=0; protected int packetsRecvCounter=0; protected int lastPacketsSentCounter=0; protected int lastPacketsRecvCounter=0; protected int proxyPort; protected Direction direction; protected InetSocketAddress proxyAddress; protected InetSocketAddress rtcpProxyAddress; private InetAddress originalAddress; protected MediaController controller; protected RtpConnection rtpConnection; public MediaZone(MediaController controller, Direction direction, String mediaType, String originalHost, int originalRtpPort, int originalRtcpPort, boolean canMux, int proxyPort) throws UnknownHostException { this.controller=controller; this.originalHost=originalHost; this.originalRtpPort=originalRtpPort; this.originalRtcpPort=originalRtcpPort; this.canMux=canMux; this.mediaType=mediaType; this.direction=direction; this.proxyPort=proxyPort; originalAddress=InetAddress.getByName(originalHost); rtpConnection= new RtpConnection(controller, originalHost, originalRtpPort); if(LOG.isTraceEnabled()) { LOG.trace("direction "+direction); } } public void setLocalProxy(String proxyHost) throws UnknownHostException, SocketException { this.proxyHost=proxyHost; proxyAddress = new InetSocketAddress(proxyHost, proxyPort); try { channel=DatagramChannel.open(); channel.bind(proxyAddress); } catch (IOException e) { throw new SocketException(e.getMessage()); } socket = channel.socket(); if(LOG.isTraceEnabled()) { LOG.trace("Opened socket "+proxyAddress.toString()+" for "+this.toPrint()); } if(!canMux) { rtcpProxyAddress = new InetSocketAddress(proxyHost, proxyPort+1); try { rtcpChannel=DatagramChannel.open(); rtcpChannel.bind(rtcpProxyAddress); } catch (IOException e) { throw new SocketException(e.getMessage()); } rtcpSocket = rtcpChannel.socket(); if(LOG.isTraceEnabled()) { LOG.trace("Opened socket "+rtcpProxyAddress.toString()+" for "+this.toPrint()); } } } public SessionDescription getLocalSdp() { return controller.getSdp(); } protected synchronized boolean checkReady() { if(!isAttached()) return false; if(originalHost==null || originalRtpPort==0) return false; if(proxyHost==null || proxyPort==0) return false; return true; } protected void fireProxyTimeoutEvent() { controller.getMediaSession().fireMediaTimeoutEvent(this); } protected void fireProxyTerminatedEvent() { controller.getMediaSession().fireMediaTerminatedEvent(this); } protected void fireProxyReadyEvent() { controller.getMediaSession().fireMediaReadyEvent(this); } protected void fireProxyFailedEvent() { controller.getMediaSession().fireMediaFailedEvent(this); } public int getOriginalRtpPort() { return originalRtpPort; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public String getOriginalHost() { return originalHost; } public int getProxyPort() { return proxyPort; } public void start() throws IOException { if(isRunning()) { LOG.warn("Media Proxy is just running, silently ignoring"); return; } if(!checkReady()) { LOG.warn("Media Zone could not stablish proper routes, should dismiss? "+this.toPrint()); } if(channel!=null && !channel.isConnected()) { LOG.debug("MUST Connect audio stream "+channel.getLocalAddress()+" to "+mediaZonePeer.getOriginalHost()+":"+mediaZonePeer.getOriginalRtpPort()); //channel.connect(new InetSocketAddress(mediaZonePeer.getOriginalHost(), mediaZonePeer.getOriginalRtpPort())); } setRunning(true); executorService = Executors.newCachedThreadPool(); executorService.execute(new Proxy()); /* if(!mediaZonePeer.isRunning()) mediaZonePeer.start(); */ if(LOG.isInfoEnabled()) { LOG.info("Started "+isRunning()+"->"+this.toPrint()); } if(!canMux) { rtcpService = Executors.newCachedThreadPool(); rtcpService.execute(new RtcpProxy()); if(LOG.isInfoEnabled()) { LOG.info("Started "+isRunning()+"-> RtcpProxy"); } } } public void suspend() { if(LOG.isTraceEnabled()) { LOG.trace("Suspending mediaZone "+this.toPrint()); } suspended=true; } public void resume() { if(LOG.isTraceEnabled()) { LOG.trace("Resuming mediaZone "+this.toPrint()); } suspended=false; } public void finalize() { //ensure not traffic setRunning(false); if(mediaZonePeer!=null) { setRunning(false); if(mediaZonePeer.socket!=null&&!mediaZonePeer.socket.isClosed()) { mediaZonePeer.socket.close(); mediaZonePeer.socket=null; if(LOG.isTraceEnabled()) { LOG.trace("Finalized mediaZone "+mediaZonePeer.toPrint()); } } if(mediaZonePeer.executorService!=null) { mediaZonePeer.executorService.shutdown(); mediaZonePeer.executorService=null; mediaZonePeer.fireProxyTerminatedEvent(); } if(!canMux) { if(mediaZonePeer.rtcpSocket!=null&&!mediaZonePeer.rtcpSocket.isClosed()) { mediaZonePeer.rtcpSocket.close(); mediaZonePeer.rtcpSocket=null; if(LOG.isTraceEnabled()) { LOG.trace("Finalized RTCP mediaZone "); } } if(mediaZonePeer.rtcpService!=null) { mediaZonePeer.rtcpService.shutdown(); mediaZonePeer.rtcpService=null; } } } mediaZonePeer=null; if(socket!=null&&!socket.isClosed()) { socket.close(); socket=null; if(LOG.isTraceEnabled()) { LOG.trace("Finalized mediaZone "+toPrint()); } } if(executorService!=null) { executorService.shutdown(); executorService=null; fireProxyTerminatedEvent(); } if(!canMux) { if(rtcpSocket!=null&&!rtcpSocket.isClosed()) { rtcpSocket.close(); rtcpSocket=null; if(LOG.isTraceEnabled()) { LOG.trace("Finalized RTCP mediaZone "); } } if(rtcpService!=null) { rtcpService.shutdown(); rtcpService=null; } } } public String toPrint() { String value; value="(UMZ "+direction+") "+this.hashCode()+" "+mediaType+", MUX("+canMux+") Origin "+originalHost+":"+originalRtpPort+"/"+originalRtcpPort+", LocalProxy "+proxyHost+":"+proxyPort; if(mediaZonePeer!=null) value+="[("+mediaZonePeer.direction+") "+mediaZonePeer.hashCode()+" "+mediaZonePeer.mediaType+", MUX("+mediaZonePeer.canMux+") Origin "+mediaZonePeer.originalHost+":"+mediaZonePeer.originalRtpPort+"/"+mediaZonePeer.originalRtcpPort+", LocalProxy "+mediaZonePeer.proxyHost+":"+mediaZonePeer.proxyPort+"]"; return value; } public byte[] encodeRTP(byte[] data, int offset, int length) { /* if(LOG.isTraceEnabled()) { LOG.trace("VOID Decoding "+length+" bytes"); } */ return ArrayUtils.subarray(data, offset, length); } public byte[] decodeRTP(byte[] data, int offset, int length) { /* if(LOG.isTraceEnabled()) { LOG.trace("VOID Encoding "+length+" bytes"); } */ return ArrayUtils.subarray(data, offset, length); } public void send(DatagramPacket dgram) throws IOException { if(dgram==null) return; dgram.setAddress(mediaZonePeer.getOriginalAddress()); dgram.setPort(mediaZonePeer.getOriginalRtpPort()); //dgram.setData(mediaZonePeer.encodeRTP(dgram.getData(), 0, dgram.getLength()), 0, dgram.getLength() ); if(dgram.getData().length>8) { if(logCounter==rtpCountLog){ RawPacket rtp=new RawPacket(dgram.getData(),0,dgram.getLength()); LOG.trace("--->[PayloadType "+rtp.getPayloadType()+"]("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]"); logCounter=0; } } else { LOG.warn("--->[PayloadType ?]("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]"); } packetsSentCounter++; socket.send(dgram); } byte[] rbuffer=new byte[BUFFER]; DatagramPacket rdgram=new DatagramPacket(rbuffer, BUFFER); public DatagramPacket receiveRtcp() throws IOException { if(mediaZonePeer.rtcpSocket==null) { throw new IOException("NULL Socket on "+this.toPrint()); } mediaZonePeer.rtcpSocket.receive(rdgram); if(rdgram==null||rdgram.getLength()<8){ LOG.warn("RTCPPacket too short, not sending ["+(rdgram!=null?rdgram.getLength():"NULL")+"]"); rdgram=new DatagramPacket(rbuffer, BUFFER); return null; } return rdgram; } public void sendRtcp(DatagramPacket rdgram) throws IOException { if(rdgram==null) return; rdgram.setAddress(mediaZonePeer.getOriginalAddress()); rdgram.setPort(mediaZonePeer.getOriginalRtcpPort()); rtcpSocket.send(rdgram); } byte[] buffer=new byte[BUFFER]; DatagramPacket dgram=new DatagramPacket(buffer, BUFFER); public DatagramPacket receive() throws IOException { if(mediaZonePeer.socket==null) { throw new IOException("NULL Socket on "+this.toPrint()); } mediaZonePeer.socket.receive(dgram); if(dgram==null||dgram.getLength()<8){ LOG.warn("RTPPacket too short on "+this.toPrint(mediaZonePeer.socket)+" not sending ["+(dgram!=null?dgram.getLength():"NULL")+"]"); dgram=new DatagramPacket(buffer, BUFFER); return null; } dgram.setData(mediaZonePeer.encodeRTP(dgram.getData(), 0, dgram.getLength())); logCounter++; if(logCounter==rtpCountLog){ RawPacket rtp=new RawPacket(dgram.getData(),0,dgram.getLength()); LOG.trace("<---[PayloadType "+rtp.getPayloadType()+"]("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]"); } packetsRecvCounter++; return dgram; } public final void attach(MediaZone mediaZone) { if(!isAttached()) { setMediaZonePeer(mediaZone); } if(!mediaZone.isAttached()) { mediaZone.attach(this); } if(checkReady()) { // Ready to start this.fireProxyReadyEvent(); } } public boolean isAttached() { return mediaZonePeer!=null; } class Proxy implements Runnable { @Override public void run() { while(isRunning()) { if(isSuspended()){ LOG.warn("("+MediaZone.this.toPrint()+") already suspended"); try { Thread.sleep(50); } catch (InterruptedException e) { continue; } continue; } try { send(receive()); } catch (Exception e) { if(!isRunning()||!mediaZonePeer.isRunning()) { LOG.warn("("+MediaZone.this.toPrint()+") not running, returning"); return; } //LOG.error("("+MediaZone.this.toPrint()+") "+e.getMessage()); continue; } } LOG.trace("Ending Media proxy process "+MediaZone.this.toPrint()); } } class RtcpProxy implements Runnable { @Override public void run() { while(isRunning()) { if(isSuspended()){ try { Thread.sleep(50); } catch (InterruptedException e) { continue; } continue; } try { sendRtcp(receiveRtcp()); } catch (Exception e) { if(!isRunning()||!mediaZonePeer.isRunning()) return; //LOG.error("("+MediaZone.this.toPrint()+") "+e.getMessage()); continue; } } } } public boolean isStreaming() { if(LOG.isTraceEnabled()) { LOG.trace("Packets stats on "+this.toPrint()); LOG.trace("Packets total/sent "+packetsSentCounter+"/"+lastPacketsSentCounter); LOG.trace("Packets total/recv "+packetsRecvCounter+"/"+lastPacketsRecvCounter); } if(packetsSentCounter>lastPacketsSentCounter && packetsRecvCounter>lastPacketsRecvCounter && packetsSentCounter>0 && packetsRecvCounter>0) { lastPacketsSentCounter=packetsSentCounter; lastPacketsRecvCounter=packetsRecvCounter; return true; } else { return false; } } public String getMediaType() { return mediaType; } public MediaZone getMediaZonePeer() { return mediaZonePeer; } protected void setMediaZonePeer(MediaZone mediaZonePeer) { this.mediaZonePeer = mediaZonePeer; } public boolean isRunning() { return running; } public boolean isSuspended() { return suspended; } protected synchronized void setRunning(boolean running) { this.running=running; } public int getPacketsSentCounter() { return packetsSentCounter; } public int getPacketsRecvCounter() { return packetsRecvCounter; } public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } @Override public boolean equals(Object zone) { MediaZone otherZone=(MediaZone) zone; if (!(zone instanceof MediaZone)) { return false; } if (otherZone.getOriginalHost().equals(this.getOriginalHost()) && otherZone.getController().equals(this.getController()) && otherZone.getOriginalRtpPort()==this.getOriginalRtpPort() && otherZone.getMediaType().equals(this.getMediaType())&& otherZone.getDirection().equals(this.getDirection())) { return true; } return false; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + ((controller == null) ? 0 : controller.hashCode()); result = prime * result + ((originalHost == null) ? 0 : originalHost.hashCode()); result = prime * result + ((originalRtpPort == 0) ? 0 : originalRtpPort); result = prime * result + ((mediaType == null) ? 0 : mediaType.hashCode()); result = prime * result + ((direction == null) ? 0 : direction.hashCode()); return result; } public enum Direction { OFFER ("*offer"), ANSWER("answer"); private final String text; private Direction(final String text) { this.text = text; } public static Direction getValueOf(final String text) { Direction[] values = values(); for (final Direction value : values) { if (value.toString().equals(text)) { return value; } } throw new IllegalArgumentException(text + " is not a valid call direction."); } @Override public String toString() { return text; } } public Direction getDirection() { return direction; } public InetSocketAddress getProxyAddress() { return proxyAddress; } public InetAddress getOriginalAddress() { return originalAddress; } public MediaController getController() { return controller; } public boolean canMux() { return canMux; } public DatagramChannel getChannel() { return channel; } public RtpConnection getRtpConnection() { return rtpConnection; } public int getOriginalRtcpPort() { return originalRtcpPort; } private String toPrint(DatagramSocket socket) { return "Socket Bound to "+socket.getLocalSocketAddress()+" Connected to "+socket.getRemoteSocketAddress(); } public enum Packet { DTLS ("dtls"), ICE("ice"), RTCP("rtcp"), RTP("rtp"); private final String text; private Packet(final String text) { this.text = text; } public static Packet getValueOf(final String text) { Packet[] values = values(); for (final Packet value : values) { if (value.toString().equals(text)) { return value; } } throw new IllegalArgumentException(text + " is not a valid packet."); } @Override public String toString() { return text; } } }
package com.developerphil.adbidea.adb.command; import com.android.ddmlib.IDevice; import com.android.ddmlib.InstallException; import com.intellij.openapi.project.Project; import org.jetbrains.android.facet.AndroidFacet; import static com.developerphil.adbidea.ui.NotificationHelper.error; import static com.developerphil.adbidea.ui.NotificationHelper.info; public class UninstallCommand implements Command { @Override public void run(Project project, IDevice device, AndroidFacet facet, String packageName) { try { String errorCode = device.uninstallPackage(packageName); if (errorCode == null) { info(String.format("<b>%s</b> uninstalled on %s", packageName, device.getName())); }else{ error(String.format("<b>%s</b> is not installed on %s", packageName, device.getName())); } } catch (InstallException e1) { error("Uninstall fail... " + e1.getMessage()); e1.printStackTrace(); } } }
package de.fosd.jdime.gui; import java.io.File; import java.io.StringWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.application.Application; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.Window; import org.apache.commons.io.IOUtils; /** * A simple JavaFX GUI for JDime. */ public class GUI extends Application { private static final String TITLE = "JDime"; public TextArea output; public TextField left; public TextField base; public TextField right; public TextField jDime; public TextField cmdArgs; public Button leftBtn; public Button baseBtn; public Button rightBtn; public Button runBtn; public Button jDimeBtn; private File lastChooseDir; private List<TextField> textFields; private List<Button> buttons; /** * Launches the GUI with the given <code>args</code>. * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { FXMLLoader loader = new FXMLLoader(getClass().getResource(getClass().getSimpleName() + ".fxml")); loader.setController(this); Parent root = loader.load(); Scene scene = new Scene(root); textFields = Arrays.asList(left, base, right, jDime, cmdArgs); buttons = Arrays.asList(leftBtn, baseBtn, rightBtn, runBtn, jDimeBtn); primaryStage.setTitle(TITLE); primaryStage.setScene(scene); primaryStage.show(); } /** * Shows a <code>FileChooser</code> and returns the chosen <code>File</code>. Sets <code>lastChooseDir</code> * to the parent file of the returned <code>File</code>. * * @param event the <code>ActionEvent</code> that occurred in the action listener * @return the chosen <code>File</code> or <code>null</code> if the dialog was closed */ private File getChosenFile(ActionEvent event) { FileChooser chooser = new FileChooser(); Window window = ((Node) event.getTarget()).getScene().getWindow(); if (lastChooseDir != null && lastChooseDir.isDirectory()) { chooser.setInitialDirectory(lastChooseDir); } return chooser.showOpenDialog(window); } /** * Called when the 'Choose' button for the left file is clicked. * * @param event the <code>ActionEvent</code> that occurred */ public void chooseLeft(ActionEvent event) { File leftArtifact = getChosenFile(event); if (leftArtifact != null) { lastChooseDir = leftArtifact.getParentFile(); left.setText(leftArtifact.getAbsolutePath()); } } /** * Called when the 'Choose' button for the base file is clicked. * * @param event * the <code>ActionEvent</code> that occurred */ public void chooseBase(ActionEvent event) { File baseArtifact = getChosenFile(event); if (baseArtifact != null) { lastChooseDir = baseArtifact.getParentFile(); base.setText(baseArtifact.getAbsolutePath()); } } /** * Called when the 'Choose' button for the right file is clicked. * * @param event * the <code>ActionEvent</code> that occurred */ public void chooseRight(ActionEvent event) { File rightArtifact = getChosenFile(event); if (rightArtifact != null) { lastChooseDir = rightArtifact.getParentFile(); right.setText(rightArtifact.getAbsolutePath()); } } /** * Called when the 'Choose' button for the JDime executable is clicked. * * @param event * the <code>ActionEvent</code> that occurred */ public void chooseJDime(ActionEvent event) { File jDimeBinary = getChosenFile(event); if (jDimeBinary != null) { lastChooseDir = jDimeBinary.getParentFile(); jDime.setText(jDimeBinary.getAbsolutePath()); } } /** * Called when the 'Run' button is clicked. */ public void runClicked() { boolean valid = textFields.stream().allMatch(tf -> { if (tf == cmdArgs) { return true; } if (tf == base) { return tf.getText().trim().isEmpty() || new File(tf.getText()).exists(); } return new File(tf.getText()).exists(); }); if (!valid) { return; } textFields.forEach(textField -> textField.setDisable(true)); buttons.forEach(button -> button.setDisable(true)); Task<String> jDimeExec = new Task<String>() { @Override protected String call() throws Exception { ProcessBuilder builder = new ProcessBuilder(); List<String> command = new ArrayList<>(); command.add(jDime.getText()); command.addAll(Arrays.asList(cmdArgs.getText().split("\\s+"))); command.add(left.getText()); command.add(base.getText()); command.add(right.getText()); builder.command(command); File workingDir = new File(jDime.getText()).getParentFile(); if (workingDir != null && workingDir.exists()) { builder.directory(workingDir); } Process process = builder.start(); process.waitFor(); StringWriter writer = new StringWriter(); IOUtils.copy(process.getInputStream(), writer, Charset.defaultCharset()); return writer.toString(); } }; jDimeExec.setOnSucceeded(event -> { output.setText(jDimeExec.getValue()); textFields.forEach(textField -> textField.setDisable(false)); buttons.forEach(button -> button.setDisable(false)); }); new Thread(jDimeExec).start(); } }