code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# TCXZpot [![Build Status](https://travis-ci.org/SweetzpotAS/TCXZpot-Swift.svg?branch=master)](https://travis-ci.org/SweetzpotAS/TCXZpot-Swift) A fluent Swift library to create TCX files. Please, note this is a Work In Process library that does not include all features supported in TCX yet. They will be added in future releases. For a detailed specification of the TCX format, visit [Garmin specification](http://www8.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd). ### Supported features The root of a TCX file is a `TrainingCenterDatabase` which can have children of multiple types. The supported ones are: - ❌ Folders - ✅ Activities - ❌ Workouts - ❌ Courses - ✅ Author - ❌ Extensions Within the supported modules, everything has been implemented except Extensions. ### Sample You can easily create TCX files with a fluent syntax in TCXZpot: ``` swift let db = TrainingCenterDatabase(activities: Activities(with: Activity(id: TCXDate(day: 10, month: 2, year: 2017, hour: 10, minute: 42, second: 0)!, laps: [Lap(startTime: TCXDate(day: 10, month: 2, year: 2017, hour: 10, minute: 42, second: 0)!, totalTime: 3000, distance: 1200, calories: 100, intensity: .active, triggerMethod: .manual, tracks: Track(with: Trackpoint(time: TCXDate(day: 10, month: 2, year: 2017, hour: 10, minute: 42, second: 0)!, position: Position(latitude: -3.6714, longitude: 36.8936)), Trackpoint(time: TCXDate(day: 10, month: 2, year: 2017, hour: 10, minute: 42, second: 43)!, position: Position(latitude: -3.6727, longitude: 36.8946)), Trackpoint(time: TCXDate(day: 10, month: 2, year: 2017, hour: 10, minute: 43, second: 20)!, position: Position(latitude: -3.6733, longitude: 36.901)) ) )], notes: Notes(text: "A sample session"), creator: Device(name: "BreathZpot Sensor", unitID: 1, productID: 1234567, version: Version(versionMajor: 1, versionMinor: 0)), sport: .running)), author: Application(name: "BreathZpot", build: Build(version: Version(versionMajor: 1, versionMinor: 0)), languageID: "en", partNumber: "123-45678-90")) let serializer = FileSerializer() db.serialize(to: serializer) serializer.save(toPath : "path/to/file") // Can throw SerializationError.fileNotSaved ``` ### Get it from CocoaPods Add the following line to your Podfile: ``` ruby pod 'TCXZpot-Swift', '~> 0.1.0' ``` ## License Copyright 2017 SweetZpot AS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
SweetzpotAS/TCXZpot-Swift
README.md
Markdown
apache-2.0
4,473
/** * Copyright 2010-2016 Boxfuse GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flywaydb.core; import org.flywaydb.core.api.FlywayException; import org.flywaydb.core.api.MigrationInfoService; import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.api.callback.FlywayCallback; import org.flywaydb.core.api.configuration.FlywayConfiguration; import org.flywaydb.core.api.resolver.MigrationResolver; import org.flywaydb.core.internal.callback.SqlScriptFlywayCallback; import org.flywaydb.core.internal.command.DbBaseline; import org.flywaydb.core.internal.command.DbClean; import org.flywaydb.core.internal.command.DbMigrate; import org.flywaydb.core.internal.command.DbRepair; import org.flywaydb.core.internal.command.DbSchemas; import org.flywaydb.core.internal.command.DbValidate; import org.flywaydb.core.internal.dbsupport.DbSupport; import org.flywaydb.core.internal.dbsupport.DbSupportFactory; import org.flywaydb.core.internal.dbsupport.Schema; import org.flywaydb.core.internal.info.MigrationInfoServiceImpl; import org.flywaydb.core.internal.metadatatable.MetaDataTable; import org.flywaydb.core.internal.metadatatable.MetaDataTableImpl; import org.flywaydb.core.internal.resolver.CompositeMigrationResolver; import org.flywaydb.core.internal.util.ClassUtils; import org.flywaydb.core.internal.util.ConfigurationInjectionUtils; import org.flywaydb.core.internal.util.Locations; import org.flywaydb.core.internal.util.PlaceholderReplacer; import org.flywaydb.core.internal.util.StringUtils; import org.flywaydb.core.internal.util.VersionPrinter; import org.flywaydb.core.internal.util.jdbc.DriverDataSource; import org.flywaydb.core.internal.util.jdbc.JdbcUtils; import org.flywaydb.core.internal.util.jdbc.TransactionCallback; import org.flywaydb.core.internal.util.jdbc.TransactionTemplate; import org.flywaydb.core.internal.util.logging.Log; import org.flywaydb.core.internal.util.logging.LogFactory; import org.flywaydb.core.internal.util.scanner.Scanner; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * This is the centre point of Flyway, and for most users, the only class they will ever have to deal with. * <p> * It is THE public API from which all important Flyway functions such as clean, validate and migrate can be called. * </p> */ public class Flyway implements FlywayConfiguration { private static final Log LOG = LogFactory.getLog(Flyway.class); /** * Property name prefix for placeholders that are configured through properties. */ private static final String PLACEHOLDERS_PROPERTY_PREFIX = "flyway.placeholders."; /** * The locations to scan recursively for migrations. * <p/> * <p>The location type is determined by its prefix. * Unprefixed locations or locations starting with {@code classpath:} point to a package on the classpath and may * contain both sql and java-based migrations. * Locations starting with {@code filesystem:} point to a directory on the filesystem and may only contain sql * migrations.</p> * <p/> * (default: db/migration) */ private Locations locations = new Locations("db/migration"); /** * The encoding of Sql migrations. (default: UTF-8) */ private String encoding = "UTF-8"; /** * The schemas managed by Flyway. These schema names are case-sensitive. (default: The default schema for the datasource connection) * <p>Consequences:</p> * <ul> * <li>The first schema in the list will be automatically set as the default one during the migration.</li> * <li>The first schema in the list will also be the one containing the metadata table.</li> * <li>The schemas will be cleaned in the order of this list.</li> * </ul> */ private String[] schemaNames = new String[0]; /** * <p>The name of the schema metadata table that will be used by Flyway. (default: schema_version)</p><p> By default * (single-schema mode) the metadata table is placed in the default schema for the connection provided by the * datasource. </p> <p> When the <i>flyway.schemas</i> property is set (multi-schema mode), the metadata table is * placed in the first schema of the list. </p> */ private String table = "schema_version"; /** * The target version up to which Flyway should consider migrations. Migrations with a higher version number will * be ignored. The special value {@code current} designates the current version of the schema (default: the latest version) */ private MigrationVersion target = MigrationVersion.LATEST; /** * Whether placeholders should be replaced. (default: true) */ private boolean placeholderReplacement = true; /** * The map of &lt;placeholder, replacementValue&gt; to apply to sql migration scripts. */ private Map<String, String> placeholders = new HashMap<String, String>(); /** * The prefix of every placeholder. (default: ${ ) */ private String placeholderPrefix = "${"; /** * The suffix of every placeholder. (default: } ) */ private String placeholderSuffix = "}"; /** * The file name prefix for sql migrations. (default: V) * <p/> * <p>Sql migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , * which using the defaults translates to V1_1__My_description.sql</p> */ private String sqlMigrationPrefix = "V"; /** * The file name prefix for repeatable sql migrations. (default: R) * <p/> * <p>Repeatable sql migrations have the following file name structure: prefixSeparatorDESCRIPTIONsuffix , * which using the defaults translates to R__My_description.sql</p> */ private String repeatableSqlMigrationPrefix = "R"; /** * The file name separator for sql migrations. (default: __) * <p/> * <p>Sql migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , * which using the defaults translates to V1_1__My_description.sql</p> */ private String sqlMigrationSeparator = "__"; /** * The file name suffix for sql migrations. (default: .sql) * <p/> * <p>Sql migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , * which using the defaults translates to V1_1__My_description.sql</p> */ private String sqlMigrationSuffix = ".sql"; /** * Ignore future migrations when reading the metadata table. These are migrations that were performed by a * newer deployment of the application that are not yet available in this version. For example: we have migrations * available on the classpath up to version 3.0. The metadata table indicates that a migration to version 4.0 * (unknown to us) has already been applied. Instead of bombing out (fail fast) with an exception, a * warning is logged and Flyway continues normally. This is useful for situations where one must be able to redeploy * an older version of the application after the database has been migrated by a newer one. (default: {@code true}) */ private boolean ignoreFutureMigrations = true; /** * Ignores failed future migrations when reading the metadata table. These are migrations that were performed by a * newer deployment of the application that are not yet available in this version. For example: we have migrations * available on the classpath up to version 3.0. The metadata table indicates that a migration to version 4.0 * (unknown to us) has already been attempted and failed. Instead of bombing out (fail fast) with an exception, a * warning is logged and Flyway terminates normally. This is useful for situations where a database rollback is not * an option. An older version of the application can then be redeployed, even though a newer one failed due to a * bad migration. (default: {@code false}) * * @deprecated Use the more generic <code>ignoreFutureMigrations</code> instead. Will be removed in Flyway 5.0. */ @Deprecated private boolean ignoreFailedFutureMigration; /** * Whether to automatically call validate or not when running migrate. (default: {@code true}) */ private boolean validateOnMigrate = true; /** * Whether to automatically call clean or not when a validation error occurs. (default: {@code false}) * <p> This is exclusively intended as a convenience for development. Even tough we * strongly recommend not to change migration scripts once they have been checked into SCM and run, this provides a * way of dealing with this case in a smooth manner. The database will be wiped clean automatically, ensuring that * the next migration will bring you back to the state checked into SCM.</p> * <p><b>Warning ! Do not enable in production !</b></p> */ private boolean cleanOnValidationError; /** * Whether to disable clean. (default: {@code false}) * <p>This is especially useful for production environments where running clean can be quite a career limiting move.</p> */ private boolean cleanDisabled; /** * The version to tag an existing schema with when executing baseline. (default: 1) */ private MigrationVersion baselineVersion = MigrationVersion.fromVersion("1"); /** * The description to tag an existing schema with when executing baseline. (default: &lt;&lt; Flyway Baseline &gt;&gt;) */ private String baselineDescription = "<< Flyway Baseline >>"; /** * <p> * Whether to automatically call baseline when migrate is executed against a non-empty schema with no metadata table. * This schema will then be initialized with the {@code baselineVersion} before executing the migrations. * Only migrations above {@code baselineVersion} will then be applied. * </p> * <p> * This is useful for initial Flyway production deployments on projects with an existing DB. * </p> * <p> * Be careful when enabling this as it removes the safety net that ensures * Flyway does not migrate the wrong database in case of a configuration mistake! (default: {@code false}) * </p> */ private boolean baselineOnMigrate; /** * Allows migrations to be run "out of order". * <p>If you already have versions 1 and 3 applied, and now a version 2 is found, * it will be applied too instead of being ignored.</p> * <p>(default: {@code false})</p> */ private boolean outOfOrder; /** * This is a list of custom callbacks that fire before and after tasks are executed. You can * add as many custom callbacks as you want. (default: none) */ private FlywayCallback[] callbacks = new FlywayCallback[0]; /** * Whether Flyway should skip the default callbacks. If true, only custom callbacks are used. * <p>(default: false)</p> */ private boolean skipDefaultCallbacks; /** * The custom MigrationResolvers to be used in addition to the built-in ones for resolving Migrations to apply. * <p>(default: none)</p> */ private MigrationResolver[] resolvers = new MigrationResolver[0]; /** * Whether Flyway should skip the default resolvers. If true, only custom resolvers are used. * <p>(default: false)</p> */ private boolean skipDefaultResolvers; /** * Whether Flyway created the DataSource. */ private boolean createdDataSource; /** * The dataSource to use to access the database. Must have the necessary privileges to execute ddl. */ private DataSource dataSource; /** * The ClassLoader to use for resolving migrations on the classpath. (default: Thread.currentThread().getContextClassLoader() ) */ private ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); /** * Whether the database connection info has already been printed in the logs. */ private boolean dbConnectionInfoPrinted; /** * Creates a new instance of Flyway. This is your starting point. */ public Flyway() { // Do nothing } @Override public String[] getLocations() { String[] result = new String[locations.getLocations().size()]; for (int i = 0; i < locations.getLocations().size(); i++) { result[i] = locations.getLocations().get(i).toString(); } return result; } @Override public String getEncoding() { return encoding; } @Override public String[] getSchemas() { return schemaNames; } @Override public String getTable() { return table; } @Override public MigrationVersion getTarget() { return target; } /** * Checks whether placeholders should be replaced. * * @return Whether placeholders should be replaced. (default: true) */ public boolean isPlaceholderReplacement() { return placeholderReplacement; } @Override public Map<String, String> getPlaceholders() { return placeholders; } @Override public String getPlaceholderPrefix() { return placeholderPrefix; } @Override public String getPlaceholderSuffix() { return placeholderSuffix; } @Override public String getSqlMigrationPrefix() { return sqlMigrationPrefix; } @Override public String getRepeatableSqlMigrationPrefix() { return repeatableSqlMigrationPrefix; } @Override public String getSqlMigrationSeparator() { return sqlMigrationSeparator; } @Override public String getSqlMigrationSuffix() { return sqlMigrationSuffix; } /** * Ignore future migrations when reading the metadata table. These are migrations that were performed by a * newer deployment of the application that are not yet available in this version. For example: we have migrations * available on the classpath up to version 3.0. The metadata table indicates that a migration to version 4.0 * (unknown to us) has already been applied. Instead of bombing out (fail fast) with an exception, a * warning is logged and Flyway continues normally. This is useful for situations where one must be able to redeploy * an older version of the application after the database has been migrated by a newer one. * * @return {@code true} to continue normally and log a warning, {@code false} to fail fast with an exception. * (default: {@code true}) */ public boolean isIgnoreFutureMigrations() { return ignoreFutureMigrations; } /** * Whether to ignore failed future migrations when reading the metadata table. These are migrations that * were performed by a newer deployment of the application that are not yet available in this version. For example: * we have migrations available on the classpath up to version 3.0. The metadata table indicates that a migration to * version 4.0 (unknown to us) has already been attempted and failed. Instead of bombing out (fail fast) with an * exception, a warning is logged and Flyway terminates normally. This is useful for situations where a database * rollback is not an option. An older version of the application can then be redeployed, even though a newer one * failed due to a bad migration. * * @return {@code true} to terminate normally and log a warning, {@code false} to fail fast with an exception. * (default: {@code false}) * @deprecated Use the more generic <code>isIgnoreFutureMigration()</code> instead. Will be removed in Flyway 5.0. */ @Deprecated public boolean isIgnoreFailedFutureMigration() { LOG.warn("ignoreFailedFutureMigration has been deprecated and will be removed in Flyway 5.0. Use the more generic ignoreFutureMigrations instead."); return ignoreFailedFutureMigration; } /** * Whether to automatically call validate or not when running migrate. * * @return {@code true} if validate should be called. {@code false} if not. (default: {@code true}) */ public boolean isValidateOnMigrate() { return validateOnMigrate; } /** * Whether to automatically call clean or not when a validation error occurs. * <p> This is exclusively intended as a convenience for development. Even tough we * strongly recommend not to change migration scripts once they have been checked into SCM and run, this provides a * way of dealing with this case in a smooth manner. The database will be wiped clean automatically, ensuring that * the next migration will bring you back to the state checked into SCM.</p> * <p><b>Warning ! Do not enable in production !</b></p> * * @return {@code true} if clean should be called. {@code false} if not. (default: {@code false}) */ public boolean isCleanOnValidationError() { return cleanOnValidationError; } /** * Whether to disable clean. * <p>This is especially useful for production environments where running clean can be quite a career limiting move.</p> * * @return {@code true} to disabled clean. {@code false} to leave it enabled. (default: {@code false}) */ public boolean isCleanDisabled() { return cleanDisabled; } @Override public MigrationVersion getBaselineVersion() { return baselineVersion; } @Override public String getBaselineDescription() { return baselineDescription; } /** * <p> * Whether to automatically call baseline when migrate is executed against a non-empty schema with no metadata table. * This schema will then be initialized with the {@code baselineVersion} before executing the migrations. * Only migrations above {@code baselineVersion} will then be applied. * </p> * <p> * This is useful for initial Flyway production deployments on projects with an existing DB. * </p> * <p> * Be careful when enabling this as it removes the safety net that ensures * Flyway does not migrate the wrong database in case of a configuration mistake! * </p> * * @return {@code true} if baseline should be called on migrate for non-empty schemas, {@code false} if not. (default: {@code false}) */ public boolean isBaselineOnMigrate() { return baselineOnMigrate; } /** * Allows migrations to be run "out of order". * <p>If you already have versions 1 and 3 applied, and now a version 2 is found, * it will be applied too instead of being ignored.</p> * * @return {@code true} if outOfOrder migrations should be applied, {@code false} if not. (default: {@code false}) */ public boolean isOutOfOrder() { return outOfOrder; } @Override public MigrationResolver[] getResolvers() { return resolvers; } @Override public boolean isSkipDefaultResolvers() { return skipDefaultResolvers; } /** * Retrieves the dataSource to use to access the database. Must have the necessary privileges to execute ddl. * * @return The dataSource to use to access the database. Must have the necessary privileges to execute ddl. */ @Override public DataSource getDataSource() { return dataSource; } @Override public ClassLoader getClassLoader() { return classLoader; } /** * Whether to ignore future migrations when reading the metadata table. These are migrations that were performed by a * newer deployment of the application that are not yet available in this version. For example: we have migrations * available on the classpath up to version 3.0. The metadata table indicates that a migration to version 4.0 * (unknown to us) has already been applied. Instead of bombing out (fail fast) with an exception, a * warning is logged and Flyway continues normally. This is useful for situations where one must be able to redeploy * an older version of the application after the database has been migrated by a newer one. * * @param ignoreFutureMigrations {@code true} to continue normally and log a warning, {@code false} to fail * fast with an exception. (default: {@code true}) */ public void setIgnoreFutureMigrations(boolean ignoreFutureMigrations) { this.ignoreFutureMigrations = ignoreFutureMigrations; } /** * Ignores failed future migrations when reading the metadata table. These are migrations that were performed by a * newer deployment of the application that are not yet available in this version. For example: we have migrations * available on the classpath up to version 3.0. The metadata table indicates that a migration to version 4.0 * (unknown to us) has already been attempted and failed. Instead of bombing out (fail fast) with an exception, a * warning is logged and Flyway terminates normally. This is useful for situations where a database rollback is not * an option. An older version of the application can then be redeployed, even though a newer one failed due to a * bad migration. * * @param ignoreFailedFutureMigration {@code true} to terminate normally and log a warning, {@code false} to fail * fast with an exception. (default: {@code false}) * @deprecated Use the more generic <code>setIgnoreFutureMigrations()</code> instead. Will be removed in Flyway 5.0. */ @Deprecated public void setIgnoreFailedFutureMigration(boolean ignoreFailedFutureMigration) { LOG.warn("ignoreFailedFutureMigration has been deprecated and will be removed in Flyway 5.0. Use the more generic ignoreFutureMigrations instead."); this.ignoreFailedFutureMigration = ignoreFailedFutureMigration; } /** * Whether to automatically call validate or not when running migrate. * * @param validateOnMigrate {@code true} if validate should be called. {@code false} if not. (default: {@code true}) */ public void setValidateOnMigrate(boolean validateOnMigrate) { this.validateOnMigrate = validateOnMigrate; } /** * Whether to automatically call clean or not when a validation error occurs. * <p> This is exclusively intended as a convenience for development. Even tough we * strongly recommend not to change migration scripts once they have been checked into SCM and run, this provides a * way of dealing with this case in a smooth manner. The database will be wiped clean automatically, ensuring that * the next migration will bring you back to the state checked into SCM.</p> * <p><b>Warning ! Do not enable in production !</b></p> * * @param cleanOnValidationError {@code true} if clean should be called. {@code false} if not. (default: {@code false}) */ public void setCleanOnValidationError(boolean cleanOnValidationError) { this.cleanOnValidationError = cleanOnValidationError; } /** * Whether to disable clean. * <p>This is especially useful for production environments where running clean can be quite a career limiting move.</p> * * @param cleanDisabled {@code true} to disabled clean. {@code false} to leave it enabled. (default: {@code false}) */ public void setCleanDisabled(boolean cleanDisabled) { this.cleanDisabled = cleanDisabled; } /** * Sets the locations to scan recursively for migrations. * <p/> * <p>The location type is determined by its prefix. * Unprefixed locations or locations starting with {@code classpath:} point to a package on the classpath and may * contain both sql and java-based migrations. * Locations starting with {@code filesystem:} point to a directory on the filesystem and may only contain sql * migrations.</p> * * @param locations Locations to scan recursively for migrations. (default: db/migration) */ public void setLocations(String... locations) { this.locations = new Locations(locations); } /** * Sets the encoding of Sql migrations. * * @param encoding The encoding of Sql migrations. (default: UTF-8) */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Sets the schemas managed by Flyway. These schema names are case-sensitive. (default: The default schema for the datasource connection) * <p>Consequences:</p> * <ul> * <li>The first schema in the list will be automatically set as the default one during the migration.</li> * <li>The first schema in the list will also be the one containing the metadata table.</li> * <li>The schemas will be cleaned in the order of this list.</li> * </ul> * * @param schemas The schemas managed by Flyway. May not be {@code null}. Must contain at least one element. */ public void setSchemas(String... schemas) { this.schemaNames = schemas; } /** * <p>Sets the name of the schema metadata table that will be used by Flyway.</p><p> By default (single-schema mode) * the metadata table is placed in the default schema for the connection provided by the datasource. </p> <p> When * the <i>flyway.schemas</i> property is set (multi-schema mode), the metadata table is placed in the first schema * of the list. </p> * * @param table The name of the schema metadata table that will be used by flyway. (default: schema_version) */ public void setTable(String table) { this.table = table; } /** * Sets the target version up to which Flyway should consider migrations. Migrations with a higher version number will * be ignored. * * @param target The target version up to which Flyway should consider migrations. (default: the latest version) */ public void setTarget(MigrationVersion target) { this.target = target; } /** * Sets the target version up to which Flyway should consider migrations. * Migrations with a higher version number will be ignored. * * @param target The target version up to which Flyway should consider migrations. * The special value {@code current} designates the current version of the schema. (default: the latest * version) */ public void setTargetAsString(String target) { this.target = MigrationVersion.fromVersion(target); } /** * Sets whether placeholders should be replaced. * * @param placeholderReplacement Whether placeholders should be replaced. (default: true) */ public void setPlaceholderReplacement(boolean placeholderReplacement) { this.placeholderReplacement = placeholderReplacement; } /** * Sets the placeholders to replace in sql migration scripts. * * @param placeholders The map of &lt;placeholder, replacementValue&gt; to apply to sql migration scripts. */ public void setPlaceholders(Map<String, String> placeholders) { this.placeholders = placeholders; } /** * Sets the prefix of every placeholder. * * @param placeholderPrefix The prefix of every placeholder. (default: ${ ) */ public void setPlaceholderPrefix(String placeholderPrefix) { if (!StringUtils.hasLength(placeholderPrefix)) { throw new FlywayException("placeholderPrefix cannot be empty!"); } this.placeholderPrefix = placeholderPrefix; } /** * Sets the suffix of every placeholder. * * @param placeholderSuffix The suffix of every placeholder. (default: } ) */ public void setPlaceholderSuffix(String placeholderSuffix) { if (!StringUtils.hasLength(placeholderSuffix)) { throw new FlywayException("placeholderSuffix cannot be empty!"); } this.placeholderSuffix = placeholderSuffix; } /** * Sets the file name prefix for sql migrations. * <p/> * <p>Sql migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , * which using the defaults translates to V1_1__My_description.sql</p> * * @param sqlMigrationPrefix The file name prefix for sql migrations (default: V) */ public void setSqlMigrationPrefix(String sqlMigrationPrefix) { this.sqlMigrationPrefix = sqlMigrationPrefix; } /** * Sets the file name prefix for repeatable sql migrations. * <p/> * <p>Repeatable sql migrations have the following file name structure: prefixSeparatorDESCRIPTIONsuffix , * which using the defaults translates to R__My_description.sql</p> * * @param repeatableSqlMigrationPrefix The file name prefix for repeatable sql migrations (default: R) */ public void setRepeatableSqlMigrationPrefix(String repeatableSqlMigrationPrefix) { this.repeatableSqlMigrationPrefix = repeatableSqlMigrationPrefix; } /** * Sets the file name separator for sql migrations. * <p/> * <p>Sql migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , * which using the defaults translates to V1_1__My_description.sql</p> * * @param sqlMigrationSeparator The file name separator for sql migrations (default: __) */ public void setSqlMigrationSeparator(String sqlMigrationSeparator) { if (!StringUtils.hasLength(sqlMigrationSeparator)) { throw new FlywayException("sqlMigrationSeparator cannot be empty!"); } this.sqlMigrationSeparator = sqlMigrationSeparator; } /** * Sets the file name suffix for sql migrations. * <p/> * <p>Sql migrations have the following file name structure: prefixVERSIONseparatorDESCRIPTIONsuffix , * which using the defaults translates to V1_1__My_description.sql</p> * * @param sqlMigrationSuffix The file name suffix for sql migrations (default: .sql) */ public void setSqlMigrationSuffix(String sqlMigrationSuffix) { this.sqlMigrationSuffix = sqlMigrationSuffix; } /** * Sets the datasource to use. Must have the necessary privileges to execute ddl. * * @param dataSource The datasource to use. Must have the necessary privileges to execute ddl. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; createdDataSource = false; } /** * Sets the datasource to use. Must have the necessary privileges to execute ddl. * <p/> * <p>To use a custom ClassLoader, setClassLoader() must be called prior to calling this method.</p> * * @param url The JDBC URL of the database. * @param user The user of the database. * @param password The password of the database. * @param initSqls The (optional) sql statements to execute to initialize a connection immediately after obtaining it. */ public void setDataSource(String url, String user, String password, String... initSqls) { this.dataSource = new DriverDataSource(classLoader, null, url, user, password, initSqls); createdDataSource = true; } /** * Sets the ClassLoader to use for resolving migrations on the classpath. * * @param classLoader The ClassLoader to use for resolving migrations on the classpath. (default: Thread.currentThread().getContextClassLoader() ) */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Sets the version to tag an existing schema with when executing baseline. * * @param baselineVersion The version to tag an existing schema with when executing baseline. (default: 1) */ public void setBaselineVersion(MigrationVersion baselineVersion) { this.baselineVersion = baselineVersion; } /** * Sets the version to tag an existing schema with when executing baseline. * * @param baselineVersion The version to tag an existing schema with when executing baseline. (default: 1) */ public void setBaselineVersionAsString(String baselineVersion) { this.baselineVersion = MigrationVersion.fromVersion(baselineVersion); } /** * Sets the description to tag an existing schema with when executing baseline. * * @param baselineDescription The description to tag an existing schema with when executing baseline. (default: &lt;&lt; Flyway Baseline &gt;&gt;) */ public void setBaselineDescription(String baselineDescription) { this.baselineDescription = baselineDescription; } /** * <p> * Whether to automatically call baseline when migrate is executed against a non-empty schema with no metadata table. * This schema will then be baselined with the {@code baselineVersion} before executing the migrations. * Only migrations above {@code baselineVersion} will then be applied. * </p> * <p> * This is useful for initial Flyway production deployments on projects with an existing DB. * </p> * <p> * Be careful when enabling this as it removes the safety net that ensures * Flyway does not migrate the wrong database in case of a configuration mistake! * </p> * * @param baselineOnMigrate {@code true} if baseline should be called on migrate for non-empty schemas, {@code false} if not. (default: {@code false}) */ public void setBaselineOnMigrate(boolean baselineOnMigrate) { this.baselineOnMigrate = baselineOnMigrate; } /** * Allows migrations to be run "out of order". * <p>If you already have versions 1 and 3 applied, and now a version 2 is found, * it will be applied too instead of being ignored.</p> * * @param outOfOrder {@code true} if outOfOrder migrations should be applied, {@code false} if not. (default: {@code false}) */ public void setOutOfOrder(boolean outOfOrder) { this.outOfOrder = outOfOrder; } /** * Gets the callbacks for lifecycle notifications. * * @return The callbacks for lifecycle notifications. An empty array if none. (default: none) */ @Override public FlywayCallback[] getCallbacks() { return callbacks; } @Override public boolean isSkipDefaultCallbacks() { return skipDefaultCallbacks; } /** * Set the callbacks for lifecycle notifications. * * @param callbacks The callbacks for lifecycle notifications. (default: none) */ public void setCallbacks(FlywayCallback... callbacks) { this.callbacks = callbacks; } /** * Set the callbacks for lifecycle notifications. * * @param callbacks The fully qualified class names of the callbacks for lifecycle notifications. (default: none) */ public void setCallbacksAsClassNames(String... callbacks) { List<FlywayCallback> callbackList = ClassUtils.instantiateAll(callbacks, classLoader); setCallbacks(callbackList.toArray(new FlywayCallback[callbacks.length])); } /** * Whether Flyway should skip the default callbacks. If true, only custom callbacks are used. * * @param skipDefaultCallbacks Whether default built-in callbacks should be skipped. <p>(default: false)</p> */ public void setSkipDefaultCallbacks(boolean skipDefaultCallbacks) { this.skipDefaultCallbacks = skipDefaultCallbacks; } /** * Sets custom MigrationResolvers to be used in addition to the built-in ones for resolving Migrations to apply. * * @param resolvers The custom MigrationResolvers to be used in addition to the built-in ones for resolving Migrations to apply. (default: empty list) */ public void setResolvers(MigrationResolver... resolvers) { this.resolvers = resolvers; } /** * Sets custom MigrationResolvers to be used in addition to the built-in ones for resolving Migrations to apply. * * @param resolvers The fully qualified class names of the custom MigrationResolvers to be used in addition to the built-in ones for resolving Migrations to apply. (default: empty list) */ public void setResolversAsClassNames(String... resolvers) { List<MigrationResolver> resolverList = ClassUtils.instantiateAll(resolvers, classLoader); setResolvers(resolverList.toArray(new MigrationResolver[resolvers.length])); } /** * Whether Flyway should skip the default resolvers. If true, only custom resolvers are used. * * @param skipDefaultResolvers Whether default built-in resolvers should be skipped. <p>(default: false)</p> */ public void setSkipDefaultResolvers(boolean skipDefaultResolvers) { this.skipDefaultResolvers = skipDefaultResolvers; } /** * <p>Starts the database migration. All pending migrations will be applied in order. * Calling migrate on an up-to-date database has no effect.</p> * <img src="https://flywaydb.org/assets/balsamiq/command-migrate.png" alt="migrate"> * * @return The number of successfully applied migrations. * @throws FlywayException when the migration failed. */ public int migrate() throws FlywayException { return execute(new Command<Integer>() { public Integer execute(Connection connectionMetaDataTable, Connection connectionUserObjects, MigrationResolver migrationResolver, MetaDataTable metaDataTable, DbSupport dbSupport, Schema[] schemas, FlywayCallback[] flywayCallbacks) { if (validateOnMigrate) { doValidate(connectionMetaDataTable, dbSupport, migrationResolver, metaDataTable, schemas, flywayCallbacks, true); } new DbSchemas(connectionMetaDataTable, schemas, metaDataTable).create(); if (!metaDataTable.hasSchemasMarker() && !metaDataTable.hasBaselineMarker() && !metaDataTable.hasAppliedMigrations()) { List<Schema> nonEmptySchemas = new ArrayList<Schema>(); for (Schema schema : schemas) { if (!schema.empty()) { nonEmptySchemas.add(schema); } } if (baselineOnMigrate || nonEmptySchemas.isEmpty()) { if (baselineOnMigrate && !nonEmptySchemas.isEmpty()) { new DbBaseline(connectionMetaDataTable, dbSupport, metaDataTable, schemas[0], baselineVersion, baselineDescription, flywayCallbacks).baseline(); } } else { if (nonEmptySchemas.size() == 1) { Schema schema = nonEmptySchemas.get(0); //Check whether we only have an empty metadata table in an otherwise empty schema if (schema.allTables().length != 1 || !schema.getTable(table).exists()) { throw new FlywayException("Found non-empty schema " + schema + " without metadata table! Use baseline()" + " or set baselineOnMigrate to true to initialize the metadata table."); } } else { throw new FlywayException("Found non-empty schemas " + StringUtils.collectionToCommaDelimitedString(nonEmptySchemas) + " without metadata table! Use baseline()" + " or set baselineOnMigrate to true to initialize the metadata table."); } } } DbMigrate dbMigrate = new DbMigrate(connectionMetaDataTable, connectionUserObjects, dbSupport, metaDataTable, schemas[0], migrationResolver, target, ignoreFutureMigrations, ignoreFailedFutureMigration, outOfOrder, flywayCallbacks); return dbMigrate.migrate(); } }); } /** * <p>Validate applied migration with classpath migrations to detect accidental changes.</p> * <img src="https://flywaydb.org/assets/balsamiq/command-validate.png" alt="validate"> * * @throws FlywayException when the validation failed. */ public void validate() throws FlywayException { execute(new Command<Void>() { public Void execute(Connection connectionMetaDataTable, Connection connectionUserObjects, MigrationResolver migrationResolver, MetaDataTable metaDataTable, DbSupport dbSupport, Schema[] schemas, FlywayCallback[] flywayCallbacks) { doValidate(connectionMetaDataTable, dbSupport, migrationResolver, metaDataTable, schemas, flywayCallbacks, false); return null; } }); } /** * Performs the actual validation. All set up must have taken place beforehand. * * @param connectionMetaDataTable The database connection for the metadata table. * @param dbSupport The database-specific support. * @param migrationResolver The migration resolver; * @param metaDataTable The metadata table. * @param schemas The schemas managed by Flyway. * @param pending Whether pending migrations are ok. */ private void doValidate(Connection connectionMetaDataTable, DbSupport dbSupport, MigrationResolver migrationResolver, MetaDataTable metaDataTable, Schema[] schemas, FlywayCallback[] flywayCallbacks, boolean pending) { String validationError = new DbValidate(connectionMetaDataTable, dbSupport, metaDataTable, schemas[0], migrationResolver, target, outOfOrder, pending, ignoreFutureMigrations, flywayCallbacks).validate(); if (validationError != null) { if (cleanOnValidationError) { new DbClean(connectionMetaDataTable, dbSupport, metaDataTable, schemas, flywayCallbacks, cleanDisabled).clean(); } else { throw new FlywayException("Validate failed: " + validationError); } } } /** * <p>Drops all objects (tables, views, procedures, triggers, ...) in the configured schemas. * The schemas are cleaned in the order specified by the {@code schemas} property.</p> * <img src="https://flywaydb.org/assets/balsamiq/command-clean.png" alt="clean"> * * @throws FlywayException when the clean fails. */ public void clean() { execute(new Command<Void>() { public Void execute(Connection connectionMetaDataTable, Connection connectionUserObjects, MigrationResolver migrationResolver, MetaDataTable metaDataTable, DbSupport dbSupport, Schema[] schemas, FlywayCallback[] flywayCallbacks) { new DbClean(connectionMetaDataTable, dbSupport, metaDataTable, schemas, flywayCallbacks, cleanDisabled).clean(); return null; } }); } /** * <p>Retrieves the complete information about all the migrations including applied, pending and current migrations with * details and status.</p> * <img src="https://flywaydb.org/assets/balsamiq/command-info.png" alt="info"> * * @return All migrations sorted by version, oldest first. * @throws FlywayException when the info retrieval failed. */ public MigrationInfoService info() { return execute(new Command<MigrationInfoService>() { public MigrationInfoService execute(final Connection connectionMetaDataTable, Connection connectionUserObjects, MigrationResolver migrationResolver, MetaDataTable metaDataTable, final DbSupport dbSupport, final Schema[] schemas, FlywayCallback[] flywayCallbacks) { try { for (final FlywayCallback callback : flywayCallbacks) { new TransactionTemplate(connectionMetaDataTable).execute(new TransactionCallback<Object>() { @Override public Object doInTransaction() throws SQLException { dbSupport.changeCurrentSchemaTo(schemas[0]); callback.beforeInfo(connectionMetaDataTable); return null; } }); } MigrationInfoServiceImpl migrationInfoService = new MigrationInfoServiceImpl(migrationResolver, metaDataTable, target, outOfOrder, true, true); migrationInfoService.refresh(); for (final FlywayCallback callback : flywayCallbacks) { new TransactionTemplate(connectionMetaDataTable).execute(new TransactionCallback<Object>() { @Override public Object doInTransaction() throws SQLException { dbSupport.changeCurrentSchemaTo(schemas[0]); callback.afterInfo(connectionMetaDataTable); return null; } }); } return migrationInfoService; } finally { dbSupport.restoreCurrentSchema(); } } }); } /** * <p>Baselines an existing database, excluding all migrations up to and including baselineVersion.</p> * <p/> * <img src="https://flywaydb.org/assets/balsamiq/command-baseline.png" alt="baseline"> * * @throws FlywayException when the schema baselining failed. */ public void baseline() throws FlywayException { execute(new Command<Void>() { public Void execute(Connection connectionMetaDataTable, Connection connectionUserObjects, MigrationResolver migrationResolver, MetaDataTable metaDataTable, DbSupport dbSupport, Schema[] schemas, FlywayCallback[] flywayCallbacks) { new DbSchemas(connectionMetaDataTable, schemas, metaDataTable).create(); new DbBaseline(connectionMetaDataTable, dbSupport, metaDataTable, schemas[0], baselineVersion, baselineDescription, flywayCallbacks).baseline(); return null; } }); } /** * Repairs the Flyway metadata table. This will perform the following actions: * <ul> * <li>Remove any failed migrations on databases without DDL transactions (User objects left behind must still be cleaned up manually)</li> * <li>Correct wrong checksums</li> * </ul> * <img src="https://flywaydb.org/assets/balsamiq/command-repair.png" alt="repair"> * * @throws FlywayException when the metadata table repair failed. */ public void repair() throws FlywayException { execute(new Command<Void>() { public Void execute(Connection connectionMetaDataTable, Connection connectionUserObjects, MigrationResolver migrationResolver, MetaDataTable metaDataTable, DbSupport dbSupport, Schema[] schemas, FlywayCallback[] flywayCallbacks) { new DbRepair(dbSupport, connectionMetaDataTable, schemas[0], migrationResolver, metaDataTable, flywayCallbacks).repair(); return null; } }); } /** * Creates the MigrationResolver. * * @param dbSupport The database-specific support. * @param scanner The Scanner for resolving migrations. * @return A new, fully configured, MigrationResolver instance. */ private MigrationResolver createMigrationResolver(DbSupport dbSupport, Scanner scanner) { for (MigrationResolver resolver : resolvers) { ConfigurationInjectionUtils.injectFlywayConfiguration(resolver, this); } return new CompositeMigrationResolver(dbSupport, scanner, this, locations, encoding, sqlMigrationPrefix, repeatableSqlMigrationPrefix, sqlMigrationSeparator, sqlMigrationSuffix, createPlaceholderReplacer(), resolvers); } /** * @return A new, fully configured, PlaceholderReplacer. */ private PlaceholderReplacer createPlaceholderReplacer() { if (placeholderReplacement) { return new PlaceholderReplacer(placeholders, placeholderPrefix, placeholderSuffix); } return PlaceholderReplacer.NO_PLACEHOLDERS; } /** * Configures Flyway with these properties. This overwrites any existing configuration. Property names are * documented in the flyway maven plugin. * <p/> * <p>To use a custom ClassLoader, setClassLoader() must be called prior to calling this method.</p> * * @param properties Properties used for configuration. * @throws FlywayException when the configuration failed. */ @SuppressWarnings("ConstantConditions") public void configure(Properties properties) { Map<String, String> props = new HashMap<String, String>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { props.put(entry.getKey().toString(), entry.getValue().toString()); } String driverProp = getValueAndRemoveEntry(props, "flyway.driver"); String urlProp = getValueAndRemoveEntry(props, "flyway.url"); String userProp = getValueAndRemoveEntry(props, "flyway.user"); String passwordProp = getValueAndRemoveEntry(props, "flyway.password"); if (StringUtils.hasText(urlProp)) { setDataSource(new DriverDataSource(classLoader, driverProp, urlProp, userProp, passwordProp)); } else if (!StringUtils.hasText(urlProp) && (StringUtils.hasText(driverProp) || StringUtils.hasText(userProp) || StringUtils.hasText(passwordProp))) { LOG.warn("Discarding INCOMPLETE dataSource configuration! flyway.url must be set."); } String locationsProp = getValueAndRemoveEntry(props, "flyway.locations"); if (locationsProp != null) { setLocations(StringUtils.tokenizeToStringArray(locationsProp, ",")); } String placeholderReplacementProp = getValueAndRemoveEntry(props, "flyway.placeholderReplacement"); if (placeholderReplacementProp != null) { setPlaceholderReplacement(Boolean.parseBoolean(placeholderReplacementProp)); } String placeholderPrefixProp = getValueAndRemoveEntry(props, "flyway.placeholderPrefix"); if (placeholderPrefixProp != null) { setPlaceholderPrefix(placeholderPrefixProp); } String placeholderSuffixProp = getValueAndRemoveEntry(props, "flyway.placeholderSuffix"); if (placeholderSuffixProp != null) { setPlaceholderSuffix(placeholderSuffixProp); } String sqlMigrationPrefixProp = getValueAndRemoveEntry(props, "flyway.sqlMigrationPrefix"); if (sqlMigrationPrefixProp != null) { setSqlMigrationPrefix(sqlMigrationPrefixProp); } String repeatableSqlMigrationPrefixProp = getValueAndRemoveEntry(props, "flyway.repeatableSqlMigrationPrefix"); if (repeatableSqlMigrationPrefixProp != null) { setRepeatableSqlMigrationPrefix(repeatableSqlMigrationPrefixProp); } String sqlMigrationSeparatorProp = getValueAndRemoveEntry(props, "flyway.sqlMigrationSeparator"); if (sqlMigrationSeparatorProp != null) { setSqlMigrationSeparator(sqlMigrationSeparatorProp); } String sqlMigrationSuffixProp = getValueAndRemoveEntry(props, "flyway.sqlMigrationSuffix"); if (sqlMigrationSuffixProp != null) { setSqlMigrationSuffix(sqlMigrationSuffixProp); } String encodingProp = getValueAndRemoveEntry(props, "flyway.encoding"); if (encodingProp != null) { setEncoding(encodingProp); } String schemasProp = getValueAndRemoveEntry(props, "flyway.schemas"); if (schemasProp != null) { setSchemas(StringUtils.tokenizeToStringArray(schemasProp, ",")); } String tableProp = getValueAndRemoveEntry(props, "flyway.table"); if (tableProp != null) { setTable(tableProp); } String cleanOnValidationErrorProp = getValueAndRemoveEntry(props, "flyway.cleanOnValidationError"); if (cleanOnValidationErrorProp != null) { setCleanOnValidationError(Boolean.parseBoolean(cleanOnValidationErrorProp)); } String cleanDisabledProp = getValueAndRemoveEntry(props, "flyway.cleanDisabled"); if (cleanDisabledProp != null) { setCleanDisabled(Boolean.parseBoolean(cleanDisabledProp)); } String validateOnMigrateProp = getValueAndRemoveEntry(props, "flyway.validateOnMigrate"); if (validateOnMigrateProp != null) { setValidateOnMigrate(Boolean.parseBoolean(validateOnMigrateProp)); } String baselineVersionProp = getValueAndRemoveEntry(props, "flyway.baselineVersion"); if (baselineVersionProp != null) { setBaselineVersion(MigrationVersion.fromVersion(baselineVersionProp)); } String baselineDescriptionProp = getValueAndRemoveEntry(props, "flyway.baselineDescription"); if (baselineDescriptionProp != null) { setBaselineDescription(baselineDescriptionProp); } String baselineOnMigrateProp = getValueAndRemoveEntry(props, "flyway.baselineOnMigrate"); if (baselineOnMigrateProp != null) { setBaselineOnMigrate(Boolean.parseBoolean(baselineOnMigrateProp)); } String ignoreFutureMigrationsProp = getValueAndRemoveEntry(props, "flyway.ignoreFutureMigrations"); if (ignoreFutureMigrationsProp != null) { setIgnoreFutureMigrations(Boolean.parseBoolean(ignoreFutureMigrationsProp)); } String ignoreFailedFutureMigrationProp = getValueAndRemoveEntry(props, "flyway.ignoreFailedFutureMigration"); if (ignoreFailedFutureMigrationProp != null) { setIgnoreFailedFutureMigration(Boolean.parseBoolean(ignoreFailedFutureMigrationProp)); } String targetProp = getValueAndRemoveEntry(props, "flyway.target"); if (targetProp != null) { setTarget(MigrationVersion.fromVersion(targetProp)); } String outOfOrderProp = getValueAndRemoveEntry(props, "flyway.outOfOrder"); if (outOfOrderProp != null) { setOutOfOrder(Boolean.parseBoolean(outOfOrderProp)); } String resolversProp = getValueAndRemoveEntry(props, "flyway.resolvers"); if (StringUtils.hasLength(resolversProp)) { setResolversAsClassNames(StringUtils.tokenizeToStringArray(resolversProp, ",")); } String skipDefaultResolversProp = getValueAndRemoveEntry(props, "flyway.skipDefaultResolvers"); if (skipDefaultResolversProp != null) { setSkipDefaultResolvers(Boolean.parseBoolean(skipDefaultResolversProp)); } String callbacksProp = getValueAndRemoveEntry(props, "flyway.callbacks"); if (StringUtils.hasLength(callbacksProp)) { setCallbacksAsClassNames(StringUtils.tokenizeToStringArray(callbacksProp, ",")); } String skipDefaultCallbacksProp = getValueAndRemoveEntry(props, "flyway.skipDefaultCallbacks"); if (skipDefaultCallbacksProp != null) { setSkipDefaultCallbacks(Boolean.parseBoolean(skipDefaultCallbacksProp)); } Map<String, String> placeholdersFromProps = new HashMap<String, String>(placeholders); Iterator<Map.Entry<String, String>> iterator = props.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); String propertyName = entry.getKey(); if (propertyName.startsWith(PLACEHOLDERS_PROPERTY_PREFIX) && propertyName.length() > PLACEHOLDERS_PROPERTY_PREFIX.length()) { String placeholderName = propertyName.substring(PLACEHOLDERS_PROPERTY_PREFIX.length()); String placeholderValue = entry.getValue(); placeholdersFromProps.put(placeholderName, placeholderValue); iterator.remove(); } } setPlaceholders(placeholdersFromProps); for (String key : props.keySet()) { if (key.startsWith("flyway.")) { LOG.warn("Unknown configuration property: " + key); } } } /** * Retrieves the value for this key in this map and removes the corresponding entry from the map. * * @param map The map. * @param key The key. * @return The value. {@code null} if not found. */ private String getValueAndRemoveEntry(Map<String, String> map, String key) { String value = map.get(key); map.remove(key); return value; } /** * Executes this command with proper resource handling and cleanup. * * @param command The command to execute. * @param <T> The type of the result. * @return The result of the command. */ /*private -> testing*/ <T> T execute(Command<T> command) { T result; VersionPrinter.printVersion(); Connection connectionMetaDataTable = null; Connection connectionUserObjects = null; try { if (dataSource == null) { throw new FlywayException("Unable to connect to the database. Configure the url, user and password!"); } connectionMetaDataTable = JdbcUtils.openConnection(dataSource); connectionUserObjects = JdbcUtils.openConnection(dataSource); DbSupport dbSupport = DbSupportFactory.createDbSupport(connectionMetaDataTable, !dbConnectionInfoPrinted); dbConnectionInfoPrinted = true; LOG.debug("DDL Transactions Supported: " + dbSupport.supportsDdlTransactions()); if (schemaNames.length == 0) { Schema currentSchema = dbSupport.getOriginalSchema(); if (currentSchema == null) { throw new FlywayException("Unable to determine schema for the metadata table." + " Set a default schema for the connection or specify one using the schemas property!"); } setSchemas(currentSchema.getName()); } if (schemaNames.length == 1) { LOG.debug("Schema: " + schemaNames[0]); } else { LOG.debug("Schemas: " + StringUtils.arrayToCommaDelimitedString(schemaNames)); } Schema[] schemas = new Schema[schemaNames.length]; for (int i = 0; i < schemaNames.length; i++) { schemas[i] = dbSupport.getSchema(schemaNames[i]); } Scanner scanner = new Scanner(classLoader); MigrationResolver migrationResolver = createMigrationResolver(dbSupport, scanner); Set<FlywayCallback> flywayCallbacks = new LinkedHashSet<FlywayCallback>(Arrays.asList(callbacks)); if (!skipDefaultCallbacks) { flywayCallbacks.add(new SqlScriptFlywayCallback(dbSupport, scanner, locations, createPlaceholderReplacer(), encoding, sqlMigrationSuffix)); } for (FlywayCallback callback : flywayCallbacks) { ConfigurationInjectionUtils.injectFlywayConfiguration(callback, this); } FlywayCallback[] flywayCallbacksArray = flywayCallbacks.toArray(new FlywayCallback[flywayCallbacks.size()]); MetaDataTable metaDataTable = new MetaDataTableImpl(dbSupport, schemas[0].getTable(table)); if (metaDataTable.upgradeIfNecessary()) { new DbRepair(dbSupport, connectionMetaDataTable, schemas[0], migrationResolver, metaDataTable, flywayCallbacksArray).repairChecksums(); LOG.info("Metadata table " + table + " successfully upgraded to the Flyway 4.0 format."); } result = command.execute(connectionMetaDataTable, connectionUserObjects, migrationResolver, metaDataTable, dbSupport, schemas, flywayCallbacksArray); } finally { JdbcUtils.closeConnection(connectionUserObjects); JdbcUtils.closeConnection(connectionMetaDataTable); if ((dataSource instanceof DriverDataSource) && createdDataSource) { ((DriverDataSource) dataSource).close(); } } return result; } /** * A Flyway command that can be executed. * * @param <T> The result type of the command. */ /*private -> testing*/ interface Command<T> { /** * Execute the operation. * * @param connectionMetaDataTable The database connection for the metadata table changes. * @param connectionUserObjects The database connection for user object changes. * @param migrationResolver The migration resolver to use. * @param metaDataTable The metadata table. * @param dbSupport The database-specific support for these connections. * @param schemas The schemas managed by Flyway. @return The result of the operation. * @param flywayCallbacks The callbacks to use. */ T execute(Connection connectionMetaDataTable, Connection connectionUserObjects, MigrationResolver migrationResolver, MetaDataTable metaDataTable, DbSupport dbSupport, Schema[] schemas, FlywayCallback[] flywayCallbacks); } }
FulcrumTechnologies/flyway
flyway-core/src/main/java/org/flywaydb/core/Flyway.java
Java
apache-2.0
63,134
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "linker/arm64/relative_patcher_arm64.h" #include "arch/arm64/instruction_set_features_arm64.h" #include "art_method.h" #include "compiled_method.h" #include "driver/compiler_driver.h" #include "utils/arm64/assembler_arm64.h" #include "oat.h" #include "output_stream.h" namespace art { namespace linker { Arm64RelativePatcher::Arm64RelativePatcher(RelativePatcherTargetProvider* provider, const Arm64InstructionSetFeatures* features) : ArmBaseRelativePatcher(provider, kArm64, CompileThunkCode(), kMaxPositiveDisplacement, kMaxNegativeDisplacement), fix_cortex_a53_843419_(features->NeedFixCortexA53_843419()), reserved_adrp_thunks_(0u), processed_adrp_thunks_(0u) { if (fix_cortex_a53_843419_) { adrp_thunk_locations_.reserve(16u); current_method_thunks_.reserve(16u * kAdrpThunkSize); } } uint32_t Arm64RelativePatcher::ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method, MethodReference method_ref) { if (!fix_cortex_a53_843419_) { DCHECK(adrp_thunk_locations_.empty()); return ReserveSpaceInternal(offset, compiled_method, method_ref, 0u); } // Add thunks for previous method if any. if (reserved_adrp_thunks_ != adrp_thunk_locations_.size()) { size_t num_adrp_thunks = adrp_thunk_locations_.size() - reserved_adrp_thunks_; offset = CompiledMethod::AlignCode(offset, kArm64) + kAdrpThunkSize * num_adrp_thunks; reserved_adrp_thunks_ = adrp_thunk_locations_.size(); } // Count the number of ADRP insns as the upper bound on the number of thunks needed // and use it to reserve space for other linker patches. size_t num_adrp = 0u; DCHECK(compiled_method != nullptr); for (const LinkerPatch& patch : compiled_method->GetPatches()) { if (patch.Type() == kLinkerPatchDexCacheArray && patch.LiteralOffset() == patch.PcInsnOffset()) { // ADRP patch ++num_adrp; } } offset = ReserveSpaceInternal(offset, compiled_method, method_ref, kAdrpThunkSize * num_adrp); if (num_adrp == 0u) { return offset; } // Now that we have the actual offset where the code will be placed, locate the ADRP insns // that actually require the thunk. uint32_t quick_code_offset = compiled_method->AlignCode(offset) + sizeof(OatQuickMethodHeader); ArrayRef<const uint8_t> code(*compiled_method->GetQuickCode()); uint32_t thunk_offset = compiled_method->AlignCode(quick_code_offset + code.size()); DCHECK(compiled_method != nullptr); for (const LinkerPatch& patch : compiled_method->GetPatches()) { if (patch.Type() == kLinkerPatchDexCacheArray && patch.LiteralOffset() == patch.PcInsnOffset()) { // ADRP patch uint32_t patch_offset = quick_code_offset + patch.LiteralOffset(); if (NeedsErratum843419Thunk(code, patch.LiteralOffset(), patch_offset)) { adrp_thunk_locations_.emplace_back(patch_offset, thunk_offset); thunk_offset += kAdrpThunkSize; } } } return offset; } uint32_t Arm64RelativePatcher::ReserveSpaceEnd(uint32_t offset) { if (!fix_cortex_a53_843419_) { DCHECK(adrp_thunk_locations_.empty()); } else { // Add thunks for the last method if any. if (reserved_adrp_thunks_ != adrp_thunk_locations_.size()) { size_t num_adrp_thunks = adrp_thunk_locations_.size() - reserved_adrp_thunks_; offset = CompiledMethod::AlignCode(offset, kArm64) + kAdrpThunkSize * num_adrp_thunks; reserved_adrp_thunks_ = adrp_thunk_locations_.size(); } } return ArmBaseRelativePatcher::ReserveSpaceEnd(offset); } uint32_t Arm64RelativePatcher::WriteThunks(OutputStream* out, uint32_t offset) { if (fix_cortex_a53_843419_) { if (!current_method_thunks_.empty()) { uint32_t aligned_offset = CompiledMethod::AlignCode(offset, kArm64); if (kIsDebugBuild) { CHECK(IsAligned<kAdrpThunkSize>(current_method_thunks_.size())); size_t num_thunks = current_method_thunks_.size() / kAdrpThunkSize; CHECK_LE(num_thunks, processed_adrp_thunks_); for (size_t i = 0u; i != num_thunks; ++i) { const auto& entry = adrp_thunk_locations_[processed_adrp_thunks_ - num_thunks + i]; CHECK_EQ(entry.second, aligned_offset + i * kAdrpThunkSize); } } uint32_t aligned_code_delta = aligned_offset - offset; if (aligned_code_delta != 0u && !WriteCodeAlignment(out, aligned_code_delta)) { return 0u; } if (!WriteMiscThunk(out, ArrayRef<const uint8_t>(current_method_thunks_))) { return 0u; } offset = aligned_offset + current_method_thunks_.size(); current_method_thunks_.clear(); } } return ArmBaseRelativePatcher::WriteThunks(out, offset); } void Arm64RelativePatcher::PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset, uint32_t target_offset) { DCHECK_LE(literal_offset + 4u, code->size()); DCHECK_EQ(literal_offset & 3u, 0u); DCHECK_EQ(patch_offset & 3u, 0u); DCHECK_EQ(target_offset & 3u, 0u); uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u); DCHECK_EQ(displacement & 3u, 0u); DCHECK((displacement >> 27) == 0u || (displacement >> 27) == 31u); // 28-bit signed. uint32_t insn = (displacement & 0x0fffffffu) >> 2; insn |= 0x94000000; // BL // Check that we're just overwriting an existing BL. DCHECK_EQ(GetInsn(code, literal_offset) & 0xfc000000u, 0x94000000u); // Write the new BL. SetInsn(code, literal_offset, insn); } void Arm64RelativePatcher::PatchDexCacheReference(std::vector<uint8_t>* code, const LinkerPatch& patch, uint32_t patch_offset, uint32_t target_offset) { DCHECK_EQ(patch_offset & 3u, 0u); DCHECK_EQ(target_offset & 3u, 0u); uint32_t literal_offset = patch.LiteralOffset(); uint32_t insn = GetInsn(code, literal_offset); uint32_t pc_insn_offset = patch.PcInsnOffset(); uint32_t disp = target_offset - ((patch_offset - literal_offset + pc_insn_offset) & ~0xfffu); bool wide = (insn & 0x40000000) != 0; uint32_t shift = wide ? 3u : 2u; if (literal_offset == pc_insn_offset) { // Check it's an ADRP with imm == 0 (unset). DCHECK_EQ((insn & 0xffffffe0u), 0x90000000u) << literal_offset << ", " << pc_insn_offset << ", 0x" << std::hex << insn; if (fix_cortex_a53_843419_ && processed_adrp_thunks_ != adrp_thunk_locations_.size() && adrp_thunk_locations_[processed_adrp_thunks_].first == patch_offset) { DCHECK(NeedsErratum843419Thunk(ArrayRef<const uint8_t>(*code), literal_offset, patch_offset)); uint32_t thunk_offset = adrp_thunk_locations_[processed_adrp_thunks_].second; uint32_t adrp_disp = target_offset - (thunk_offset & ~0xfffu); uint32_t adrp = PatchAdrp(insn, adrp_disp); uint32_t out_disp = thunk_offset - patch_offset; DCHECK_EQ(out_disp & 3u, 0u); DCHECK((out_disp >> 27) == 0u || (out_disp >> 27) == 31u); // 28-bit signed. insn = (out_disp & 0x0fffffffu) >> shift; insn |= 0x14000000; // B <thunk> uint32_t back_disp = -out_disp; DCHECK_EQ(back_disp & 3u, 0u); DCHECK((back_disp >> 27) == 0u || (back_disp >> 27) == 31u); // 28-bit signed. uint32_t b_back = (back_disp & 0x0fffffffu) >> 2; b_back |= 0x14000000; // B <back> size_t thunks_code_offset = current_method_thunks_.size(); current_method_thunks_.resize(thunks_code_offset + kAdrpThunkSize); SetInsn(&current_method_thunks_, thunks_code_offset, adrp); SetInsn(&current_method_thunks_, thunks_code_offset + 4u, b_back); static_assert(kAdrpThunkSize == 2 * 4u, "thunk has 2 instructions"); processed_adrp_thunks_ += 1u; } else { insn = PatchAdrp(insn, disp); } // Write the new ADRP (or B to the erratum 843419 thunk). SetInsn(code, literal_offset, insn); } else { // LDR 32-bit or 64-bit with imm12 == 0 (unset). DCHECK_EQ(insn & 0xbffffc00, 0xb9400000) << insn; if (kIsDebugBuild) { uint32_t adrp = GetInsn(code, pc_insn_offset); if ((adrp & 0x9f000000u) != 0x90000000u) { CHECK(fix_cortex_a53_843419_); CHECK_EQ(adrp & 0xfc000000u, 0x14000000u); // B <thunk> CHECK(IsAligned<kAdrpThunkSize>(current_method_thunks_.size())); size_t num_thunks = current_method_thunks_.size() / kAdrpThunkSize; CHECK_LE(num_thunks, processed_adrp_thunks_); uint32_t b_offset = patch_offset - literal_offset + pc_insn_offset; for (size_t i = processed_adrp_thunks_ - num_thunks; ; ++i) { CHECK_NE(i, processed_adrp_thunks_); if (adrp_thunk_locations_[i].first == b_offset) { size_t idx = num_thunks - (processed_adrp_thunks_ - i); adrp = GetInsn(&current_method_thunks_, idx * kAdrpThunkSize); break; } } } CHECK_EQ(adrp & 0x9f00001fu, // Check that pc_insn_offset points 0x90000000 | ((insn >> 5) & 0x1fu)); // to ADRP with matching register. } uint32_t imm12 = (disp & 0xfffu) >> shift; insn = (insn & ~(0xfffu << 10)) | (imm12 << 10); SetInsn(code, literal_offset, insn); } } std::vector<uint8_t> Arm64RelativePatcher::CompileThunkCode() { // The thunk just uses the entry point in the ArtMethod. This works even for calls // to the generic JNI and interpreter trampolines. arm64::Arm64Assembler assembler; Offset offset(ArtMethod::EntryPointFromQuickCompiledCodeOffset( kArm64PointerSize).Int32Value()); assembler.JumpTo(ManagedRegister(arm64::X0), offset, ManagedRegister(arm64::IP0)); // Ensure we emit the literal pool. assembler.EmitSlowPaths(); std::vector<uint8_t> thunk_code(assembler.CodeSize()); MemoryRegion code(thunk_code.data(), thunk_code.size()); assembler.FinalizeInstructions(code); return thunk_code; } uint32_t Arm64RelativePatcher::PatchAdrp(uint32_t adrp, uint32_t disp) { return (adrp & 0x9f00001fu) | // Clear offset bits, keep ADRP with destination reg. // Bottom 12 bits are ignored, the next 2 lowest bits are encoded in bits 29-30. ((disp & 0x00003000u) << (29 - 12)) | // The next 16 bits are encoded in bits 5-22. ((disp & 0xffffc000u) >> (12 + 2 - 5)) | // Since the target_offset is based on the beginning of the oat file and the // image space precedes the oat file, the target_offset into image space will // be negative yet passed as uint32_t. Therefore we limit the displacement // to +-2GiB (rather than the maximim +-4GiB) and determine the sign bit from // the highest bit of the displacement. This is encoded in bit 23. ((disp & 0x80000000u) >> (31 - 23)); } bool Arm64RelativePatcher::NeedsErratum843419Thunk(ArrayRef<const uint8_t> code, uint32_t literal_offset, uint32_t patch_offset) { DCHECK_EQ(patch_offset & 0x3u, 0u); if ((patch_offset & 0xff8) == 0xff8) { // ...ff8 or ...ffc uint32_t adrp = GetInsn(code, literal_offset); DCHECK_EQ(adrp & 0xff000000, 0x90000000); uint32_t next_offset = patch_offset + 4u; uint32_t next_insn = GetInsn(code, literal_offset + 4u); // Below we avoid patching sequences where the adrp is followed by a load which can easily // be proved to be aligned. // First check if the next insn is the LDR using the result of the ADRP. // LDR <Wt>, [<Xn>, #pimm], where <Xn> == ADRP destination reg. if ((next_insn & 0xffc00000) == 0xb9400000 && (((next_insn >> 5) ^ adrp) & 0x1f) == 0) { return false; } // LDR <Wt>, <label> is always aligned and thus it doesn't cause boundary crossing. if ((next_insn & 0xff000000) == 0x18000000) { return false; } // LDR <Xt>, <label> is aligned iff the pc + displacement is a multiple of 8. if ((next_insn & 0xff000000) == 0x58000000) { bool is_aligned_load = (((next_offset >> 2) ^ (next_insn >> 5)) & 1) == 0; return !is_aligned_load; } // LDR <Wt>, [SP, #<pimm>] and LDR <Xt>, [SP, #<pimm>] are always aligned loads, as SP is // guaranteed to be 128-bits aligned and <pimm> is multiple of the load size. if ((next_insn & 0xbfc003e0) == 0xb94003e0) { return false; } return true; } return false; } void Arm64RelativePatcher::SetInsn(std::vector<uint8_t>* code, uint32_t offset, uint32_t value) { DCHECK_LE(offset + 4u, code->size()); DCHECK_EQ(offset & 3u, 0u); uint8_t* addr = &(*code)[offset]; addr[0] = (value >> 0) & 0xff; addr[1] = (value >> 8) & 0xff; addr[2] = (value >> 16) & 0xff; addr[3] = (value >> 24) & 0xff; } uint32_t Arm64RelativePatcher::GetInsn(ArrayRef<const uint8_t> code, uint32_t offset) { DCHECK_LE(offset + 4u, code.size()); DCHECK_EQ(offset & 3u, 0u); const uint8_t* addr = &code[offset]; return (static_cast<uint32_t>(addr[0]) << 0) + (static_cast<uint32_t>(addr[1]) << 8) + (static_cast<uint32_t>(addr[2]) << 16)+ (static_cast<uint32_t>(addr[3]) << 24); } template <typename Alloc> uint32_t Arm64RelativePatcher::GetInsn(std::vector<uint8_t, Alloc>* code, uint32_t offset) { return GetInsn(ArrayRef<const uint8_t>(*code), offset); } } // namespace linker } // namespace art
android-art-intel/marshmallow
art-extension/compiler/linker/arm64/relative_patcher_arm64.cc
C++
apache-2.0
14,229
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package spec4j.asm.util; import java.io.PrintWriter; import spec4j.asm.AnnotationVisitor; import spec4j.asm.Attribute; import spec4j.asm.ClassVisitor; import spec4j.asm.FieldVisitor; import spec4j.asm.MethodVisitor; import spec4j.asm.Opcodes; import spec4j.asm.TypePath; /** * A {@link ClassVisitor} that prints the classes it visits with a * {@link Printer}. This class visitor can be used in the middle of a class * visitor chain to trace the class that is visited at a given point in this * chain. This may be useful for debugging purposes. * <p> * The trace printed when visiting the <tt>Hello</tt> class is the following: * <p> * <blockquote> * * <pre> * // class version 49.0 (49) // access flags 0x21 public class Hello { * * // compiled from: Hello.java * * // access flags 0x1 public &lt;init&gt; ()V ALOAD 0 INVOKESPECIAL * java/lang/Object &lt;init&gt; ()V RETURN MAXSTACK = 1 MAXLOCALS = 1 * * // access flags 0x9 public static main ([Ljava/lang/String;)V GETSTATIC * java/lang/System out Ljava/io/PrintStream; LDC &quot;hello&quot; * INVOKEVIRTUAL java/io/PrintStream println (Ljava/lang/String;)V RETURN * MAXSTACK = 2 MAXLOCALS = 1 } * </pre> * * </blockquote> where <tt>Hello</tt> is defined by: * <p> * <blockquote> * * <pre> * public class Hello { * * public static void main(String[] args) { * System.out.println(&quot;hello&quot;); * } * } * </pre> * * </blockquote> * * @author Eric Bruneton * @author Eugene Kuleshov */ public final class TraceClassVisitor extends ClassVisitor { /** * The print writer to be used to print the class. May be null. */ private final PrintWriter pw; /** * The object that actually converts visit events into text. */ public final Printer p; /** * Constructs a new {@link TraceClassVisitor}. * * @param pw * the print writer to be used to print the class. */ public TraceClassVisitor(final PrintWriter pw) { this(null, pw); } /** * Constructs a new {@link TraceClassVisitor}. * * @param cv * the {@link ClassVisitor} to which this visitor delegates * calls. May be <tt>null</tt>. * @param pw * the print writer to be used to print the class. */ public TraceClassVisitor(final ClassVisitor cv, final PrintWriter pw) { this(cv, new Textifier(), pw); } /** * Constructs a new {@link TraceClassVisitor}. * * @param cv * the {@link ClassVisitor} to which this visitor delegates * calls. May be <tt>null</tt>. * @param p * the object that actually converts visit events into text. * @param pw * the print writer to be used to print the class. May be null if * you simply want to use the result via * {@link Printer#getText()}, instead of printing it. */ public TraceClassVisitor(final ClassVisitor cv, final Printer p, final PrintWriter pw) { super(Opcodes.ASM5, cv); this.pw = pw; this.p = p; } @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { p.visit(version, access, name, signature, superName, interfaces); super.visit(version, access, name, signature, superName, interfaces); } @Override public void visitSource(final String file, final String debug) { p.visitSource(file, debug); super.visitSource(file, debug); } @Override public void visitOuterClass(final String owner, final String name, final String desc) { p.visitOuterClass(owner, name, desc); super.visitOuterClass(owner, name, desc); } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { Printer p = this.p.visitClassAnnotation(desc, visible); AnnotationVisitor av = cv == null ? null : cv.visitAnnotation(desc, visible); return new TraceAnnotationVisitor(av, p); } @Override public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { Printer p = this.p.visitClassTypeAnnotation(typeRef, typePath, desc, visible); AnnotationVisitor av = cv == null ? null : cv.visitTypeAnnotation( typeRef, typePath, desc, visible); return new TraceAnnotationVisitor(av, p); } @Override public void visitAttribute(final Attribute attr) { p.visitClassAttribute(attr); super.visitAttribute(attr); } @Override public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { p.visitInnerClass(name, outerName, innerName, access); super.visitInnerClass(name, outerName, innerName, access); } @Override public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { Printer p = this.p.visitField(access, name, desc, signature, value); FieldVisitor fv = cv == null ? null : cv.visitField(access, name, desc, signature, value); return new TraceFieldVisitor(fv, p); } @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { Printer p = this.p.visitMethod(access, name, desc, signature, exceptions); MethodVisitor mv = cv == null ? null : cv.visitMethod(access, name, desc, signature, exceptions); return new TraceMethodVisitor(mv, p); } @Override public void visitEnd() { p.visitClassEnd(); if (pw != null) { p.print(pw); pw.flush(); } super.visitEnd(); } }
ikisis/spec4j
spec4j-agent/src/main/java/spec4j/asm/util/TraceClassVisitor.java
Java
apache-2.0
7,813
// Code generated by go-swagger; DO NOT EDIT. package storage // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) // NewDiskGetParams creates a new DiskGetParams object, // with the default timeout for this client. // // Default values are not hydrated, since defaults are normally applied by the API server side. // // To enforce default values in parameter, use SetDefaults or WithDefaults. func NewDiskGetParams() *DiskGetParams { return &DiskGetParams{ timeout: cr.DefaultTimeout, } } // NewDiskGetParamsWithTimeout creates a new DiskGetParams object // with the ability to set a timeout on a request. func NewDiskGetParamsWithTimeout(timeout time.Duration) *DiskGetParams { return &DiskGetParams{ timeout: timeout, } } // NewDiskGetParamsWithContext creates a new DiskGetParams object // with the ability to set a context for a request. func NewDiskGetParamsWithContext(ctx context.Context) *DiskGetParams { return &DiskGetParams{ Context: ctx, } } // NewDiskGetParamsWithHTTPClient creates a new DiskGetParams object // with the ability to set a custom HTTPClient for a request. func NewDiskGetParamsWithHTTPClient(client *http.Client) *DiskGetParams { return &DiskGetParams{ HTTPClient: client, } } /* DiskGetParams contains all the parameters to send to the API endpoint for the disk get operation. Typically these are written to a http.Request. */ type DiskGetParams struct { /* Fields. Specify the fields to return. */ FieldsQueryParameter []string /* Name. Disk name */ NamePathParameter string timeout time.Duration Context context.Context HTTPClient *http.Client } // WithDefaults hydrates default values in the disk get params (not the query body). // // All values with no default are reset to their zero value. func (o *DiskGetParams) WithDefaults() *DiskGetParams { o.SetDefaults() return o } // SetDefaults hydrates default values in the disk get params (not the query body). // // All values with no default are reset to their zero value. func (o *DiskGetParams) SetDefaults() { // no default values defined for this parameter } // WithTimeout adds the timeout to the disk get params func (o *DiskGetParams) WithTimeout(timeout time.Duration) *DiskGetParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the disk get params func (o *DiskGetParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the disk get params func (o *DiskGetParams) WithContext(ctx context.Context) *DiskGetParams { o.SetContext(ctx) return o } // SetContext adds the context to the disk get params func (o *DiskGetParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the disk get params func (o *DiskGetParams) WithHTTPClient(client *http.Client) *DiskGetParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the disk get params func (o *DiskGetParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithFieldsQueryParameter adds the fields to the disk get params func (o *DiskGetParams) WithFieldsQueryParameter(fields []string) *DiskGetParams { o.SetFieldsQueryParameter(fields) return o } // SetFieldsQueryParameter adds the fields to the disk get params func (o *DiskGetParams) SetFieldsQueryParameter(fields []string) { o.FieldsQueryParameter = fields } // WithNamePathParameter adds the name to the disk get params func (o *DiskGetParams) WithNamePathParameter(name string) *DiskGetParams { o.SetNamePathParameter(name) return o } // SetNamePathParameter adds the name to the disk get params func (o *DiskGetParams) SetNamePathParameter(name string) { o.NamePathParameter = name } // WriteToRequest writes these params to a swagger request func (o *DiskGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.FieldsQueryParameter != nil { // binding items for fields joinedFields := o.bindParamFields(reg) // query array param fields if err := r.SetQueryParam("fields", joinedFields...); err != nil { return err } } // path param name if err := r.SetPathParam("name", o.NamePathParameter); err != nil { return err } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } // bindParamDiskGet binds the parameter fields func (o *DiskGetParams) bindParamFields(formats strfmt.Registry) []string { fieldsIR := o.FieldsQueryParameter var fieldsIC []string for _, fieldsIIR := range fieldsIR { // explode []string fieldsIIV := fieldsIIR // string as string fieldsIC = append(fieldsIC, fieldsIIV) } // items.CollectionFormat: "csv" fieldsIS := swag.JoinByFormat(fieldsIC, "csv") return fieldsIS }
NetApp/trident
storage_drivers/ontap/api/rest/client/storage/disk_get_parameters.go
GO
apache-2.0
5,120
/* * Copyright (c) 2015. Zuercher Hochschule fuer Angewandte Wissenschaften * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ //package ch.icclab.cyclops.usecases.tnova.resource; // //import ch.icclab.cyclops.load.Loader; //import ch.icclab.cyclops.model.ChargeResponse; //import ch.icclab.cyclops.usecases.tnova.model.ChargeReport; //import ch.icclab.cyclops.usecases.tnova.model.RevenueSharingList; //import ch.icclab.cyclops.util.APICallCounter; //import com.fasterxml.jackson.core.JsonProcessingException; //import com.fasterxml.jackson.databind.ObjectMapper; //import com.google.gson.Gson; //import org.apache.log4j.LogManager; //import org.apache.log4j.Logger; //import org.restlet.ext.json.JsonRepresentation; //import org.restlet.representation.Representation; //import org.restlet.resource.ClientResource; //import org.restlet.resource.Get; //import org.restlet.resource.ServerResource; // //import java.io.IOException; //import java.util.HashMap; // ///** // * @author Manu // * Created on 08.12.15. // */ //public class ChargeReportResource extends ServerResource{ // final static Logger logger = LogManager.getLogger(ChargeReportResource.class.getName()); // // // who am I? // private String endpoint = "/charge/report"; // // // used as counter // private APICallCounter counter = APICallCounter.getInstance(); // // /** // * Queries the database to get the charge data records for a given time period // * // * Pseudo Code // * 1. Get the userid , from and to details from the API query parameters // * 2. Query the database to get the cdr // * 3. Construct the response and return the json string // * // * @return Representation // */ // @Get // public String getChargeRecords(){ // // counter.increment(endpoint); // // Representation response; // ObjectMapper objectMapper = new ObjectMapper(); // String jsonStr; // Double sum = 0.0; // // // String userid = getQueryValue("userid"); // String fromDate = normalizeDateAndTime(getQueryValue("from")); // String toDate = normalizeDateAndTime(getQueryValue("to")); // // String urlParams = "/charge?userid="+userid+"&from="+fromDate+"&to="+toDate; // // ClientResource clientResource = new ClientResource(Loader.getSettings().getCyclopsSettings().getRcServiceUrl()+ urlParams); // // response = clientResource.get(); // try { // jsonStr = response.getText(); // Gson gson = new Gson(); // RevenueSharingList revenueSharingList = gson.fromJson(jsonStr, RevenueSharingList.class); // sum = revenueSharingList.getAggregation(); // } catch (IOException e) { // logger.debug("Error while mapping the Charge Report List object: "+ e.getMessage()); // } // // ChargeReport report = new ChargeReport(); // report.setUserid(userid); // report.setPrice(sum); // report.setTime(fromDate, toDate); // // // Gson gson = new Gson(); // String result = gson.toJson(report); // return result; // } // // /** // * Construct the JSON response consisting of the meter and the usage values // * // * Pseudo Code // * 1. Create the HasMap consisting of time range // * 2. Create the response POJO // * 3. Convert the POJO to JSON // * 4. Return the JSON string // * // * @param rateArr An arraylist consisting of metername and corresponding usage // * @param fromDate DateTime from usage data needs to be calculated // * @param toDate DateTime upto which the usage data needs to be calculated // * @return responseJson The response object in the JSON format // */ // public Representation constructResponse(HashMap rateArr, String userid, String fromDate, String toDate){ // // String jsonStr; // JsonRepresentation responseJson = null; // // ChargeResponse responseObj = new ChargeResponse(); // HashMap time = new HashMap(); // ObjectMapper mapper = new ObjectMapper(); // // time.put("from",fromDate); // time.put("to",toDate); // // //Build the response POJO // responseObj.setUserid(userid); // responseObj.setTime(time); // responseObj.setCharge(rateArr); // // //Convert the POJO to a JSON string // try { // jsonStr = mapper.writeValueAsString(responseObj); // responseJson = new JsonRepresentation(jsonStr); // } catch (JsonProcessingException e) { // e.printStackTrace(); // } // // return responseJson; // } // // /** // * Remove ' character and replace T with a space // * @param time // * @return // */ // private String normalizeDateAndTime(String time) { // String first = time.replace("'", ""); // return first.replace("T", " "); // } //}
icclab/cyclops-rc
src/main/java/ch/icclab/cyclops/usecases/tnova/resource/ChargeReportResource.java
Java
apache-2.0
5,500
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <aboutdialog.h> #include <robot.h> #include <QTimer> #include "scenario.h" #include "bayesmap.h" #include "himmmap.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); public slots: void dialChanged(int value); void openAboutDialog(); void upClicked(); void downClicked(); void leftClicked(); void rightClicked(); void updateData(); void startStopRobot(); signals: void moving(int distanceMM); private: void connectActions(); Ui::MainWindow *ui; AboutDialog aboutDialog; Robot *mRobot; QTimer mTimer; Scenario *environment; }; #endif // MAINWINDOW_H
Lhdsouza/Robotics101
R.Movel/AriaDemo-master/mainwindow.h
C
apache-2.0
812
=head1 NAME History =head1 Description Since mod_perl's inception in 1996, many things have changed, and it's interesting to look at mod_perl's evolution and related events during the time from then to now. Based on the mod_perl I<Changes> file and talks with mod_perl developer's, we have here reconstructed the important steps in the development of this successful Open Source project. =head1 Beginnings The first version of mod_perl was written by Gisle Aas and released on March 25, 1996. The effort was instantly recognized by Doug MacEachern and Andreas Koenig; the former had been working on Perl embedding. They picked up the torch and brought the project we all love to what it has become today, thanks to the help of countless contributors. An extract from I<Changes> (the first one): =item March 25, 1996 Initial version of mod_perl.c and perl_glue.xs by Gisle Aas <aas (at) oslonett.no> Thanks for getting this started Gisle! Andreas Koenig tells us about how things happened: "It was a time when FastCGI was still considered cool. But making FastCGI work required a patched perl, since tied file handles were still in their infancy. "PHP was also around already, and was an embarrassing witness to Perl's greatest weakness for server-side programming: that embedding Perl was a pain. Although the hooks were there for embedding Perl, they were both undocumented and buggy. "Doug MacEachern first got involved by addressing these problems. He wrote documentation for embedding Perl (the C<perlembed> manpage) and fixed a couple of bugs. Then one day, Gisle Aas posted on perl5-porters that he had built Apache with an embedded Perl interpreter as a proof-of-concept. However, Gisle lacked the time for further work. "That announcement was like a lightening bolt for at least two guys: Doug and me. While Doug shuffled the C code, I wrote the first working I<Makefile.PL>, or at least I smoothed the build process to reduce the error rate resulting from silly mistakes during installation. Doug was working on HP-UX and I was using IRIX, so Doug wrote C<ExtUtils::Embed> to generate the command line arguments for I<gcc> that tie things together for embedded applications. "Early versions of mod_perl needed to be recompiled to add a single CGI application. To get over that, I invented something without a name that mapped filenames to perl package names. When Doug received it, he called it C<Apache::Registry>, as noted in I<Changes>: =item release 0.75a1 - July 21, 1996 added Apache::Registry module contributed by Andreas Koenig <andreas.koenig (at) franz.ww.tu-berlin.de> "From that moment in July 1996, we could count on a number of interested developers on the mailing list to test the nascent mod_perl. The I<Changes> file mentions a few of them: Salvador Ortiz, Alan Beale, and John Detloff. Rob Hartill of IMDB fame joined us in July. (See L<contributors|about::contributors::people> for more information.) In August 1996, time was ripe to let a production server run mod_perl, and PAUSE (the Perl Authors Upload Server) was the first such server. We still had to use C<$r-E<gt>print>, and couldn't C<"use CGI">, but we could add and remove scripts without recompiling and we were happy. Being unable to use the popular C<CGI.pm> module turned out to be a pain for us, so I wrote a complete C<CGI.pm> clone, C<CGI::XA> and hoped that Lincoln would pick up the ball once there was a working alternative implementation. Eventually, Lincoln (with the encouragement of Mike Stok) made C<CGI.pm> compatible with mod_perl starting with C<CGI.pm> 2.32, and in March 1997, C<CGI::XA> was removed from the mod_perl distribution. This was one of the most important entries into the Changes file: =item 0.95 - 03/20/97 ****************************************** *** CGI-XA/* removed from distribution *** CGI.pm-2.32 is now mod_perl compatible, and now ships with CGI::Switch and CGI::Apache. ****************************************** Can you feel the relief it was for Doug to write that? I think this was the greatest day of the whole development. One year of very tough work got the reward it deserved. After that, mod_perl started to get attention from an increasing number of users. Doug worked like mad on fixing bugs and inventing one thing after another, just as he still does today. Things started flowing and people sent in patches, so Doug got the impression that the bazaar model was beginning to work. (From Eric Raymond's essay "The Cathedral and the Bazaar," the unofficial manifesto of the Open Source movement.) I remember one day Doug got a confidential message from a Sun employee. They had made an investigation on "where the web is heading", and they had come to the conclusion that "mod_perl will have an impact on the whole Web"." =head1 Up to 1.0 The first public release after Gisle's proof-of-concept happened on May 1, 1996: release 0.50a1 of mod_perl, with a long list of changes. In 0.50a2, an alternative implementation was provided, mod_perl_fast, which became the standard in 0.83_10. Another probably important change was the possibility of using C<print> instead of C<$r-E<gt>print>, greatly facilitating output generation: =item release 0.80 - September 06, 1996 [...] we now take advantage of Perl's new IO abstraction so STDIN and STDOUT are hooked up to the client. Thanks to Sven Verdoolaege <skimo@breughel.ufsia.ac.be> for the initial patch With 0.85 came the start of the test suite! =item 0.85 added the start of a mod_perl test suite Another interesting feature was added just before 1.0: stacked handlers! =item 0.95_02 introduced experimental "stacked handlers" mechanism, allowing more than one Perl*Handler to be defined and run during each stage of the request. Perl*Handler directives can now define any number of subroutines, e.g. PerlTransHandler OneTrans TwoTrans RedTrans BlueTrans with a new method, Apache->push_handlers can add to the stack by scripts at runtime And just after that, our beloved C<E<lt>PerlE<gt>> sections! =item 0.95_03 [...] added <Perl> config section (see httpd.conf.pl) (needs 'perl Makefile.PL PERL_SECTIONS=1') Finally, more than one year after Doug's original 0.50a1, 1.0 was released on July 28 1997: =item 1.00 - 07/28/97 It primarily began adapting to the 1.3 series of Apache. =head1 1.x development =head2 Core During 1.x development, there has generally been many bug fixes and adaptions to Apache and Perl versions, striving to remain compatible. Some parts stand out as pretty important. In v1.12, the important APACI-support was added thanks to Ralf S. Engelschall: =item 1.12 - June 14, 1998 added new (but still optional!) Apache 1.3 support via the new Apache Autoconf-style Interface (APACI): The option USE_APACI=1 triggers a new build-environment (from local apaci/) for the APACHE_SRC/src/modules/perl/ which provides a clean way (i.e. without patching anything inside APACHE_SRC, not even the Configuration file) of configuring mod_perl via a APACHE_SRC/src/modules/perl/mod_perl.config file. The complete configuration is enabled by just using the APACI command "configure --activate-module=src/modules/perl/libperl.a" [Ralf S. Engelschall <rse@engelschall.com>] And with new versions of Perl come new fixes to mod_perl of course. =item 1.22 - March 22, 2000 compile fixes for 5.6 + -Duse5005threads [Lincoln Stein <lstein@cshl.org>] But the most important happenings weren't the bug fixes in the mod_perl core, but all that happened around it. The L<usage statistics|outstanding::stats::netcraft> show an incredible boom in mod_perl deployment, which has been accompanied by the release of very interesting applications and frameworks for mod_perl. =head2 Related events Maybe even more interesting are the things happening around mod_perl, mainly concerning Perl and Apache. The reason is that this impacts as much on mod_perl users as the changes to mod_perl itself; for example, a bug fix in Perl will help a lot to someone writing Perl handlers, and a security fix in Apache is of immense benefit to I<anyone> running an Apache server. I<Writing Apache Modules with Perl and C> (http://www.modperl.com/), by Lincoln Stein and Doug MacEachern, for a long time considered the best resource for mod_perl programmers, was published in March 1999 by O'Reilly & Associates. While not the only book on the subject, it is still a must-have for any serious mod_perl programmer. At ApacheCon in Orlando in 1999, mod_perl officially became an Apache Software Foundation project, and Ask Bjørn Hansen, Eric Cholet and Stas Bekman were voted in as ASF members in addition to Doug MacEachern. Together they formed L<the mod_perl PMC|about::pmc>. In March 2000, Perl 5.6.0 was released, bringing many new features to Perl and mod_perl programmers the world over. In October 2000, Take23 (http://www.take23.org/) was created as an alternative site for mod_perl, because of the back-and-forth discussions about re-designing the I<perl.apache.org> site weren't going anywhere at that time. It collected news and articles about mod_perl and also related issues such as other interesting Apache modules. It wasn't maintained for several years, and somewhere in 2003 it has disappeared. Also in October 2000, Geoffrey Young got the idea to begin a mod_perl mailing list digest (see http://marc.theaimsgroup.com/?l=apache-modperl-dev&m=97051473628623&w=2 and http://marc.theaimsgroup.com/?l=apache-modperl&m=97059662005378&w=2 ), which he kept up regularly (weekly, then biweekly) up until late 2001, when James G. Smith took over and has been running it since then. The I<mod_perl Pocket Reference> (http://www.oreilly.com/catalog/modperlpr/), by Andrew Ford, was published by O'Reilly and Associates in December 2000. It summarizes the whole mod_perl API as well as configuration directives and some other tips in an easy-to-use format. In January 2002, the I<mod_perl Developer's Cookbook> (http://www.modperlcookbook.org/), authored by Geoffrey Young, Paul Lindner and Randy Kobes, was published by Sams Publishing. It presents the mod_perl API by example, teaching a programmer all the facets of mod_perl installation, programming and configuration, and is a valuable resource to everyone. META: - mailing list creations - beginnings of new site - conferences w/ mod_perl present - when Doug and Stas funded? Stas: August 2001; end 2002 =head1 The arrival of 2.0 ... =head1 Future directions for mod_perl mod_perl has clearly shown its strength as an Open Source project and application development platform. mod_perl 2.0 has been a jump forward, but with the arrival of Perl 6 we might expect another new version of mod_perl. If the developers are still interested, that is. There has been started development on mod_parrot (http://svn.perl.org/parrot-modules/mod_parrot), but Perl 6 is far from ready, so we don't really know what will be needed. The future hold great things for us. I will quote Stas Bekman's commentary in the L<contributors list|about::contributors::people/stas-bekman>: I<"He is now thinking about mod_perl 3.0's architecture, hopefully to be implemented solely with AND and OR gates, driven by the Perl 6.0 chipset for the best performance. Don't be surprised when you get offered a shiny Bluetooth mod_perl 3.0 PCI card when you shop for your new server machine."> Who knows? =head1 See Also =over =item * CPAST: Comprehensive Perl Arcana Society Tapestry, http://history.perl.org/ =item * About the Apache HTTP Server Project, http://httpd.apache.org/ABOUT_APACHE.html =item * The I<perlhist> manpage, containing records of all perl versions, and the I<perl*delta> manpages relating changes in the respective versions. =back =head1 Maintainers The maintainer is the person you should contact with updates, corrections and patches. =over =item * Per Einar Ellefsen E<lt>pereinar (at) oslo.online.noE<gt> =back =head1 Authors =over =item * Per Einar Ellefsen E<lt>pereinar (at) oslo.online.noE<gt> =back Only the major authors are listed above. For contributors see the Changes file. =cut
Distrotech/mod_perl
docs/src/about/history.pod
Perl
apache-2.0
12,251
package com.tvd12.ezyfox.reflect; import java.lang.reflect.Method; import java.lang.reflect.Type; public class EzyGetterMethod extends EzyByFieldMethod { public EzyGetterMethod(Method method) { this(new EzyMethod(method)); } public EzyGetterMethod(EzyMethod method) { super(method.getMethod()); } @SuppressWarnings("rawtypes") @Override public Class getType() { return getReturnType(); } @Override public Type getGenericType() { return getGenericReturnType(); } @Override public String getFieldName() { return EzyMethods.getFieldNameOfGetter(method); } }
youngmonkeys/ezyfox
ezyfox-util/src/main/java/com/tvd12/ezyfox/reflect/EzyGetterMethod.java
Java
apache-2.0
589
/* * Copyright (c) 2017, Inversoft Inc., All Rights Reserved */ package com.inversoft.passport.domain.api.user; import com.inversoft.json.JacksonConstructor; /** * @author Daniel DeGroff */ public class VerifyEmailResponse { public String verificationId; @JacksonConstructor public VerifyEmailResponse() { } public VerifyEmailResponse(String verificationId) { this.verificationId = verificationId; } }
inversoft/passport-java-client
src/main/java/com/inversoft/passport/domain/api/user/VerifyEmailResponse.java
Java
apache-2.0
427
/* * © Copyright 2015 - SourceClear Inc */ package com.sourceclear.gramtest; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.ParserRuleContext; import org.apache.commons.cli.*; /** * */ public class Main { ///////////////////////////// Class Attributes \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ////////////////////////////// Class Methods \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ public static void main(String[] args ) { // create the parser CommandLineParser parser = new DefaultParser(); // create Options object Options options = new Options(); Option help = new Option("h","help",false,"prints this message"); Option maxoption = Option.builder("num").type(Integer.class) .argName("number of tests") .hasArg() .desc("maximum number of test cases") .build(); Option depthoption = Option.builder("dep").type(Integer.class) .argName("depth of rules") .hasArg() .desc("maximum depth for recursive rules") .build(); Option maxsizeoption = Option.builder("max").type(Integer.class) .argName("max size of test") .hasArg() .desc("maximum size of each generated test") .build(); Option minsizeoption = Option.builder("min").type(Integer.class) .argName("min size of test") .hasArg() .desc("minimum size of each generated test") .build(); Option grammarfile = Option.builder("file").argName("grammar file") .hasArg() .desc("path to the grammar file (in BNF notation)") .build(); Option testsfolder = Option.builder("tests").argName("test folder") .hasArg() .desc("path to the folder to store generated tests") .build(); Option extension = Option.builder("ext").argName("extension") .hasArg() .desc("file extension for generated tests") .build(); Option usemingen = Option.builder("mingen").type(Boolean.class) .argName("minimal generator") .hasArg() .desc("use minimal sentence generation (true/false)") .build(); options.addOption(help); options.addOption(grammarfile); options.addOption(testsfolder); options.addOption(extension); options.addOption(maxoption); options.addOption(depthoption); options.addOption(usemingen); options.addOption(maxsizeoption); options.addOption(minsizeoption); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if(line.hasOption("help") || line.getOptions().length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gramtest [options]", options); } else if(line.hasOption("file")) { String filename = line.getOptionValue("file"); int num = 100; int depth = 2; int max = 4; int min = 1; String extStr = "txt"; boolean useMinGen = true; if(line.hasOption("num")) { num = Integer.valueOf(line.getOptionValue("num")); } if(line.hasOption("dep")) { depth = Integer.valueOf(line.getOptionValue("dep")); } if(line.hasOption("max")) { max = Integer.valueOf(line.getOptionValue("max")); } if(line.hasOption("min")) { min = Integer.valueOf(line.getOptionValue("min")); } if(line.hasOption("mingen")) { useMinGen = Boolean.valueOf(line.getOptionValue("mingen")); } if(line.hasOption("ext")) { extStr = String.valueOf(line.getOptionValue("ext")); } Lexer lexer; try { lexer = new bnfLexer(new ANTLRFileStream(filename)); CommonTokenStream tokens = new CommonTokenStream(lexer); bnfParser grammarparser = new bnfParser(tokens); //grammarparser.setTrace(true); ParserRuleContext tree = grammarparser.rulelist(); GeneratorVisitor extractor = new GeneratorVisitor(num,depth,min,max,useMinGen); extractor.visit(tree); List<String> generatedTests = extractor.getTests(); System.out.println("Generating tests ..."); if(line.hasOption("tests")) { String folderPath = line.getOptionValue("tests"); int i = 1; for(String s: generatedTests) { File f = new File(folderPath+"/"+i+"."+extStr); Files.createParentDirs(f); Files.write(s, f, Charset.forName("UTF-8")); i++; } System.out.println("All tests have been saved in the "+ folderPath + " folder!"); } else { for(String s : generatedTests) { System.out.println(s); } } } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Exception: grammar file cannot be read!", ex); } } else { System.out.println("Error: grammar file not specified!"); System.out.println("Please give the path to the grammar file using the \"-file\" option."); } } catch(ParseException exp) { // oops, something went wrong System.err.println( "Parsing failed. Reason: " + exp.getMessage() ); } } //////////////////////////////// Attributes \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ /////////////////////////////// Constructors \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ////////////////////////////////// Methods \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ //------------------------ Implements: //------------------------ Overrides: //---------------------------- Abstract Methods ----------------------------- //---------------------------- Utility Methods ------------------------------ //---------------------------- Property Methods ----------------------------- }
codelion/gramtest
src/main/java/com/sourceclear/gramtest/Main.java
Java
apache-2.0
6,798
/* Copyright 2019 The Tekton Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package pod import ( "context" "testing" "github.com/google/go-cmp/cmp" "github.com/tektoncd/pipeline/pkg/apis/config" "github.com/tektoncd/pipeline/test/diff" "github.com/tektoncd/pipeline/test/names" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" fakek8s "k8s.io/client-go/kubernetes/fake" logtesting "knative.dev/pkg/logging/testing" "knative.dev/pkg/system" ) const ( serviceAccountName = "my-service-account" namespace = "namespacey-mcnamespace" featureFlagRequireKnownHosts = "require-git-ssh-secret-known-hosts" ) func TestCredsInit(t *testing.T) { customHomeEnvVar := corev1.EnvVar{ Name: "HOME", Value: "/users/home/my-test-user", } for _, c := range []struct { desc string wantArgs []string wantVolumeMounts []corev1.VolumeMount objs []runtime.Object envVars []corev1.EnvVar ctx context.Context }{{ desc: "service account exists with no secrets; nothing to initialize", objs: []runtime.Object{ &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName, Namespace: namespace}}, }, wantArgs: nil, wantVolumeMounts: nil, ctx: context.Background(), }, { desc: "service account has no annotated secrets; nothing to initialize", objs: []runtime.Object{ &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName, Namespace: namespace}, Secrets: []corev1.ObjectReference{{ Name: "my-creds", }}, }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ // No matching annotations. }, }, }, }, wantArgs: nil, wantVolumeMounts: nil, ctx: context.Background(), }, { desc: "service account has annotated secret and no HOME env var passed in; initialize creds in /tekton/creds", objs: []runtime.Object{ &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName, Namespace: namespace}, Secrets: []corev1.ObjectReference{{ Name: "my-creds", }}, }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ "tekton.dev/docker-0": "https://us.gcr.io", "tekton.dev/docker-1": "https://docker.io", "tekton.dev/git-0": "github.com", "tekton.dev/git-1": "gitlab.com", }, }, Type: "kubernetes.io/basic-auth", Data: map[string][]byte{ "username": []byte("foo"), "password": []byte("BestEver"), }, }, }, envVars: []corev1.EnvVar{}, wantArgs: []string{ "-basic-docker=my-creds=https://docker.io", "-basic-docker=my-creds=https://us.gcr.io", "-basic-git=my-creds=github.com", "-basic-git=my-creds=gitlab.com", }, wantVolumeMounts: []corev1.VolumeMount{{ Name: "tekton-internal-secret-volume-my-creds-9l9zj", MountPath: "/tekton/creds-secrets/my-creds", }}, ctx: context.Background(), }, { desc: "service account with secret and HOME env var passed in", objs: []runtime.Object{ &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName, Namespace: namespace}, Secrets: []corev1.ObjectReference{{ Name: "my-creds", }}, }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ "tekton.dev/docker-0": "https://us.gcr.io", "tekton.dev/docker-1": "https://docker.io", "tekton.dev/git-0": "github.com", "tekton.dev/git-1": "gitlab.com", }, }, Type: "kubernetes.io/basic-auth", Data: map[string][]byte{ "username": []byte("foo"), "password": []byte("BestEver"), }, }, }, envVars: []corev1.EnvVar{customHomeEnvVar}, wantArgs: []string{ "-basic-docker=my-creds=https://docker.io", "-basic-docker=my-creds=https://us.gcr.io", "-basic-git=my-creds=github.com", "-basic-git=my-creds=gitlab.com", }, wantVolumeMounts: []corev1.VolumeMount{{ Name: "tekton-internal-secret-volume-my-creds-9l9zj", MountPath: "/tekton/creds-secrets/my-creds", }}, ctx: context.Background(), }, { desc: "disabling legacy credential helper (creds-init) via feature-flag results in no args or volumes", objs: []runtime.Object{ &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName, Namespace: namespace}, Secrets: []corev1.ObjectReference{{ Name: "my-creds", }}, }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ "tekton.dev/docker-0": "https://us.gcr.io", "tekton.dev/docker-1": "https://docker.io", "tekton.dev/git-0": "github.com", "tekton.dev/git-1": "gitlab.com", }, }, Type: "kubernetes.io/basic-auth", Data: map[string][]byte{ "username": []byte("foo"), "password": []byte("BestEver"), }, }, }, envVars: []corev1.EnvVar{customHomeEnvVar}, wantArgs: nil, wantVolumeMounts: nil, ctx: config.ToContext(context.Background(), &config.Config{ FeatureFlags: &config.FeatureFlags{ DisableCredsInit: true, }, }), }, { desc: "secret name contains characters that are not allowed in volume mount context", objs: []runtime.Object{ &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName, Namespace: namespace}, Secrets: []corev1.ObjectReference{{ Name: "foo.bar.com", }}, }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "foo.bar.com", Namespace: namespace, Annotations: map[string]string{"tekton.dev/docker-0": "https://docker.io"}, }, Type: "kubernetes.io/basic-auth", Data: map[string][]byte{ "username": []byte("foo"), "password": []byte("bar"), }, }, }, envVars: []corev1.EnvVar{}, wantArgs: []string{"-basic-docker=foo.bar.com=https://docker.io"}, wantVolumeMounts: []corev1.VolumeMount{{ Name: "tekton-internal-secret-volume-foo-bar-com-9l9zj", MountPath: "/tekton/creds-secrets/foo.bar.com", }}, ctx: context.Background(), }, { desc: "service account has empty-named secrets", objs: []runtime.Object{ &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{Name: serviceAccountName, Namespace: namespace}, Secrets: []corev1.ObjectReference{{ Name: "my-creds", }, {}}, }, &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ "tekton.dev/git-0": "github.com", }, }, Type: "kubernetes.io/basic-auth", Data: map[string][]byte{ "username": []byte("foo"), "password": []byte("BestEver"), }, }, }, envVars: []corev1.EnvVar{}, wantArgs: []string{ "-basic-git=my-creds=github.com", }, wantVolumeMounts: []corev1.VolumeMount{{ Name: "tekton-internal-secret-volume-my-creds-9l9zj", MountPath: "/tekton/creds-secrets/my-creds", }}, ctx: context.Background(), }} { t.Run(c.desc, func(t *testing.T) { names.TestingSeed() kubeclient := fakek8s.NewSimpleClientset(c.objs...) args, volumes, volumeMounts, err := credsInit(c.ctx, serviceAccountName, namespace, kubeclient) if err != nil { t.Fatalf("credsInit: %v", err) } if len(args) == 0 && len(volumes) != 0 { t.Fatalf("credsInit returned secret volumes but no arguments") } if d := cmp.Diff(c.wantArgs, args); d != "" { t.Fatalf("Diff %s", diff.PrintWantGot(d)) } if d := cmp.Diff(c.wantVolumeMounts, volumeMounts); d != "" { t.Fatalf("Diff %s", diff.PrintWantGot(d)) } }) } } func TestCheckGitSSHSecret(t *testing.T) { for _, tc := range []struct { desc string configMap *corev1.ConfigMap secret *corev1.Secret wantErrorMsg string }{{ desc: "require known_hosts but secret does not include known_hosts", configMap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{Name: config.GetFeatureFlagsConfigName(), Namespace: system.Namespace()}, Data: map[string]string{ featureFlagRequireKnownHosts: "true", }, }, secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ "tekton.dev/git-0": "github.com", }, }, Type: "kubernetes.io/ssh-auth", Data: map[string][]byte{ "ssh-privatekey": []byte("Hello World!"), }, }, wantErrorMsg: "TaskRun validation failed. Git SSH Secret must have \"known_hosts\" included " + "when feature flag \"require-git-ssh-secret-known-hosts\" is set to true", }, { desc: "require known_hosts and secret includes known_hosts", configMap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{Name: config.GetFeatureFlagsConfigName(), Namespace: system.Namespace()}, Data: map[string]string{ featureFlagRequireKnownHosts: "true", }, }, secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ "tekton.dev/git-0": "github.com", }, }, Type: "kubernetes.io/ssh-auth", Data: map[string][]byte{ "ssh-privatekey": []byte("Hello World!"), "known_hosts": []byte("Hello World!"), }, }, }, { desc: "not require known_hosts", configMap: &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{Name: config.GetFeatureFlagsConfigName(), Namespace: system.Namespace()}, Data: map[string]string{ featureFlagRequireKnownHosts: "false", }, }, secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "my-creds", Namespace: namespace, Annotations: map[string]string{ "tekton.dev/git-0": "github.com", }, }, Type: "kubernetes.io/ssh-auth", Data: map[string][]byte{ "ssh-privatekey": []byte("Hello World!"), }, }, }} { t.Run(tc.desc, func(t *testing.T) { store := config.NewStore(logtesting.TestLogger(t)) store.OnConfigChanged(tc.configMap) err := checkGitSSHSecret(store.ToContext(context.Background()), tc.secret) if wantError := tc.wantErrorMsg != ""; wantError { if err == nil { t.Errorf("expected error %q, got nil", tc.wantErrorMsg) } else if diff := cmp.Diff(tc.wantErrorMsg, err.Error()); diff != "" { t.Errorf("unexpected (-want, +got) = %v", diff) } } else if err != nil { t.Errorf("unexpected error: %v", err) } }) } }
tektoncd/pipeline
pkg/pod/creds_init_test.go
GO
apache-2.0
11,261
package com.zeef.client; /* * #%L * ZEEF API Client * ---------------------------------------- * Copyright (C) 2015 ZEEF * ---------------------------------------- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ResponseType<T> { private final Type type; public ResponseType() { type = deriveType(); } private Type deriveType() { Type type = getClass().getGenericSuperclass(); Map<TypeVariable<?>, Type> typeMapping = new HashMap<>(); while (!(type instanceof ParameterizedType) || !ResponseType.class.equals(((ParameterizedType) type).getRawType())) { if (type instanceof ParameterizedType) { Class<?> rawType = (Class<?>) ((ParameterizedType) type).getRawType(); Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments(); TypeVariable<?>[] typeParameters = rawType.getTypeParameters(); for (int i = 0; i < typeParameters.length; i++) { if (typeArguments[i] instanceof TypeVariable) { typeMapping.put(typeParameters[i], typeMapping.get(typeArguments[i])); } else { typeMapping.put(typeParameters[i], typeArguments[i]); } } type = ((Class<?>) ((ParameterizedType) type).getRawType()).getGenericSuperclass(); } else { type = ((Class<?>) type).getGenericSuperclass(); } } Type typeArgument = ((ParameterizedType) type).getActualTypeArguments()[0]; if (typeArgument instanceof TypeVariable) { typeArgument = typeMapping.get(typeArgument); } Objects.requireNonNull(typeArgument); return typeArgument; } public ResponseType(Type type) { this.type = type; } public Type getType() { return type; } }
ZEEFcom/zeef-api-client
src/main/java/com/zeef/client/ResponseType.java
Java
apache-2.0
2,362
/* * Copyright 2019, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.iot.registry.infinispan.device.impl; import static io.enmasse.iot.infinispan.device.DeviceKey.deviceKey; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import static java.net.HttpURLConnection.HTTP_OK; import org.eclipse.hono.util.RegistrationConstants; import org.eclipse.hono.util.RegistrationResult; import org.infinispan.client.hotrod.RemoteCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import io.enmasse.iot.infinispan.cache.DeviceManagementCacheProvider; import io.enmasse.iot.infinispan.device.DeviceInformation; import io.enmasse.iot.registry.device.AbstractRegistrationService; import io.enmasse.iot.registry.device.DeviceKey; import io.enmasse.iot.utils.MoreFutures; import io.opentracing.Span; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; @Component public class RegistrationServiceImpl extends AbstractRegistrationService { private static final Logger log = LoggerFactory.getLogger(RegistrationServiceImpl.class); // Management cache // <(TenantId+DeviceId), (Device information + version + credentials)> private final RemoteCache<io.enmasse.iot.infinispan.device.DeviceKey, DeviceInformation> managementCache; public RegistrationServiceImpl(final DeviceManagementCacheProvider provider) { this.managementCache = provider.getOrCreateDeviceManagementCache(); } @Override protected Future<RegistrationResult> processGetDevice(final DeviceKey key, final Span span) { var f = this.managementCache .getWithMetadataAsync(deviceKey(key)) .thenApply(result -> { if (result == null) { return RegistrationResult.from(HTTP_NOT_FOUND); } log.debug("Found device: {}", result); return RegistrationResult.from(HTTP_OK, convertTo(result.getValue().getRegistrationInformationAsJson())); }); return MoreFutures.map(f); } private static JsonObject convertTo(final JsonObject deviceInfo) { return new JsonObject() .put(RegistrationConstants.FIELD_DATA, deviceInfo); } }
jenmalloy/enmasse
iot/iot-device-registry-infinispan/src/main/java/io/enmasse/iot/registry/infinispan/device/impl/RegistrationServiceImpl.java
Java
apache-2.0
2,388
package com.schoolbus.client.api; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.jar.Manifest; import javax.inject.Inject; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import io.fabric8.utils.Manifests; import org.apache.cxf.feature.LoggingFeature; import org.apache.cxf.jaxrs.swagger.SwaggerFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @javax.annotation.Generated(value = "class com.quartech.codegen.FuseGenerator", date = "2016-12-12T18:43:27.997-08:00") @ApplicationPath("/api/region") public class RegionsApiApplication extends Application{ @Inject private RegionsApi _RegionsApi; private static final Logger LOG = LoggerFactory.getLogger(RegionsApiApplication.class); private static SwaggerFeature swaggerFeature; @Override public Set<Object> getSingletons() { if (swaggerFeature == null) { swaggerFeature = new SwaggerFeature(); try { Manifest manifest = Manifests.getManifestFromCurrentJar(getClass()); Map<Manifests.Attribute,String> projectInfo = Manifests.getManifestEntryMap(manifest, Manifests.PROJECT_ATTRIBUTES.class); swaggerFeature.setTitle( projectInfo.get(Manifests.PROJECT_ATTRIBUTES.Title)); swaggerFeature.setDescription(projectInfo.get(Manifests.PROJECT_ATTRIBUTES.Description)); swaggerFeature.setLicense( projectInfo.get(Manifests.PROJECT_ATTRIBUTES.License)); swaggerFeature.setLicenseUrl( projectInfo.get(Manifests.PROJECT_ATTRIBUTES.LicenseUrl)); swaggerFeature.setVersion( projectInfo.get(Manifests.PROJECT_ATTRIBUTES.Version)); swaggerFeature.setContact( projectInfo.get(Manifests.PROJECT_ATTRIBUTES.Contact)); } catch (IOException e) { LOG.info("Could not read the project attributes from the Manifest due to " + e.getMessage()); } } return new HashSet<Object>( Arrays.asList( _RegionsApi, swaggerFeature, new LoggingFeature() ) ); } }
GeorgeWalker/schoolbus
API-Proxy/src/main/java/com/schoolbus/client/api/RegionsApiApplication.java
Java
apache-2.0
2,094
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.example.android.sunshine.data.SunshinePreferences; import com.example.android.sunshine.utilities.NetworkUtils; import com.example.android.sunshine.utilities.OpenWeatherJsonUtils; import java.net.URL; public class MainActivity extends AppCompatActivity { // Within forecast_list_item.xml ////////////////////////////////////////////////////////////// // TODO (5) Add a layout for an item in the list called forecast_list_item.xml --> Completed // TODO (6) Make the root of the layout a vertical LinearLayout --> Completed // TODO (7) Set the width of the LinearLayout to match_parent and the height to wrap_content --> Completed // TODO (8) Add a TextView with an id @+id/tv_weather_data --> Completed // TODO (9) Set the text size to 22sp --> Completed // TODO (10) Make the width and height wrap_content --> Completed // TODO (11) Give the TextView 16dp of padding --> Completed // TODO (12) Add a View to the layout with a width of match_parent and a height of 1dp --> Completed // TODO (13) Set the background color to #dadada --> Completed // TODO (14) Set the left and right margins to 8dp --> Completed // Within forecast_list_item.xml ////////////////////////////////////////////////////////////// // Within ForecastAdapter.java ///////////////////////////////////////////////////////////////// // TODO (15) Add a class file called ForecastAdapter --> Completed // TODO (22) Extend RecyclerView.Adapter<ForecastAdapter.ForecastAdapterViewHolder> --> Completed // TODO (23) Create a private string array called mWeatherData --> Completed // TODO (47) Create the default constructor (we will pass in parameters in a later lesson) --> Completed // TODO (16) Create a class within ForecastAdapter called ForecastAdapterViewHolder --> Completed // TODO (17) Extend RecyclerView.ViewHolder --> Completed // Within ForecastAdapterViewHolder /////////////////////////////////////////////////////////// // TODO (18) Create a public final TextView variable called mWeatherTextView --> Completed // TODO (19) Create a constructor for this class that accepts a View as a parameter --> Completed // TODO (20) Call super(view) within the constructor for ForecastAdapterViewHolder --> Completed // TODO (21) Using view.findViewById, get a reference to this layout's TextView and save it to mWeatherTextView --> Completed // Within ForecastAdapterViewHolder /////////////////////////////////////////////////////////// // TODO (24) Override onCreateViewHolder --> Completed // TODO (25) Within onCreateViewHolder, inflate the list item xml into a view --> Completed // TODO (26) Within onCreateViewHolder, return a new ForecastAdapterViewHolder with the above view passed in as a parameter --> Completed // TODO (27) Override onBindViewHolder --> Completed // TODO (28) Set the text of the TextView to the weather for this list item's position --> Completed // TODO (29) Override getItemCount --> Completed // TODO (30) Return 0 if mWeatherData is null, or the size of mWeatherData if it is not null --> Completed // TODO (31) Create a setWeatherData method that saves the weatherData to mWeatherData --> Completed // TODO (32) After you save mWeatherData, call notifyDataSetChanged --> Completed // Within ForecastAdapter.java ///////////////////////////////////////////////////////////////// // TODO (33) Delete mWeatherTextView --> Completed // TODO (34) Add a private RecyclerView variable called mRecyclerView --> Completed private RecyclerView mRecyclerView; // TODO (35) Add a private ForecastAdapter variable called mForecastAdapter --> Completed private ForecastAdapter mForecastAdapter; private TextView mErrorMessageDisplay; private ProgressBar mLoadingIndicator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forecast); // TODO (36) Delete the line where you get a reference to mWeatherTextView --> Completed /* * Using findViewById, we get a reference to our TextView from xml. This allows us to * do things like set the text of the TextView. */ // TODO (37) Use findViewById to get a reference to the RecyclerView--> Completed mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_forecast); mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display); // COMPLETED (38) Create layoutManager, a LinearLayoutManager with VERTICAL orientation and shouldReverseLayout == false LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); // TODO (39) Set the layoutManager on mRecyclerView --> Completed mRecyclerView.setLayoutManager(layoutManager); // TODO (40) Use setHasFixedSize(true) on mRecyclerView to designate that all items in the list will have the same size --> Completed mRecyclerView.setHasFixedSize(true); // TODO (41) set mForecastAdapter equal to a new ForecastAdapter --> Completed mForecastAdapter = new ForecastAdapter(); // TODO (42) Use mRecyclerView.setAdapter and pass in mForecastAdapter --> Completed mRecyclerView.setAdapter(mForecastAdapter); /* * The ProgressBar that will indicate to the user that we are loading data. It will be * hidden when no data is loading. * * Please note: This so called "ProgressBar" isn't a bar by default. It is more of a * circle. We didn't make the rules (or the names of Views), we just follow them. */ mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator); /* Once all of our views are setup, we can load the weather data. */ loadWeatherData(); } /** * This method will get the user's preferred location for weather, and then tell some * background method to get the weather data in the background. */ private void loadWeatherData() { showWeatherDataView(); String location = SunshinePreferences.getPreferredWeatherLocation(this); new FetchWeatherTask().execute(location); } /** * This method will make the View for the weather data visible and * hide the error message. * <p> * Since it is okay to redundantly set the visibility of a View, we don't * need to check whether each view is currently visible or invisible. */ private void showWeatherDataView() { /* First, make sure the error is invisible */ mErrorMessageDisplay.setVisibility(View.INVISIBLE); // TODO (43) Show mRecyclerView, not mWeatherTextView --> Completed /* Then, make sure the weather data is visible */ mRecyclerView.setVisibility(View.VISIBLE); } /** * This method will make the error message visible and hide the weather * View. * <p> * Since it is okay to redundantly set the visibility of a View, we don't * need to check whether each view is currently visible or invisible. */ private void showErrorMessage() { // TODO (44) Hide mRecyclerView, not mWeatherTextView --> Completed /* First, hide the currently visible data */ mRecyclerView.setVisibility(View.INVISIBLE); /* Then, show the error */ mErrorMessageDisplay.setVisibility(View.VISIBLE); } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { @Override protected void onPreExecute() { super.onPreExecute(); mLoadingIndicator.setVisibility(View.VISIBLE); } @Override protected String[] doInBackground(String... params) { /* If there's no zip code, there's nothing to look up. */ if (params.length == 0) { return null; } String location = params[0]; URL weatherRequestUrl = NetworkUtils.buildUrl(location); try { String jsonWeatherResponse = NetworkUtils .getResponseFromHttpUrl(weatherRequestUrl); String[] simpleJsonWeatherData = OpenWeatherJsonUtils .getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse); return simpleJsonWeatherData; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String[] weatherData) { mLoadingIndicator.setVisibility(View.INVISIBLE); if (weatherData != null) { showWeatherDataView(); // TODO (45) Instead of iterating through every string, use mForecastAdapter.setWeatherData and pass in the weather data --> Completed /* * Iterate through the array and append the Strings to the TextView. The reason why we add * the "\n\n\n" after the String is to give visual separation between each String in the * TextView. Later, we'll learn about a better way to display lists of data. */ mForecastAdapter.setWeatherData(weatherData); } else { showErrorMessage(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */ MenuInflater inflater = getMenuInflater(); /* Use the inflater's inflate method to inflate our menu layout to this menu */ inflater.inflate(R.menu.forecast, menu); /* Return true so that the menu is displayed in the Toolbar */ return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_refresh) { // TODO (46) Instead of setting the text to "", set the adapter to null before refreshing mForecastAdapter.setWeatherData(null); loadWeatherData(); return true; } return super.onOptionsItemSelected(item); } }
juhi16792/CS5540-Android-Development
S03.01-Exercise-RecyclerView/app/src/main/java/com/example/android/sunshine/MainActivity.java
Java
apache-2.0
11,432
// // NBSendStatusParam.h // weibo // // Created by yoga on 15/8/31. // Copyright (c) 2015年 ioslearning. All rights reserved. // #import "NBBaseParam.h" @interface NBSendStatusParam : NBBaseParam /** true string 要发布的微博文本内容,必须做URLencode,内容不超过140个汉字。*/ @property (nonatomic, copy) NSString *status; @end
YogaChen/weibo
weibo/weibo/Classes/Main(主要)/Model/SendStatus/NBSendStatusParam.h
C
apache-2.0
360
package com.gymnast.view.personal.activity; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.R; import com.gymnast.data.net.API; import com.gymnast.utils.DialogUtil; import com.gymnast.utils.GetUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.StorePhotosUtil; import com.gymnast.utils.UploadUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.citypacker.CityPackerActivity; import com.gymnast.view.wheeladapter.NumericWheelAdapter; import com.gymnast.view.widget.OnWheelScrollListener; import com.gymnast.view.widget.WheelView; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.net.URI; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * Created by yf928 on 2016/7/25. */ public class PersonalEditDataActivity extends ImmersiveActivity implements View.OnClickListener{ private ImageView ivEditMSGBack; private RelativeLayout rlEditDataName,rlEditSex,rlEditPhoto,rlEditBirthday,rlEditSignature,rlEditAddress; private TextView tvEditNickname,tvEditSex,tvEditSignature,tvEditBirthday,tvEditAddress,camera,gallery,cancel; private String token,id,fileName; private AlertDialog.Builder builder; private SharedPreferences share; private WheelView year,month,day; private final int PIC_FROM_CAMERA = 1; PopupWindow menuWindow; private Dialog cameradialog; private com.makeramen.roundedimageview.RoundedImageView rivEditPhoto; SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");; private String return_birthdays, picAddress=null; private Bitmap bitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_edit_data); share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token",""); id = share.getString("UserId",""); setView(); setData(); } private void setData(){ new Thread(new Runnable() { private String name,address,signature,birthday,return_avatar,sex; private long timebirthday; private int Sex; @Override public void run() { String uri = API.BASE_URL + "/v1/account/center_info"; HashMap<String, String> params = new HashMap<>(); params.put("token", token); params.put("account_id", id); String result = GetUtil.sendGetMessage(uri, params); if (TextUtils.isEmpty(token)) { } else { try { JSONObject obj = new JSONObject(result); JSONObject data = obj.getJSONObject("data"); name = data.getString("nickname"); if(data.getString("sex")==null){ sex="请填写性别"; }else { Sex=data.getInt("sex"); } if (data.getString("avatar").equals("")){ return_avatar="group1/M00/00/00/052YyFfXxLKARvQWAAAbNiA-OGw444.png"; }else { return_avatar=data.getString("avatar"); } if(!data.getString("address").equals("")){ address=data.getString("address"); }else { address="请填写地址"; } if(data.getLong("birthday")!=0){ timebirthday=data.getLong("birthday"); return_birthdays= simpleDateFormat.format(timebirthday); birthday= return_birthdays.substring(0, 10); }else { birthday="请填写生日"; } if(!data.getString("signature").equals("")){ signature=data.getString("signature"); }else { signature="来个签名吧~"; } final Bitmap bitmap= PicUtil.getImageBitmap(API.IMAGE_URL + return_avatar); runOnUiThread(new Runnable() { @Override public void run() { tvEditNickname.setText(name); if (Sex==0){ tvEditSex.setText("女"); }else if(Sex==1){ tvEditSex.setText("男"); }else { tvEditSex.setText(sex); } tvEditSignature.setText(signature); tvEditAddress.setText(address); tvEditBirthday.setText(birthday); rivEditPhoto.setImageBitmap(bitmap); } }); } catch (Exception e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PersonalEditDataActivity.this,"服务器异常",Toast.LENGTH_SHORT).show(); } }); } } } }).start(); } private void setView() { ivEditMSGBack= (ImageView)findViewById(R.id.ivEditMSGBack); rlEditDataName= (RelativeLayout)findViewById(R.id.rlEditDataName); rlEditSex= (RelativeLayout)findViewById(R.id.rlEditSex); rlEditAddress= (RelativeLayout)findViewById(R.id.rlEditAddress); rlEditSignature= (RelativeLayout)findViewById(R.id.rlEditSignature); rlEditBirthday= (RelativeLayout)findViewById(R.id.rlEditBirthday); rlEditPhoto= (RelativeLayout)findViewById(R.id.rlEditPhoto); tvEditNickname= (TextView)findViewById(R.id.tvEditNickname); tvEditSex= (TextView)findViewById(R.id.tvEditSex); tvEditSignature= (TextView)findViewById(R.id.tvEditSignature); tvEditAddress= (TextView)findViewById(R.id.tvEditAddress); tvEditBirthday= (TextView)findViewById(R.id.tvEditBirthday); rivEditPhoto= (com.makeramen.roundedimageview.RoundedImageView)findViewById(R.id.rivEditPhoto); ivEditMSGBack.setOnClickListener(this); rlEditSex.setOnClickListener(this); rlEditDataName.setOnClickListener(this); rlEditSignature.setOnClickListener(this); rlEditAddress.setOnClickListener(this); rlEditBirthday.setOnClickListener(this); rlEditPhoto.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); setData(); } /** * 初始化popupWindow * @param view */ private void showPopWindow(View view) { menuWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); menuWindow.setFocusable(true); menuWindow.setBackgroundDrawable(new BitmapDrawable()); menuWindow.showAtLocation(view, Gravity.CENTER, 0, 0); menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { menuWindow=null; } }); } /** * 活动结束的监听 */ OnWheelScrollListener scrollListener = new OnWheelScrollListener() { @Override public void onScrollingStarted(WheelView wheel) { } @Override public void onScrollingFinished(WheelView wheel) { int n_year = 2015;// int n_month = month.getCurrentItem() + 1;// initDay(n_year,n_month); } }; /** * @param year * @param month * @return */ private int getDay(int year, int month) { int day = 30; boolean flag = false; switch (year % 4) { case 0: flag = true; break; default: flag = false; break; } switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = 31; break; case 2: day = flag ? 29 : 28; break; default: day = 30; break; } return day; } /** * 初始化年 */ private void initYear(int curYear) { NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this,1950, curYear); numericWheelAdapter.setLabel(" 年"); // numericWheelAdapter.setTextSize(15); 设置字体大小 year.setViewAdapter(numericWheelAdapter); year.setCyclic(true); } /** * 初始化月 */ private void initMonth() { NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this,1, 12, "%02d"); numericWheelAdapter.setLabel(" 月"); // numericWheelAdapter.setTextSize(15); 设置字体大小 month.setViewAdapter(numericWheelAdapter); month.setCyclic(true); } /** * 初始化天 */ private void initDay(int arg1, int arg2) { NumericWheelAdapter numericWheelAdapter=new NumericWheelAdapter(this,1, getDay(arg1, arg2), "%02d"); numericWheelAdapter.setLabel(" 日"); // numericWheelAdapter.setTextSize(15); 设置字体大小 day.setViewAdapter(numericWheelAdapter); day.setCyclic(true); } /** * 显示日期 */ private void showDateDialog() { final AlertDialog dialog = new AlertDialog.Builder(PersonalEditDataActivity.this) .create(); dialog.show(); Window window = dialog.getWindow(); // 设置布局 window.setContentView(R.layout.datapick); // 设置宽高 // window.setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); // 设置弹出的动画效果 window.setWindowAnimations(R.style.log_out_dialog); dialog.setCanceledOnTouchOutside(true); Calendar c = Calendar.getInstance(); int curYear = c.get(Calendar.YEAR); int curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1 int curDate = c.get(Calendar.DATE); year = (WheelView) window.findViewById(R.id.year); initYear(curYear); month = (WheelView) window.findViewById(R.id.month); initMonth(); day = (WheelView) window.findViewById(R.id.day); initDay(curYear,curMonth); year.setCurrentItem(curYear - 1950); month.setCurrentItem(curMonth - 1); day.setCurrentItem(curDate - 1); year.setVisibleItems(7); month.setVisibleItems(7); day.setVisibleItems(7); // 设置监听 Button ok = (Button) window.findViewById(R.id.set); Button cancel = (Button) window.findViewById(R.id.cancel); ok.setOnClickListener(new View.OnClickListener() { public String str; @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { str = (year.getCurrentItem()+1950) + "-"+ (month.getCurrentItem()+1)+"-"+(day.getCurrentItem()+1); Log.e("str",str); String uri= API.BASE_URL+"/v1/account/info/edit"; Map<String, String> params=new HashMap<>(); SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd"); Date date=simpleDateFormat.parse(str); Long birthday_time= date.getTime(); Log.e("birthday_time",birthday_time+""); params.put("token",token); params.put("account_id",id); params.put("birthday",birthday_time+""); String result= PostUtil.sendPostMessage(uri,params); JSONObject json = new JSONObject(result); if(json.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { tvEditBirthday.setText(str); } }); } } catch (Exception e) { e.printStackTrace(); } } }).start(); dialog.cancel(); } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.cancel(); } }); } private void showDialogs() { View view = getLayoutInflater().inflate(R.layout.dialog_phone, null); cameradialog = new Dialog(this,R.style.Dialog_Fullscreen); camera=(TextView)view.findViewById(R.id.camera); gallery=(TextView)view.findViewById(R.id.gallery); cancel=(TextView)view.findViewById(R.id.cancel); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cameradialog.dismiss(); } }); //从相册获取 gallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, 1000); cameradialog.dismiss(); } }); //拍照 camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fileName = getPhotopath(); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); File out = new File(fileName); Uri uri = Uri.fromFile(out); // 获取拍照后未压缩的原图片,并保存在uri路径中 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent,PIC_FROM_CAMERA); cameradialog.dismiss(); } }); cameradialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = cameradialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.main_menu_animstyle); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 wl.width = ViewGroup.LayoutParams.MATCH_PARENT; wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 cameradialog.onWindowAttributesChanged(wl); // 设置点击外围解散 cameradialog.setCanceledOnTouchOutside(true); cameradialog.show(); } /** * 路径 * @return */ private String getPhotopath() { // 照片全路径 String fileName = ""; // 文件夹路径 String pathUrl = Environment.getExternalStorageDirectory()+"/Zyx/"; //照片名 String name = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".png"; File file = new File(pathUrl); if (!file.exists()) { Log.e("TAG", "第一次创建文件夹"); file.mkdirs();// 如果文件夹不存在,则创建文件夹 } fileName=pathUrl+name; return fileName; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==PIC_FROM_CAMERA&&resultCode == Activity.RESULT_OK) { final Bitmap bitmap = PicUtil.getSmallBitmap(fileName); // 这里是先压缩质量,再调用存储方法 new StorePhotosUtil(bitmap, fileName); if (bitmap!=null) { new Thread(new Runnable() { @Override public void run() { try { String uri= API.BASE_URL+"/v1/upload"; String result=UploadUtil.uploadFile2(uri, fileName); JSONObject object= null; object = new JSONObject(result); JSONObject data=object.getJSONObject("data"); String newUrl = URI.create(data.getString("url")).getPath(); String uri2= API.BASE_URL+"/v1/account/info/edit"; HashMap<String, String> params = new HashMap<>(); params.put("token", token); params.put("account_id", id); params.put("avatar", newUrl); String result1 = PostUtil.sendPostMessage(uri2, params); runOnUiThread(new Runnable() { @Override public void run() { rivEditPhoto.setImageBitmap(bitmap); } }); } catch (JSONException e) { e.printStackTrace(); } } }).start(); } } if (requestCode == 1000 && data != null){ // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口 final ContentResolver resolver = getContentResolver(); final Uri originalUri = data.getData(); // 获得图片的uri try { Bitmap bitmap1 = MediaStore.Images.Media.getBitmap(resolver, originalUri); bitmap= PicUtil.compress(bitmap1, 720, 480); rivEditPhoto.setImageBitmap(bitmap); }catch (Exception e){ e.printStackTrace(); } Thread thread1=new Thread(){ @Override public void run() { String path=UploadUtil.getAbsoluteImagePath(PersonalEditDataActivity.this,originalUri); picAddress=UploadUtil.getNetWorkImageAddress(path, PersonalEditDataActivity.this); runOnUiThread(new Runnable() { @Override public void run() { if (picAddress!=null){ cameradialog.dismiss(); } } }); } }; thread1.setPriority(8); thread1.start(); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.ivEditMSGBack: finish(); break; case R.id.rlEditDataName: Intent a= new Intent(PersonalEditDataActivity.this,PersonalEditNickNameActivity.class); startActivity(a); break; case R.id.rlEditSignature: Intent b= new Intent(PersonalEditDataActivity.this,PersonalSignatureActivity.class); startActivity(b); break; case R.id.rlEditAddress: Intent c= new Intent(PersonalEditDataActivity.this,CityPackerActivity.class); startActivity(c); break; case R.id.rlEditBirthday: showDateDialog(); break; case R.id.rlEditPhoto: showDialogs(); setData(); break; case R.id.rlEditSex: builder = new AlertDialog.Builder(PersonalEditDataActivity.this); builder.setTitle("请选择性别"); final String[] sexList = {"女", "男"}; // 设置一个单项选择下拉框 /** * 第一个参数指定我们要显示的一组下拉单选框的数据集合 * 第二个参数代表索引,指定默认哪一个单选框被勾选上 * 第三个参数给每一个单选项绑定一个监听器 */ builder.setSingleChoiceItems(sexList, 0, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, final int which) { new Thread(new Runnable() { @Override public void run() { try { String uri= API.BASE_URL+"/v1/account/info/edit"; Map<String, String> params=new HashMap<>(); params.put("token",token); params.put("account_id",id); params.put("sex",which+""); String result= PostUtil.sendPostMessage(uri,params); Log.e("result",result); JSONObject json = new JSONObject(result); if(json.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { tvEditSex.setText(sexList[which]); Toast.makeText(PersonalEditDataActivity.this,"您的性别是:"+sexList[which],Toast.LENGTH_SHORT).show(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); dialog.dismiss(); } }); builder.show(); break; } } }
928902646/Gymnast
app/src/main/java/com/gymnast/view/personal/activity/PersonalEditDataActivity.java
Java
apache-2.0
24,598
/** * A function to be invoked after completing an asynchronous task. * * @typedef {Function} Callback */ /** * A callback whose first argument is either an `Error` or `null`. * * @typedef {Callback} Errback */
stdlib-js/stdlib
tools/docs/jsdoc/typedefs/functions.js
JavaScript
apache-2.0
212
/** * Copyright (C) 2014 Xillio (support@xillio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.xillio.xill.plugins.testing.constructs; import nl.xillio.xill.api.components.MetaExpression; import nl.xillio.xill.api.construct.Argument; import nl.xillio.xill.api.construct.Construct; import nl.xillio.xill.api.construct.ConstructContext; import nl.xillio.xill.api.construct.ConstructProcessor; import nl.xillio.xill.api.errors.RobotRuntimeException; /** * This construct checks for equality and throws an error if true. * * @author Thomas Biesaart */ public class IsTrueConstruct extends Construct { @Override public ConstructProcessor prepareProcess(ConstructContext context) { return new ConstructProcessor( this::process, new Argument("value"), new Argument("message", NULL) ); } MetaExpression process(MetaExpression value, MetaExpression message) { if (value.getBooleanValue()) { return NULL; } String containedMessage = message.isNull() ? "" : ": " + message.getStringValue(); throw new RobotRuntimeException("Assertion failed. Found [" + value.getStringValue() + "] but expected a true expression" + containedMessage); } }
XillioQA/xill-platform-3.4
xill-processor/src/main/java/nl/xillio/xill/plugins/testing/constructs/IsTrueConstruct.java
Java
apache-2.0
1,851
/** * Created by liyadan01_bj on 2016/4/26. */ function addLoadEvent(func){ var oldonload=window.onload; if(typeof window.onload != 'function'){ window.onload=func; }else{ window.onload=function(){ oldonload(); func(); } } }
KMJB/IFE
lyd/learning_01/scripts/addLoadEvent.js
JavaScript
apache-2.0
290
<md-card-header> <md-card-avatar> <md-icon>build</md-icon> </md-card-avatar> <md-card-header-text layout="row" layout-align="space-between center"> <div layout="column"> <span class="md-title">Index configuration</span> </div> <md-button class="md-fab md-mini md-hue-1" aria-label="Add new field" ng-click="saveIndexConfig()"> <md-icon>save</md-icon> </md-button> </md-card-header-text> </md-card-header> <md-divider></md-divider> <md-card-content class="config"> <md-content class="scrollable" style="max-height: 500px;"> <md-list> <md-subheader class="md-no-sticky">Commit configs</md-subheader> <md-divider></md-divider> <md-list-item> <div layout-align="space-between center" layout-fill layout="row"> <span class="md-body-1">Auto-commit: {{ index.indexConfiguration.autoCommit ? "yes" : "no" }}</span> <md-switch ng-model="index.indexConfiguration.autoCommit" aria-label="AutoCommit"> </div> </md-list-item> <md-list-item> <div layout-align="space-between center" layout-fill layout="row"> <span class="md-body-1">Commit on close: {{ index.indexConfiguration.commitOnClose ? "yes" : "no" }}</span> <md-switch ng-model="index.indexConfiguration.commitOnClose" aria-label="CommitOnClose"> </div> </md-list-item> <md-list-item> <md-slider-container ng-disabled="!index.indexConfiguration.autoCommit" layout-fill> <span class="md-body-1">Commit time (s)</span> <md-tooltip>The amount of time in seconds that FlexSearch should wait before committing changes to the disk. This is only used if no commits have happened in the set time period otherwise CommitEveryNFlushes takes care of commits</md-tooltip> <md-slider flex ng-model="index.indexConfiguration.commitTimeSeconds" min="1" max="300" aria-label="Commit Time Seconds" id="commit-time-slider"> </md-slider> <md-input-container> <input flex type="number" ng-model="index.indexConfiguration.commitTimeSeconds" aria-label="Commit Time Seconds" aria-controls="commit-time-slider"> </md-input-container> </md-slider-container> </md-list-item> <md-subheader class="md-no-sticky">Refresh configs</md-subheader> <md-divider></md-divider> <md-list-item> <div layout-align="space-between center" layout-fill layout="row"> <span class="md-body-1">Auto-refresh: {{ index.indexConfiguration.autoRefresh ? "yes" : "no" }}</span> <md-switch ng-model="index.indexConfiguration.autoRefresh" aria-label="AutoRefresh"> </div> </md-list-item> <md-list-item> <md-slider-container layout-fill ng-disabled="!index.indexConfiguration.autoRefresh"> <span class="md-body-1">Refresh time (s)</span> <md-slider flex ng-model="index.indexConfiguration.refreshTimeMilliseconds" min="1" max="10000" aria-label="Refresh Time Seconds" id="refresh-time-slider"> </md-slider> <md-input-container> <input flex type="number" ng-model="index.indexConfiguration.refreshTimeMilliseconds" aria-label="Refresh Time Seconds" aria-controls="refresh-time-slider"> </md-input-container> </md-slider-container> </md-list-item> <md-subheader class="md-no-sticky">Other configs</md-subheader> <md-divider></md-divider> <md-list-item> <div layout-align="space-between center" layout-fill layout="row"> <span class="md-body-1">Delete logs on close: {{ index.indexConfiguration.deleteLogsOnClose ? "yes" : "no" }}</span> <md-switch ng-model="index.indexConfiguration.deleteLogsOnClose" aria-label="deleteLogsOnClose"> </div> </md-list-item> <md-list-item> <div layout-align="space-between center" layout-fill layout="row"> <span class="md-body-1">Allow reads: {{ index.indexConfiguration.allowReads ? "yes" : "no" }}</span> <md-switch ng-model="index.indexConfiguration.allowReads" aria-label="allowReads"> </div> </md-list-item> <md-list-item> <div layout-align="space-between center" layout-fill layout="row"> <span class="md-body-1">Allow writes: {{ index.indexConfiguration.allowWrites ? "yes" : "no" }}</span> <md-switch ng-model="index.indexConfiguration.allowWrites" aria-label="allowWrites"> </div> </md-list-item> <md-list-item> <div layout="row" layout-fill> <md-input-container flex> <label for="directoryType">Directory Type</label> <md-select ng-model="index.indexConfiguration.directoryType"> <md-option ng-repeat="d in directoryTypes" value="{{d}}"> {{d}} </md-option> </md-select> <md-tooltip>A Directory is a flat list of files. Files may be written once, when they are created. Once a file is created it may only be opened for read, or deleted. Random access is permitted both when reading and writing.</md-tooltip> </md-input-container> <md-input-container flex> <label for="indexVersion">Index version</label> <md-select ng-model="index.indexConfiguration.indexVersion"> <md-option ng-repeat="v in indexVersions" value="{{v}}"> {{v}} </md-option> </md-select> <md-tooltip>Corresponds to Lucene Index version. There will always be a default codec associated with each index version.</md-tooltip> </md-input-container> </div> </md-list-item> <md-list-item> <md-slider-container layout-fill> <span class="md-body-1">RAM buffer size (Mb)</span> <md-slider flex ng-model="index.indexConfiguration.ramBufferSizeMb" min="1" max="10000" aria-label="ramBufferSizeMb" id="ramBufferSizeMb"> </md-slider> <md-input-container> <input flex type="number" ng-model="index.indexConfiguration.ramBufferSizeMb" aria-label="ramBufferSizeMb" aria-controls="ramBufferSizeMb"> </md-input-container> </md-slider-container> </md-list-item> <md-list-item> <md-slider-container layout-fill> <span class="md-body-1">Max bufferred docs</span> <md-slider flex ng-model="index.indexConfiguration.maxBufferedDocs" min="1" max="100" aria-label="maxBufferedDocs" id="maxBufferedDocs"> </md-slider> <md-input-container> <input flex type="number" ng-model="index.indexConfiguration.maxBufferedDocs" aria-label="maxBufferedDocs" aria-controls="maxBufferedDocs"> </md-input-container> </md-slider-container> </md-list-item> <md-list-item> <md-slider-container layout-fill> <span class="md-body-1">Write lock timeout (ms)</span> <md-slider flex ng-model="index.indexConfiguration.defaultWriteLockTimeout" min="1" max="10000" aria-label="defaultWriteLockTimeout" id="defaultWriteLockTimeout"> </md-slider> <md-input-container> <input flex type="number" ng-model="index.indexConfiguration.defaultWriteLockTimeout" aria-label="defaultWriteLockTimeout" aria-controls="defaultWriteLockTimeout"> </md-input-container> </md-slider-container> </md-list-item> </md-list> </md-content> </md-card-content>
FlexSearch/FlexSearch
srcjs/src/apps/adminui/indexConfigTemplate.html
HTML
apache-2.0
7,471
/* Copyright (c) 2015 Magnet Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.magnet.mmx.protocol; import com.google.gson.annotations.SerializedName; import com.magnet.mmx.util.GsonData; /** * The request for device and the optional push registration. * * The response is MMXStatus. * */ public class DevReg extends DeviceInfo { @SerializedName("apiKey") private String mApiKey; public String getApiKey() { return mApiKey; } public DevReg setApiKey(String apiKey) { mApiKey = apiKey; return this; } public static DevReg fromJson(String json) { return GsonData.getGson().fromJson(json, DevReg.class); } @Override public String toString() { final StringBuilder sb = new StringBuilder() .append("apiKey='").append(mApiKey) .append("', ").append(super.toString()); return sb.toString(); } }
magnetsystems/message-common
src/main/java/com/magnet/mmx/protocol/DevReg.java
Java
apache-2.0
1,407
<div ng-controller="createClusterModalController as createClusterModalCntrl"> <div class="tendrl-create-cluster-modal-container"> <custom-modal-header title="createClusterModalCntrl.modalHeader.title" close="createClusterModalCntrl.modalHeader.close"></custom-modal-header> <div class="modal-body"> <p>Multiple storage service providers available on this system. Select the storage service to use for this cluster.</p> <b>Storage Service</b> <ul class="list-group"> <li ng-class="{selectedCluster : cluster.value === createClusterModalCntrl.valueSelected}" ng-repeat = "cluster in createClusterModalCntrl.StorageServices" ng-click="createClusterModalCntrl.setSelected(cluster.value)" class="list-group-item" >{{cluster.name}}</li> </ul> </div> <custom-modal-footer modal-footer="createClusterModalCntrl.modalFooter"></custom-modal-footer> </div> </div>
cloudbehl/tendrl_frontend
src/modules/cluster/create-cluster/create-cluster-modal/create-cluster-modal.html
HTML
apache-2.0
881
google-python-exercises ======================= Following Google's Python Class at: https://developers.google.com/edu/python
amir-toly/google-python-exercises
README.md
Markdown
apache-2.0
125
// ---------------------------------------------------------------------------- // Copyright 2007-2017, GeoTelematic Solutions, Inc. // All rights reserved // ---------------------------------------------------------------------------- // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // Change History: // 2007/01/25 Martin D. Flynn // -Initial release // 2007/02/25 Martin D. Flynn // -Fixed possible exception when notification email has been disabled. // 2007/06/03 Martin D. Flynn // -Added I18N support // 2007/06/13 Martin D. Flynn // -Added support for browsers with disabled cookies // 2007/06/30 Martin D. Flynn // -Added Device table view // 2007/07/27 Martin D. Flynn // -Added 'getNavigationTab(...)' // 2007/12/13 Martin D. Flynn // -Fixed NPE when no devices are yet defined for the account // 2007/01/10 Martin D. Flynn // -Added edit fields for 'notes', 'simPhoneNumber'. // 2008/05/14 Martin D. Flynn // -Integrated Device DataTransport interface // 2008/10/16 Martin D. Flynn // -Added ability to create/delete devices. // -Added ability to edit unique-id and 'active' state. // -'setAllowNotify()' now properly set when rule selector has been specified. // -Update with new ACL usage // 2008/12/01 Martin D. Flynn // -Added 'Map Pushpin ID' field to specify group map icon for a specific device. // 2009/01/01 Martin D. Flynn // -Added Notification Description fields (if a valid RuleFactory is in place). // 2009/05/01 Martin D. Flynn // -Added "Ignition Input Line" field. // 2009/08/23 Martin D. Flynn // -Convert new entered IDs to lowercase // 2009/11/10 Martin D. Flynn // -Added PushpinChooser support // 2010/01/29 Martin D. Flynn // -Added 'codeVersion' field displayed as "Firmware Version". // 2010/04/11 Martin D. Flynn // -Added Link fields (linkURL/linkDescription) // -"Properties" button will not display if no listed device supports the DeviceCmdHandler // 2010/07/18 Martin D. Flynn // -Allow editing Server-id ("deviceCode") if device has not yet connected to server. // -Added "Fuel Capacity" field. // 2010/09/09 Martin D. Flynn // -Added "vehicleID" field // 2011/01/28 Martin D. Flynn // -Added "Creation Date" display (read-only) field // -Added "Driver ID" // 2011/10/03 Martin D. Flynn // -Added PROP_DeviceInfo_maxIgnitionIndex // -Added edit "Serial Number" [device.getSerialNumber()] // 2011/12/06 Martin D. Flynn // -Added ACL support for fields: IMEI, SIM, SMS, Serial#, DataKey // -Hide Rule Selector if "Device.CheckNotifySelector()" is false. // 2012/02/03 Martin D. Flynn // -Added ACL support for fields: Active // -Added support for engine hours offset // 2012/04/03 Martin D. Flynn // -Hide UniqueID,SIM#,Active in device list based on ACLs // -Extract a single address from the SMS Email address // -Added support for displaying/resetting fault codes // 2012/06/29 Martin D. Flynn // -Added "Preferred Group" field. // -Added Reminder Message field. // 2012/08/01 Martin D. Flynn // -Added "Assigned User ID" // 2013/04/08 Martin D. Flynn // -Added "PROP_DeviceInfo_showCommandState_" property support. // (Configured command state bits are set/cleared when specific command // are selected and sent to the device). // -Added PARM_HOURS_OF_OPERATION, controlled by PROP_DeviceInfo_showHoursOfOperation // 2013/05/19 Martin D. Flynn // -Added Calendar display for dates (ie. last/next service time) // 2013/08/06 Martin D. Flynn // -Added PROP_DeviceInfo_uniqueSimPhoneNumber // -Added ACL support for "fuelCapacity", "fuelEconomy" // 2013/11/11 Martin D. Flynn // -Added "manager" option to "deviceInfo.allowNewDevice" property // -Allow device "delete" if over limit // 2014/05/05 Martin D. Flynn // -Added a fuel cost field. // 2014/06/29 Martin D. Flynn // -Added support for FuelLevelProfile // 2014/12/22 Martin D. Flynn // -Added pull-down menu list for "DCS Property ID" // 2015/05/05 Martin D. Flynn // -Added support for PROP_DeviceInfo_showFuelLevelProfile // -Added support for "fixedAddress" (see PARM_FIXED_ADDRESS) // -Added support for "fixedContactPhone" (see PARM_FIXED_PHONE) // 2016/01/04 Martin D. Flynn // -Fixed race-condition when initializing Device Command Handlers [2.6.1-B21] // -Added support for Fuel Tank #2 Profile [2.6.1-B45] (see fuelProf2) // 2016/04/06 Martin D. Flynn // -Check actual selected device prior to delete (see "actualDev") [2.6.2-B15] // 2016/12/21 Martin D. Flynn // -Added support for device expiration time (see DEVICE_EXPIRE, PARM_DEV_EXPIRE) [2.6.4-B12] // ---------------------------------------------------------------------------- package org.opengts.war.track.page; import java.util.Locale; import java.util.TimeZone; import java.util.Iterator; import java.util.Vector; import java.util.Map; import java.util.Set; import java.util.HashMap; import java.util.Collection; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.opengts.util.*; import org.opengts.dbtools.*; import org.opengts.dbtypes.*; import org.opengts.db.*; import org.opengts.db.AclEntry.AccessLevel; import org.opengts.db.tables.*; import org.opengts.war.tools.*; import org.opengts.war.track.*; import org.opengts.war.maps.JSMap; import org.opengts.war.track.page.devcmd.*; public class DeviceInfo extends WebPageAdaptor implements Constants { // ------------------------------------------------------------------------ private static final boolean EDIT_SERVER_ID = false; private static final boolean EDIT_CODE_VERSION = false; private static final boolean SHOW_LAST_CONNECT = false; private static final boolean SHOW_NOTES = false; private static final String SHOW_DATA_KEY = "false"; private static final boolean SHOW_PUSHPIN_ID = true; private static final boolean SHOW_IGNITION_NDX = true; private static final boolean SHOW_DISPLAY_COLOR = true; private static final boolean SHOW_SPEED_LIMIT = false; private static final boolean SHOW_REPORTED_ODOM = true; private static final boolean SHOW_REPORTED_ENG_HRS = true; private static final boolean SHOW_MAINTENANCE_ODOM = true; // still requires maintenance support private static final boolean SHOW_MAINTENANCE_HOURS = true; // still requires maintenance support private static final boolean SHOW_MAINTENANCE_NOTES = true; // still requires maintenance support private static final boolean SHOW_REMINDER_MESSAGE = false; // still requires maintenance support private static final boolean SHOW_SERVICE_TIME = false; // still requires maintenance support private static final boolean SHOW_SERVICE_ID = true; private static final boolean SHOW_EXPIRATION_TIME = true; // false; // device expiration private static final boolean SHOW_FIXED_LOCATION = false; private static final boolean SHOW_NOTIFY_SELECTOR = false; // only if RuleFactory defined private static final boolean SHOW_DCS_PROPERTIES_ID = false; private static final boolean SHOW_DCS_CONFIG_STRING = false; private static final boolean SHOW_FIXED_TCP_SESSION_ID = false; private static final boolean SHOW_PREFERRED_GROUP = false; private static final boolean ADD_TO_PREFERRED_GROUP = true; private static final boolean SHOW_ASSIGNED_USER = false; private static final boolean SHOW_HOURS_OF_OPERATION = false; private static final boolean SHOW_FAULT_CODES = true; private static final boolean SHOW_FUEL_CAPACITY = true; private static final boolean OPTIMIZE_IGNITION_STATE = false; private static final boolean ADD_DEV_TO_USER_AUTH_GROUP = true; private static final boolean SHOW_PUSHPIN_CHOOSER = false; private static final boolean SHOW_DATE_CALENDAR = false; private static final boolean SHOW_MAP_SHARE_DATES = false; // ------------------------------------------------------------------------ public static final String _ACL_SERVERID = "serverID"; public static final String _ACL_FIRMWARE = "firmware"; public static final String _ACL_RULES = "rules"; public static final String _ACL_UNIQUEID = "uniqueID"; public static final String _ACL_ACTIVE = "active"; public static final String _ACL_EXPIRE = "expire"; public static final String _ACL_SHARE = "share"; public static final String _ACL_COMMANDS = "commands"; public static final String _ACL_SMS = "sms"; public static final String _ACL_EDIT_SMS = "editSMS"; public static final String _ACL_EDIT_SIM = "editSIM"; public static final String _ACL_EDIT_EQSTAT = "editEquipStat"; public static final String _ACL_EDIT_IMEI = "editIMEI"; public static final String _ACL_EDIT_SERIAL = "editSerial"; public static final String _ACL_EDIT_DATKEY = "editDatKey"; public static final String _ACL_FUEL_CAPACITY = "fuelCapacity"; public static final String _ACL_FUEL_PROFILE = "fuelProfile"; public static final String _ACL_FUEL_ECONOMY = "fuelEconomy"; private static final String _ACL_LIST[] = new String[] { //_ACL_SERVERID, // [2.6.2-B19] //_ACL_FIRMWARE, // [2.6.2-B19] _ACL_RULES, _ACL_UNIQUEID, _ACL_ACTIVE, _ACL_EXPIRE, // [2.6.4-B12] _ACL_SHARE, // [2.6.4-B12] _ACL_COMMANDS, _ACL_SMS, _ACL_EDIT_SMS, _ACL_EDIT_SIM, _ACL_EDIT_EQSTAT, _ACL_EDIT_IMEI, _ACL_EDIT_SERIAL, _ACL_EDIT_DATKEY, _ACL_FUEL_CAPACITY, _ACL_FUEL_PROFILE, _ACL_FUEL_ECONOMY }; // ------------------------------------------------------------------------ // allow new/delete device modes public static final int DEVMODE_DENY = 0; public static final int DEVMODE_ALLOW = 1; public static final int DEVMODE_SYSADMIN = 2; public static final int DEVMODE_MANAGER = 3; public static final int DEVMODE_MAXLIMIT = 4; // ------------------------------------------------------------------------ // Ignition type selection public static final String IGNITION_notApplicable = "n/a"; public static final String IGNITION_ignition = "IgnitionOn/Off"; // "ign" public static final String IGNITION_startStop = "Start/Stop"; // "s/s" // ------------------------------------------------------------------------ // Parameters // -- device expiration vars public static final String DEVICE_EXPIRE = "devExpCal"; // -- device expiration vars public static final String SHARE_START = "shareFrCal"; public static final String SHARE_END = "shareToCal"; // -- license/registration expiration vars public static final String LICENSE_EXPIRE = "licExpCal"; // -- last service time calendar vars public static final String LAST_SERVICE_TIME = "lastSrvDateCal"; public static final String NEXT_SERVICE_TIME = "nextSrvDateCal"; // -- forms public static final String FORM_DEVICE_SELECT = "DeviceInfoSelect"; public static final String FORM_DEVICE_EDIT = "DeviceInfoEdit"; public static final String FORM_DEVICE_NEW = "DeviceInfoNew"; // -- commands public static final String COMMAND_INFO_UPD_DEVICE = "updateDev"; public static final String COMMAND_INFO_UPD_PROPS = "updateProps"; // see DeviceCmdHandler public static final String COMMAND_INFO_UPD_SMS = "updateSms"; // see DeviceCmd_SMS //public static final String COMMAND_INFO_REFRESH = "refreshList"; public static final String COMMAND_INFO_SEL_DEVICE = "selectDev"; public static final String COMMAND_INFO_NEW_DEVICE = "newDev"; // -- submit public static final String PARM_SUBMIT_EDIT = "d_subedit"; public static final String PARM_SUBMIT_VIEW = "d_subview"; public static final String PARM_SUBMIT_CHG = "d_subchg"; public static final String PARM_SUBMIT_DEL = "d_subdel"; public static final String PARM_SUBMIT_NEW = "d_subnew"; public static final String PARM_SUBMIT_QUE = "d_subque"; public static final String PARM_SUBMIT_PROP = "d_subprop"; public static final String PARM_SUBMIT_SMS = "d_subsms"; // -- buttons public static final String PARM_BUTTON_CANCEL = "d_btncan"; public static final String PARM_BUTTON_BACK = "d_btnbak"; // -- device table fields public static final String PARM_NEW_NAME = "d_newname"; public static final String PARM_CREATE_DATE = "d_creation"; public static final String PARM_SERVER_ID = "d_servid"; public static final String PARM_CODE_VERS = "d_codevers"; public static final String PARM_DEV_UNIQ = "d_uniq"; public static final String PARM_DEV_DESC = "d_desc"; public static final String PARM_DEV_NAME = "d_name"; public static final String PARM_VEHICLE_ID = "d_vehicid"; public static final String PARM_VEHICLE_MAKE = "d_vehMake"; public static final String PARM_VEHICLE_MODEL = "d_vehModel"; public static final String PARM_LICENSE_PLATE = "d_licPlate"; public static final String PARM_LICENSE_EXPIRE = "d_licExp"; public static final String PARM_DEV_EQUIP_TYPE = "d_equipt"; public static final String PARM_DEV_EQUIP_STATUS = "d_equips"; public static final String PARM_DEV_FUEL_CAP1 = "d_fuelcap1"; public static final String PARM_DEV_FUEL_CAP2 = "d_fuelcap2"; public static final String PARM_DEV_FUEL_PROFILE1 = "d_fuelprof1"; public static final String PARM_DEV_FUEL_PROFILE1_SCALE= "d_fuelprof1Sca"; public static final String PARM_DEV_FUEL_PROFILE1_OFFS = "d_fuelprof1Ofs"; public static final String PARM_DEV_FUEL_PROFILE2 = "d_fuelprof2"; public static final String PARM_DEV_FUEL_PROFILE2_SCALE= "d_fuelprof2Sca"; public static final String PARM_DEV_FUEL_PROFILE2_OFFS = "d_fuelprof2Ofs"; public static final String PARM_DEV_FUEL_ECON = "d_fuelecon"; public static final String PARM_DEV_FUEL_COST = "d_fuelcost"; public static final String PARM_DEV_SPEED_LIMIT = "d_speedLim"; public static final String PARM_DEV_IMEI = "d_imei"; public static final String PARM_DEV_SERIAL_NO = "d_sernum"; public static final String PARM_DATA_KEY = "d_datakey"; public static final String PARM_DEV_SIMPHONE = "d_simph"; public static final String PARM_SMS_EMAIL = "d_smsemail"; public static final String PARM_ICON_ID = "d_iconid"; public static final String PARM_DISPLAY_COLOR = "d_dcolor"; public static final String PARM_DEV_ACTIVE = "d_actv"; public static final String PARM_DEV_EXPIRE = "d_devExp"; public static final String PARM_DEV_SERIAL = "d_ser"; public static final String PARM_DEV_LAST_CONNECT = "d_lconn"; public static final String PARM_DEV_LAST_EVENT = "d_levnt"; public static final String PARM_DEV_NOTES = "d_notes"; public static final String PARM_LINK_URL = "d_linkurl"; public static final String PARM_LINK_DESC = "d_linkdesc"; public static final String PARM_FIXED_LAT = "d_fixlat"; public static final String PARM_FIXED_LON = "d_fixlon"; public static final String PARM_FIXED_ADDRESS = "d_fixAddr"; public static final String PARM_FIXED_PHONE = "d_fixPhone"; public static final String PARM_IGNITION_INDEX = "d_ignndx"; public static final String PARM_DCS_PROPS_ID = "d_dcspropid"; public static final String PARM_DCS_CONFIG_STR = "d_dcscfgstr"; public static final String PARM_TCP_SESSION_ID = "d_tcpSessID"; public static final String PARM_DEV_ENABLE_ELOG = "d_elog"; public static final String PARM_DRIVER_ID = "d_driver"; public static final String PARM_USER_ID = "d_user"; public static final String PARM_GROUP_ID = "d_group"; public static final String PARM_DEV_GROUP_ = "d_grp_"; public static final String PARM_REPORT_ODOM = "d_rptodom"; public static final String PARM_REPORT_HOURS = "d_rpthours"; public static final String PARM_MAINT_INTERVKM_ = "d_mntintrkm"; public static final String PARM_MAINT_LASTKM_ = "d_mntlastkm"; // read-only public static final String PARM_MAINT_NEXTKM_ = "d_mntnextkm"; // read-only public static final String PARM_MAINT_RESETKM_ = "d_mntreskm"; // reset checkbox public static final String PARM_MAINT_INTERVKM_0 = PARM_MAINT_INTERVKM_+"0"; public static final String PARM_MAINT_LASTKM_0 = PARM_MAINT_LASTKM_+"0"; public static final String PARM_MAINT_NEXTKM_0 = PARM_MAINT_NEXTKM_+"0"; public static final String PARM_MAINT_RESETKM_0 = PARM_MAINT_RESETKM_+"0"; public static final String PARM_MAINT_INTERVKM_1 = PARM_MAINT_INTERVKM_+"1"; public static final String PARM_MAINT_LASTKM_1 = PARM_MAINT_LASTKM_+"1"; public static final String PARM_MAINT_NEXTKM_1 = PARM_MAINT_NEXTKM_+"1"; public static final String PARM_MAINT_RESETKM_1 = PARM_MAINT_RESETKM_+"1"; public static final String PARM_MAINT_INTERVHR_ = "d_mntintrhr"; public static final String PARM_MAINT_LASTHR_ = "d_mntlasthr"; // read-only public static final String PARM_MAINT_RESETHR_ = "d_mntreshr"; // reset checkbox public static final String PARM_MAINT_INTERVHR_0 = PARM_MAINT_INTERVHR_+"0"; public static final String PARM_MAINT_LASTHR_0 = PARM_MAINT_LASTHR_+"0"; public static final String PARM_MAINT_RESETHR_0 = PARM_MAINT_RESETHR_+"0"; public static final String PARM_MAINT_NOTES = "d_mntnotes"; public static final String PARM_REMIND_MESSAGE = "d_remmsg"; public static final String PARM_REMIND_INTERVAL = "d_remintrv"; public static final String PARM_LAST_SERVICE_TIME = "d_lastserv"; public static final String PARM_NEXT_SERVICE_TIME = "d_nextserv"; public static final String PARM_HOURS_OF_OPERATION = "d_hrOfOp"; public static final String PARM_FAULT_CODES = "d_faultc"; // read-only public static final String PARM_FAULT_RESET = "d_faultres"; // reset checkbox public static final String PARM_DEV_RULE_ALLOW = "d_ruleallw"; // "Notify Enable" public static final String PARM_DEV_RULE_EMAIL = "d_rulemail"; public static final String PARM_DEV_RULE_SEL = "d_rulesel"; public static final String PARM_DEV_RULE_DESC = "d_ruledesc"; public static final String PARM_DEV_RULE_SUBJ = "d_rulesubj"; public static final String PARM_DEV_RULE_TEXT = "d_ruletext"; //public static final String PARM_DEV_RULE_WRAP = "d_rulewrap"; public static final String PARM_LAST_ALERT_TIME = "d_alertTime"; public static final String PARM_LAST_ALERT_RESET = "d_alertReset"; public static final String PARM_ACTIVE_CORRIDOR = "d_actvcorr"; public static final String PARM_BORDER_CROSS_ENAB = "d_bcEnable"; public static final String PARM_BORDER_CROSS_TIME = "d_bcTime"; public static final String PARM_SHARE_START = "d_shareFr"; public static final String PARM_SHARE_END = "d_shareTo"; public static final String PARM_SUBSCRIBE_ID = "d_subsID"; public static final String PARM_SUBSCRIBE_NAME = "d_subsName"; public static final String PARM_SUBSCRIBE_AVATAR = "d_subsAvat"; //public static final String PARM_WORKORDER_ID = "d_workid"; public static final String PARM_DEV_CUSTOM_ = "d_c_"; // ------------------------------------------------------------------------ // Device command handlers private static Map<String,DeviceCmdHandler> _DCMap = new HashMap<String,DeviceCmdHandler>(); private static DeviceCmd_SMS SMSCommandHandler = null; private static volatile boolean didInitDeviceCommandHandlers = false; static { // DeviceInfo._initDeviceCommandHandlers(); <== cannot be initialized here }; private static Map<String,DeviceCmdHandler> _getDCMap() { DeviceInfo._initDeviceCommandHandlers(); return _DCMap; } private static void _addDeviceCommandHandler(DeviceCmdHandler dch) { String servID = dch.getServerID(); if (!_DCMap.containsKey(servID)) { //Print.logInfo("Installing DeviceCmdHandler: " + servID); DeviceInfo._DCMap.put(servID, dch); } else { DeviceCmdHandler dupDCH = DeviceInfo._DCMap.get(servID); Print.logError("Duplicate ServerID found: " + servID); Print.logError(" Current class : " + StringTools.className(dch)); Print.logError(" Previous class: " + StringTools.className(dupDCH)); Print.logStackTrace("Duplicate ServerID: " + servID); } } @SuppressWarnings("unchecked") private static Class<DeviceCmd_SMS> GetDeviceCmd_SMS_class() { try { return (Class<DeviceCmd_SMS>)Class.forName("org.opengts.war.track.page.devcmd.DeviceCmd_SMS"); } catch (Throwable th) { // ClassNotFoundException Print.logWarn("Unable to find class DeviceCmd_SMS ..."); return null; } } @SuppressWarnings("unchecked") private static Class<DeviceCmdHandler> GetDeviceCmd_General_class() { try { return (Class<DeviceCmdHandler>)Class.forName("org.opengts.war.track.page.devcmd.DeviceCmd_General"); } catch (Throwable th) { // ClassNotFoundException Print.logWarn("Unable to find class DeviceCmd_General ..."); return null; } } private static void _initDeviceCommandHandlers() { String threadName = Thread.currentThread().getName(); /* already initialized? */ if (didInitDeviceCommandHandlers) { // -- already initiualized //Print.logInfo("**** Device Command Handlers already initialized ["+threadName+"] ****"); return; } /* initialize (thread safe) */ synchronized (DeviceInfo._DCMap) { // [2.6.1-B21] if (!didInitDeviceCommandHandlers) { //Print.logInfo("**** Initializing Device Command Handlers ["+threadName+"] ****"); /* list of possible DeviceCmdHandler UI pages */ /* The following list is no longer required String optDevCmdHandlerClasses[] = new String[] { "DeviceCmd_SMS", // always available "DeviceCmd_gtsdmtp", // always available "DeviceCmd_template", // always available ... }; */ /* DeviceCmd_SMS.class */ Class<DeviceCmd_SMS> DeviceCmd_SMS_class = GetDeviceCmd_SMS_class(); if (DeviceCmd_SMS_class != null) { /* add available Device command pages */ String DeviceCmd_ = "DeviceCmd_"; String devCmdPackage = DeviceCmd_SMS_class.getPackage().getName(); // always present java.util.List<DCServerConfig> dcServerList = DCServerFactory.getServerConfigList(true/*inclAll*/); for (DCServerConfig dcs : dcServerList) { // for (String _dchn : optDevCmdHandlerClasses) /* existing "DeviceCmd_xxxx" command ui module */ String dcsName = dcs.getName(); String _dchn = DeviceCmd_ + dcsName; /* separate any class:args */ // DeviceInfo.DeviceCmdAlternate.calamp=1,2,3 int p = _dchn.indexOf(":"); String dcn = (p >= 0)? _dchn.substring(0,p).trim() : _dchn; String dca = (p >= 0)? _dchn.substring(p+1).trim() : null; String dchArgs[] = RTConfig.getStringArray(DBConfig.PROP_DeviceInfo_DeviceCmdAlternate_+dcsName, null); if (ListTools.isEmpty(dchArgs) && !StringTools.isBlank(dca)) { dchArgs = StringTools.split(dca,','); } /* has commands */ if (ListTools.isEmpty(dcs.getCommandList())) { // -- no defined commands //Print.logInfo("DCS does not define any commands: " + dcsName); continue; } /* get class */ String dchClassName = devCmdPackage + "." + dcn; Class<?> dchClass = null; try { //Print.logInfo("Getting Class.forName: " + dchClassName); dchClass = Class.forName(dchClassName); } catch (Throwable th) { // ClassNotFoundException // -- not found //Print.logInfo("DeviceCmdHandler UI class not found: " + dchClassName + " (using General)"); dchClass = null; } /* add command handler UI */ if (dchClass != null) { // -- found existing page, create instance try { DeviceCmdHandler stdDCH = (DeviceCmdHandler)dchClass.newInstance(); DeviceInfo._addDeviceCommandHandler(stdDCH); //Print.logInfo("Added existing command handler UI: "+dcn+"("+dcsName+")"); } catch (Throwable th) { // ClassNotFoundException, ... Print.logException("DeviceCmdHandler UI instantiation error: " + dchClassName, th); continue; } } else { // -- existing page not found, use DeviceCmd_General DeviceCmdHandler stdDCH; // = new DeviceCmd_General(dcsName); try { String dcgClassN = "org.opengts.war.track.page.devcmd.DeviceCmd_General"; MethodAction dchMA = new MethodAction(dcgClassN, String.class); stdDCH = (DeviceCmdHandler)dchMA.invoke(dcsName); } catch (Throwable th) { Print.logInfo("Unable to load DeviceCmd_General class: " + th.getMessage()); continue; } DeviceInfo._addDeviceCommandHandler(stdDCH); //Print.logInfo("Added General command handler UI: DeviceCmd_General("+dcsName+")"); } // -- check for additional DCS name args if (!ListTools.isEmpty(dchArgs)) { for (int a = 0; a < dchArgs.length; a++) { String arg = StringTools.trim(dchArgs[a]); if (!StringTools.isBlank(arg)) { if (dchClass != null) { try { DeviceCmdHandler argDCH = (DeviceCmdHandler)dchClass.newInstance(); argDCH.setServerIDArg(arg); DeviceInfo._addDeviceCommandHandler(argDCH); Print.logInfo("Added custom command handler: "+dcn+"("+dcsName+") [" + arg + "]"); } catch (Throwable th) { // ClassNotFoundException, ... Print.logException("DeviceCmdHandler UI instantiation error: " + dchClassName, th); break; } } else { DeviceCmdHandler argDCH; // = new DeviceCmd_General(dcsName); try { String dcgClassN = "org.opengts.war.track.page.devcmd.DeviceCmd_General"; MethodAction dchMA = new MethodAction(dcgClassN, String.class); argDCH = (DeviceCmdHandler)dchMA.invoke(dcsName); } catch (Throwable th) { Print.logInfo("Unable to load DeviceCmd_General class: " + th.getMessage()); continue; } argDCH.setServerIDArg(arg); DeviceInfo._addDeviceCommandHandler(argDCH); Print.logInfo("Added custom command handler: DeviceCmd_General("+dcsName+") [" + arg + "]"); } } } } } /* SMS */ try { SMSCommandHandler = /*(DeviceCmd_SMS)*/DeviceCmd_SMS_class.newInstance(); // new DeviceCmd_SMS(); Print.logDebug("Created DeviceCmd_SMS command handler"); } catch (Throwable th) { Print.logWarn("Unable to create DeviceCmd_SMS ..."); } } /* initialized */ didInitDeviceCommandHandlers = true; } } } private DeviceCmdHandler getDeviceCommandHandler(String dcid) { /* must not be null/blank */ if (StringTools.isBlank(dcid)) { return null; } /* get DCS module */ DCServerConfig dcs = DCServerFactory.getServerConfig(dcid); if (dcs == null) { Print.logWarn("DCSServerConfig not found for DCS: " + dcid); return null; } else if (ListTools.isEmpty(dcs.getCommandList())) { //Print.logInfo("No commands defined for DCS: " + dcid); return null; } /* get command handler UI */ DeviceCmdHandler dch = DeviceInfo._getDCMap().get(dcid); // may still be null if (dch == null) { //Print.logWarn("DCS does not have a command handler UI: " + dcid); return null; } /* return DeviceCmdHandler */ return dch; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ private static class StateMaskBit // see "inpStateList"/"cmdStateList" { int bitNdx = 0; String title = ""; String falseDesc = ""; String trueDesc = ""; public StateMaskBit(int ndx, String csvDesc, String dftTitle, Locale locale) { this.bitNdx = ndx; String v[] = StringTools.split(csvDesc,','); // Title,FalseDesc,TrueDesc this.title = AccountRecord.GetSimpleLocalString((v.length > 0)? v[0] : dftTitle+ndx, locale); this.falseDesc = AccountRecord.GetSimpleLocalString((v.length > 1)? v[1] : "0" , locale); this.trueDesc = AccountRecord.GetSimpleLocalString((v.length > 2)? v[2] : "1" , locale); } public StateMaskBit(int ndx, String title, String offDesc, String onDesc) { this.bitNdx = ndx; this.title = title; this.falseDesc = offDesc; this.trueDesc = onDesc; } public int getBitIndex() { return this.bitNdx; } public String getTitle() { return this.title; } public String getFalseDesc() { return this.falseDesc; } public String getTrueDesc() { return this.trueDesc; } public String getStateDescription(boolean state) { return state? this.getTrueDesc() : this.getFalseDesc(); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.getBitIndex()); sb.append(","); sb.append(this.getTitle()); sb.append(","); sb.append(this.getFalseDesc()); sb.append(","); sb.append(this.getTrueDesc()); return sb.toString(); } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ private static boolean ShowNotifySelector() { return Device.CheckNotifySelector(); } // ------------------------------------------------------------------------ private static long GetEpochTime(String ymd, TimeZone tz, DateTime.DefaultParsedTime dftTime) { if (StringTools.isBlank(ymd)) { return 0L; } else { try { DateTime.ParsedDateTime pdt = DateTime.parseDateTime(ymd, tz, dftTime); return (pdt != null)? pdt.getEpochTime() : 0L; } catch (DateTime.DateParseException dpe) { return 0L; } } } private static long GetEpochTimeDayStart(DateTime.DateStringFormat dsf, String dat, TimeZone tz) { String ymd = (dsf != null)? dsf.convertToYMD(dat) : dat; return DeviceInfo.GetEpochTime(ymd, tz, DateTime.DefaultParsedTime.DayStart); } private static long GetEpochTimeDayEnd(DateTime.DateStringFormat dsf, String dat, TimeZone tz) { String ymd = (dsf != null)? dsf.convertToYMD(dat) : dat; return DeviceInfo.GetEpochTime(ymd, tz, DateTime.DefaultParsedTime.DayEnd); } // ------------------------------------------------------------------------ private static long GetDayNumber(String ymd) { if (StringTools.isBlank(ymd)) { return 0L; } else { DayNumber dn = DayNumber.parseDayNumber(ymd); return (dn != null)? dn.getDayNumber() : 0L; } } private static long GetDayNumberTS(String ymd, TimeZone tmz, boolean dayStart) { if (StringTools.isBlank(ymd)) { return 0L; } else { DayNumber dn = DayNumber.parseDayNumber(ymd); DateTime dt = (dn != null)? (dayStart?dn.getDayStart(tmz):dn.getDayEnd(tmz)) : null; return (dt != null)? dt.getTimeSec() : 0L; } } // -------------------------------- private static String FormatDayNumber(DateTime.DateStringFormat dsf, long dn) { if (dn < 0L) { return ""; } else { String dateYMD = (new DayNumber(dn)).format(DayNumber.DATE_FORMAT_YMD_1); if (dsf != null) { return dsf.convertFromYMD(dateYMD); } else { return dateYMD; } } } private static String FormatDayNumberTS(DateTime.DateStringFormat dsf, long ts, TimeZone tmz) { if (ts <= 0L) { return FormatDayNumber(dsf, 0L); } else { long dn = new DateTime(ts,tmz).getDayNumber(); return FormatDayNumber(dsf, dn); } } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // WebPage interface public DeviceInfo() { this.setBaseURI(RequestProperties.TRACK_BASE_URI()); this.setPageName(PAGE_DEVICE_INFO); this.setPageNavigation(new String[] { PAGE_LOGIN, PAGE_MENU_TOP }); this.setLoginRequired(true); } // ------------------------------------------------------------------------ public String getMenuName(RequestProperties reqState) { return MenuBar.MENU_ADMIN; } public String getMenuDescription(RequestProperties reqState, String parentMenuName) { PrivateLabel privLabel = reqState.getPrivateLabel(); I18N i18n = privLabel.getI18N(DeviceInfo.class); String devTitles[] = reqState.getDeviceTitles(); return super._getMenuDescription(reqState,i18n.getString("DeviceInfo.editMenuDesc","View/Edit {0} Information", devTitles)); } public String getMenuHelp(RequestProperties reqState, String parentMenuName) { PrivateLabel privLabel = reqState.getPrivateLabel(); I18N i18n = privLabel.getI18N(DeviceInfo.class); String devTitles[] = reqState.getDeviceTitles(); return super._getMenuHelp(reqState,i18n.getString("DeviceInfo.editMenuHelp","View and Edit {0} information", devTitles)); } // ------------------------------------------------------------------------ public String getNavigationDescription(RequestProperties reqState) { PrivateLabel privLabel = reqState.getPrivateLabel(); I18N i18n = privLabel.getI18N(DeviceInfo.class); String devTitles[] = reqState.getDeviceTitles(); return super._getNavigationDescription(reqState,i18n.getString("DeviceInfo.navDesc","{0}", devTitles)); } public String getNavigationTab(RequestProperties reqState) { PrivateLabel privLabel = reqState.getPrivateLabel(); I18N i18n = privLabel.getI18N(DeviceInfo.class); String devTitles[] = reqState.getDeviceTitles(); return i18n.getString("DeviceInfo.navTab","{0} Admin", devTitles); } // ------------------------------------------------------------------------ public String[] getChildAclList() { return _ACL_LIST; } // ------------------------------------------------------------------------ private String _filterPhoneNum(String simPhone) { if (StringTools.isBlank(simPhone)) { return ""; } else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < simPhone.length(); i++) { char ch = simPhone.charAt(i); if (Character.isDigit(ch)) { sb.append(ch); } } return sb.toString(); } } private boolean _showNotificationFields(PrivateLabel privLabel) { String propShowNotify = PrivateLabel.PROP_DeviceInfo_showNotificationFields; String snf = (privLabel != null)? privLabel.getStringProperty(propShowNotify,null) : null; /* has notification fields? */ if (!Device.supportsNotification()) { if ((snf != null) && snf.equalsIgnoreCase(StringTools.STRING_TRUE)) { Print.logWarn("Property "+propShowNotify+" is 'true', but Device notification fields are not supported"); } return false; } /* show notification fields? */ if (StringTools.isBlank(snf) || snf.equalsIgnoreCase("default")) { return Device.hasRuleFactory(); // default value } else { return StringTools.parseBoolean(snf,false); } } private boolean _showSubscriberInfo(PrivateLabel privLabel) { String propShowSubscr = PrivateLabel.PROP_DeviceInfo_showSubscriberInfo; boolean ssi = (privLabel != null)? privLabel.getBooleanProperty(propShowSubscr,false) : false; /* has subscriber fields? */ if (!Device.supportsSubscriber()) { if (ssi) { Print.logWarn("Property "+propShowSubscr+" is 'true', but Device subscriber fields are not supported"); } return false; } /* show subscriber info*/ return ssi; } /* private boolean _showWorkOrderID(PrivateLabel privLabel) { String propShowWorkOrder = PrivateLabel.PROP_DeviceInfo_showWorkOrderField; String swo = (privLabel != null)? privLabel.getStringProperty(propShowWorkOrder,null) : null; //* has workOrderID field? if (!Device.getFactory().hasField(Device.FLD_workOrderID)) { if ((swo != null) && swo.equalsIgnoreCase(StringTools.STRING_TRUE)) { Print.logWarn("Property "+propShowWorkOrder+" is 'true', but Device workOrderID not supported"); } return false; } //* show workOrder field? if (StringTools.isBlank(swo) || swo.equalsIgnoreCase("default")) { return true; // default value } else { return StringTools.parseBoolean(swo,false); } } */ private int _allowNewDevice(Account currAcct, PrivateLabel privLabel) { if (currAcct == null) { // -- always deny if no account Print.logInfo("Allow New Device? Deny - null account"); return DEVMODE_DENY; } else if (Account.isSystemAdmin(currAcct)) { // -- always allow if "sysadmin" Print.logDebug("Allow New Device? Allow - SystemAdmin"); return DEVMODE_ALLOW; } else { String globAND = privLabel.getStringProperty(PrivateLabel.PROP_DeviceInfo_allowNewDevice,""); if (globAND.equalsIgnoreCase("sysadmin")) { // "deviceInfo.allowNewDevice" keyword // -- only allow if logged-in from "sysadmin" Print.logDebug("Allow New Device? Allow - if SystemAdmin"); return DEVMODE_SYSADMIN; } else if (globAND.equalsIgnoreCase("manager")) { // "deviceInfo.allowNewDevice" keyword // -- only allow if logged-in account is "sysadmin" or an account-manager Print.logDebug("Allow New Device? Allow - if AccountManager"); return DEVMODE_MANAGER; } else if (globAND.equalsIgnoreCase("maxlimit")) { // "deviceInfo.allowNewDevice" keyword // -- only allow if specified max-limit is > 0 (and not over-limit) Print.logDebug("Allow New Device? Allow - if MaxLimit > 0"); return DEVMODE_MAXLIMIT; } else if (StringTools.parseBoolean(globAND,false) == false) { // -- explicit deny Print.logInfo("Allow New Device? Deny - disallowed"); return DEVMODE_DENY; } else //if (currAcct.isAtMaximumDevices(true)) { // // deny if over limit // Print.logInfo("Allow New Device? Deny - over limit"); // return DEVMODE_DENY; //} else { // -- otherwise allow Print.logDebug("Allow New Device? Allow - as specified"); return DEVMODE_ALLOW; } } } private int _allowDeleteDevice(Account currAcct, PrivateLabel privLabel) { if (currAcct == null) { // -- always deny if no account Print.logInfo("Allow Delete Device? Deny - null account"); return DEVMODE_DENY; } else if (Account.isSystemAdmin(currAcct)) { // -- always allow if "sysadmin" Print.logDebug("Allow Delete Device? Allow - SystemAdmin"); return DEVMODE_ALLOW; } else { String globAND = privLabel.getStringProperty(PrivateLabel.PROP_DeviceInfo_allowDeleteDevice,""); if (globAND.equalsIgnoreCase("sysadmin")) { // "deviceInfo.allowDelete" keyword // -- only allow if logged-in from "sysadmin" Print.logDebug("Allow Delete Device? Allow - if SystemAdmin"); return DEVMODE_SYSADMIN; } else if (globAND.equalsIgnoreCase("manager")) { // "deviceInfo.allowNewDevice" keyword // -- only allow if logged-in account is "sysadmin" or an account-manager Print.logDebug("Allow Delete Device? Allow - if AccountManager"); return DEVMODE_MANAGER; } else if (!StringTools.isBlank(globAND) && StringTools.parseBoolean(globAND,false) == false) { // -- explicit deny Print.logInfo("Allow Delete Device? Deny - disallowed"); return DEVMODE_DENY; } else { // -- otherwise allow Print.logDebug("Allow Delete Device? Allow - as specified"); return DEVMODE_ALLOW; } } } /* update Device table with user entered information */ private String _updateDeviceTable(RequestProperties reqState) { final HttpServletRequest request = reqState.getHttpServletRequest(); final boolean sysadminLogin = reqState.isLoggedInFromSysAdmin(); final Account currAcct = reqState.getCurrentAccount(); // should not be null final User currUser = reqState.getCurrentUser(); final PrivateLabel privLabel = reqState.getPrivateLabel(); final Device selDev = reqState.getSelectedDevice(); // 'selDev' is non-null final I18N i18n = privLabel.getI18N(DeviceInfo.class); final Locale locale = reqState.getLocale(); final String devTitles[] = reqState.getDeviceTitles(); final boolean showFuelCap = true; final boolean showFuelProf = showFuelCap; final boolean showFuelEcon = DBConfig.hasExtraPackage(); final boolean showFuelCost = showFuelEcon; final boolean acctBCEnabled = ((currAcct!=null)&&currAcct.getIsBorderCrossing())?true:false; final TimeZone acctTimeZone = Account.getTimeZone(currAcct,DateTime.getGMTTimeZone()); String msg = null; boolean groupsChg = false; String serverID = AttributeTools.getRequestString(request, PARM_SERVER_ID , ""); String codeVers = AttributeTools.getRequestString(request, PARM_CODE_VERS , ""); String uniqueID = AttributeTools.getRequestString(request, PARM_DEV_UNIQ , ""); String vehicleID = AttributeTools.getRequestString(request, PARM_VEHICLE_ID , null); String vehMake = AttributeTools.getRequestString(request, PARM_VEHICLE_MAKE , null); String vehModel = AttributeTools.getRequestString(request, PARM_VEHICLE_MODEL , null); String licPlate = AttributeTools.getRequestString(request, PARM_LICENSE_PLATE , null); String licExpire = AttributeTools.getRequestString(request, PARM_LICENSE_EXPIRE , ""); String shareStart = AttributeTools.getRequestString(request, PARM_SHARE_START , ""); String shareEnd = AttributeTools.getRequestString(request, PARM_SHARE_END , ""); String devActive = AttributeTools.getRequestString(request, PARM_DEV_ACTIVE , ""); String devExpire = AttributeTools.getRequestString(request, PARM_DEV_EXPIRE , ""); String devDesc = AttributeTools.getRequestString(request, PARM_DEV_DESC , ""); String devName = AttributeTools.getRequestString(request, PARM_DEV_NAME , ""); String pushpinID = AttributeTools.getRequestString(request, PARM_ICON_ID , ""); String dispColor = AttributeTools.getRequestString(request, PARM_DISPLAY_COLOR , ""); String equipType = AttributeTools.getRequestString(request, PARM_DEV_EQUIP_TYPE , ""); String equipStatus = AttributeTools.getRequestString(request, PARM_DEV_EQUIP_STATUS , ""); double fuelCap1 = AttributeTools.getRequestDouble(request, PARM_DEV_FUEL_CAP1 , 0.0); double fuelCap2 = AttributeTools.getRequestDouble(request, PARM_DEV_FUEL_CAP2 , 0.0); String fuelProf1 = AttributeTools.getRequestString(request, PARM_DEV_FUEL_PROFILE1 , ""); String fuelProf1Sca= AttributeTools.getRequestString(request, PARM_DEV_FUEL_PROFILE1_SCALE, ""); String fuelProf1Ofs= AttributeTools.getRequestString(request, PARM_DEV_FUEL_PROFILE1_OFFS , ""); String fuelProf2 = AttributeTools.getRequestString(request, PARM_DEV_FUEL_PROFILE2 , ""); String fuelProf2Sca= AttributeTools.getRequestString(request, PARM_DEV_FUEL_PROFILE2_SCALE, ""); String fuelProf2Ofs= AttributeTools.getRequestString(request, PARM_DEV_FUEL_PROFILE2_OFFS , ""); double fuelEcon = AttributeTools.getRequestDouble(request, PARM_DEV_FUEL_ECON , 0.0); double fuelCostPU = AttributeTools.getRequestDouble(request, PARM_DEV_FUEL_COST , 0.0); double speedLimU = AttributeTools.getRequestDouble(request, PARM_DEV_SPEED_LIMIT , 0.0); String driverID = AttributeTools.getRequestString(request, PARM_DRIVER_ID , ""); String prefUsrID = AttributeTools.getRequestString(request, PARM_USER_ID , ""); String imeiNum = AttributeTools.getRequestString(request, PARM_DEV_IMEI , ""); String serialNum = AttributeTools.getRequestString(request, PARM_DEV_SERIAL_NO , ""); String dataKey = AttributeTools.getRequestString(request, PARM_DATA_KEY , ""); String simPhone = this._filterPhoneNum(AttributeTools.getRequestString(request,PARM_DEV_SIMPHONE,"")); String smsEmail = AttributeTools.getRequestString(request, PARM_SMS_EMAIL , ""); String noteText = AttributeTools.getRequestString(request, PARM_DEV_NOTES , ""); String linkURL = AttributeTools.getRequestString(request, PARM_LINK_URL , ""); String linkDesc = AttributeTools.getRequestString(request, PARM_LINK_DESC , ""); double fixedLat = AttributeTools.getRequestDouble(request, PARM_FIXED_LAT , 0.0); double fixedLon = AttributeTools.getRequestDouble(request, PARM_FIXED_LON , 0.0); String fixedAddr = AttributeTools.getRequestString(request, PARM_FIXED_ADDRESS , ""); String fixedPhone = AttributeTools.getRequestString(request, PARM_FIXED_PHONE , ""); // _filterPhoneNum? String ignition = AttributeTools.getRequestString(request, PARM_IGNITION_INDEX , ""); String dcsPropsID = AttributeTools.getRequestString(request, PARM_DCS_PROPS_ID , ""); String dcsCfgStr = AttributeTools.getRequestString(request, PARM_DCS_CONFIG_STR , ""); String tcpSessID = AttributeTools.getRequestString(request, PARM_TCP_SESSION_ID , ""); String enELogStr = AttributeTools.getRequestString(request, PARM_DEV_ENABLE_ELOG , ""); String prefGrpID = AttributeTools.getRequestString(request, PARM_GROUP_ID , ""); String grpKeys[] = AttributeTools.getMatchingKeys( request, PARM_DEV_GROUP_); String cstKeys[] = AttributeTools.getMatchingKeys( request, PARM_DEV_CUSTOM_); double rptOdom = AttributeTools.getRequestDouble(request, PARM_REPORT_ODOM , 0.0); double rptEngHrs = AttributeTools.getRequestDouble(request, PARM_REPORT_HOURS , 0.0); String actvCorr = AttributeTools.getRequestString(request, PARM_ACTIVE_CORRIDOR , ""); String borderCross = AttributeTools.getRequestString(request, PARM_BORDER_CROSS_ENAB , ""); //String worderID = AttributeTools.getRequestString(request, PARM_WORKORDER_ID , ""); try { // -- unique id boolean editUniqID = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_UNIQUEID)); if (editUniqID && !selDev.getUniqueID().equals(uniqueID)) { if (StringTools.isBlank(uniqueID)) { selDev.setUniqueID(""); } else { // -- TODO: incorporate <Device>.validateUniqueID(...) try { Device dev = Transport.loadDeviceByUniqueID(uniqueID); if (dev == null) { selDev.setUniqueID(uniqueID); } else { String devAcctID = dev.getAccountID(); String devDevID = dev.getDeviceID(); if (devAcctID.equals(reqState.getCurrentAccountID())) { // -- same account, this user can fix this himself msg = i18n.getString("DeviceInfo.uniqueIdAlreadyAssignedToDevice","UniqueID is already assigned to {0}: {1}", devTitles[0], devDevID); // UserErrMsg selDev.setError(msg); } else { // -- different account, this user cannot fix this himself Print.logWarn("UniqueID '%s' already assigned: %s/%s", uniqueID, devAcctID, devDevID); msg = i18n.getString("DeviceInfo.uniqueIdAlreadyAssigned","UniqueID is already assigned to another Account"); // UserErrMsg selDev.setError(msg); } } } catch (DBException dbe) { msg = i18n.getString("DeviceInfo.errorReadingUniqueID","Error while looking for other matching UniqueIDs"); // UserErrMsg selDev.setError(msg); } } } // -- server id boolean editServID = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_SERVERID)) && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_allowEditServerID,EDIT_SERVER_ID) && (selDev.getLastConnectTime() <= 0L); if (editServID && !selDev.getDeviceCode().equals(serverID) && DCServerFactory.hasServerConfig(serverID)) { selDev.setDeviceCode(serverID); } // -- code version (firmware version) boolean editCodeVer = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FIRMWARE)) && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_allowEditFirmwareVersion,EDIT_CODE_VERSION); if (editCodeVer && !selDev.getCodeVersion().equals(codeVers)) { selDev.setCodeVersion(codeVers); } // -- active boolean editActive = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_ACTIVE)); boolean devActv = ComboOption.parseYesNoText(locale, devActive, true); if (editActive && (selDev.getIsActive() != devActv)) { selDev.setIsActive(devActv); } // -- expiration timestamp [2.6.4-B12] boolean devExpOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDeviceExpirationTime,SHOW_EXPIRATION_TIME);; boolean editExpire = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EXPIRE)); if (devExpOK && editExpire) { long expireTS = GetDayNumberTS(devExpire, acctTimeZone, true); if (expireTS != selDev.getExpirationTime()) { selDev.setExpirationTime(expireTS); // Epoch timestamp } } // -- share start/end timestamp [2.6.4-B12] if (Device.supportsMapShare()) { // -- share map date fields are available boolean shareMapOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showSharedMapDates,SHOW_MAP_SHARE_DATES);; boolean editShare = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_SHARE)); if (!editShare) { // -- do not update shareMap dates } else if (shareMapOK) { // -- shareMap dates displayed and editable long shareStartTS = GetDayNumberTS(shareStart, acctTimeZone, true); long shareEndTS = GetDayNumberTS(shareEnd , acctTimeZone, false); if ((shareStartTS <= 0L) || (shareStartTS >= shareEndTS)) { shareStartTS = 0L; shareEndTS = 0L; } if (shareStartTS != selDev.getMapShareStartTime()) { selDev.setMapShareStartTime(shareStartTS); // Epoch timestamp } if (shareEndTS != selDev.getMapShareEndTime()) { selDev.setMapShareEndTime(shareEndTS); // Epoch timestamp } } else { // -- shareMap dates not displayed, but editable if (selDev.getMapShareStartTime() != 0L) { selDev.setMapShareStartTime(0L); // Epoch timestamp } if (selDev.getMapShareEndTime() != 0L) { selDev.setMapShareEndTime(0L); // Epoch timestamp } } } // -- description if (!selDev.getDescription().equals(devDesc)) { selDev.setDescription(devDesc); } // -- display name if (!selDev.getDisplayName().equals(devName)) { selDev.setDisplayName(devName); } // -- vehicle ID (VIN) if ((vehicleID != null) && !selDev.getVehicleID().equals(vehicleID)) { selDev.setVehicleID(vehicleID); } // -- vehicle Make if ((vehMake != null) && !selDev.getVehicleMake().equals(vehMake)) { selDev.setVehicleMake(vehMake); } // -- vehicle Model if ((vehModel != null) && !selDev.getVehicleModel().equals(vehModel)) { selDev.setVehicleModel(vehModel); } // -- License Plate if ((licPlate != null) && !selDev.getLicensePlate().equals(licPlate)) { selDev.setLicensePlate(licPlate); } // -- License Expire long licExpireDN = GetDayNumber(licExpire); if ((licExpireDN >= 0L) && (licExpireDN != selDev.getLicenseExpire())) { selDev.setLicenseExpire(licExpireDN); } // -- equipment type/status if (!selDev.getEquipmentType().equals(equipType)) { selDev.setEquipmentType(equipType); } if (!selDev.getEquipmentStatus().equals(equipStatus)) { selDev.setEquipmentStatus(equipStatus); } // -- fuel capacity tank #1 boolean editFuelCap1 = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_CAPACITY)); if (showFuelCap && editFuelCap1) { double fuelCap1L = Account.getVolumeUnits(currAcct).convertToLiters(fuelCap1); if (selDev.getFuelCapacity() != fuelCap1L) { selDev.setFuelCapacity(fuelCap1L); } } // -- fuel capacity tank #2 boolean editFuelCap2 = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_CAPACITY)); if (showFuelCap && editFuelCap2) { double fuelCap2L = Account.getVolumeUnits(currAcct).convertToLiters(fuelCap2); if (selDev.getFuelCapacity2() != fuelCap2L) { selDev.setFuelCapacity2(fuelCap2L); } } // -- fuel tank profile #1 boolean editFuelProf1 = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_PROFILE)); if (showFuelProf && editFuelProf1) { String flpn1 = fuelProf1.equalsIgnoreCase(FuelLevelProfile.FLP_NONE_ID)? "" : fuelProf1; if ((flpn1.indexOf(":") < 0) && (flpn1.equalsIgnoreCase(FuelLevelProfile.FLP_LINEAR_NAME ) || flpn1.equalsIgnoreCase(FuelLevelProfile.FLP_CYLINDER_NAME) ) ) { int scale1 = StringTools.parseInt(fuelProf1Sca,0); int offset1 = StringTools.parseInt(fuelProf1Ofs,0); if (scale1 > 0) { flpn1 += ":" + scale1; // "CYLIDER:600" if (offset1 > 0) { flpn1 += "," + offset1; // "CYLIDER:600,40" } } } if (!selDev.getFuelTankProfile().equals(flpn1)) { selDev.setFuelTankProfile(flpn1); } } // -- fuel tank profile #2 boolean editFuelProf2 = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_PROFILE)); if (showFuelProf && editFuelProf2) { String flpn2 = fuelProf1.equalsIgnoreCase(FuelLevelProfile.FLP_NONE_ID)? "" : fuelProf2; if ((flpn2.indexOf(":") < 0) && (flpn2.equalsIgnoreCase(FuelLevelProfile.FLP_LINEAR_NAME ) || flpn2.equalsIgnoreCase(FuelLevelProfile.FLP_CYLINDER_NAME) ) ) { int scale2 = StringTools.parseInt(fuelProf2Sca,0); int offset2 = StringTools.parseInt(fuelProf2Ofs,0); if (scale2 > 0) { flpn2 += ":" + scale2; // "CYLIDER:600" if (offset2 > 0) { flpn2 += "," + offset2; // "CYLIDER:600,40" } } } if (!selDev.getFuelTankProfile2().equals(flpn2)) { selDev.setFuelTankProfile2(flpn2); } } // -- fuel economy (km/L) boolean editFuelEcon = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_ECONOMY)); if (showFuelEcon && editFuelEcon) { double fuelEconomy = Account.getEconomyUnits(currAcct).convertToKPL(fuelEcon); if (selDev.getFuelEconomy() != fuelEconomy) { selDev.setFuelEconomy(fuelEconomy); } } // -- fuel cost ($/L) boolean editFuelCost = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_ECONOMY)); if (showFuelCost && editFuelCost) { double unitsPerLiter = Account.getVolumeUnits(currAcct).convertFromLiters(1.0); double costPerUnit = fuelCostPU; double costPerLiter = costPerUnit * unitsPerLiter; if (selDev.getFuelCostPerLiter() != costPerLiter) { selDev.setFuelCostPerLiter(costPerLiter); } } // -- Driver ID if (!selDev.getDriverID().equals(driverID)) { selDev.setDriverID(driverID); } // -- Assigned User ID boolean showAssgnUsr = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showAssignedUserID,SHOW_ASSIGNED_USER); if (showAssgnUsr && Device.supportsAssignedUserID()) { if (!StringTools.isBlank(prefUsrID)) { try { User user = User.getUser(selDev.getAccount(),prefUsrID); if (user == null) { Print.logWarn("Assigned User ID does not exist: " + prefUsrID); prefUsrID = ""; } else if (!user.isAuthorizedDevice(selDev.getDeviceID())) { Print.logWarn("Assigned User ID not authorized: " + prefUsrID); prefUsrID = ""; } } catch (DBException dbe) { Print.logError("Unable to read user: " + prefUsrID + " [" + dbe); prefUsrID = ""; } } if (!selDev.getAssignedUserID().equals(prefUsrID)) { //Print.logInfo("Setting Assigned User ID: " + prefUsrID); selDev.setAssignedUserID(prefUsrID); } } // -- IMEI number boolean editIMEI = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_IMEI)); if (editIMEI && !selDev.getImeiNumber().equals(imeiNum)) { selDev.setImeiNumber(imeiNum); } // -- Serial number boolean editSERIAL = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_SERIAL)); if (!selDev.getSerialNumber().equals(serialNum)) { selDev.setSerialNumber(serialNum); } // -- SIM phone number boolean editSIM = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_SIM)); if (editSIM && !selDev.getSimPhoneNumber().equals(simPhone)) { boolean uniqSimPhone = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_uniqueSimPhoneNumber,false); if (uniqSimPhone) { char sep = '/'; String devAcctID = selDev.getAccountID(); String devDevID = selDev.getDeviceID(); java.util.List<String> devList = Device.getDeviceIDsForSimPhoneNumber(simPhone,sep); // "account,device" int devListCnt = ListTools.size(devList); if (devListCnt <= 0) { // -- Ok. SIM phone number has not yet been assigned } else if (devListCnt == 1) { String acctDevID = devList.get(0); // "account,device" if (!acctDevID.equalsIgnoreCase(devAcctID + sep + devDevID)) { Print.logWarn("SIM Phone number ["+simPhone+"] already assigned: "+acctDevID); msg = i18n.getString("DeviceInfo.simPhoneNotUnique","SIM phone number is not unique: " + simPhone); selDev.setError(msg); simPhone = ""; } } else { // multiple occurances found String simAssignList = StringTools.join(devList,", "); Print.logWarn("SIM Phone number ["+simPhone+"] already assigned: "+simAssignList); msg = i18n.getString("DeviceInfo.simPhoneNotUnique","SIM phone number is not unique: " + simPhone); selDev.setError(msg); simPhone = ""; } } selDev.setSimPhoneNumber(simPhone); } // -- SMS EMail address boolean editSMSEm = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_SMS)); if (editSMSEm && !selDev.getSmsEmail().equals(smsEmail)) { // EMail.validateAddress(smsEmail) String se[] = StringTools.split(smsEmail,','); if (ListTools.size(se) > 0) { for (String s : se) { if (!StringTools.isBlank(s)) { // -- save first non-blank entry smsEmail = s; break; } } } selDev.setSmsEmail(smsEmail); } // -- Notes boolean notesOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showNotes,SHOW_NOTES); if (notesOK && !selDev.getNotes().equals(noteText)) { selDev.setNotes(noteText); } // -- Link URL/Description if (Device.supportsLinkURL()) { if (!selDev.getLinkURL().equals(linkURL)) { selDev.setLinkURL(linkURL); } if (!selDev.getLinkDescription().equals(linkDesc)) { selDev.setLinkDescription(linkDesc); } } // -- Fixed Latitude/Longitude if (Device.supportsFixedLocation()) { if ((fixedLat != 0.0) || (fixedLon != 0.0)) { selDev.setFixedLatitude(fixedLat); selDev.setFixedLongitude(fixedLon); } if (!selDev.getFixedAddress().equals(fixedAddr)) { selDev.setFixedAddress(fixedAddr); } if (!selDev.getFixedContactPhone().equals(fixedPhone)) { selDev.setFixedContactPhone(fixedPhone); } } // -- Ignition index boolean ignOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showIgnitionIndex,SHOW_IGNITION_NDX); if (ignOK && !StringTools.isBlank(ignition)) { String ign = ignition.toLowerCase(); int ignNdx = -1; if (ign.equalsIgnoreCase(IGNITION_notApplicable)) { ignNdx = -1; } else if (ign.equalsIgnoreCase(IGNITION_ignition)) { ignNdx = StatusCodes.IGNITION_INPUT_INDEX; } else if (ign.equalsIgnoreCase(IGNITION_startStop)) { ignNdx = StatusCodes.IGNITION_START_STOP; } else { ignNdx = StringTools.parseInt(ignition,-1); } selDev.setIgnitionIndex(ignNdx); // may also clear "lastIgnitionOnTime"/"lastIgnitionOffTime" } // -- speed limit boolean speedLimOK = Device.hasRuleFactory(); // || privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showSpeedLimit,SHOW_SPEED_LIMIT); double speedLimKPH = Account.getSpeedUnits(currAcct).convertToKPH(speedLimU); if (speedLimOK && (selDev.getSpeedLimitKPH() != speedLimKPH)) { selDev.setSpeedLimitKPH(speedLimKPH); } // -- Data Key boolean editDATKEY = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_DATKEY)); String dataKeyStr = privLabel.getStringProperty(PrivateLabel.PROP_DeviceInfo_showDataKey,SHOW_DATA_KEY); boolean dataKeyReq = "required".equalsIgnoreCase(dataKeyStr); boolean dataKeyOK = dataKeyReq || "true".equalsIgnoreCase(dataKeyStr); if (!editDATKEY || !dataKeyOK) { // -- we are not editing the dataKey } else if (dataKeyReq && StringTools.isBlank(dataKey)) { msg = i18n.getString("DeviceInfo.dataKeyRequired","Non-blank 'Data Key' entry required"); selDev.setError(msg); } else if (!selDev.getDataKey().equals(dataKey)) { // -- dataKey has changed selDev.setDataKey(dataKey); } // -- Pushpin ID boolean ppidOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showPushpinID,SHOW_PUSHPIN_ID); if (ppidOK && !selDev.getPushpinID().equals(pushpinID)) { selDev.setPushpinID(pushpinID); } // -- Display Color boolean dcolorOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDisplayColor,SHOW_DISPLAY_COLOR); if (dcolorOK && !selDev.getDisplayColor().equals(dispColor)) { selDev.setDisplayColor(dispColor); } // -- Reported Odometer boolean lastOdomOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showReportedOdometer,SHOW_REPORTED_ODOM); if (lastOdomOK && Device.supportsLastOdometer()) { // Domain.Properties.deviceInfo.showReportedOdometer=false if (rptOdom >= 0.0) { Account.DistanceUnits distUnits = Account.getDistanceUnits(currAcct); double rptOdomKM = distUnits.convertToKM(rptOdom); double lastOdomKM = selDev.getLastOdometerKM(); double offsetKM = rptOdomKM - lastOdomKM; if (Math.abs(offsetKM - selDev.getOdometerOffsetKM()) >= 0.1) { selDev.setOdometerOffsetKM(offsetKM); } } else if (rptOdom < 0.0) { selDev.setOdometerOffsetKM(0.0); } } // -- Reported EngineHours boolean lastEngHrsOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showReportedEngineHours,SHOW_REPORTED_ENG_HRS); if (lastEngHrsOK && Device.supportsLastEngineHours()) { // Domain.Properties.deviceInfo.showReportedEngineHours=false if (rptEngHrs >= 0.0) { double lastEngHrs = selDev.getLastEngineHours(); double offsetHrs = rptEngHrs - lastEngHrs; if (Math.abs(offsetHrs - selDev.getEngineHoursOffset()) >= 0.01) { selDev.setEngineHoursOffset(offsetHrs); } } } // -- Maintenance Interval if (Device.supportsPeriodicMaintenance()) { Account.DistanceUnits distUnits = Account.getDistanceUnits(currAcct); // -- Odometer Maintenance boolean maintOdomOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showMaintenanceOdometer,SHOW_MAINTENANCE_ODOM); if (maintOdomOK) { // Domain.Properties.deviceInfo.showMaintenanceOdometer=false // -- Odometer Maintenance #0 long mIntrvKM0 = AttributeTools.getRequestLong(request, PARM_MAINT_INTERVKM_0, 0L); double intrvKM0 = distUnits.convertToKM((double)mIntrvKM0); boolean mResetKM0 = !StringTools.isBlank(AttributeTools.getRequestString(request,PARM_MAINT_RESETKM_0,null)); selDev.setMaintIntervalKM0(intrvKM0); if (mResetKM0) { selDev.setMaintOdometerKM0(selDev.getLastOdometerKM()); } // -- Odometer Maintenance #1 long mIntrvKM1 = AttributeTools.getRequestLong(request, PARM_MAINT_INTERVKM_1, 0L); double intrvKM1 = distUnits.convertToKM((double)mIntrvKM1); boolean mResetKM1 = !StringTools.isBlank(AttributeTools.getRequestString(request,PARM_MAINT_RESETKM_1,null)); selDev.setMaintIntervalKM1(intrvKM1); if (mResetKM1) { selDev.setMaintOdometerKM1(selDev.getLastOdometerKM()); } } // -- EngineHours Maintenane #0 boolean maintHoursOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showMaintenanceHours,SHOW_MAINTENANCE_HOURS); if (maintHoursOK) { // Domain.Properties.deviceInfo.showMaintenanceHours=false double mIntrvHR0 = AttributeTools.getRequestDouble(request, PARM_MAINT_INTERVHR_0, 0.0); double intrvHR0 = mIntrvHR0; boolean mResetHR0 = !StringTools.isBlank(AttributeTools.getRequestString(request,PARM_MAINT_RESETHR_0,null)); selDev.setMaintIntervalHR0(intrvHR0); if (mResetHR0) { double lastEngHrs = selDev.getLastEngineHours(); selDev.setMaintEngHoursHR0(lastEngHrs); } } // -- maintenance notes boolean maintNotesOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showMaintenanceNotes,SHOW_MAINTENANCE_NOTES); if (maintNotesOK) { // Domain.Properties.deviceInfo.showMaintenanceNotes=false String maintText = AttributeTools.getRequestString(request, PARM_MAINT_NOTES , ""); if (!selDev.getMaintNotes().equals(maintText)) { selDev.setMaintNotes(maintText); } } // -- reminder interval boolean reminderOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showReminderMessage,SHOW_REMINDER_MESSAGE); if (reminderOK) { // Domain.Properties.deviceInfo.showReminderMessage=false // -- reminder interval String remIntrv = AttributeTools.getRequestString(request, PARM_REMIND_INTERVAL, ""); if (!selDev.getReminderInterval().equals(remIntrv)) { selDev.setReminderInterval(remIntrv); } // -- reminder message String remMsg = AttributeTools.getRequestString(request, PARM_REMIND_MESSAGE, ""); if (!selDev.getReminderMessage().equals(remMsg)) { selDev.setReminderMessage(remMsg); } } // -- service time boolean servTimeOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showServiceTime,SHOW_SERVICE_TIME); if (servTimeOK) { // Domain.Properties.deviceInfo.showServiceTime=false DateTime.DateStringFormat dsf = privLabel.getDateStringFormat(); TimeZone tmz = Account.getTimeZone(selDev.getAccount(),DateTime.getGMTTimeZone()); String lastServ = AttributeTools.getRequestString(request, PARM_LAST_SERVICE_TIME, ""); long lastServTS = GetEpochTimeDayEnd(dsf, lastServ, tmz); selDev.setLastServiceTime(lastServTS); // saved as epoch timestamp String nextServ = AttributeTools.getRequestString(request, PARM_NEXT_SERVICE_TIME, ""); long nextServTS = GetEpochTimeDayStart(dsf, nextServ, tmz); selDev.setNextServiceTime(nextServTS); // saved as epoch timestamp } } // -- hours of operation boolean workHoursOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showHoursOfOperation,SHOW_HOURS_OF_OPERATION); if (workHoursOK && Device.supportsHoursOfOperation()) { // Domain.Properties.deviceInfo.showHoursOfOperation=false String whStr = AttributeTools.getRequestString(request, PARM_HOURS_OF_OPERATION, ""); if (!whStr.equals(selDev.getHoursOfOperation())) { selDev.setHoursOfOperation(whStr); } } // -- Reset Fault codes boolean faultCodesOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showFaultCodes,SHOW_FAULT_CODES); if (faultCodesOK && Device.supportsFaultCodes()) { boolean fReset = !StringTools.isBlank(AttributeTools.getRequestString(request,PARM_FAULT_RESET,null)); if (fReset) { Print.logInfo("Resetting Fault Codes ..."); selDev.setLastFaultCode(null); // clear fault codes selDev.setLastMalfunctionLamp(false); // clear MIL indicator } } // -- Rule Engine Notification if (_showNotificationFields(privLabel)) { String ruleAllow = AttributeTools.getRequestString( request, PARM_DEV_RULE_ALLOW , null); // "Notify Enable" String notifyEmail = AttributeTools.getRequestString( request, PARM_DEV_RULE_EMAIL , null); boolean alertReset = AttributeTools.getRequestCheckbox(request, PARM_LAST_ALERT_RESET); String ruleSel = AttributeTools.getRequestString( request, PARM_DEV_RULE_SEL , null); String ruleDesc = AttributeTools.getRequestString( request, PARM_DEV_RULE_DESC , null); String ruleSubj = AttributeTools.getRequestString( request, PARM_DEV_RULE_SUBJ , null); String ruleText = AttributeTools.getRequestString( request, PARM_DEV_RULE_TEXT , null); //String ruleWrap = AttributeTools.getRequestString( request, PARM_DEV_RULE_WRAP , null); // -- Allow Notification boolean allowNtfy = ComboOption.parseYesNoText(locale, ruleAllow, true); if (selDev.getAllowNotify() != allowNtfy) { selDev.setAllowNotify(allowNtfy); } // -- Notification email if (notifyEmail != null) { String devNE = selDev.getNotifyEmail(); // no acct/user email if (StringTools.isBlank(notifyEmail)) { if (!devNE.equals(notifyEmail)) { selDev.setNotifyEmail(notifyEmail); } } else if (EMail.validateAddresses(notifyEmail,true)) { if (!devNE.equals(notifyEmail)) { selDev.setNotifyEmail(notifyEmail); } } else { msg = i18n.getString("DeviceInfo.enterEMail","Please enter a valid notification email/sms address"); selDev.setError(msg); } } // -- notification selector if (ruleSel != null) { if (DeviceInfo.ShowNotifySelector() && !Device.CheckSelectorSyntax(ruleSel)) { Print.logInfo("Notification selector has a syntax error: " + ruleSel); msg = i18n.getString("DeviceInfo.ruleError","Notification rule contains a syntax error"); selDev.setError(msg); } else { // -- update rule selector (if changed) if (!selDev.getNotifySelector().equals(ruleSel)) { selDev.setNotifySelector(ruleSel); } //selDev.setAllowNotify(!StringTools.isBlank(ruleSel)); } } // -- notification description if (ruleDesc != null) { if (!selDev.getNotifyDescription().equals(ruleDesc)) { selDev.setNotifyDescription(ruleDesc); } } // -- notification subject if (ruleSubj != null) { if (!selDev.getNotifySubject().equals(ruleSubj)) { selDev.setNotifySubject(ruleSubj); } } // -- notification message if (ruleText != null) { if (!selDev.getNotifyText().equals(ruleText)) { selDev.setNotifyText(ruleText); } } // -- notify wrapper boolean ntfyWrap = false; // ComboOption.parseYesNoText(locale, ruleWrap, true); if (selDev.getNotifyUseWrapper() != ntfyWrap) { selDev.setNotifyUseWrapper(ntfyWrap); } // -- last-notify-time reset if ((selDev.getLastNotifyTime() != 0L) && alertReset) { selDev.clearLastNotifyEvent(false/*nosave*/); } } // -- Active Corridor if (Device.hasENRE() && Device.supportsActiveCorridor()) { if (!selDev.getActiveCorridor().equals(actvCorr)) { selDev.setActiveCorridor(actvCorr); } } // -- BorderCrossing if (acctBCEnabled && Device.supportsBorderCrossing()) { int bcState = ComboOption.parseYesNoText(locale,borderCross,true)? Device.BorderCrossingState.ON.getIntValue() : Device.BorderCrossingState.OFF.getIntValue(); if (selDev.getBorderCrossing() != bcState) { selDev.setBorderCrossing(bcState); } } // -- WorkOrder ID /* if (_showWorkOrderID(privLabel)) { if (!selDev.getWorkOrderID().equals(worderID)) { selDev.setWorkOrderID(worderID); } } */ // -- DCS properties ID boolean showDCSPropID = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDcsPropertiesID,SHOW_DCS_PROPERTIES_ID); if (showDCSPropID) { if (!selDev.getDcsPropertiesID().equals(dcsPropsID)) { selDev.setDcsPropertiesID(dcsPropsID); } } // -- DCS config string boolean showDCSCfgStr = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDcsConfigString,SHOW_DCS_CONFIG_STRING); if (showDCSCfgStr) { if (!selDev.getDcsConfigString().equals(dcsCfgStr)) { selDev.setDcsConfigString(dcsCfgStr); } } // -- Fixed TCP Session ID boolean showTcpSessID = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showStaticTcpSessionID,SHOW_FIXED_TCP_SESSION_ID); if (showTcpSessID) { if (!selDev.getFixedTcpSessionID().equals(tcpSessID)) { selDev.setFixedTcpSessionID(tcpSessID); } } // -- Enable Driver ELogs if (Account.IsELogEnabled(selDev.getAccount())) { boolean elogEnable = ComboOption.parseYesNoText(locale, enELogStr, false); if (selDev.getELogEnabled() != elogEnable) { selDev.setELogEnabled(elogEnable); } } // -- Preferred Group ID [PARM_GROUP_ID] String skipGrpID = null; boolean showPrefGrp = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showPreferredGroupID,SHOW_PREFERRED_GROUP); if (showPrefGrp) { if (DeviceGroup.DEVICE_GROUP_ALL.equalsIgnoreCase(prefGrpID)) { prefGrpID = ""; // "all" ==> "" } //Print.logInfo("Preferred groupID: " + prefGrpID); if (selDev.getGroupID().equals(prefGrpID)) { // -- already the same groupID, skip //Print.logInfo("Preferred groupID already matched Device"); prefGrpID = ""; } else if (StringTools.isBlank(prefGrpID)) { // -- clear groupID //Print.logInfo("Clearing Preferred GroupID ..."); selDev.setGroupID(prefGrpID); } else { // -- make sure that the current user is authorized for the group "prefGrpID" DeviceGroup dg = DeviceGroup.getDeviceGroup(currAcct, prefGrpID); OrderedSet<String> dgList = reqState.getDeviceGroupIDList(false); // user groups if (dg == null) { Print.logError("DeviceGroup does not exist: " + prefGrpID); prefGrpID = ""; } else if (!dgList.contains(prefGrpID)) { Print.logError("User is not authorized to DeviceGroup: " + prefGrpID); prefGrpID = ""; } else { // -- preferred groupID //Print.logInfo("Setting current Device Preferred GroupID: " + prefGrpID); selDev.setGroupID(prefGrpID); boolean addGroupEntry = showPrefGrp && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_addToPreferredGroup,ADD_TO_PREFERRED_GROUP); if (addGroupEntry) { // -- add a group entry for this group try { //Print.logInfo("Adding current Device to Group: " + prefGrpID); dg.addDeviceToDeviceGroup(selDev); skipGrpID = prefGrpID; } catch (DBException dbe) { // Print.logException("Unable to add current Device to preferred group", dbe); } } else { //Print.logInfo("Not adding current Device to Group: " + prefGrpID); } } } } else { prefGrpID = ""; } // -- Subscriber info if (_showSubscriberInfo(privLabel)) { String subsID = AttributeTools.getRequestString(request, PARM_SUBSCRIBE_ID , null); String subsName = AttributeTools.getRequestString(request, PARM_SUBSCRIBE_NAME , null); String subsAvat = AttributeTools.getRequestString(request, PARM_SUBSCRIBE_AVATAR, null); selDev.setSubscriberID(subsID); selDev.setSubscriberName(subsName); selDev.setSubscriberAvatar(subsAvat); } // -- DeviceGroups if (!selDev.hasError()) { String accountID = selDev.getAccountID(); String deviceID = selDev.getDeviceID(); // -- 'grpKey' may only contain 'checked' items! OrderedSet<String> fullGroupSet = reqState.getDeviceGroupIDList(true); // -- add checked groups if (!ListTools.isEmpty(grpKeys)) { for (int i = 0; i < grpKeys.length; i++) { String grpID = grpKeys[i].substring(PARM_DEV_GROUP_.length()); //Print.logInfo("Checking GroupID: " + grpID); if (grpID.equalsIgnoreCase(DeviceGroup.DEVICE_GROUP_ALL)) { // -- skip Group "ALL" } else if (!StringTools.isBlank(skipGrpID) && skipGrpID.equals(grpID)) { // -- "grpID" already handled } else { String chkStr = AttributeTools.getRequestString(request,grpKeys[i],""); boolean chked = chkStr.equalsIgnoreCase("on"); boolean exists = DeviceGroup.isDeviceInDeviceGroup(accountID, grpID, deviceID); //Print.logInfo("Checking group : " + grpID + " [checked=" + chked + "]"); if (chked) { if (!exists) { DeviceGroup.addDeviceToDeviceGroup(accountID, grpID, deviceID); groupsChg = true; } } else { if (exists) { DeviceGroup.removeDeviceFromDeviceGroup(accountID, grpID, deviceID); groupsChg = true; } } fullGroupSet.remove(grpID); } } } // -- delete remaining (unchecked) groups for (Iterator<String> i = fullGroupSet.iterator(); i.hasNext();) { String grpID = i.next(); if (grpID.equalsIgnoreCase(DeviceGroup.DEVICE_GROUP_ALL)) { // -- skip Group "ALL" } else if (!StringTools.isBlank(skipGrpID) && skipGrpID.equals(grpID)) { // -- "grpID" already handled } else { boolean exists = DeviceGroup.isDeviceInDeviceGroup(accountID, grpID, deviceID); //Print.logInfo("Removing group: " + grpID + " [" + exists + "]"); if (exists) { DeviceGroup.removeDeviceFromDeviceGroup(accountID, grpID, deviceID); groupsChg = true; } } } } // -- Custom Attributes if (!ListTools.isEmpty(cstKeys)) { String oldCustAttr = selDev.getCustomAttributes(); RTProperties rtp = selDev.getCustomAttributesRTP(); for (int i = 0; i < cstKeys.length; i++) { String cstKey = cstKeys[i]; String rtpVal = AttributeTools.getRequestString(request, cstKey, ""); String rtpKey = cstKey.substring(PARM_DEV_CUSTOM_.length()); rtp.setString(rtpKey, rtpVal); } String rtpStr = rtp.toString(); if (!rtpStr.equals(oldCustAttr)) { //Print.logInfo("Setting custom attributes: " + rtpStr); selDev.setCustomAttributes(rtpStr); } } // -- save if (selDev.hasError()) { // -- should stay on same page Print.logInfo("An error occured during Edit ..."); } else if (selDev.hasChanged()) { selDev.save(); msg = i18n.getString("DeviceInfo.updatedDevice","{0} information updated", devTitles); } else if (groupsChg) { String grpTitles[] = reqState.getDeviceGroupTitles(); msg = i18n.getString("DeviceInfo.updatedDeviceGroups","{0} membership updated", grpTitles); } else { // -- nothing changed Print.logInfo("Nothing has changed for this Device ..."); } } catch (Throwable t) { Print.logException("Updating Device", t); msg = i18n.getString("DeviceInfo.errorUpdate","Internal error updating {0}", devTitles); selDev.setError(msg); } return msg; } // ------------------------------------------------------------------------ /* write html */ public void writePage( final RequestProperties reqState, String pageMsg) throws IOException { final HttpServletRequest request = reqState.getHttpServletRequest(); final boolean sysadminLogin = reqState.isLoggedInFromSysAdmin(); final PrivateLabel privLabel = reqState.getPrivateLabel(); final I18N i18n = privLabel.getI18N(DeviceInfo.class); final Locale locale = reqState.getLocale(); final String devTitles[] = reqState.getDeviceTitles(); final String grpTitles[] = reqState.getDeviceGroupTitles(); final Account currAcct = reqState.getCurrentAccount(); // should not be null final String currAcctID = reqState.getCurrentAccountID(); final User currUser = reqState.getCurrentUser(); // may be null final String pageName = this.getPageName(); final boolean acctBCEnabled = ((currAcct!=null)&&currAcct.getIsBorderCrossing())?true:false; final TimeZone acctTimeZone = Account.getTimeZone(currAcct,DateTime.getGMTTimeZone()); String m = pageMsg; boolean error = false; String cmdBtnTitle = i18n.getString("DeviceInfo.commands","Commands"); // included here to maintain I18N string /* device */ OrderedSet<String> devList = reqState.getDeviceIDList(true/*inclInactv*/); if (devList == null) { devList = new OrderedSet<String>(); } Device selDev = reqState.getSelectedDevice(); boolean actualDev = reqState.isActualSpecifiedDevice(); String selDevID = (selDev != null)? selDev.getDeviceID() : ""; /* new/delete device creation */ final int allowNewDevMode = this._allowNewDevice(currAcct, privLabel); final int allowDelDevMode = this._allowDeleteDevice(currAcct, privLabel); boolean allowNew = privLabel.hasAllAccess(currUser,this.getAclName()); boolean allowDelete = allowNew; int overDevLimit = -1; // undefined boolean allowNewZeroUnl = true; // -- check "New" if (!allowNew) { // -- already denied per ACL Print.logInfo("Allow New Device? Deny - per ACL"); } else if (currAcct == null) { // -- null account (should not be null) Print.logInfo("Allow New Device? Deny - current account is null"); allowNew = false; allowDelete = false; } else if (allowNewDevMode == DEVMODE_DENY) { // -- explicitly denied Print.logInfo("Allow New Device: Deny - per '"+PrivateLabel.PROP_DeviceInfo_allowNewDevice+"' property"); allowNew = false; allowDelete = false; } else if (allowNewDevMode == DEVMODE_SYSADMIN) { if (!sysadminLogin) { // -- allow only if currently logged in from sysadmin "System Accounts" Print.logInfo("Allow New Device? Deny - not SysAdmin login"); allowNew = false; allowDelete = false; } } else if (allowNewDevMode == DEVMODE_MANAGER) { if (!Account.isAccountManager(currAcct) && !Account.isSystemAdmin(currAcct)) { // -- allow only if AccountManager or SystemAdmin Print.logInfo("Allow New Device? Deny - not AccountManager"); allowNew = false; allowDelete = false; } } else if (allowNewDevMode == DEVMODE_MAXLIMIT) { allowNewZeroUnl = false; if (sysadminLogin) { // -- no max limit } else if (currAcct.isAtMaximumDevices(false)) { // -- over device limit Print.logInfo("Allow New Device: Deny - at maximum devices, per '"+PrivateLabel.PROP_DeviceInfo_allowNewDevice+"' property"); overDevLimit = 1; //allowNew = false; //allowDelete = false; <== leave as-is (allow delete, for now) } else { // -- not over device limit overDevLimit = 0; } } else if (allowNewDevMode == DEVMODE_ALLOW) { if (sysadminLogin) { // -- no max limit } else if (currAcct.isAtMaximumDevices(true/*0=unlim*/)) { // -- over device limit Print.logInfo("Allow New Device? Deny - over limit"); overDevLimit = 1; //allowNew = false; //allowDelete = false; <== leave as-is (allow delete, for now) } else { // -- not over device limit overDevLimit = 0; } } // -- check "Delete" if (!allowDelete) { Print.logInfo("Allow Delete Device? Deny - per ACL/New"); } else if (allowDelDevMode == DEVMODE_DENY) { // -- explicitly denied Print.logInfo("Allow Delete Device: Deny - per '"+PrivateLabel.PROP_DeviceInfo_allowDeleteDevice+"' property"); allowDelete = false; } else if (allowDelDevMode == DEVMODE_SYSADMIN) { if (!sysadminLogin) { // -- allow only if currently logged in from sysadmin "System Accouts" Print.logInfo("Allow Delete Device? Deny - not SysAdmin login"); allowDelete = false; } } else if (allowDelDevMode == DEVMODE_MANAGER) { if (!Account.isAccountManager(currAcct) && !Account.isSystemAdmin(currAcct)) { // -- allow only if AccountManager or SystemAdmin Print.logInfo("Allow Delete Device? Deny - not AccountManager"); allowDelete = false; } } /* ACL allow edit/view */ boolean allowEdit = allowNew || privLabel.hasWriteAccess(currUser, this.getAclName()); boolean allowView = allowEdit || privLabel.hasReadAccess(currUser, this.getAclName()); /* "Commands"("Properties") */ boolean allowCommand = (currAcct != null) && allowView && privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_COMMANDS)) && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showPropertiesButton,true); if (Print.isDebugLoggingLevel()) { if (allowCommand) { Print.logInfo("Commands: Allow Commands: " + allowCommand); } else { StringBuffer sb = new StringBuffer(); if (!(currAcct != null)) { sb.append("-Account"); } if (!allowView) { sb.append("-View"); } if (!privLabel.hasWriteAccess(currUser,this.getAclName(_ACL_COMMANDS))) { sb.append("-ACL"); } if (!privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showPropertiesButton,true)) { sb.append("-Show"); } Print.logWarn("Commands: Allow Commands: " + allowCommand + " ["+sb+"]"); } } /* "SMS" Commands */ DeviceInfo._initDeviceCommandHandlers(); // initialize to pick up SMS command button [2.6.1-B21] boolean allowSmsCmd = (currAcct != null) && currAcct.getSmsEnabled() && allowView && privLabel.hasWriteAccess(currUser,this.getAclName(_ACL_SMS)) && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showSmsButton,false) && (SMSCommandHandler != null) && SMSCommandHandler.hasSmsCommands(reqState); // DeviceCmd_SMS if (Print.isDebugLoggingLevel()) { if (allowSmsCmd) { Print.logInfo("Commands: Allow SMS Commands: " + allowSmsCmd); } else { StringBuffer sb = new StringBuffer(); if (!(currAcct != null)) { sb.append("-Account"); } if (!((currAcct != null) && currAcct.getSmsEnabled())) { sb.append("-Enabled"); } if (!allowView) { sb.append("-View"); } if (!privLabel.hasWriteAccess(currUser,this.getAclName(_ACL_SMS))) { sb.append("-ACL"); } if (!privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showSmsButton,false)) { sb.append("-Show"); } if (!(SMSCommandHandler != null)) { sb.append("-Null"); } if (!((SMSCommandHandler != null) && SMSCommandHandler.hasSmsCommands(reqState))) { sb.append("-SMS"); } Print.logWarn("Commands: Allow SMS commands: " + allowSmsCmd + " ["+sb+"]"); } } /* submit buttons */ String submitEdit = AttributeTools.getRequestString(request, PARM_SUBMIT_EDIT, ""); String submitView = AttributeTools.getRequestString(request, PARM_SUBMIT_VIEW, ""); String submitChange = AttributeTools.getRequestString(request, PARM_SUBMIT_CHG , ""); String submitNew = AttributeTools.getRequestString(request, PARM_SUBMIT_NEW , ""); String submitDelete = AttributeTools.getRequestString(request, PARM_SUBMIT_DEL , ""); String submitQueue = AttributeTools.getRequestString(request, PARM_SUBMIT_QUE , ""); String submitProps = AttributeTools.getRequestString(request, PARM_SUBMIT_PROP, ""); String submitSms = AttributeTools.getRequestString(request, PARM_SUBMIT_SMS , ""); /* ACL view/edit */ boolean editServID = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_SERVERID )); boolean viewServID = editServID || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_SERVERID )); boolean editCodeVer = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FIRMWARE )); boolean viewCodeVer = editCodeVer || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_FIRMWARE )); boolean editUniqID = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_UNIQUEID )); boolean viewUniqID = editUniqID || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_UNIQUEID )); boolean editActive = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_ACTIVE )); boolean viewActive = editActive || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_ACTIVE )); boolean editExpire = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EXPIRE )); boolean viewExpire = editExpire || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_EXPIRE )); boolean editShare = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_SHARE )); boolean viewShare = editShare || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_SHARE )); boolean editRules = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_RULES )); boolean viewRules = editRules || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_RULES )); boolean editSMSEm = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_SMS )); boolean viewSMSEm = editSMSEm || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_EDIT_SMS )); boolean editSIM = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_SIM )); boolean viewSIM = editSIM || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_EDIT_SIM )); boolean editEqStat = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_EQSTAT )); boolean viewEqStat = editEqStat || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_EDIT_EQSTAT )); boolean editIMEI = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_IMEI )); boolean viewIMEI = editIMEI || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_EDIT_IMEI )); boolean editSERIAL = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_SERIAL )); boolean viewSERIAL = editSERIAL || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_EDIT_SERIAL )); boolean editDATKEY = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_EDIT_DATKEY )); boolean viewDATKEY = editDATKEY || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_EDIT_DATKEY )); boolean editFuelCap = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_CAPACITY)); boolean viewFuelCap = editFuelCap || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_FUEL_CAPACITY)); boolean editFuelPrf = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_PROFILE )); boolean viewFuelPrf = editFuelPrf || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_FUEL_PROFILE )); boolean editFuelEco = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_ECONOMY )); boolean viewFuelEco = editFuelEco || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_FUEL_ECONOMY )); boolean editFuelCst = sysadminLogin || privLabel.hasWriteAccess(currUser, this.getAclName(_ACL_FUEL_ECONOMY )); boolean viewFuelCst = editFuelCst || privLabel.hasReadAccess( currUser, this.getAclName(_ACL_FUEL_ECONOMY )); /* command */ String deviceCmd = reqState.getCommandName(); //boolean refreshList = deviceCmd.equals(COMMAND_INFO_REFRESH); boolean selectDevice = deviceCmd.equals(COMMAND_INFO_SEL_DEVICE); boolean newDevice = deviceCmd.equals(COMMAND_INFO_NEW_DEVICE); boolean updateDevice = deviceCmd.equals(COMMAND_INFO_UPD_DEVICE); boolean sendCommand = deviceCmd.equals(COMMAND_INFO_UPD_PROPS); boolean updateSms = deviceCmd.equals(COMMAND_INFO_UPD_SMS); boolean deleteDevice = false; /* ui display */ boolean uiList = false; boolean uiEdit = false; boolean uiView = false; boolean uiCmd = false; boolean uiSms = false; /* DeviceCmdHandler */ DeviceCmdHandler dcHandler = null; /* pre-qualify commands */ String newDeviceID = null; if (newDevice) { if (!allowNew) { newDevice = false; // not authorized } else if (overDevLimit > 0) { newDevice = false; // over limit } else { if (allowNewDevMode == DEVMODE_SYSADMIN) { // -- TODO: need to check some "Create Device Password" field } HttpServletRequest httpReq = reqState.getHttpServletRequest(); newDeviceID = AttributeTools.getRequestString(httpReq,PARM_NEW_NAME,"").trim(); newDeviceID = newDeviceID.toLowerCase(); if (StringTools.isBlank(newDeviceID)) { m = i18n.getString("DeviceInfo.enterNewDevice","Please enter a new {0} ID.", devTitles); // UserErrMsg error = true; newDevice = false; } else if (!WebPageAdaptor.isValidID(reqState,/*PrivateLabel.PROP_DeviceInfo_validateNewIDs,*/newDeviceID)) { m = i18n.getString("DeviceInfo.invalidIDChar","ID contains invalid characters"); // UserErrMsg error = true; newDevice = false; } } } else if (updateDevice) { if (!allowEdit) { updateDevice = false; // not authorized } else if (!SubmitMatch(submitChange,i18n.getString("DeviceInfo.change","Change"))) { updateDevice = false; } else if (selDev == null) { // should not occur m = i18n.getString("DeviceInfo.unableToUpdate","Unable to update Device, ID not found"); // UserErrMsg error = true; updateDevice = false; } } else if (sendCommand) { if (!allowCommand) { sendCommand = false; // not authorized } else if (!SubmitMatch(submitQueue,i18n.getString("DeviceInfo.queue","Queue"))) { sendCommand = false; // button not pressed } else if (selDev == null) { m = i18n.getString("DeviceInfo.pleaseSelectDevice","Please select a {0}", devTitles); // UserErrMsg error = true; sendCommand = false; // no device selected } else if (StringTools.isBlank(selDev.getDeviceCode())) { Print.logInfo("DeviceCode/ServerID is blank"); sendCommand = false; } else { dcHandler = this.getDeviceCommandHandler(selDev.getDeviceCode()); if (dcHandler == null) { Print.logWarn("DeviceCmdHandler not found: " + selDev.getDeviceCode()); sendCommand = false; // not found } else if (!dcHandler.deviceSupportsCommands(selDev)) { Print.logWarn("DeviceCode/ServerID not supported by handler: " + selDev.getDeviceCode()); sendCommand = false; // not supported } } } else if (updateSms) { if (!allowSmsCmd) { updateSms = false; // not authorized } else if (!SubmitMatch(submitQueue,i18n.getString("DeviceInfo.queue","Queue"))) { updateSms = false; // button not pressed } else if (selDev == null) { m = i18n.getString("DeviceInfo.pleaseSelectDevice","Please select a {0}", devTitles); // UserErrMsg error = true; updateSms = false; // no device selected //} else //if (StringTools.isBlank(selDev.getDeviceCode())) { // Print.logInfo("DeviceCode/ServerID is blank"); // updateSms = false; } else { dcHandler = SMSCommandHandler; if (dcHandler == null) { Print.logWarn("SMS DeviceCmdHandler not found"); updateSms = false; // not found } else if (!dcHandler.deviceSupportsCommands(selDev)) { Print.logWarn("DeviceCode/ServerID not supported by handler: " + selDev.getDeviceCode()); updateSms = false; // not supported } } } else if (selectDevice) { if (SubmitMatch(submitDelete,i18n.getString("DeviceInfo.delete","Delete"))) { if (!allowDelete) { deleteDevice = false; // not authorized } else if (selDev == null) { m = i18n.getString("DeviceInfo.pleaseSelectDevice","Please select a {0}", devTitles); // UserErrMsg error = true; deleteDevice = false; // not selected } else if (!actualDev) { // -- "selDev" is not the actual selected device (possibly due to invalid deviceID?) m = i18n.getString("DeviceInfo.unableToDelete","Unable to delete selected {0}", devTitles); // UserErrMsg error = true; deleteDevice = false; // not selected } else { deleteDevice = true; } } else if (SubmitMatch(submitEdit,i18n.getString("DeviceInfo.edit","Edit"))) { if (!allowEdit) { uiEdit = false; // not authorized } else if (selDev == null) { m = i18n.getString("DeviceInfo.pleaseSelectDevice","Please select a {0}", devTitles); // UserErrMsg error = true; uiEdit = false; // not selected } else { uiEdit = true; } } else if (SubmitMatch(submitView,i18n.getString("DeviceInfo.view","View"))) { if (!allowView) { uiView = false; // not authorized } else if (selDev == null) { m = i18n.getString("DeviceInfo.pleaseSelectDevice","Please select a {0}", devTitles); // UserErrMsg error = true; uiView = false; // not selected } else { uiView = true; } } else if (SubmitMatch(submitProps,i18n.getString("DeviceInfo.properties","Commands"))) { if (!allowCommand) { uiCmd = false; // not authorized } else if (selDev == null) { m = i18n.getString("DeviceInfo.pleaseSelectDevice","Please select a {0}", devTitles); // UserErrMsg error = true; uiCmd = false; // not selected } else { String dcsName = selDev.getDeviceCode(); dcHandler = this.getDeviceCommandHandler(dcsName); if (dcHandler == null) { if (StringTools.isBlank(dcsName)) { Print.logWarn("ServerID is blank"); m = i18n.getString("DeviceInfo.deviceCommandsNotDefined","Unknown {0} type (blank)", devTitles); // UserErrMsg } else { Print.logWarn("DeviceCmdHandler not found: " + dcsName); m = i18n.getString("DeviceInfo.deviceCommandsNotFound","{0} not supported", devTitles); // UserErrMsg } error = true; uiCmd = false; // not supported / blank } else if (!dcHandler.deviceSupportsCommands(selDev)) { Print.logWarn("ServerID does not support Device commands: " + dcsName); m = i18n.getString("DeviceInfo.deviceCommandsNotSupported","{0} Commands not supported", devTitles); // UserErrMsg error = true; uiCmd = false; // not supported } else { uiCmd = true; } } } else if (SubmitMatch(submitSms,i18n.getString("DeviceInfo.sms","SMS"))) { if (!allowSmsCmd) { uiSms = false; // not authorized } else if (selDev == null) { m = i18n.getString("DeviceInfo.pleaseSelectDevice","Please select a {0}", devTitles); // UserErrMsg error = true; uiSms = false; // not selected } else { dcHandler = SMSCommandHandler; if (dcHandler == null) { Print.logWarn("SMS DeviceCmdHandler not found: " + currAcctID + "/" + selDevID); m = i18n.getString("DeviceInfo.deviceSmsNotSupported","{0} SMS not supported", devTitles); // UserErrMsg error = true; uiSms = false; // not supported } else if (!dcHandler.deviceSupportsCommands(selDev)) { Print.logWarn("SMS not supported by device: " + currAcctID + "/" + selDevID); m = i18n.getString("DeviceInfo.deviceSmsNotSupported","{0} SMS not supported", devTitles); // UserErrMsg error = true; uiSms = false; // not supported } else { uiSms = true; } } } } /* delete device? */ if (deleteDevice) { // -- 'selDev' guaranteed non-null here try { // -- delete device Device.Key devKey = (Device.Key)selDev.getRecordKey(); Print.logWarn("Deleting Device: " + devKey); devKey.delete(true); // will also delete dependencies selDevID = ""; selDev = null; actualDev = false; reqState.clearDeviceList(); // -- select another device devList = reqState.getDeviceIDList(true/*inclInactv*/); if (!ListTools.isEmpty(devList)) { selDevID = devList.get(0); try { selDev = !selDevID.equals("")? Device.getDevice(currAcct,selDevID) : null; // null if non-existent } catch (DBException dbe) { // -- ignore } } // -- still over limit? if ((overDevLimit > 0) && !currAcct.isAtMaximumDevices(allowNewDevMode == DEVMODE_ALLOW)) { overDevLimit = 0; // no, no longer over limit } } catch (DBException dbe) { Print.logException("Deleting Device", dbe); m = i18n.getString("DeviceInfo.errorDelete","Internal error deleting {0}", devTitles); // UserErrMsg error = true; } uiList = true; } /* new device? */ if (newDevice) { boolean createDeviceOK = true; for (int d = 0; d < devList.size(); d++) { if (newDeviceID.equalsIgnoreCase(devList.get(d))) { m = i18n.getString("DeviceInfo.alreadyExists","This {0} already exists", devTitles); // UserErrMsg error = true; createDeviceOK = false; break; } } if (createDeviceOK) { try { // -- create device Device device = Device.createNewDevice(currAcct, newDeviceID, null); // also saves selDev = device; selDevID = device.getDeviceID(); // -- add device to Users first authorized group boolean addDevToUsrGrp = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_addDeviceToUserAuthGroup,ADD_DEV_TO_USER_AUTH_GROUP); if (addDevToUsrGrp && (currUser != null)) { String groupID = currUser.getFirstDeviceGroupID(); if (!StringTools.isBlank(groupID) && !groupID.equalsIgnoreCase(DeviceGroup.DEVICE_GROUP_ALL)) { try { DeviceGroup.addDeviceToDeviceGroup(currAcctID, groupID, selDevID); Print.logInfo("Device '"+currAcctID+"/"+selDevID+"' added to group: "+groupID); } catch (DBException dbe) { Print.logException("Adding Device to DeviceGroup: " + currAcctID + "/" + groupID, dbe); // -- ignore } } } // -- update device list reqState.clearDeviceList(); devList = reqState.getDeviceIDList(true/*inclInactv*/); // -- now over limit? if ((overDevLimit == 0) && currAcct.isAtMaximumDevices(allowNewDevMode == DEVMODE_ALLOW)) { overDevLimit = 1; // yes, now over limit } // -- message //m = i18n.getString("DeviceInfo.createdUser","New {0} has been created", devTitles); // UserErrMsg m = i18n.getString("DeviceInfo.createdDevice","New {0} has been created", devTitles); // UserErrMsg } catch (DBAlreadyExistsException dbaee) { Print.logError("Device already exists: " + currAcct + "/" + newDeviceID); m = i18n.getString("DeviceInfo.alreadyExists","This {0} already exists", devTitles); // UserErrMsg error = true; } catch (DBException dbe) { Print.logException("Creating Device", dbe); m = i18n.getString("DeviceInfo.errorCreate","Internal error creating {0}", devTitles); // UserErrMsg error = true; } } uiList = true; } /* update the device info? */ if (updateDevice) { // -- 'selDev' guaranteed non-null here selDev.clearChanged(); m = _updateDeviceTable(reqState); if (selDev.hasError()) { // -- stay on this page uiEdit = true; } else { uiList = true; } } /* send command */ if (sendCommand) { // 'selDev' and 'dcHandler' guaranteed non-null here m = dcHandler.handleDeviceCommands(reqState, selDev); Print.logInfo("Returned Message: " + m); error = true; uiList = true; } /* update SMS */ if (updateSms) { // 'selDev' and 'dcHandler' guaranteed non-null here m = dcHandler.handleDeviceCommands(reqState, selDev); Print.logInfo("Returned Message: " + m); error = true; uiList = true; } /* last event from device */ try { EventData evd[] = (selDev != null)? selDev.getLatestEvents(1L,false) : null; if ((evd != null) && (evd.length > 0)) { reqState.setLastEventTime(new DateTime(evd[0].getTimestamp())); } } catch (DBException dbe) { // ignore } /* config */ final boolean showPushpinChooser = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showPushpinChooser,SHOW_PUSHPIN_CHOOSER); final boolean showDateCal = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDateCalendar,SHOW_DATE_CALENDAR); final boolean showServiceID = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showServiceID,SHOW_SERVICE_ID); /* Style */ HTMLOutput HTML_CSS = new HTMLOutput() { public void write(PrintWriter out) throws IOException { String cssDir = DeviceInfo.this.getCssDirectory(); WebPageAdaptor.writeCssLink(out, reqState, "DeviceInfo.css", cssDir); if (showDateCal) { Calendar.writeStyle(out, reqState); } if (showPushpinChooser) { WebPageAdaptor.writeCssLink(out, reqState, "PushpinChooser.css", cssDir); } } }; /* JavaScript */ HTMLOutput HTML_JS = new HTMLOutput() { public void write(PrintWriter out) throws IOException { MenuBar.writeJavaScript(out, pageName, reqState); JavaScriptTools.writeJSInclude(out, JavaScriptTools.qualifyJSFileRef(SORTTABLE_JS), request); JavaScriptTools.writeJSInclude(out, JavaScriptTools.qualifyJSFileRef("DeviceInfo.js"), request); if (showDateCal) { Calendar.writeJavaScript(out, reqState); JavaScriptTools.writeStartJavaScript(out); // -- device expire out.write("// Device Expiration Calendar vars \n"); JavaScriptTools.writeJSVar(out, "ID_DEVICE_EXPIRE", DEVICE_EXPIRE); Calendar.writeNewCalendar(out, DEVICE_EXPIRE, null/*formID*/, "", null); out.write(DEVICE_EXPIRE+".setYearAdvanceSelection(true);\n"); out.write(DEVICE_EXPIRE+".setCollapsible(true,false,true);\n"); // -- Share Start/End out.write("// Share Start/End Calendar vars \n"); JavaScriptTools.writeJSVar(out, "ID_SHARE_START", SHARE_START); Calendar.writeNewCalendar(out, SHARE_START, null/*formID*/, "", null); out.write(SHARE_START+".setYearAdvanceSelection(true);\n"); out.write(SHARE_START+".setCollapsible(true,false,true);\n"); // -- Share End JavaScriptTools.writeJSVar(out, "ID_SHARE_END", SHARE_END); Calendar.writeNewCalendar(out, SHARE_END, null/*formID*/, "", null); out.write(SHARE_END+".setYearAdvanceSelection(true);\n"); out.write(SHARE_END+".setCollapsible(true,false,true);\n"); // -- license expire out.write("// License Expiration Calendar vars \n"); JavaScriptTools.writeJSVar(out, "ID_LICENSE_EXPIRE", LICENSE_EXPIRE); Calendar.writeNewCalendar(out, LICENSE_EXPIRE, null/*formID*/, "", null); out.write(LICENSE_EXPIRE+".setYearAdvanceSelection(true);\n"); out.write(LICENSE_EXPIRE+".setCollapsible(true,false,true);\n"); // -- last service time out.write("// last Service Time Calendar vars \n"); JavaScriptTools.writeJSVar(out, "ID_LAST_SERVICE_DATE", LAST_SERVICE_TIME); Calendar.writeNewCalendar(out, LAST_SERVICE_TIME, null/*formID*/, "", null); out.write(LAST_SERVICE_TIME+".setYearAdvanceSelection(true);\n"); out.write(LAST_SERVICE_TIME+".setCollapsible(true,false,true);\n"); // -- next service time out.write("// Next Service date Calendar vars \n"); JavaScriptTools.writeJSVar(out, "ID_NEXT_SERVICE_DATE", NEXT_SERVICE_TIME); Calendar.writeNewCalendar(out, NEXT_SERVICE_TIME, null/*formID*/, "", null); out.write(NEXT_SERVICE_TIME+".setYearAdvanceSelection(true);\n"); out.write(NEXT_SERVICE_TIME+".setCollapsible(true,false,true);\n"); // -- JavaScriptTools.writeEndJavaScript(out); } if (showPushpinChooser) { PushpinChooser.writePushpinChooserJS(out, reqState, true); } } }; /* Content */ final Device _selDev = selDev; // may be null !!! final OrderedSet<String> _deviceList = devList; final String _selDevID = selDevID; final boolean _allowEdit = allowEdit; final boolean _allowView = allowView; final boolean _allowCommand = allowCommand; final boolean _allowSmsCmd = allowSmsCmd; final int _overDevLimit = overDevLimit; final boolean _allowNew = allowNew; final boolean _allowDelete = allowDelete; final boolean _uiCmd = _allowCommand && uiCmd ; final boolean _uiSms = _allowSmsCmd && uiSms ; final boolean _uiEdit = _allowEdit && uiEdit; final boolean _uiView = _uiEdit || uiView; final boolean _uiList = uiList || (!_uiEdit && !_uiView && !_uiCmd && !_uiSms); HTMLOutput HTML_CONTENT = null; if (_uiList) { final boolean _viewUniqID = viewUniqID; final boolean _viewServID = viewServID && showServiceID; final boolean _viewSIM = viewSIM; final boolean _viewActive = viewActive; HTML_CONTENT = new HTMLOutput(CommonServlet.CSS_CONTENT_FRAME, m) { public void write(PrintWriter out) throws IOException { String selectURL = DeviceInfo.this.encodePageURL(reqState);//,RequestProperties.TRACK_BASE_URI()); String refreshURL = DeviceInfo.this.encodePageURL(reqState); //String editURL = DeviceInfo.this.encodePageURL(reqState);//,RequestProperties.TRACK_BASE_URI()); String newURL = DeviceInfo.this.encodePageURL(reqState);//,RequestProperties.TRACK_BASE_URI()); /* digital input state */ Vector<StateMaskBit> inpStateList = null; for (int i = 0; i < 16; i++) { // -- DeviceInfo.showInputState.01=Panic,Off,On String key = PrivateLabel.PROP_DeviceInfo_showInputState_ + i; String val = privLabel.getStringProperty(key,null); if (StringTools.isBlank(val)) { // -- not found, try again with prefixing "0" if (i < 10) { key = PrivateLabel.PROP_DeviceInfo_showInputState_ + "0" + i; val = privLabel.getStringProperty(key,null); if (StringTools.isBlank(val)) { continue; } } else { continue; } } StateMaskBit smb = new StateMaskBit(i,val,"Input_",locale); if (inpStateList == null) { inpStateList = new Vector<StateMaskBit>(); } inpStateList.add(smb); //Print.logInfo("Added InputState : " + smb); } /* digital output state */ Vector<StateMaskBit> outStateList = null; for (int i = 0; i < 16; i++) { // -- DeviceInfo.showOutputState.01=Panic,Off,On String key = PrivateLabel.PROP_DeviceInfo_showOutputState_ + i; String val = privLabel.getStringProperty(key,null); if (StringTools.isBlank(val)) { // -- not found, try again with prefixing "0" if (i < 10) { key = PrivateLabel.PROP_DeviceInfo_showOutputState_ + "0" + i; val = privLabel.getStringProperty(key,null); if (StringTools.isBlank(val)) { continue; } } else { continue; } } StateMaskBit smb = new StateMaskBit(i,val,"Output_",locale); if (outStateList == null) { outStateList = new Vector<StateMaskBit>(); } outStateList.add(smb); //Print.logInfo("Added OutputState : " + smb); } /* command state */ Vector<StateMaskBit> cmdStateList = null; for (int i = 0; i < 16; i++) { String key = PrivateLabel.PROP_DeviceInfo_showCommandState_ + i; String val = privLabel.getStringProperty(key,null); if (StringTools.isBlank(val)) { // -- not found, try again with prefixing "0" if (i < 10) { key = PrivateLabel.PROP_DeviceInfo_showCommandState_ + "0" + i; val = privLabel.getStringProperty(key,null); if (StringTools.isBlank(val)) { continue; } } else { continue; } } StateMaskBit smb = new StateMaskBit(i,val,"Command_",locale); if (cmdStateList == null) { cmdStateList = new Vector<StateMaskBit>(); } cmdStateList.add(smb); //Print.logInfo("Added CommandState : " + smb); } /* show expected ACKs */ boolean showAcks = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showExpectedAcks,false); // -- frame header String frameTitle = _allowEdit? i18n.getString("DeviceInfo.viewEditDevice","View/Edit {0} Information", devTitles) : i18n.getString("DeviceInfo.viewDevice","View {0} Information", devTitles); out.write("<span class='"+CommonServlet.CSS_MENU_TITLE+"'>"+frameTitle+"</span>&nbsp;\n"); out.write("<a href='"+refreshURL+"'><span class=''>"+i18n.getString("DeviceInfo.refresh","Refresh")+"</a>\n"); out.write("<br/>\n"); out.write("<hr>\n"); // -- device selection table (Select, Device ID, Description, ...) out.write("<h1 class='"+CommonServlet.CSS_ADMIN_SELECT_TITLE+"'>"+i18n.getString("DeviceInfo.selectDevice","Select a {0}",devTitles)+":</h1>\n"); out.write("<div style='margin-left:25px;'>\n"); out.write("<form name='"+FORM_DEVICE_SELECT+"' method='post' action='"+selectURL+"' target='_self'>"); // target='_top' out.write("<input type='hidden' name='"+PARM_COMMAND+"' value='"+COMMAND_INFO_SEL_DEVICE+"'/>"); out.write("<table class='"+CommonServlet.CSS_ADMIN_SELECT_TABLE+"' cellspacing='0' cellpadding='0' border='0'>\n"); out.write(" <thead>\n"); out.write(" <tr class='" +CommonServlet.CSS_ADMIN_TABLE_HEADER_ROW+"'>\n"); out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL_SEL+"' nowrap>"+FilterText(i18n.getString("DeviceInfo.select","Select"))+"</th>\n"); out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.deviceID","{0} ID",devTitles))+"</th>\n"); if (_viewUniqID) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.uniqueID","Unique ID"))+"</th>\n"); } out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.decription","Description",devTitles))+"</th>\n"); out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.devEquipType","Equipment\nType"))+"</th>\n"); if (_viewSIM) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.simPhoneNumber","SIM Phone#"))+"</th>\n"); } if (_viewServID) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.devServerID","Server ID"))+"</th>\n"); } out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.ignitionState","Ignition\nState"))+"</th>\n"); if (!ListTools.isEmpty(inpStateList)) { for (StateMaskBit smb : inpStateList) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(smb.getTitle())+"</th>\n"); } } if (!ListTools.isEmpty(outStateList)) { for (StateMaskBit smb : outStateList) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(smb.getTitle())+"</th>\n"); } } if (!ListTools.isEmpty(cmdStateList)) { for (StateMaskBit smb : cmdStateList) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(smb.getTitle())+"</th>\n"); } } if (showAcks) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.ackExpected","Expecting\nACK"))+"</th>\n"); } if (_viewActive) { out.write(" <th class='"+CommonServlet.CSS_ADMIN_TABLE_HEADER_COL +"' nowrap>"+FilterText(i18n.getString("DeviceInfo.active","Active"))+"</th>\n"); } out.write(" </tr>\n"); out.write(" </thead>\n"); out.write(" <tbody>\n"); Device deviceRcd[] = new Device[_deviceList.size()]; int hasCommandHandlers = 0; boolean okUpdateDevice = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_optimizeUpdateDevice,OPTIMIZE_IGNITION_STATE); for (int d = 0; d < _deviceList.size(); d++) { String rowClass = ((d & 1) == 0)? CommonServlet.CSS_ADMIN_TABLE_BODY_ROW_ODD : CommonServlet.CSS_ADMIN_TABLE_BODY_ROW_EVEN; out.write(" <tr class='"+rowClass+"'>\n"); try { Device dev = Device._getDevice(currAcct, _deviceList.get(d)); // may throw DBException if (dev != null) { // -- will not be null if "_getDevice" is used to retrieve records String deviceID = FilterText(dev.getDeviceID()); String uniqueID = FilterText(dev.getUniqueID()); String deviceDesc = FilterText(dev.getDescription()); String equipType = FilterText(dev.getEquipmentType()); String imeiNum = FilterText(dev.getImeiNumber()); String simPhone = FilterText(dev.getSimPhoneNumber()); String devCode = FilterText(DCServerFactory.getServerConfigDescription(dev.getDeviceCode())); int ignState = dev.getCurrentIgnitionState(); // may update ignition state times String ignDesc = ""; String ignColor = "black"; switch (ignState) { case 0: ignDesc = FilterText(i18n.getString("DeviceInfo.ignitionOff" , "Off")); ignColor = ColorTools.BLACK.toString(true); break; case 1: ignDesc = FilterText(i18n.getString("DeviceInfo.ignitionOn" , "On")); ignColor = ColorTools.GREEN.toString(true); break; default: ignDesc = FilterText(i18n.getString("DeviceInfo.ignitionUnknown", "Unknown")); ignColor = ColorTools.DARK_YELLOW.toString(true); break; } String pendingACK = FilterText(dev.getExpectingCommandAck()?ComboOption.getYesNoText(locale,true):""); String active = FilterText(ComboOption.getYesNoText(locale,dev.isActive())); String checked = _selDevID.equals(dev.getDeviceID())? "checked" : ""; out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL_SEL+"' "+SORTTABLE_SORTKEY+"='"+d+"'><input type='radio' name='"+PARM_DEVICE+"' id='"+deviceID+"' value='"+deviceID+"' "+checked+"></td>\n"); out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap><label for='"+deviceID+"'>"+deviceID+"</label></td>\n"); if (_viewUniqID) { out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+uniqueID+"</td>\n"); } out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+deviceDesc+"</td>\n"); out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+equipType+"</td>\n"); if (_viewSIM) { out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+simPhone+"</td>\n"); } if (_viewServID) { out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+devCode+"</td>\n"); } out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap style='color:"+ignColor+"'>"+ignDesc+"</td>\n"); if (!ListTools.isEmpty(inpStateList)) { for (StateMaskBit smb : inpStateList) { String state_val = smb.getStateDescription(dev.getLastInputState(smb.getBitIndex())); out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+state_val+"</td>\n"); } } if (!ListTools.isEmpty(outStateList)) { for (StateMaskBit smb : outStateList) { String state_val = smb.getStateDescription(dev.getLastOutputState(smb.getBitIndex())); out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+state_val+"</td>\n"); } } if (!ListTools.isEmpty(cmdStateList)) { for (StateMaskBit smb : cmdStateList) { String state_val = smb.getStateDescription(dev.getCommandStateMaskBit(smb.getBitIndex())); out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+state_val+"</td>\n"); } } if (showAcks) { out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap style='color:red'>"+pendingACK+"</td>\n"); } if (_viewActive) { out.write(" <td class='"+CommonServlet.CSS_ADMIN_TABLE_BODY_COL +"' nowrap>"+active+"</td>\n"); } // -- count command handlers String serverID = dev.getDeviceCode(); if (StringTools.isBlank(serverID)) { // -- ignore } else if (DeviceInfo.this.getDeviceCommandHandler(serverID) != null) { //Print.logInfo("Found DeviceCommandHandler: " + serverID); hasCommandHandlers++; } else { //Print.logInfo("DCS not found: " + serverID); } // -- update device ignition state? if (okUpdateDevice && dev.hasChangedFieldNames()) { dev.updateOtherChangedEventFields(); } } else { // -- unlikely deviceRcd[d] = null; } } catch (DBException dbe) { deviceRcd[d] = null; } out.write(" </tr>\n"); } out.write(" </tbody>\n"); out.write("</table>\n"); out.write("<table cellpadding='0' cellspacing='0' border='0' style='width:95%; margin-top:5px; margin-left:5px; margin-bottom:5px;'>\n"); out.write("<tr>\n"); if (_allowView) { out.write("<td style='padding-left:5px;'>"); out.write("<input type='submit' name='"+PARM_SUBMIT_VIEW+"' value='"+i18n.getString("DeviceInfo.view","View")+"'>"); out.write("</td>\n"); } if (_allowEdit) { out.write("<td style='padding-left:5px;'>"); out.write("<input type='submit' name='"+PARM_SUBMIT_EDIT+"' value='"+i18n.getString("DeviceInfo.edit","Edit")+"'>"); out.write("</td>\n"); } if (_allowCommand) { if (hasCommandHandlers > 0) { out.write("<td style='padding-left:5px;'>"); out.write("<input type='submit' name='"+PARM_SUBMIT_PROP+"' value='"+i18n.getString("DeviceInfo.properties","Commands")+"'>"); out.write("</td>\n"); } else { //Print.logWarn("No matching DeviceCommandHandlers found"); } } if (_allowSmsCmd) { // SMS commands out.write("<td style='padding-left:5px;'>"); out.write("<input type='submit' name='"+PARM_SUBMIT_SMS +"' value='"+i18n.getString("DeviceInfo.sms","SMS")+"'>"); out.write("</td>\n"); } out.write("<td style='width:100%; text-align:right; padding-right:10px;'>"); if (_allowDelete) { out.write("<input type='submit' name='"+PARM_SUBMIT_DEL +"' value='"+i18n.getString("DeviceInfo.delete","Delete")+"' "+Onclick_ConfirmDelete(locale)+">"); } else { out.write("&nbsp;"); } out.write("</td>\n"); out.write("</tr>\n"); out.write("</table>\n"); out.write("</form>\n"); out.write("</div>\n"); out.write("<hr>\n"); /* new device */ if (_allowNew && (_overDevLimit <= 0)) { String createText = i18n.getString("DeviceInfo.createNewDevice","Create a new device"); if (allowNewDevMode == DEVMODE_SYSADMIN) { createText += " " + i18n.getString("DeviceInfo.sysadminOnly","(System Admin only)"); } else if (allowNewDevMode == DEVMODE_MANAGER) { createText += " " + i18n.getString("DeviceInfo.managerOnly","(AccountManager only)"); } out.write("<h1 class='"+CommonServlet.CSS_ADMIN_SELECT_TITLE+"'>"+createText+":</h1>\n"); out.write("<div style='margin-top:5px; margin-left:5px; margin-bottom:5px;'>\n"); out.write("<form name='"+FORM_DEVICE_NEW+"' method='post' action='"+newURL+"' target='_self'>"); // target='_top' out.write(" <input type='hidden' name='"+PARM_COMMAND+"' value='"+COMMAND_INFO_NEW_DEVICE+"'/>"); out.write(i18n.getString("DeviceInfo.deviceID","{0} ID",devTitles)+": <input type='text' class='"+CommonServlet.CSS_TEXT_INPUT+"' name='"+PARM_NEW_NAME+"' value='' size='32' maxlength='32'><br>\n"); out.write(" <input type='submit' name='"+PARM_SUBMIT_NEW+"' value='"+i18n.getString("DeviceInfo.new","New")+"' style='margin-top:5px; margin-left:10px;'>\n"); out.write("</form>\n"); out.write("</div>\n"); out.write("<hr>\n"); } } }; } else if (_uiEdit || _uiView) { final boolean _editServID = _uiEdit && editServID && showServiceID; // fix: was '_uiView' [2.6.4-B12] final boolean _viewServID = _uiView && viewServID && showServiceID; final boolean _editCodeVer = _uiEdit && editCodeVer; final boolean _viewCodeVer = _uiView && viewCodeVer; final boolean _editUniqID = _uiEdit && editUniqID; final boolean _viewUniqID = _uiView && viewUniqID; final boolean _editActive = _uiEdit && editActive; final boolean _viewActive = _uiView && viewActive; final boolean _editExpire = _uiEdit && editExpire; final boolean _viewExpire = _uiView && viewExpire; final boolean _editShare = _uiEdit && editShare; final boolean _viewShare = _uiView && viewShare; final boolean _editRules = _uiEdit && editRules; final boolean _viewRules = _uiView && viewRules; final boolean _editSMSEm = _uiEdit && editSMSEm; final boolean _viewSMSEm = _uiView && viewSMSEm; final boolean _editSIM = _uiEdit && editSIM; final boolean _viewSIM = _uiView && viewSIM; final boolean _editEqStat = _uiEdit && editEqStat; final boolean _viewEqStat = _uiView && viewEqStat; final boolean _editIMEI = _uiEdit && editIMEI; final boolean _viewIMEI = _uiView && viewIMEI; final boolean _editSERIAL = _uiEdit && editSERIAL; final boolean _viewSERIAL = _uiView && viewSERIAL; final boolean _editDATKEY = _uiEdit && editDATKEY; final boolean _viewDATKEY = _uiView && viewDATKEY; final boolean _editFuelCap = _uiEdit && editFuelCap; final boolean _viewFuelCap = _uiView && viewFuelCap; final boolean _editFuelPrf = _uiEdit && editFuelPrf; final boolean _viewFuelPrf = _uiView && viewFuelPrf; final boolean _editFuelEco = _uiEdit && editFuelEco; final boolean _viewFuelEco = _uiView && viewFuelEco; final boolean _editFuelCst = _uiEdit && editFuelCst; final boolean _viewFuelCst = _uiView && viewFuelCst; HTML_CONTENT = new HTMLOutput(CommonServlet.CSS_CONTENT_FRAME, m) { public void write(PrintWriter out) throws IOException { String editURL = DeviceInfo.this.encodePageURL(reqState);//,RequestProperties.TRACK_BASE_URI()); boolean ntfyOK = _viewRules && _showNotificationFields(privLabel); boolean ntfyEdit = ntfyOK && _editRules; boolean subscribeOK = _showSubscriberInfo(privLabel); boolean ignOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showIgnitionIndex,SHOW_IGNITION_NDX); boolean ppidOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showPushpinID,SHOW_PUSHPIN_ID); boolean dcolorOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDisplayColor,SHOW_DISPLAY_COLOR); boolean notesOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showNotes,SHOW_NOTES); boolean lastOdomOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showReportedOdometer,SHOW_REPORTED_ODOM); boolean lastEngHrsOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showReportedEngineHours,SHOW_REPORTED_ENG_HRS); boolean maintOdomOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showMaintenanceOdometer,SHOW_MAINTENANCE_ODOM); boolean maintHoursOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showMaintenanceHours,SHOW_MAINTENANCE_HOURS); boolean maintNotesOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showMaintenanceNotes,SHOW_MAINTENANCE_NOTES); boolean reminderOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showReminderMessage,SHOW_REMINDER_MESSAGE); boolean servTimeOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showServiceTime,SHOW_SERVICE_TIME); boolean devExpOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDeviceExpirationTime,SHOW_EXPIRATION_TIME);; boolean licExpOK = true; String dataKeyStr = privLabel.getStringProperty( PrivateLabel.PROP_DeviceInfo_showDataKey,SHOW_DATA_KEY); boolean dataKeyReq = "required".equalsIgnoreCase(dataKeyStr); boolean dataKeyOK = dataKeyReq || "true".equalsIgnoreCase(dataKeyStr); boolean workHoursOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showHoursOfOperation,SHOW_HOURS_OF_OPERATION); boolean faultCodesOK = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showFaultCodes,SHOW_FAULT_CODES); boolean speedLimOK = Device.hasRuleFactory(); // || privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showSpeedLimit,SHOW_SPEED_LIMIT); boolean fixLocOK = (_selDev != null) && Device.supportsFixedLocation() && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showFixedLocation,SHOW_FIXED_LOCATION); boolean shareMapOK = (_selDev != null) && Device.supportsMapShare() && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showSharedMapDates,SHOW_MAP_SHARE_DATES); boolean edServID_ = _editServID && ((_selDev == null) || (_selDev.getLastConnectTime() <= 0L)) && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_allowEditServerID,EDIT_SERVER_ID); boolean edCodeVer_ = _editCodeVer && privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_allowEditFirmwareVersion,EDIT_CODE_VERSION); boolean showDCSPropID = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDcsPropertiesID,SHOW_DCS_PROPERTIES_ID); boolean showDCSCfgStr = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showDcsConfigString,SHOW_DCS_CONFIG_STRING); boolean showTcpSessID = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showStaticTcpSessionID,SHOW_FIXED_TCP_SESSION_ID); boolean showPrefGrp = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showPreferredGroupID,SHOW_PREFERRED_GROUP); boolean showAssgnUsr = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showAssignedUserID,SHOW_ASSIGNED_USER); // -- boolean showFuelEcon = DBConfig.hasExtraPackage(); boolean showFuelCost = showFuelEcon; boolean showFuelCap = privLabel.getBooleanProperty(PrivateLabel.PROP_DeviceInfo_showFuelCapacity,SHOW_FUEL_CAPACITY); String showFuelProfS = privLabel.getStringProperty(PrivateLabel.PROP_DeviceInfo_showFuelLevelProfile,""); boolean showFuelProf = showFuelCap; int fuelProfType = 1; // 0=None, 1=text, 2=select, 3=scale //Print.logInfo("deviceInfo.showFuelLevelProfile: " + showFuelProfS); if (StringTools.isBlank(showFuelProfS)) { // -- default when blank showFuelProf = showFuelCap; fuelProfType = 1; // text } else if (showFuelProfS.equalsIgnoreCase("false" ) || showFuelProfS.equalsIgnoreCase("no" ) ) { // -- do not show showFuelProf = false; // no display fuelProfType = 0; // none } else if (showFuelProfS.equalsIgnoreCase("true" ) || showFuelProfS.equalsIgnoreCase("yes" ) || showFuelProfS.equalsIgnoreCase("combo" ) || showFuelProfS.equalsIgnoreCase("select") ) { // -- show as ComboBox showFuelProf = true; // display fuelProfType = 2; // combo } else if (showFuelProfS.equalsIgnoreCase("text" ) ) { // -- show as TextField showFuelProf = true; // display fuelProfType = 1; // text } else if (showFuelProfS.equalsIgnoreCase("scale" ) ) { showFuelProf = true; // display fuelProfType = 3; // scale } else { // -- default text showFuelProf = showFuelCap; fuelProfType = 1; // text } /* distance units description */ Account.DistanceUnits distUnits = Account.getDistanceUnits(currAcct); String distUnitsStr = distUnits.toString(locale); /* speed units description */ Account.SpeedUnits speedUnits = Account.getSpeedUnits(currAcct); String speedUnitsStr = speedUnits.toString(locale); /* volume units description */ Account.VolumeUnits volmUnits = Account.getVolumeUnits(currAcct); String volmUnitsStr = volmUnits.toString(locale); /* volume units description */ Account.EconomyUnits econUnits = Account.getEconomyUnits(currAcct); String econUnitsStr = econUnits.toString(locale); /* custom attributes */ Collection<String> customKeys = new OrderedSet<String>(); String ppAccounts[] = StringTools.parseArray(privLabel.getStringProperty(PrivateLabel.PROP_DeviceInfo_customAccounts,null)); if (ListTools.isEmpty(ppAccounts)) { // -- no accounts specified, custom fields disabled } else if (ppAccounts[0].equals("*") || ListTools.contains(ppAccounts,currAcctID)) { // -- either all accounts, or current account is a match Collection<String> ppKeys = privLabel.getPropertyKeys(PrivateLabel.PROP_DeviceInfo_custom_); for (String ppKey : ppKeys) { // -- Add all custom field keys defined in the PrivateLabel properties // - "DeviceInfo.custom.DEVICEKEY" ==> "DEVICEKEY" String desc = privLabel.getStringProperty(ppKey, null); // must have a non-blank description if (!StringTools.isBlank(desc)) { String key = ppKey.substring(PrivateLabel.PROP_DeviceInfo_custom_.length()); customKeys.add(key); } } } if (_selDev != null) { // -- Add additional custom field keys defined in the Device table customKeys.addAll(_selDev.getCustomAttributeKeys()); } /* last connect times */ String lastConnectTime = (_selDev != null)? reqState.formatDateTime(_selDev.getLastTotalConnectTime()) : ""; if (StringTools.isBlank(lastConnectTime)) { lastConnectTime = i18n.getString("DeviceInfo.neverConnected","never"); } String lastEventTime = reqState.formatDateTime(reqState.getLastEventTime()); if (StringTools.isBlank(lastEventTime )) { lastEventTime = i18n.getString("DeviceInfo.noLastEvent" ,"none" ); } /* frame header */ String frameTitle = _allowEdit? i18n.getString("DeviceInfo.viewEditDevice","View/Edit {0} Information", devTitles) : i18n.getString("DeviceInfo.viewDevice","View {0} Information", devTitles); out.write("<span class='"+CommonServlet.CSS_MENU_TITLE+"'>"+frameTitle+"</span><br/>\n"); out.write("<hr>\n"); /* start of form */ out.write("<form name='"+FORM_DEVICE_EDIT+"' method='post' action='"+editURL+"' target='_self'>\n"); // target='_top' out.write("<input type='hidden' name='"+PARM_COMMAND+"' value='"+COMMAND_INFO_UPD_DEVICE+"'/>\n"); /* Device fields */ ComboOption devActive = ComboOption.getYesNoOption(locale, ((_selDev != null) && _selDev.isActive())); ComboOption equipStat = ComboOption.getYesNoOption(locale, ((_selDev != null) && _selDev.isActive())); String firmVers = (_selDev!=null)? _selDev.getCodeVersion() : ""; long createTS = (_selDev!=null)? _selDev.getCreationTime() : 0L; String createStr = reqState.formatDateTime(createTS, "--"); out.println("<table class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE+"' cellspacing='0' callpadding='0' border='0'>"); out.println(FormRow_TextField(PARM_DEVICE , false , i18n.getString("DeviceInfo.deviceID","{0} ID",devTitles)+":" , _selDevID, 32, 32)); out.println(FormRow_TextField(PARM_CREATE_DATE , false , i18n.getString("DeviceInfo.creationDate","Creation Date")+":" , createStr, 30, 30)); String deviceCode = (_selDev != null)? DCServerFactory.getServerConfigDescription(_selDev.getDeviceCode()) : ""; String autoFill = null; if (StringTools.isBlank(deviceCode)) { autoFill = i18n.getString("DeviceInfo.serverIdAutoFill","(automatically entered by the DCS)"); } if (_viewServID) { out.println(FormRow_TextField(PARM_SERVER_ID , edServID_ , i18n.getString("DeviceInfo.serverID","Server ID")+":" , deviceCode, 18, 20, autoFill)); } if (_viewCodeVer) { out.println(FormRow_TextField(PARM_CODE_VERS , edCodeVer_ , i18n.getString("DeviceInfo.firmwareVers","Firmware Version")+":" , firmVers, 28, 28)); } if (_viewUniqID) { out.println(FormRow_TextField(PARM_DEV_UNIQ , _editUniqID, i18n.getString("DeviceInfo.uniqueID","Unique ID")+":" , (_selDev!=null)?_selDev.getUniqueID():"" , 30, 30)); } if (_viewActive) { out.println(FormRow_ComboBox (PARM_DEV_ACTIVE , _editActive, i18n.getString("DeviceInfo.active","Active")+":" , devActive, ComboMap.getYesNoMap(locale), "" , -1)); } if (devExpOK && _viewExpire) { String expTitle = i18n.getString("DeviceInfo.deviceExpire","{0} Expiration",devTitles) + ":"; DateTime.DateStringFormat dsf = privLabel.getDateStringFormat(); String devExpStr = (_selDev != null)? FormatDayNumberTS(dsf,_selDev.getExpirationTime(),acctTimeZone) : ""; if (showDateCal) { String onclick = _editExpire? "javascript:deviceToggleDevExpCalendar()" : null; out.println(FormRow_TextField(DEVICE_EXPIRE, PARM_DEV_EXPIRE, _editExpire, expTitle, devExpStr, onclick, 13, 13, null)); } else { String extraYMD = i18n.getString("DeviceInfo.dateYMD","(yyyy/mm/dd)"); out.println(FormRow_TextField(PARM_DEV_EXPIRE, _editExpire, expTitle, devExpStr, 13, 13, extraYMD)); } } // -- Device description, name, id, make , model out.println(FormRow_TextField(PARM_DEV_DESC , _uiEdit , i18n.getString("DeviceInfo.deviceDesc","{0} Description",devTitles) +":",(_selDev!=null)?_selDev.getDescription():"" , 40, 64)); out.println(FormRow_TextField(PARM_DEV_NAME , _uiEdit , i18n.getString("DeviceInfo.displayName","Short Name") +":" , (_selDev!=null)?_selDev.getDisplayName():"" , 16, 64)); out.println(FormRow_TextField(PARM_VEHICLE_ID , _uiEdit , i18n.getString("DeviceInfo.vehicleID","Vehicle ID") +":" , (_selDev!=null)?_selDev.getVehicleID():"" , 24, 24)); out.println(FormRow_TextField(PARM_VEHICLE_MAKE , _uiEdit , i18n.getString("DeviceInfo.vehicleMake","Vehicle Make") +":" , (_selDev!=null)?_selDev.getVehicleMake():"" , 40, 40)); out.println(FormRow_TextField(PARM_VEHICLE_MODEL , _uiEdit , i18n.getString("DeviceInfo.vehicleModel","Vehicle Model") +":" , (_selDev!=null)?_selDev.getVehicleModel():"" , 40, 40)); // -- license plate/expire out.println(FormRow_TextField(PARM_LICENSE_PLATE , _uiEdit , i18n.getString("DeviceInfo.licensePlate","License Plate") +":" , (_selDev!=null)?_selDev.getLicensePlate():"" , 16, 24)); if (licExpOK) { String licTitle = i18n.getString("DeviceInfo.licenseExpire","License Expiration") + ":"; DateTime.DateStringFormat dsf = privLabel.getDateStringFormat(); String licExpStr = (_selDev != null)? FormatDayNumber(dsf,_selDev.getLicenseExpire()) : ""; if (showDateCal) { String onclick = _uiEdit? "javascript:deviceToggleLicExpCalendar()" : null; out.println(FormRow_TextField(LICENSE_EXPIRE, PARM_LICENSE_EXPIRE, _uiEdit, licTitle, licExpStr, onclick, 13, 13, null)); } else { String extraYMD = i18n.getString("DeviceInfo.dateYMD","(yyyy/mm/dd)"); out.println(FormRow_TextField(PARM_LICENSE_EXPIRE, _uiEdit, licTitle, licExpStr, 13, 13, extraYMD)); } } // -- Equipment type/status out.println(FormRow_TextField(PARM_DEV_EQUIP_TYPE , _uiEdit , i18n.getString("DeviceInfo.equipmentType","Equipment Type") +":" , (_selDev!=null)?_selDev.getEquipmentType():"" , 30, 40)); if (_viewEqStat) { String eqTitle = i18n.getString("DeviceInfo.equipmentStatus","Equipment Status") + ":"; String devEqSt = (_selDev != null)? _selDev.getEquipmentStatus() : ""; OrderedMap<String,String> eqStatMap = Device.GetEquipmentStatusMap(locale); if (!ListTools.isEmpty(eqStatMap)) { ComboMap esList = new ComboMap(eqStatMap); if (!esList.containsKeyIgnoreCase(devEqSt)) { String desc = !StringTools.isBlank(devEqSt)? devEqSt : i18n.getString("DeviceInfo.blank","(blank)"); esList.insert(devEqSt, desc); } out.println(FormRow_ComboBox( PARM_DEV_EQUIP_STATUS, _editEqStat, eqTitle, devEqSt, esList, "", -1)); } else { out.println(FormRow_TextField(PARM_DEV_EQUIP_STATUS, _editEqStat, eqTitle, devEqSt, 20, 20)); } } if (_viewIMEI) { out.println(FormRow_TextField(PARM_DEV_IMEI , _editIMEI , i18n.getString("DeviceInfo.imeiNumber","IMEI/ESN Number") +":" , (_selDev!=null)?_selDev.getImeiNumber():"" , 18, 24)); } if (_viewSERIAL) { out.println(FormRow_TextField(PARM_DEV_SERIAL_NO , _editSERIAL, i18n.getString("DeviceInfo.serialNumber","Serial Number") +":" , (_selDev!=null)?_selDev.getSerialNumber():"" , 20, 24)); } if (dataKeyOK && _viewDATKEY) { out.println(FormRow_TextField(PARM_DATA_KEY , _editDATKEY, i18n.getString("DeviceInfo.dataKey","Data Key") +":" , (_selDev!=null)?_selDev.getDataKey():"" , 60, 200)); } if (_viewSIM) { out.println(FormRow_TextField(PARM_DEV_SIMPHONE , _editSIM , i18n.getString("DeviceInfo.simPhoneNumber","SIM Phone#") +":" , (_selDev!=null)?_selDev.getSimPhoneNumber():"" , 14, 18)); } if (_viewSMSEm) { out.println(FormRow_TextField(PARM_SMS_EMAIL , _editSMSEm , i18n.getString("DeviceInfo.smsEmail","SMS Email Address") +":" , (_selDev!=null)?_selDev.getSmsEmail():"" , 60, 60)); } if (ppidOK) { String ppDesc = i18n.getString("DeviceInfo.mapPushpinID","{0} Pushpin ID",grpTitles)+":"; String ppid = (_selDev != null)? _selDev.getPushpinID() : ""; if (showPushpinChooser) { String ID_ICONSEL = "PushpinChooser"; String onclick = _uiEdit? "javascript:ppcShowPushpinChooser('"+ID_ICONSEL+"')" : null; out.println(FormRow_TextField(ID_ICONSEL, PARM_ICON_ID, _uiEdit, ppDesc, ppid, onclick, 32, 32, null)); } else { ComboMap ppList = new ComboMap(reqState.getMapProviderPushpinIDs()); ppList.insert(""); // insert a blank as the first entry out.println(FormRow_ComboBox(PARM_ICON_ID, _uiEdit, ppDesc, ppid, ppList, "", -1)); } } if (dcolorOK) { String dcDesc = i18n.getString("DeviceInfo.mapRouteColor","Map Route Color")+":"; String dcolor = (_selDev != null)? _selDev.getDisplayColor() : ""; double P = 0.30; ComboMap dcCombo = new ComboMap(); dcCombo.add("" ,i18n.getString("DeviceInfo.color.default","Default")); dcCombo.add(ColorTools.BLACK.toString(true) ,i18n.getString("DeviceInfo.color.black" ,"Black" )); dcCombo.add(ColorTools.BROWN.toString(true) ,i18n.getString("DeviceInfo.color.brown" ,"Brown" )); dcCombo.add(ColorTools.RED.toString(true) ,i18n.getString("DeviceInfo.color.red" ,"Red" )); dcCombo.add(ColorTools.ORANGE.darker(P).toString(true),i18n.getString("DeviceInfo.color.orange" ,"Orange" )); //dcCombo.add(ColorTools.YELLOW.darker(P).toString(true),i18n.getString("DeviceInfo.color.yellow" ,"Yellow" )); dcCombo.add(ColorTools.GREEN.darker(P).toString(true) ,i18n.getString("DeviceInfo.color.green" ,"Green" )); dcCombo.add(ColorTools.BLUE.toString(true) ,i18n.getString("DeviceInfo.color.blue" ,"Blue" )); dcCombo.add(ColorTools.PURPLE.toString(true) ,i18n.getString("DeviceInfo.color.purple" ,"Purple" )); dcCombo.add(ColorTools.DARK_GRAY.toString(true) ,i18n.getString("DeviceInfo.color.gray" ,"Gray" )); //dcCombo.add(ColorTools.WHITE.toString(true) ,i18n.getString("DeviceInfo.color.white" ,"White" )); dcCombo.add(ColorTools.CYAN.darker(P).toString(true) ,i18n.getString("DeviceInfo.color.cyan" ,"Cyan" )); dcCombo.add(ColorTools.PINK.toString(true) ,i18n.getString("DeviceInfo.color.pink" ,"Pink" )); dcCombo.add("none" ,i18n.getString("DeviceInfo.color.none" ,"None" )); out.println(FormRow_ComboBox(PARM_DISPLAY_COLOR, _uiEdit, dcDesc, dcolor, dcCombo, "", -1)); } if (ignOK) { ComboMap ignList = new ComboMap(new String[] { IGNITION_notApplicable, IGNITION_ignition, IGNITION_startStop }); //,"0","1","2","3","4","5","6","7" }); int maxIgnNdx = privLabel.getIntProperty(PrivateLabel.PROP_DeviceInfo_maximumIgnitionIndex,7); for (int igx = 0; igx <= maxIgnNdx; igx++) { String igs = String.valueOf(igx); ignList.add(igs, igs); } int ignNdx = (_selDev != null)? _selDev.getIgnitionIndex() : -1; String ignSel = ""; if (ignNdx < 0) { ignSel = IGNITION_notApplicable; } else if (ignNdx == StatusCodes.IGNITION_INPUT_INDEX) { ignSel = IGNITION_ignition; } else if (ignNdx == StatusCodes.IGNITION_START_STOP) { ignSel = IGNITION_startStop; } else { ignSel = String.valueOf(ignNdx); } out.println(FormRow_ComboBox( PARM_IGNITION_INDEX, _uiEdit , i18n.getString("DeviceInfo.ignitionIndex","Ignition Input") +":" , ignSel, ignList, "", -1, i18n.getString("DeviceInfo.ignitionIndexDesc","(ignition input line, if applicable)"))); } // -- Speed Limit if (speedLimOK) { double speedLimUnits = (_selDev!=null)? Account.getSpeedUnits(currAcct).convertFromKPH(_selDev.getSpeedLimitKPH()) : 0.0; String speedLimStr = StringTools.format(speedLimUnits, "0.0"); out.println(FormRow_TextField(PARM_DEV_SPEED_LIMIT, _uiEdit , i18n.getString("DeviceInfo.speedLimit","Maximum Speed") +":" , speedLimStr , 10, 10, speedUnitsStr)); } // -- Driver ID out.println(FormRow_TextField(PARM_DRIVER_ID, _uiEdit, i18n.getString("DeviceInfo.driverID","Driver ID")+":", (_selDev!=null)?_selDev.getDriverID():"" , 24, 30)); // -- User ID if (showAssgnUsr && Device.supportsAssignedUserID()) { OrderedMap<String,String> userMap = new OrderedMap<String,String>(); userMap.put("", "---"); try { OrderedSet<User> userList = Device.getAuthorizedUsers(_selDev); for (User usr : userList) { String id = usr.getUserID(); String desc = usr.getDescription() + " [" + id + "]"; userMap.put(id, desc); } } catch (DBException dbe) { // -- ignore } ComboMap userCombo = new ComboMap(userMap); String userSel = (_selDev != null)? _selDev.getAssignedUserID() : ""; //out.println(FormRow_TextField(PARM_USER_ID, _uiEdit, i18n.getString("DeviceInfo.userID","Assigned User ID")+":", userSel , 24, 24)); out.println(FormRow_ComboBox(PARM_USER_ID, _uiEdit, i18n.getString("DeviceInfo.userID","Assigned User ID")+":", userSel, userCombo, "", -1)); } // ------------------------------------ //-- Fuel Section // -- fuel capacity int fuelItemDisplayed = 0; if ((showFuelEcon && _viewFuelEco) || (showFuelCost && _viewFuelCst) || (showFuelCap && _viewFuelCap) || (showFuelProf && _viewFuelPrf) ) { // -- add separator before odometer if maintenance is supported out.println(FormRow_Separator()); } // -- fuel economy if (showFuelEcon && _viewFuelEco) { double fuelEconUnits = (_selDev!=null)? econUnits.convertFromKPL(_selDev.getFuelEconomy()) : 0.0; String fuelEconStr = StringTools.format(fuelEconUnits, "0.0"); out.println(FormRow_TextField(PARM_DEV_FUEL_ECON , _editFuelEco, i18n.getString("DeviceInfo.fuelEconomy","Fuel Economy") +":" , fuelEconStr, 10, 10, econUnitsStr)); fuelItemDisplayed++; } // -- fuel cost if (showFuelCost && _viewFuelCst) { double unitsPerLiter = volmUnits.convertFromLiters(1.0); double litersPerUnit = (unitsPerLiter > 0.0)? (1.0 / unitsPerLiter) : 0.0; double costPerLiter = (_selDev!=null)? _selDev.getFuelCostPerLiter() : 0.0; double costPerUnit = costPerLiter * litersPerUnit; double fuelCostUnits = costPerUnit; String fuelCostStr = StringTools.format(fuelCostUnits, "0.00"); String costUnitsStr = Account.getCurrency(currAcct) + "/" + volmUnitsStr; out.println(FormRow_TextField(PARM_DEV_FUEL_COST , _editFuelCst, i18n.getString("DeviceInfo.fuelCost","Fuel Cost") +":" , fuelCostStr, 10, 10, costUnitsStr)); fuelItemDisplayed++; } // -- fuel capacity (tank #1/tank#2) if (showFuelCap && _viewFuelCap) { if (fuelItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } // -- Tank #1 double fuelCap1Units = (_selDev!=null)? volmUnits.convertFromLiters(_selDev.getFuelCapacity()) : 0.0; // tank #1 String fuelCap1Str = StringTools.format(fuelCap1Units, "0.0"); out.println(FormRow_TextField(PARM_DEV_FUEL_CAP1 , _editFuelCap, i18n.getString("DeviceInfo.fuelCapacity","Fuel Tank #1 Capacity") +":", fuelCap1Str, 10, 10, volmUnitsStr)); // -- Tank #2 double fuelCap2Units = (_selDev!=null)? volmUnits.convertFromLiters(_selDev.getFuelCapacity2()) : 0.0; // tank #2 String fuelCap2Str = StringTools.format(fuelCap2Units, "0.0"); out.println(FormRow_TextField(PARM_DEV_FUEL_CAP2 , _editFuelCap, i18n.getString("DeviceInfo.fuelCapacity2","Fuel Tank #2 Capacity") +":", fuelCap2Str, 10, 10, volmUnitsStr)); fuelItemDisplayed++; } // -- fuel tank profile if (showFuelProf && _viewFuelPrf) { String profSel1 = (_selDev!=null)? _selDev.getFuelTankProfile(Device.FuelTankIndex.TANK_1) : null; String profSel2 = (_selDev!=null)? _selDev.getFuelTankProfile(Device.FuelTankIndex.TANK_2) : null; if (StringTools.isBlank(profSel1)) { profSel1 = FuelLevelProfile.FLP_NONE_ID; } if (StringTools.isBlank(profSel2)) { profSel2 = FuelLevelProfile.FLP_NONE_ID; } switch (fuelProfType) { default: case 0: {// "none" // -- no-op (fuel tank profiles not displayed) } break; case 1: { // "text" // -- view as TextField // -- #1 if (fuelItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_TextField(PARM_DEV_FUEL_PROFILE1, _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile1","Fuel Tank #1 Profile")+":", profSel1, 80, 250)); fuelItemDisplayed++; // -- #2 if (fuelItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_TextField(PARM_DEV_FUEL_PROFILE2, _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile2","Fuel Tank #2 Profile")+":", profSel2, 80, 250)); fuelItemDisplayed++; } break; case 2: { // "select" // -- view as ComboBox OrderedMap<String,String> profMap = FuelLevelProfile.GetFuelLevelProfiles(locale,true/*inclNone*/); ComboMap flpCombo = new ComboMap(profMap); // -- #1 if (fuelItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_ComboBox( PARM_DEV_FUEL_PROFILE1, _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile1","Fuel Tank #1 Profile")+":", profSel1, flpCombo, "", -1)); fuelItemDisplayed++; // -- #1 if (fuelItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_ComboBox( PARM_DEV_FUEL_PROFILE2, _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile2","Fuel Tank #2 Profile")+":", profSel2, flpCombo, "", -1)); fuelItemDisplayed++; } break; case 3: { // "scale" // -- view as "Linear"/"Cylider" pull-down and scale/offset text OrderedMap<String,String> profMap = new OrderedMap<String,String>(); profMap.put(FuelLevelProfile.FLP_NONE_NAME , i18n.getString("DeviceInfo.None" ,"None" )); profMap.put(FuelLevelProfile.FLP_LINEAR_NAME , i18n.getString("DeviceInfo.Linear" ,"Linear" )); profMap.put(FuelLevelProfile.FLP_CYLINDER_NAME, i18n.getString("DeviceInfo.Cylinder","Cylinder")); ComboMap flpCombo = new ComboMap(profMap); // -- #1 { String name1, scale1, offset1; if (profSel1 == null) { name1 = FuelLevelProfile.FLP_NONE_NAME; scale1 = ""; offset1 = ""; } else if (profSel1.indexOf(":") < 0) { name1 = profSel1.toUpperCase(); if (!name1.equals(FuelLevelProfile.FLP_LINEAR_NAME) && !name1.equals(FuelLevelProfile.FLP_CYLINDER_NAME) ) { name1 = FuelLevelProfile.FLP_NONE_NAME; scale1 = ""; offset1 = ""; } else { scale1 = "1"; offset1 = ""; } } else { FuelLevelProfile flp = new FuelLevelProfile(profSel1, null); name1 = flp.getID(); scale1 = String.valueOf(Math.round(flp.getScale())); offset1 = String.valueOf(Math.round(flp.getOffset())); } if (fuelItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_ComboBox( PARM_DEV_FUEL_PROFILE1 , _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile1" ,"Fuel Tank #1 Profile" )+":", name1 , flpCombo, "", -1)); out.println(FormRow_TextField(PARM_DEV_FUEL_PROFILE1_SCALE, _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile1Scale" ,"Fuel Tank #1 Profile Scale" )+":", scale1 , 5, 5)); out.println(FormRow_TextField(PARM_DEV_FUEL_PROFILE1_OFFS , _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile1Offset","Fuel Tank #1 Profile Offset")+":", offset1, 5, 5)); fuelItemDisplayed++; } // -- #2 { String name2, scale2, offset2; if (profSel2 == null) { name2 = FuelLevelProfile.FLP_NONE_NAME; scale2 = ""; offset2 = ""; } else if (profSel2.indexOf(":") < 0) { name2 = profSel2.toUpperCase(); if (!name2.equals(FuelLevelProfile.FLP_LINEAR_NAME) && !name2.equals(FuelLevelProfile.FLP_CYLINDER_NAME) ) { name2 = FuelLevelProfile.FLP_NONE_NAME; scale2 = ""; offset2 = ""; } else { scale2 = "1"; offset2 = ""; } } else { FuelLevelProfile flp = new FuelLevelProfile(profSel2, null); name2 = flp.getID(); scale2 = String.valueOf(Math.round(flp.getScale())); offset2 = String.valueOf(Math.round(flp.getOffset())); } if (fuelItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_ComboBox( PARM_DEV_FUEL_PROFILE2 , _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile2" ,"Fuel Tank #2 Profile" )+":", name2 , flpCombo, "", -1)); out.println(FormRow_TextField(PARM_DEV_FUEL_PROFILE2_SCALE, _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile2Scale" ,"Fuel Tank #2 Profile Scale" )+":", scale2 , 5, 5)); out.println(FormRow_TextField(PARM_DEV_FUEL_PROFILE2_OFFS , _editFuelPrf, i18n.getString("DeviceInfo.fuelProfile2Offset","Fuel Tank #2 Profile Offset")+":", offset2, 5, 5)); fuelItemDisplayed++; } } break; } } // ------------------------------------ // -- Maintenance Section int maintItemDisplayed = 0; if ((lastOdomOK && Device.supportsLastOdometer()) || (lastEngHrsOK && Device.supportsLastEngineHours()) || Device.supportsPeriodicMaintenance() || (workHoursOK && Device.supportsHoursOfOperation()) ) { // -- add separator before odometer if maintenance is supported out.println(FormRow_Separator()); } if (lastOdomOK && Device.supportsLastOdometer()) { double odomKM = (_selDev != null)? _selDev.getLastOdometerKM() : 0.0; double offsetKM = (_selDev != null)? _selDev.getOdometerOffsetKM() : 0.0; double rptOdom = distUnits.convertFromKM(odomKM + offsetKM); String odomStr = StringTools.format(rptOdom, "0.0"); String ofsStr = StringTools.format(distUnits.convertFromKM(offsetKM),"0.0"); String ofsText = i18n.getString("DeviceInfo.offset","Offset"); String odom_ofs = distUnitsStr; odom_ofs += " [" + ofsText + " " + ofsStr + "]"; out.println(FormRow_TextField(PARM_REPORT_ODOM, _uiEdit, i18n.getString("DeviceInfo.reportOdometer","Reported Odometer") +":" , odomStr, 10, 11, odom_ofs)); maintItemDisplayed++; } if (lastEngHrsOK && Device.supportsLastEngineHours()) { double engHR = (_selDev != null)? _selDev.getLastEngineHours() : 0.0; double offsetHr = (_selDev != null)? _selDev.getEngineHoursOffset() : 0.0; String hourStr = StringTools.format(engHR + offsetHr, "0.00"); //String lastHrT = i18n.getString("DeviceInfo.lastEngineHours","Last Engine Hours"); String ofsStr = StringTools.format(offsetHr,"0.00"); String ofsText = i18n.getString("DeviceInfo.offset","Offset"); String hour_ofs = i18n.getString("DeviceInfo.hours","Hours"); hour_ofs += " [" + ofsText + " " + ofsStr + "]"; out.println(FormRow_TextField(PARM_REPORT_HOURS, _uiEdit, i18n.getString("DeviceInfo.reportEngineHours","Reported Engine Hours") +":" , hourStr, 10, 11, hour_ofs)); maintItemDisplayed++; } if (Device.supportsPeriodicMaintenance()) { double offsetKM = (_selDev != null)? _selDev.getOdometerOffsetKM() : 0.0; double offsetHR = (_selDev != null)? _selDev.getEngineHoursOffset() : 0.0; // -- Maintenance Notes if (maintNotesOK) { // Domain.Properties.deviceInfo.showMaintenanceNotes=false String noteText = (_selDev!=null)? StringTools.decodeNewline(_selDev.getMaintNotes()) : ""; out.println(FormRow_TextArea(PARM_MAINT_NOTES, _uiEdit, i18n.getString("DeviceInfo.maintNotes" ,"Maintenance Notes")+":", noteText, 3, 70)); maintItemDisplayed++; } // -- Odometer Maintenance / Interval if (maintOdomOK) { // Domain.Properties.deviceInfo.showMaintenanceOdometer=false for (int ndx = 0; ndx < Device.getPeriodicMaintOdometerCount(); ndx++) { String ndxStr = String.valueOf(ndx + 1); if (maintItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } double lastMaintKM = (_selDev != null)? _selDev.getMaintOdometerKM(ndx) : 0.0; double lastMaint = distUnits.convertFromKM(lastMaintKM + offsetKM); String lastMaintSt = StringTools.format(lastMaint, "0.0"); out.println(FormRow_TextField(PARM_MAINT_LASTKM_+ndx, false, i18n.getString("DeviceInfo.mainLast","Last Maintenance #{0}",ndxStr) +":" , lastMaintSt, 10, 11, distUnitsStr)); double intrvKM = (_selDev != null)? _selDev.getMaintIntervalKM(ndx) : 0.0; double intrv = distUnits.convertFromKM(intrvKM); out.print("<tr>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_HEADER+"' nowrap>"+i18n.getString("DeviceInfo.maintInterval","Maintenance Interval #{0}",ndxStr)+":</td>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_DATA+"'>"); out.print(Form_TextField(PARM_MAINT_INTERVKM_+ndx, _uiEdit, String.valueOf((long)intrv), 10, 11)); out.print("&nbsp;" + distUnitsStr); if (_uiEdit) { out.print(" &nbsp;&nbsp;(" + i18n.getString("DeviceInfo.maintReset","Check to Reset Service") + " "); out.print(Form_CheckBox(PARM_MAINT_RESETKM_+ndx, PARM_MAINT_RESETKM_+ndx, _uiEdit, false, null, null)); out.print(")"); } out.print("</td>"); out.print("</tr>\n"); maintItemDisplayed++; } } // -- EngineHours Maintenance / Interval if (maintHoursOK) { // Domain.Properties.deviceInfo.showMaintenanceHours=false for (int ndx = 0; ndx < Device.getPeriodicMaintEngHoursCount(); ndx++) { String ndxStr = String.valueOf(ndx + 1); if (maintItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } double lastMaintHR = (_selDev != null)? _selDev.getMaintEngHoursHR(ndx) : 0.0; double lastMaint = lastMaintHR + offsetHR; // _selDev.getEngineHoursOffset() String lastMaintSt = StringTools.format(lastMaint, "0.00"); out.println(FormRow_TextField(PARM_MAINT_LASTHR_+ndx, false, i18n.getString("DeviceInfo.maintEngHours","Last Eng Hours Maint",ndxStr) +":" , lastMaintSt, 10, 11)); double intrvHR = (_selDev != null)? _selDev.getMaintIntervalHR(ndx) : 0.0; double intrv = intrvHR; out.print("<tr>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_HEADER+"' nowrap>"+i18n.getString("DeviceInfo.maintIntervalHR","Eng Hours Maint Interval",ndxStr)+":</td>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_DATA+"'>"); out.print(Form_TextField(PARM_MAINT_INTERVHR_+ndx, _uiEdit, String.valueOf((long)intrv), 10, 11)); out.print("&nbsp;"); if (_uiEdit) { out.print(" &nbsp;&nbsp;(" + i18n.getString("DeviceInfo.maintResetHR","Check to Reset Service") + " "); out.print(Form_CheckBox(PARM_MAINT_RESETHR_+ndx, PARM_MAINT_RESETHR_+ndx, _uiEdit, false, null, null)); out.print(")"); } out.print("</td>"); out.print("</tr>\n"); maintItemDisplayed++; } } // -- Reminder if (reminderOK) { // Domain.Properties.deviceInfo.showReminderMessage=false String remIntr = (_selDev!=null)? _selDev.getReminderInterval() : ""; String remText = (_selDev!=null)? StringTools.decodeNewline(_selDev.getReminderMessage()) : ""; if (maintItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_TextField(PARM_REMIND_INTERVAL, _uiEdit, i18n.getString("DeviceInfo.reminderInterval","Reminder Interval") +":", remIntr, 30, 60)); out.println(FormRow_TextArea( PARM_REMIND_MESSAGE , _uiEdit, i18n.getString("DeviceInfo.reminderMessage" ,"Reminder Message")+":", remText, 3, 70)); maintItemDisplayed++; } // -- Last/Next Service time if (servTimeOK) { DateTime.DateStringFormat dsf = privLabel.getDateStringFormat(); String dateFmtTxt = privLabel.getDateStringFormatText(locale); String lastServDay = (_selDev!=null)?FormatDayNumber(dsf,_selDev.getLastServiceDayNumber()):""; String nextServDay = (_selDev!=null)?FormatDayNumber(dsf,_selDev.getNextServiceDayNumber()):""; String lastTitle = i18n.getString("DeviceInfo.lastServiceTime","Last Service Time")+":"; String nextTitle = i18n.getString("DeviceInfo.nextServiceTime","Next Service Time")+":"; if (maintItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } if (showDateCal) { String lastOnclick = _uiEdit? "javascript:deviceToggleLastServiceTimeCalendar()" : null; String nextOnclick = _uiEdit? "javascript:deviceToggleNextServiceTimeCalendar()" : null; out.println(FormRow_TextField(LAST_SERVICE_TIME, PARM_LAST_SERVICE_TIME, _uiEdit, lastTitle, lastServDay, lastOnclick, 13, 13)); out.println(FormRow_TextField(NEXT_SERVICE_TIME, PARM_NEXT_SERVICE_TIME, _uiEdit, nextTitle, nextServDay, nextOnclick, 13, 13)); } else { out.println(FormRow_TextField(PARM_LAST_SERVICE_TIME, _uiEdit, lastTitle, lastServDay, 13,13, dateFmtTxt)); out.println(FormRow_TextField(PARM_NEXT_SERVICE_TIME, _uiEdit, nextTitle, nextServDay, 13,13, dateFmtTxt)); } maintItemDisplayed++; } } // Device.supportsPeriodicMaintenance if (workHoursOK && Device.supportsHoursOfOperation()) { String hooStr = (_selDev != null)? _selDev.getHoursOfOperation() : ""; if (maintItemDisplayed > 0) { out.println(FormRow_SubSeparator()); } out.println(FormRow_TextField(PARM_HOURS_OF_OPERATION, _uiEdit, i18n.getString("DeviceInfo.hoursOfOperation","Hours of Operation")+":", hooStr, 100,140)); maintItemDisplayed++; } // ------------------------------------ // -- FaultCode Section if (faultCodesOK && Device.supportsFaultCodes()) { String fs = (_selDev != null)? _selDev.getLastFaultCode() : null; String fc = !StringTools.isBlank(fs)? DTOBDFault.GetFaultString(new RTProperties(fs)) : ""; out.println(FormRow_Separator()); out.print("<tr>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_HEADER+"' nowrap>"+i18n.getString("DeviceInfo.faultCodes","Fault Codes")+":</td>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_DATA+"'>"); out.print(Form_TextField(PARM_FAULT_CODES, false, fc, 60, 60)); out.print("&nbsp;"); if (_uiEdit) { out.print(" &nbsp;&nbsp;(" + i18n.getString("DeviceInfo.faultReset","Check to Reset") + " "); out.print(Form_CheckBox(PARM_FAULT_RESET, PARM_FAULT_RESET, _uiEdit, false, null, null)); out.print(")"); } out.print("</td>"); out.print("</tr>\n"); } // ------------------------------------ // -- Notification Section if (ntfyOK) { int neFldLen = Device.getMaximumNotifyEmailLength(); // 125 ComboOption allowNotfy = ComboOption.getYesNoOption(locale, ((_selDev!=null) && _selDev.getAllowNotify())); out.println(FormRow_Separator()); out.println(FormRow_ComboBox (PARM_DEV_RULE_ALLOW, ntfyEdit , i18n.getString("DeviceInfo.notifyAllow","Notify Enable")+":" , allowNotfy, ComboMap.getYesNoMap(locale), "", -1)); out.println(FormRow_TextField(PARM_DEV_RULE_EMAIL, ntfyEdit , i18n.getString("DeviceInfo.notifyEMail","Notify Email")+":" , (_selDev!=null)?_selDev.getNotifyEmail():"", 95, neFldLen)); out.print("<tr>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_HEADER+"' nowrap>"+i18n.getString("DeviceInfo.lastAlertTime","Last Alert Time")+":</td>"); out.print("<td class='"+CommonServlet.CSS_ADMIN_VIEW_TABLE_DATA+"'>"); long lastNotifyTime = (_selDev != null)? _selDev.getLastNotifyTime() : 0L; if (lastNotifyTime <= 0L) { String na = i18n.getString("DeviceInfo.noAlert","n/a"); out.print(Form_TextField(PARM_LAST_ALERT_TIME, false, na, 10, 10)); } else { String lastAlertTime = reqState.formatDateTime(lastNotifyTime,"--"); out.print(Form_TextField(PARM_LAST_ALERT_TIME, false, lastAlertTime, 24, 24)); if (ntfyEdit) { out.print(" &nbsp;&nbsp;(" + i18n.getString("DeviceInfo.lastAlertReset","Check to Reset Alert") + " "); out.print(Form_CheckBox(PARM_LAST_ALERT_RESET, PARM_LAST_ALERT_RESET, ntfyEdit, false, null, null)); out.print(")"); } } out.print("</td>"); out.print("</tr>\n"); // -- notify selector, subject, body ... String ntfySel = (_selDev!=null)?_selDev.getNotifySelector():""; String ntfyDesc = (_selDev!=null)?_selDev.getNotifyDescription():""; String ntfySubj = (_selDev!=null)?_selDev.getNotifySubject():""; String ntfyText = (_selDev!=null)? StringTools.decodeNewline(_selDev.getNotifyText()) : ""; if (!DeviceInfo.ShowNotifySelector()) { // the Device rule selector is not used, don't show } else if (SHOW_NOTIFY_SELECTOR || // always show? !Device.hasENRE() || // show if non-ENRE is installed !StringTools.isBlank(ntfySel) || // or if the selector or message is specified !StringTools.isBlank(ntfySubj) || !StringTools.isBlank(ntfyText) ) { out.println(FormRow_SubSeparator()); String notifyRuleTitle = i18n.getString("DeviceInfo.notifyRule","Notify Rule"); out.println(FormRow_TextField(PARM_DEV_RULE_SEL , ntfyEdit , i18n.getString("DeviceInfo.ruleSelector","Rule Selector")+":" , ntfySel , 80, 200)); //out.println(FormRow_TextField(PARM_DEV_RULE_DESC , ntfyEdit , i18n.getString("DeviceInfo.notifyDesc" ,"Notify Description")+":", ntfyDesc , 75, 90)); out.println(FormRow_TextField(PARM_DEV_RULE_SUBJ , ntfyEdit , i18n.getString("DeviceInfo.notifySubj" ,"Notify Subject")+":" , ntfySubj , 75, 90)); out.println(FormRow_TextArea( PARM_DEV_RULE_TEXT , ntfyEdit , i18n.getString("DeviceInfo.notifyText" ,"Notify Message")+":" , ntfyText , 5, 70)); //if (privLabel.hasEventNotificationEMail()) { // boolean editWrap = ntfyEdit; // && privLabel.hasEventNotificationEMail() // boolean useEMailWrapper = (_selDev!=null) && _selDev.getNotifyUseWrapper(); // ComboOption wrapEmail = ComboOption.getYesNoOption(locale, useEMailWrapper); // out.println(FormRow_ComboBox(PARM_DEV_RULE_WRAP, editWrap, i18n.getString("DeviceInfo.notifyWrap" ,"Notify Use Wrapper")+":", wrapEmail, ComboMap.getYesNoMap(locale), "", -1, i18n.getString("DeviceInfo.seeEventNotificationEMail","(See 'EventNotificationEMail' tag in 'private.xml')"))); //} else { // Print.logInfo("PrivateLabel EventNotificationEMail Subject/Body not defined"); //} } } // -- Active Corridor if (Device.hasENRE() && Device.supportsActiveCorridor()) { String actvGC = (_selDev != null)? _selDev.getActiveCorridor() : ""; String gcTitle = i18n.getString("DeviceInfo.activeCorridor","Active Corridor") + ":"; String gcList[] = Device.getCorridorIDsForAccount(reqState.getCurrentAccountID()); out.println(FormRow_Separator()); if (gcList != null) { ComboMap gcCombo = new ComboMap(gcList); gcCombo.insert("", i18n.getString("DeviceInfo.corridorNone","(none)")); out.println(FormRow_ComboBox( PARM_ACTIVE_CORRIDOR, _uiEdit, gcTitle, actvGC, gcCombo, "", -1)); } else { out.println(FormRow_TextField(PARM_ACTIVE_CORRIDOR, _uiEdit, gcTitle, actvGC, 20, 20)); } } // -- BorderCrossing if (acctBCEnabled && Device.supportsBorderCrossing()) { long bcTime = (_selDev != null)? _selDev.getLastBorderCrossTime() : 0L; String bcTimeS = reqState.formatDateTime(bcTime, "--"); int bcState = (_selDev != null)? _selDev.getBorderCrossing() : Device.BorderCrossingState.OFF.getIntValue(); boolean bcOK = (bcState == Device.BorderCrossingState.ON.getIntValue())? true : false; ComboOption bcOpt = ComboOption.getYesNoOption(locale, bcOK); out.println(FormRow_Separator()); out.println(FormRow_ComboBox (PARM_BORDER_CROSS_ENAB, _uiEdit, i18n.getString("DeviceInfo.borderCrossingEnabled","Border Crossing Enable")+":", bcOpt, ComboMap.getYesNoMap(locale), "", -1)); out.println(FormRow_TextField(PARM_BORDER_CROSS_TIME, false , i18n.getString("DeviceInfo.borderCrossingTime" ,"Border Crossing Time" )+":", bcTimeS, 30, 30)); } // -- WorkOrder info /* if (_showWorkOrderID(privLabel)) { String actvWO = (_selDev != null)? _selDev.getWorkOrderID() : ""; String woTitle = i18n.getString("DeviceInfo.workOrderID","Work Order ID") + ":"; out.println(FormRow_Separator()); out.println(FormRow_TextField(PARM_WORKORDER_ID , _uiEdit, woTitle, actvWO, 20, 20)); } */ // -- Device URL links if (Device.supportsLinkURL()) { out.println(FormRow_Separator()); out.println(FormRow_TextField(PARM_LINK_URL , _uiEdit, i18n.getString("DeviceInfo.linkURL" ,"Link URL") +":" , (_selDev!=null)?String.valueOf(_selDev.getLinkURL()):"" , 60, 70)); out.println(FormRow_TextField(PARM_LINK_DESC , _uiEdit, i18n.getString("DeviceInfo.linkDescription","Link Description") +":" , (_selDev!=null)?String.valueOf(_selDev.getLinkDescription()):"", 10, 24)); } // -- Fixed location if (fixLocOK) { out.println(FormRow_Separator()); out.println(FormRow_TextField(PARM_FIXED_LAT , _uiEdit, i18n.getString("DeviceInfo.fixedLatitude" ,"Fixed Latitude") +":" , (_selDev!=null)?String.valueOf(_selDev.getFixedLatitude()) :"0.0", 9, 10)); out.println(FormRow_TextField(PARM_FIXED_LON , _uiEdit, i18n.getString("DeviceInfo.fixedLongitude","Fixed Longitude") +":" , (_selDev!=null)?String.valueOf(_selDev.getFixedLongitude()):"0.0", 10, 11)); out.println(FormRow_TextField(PARM_FIXED_ADDRESS , _uiEdit, i18n.getString("DeviceInfo.fixedAddress" ,"Fixed Address") +":" , (_selDev!=null)?_selDev.getFixedAddress():"" , 70, 80)); out.println(FormRow_TextField(PARM_FIXED_PHONE , _uiEdit, i18n.getString("DeviceInfo.fixedPhone" ,"Fixed Contact Phone")+":" , (_selDev!=null)?_selDev.getFixedContactPhone():"" , 30, 40)); } // -- Shared Map start/end times if (shareMapOK) { out.println(FormRow_Separator()); String extraYMD = i18n.getString("DeviceInfo.dateYMD", "(yyyy/mm/dd)"); String startTitle = i18n.getString("DeviceInfo.shareMapStartDay","ShareMap Start Day") + ":"; String endTitle = i18n.getString("DeviceInfo.shareMapEndDay" ,"ShareMap End Day") + ":"; DateTime.DateStringFormat dsf = privLabel.getDateStringFormat(); String startStr = (_selDev != null)? FormatDayNumberTS(dsf,_selDev.getMapShareStartTime(),acctTimeZone) : ""; String endStr = (_selDev != null)? FormatDayNumberTS(dsf,_selDev.getMapShareEndTime() ,acctTimeZone) : ""; if (showDateCal) { String onclickStart = _editShare? "javascript:deviceToggleShareStartCalendar()" : null; out.println(FormRow_TextField(SHARE_START, PARM_SHARE_START, _editShare, startTitle, startStr, onclickStart, 13, 13, extraYMD)); String onclickEnd = _editShare? "javascript:deviceToggleShareEndCalendar()" : null; out.println(FormRow_TextField(SHARE_END , PARM_SHARE_END , _editShare, endTitle , endStr , onclickEnd , 13, 13, extraYMD)); } else { out.println(FormRow_TextField(PARM_SHARE_START, _editShare, startTitle, startStr, 13, 13, extraYMD)); out.println(FormRow_TextField(PARM_SHARE_END , _editShare, endTitle , endStr , 13, 13, extraYMD)); } } // -- Subscriber Section if (subscribeOK) { out.println(FormRow_Separator()); out.println(FormRow_TextField(PARM_SUBSCRIBE_ID , _uiEdit, i18n.getString("DeviceInfo.subscriberID" ,"Subscriber ID")+":" , _selDev.getSubscriberID() , 24, 24)); out.println(FormRow_TextField(PARM_SUBSCRIBE_NAME , _uiEdit, i18n.getString("DeviceInfo.subscriberName" ,"Subscriber Name")+":" , _selDev.getSubscriberName() , 40, 40)); out.println(FormRow_TextField(PARM_SUBSCRIBE_AVATAR, _uiEdit, i18n.getString("DeviceInfo.subscriberAvatar","Subscriber Avatar")+":" , _selDev.getSubscriberAvatar(), 80, 80)); } // -- Last connect time if (SHOW_LAST_CONNECT) { out.println(FormRow_Separator()); out.println(FormRow_TextField(PARM_DEV_LAST_CONNECT , false , i18n.getString("DeviceInfo.lastConnect","Last Connect")+":" , lastConnectTime, 30, 30, i18n.getString("DeviceInfo.serverTime","(Server time)"))); // read-only out.println(FormRow_TextField(PARM_DEV_LAST_EVENT , false , i18n.getString("DeviceInfo.lastEvent" ,"Last Event" )+":" , lastEventTime , 30, 30, i18n.getString("DeviceInfo.deviceTime","(Device time)"))); // read-only } // -- Notes if (notesOK) { String noteText = (_selDev!=null)? StringTools.decodeNewline(_selDev.getNotes()) : ""; out.println(FormRow_Separator()); out.println(FormRow_TextArea(PARM_DEV_NOTES, _uiEdit, i18n.getString("DeviceInfo.notes" ,"General Notes")+":", noteText, 5, 70)); } // -- Custom attributes/fields if (!ListTools.isEmpty(customKeys)) { out.println(FormRow_Separator()); for (String key : customKeys) { // -- PrivateLabel defines description, Device defined value String desc = privLabel.getStringProperty(PrivateLabel.PROP_DeviceInfo_custom_ + key, key); String value = (_selDev != null)? _selDev.getCustomAttribute(key) : ""; out.println(FormRow_TextField(PARM_DEV_CUSTOM_ + key, _uiEdit, desc + ":", value, 40, 50)); } } out.println(FormRow_Separator()); /* DCS propID / config string / TCP Session ID */ if (showDCSPropID || showDCSCfgStr || showTcpSessID) { // -- properties ID if (showDCSPropID) { String propID = (_selDev != null)? _selDev.getDcsPropertiesID() : ""; String gnID = !StringTools.isBlank(propID)? propID : DCServerConfig.DEFAULT_PROP_GROUP_ID; DCServerConfig dcsc = (_selDev != null)? _selDev.getDCServerConfig() : null; Set<String> gnList = (dcsc != null)? dcsc.getPropertyGroupNames() : null; String desc = i18n.getString("DeviceInfo.dcsPropertiesID" ,"DCS Properties ID"); if (gnList != null) { ComboMap gnCM = new ComboMap(gnList); if (!gnList.contains(gnID)) { gnCM.insert(gnID); } out.println(FormRow_ComboBox(PARM_DCS_PROPS_ID, _uiEdit, desc+":", gnID, gnCM, "", 20)); } else { out.println(FormRow_TextField(PARM_DCS_PROPS_ID, _uiEdit, desc+":", gnID, 20, 32)); } } // -- configuration string if (showDCSCfgStr) { String desc = i18n.getString("DeviceInfo.dcsConfigString","DCS Configuration String"); String value = (_selDev != null)? _selDev.getDcsConfigString() : ""; out.println(FormRow_TextField(PARM_DCS_CONFIG_STR, _uiEdit, desc+":", value, 32, 32)); } // -- static TCP session ID if (showTcpSessID) { String desc = i18n.getString("DeviceInfo.tcpSessionID","Static TCP Session ID"); String value = (_selDev != null)? _selDev.getFixedTcpSessionID() : ""; out.println(FormRow_TextField(PARM_TCP_SESSION_ID, _uiEdit, desc+":", value, 32, 32)); } // -- out.println(FormRow_Separator()); } /* Enable Driver ELogs */ if ((_selDev != null) && Account.IsELogEnabled(_selDev.getAccount())) { // -- "Enable Driver ELogs": boolean elogEnabled = _selDev.getELogEnabled(); ComboOption elogOpt = ComboOption.getYesNoOption(locale, elogEnabled); ComboMap elogMap = ComboMap.getYesNoMap(locale); String elogDesc = null; out.println(FormRow_ComboBox(PARM_DEV_ENABLE_ELOG, _uiEdit, i18n.getString("DeviceInfo.enableDriverELogs","Enable Driver ELogs")+":", elogOpt, elogMap, "", -1, elogDesc)); out.println(FormRow_Separator()); } else { //Print.logInfo("HOS/ELog not enabled"); } /* preferred group-id */ if (showPrefGrp) { boolean includeAll = false; ComboMap grpMap = new ComboMap(reqState.createGroupDescriptionMap(true/*includeID*/,includeAll)); if (!includeAll) { grpMap.insert("", i18n.getString("DeviceInfo.noGroup" ,"No {0}",grpTitles)); } String grpSel = (_selDev != null)? _selDev.getGroupID() : ""; out.println(FormRow_ComboBox(PARM_GROUP_ID, _uiEdit, i18n.getString("DeviceInfo.groupID","Preferred {0}",grpTitles)+":", grpSel, grpMap, "", -1)); out.println(FormRow_SubSeparator()); } /* end of field table */ out.println("</table>"); /* DeviceGroup membership */ final OrderedSet<String> grpList = reqState.getDeviceGroupIDList(true/*includeAll*/); out.write("<span style='margin-left:4px; margin-top:10px; font-weight:bold;'>"); out.write( i18n.getString("DeviceInfo.groupMembership","{0} Membership:",grpTitles)); out.write( "</span>\n"); out.write("<div style='border: 1px solid black; margin: 2px 20px 5px 10px; height:80px; width:400px; overflow-x: hidden; overflow-y: scroll;'>\n"); out.write("<table>\n"); for (int g = 0; g < grpList.size(); g++) { String grpID = grpList.get(g); String pname = PARM_DEV_GROUP_ + grpID; String desc = reqState.getDeviceGroupDescription(grpID,false/*!rtnDispName*/); if (!desc.equals(grpID)) { desc += " ["+grpID+"]"; } out.write("<tr>"); out.write("<td><label for='"+grpID+"'>"+FilterText(desc)+" : </label></td>"); // [2.6.3-B21] out.write("<td>"); if (grpID.equalsIgnoreCase(DeviceGroup.DEVICE_GROUP_ALL)) { out.write(Form_CheckBox(null,pname,false,true,null,null)); } else { boolean devInGroup = (_selDev != null)? DeviceGroup.isDeviceInDeviceGroup(_selDev.getAccountID(), grpID, _selDevID) : false; out.write(Form_CheckBox(grpID,pname,_uiEdit,devInGroup,null,null)); } out.write("</td>"); out.write("</tr>\n"); } out.write("</table>\n"); out.write("</div>\n"); /* end of form */ out.write("<hr style='margin-bottom:5px;'>\n"); out.write("<span style='padding-left:10px'>&nbsp;</span>\n"); if (_uiEdit) { out.write("<input type='submit' name='"+PARM_SUBMIT_CHG+"' value='"+i18n.getString("DeviceInfo.change","Change")+"'>\n"); out.write("<span style='padding-left:10px'>&nbsp;</span>\n"); out.write("<input type='button' name='"+PARM_BUTTON_CANCEL+"' value='"+i18n.getString("DeviceInfo.cancel","Cancel")+"' onclick=\"javascript:openURL('"+editURL+"','_self');\">\n"); // target='_top' } else { out.write("<input type='button' name='"+PARM_BUTTON_BACK+"' value='"+i18n.getString("DeviceInfo.back","Back")+"' onclick=\"javascript:openURL('"+editURL+"','_self');\">\n"); // target='_top' } out.write("</form>\n"); } }; } else if (_uiCmd) { final boolean _editProps = _allowCommand && (selDev != null); final DeviceCmdHandler _dcHandler = dcHandler; // non-null here HTML_CONTENT = new HTMLOutput(CommonServlet.CSS_CONTENT_FRAME, m) { public void write(PrintWriter out) throws IOException { /* frame title */ String frameTitle = i18n.getString("DeviceInfo.setDeviceProperties","({0}) Set {1} Properties", _dcHandler.getServerDescription(), devTitles[0]); out.write("<span class='"+CommonServlet.CSS_MENU_TITLE+"'>"+frameTitle+"</span><br/>\n"); out.write("<hr>\n"); /* Device Command/Properties content */ String editURL = DeviceInfo.this.encodePageURL(reqState);//, RequestProperties.TRACK_BASE_URI()); _dcHandler.writeCommandForm(out, reqState, _selDev, editURL, _editProps); } }; } else if (_uiSms) { final boolean _editSmsCmd = _allowSmsCmd && (selDev != null); final DeviceCmdHandler _dcHandler = dcHandler; // non-null here HTML_CONTENT = new HTMLOutput(CommonServlet.CSS_CONTENT_FRAME, m) { public void write(PrintWriter out) throws IOException { /* frame title */ String frameTitle = i18n.getString("DeviceInfo.setDeviceSMS","({0}) Send {1} SMS", _dcHandler.getServerDescription(), devTitles[0]); out.write("<span class='"+CommonServlet.CSS_MENU_TITLE+"'>"+frameTitle+"</span><br/>\n"); out.write("<hr>\n"); /* Device Command/Properties content */ String editURL = DeviceInfo.this.encodePageURL(reqState);//, RequestProperties.TRACK_BASE_URI()); _dcHandler.writeCommandForm(out, reqState, _selDev, editURL, _editSmsCmd); } }; } /* write frame */ String onloadAlert = error? JS_alert(true,m) : null; String onload = (_uiCmd || _uiSms)? "javascript:devCommandOnLoad();" : onloadAlert; CommonServlet.writePageFrame( reqState, onload,null, // onLoad/onUnload HTML_CSS, // Style sheets HTML_JS, // Javascript null, // Navigation HTML_CONTENT); // Content } // ------------------------------------------------------------------------ }
Kiosani/OpenGTS
src/org/opengts/war/track/page/DeviceInfo.java
Java
apache-2.0
231,509
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package com.javadeobfuscator.deobfuscator.org.objectweb.asm.tree.analysis; import java.util.List; import com.javadeobfuscator.deobfuscator.org.objectweb.asm.Type; import com.javadeobfuscator.deobfuscator.org.objectweb.asm.tree.AbstractInsnNode; /** * A semantic bytecode interpreter. More precisely, this interpreter only * manages the computation of values from other values: it does not manage the * transfer of values to or from the stack, and to or from the local variables. * This separation allows a generic bytecode {@link Analyzer} to work with * various semantic interpreters, without needing to duplicate the code to * simulate the transfer of values. * * @param <V> * type of the Value used for the analysis. * * @author Eric Bruneton */ public abstract class Interpreter<V extends Value> { protected final int api; protected Interpreter(final int api) { this.api = api; } /** * Creates a new value that represents the given type. * * Called for method parameters (including <code>this</code>), exception * handler variable and with <code>null</code> type for variables reserved * by long and double types. * * @param type * a primitive or reference type, or <tt>null</tt> to represent * an uninitialized value. * @return a value that represents the given type. The size of the returned * value must be equal to the size of the given type. */ public abstract V newValue(Type type); /** * Interprets a bytecode instruction without arguments. This method is * called for the following opcodes: * * ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, * ICONST_5, LCONST_0, LCONST_1, FCONST_0, FCONST_1, FCONST_2, DCONST_0, * DCONST_1, BIPUSH, SIPUSH, LDC, JSR, GETSTATIC, NEW * * @param insn * the bytecode instruction to be interpreted. * @return the result of the interpretation of the given instruction. * @throws AnalyzerException * if an error occured during the interpretation. */ public abstract V newOperation(AbstractInsnNode insn) throws AnalyzerException; /** * Interprets a bytecode instruction that moves a value on the stack or to * or from local variables. This method is called for the following opcodes: * * ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE, LSTORE, FSTORE, DSTORE, * ASTORE, DUP, DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2, SWAP * * @param insn * the bytecode instruction to be interpreted. * @param value * the value that must be moved by the instruction. * @return the result of the interpretation of the given instruction. The * returned value must be <tt>equal</tt> to the given value. * @throws AnalyzerException * if an error occured during the interpretation. */ public abstract V copyOperation(AbstractInsnNode insn, V value) throws AnalyzerException; /** * Interprets a bytecode instruction with a single argument. This method is * called for the following opcodes: * * INEG, LNEG, FNEG, DNEG, IINC, I2L, I2F, I2D, L2I, L2F, L2D, F2I, F2L, * F2D, D2I, D2L, D2F, I2B, I2C, I2S, IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, * TABLESWITCH, LOOKUPSWITCH, IRETURN, LRETURN, FRETURN, DRETURN, ARETURN, * PUTSTATIC, GETFIELD, NEWARRAY, ANEWARRAY, ARRAYLENGTH, ATHROW, CHECKCAST, * INSTANCEOF, MONITORENTER, MONITOREXIT, IFNULL, IFNONNULL * * @param insn * the bytecode instruction to be interpreted. * @param value * the argument of the instruction to be interpreted. * @return the result of the interpretation of the given instruction. * @throws AnalyzerException * if an error occured during the interpretation. */ public abstract V unaryOperation(AbstractInsnNode insn, V value) throws AnalyzerException; /** * Interprets a bytecode instruction with two arguments. This method is * called for the following opcodes: * * IALOAD, LALOAD, FALOAD, DALOAD, AALOAD, BALOAD, CALOAD, SALOAD, IADD, * LADD, FADD, DADD, ISUB, LSUB, FSUB, DSUB, IMUL, LMUL, FMUL, DMUL, IDIV, * LDIV, FDIV, DDIV, IREM, LREM, FREM, DREM, ISHL, LSHL, ISHR, LSHR, IUSHR, * LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR, LCMP, FCMPL, FCMPG, DCMPL, * DCMPG, IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, * IF_ACMPEQ, IF_ACMPNE, PUTFIELD * * @param insn * the bytecode instruction to be interpreted. * @param value1 * the first argument of the instruction to be interpreted. * @param value2 * the second argument of the instruction to be interpreted. * @return the result of the interpretation of the given instruction. * @throws AnalyzerException * if an error occured during the interpretation. */ public abstract V binaryOperation(AbstractInsnNode insn, V value1, V value2) throws AnalyzerException; /** * Interprets a bytecode instruction with three arguments. This method is * called for the following opcodes: * * IASTORE, LASTORE, FASTORE, DASTORE, AASTORE, BASTORE, CASTORE, SASTORE * * @param insn * the bytecode instruction to be interpreted. * @param value1 * the first argument of the instruction to be interpreted. * @param value2 * the second argument of the instruction to be interpreted. * @param value3 * the third argument of the instruction to be interpreted. * @return the result of the interpretation of the given instruction. * @throws AnalyzerException * if an error occured during the interpretation. */ public abstract V ternaryOperation(AbstractInsnNode insn, V value1, V value2, V value3) throws AnalyzerException; /** * Interprets a bytecode instruction with a variable number of arguments. * This method is called for the following opcodes: * * INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC, INVOKEINTERFACE, * MULTIANEWARRAY and INVOKEDYNAMIC * * @param insn * the bytecode instruction to be interpreted. * @param values * the arguments of the instruction to be interpreted. * @return the result of the interpretation of the given instruction. * @throws AnalyzerException * if an error occured during the interpretation. */ public abstract V naryOperation(AbstractInsnNode insn, List<? extends V> values) throws AnalyzerException; /** * Interprets a bytecode return instruction. This method is called for the * following opcodes: * * IRETURN, LRETURN, FRETURN, DRETURN, ARETURN * * @param insn * the bytecode instruction to be interpreted. * @param value * the argument of the instruction to be interpreted. * @param expected * the expected return type of the analyzed method. * @throws AnalyzerException * if an error occured during the interpretation. */ public abstract void returnOperation(AbstractInsnNode insn, V value, V expected) throws AnalyzerException; /** * Merges two values. The merge operation must return a value that * represents both values (for instance, if the two values are two types, * the merged value must be a common super type of the two types. If the two * values are integer intervals, the merged value must be an interval that * contains the previous ones. Likewise for other types of values). * * @param v * a value. * @param w * another value. * @return the merged value. If the merged value is equal to <tt>v</tt>, * this method <i>must</i> return <tt>v</tt>. */ public abstract V merge(V v, V w); }
FFY00/deobfuscator
src/main/java/com/javadeobfuscator/deobfuscator/org/objectweb/asm/tree/analysis/Interpreter.java
Java
apache-2.0
9,894
package com.wincom.mstar; public class Alarm { private int signalId; private String station; private String deviceName; private String signalName; private String alarmBegin; private String alarmEnd; private String alarmLevel; private int level; private int serial; private int parent_id; private int ackStatus; public int getSignalId() { return signalId; } public void setSignalId(int signalId) { this.signalId = signalId; } public String getStation() { return station; } public void setStation(String station) { this.station = station; } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getSignalName() { return signalName; } public void setSignalName(String signalName) { this.signalName = signalName; } public String getAlarmBegin() { return alarmBegin; } public void setAlarmBegin(String alarmBegin) { this.alarmBegin = alarmBegin; } public String getAlarmEnd() { return alarmEnd; } public void setAlarmEnd(String alarmEnd) { this.alarmEnd = alarmEnd; } public String getAlarmLevel() { return alarmLevel; } public void setAlarmLevel(String alarmLevel) { this.alarmLevel = alarmLevel; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public int getSerial() { return serial; } public void setSerial(int serial) { this.serial = serial; } public int getParent_id() { return parent_id; } public void setParent_id(int parent_id) { this.parent_id = parent_id; } public void setRemarks(String remarks) { } public String getRemarks() { return ""; } public int getAckStatus() { return ackStatus; } public void setAckStatus(int ackStatus) { this.ackStatus = ackStatus; } }
xtwxy/cassandra-tests
mstar-server/src/main/java/com/wincom/mstar/Alarm.java
Java
apache-2.0
1,909
<?php /* * This file is part of the FilemanagerBundle package. * * (c) Trimech Mahdi <http://www.trimech-mahdi.fr/> * @author: Trimech Mehdi <trimechmehdi11@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Core\FilemanagerBundle\Manager; use Core\FilemanagerBundle\Entity\Folders; use Doctrine\ORM\EntityManager; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class FolderManager * @package Core\FilemanagerBundle\Manager */ class FolderManager { /** * @var EntityManager */ private $entityManager; /** * @var string */ private $rootDir; /** * FolderManager constructor. * @param EntityManager $entityManager */ public function __construct(EntityManager $entityManager, $rootDir = '') { $this->entityManager = $entityManager; $this->rootDir = $rootDir; } /** * @param $path * @param $name * @param $fullname * @param Folders|null $parent * @return Folders */ public function create($path, $name, $fullname, Folders $parent = null, $permissions = null) { $folder = new Folders(); $folder->setName($name); $folder->setFullName($fullname); $folder->setPermissions($permissions); if ($parent) { $folder->setParent($parent); $path = $parent->getPath() . '/' . $path; if (!$permissions){ $folder->setPermissions($parent->getPermissions()); } } $folder->setPath($path); $this->entityManager->persist($folder); $this->entityManager->flush(); return $folder; } /** * @param $path * @param $name * @param $fullname * @param $id * @return Folders|null|object */ public function update($path, $name, $fullname, $id) { $folder = $this->find($id); if (!$folder) { throw new NotFoundHttpException('Folder ' . $id . ' dosnt exist.'); } $folder->setName($name); $folder->setFullName($fullname); $folder->setPath($path); $this->entityManager->persist($folder); $this->entityManager->flush(); return $folder; } /** * @param $id * @return bool */ public function delete($id) { $folder = $this->find($id); if (!$folder) { throw new NotFoundHttpException('Folder ' . $id . ' dosnt exist.'); } $this->entityManager->remove($folder); $this->entityManager->flush(); return true; } /** * @param $id * @return Folders|null|object */ public function find($id) { return $this->repository()->find($id); } /** * @param array $criteria * @return array|\Core\FilemanagerBundle\Entity\Folders[] */ public function findBy(array $criteria) { return $this->repository()->findBy($criteria); } /** * @param array $criteria * @return Folders|null|object */ public function findOneBy(array $criteria) { return $this->repository()->findOneBy($criteria); } /** * @return array|\Core\FilemanagerBundle\Entity\Folders[] */ public function findAll() { return $this->repository()->findAll(); } /** * @return \Core\FilemanagerBundle\Repository\FoldersRepository|\Doctrine\ORM\EntityRepository */ public function repository() { return $this->entityManager->getRepository('FilemanagerBundle:Folders'); } /** * @return \Doctrine\ORM\QueryBuilder */ public function getQuery() { return $this->repository()->createQueryBuilder('e'); } /** * @return Folders|null|object */ public function main() { return $this->findOneBy(array( 'lvl' => 0, )); } /** * @return Folders */ public function initRootDir() { $path = $this->rootDir . '/../web/data'; $name = $fullname = str_replace($this->rootDir . '/../web/', '', $path); return $this->create($name, $name, $fullname, null, 2); } }
medooch/filemanager
Manager/FolderManager.php
PHP
apache-2.0
4,307
# Copyright (C) 2017,2019 Rodrigo Jose Hernandez Cordoba # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. bl_info = { "name": "AeonGames Skeleton Format (.skl)", "author": "Rodrigo Hernandez", "version": (1, 0, 0), "blender": (2, 80, 0), "location": "File > Export > Export AeonGames Skeleton", "description": "Exports an armature to an AeonGames Skeleton (SKL) file", "warning": "", "wiki_url": "", "tracker_url": "", "category": "Import-Export"} import bpy from . import export def skl_menu_func(self, context): self.layout.operator( export.SKL_OT_exporter.bl_idname, text="AeonGames Skeleton (.skl)") def register(): bpy.utils.register_class(export.SKL_OT_exporter) bpy.types.TOPBAR_MT_file_export.append(skl_menu_func) if __name__ == "__main__": register()
AeonGames/AeonEngine
tools/blender/addons/io_skeleton_skl/__init__.py
Python
apache-2.0
1,334
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.internal.core.type.codec; import com.datastax.oss.driver.api.core.ProtocolVersion; import com.datastax.oss.driver.api.core.data.TupleValue; import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.TupleType; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; import com.datastax.oss.driver.api.core.type.reflect.GenericType; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import net.jcip.annotations.ThreadSafe; @ThreadSafe public class TupleCodec implements TypeCodec<TupleValue> { private final TupleType cqlType; public TupleCodec(@NonNull TupleType cqlType) { this.cqlType = cqlType; } @NonNull @Override public GenericType<TupleValue> getJavaType() { return GenericType.TUPLE_VALUE; } @NonNull @Override public DataType getCqlType() { return cqlType; } @Override public boolean accepts(@NonNull Object value) { return (value instanceof TupleValue) && ((TupleValue) value).getType().equals(cqlType); } @Override public boolean accepts(@NonNull Class<?> javaClass) { return TupleValue.class.equals(javaClass); } @Nullable @Override public ByteBuffer encode(@Nullable TupleValue value, @NonNull ProtocolVersion protocolVersion) { if (value == null) { return null; } if (!value.getType().equals(cqlType)) { throw new IllegalArgumentException( String.format("Invalid tuple type, expected %s but got %s", cqlType, value.getType())); } // Encoding: each field as a [bytes] value ([bytes] = int length + contents, null is // represented by -1) int toAllocate = 0; for (int i = 0; i < value.size(); i++) { ByteBuffer field = value.getBytesUnsafe(i); toAllocate += 4 + (field == null ? 0 : field.remaining()); } ByteBuffer result = ByteBuffer.allocate(toAllocate); for (int i = 0; i < value.size(); i++) { ByteBuffer field = value.getBytesUnsafe(i); if (field == null) { result.putInt(-1); } else { result.putInt(field.remaining()); result.put(field.duplicate()); } } return (ByteBuffer) result.flip(); } @Nullable @Override public TupleValue decode(@Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { if (bytes == null) { return null; } // empty byte buffers will result in empty values try { ByteBuffer input = bytes.duplicate(); TupleValue value = cqlType.newValue(); int i = 0; while (input.hasRemaining()) { if (i > cqlType.getComponentTypes().size()) { throw new IllegalArgumentException( String.format( "Too many fields in encoded tuple, expected %d", cqlType.getComponentTypes().size())); } int elementSize = input.getInt(); ByteBuffer element; if (elementSize < 0) { element = null; } else { element = input.slice(); element.limit(elementSize); input.position(input.position() + elementSize); } value = value.setBytesUnsafe(i, element); i += 1; } return value; } catch (BufferUnderflowException e) { throw new IllegalArgumentException("Not enough bytes to deserialize a tuple", e); } } @NonNull @Override public String format(@Nullable TupleValue value) { if (value == null) { return "NULL"; } if (!value.getType().equals(cqlType)) { throw new IllegalArgumentException( String.format("Invalid tuple type, expected %s but got %s", cqlType, value.getType())); } CodecRegistry registry = cqlType.getAttachmentPoint().getCodecRegistry(); StringBuilder sb = new StringBuilder("("); boolean first = true; for (int i = 0; i < value.size(); i++) { if (first) { first = false; } else { sb.append(","); } DataType elementType = cqlType.getComponentTypes().get(i); TypeCodec<Object> codec = registry.codecFor(elementType); sb.append(codec.format(value.get(i, codec))); } sb.append(")"); return sb.toString(); } @Nullable @Override public TupleValue parse(@Nullable String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) { return null; } TupleValue tuple = cqlType.newValue(); int length = value.length(); int position = ParseUtils.skipSpaces(value, 0); if (value.charAt(position) != '(') { throw new IllegalArgumentException( String.format( "Cannot parse tuple value from \"%s\", at character %d expecting '(' but got '%c'", value, position, value.charAt(position))); } position++; position = ParseUtils.skipSpaces(value, position); CodecRegistry registry = cqlType.getAttachmentPoint().getCodecRegistry(); int field = 0; while (position < length) { if (value.charAt(position) == ')') { position = ParseUtils.skipSpaces(value, position + 1); if (position == length) { return tuple; } throw new IllegalArgumentException( String.format( "Cannot parse tuple value from \"%s\", at character %d expecting EOF or blank, but got \"%s\"", value, position, value.substring(position))); } int n; try { n = ParseUtils.skipCQLValue(value, position); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format( "Cannot parse tuple value from \"%s\", invalid CQL value at field %d (character %d)", value, field, position), e); } String fieldValue = value.substring(position, n); DataType elementType = cqlType.getComponentTypes().get(field); TypeCodec<Object> codec = registry.codecFor(elementType); Object parsed; try { parsed = codec.parse(fieldValue); } catch (Exception e) { throw new IllegalArgumentException( String.format( "Cannot parse tuple value from \"%s\", invalid CQL value at field %d (character %d): %s", value, field, position, e.getMessage()), e); } tuple = tuple.set(field, parsed, codec); position = n; position = ParseUtils.skipSpaces(value, position); if (position == length) { throw new IllegalArgumentException( String.format( "Cannot parse tuple value from \"%s\", at field %d (character %d) expecting ',' or ')', but got EOF", value, field, position)); } if (value.charAt(position) == ')') { continue; } if (value.charAt(position) != ',') { throw new IllegalArgumentException( String.format( "Cannot parse tuple value from \"%s\", at field %d (character %d) expecting ',' but got '%c'", value, field, position, value.charAt(position))); } ++position; // skip ',' position = ParseUtils.skipSpaces(value, position); field += 1; } throw new IllegalArgumentException( String.format( "Cannot parse tuple value from \"%s\", at field %d (character %d) expecting CQL value or ')', got EOF", value, field, position)); } }
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodec.java
Java
apache-2.0
8,204
/* * Copyright (c) 1999 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ # include "stlport_prefix.h" # ifndef _STLP_NO_MBSTATE_T #include <stl/_codecvt.h> #include <stl/_algobase.h> _STLP_BEGIN_NAMESPACE //---------------------------------------------------------------------- // codecvt<char, char, mbstate_t> codecvt<char, char, mbstate_t>::~codecvt() {} int codecvt<char, char, mbstate_t>::do_length(const mbstate_t&, const char* from, const char* end, size_t mx) const { return (int)(min) ( __STATIC_CAST(size_t, (end - from)), mx); } int codecvt<char, char, mbstate_t>::do_max_length() const _STLP_NOTHROW { return 1; } bool codecvt<char, char, mbstate_t>::do_always_noconv() const _STLP_NOTHROW { return true; } int codecvt<char, char, mbstate_t>::do_encoding() const _STLP_NOTHROW { return 1; } codecvt_base::result codecvt<char, char, mbstate_t>::do_unshift(mbstate_t& /* __state */, char* __to, char* /* __to_limit */, char*& __to_next) const { __to_next = __to; return noconv; } codecvt_base::result codecvt<char, char, mbstate_t>::do_in (mbstate_t& /* __state */ , const char* __from, const char* /* __from_end */, const char*& __from_next, char* __to, char* /* __to_end */, char*& __to_next) const { __from_next = __from; __to_next = __to; return noconv; } codecvt_base::result codecvt<char, char, mbstate_t>::do_out(mbstate_t& /* __state */, const char* __from, const char* /* __from_end */, const char*& __from_next, char* __to, char* /* __to_limit */, char*& __to_next) const { __from_next = __from; __to_next = __to; return noconv; } # ifndef _STLP_NO_WCHAR_T //---------------------------------------------------------------------- // codecvt<wchar_t, char, mbstate_t> codecvt<wchar_t, char, mbstate_t>::~codecvt() {} codecvt<wchar_t, char, mbstate_t>::result codecvt<wchar_t, char, mbstate_t>::do_out(state_type& /* state */, const intern_type* from, const intern_type* from_end, const intern_type*& from_next, extern_type* to, extern_type* to_limit, extern_type*& to_next) const { ptrdiff_t len = (min) (from_end - from, to_limit - to); copy(from, from + len, to); from_next = from + len; to_next = to + len; return ok; } codecvt<wchar_t, char, mbstate_t>::result codecvt<wchar_t, char, mbstate_t>::do_in (state_type& /* state */, const extern_type* from, const extern_type* from_end, const extern_type*& from_next, intern_type* to, intern_type* to_limit, intern_type*& to_next) const { ptrdiff_t len = (min) (from_end - from, to_limit - to); copy(from, from + len, to); from_next = from + len; to_next = to + len; return ok; } codecvt<wchar_t, char, mbstate_t>::result codecvt<wchar_t, char, mbstate_t>::do_unshift(state_type& /* state */, extern_type* to, extern_type* , extern_type*& to_next) const { to_next = to; return noconv; } int codecvt<wchar_t, char, mbstate_t>::do_encoding() const _STLP_NOTHROW { return 1; } bool codecvt<wchar_t, char, mbstate_t>::do_always_noconv() const _STLP_NOTHROW { return true; } int codecvt<wchar_t, char, mbstate_t>::do_length(const state_type&, const extern_type* from, const extern_type* end, size_t mx) const { return (int)(min) ((size_t) (end - from), mx); } int codecvt<wchar_t, char, mbstate_t>::do_max_length() const _STLP_NOTHROW { return 1; } # endif /* wchar_t */ _STLP_END_NAMESPACE # endif /* _STLP_NO_MBSTATE_T */ // Local Variables: // mode:C++ // End:
aestesis/elektronika
src/STLport/src/codecvt.cpp
C++
apache-2.0
5,769
<div class="serviceaddressPage"> <form> <div class="right-inner-addon"> <input id="address" type="text" class="form-control searchplace" [(ngModel)]="userAddress" name="user Address" placeholder="Search for your service needed location on Map and drag marker to your place." /> </div> <div> <sebm-google-map [latitude]="serviceinfo.latitude" [longitude]="serviceinfo.longitude" [zoom]="serviceinfo.zoom" [disableDefaultUI]="false" [zoomControl]="true"> <sebm-google-map-marker [latitude]="serviceinfo.latitude" [longitude]="serviceinfo.longitude" [markerDraggable]="true" (dragEnd)="markerPostionChanged($event)"></sebm-google-map-marker> </sebm-google-map> </div> <div class="form-group"> <label for="Address">Please modify as any specific location address in selected place in Map:</label> <textarea class="form-control" cols="10" rows="7" [(ngModel)]="serviceinfo.address" (ngModelChange)="addressChange($event)" name="address"></textarea> </div> </form> </div>
chaithu563/myserviceneed
app/core/userview/postservice/address/address.html
HTML
apache-2.0
1,106
/* * Copyright 2016-2018 Axioma srl. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.holonplatform.jaxrs.swagger.v3.internal.endpoints; import javax.ws.rs.GET; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Application; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import io.swagger.v3.oas.annotations.Operation; /** * Default JAX-RS resource to implement an OpenAPI documentation endpoint. * <p> * This endpoint uses a <code>type</code> path parameter to declare the OpenAPI output type, which can be either * <code>json</code> or <code>yaml</code>. * </p> * * @since 5.2.0 */ public class PathParamOpenApiEndpoint extends AbstractOpenApiEndpoint { @Context Application application; @GET @Produces({ MediaType.APPLICATION_JSON, "application/yaml" }) @Operation(hidden = true) public Response getOpenApi(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type) { return getApi(application, headers, uriInfo, type); } }
holon-platform/holon-jaxrs
swagger-v3/src/main/java/com/holonplatform/jaxrs/swagger/v3/internal/endpoints/PathParamOpenApiEndpoint.java
Java
apache-2.0
1,662
<!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="style.css" /> <title>Duel - Alexaviers Games</title> </head> <body> <div id="page"> <div id="game"> <canvas width="600" height="600"></canvas> </div> <div id="menu-info"> Move with arrows, shoot with space. Select with Return. </div> <div id="status-bar"> <div id=player1-health"> </div> </div> <div id="game-info"> FPS: <span id="fps"></span> <h1>Game states</h1> Minimalistic example using all jaws convenience methods and game states. Game states are an proven and robust way of separating various parts of the game. For example: An intro, a menu, the actual game play, the high score list. That's 4 different game states right there. <br /> <br /> A gamestate is just an normal javascript object with the methods setup(), update() and draw(). In this example we make 2 Constructors: <code> PlayState()</code> and <code> MenuState()</code> . <br /> We switch active game state with: <code> jaws.switchGameState(a_game_state_or_function)</code> </div > <h3>jaws log</h3> <div id="jaws-log"></div> </div> <script type="text/javascript" src="jaws.js"></script> <script type="text/javascript" src="duel.js"></script> <script> /* * * PlayState is the actual game play. We switch to it once user choses "Start game" * */ var fps = document.getElementById("fps") /* * * MenuState is our lobby/welcome menu were gamer can chose start, high score and settings. * For this example we have only implemented start. Start switches active game state by simply: * jaws.switchGameState(play) (jaws.switchGameState(PlayState) would have worked too) * */ function MenuState() { var index = 0 var items = ["Start", "Shop", "Highscore"] this.setup = function() { index = 0 jaws.on_keydown(["down", "s"], function() { index++; if(index >= items.length) { index = items.length - 1 } }) jaws.on_keydown(["up", "w"], function() { index--; if(index < 0) { index = 0 } }) jaws.on_keydown(["enter", "space"], function() { if(items[index] == "Start") { jaws.switchGameState(PlayState, { fps : 30, height : 768, width : 1024 }) } if(items[index] == "Shop") { jaws.switchGameState(ShopState, { fps : 30, height : 768, width : 1024 }) } }) } this.draw = function() { jaws.clear() for(var i = 0; items[i]; i++) { // jaws.context.translate(0.5, 0.5) jaws.context.font = "bold 50pt terminal"; jaws.context.lineWidth = 10 jaws.context.fillStyle = (i == index) ? "Red" : "Black" jaws.context.strokeStyle = "rgba(200,200,200,0.0)" jaws.context.fillText(items[i], 30, 100 + i * 60) } } } function ShopState() { var index = 0 var items = ["Cannon", "HeatSeeker", "Mine"] this.setup = function() { index = 0 jaws.on_keydown(["down", "s"], function() { index++; if(index >= items.length) { index = items.length - 1 } }) jaws.on_keydown(["up", "w"], function() { index--; if(index < 0) { index = 0 } }) jaws.on_keydown(["enter", "space"], function() { if(items[index] == "Cannon") { jaws.switchGameState(new duel.PlayState({ gun : new duel.Cannon(), mineLauncher : new duel.MineLauncher() }), { fps : 30, height : 768, width : 1024 }) } if(items[index] == "HeatSeeker") { jaws.switchGameState(new duel.PlayState({ gun : new duel.MissileLauncher(), mineLauncher : new duel.MineLauncher() }), { fps : 30, height : 768, width : 1024 }) } }) } this.draw = function() { jaws.clear() for(var i = 0; items[i]; i++) { // jaws.context.translate(0.5, 0.5) jaws.context.font = "bold 50pt terminal"; jaws.context.lineWidth = 10 jaws.context.fillStyle = (i == index) ? "Red" : "Black" jaws.context.strokeStyle = "rgba(200,200,200,0.0)" jaws.context.fillText(items[i], 30, 100 + i * 60) } } } /* * * Our script-entry point * */ window.onload = function() { duel.load(); duel.showMenu(); } </script> </body> </html>
stickycode/dragonfly
jaws.html
HTML
apache-2.0
4,667
<?php namespace Home\Model; use Think\Model; class IndexModel extends Model{ /** * index页面的图片显示 * 1.根据design表中划分字段design_devide字段查找到所有的第一部分的图片,只找出最热门的4张 * 2.同理找出第二部分的4张 * 3.拼装成一个大数组,对大数组中的所有的图片路径进行处理 * 4.最后将处理好的数组返回给index控制器中的index方法 * @return [type] [description]/ */ function getItems(){ $design = M("design"); //获取主页划分的第一部分的图片 $result1 = $design->where('devide=1')->order('hot desc')->field('id,show_img')->select(); $result2 = $design->where('devide=2')->order('hot desc')->field('id,show_img')->select(); $result3 = $design->where('devide=3')->order('hot desc')->field('id,show_img')->select(); // show_bug($devideResult); //拼装3个单元元素的数组 $result = array($result1,$result2,$result3); foreach ($result as $key => $value) { for($i=0; $i<4; $i++){ // echo DESIGN_IMG.$value[$i]['design_show_img']; $result[$key][$i]['show_img'] = DESIGN_IMG.$value[$i]['show_img']; } } // show_bug($result); return $result; } /** * showDesin页面的图片显示 * 1.查找design表中所有的design_id,design_show_img字段 * 2.将所有的元素,切分成每个单元4个元素 * 3.拼装图片路径,图片源路径+数据库的图片名 * 4.给showDesign方法控制器调用 * @return [array] [所有设计分切后的数组] */ function findDesign(){ $design = M("design"); //获取所有元素 $result = $design->where('id>=0')->field('id,show_img')->select(); //将元素组分隔四分组成新的数组 $devideResult = array_chunk ($result, 4); // show_bug($devideResult); foreach ($devideResult as $key => $value) { for($i=0;$i<4;$i++){ // echo DESIGN_IMG.$value[$i]['design_show_img']; $devideResult[$key][$i]['show_img'] = DESIGN_IMG.$value[$i]['show_img']; } } return $devideResult; } }
suoyuesmile/zxyClothPat
Apps/Home/Model/IndexModel.class.php
PHP
apache-2.0
2,266
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/util/tensor_slice_reader.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/port.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/util/saved_tensor_slice_util.h" #include "tensorflow/core/util/tensor_slice_reader_cache.h" #include "tensorflow/core/util/tensor_slice_writer.h" namespace tensorflow { namespace checkpoint { namespace { // A simple test where we write a few tensor slices with a number of tensor // slice writers and then read them back from a tensor slice reader. // // We have a 2-d tensor of shape 4 X 5 that looks like this: // // 0 1 2 3 4 // 5 6 7 8 9 // 10 11 12 13 14 // 15 16 17 18 19 // // We assume this is a row-major matrix. void SimpleFloatHelper(TensorSliceWriter::CreateBuilderFunction create_function, TensorSliceReader::OpenTableFunction open_function) { const string fname_base = io::JoinPath(testing::TmpDir(), "float_checkpoint"); TensorShape shape({4, 5}); // File #0 contains a slice that is the top two rows: // // 0 1 2 3 4 // 5 6 7 8 9 // . . . . . // . . . . . { const string fname = strings::StrCat(fname_base, "_0"); TensorSliceWriter writer(fname, create_function); const float data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TensorSlice slice = TensorSlice::ParseOrDie("0,2:-"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); TF_CHECK_OK(writer.Finish()); } // File #1 contains two slices: // // slice #0 is the bottom left corner // . . . . . // . . . . . // 10 11 12 . . // 15 16 17 . . // // slice #1 is the bottom right corner // . . . . . // . . . . . // . . . . . // . . . 18 19 { const string fname = strings::StrCat(fname_base, "_1"); TensorSliceWriter writer(fname, create_function); // slice #0 { const float data[] = {10, 11, 12, 15, 16, 17}; TensorSlice slice = TensorSlice::ParseOrDie("2,2:0,3"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); } // slice #1 { const float data[] = {18, 19}; TensorSlice slice = TensorSlice::ParseOrDie("3,1:3,2"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); } TF_CHECK_OK(writer.Finish()); } // Notice that we leave a hole in the tensor // . . . . . // . . . . . // . . . (13) (14) // . . . . . // Now we need to read the tensor slices const string filepattern = strings::StrCat(fname_base, "_*"); TensorSliceReader reader(filepattern, open_function); EXPECT_OK(reader.status()); EXPECT_EQ(2, reader.num_files()); // We query some of the tensors { TensorShape shape; DataType type; EXPECT_TRUE(reader.HasTensor("test", &shape, &type)); EXPECT_EQ("[4,5]", shape.DebugString()); EXPECT_EQ(DT_FLOAT, type); EXPECT_FALSE(reader.HasTensor("don't exist", nullptr, nullptr)); } // Now we query some slices // // Slice #1 is an exact match // 0 1 2 3 4 // 5 6 7 8 9 // . . . . . // . . . . . { TensorSlice s = TensorSlice::ParseOrDie("0,2:-"); float expected[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; float results[10]; EXPECT_TRUE(reader.CopySliceData("test", s, results)); for (int i = 0; i < 10; ++i) { EXPECT_EQ(expected[i], results[i]); } } // Slice #2 is a subset match // . . . . . // 5 6 7 8 9 // . . . . . // . . . . . { TensorSlice s = TensorSlice::ParseOrDie("1,1:-"); float expected[] = {5, 6, 7, 8, 9}; float results[5]; EXPECT_TRUE(reader.CopySliceData("test", s, results)); for (int i = 0; i < 5; ++i) { EXPECT_EQ(expected[i], results[i]); } } // Slice #4 includes the hole and so there is no match // . . . . . // . . 7 8 9 // . . 12 13 14 // . . . . . { TensorSlice s = TensorSlice::ParseOrDie("1,2:2,3"); float results[6]; EXPECT_FALSE(reader.CopySliceData("test", s, results)); } } TEST(TensorSliceReaderTest, SimpleFloat) { SimpleFloatHelper(CreateTableTensorSliceBuilder, OpenTableTensorSliceReader); } template <typename T, typename U> void SimpleIntXHelper(TensorSliceWriter::CreateBuilderFunction create_function, TensorSliceReader::OpenTableFunction open_function, const string& checkpoint_file) { const string fname_base = io::JoinPath(testing::TmpDir(), checkpoint_file); TensorShape shape({4, 5}); // File #0 contains a slice that is the top two rows: // // 0 1 2 3 4 // 5 6 7 8 9 // . . . . . // . . . . . { const string fname = strings::StrCat(fname_base, "_0"); TensorSliceWriter writer(fname, create_function); const T data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TensorSlice slice = TensorSlice::ParseOrDie("0,2:-"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); TF_CHECK_OK(writer.Finish()); } // File #1 contains two slices: // // slice #0 is the bottom left corner // . . . . . // . . . . . // 10 11 12 . . // 15 16 17 . . // // slice #1 is the bottom right corner // . . . . . // . . . . . // . . . . . // . . . 18 19 { const string fname = strings::StrCat(fname_base, "_1"); TensorSliceWriter writer(fname, create_function); // slice #0 { const T data[] = {10, 11, 12, 15, 16, 17}; TensorSlice slice = TensorSlice::ParseOrDie("2,2:0,3"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); } // slice #1 { const T data[] = {18, 19}; TensorSlice slice = TensorSlice::ParseOrDie("3,1:3,2"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); } TF_CHECK_OK(writer.Finish()); } // Notice that we leave a hole in the tensor // . . . . . // . . . . . // . . . (13) (14) // . . . . . // Now we need to read the tensor slices const string filepattern = strings::StrCat(fname_base, "_*"); TensorSliceReader reader(filepattern, open_function); EXPECT_OK(reader.status()); EXPECT_EQ(2, reader.num_files()); // We query some of the tensors { TensorShape shape; DataType type; EXPECT_TRUE(reader.HasTensor("test", &shape, &type)); EXPECT_EQ("[4,5]", shape.DebugString()); EXPECT_EQ(DataTypeToEnum<T>::v(), type); EXPECT_FALSE(reader.HasTensor("don't exist", nullptr, nullptr)); } // Now we query some slices // // Slice #1 is an exact match // 0 1 2 3 4 // 5 6 7 8 9 // . . . . . // . . . . . { TensorSlice s = TensorSlice::ParseOrDie("0,2:-"); T expected[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; U results[10]; EXPECT_TRUE(reader.CopySliceData("test", s, results)); for (int i = 0; i < 10; ++i) { EXPECT_EQ(expected[i], results[i]); } } // Slice #2 is a subset match // . . . . . // 5 6 7 8 9 // . . . . . // . . . . . { TensorSlice s = TensorSlice::ParseOrDie("1,1:-"); T expected[] = {5, 6, 7, 8, 9}; U results[5]; EXPECT_TRUE(reader.CopySliceData("test", s, results)); for (int i = 0; i < 5; ++i) { EXPECT_EQ(expected[i], results[i]); } } // Slice #4 includes the hole and so there is no match // . . . . . // . . 7 8 9 // . . 12 13 14 // . . . . . { TensorSlice s = TensorSlice::ParseOrDie("1,2:2,3"); U results[6]; EXPECT_FALSE(reader.CopySliceData("test", s, results)); } } #define TEST_SIMPLE_INT(TYPE, SAVED_TYPE) \ TEST(TensorSliceReaderTest, Simple##TYPE) { \ SimpleIntXHelper<TYPE, SAVED_TYPE>(CreateTableTensorSliceBuilder, \ OpenTableTensorSliceReader, \ #TYPE "_checkpoint"); \ } TEST_SIMPLE_INT(int32, int32) TEST_SIMPLE_INT(int64, int64) TEST_SIMPLE_INT(int16, int32) TEST_SIMPLE_INT(int8, int32) TEST_SIMPLE_INT(uint8, int32) void CachedTensorSliceReaderTesterHelper( TensorSliceWriter::CreateBuilderFunction create_function, TensorSliceReader::OpenTableFunction open_function) { const string fname_base = io::JoinPath(testing::TmpDir(), "float_checkpoint"); TensorShape shape({4, 5}); // File #0 contains a slice that is the top two rows: // // 0 1 2 3 4 // 5 6 7 8 9 // . . . . . // . . . . . { const string fname = strings::StrCat(fname_base, "_0"); TensorSliceWriter writer(fname, create_function); const float data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; TensorSlice slice = TensorSlice::ParseOrDie("0,2:-"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); TF_CHECK_OK(writer.Finish()); } // File #1 contains two slices: // // slice #0 is the bottom left corner // . . . . . // . . . . . // 10 11 12 . . // 15 16 17 . . // // slice #1 is the bottom right corner // . . . . . // . . . . . // . . . . . // . . . 18 19 { const string fname = strings::StrCat(fname_base, "_1"); TensorSliceWriter writer(fname, create_function); // slice #0 { const float data[] = {10, 11, 12, 15, 16, 17}; TensorSlice slice = TensorSlice::ParseOrDie("2,2:0,3"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); } // slice #1 { const float data[] = {18, 19}; TensorSlice slice = TensorSlice::ParseOrDie("3,1:3,2"); TF_CHECK_OK(writer.Add("test", shape, slice, data)); } TF_CHECK_OK(writer.Finish()); } // Notice that we leave a hole in the tensor // . . . . . // . . . . . // . . . (13) (14) // . . . . . // Now we need to read the tensor slices TensorSliceReaderCache cache; const string filepattern = strings::StrCat(fname_base, "_*"); const TensorSliceReader* reader = cache.GetReader( filepattern, open_function, TensorSliceReader::kLoadAllShards); EXPECT_TRUE(reader != nullptr); EXPECT_EQ(2, reader->num_files()); // We query some of the tensors { TensorShape shape; DataType type; EXPECT_TRUE(reader->HasTensor("test", &shape, &type)); EXPECT_EQ("[4,5]", shape.DebugString()); EXPECT_EQ(DT_FLOAT, type); EXPECT_FALSE(reader->HasTensor("don't exist", nullptr, nullptr)); } // Make sure the reader is cached. const TensorSliceReader* reader2 = cache.GetReader( filepattern, open_function, TensorSliceReader::kLoadAllShards); EXPECT_EQ(reader, reader2); reader = cache.GetReader("file_does_not_exist", open_function, TensorSliceReader::kLoadAllShards); EXPECT_TRUE(reader == nullptr); } TEST(CachedTensorSliceReaderTest, SimpleFloat) { CachedTensorSliceReaderTesterHelper(CreateTableTensorSliceBuilder, OpenTableTensorSliceReader); } } // namespace } // namespace checkpoint } // namespace tensorflow
DeepThoughtTeam/tensorflow
tensorflow/core/util/tensor_slice_reader_test.cc
C++
apache-2.0
12,348
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Wed Sep 24 06:08:09 EDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.cloud.ZkTestServer (Solr 4.10.1 API)</title> <meta name="date" content="2014-09-24"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.cloud.ZkTestServer (Solr 4.10.1 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/solr/cloud/class-use/ZkTestServer.html" target="_top">Frames</a></li> <li><a href="ZkTestServer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.cloud.ZkTestServer" class="title">Uses of Class<br>org.apache.solr.cloud.ZkTestServer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.solr.cloud">org.apache.solr.cloud</a></td> <td class="colLast"> <div class="block">Base classes and utilities for creating and testing <a href="https://wiki.apache.org/solr/SolrCloud">Solr Cloud</a> clusters.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.solr.cloud"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a> in <a href="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</a> declared as <a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a></code></td> <td class="colLast"><span class="strong">AbstractDistribZkTestBase.</span><code><strong><a href="../../../../../org/apache/solr/cloud/AbstractDistribZkTestBase.html#zkServer">zkServer</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected static <a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a></code></td> <td class="colLast"><span class="strong">AbstractZkTestCase.</span><code><strong><a href="../../../../../org/apache/solr/cloud/AbstractZkTestCase.html#zkServer">zkServer</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</a> that return <a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a></code></td> <td class="colLast"><span class="strong">MiniSolrCloudCluster.</span><code><strong><a href="../../../../../org/apache/solr/cloud/MiniSolrCloudCluster.html#getZkServer()">getZkServer</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../org/apache/solr/cloud/package-summary.html">org.apache.solr.cloud</a> with parameters of type <a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../org/apache/solr/cloud/ChaosMonkey.html#ChaosMonkey(org.apache.solr.cloud.ZkTestServer, org.apache.solr.common.cloud.ZkStateReader, java.lang.String, java.util.Map, java.util.Map)">ChaosMonkey</a></strong>(<a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">ZkTestServer</a>&nbsp;zkServer, org.apache.solr.common.cloud.ZkStateReader&nbsp;zkStateReader, <a href="http://download.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;collection, <a href="http://download.oracle.com/javase/7/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a>&lt;<a href="http://download.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="http://download.oracle.com/javase/7/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../org/apache/solr/cloud/AbstractFullDistribZkTestBase.CloudJettyRunner.html" title="class in org.apache.solr.cloud">AbstractFullDistribZkTestBase.CloudJettyRunner</a>&gt;&gt;&nbsp;shardToJetty, <a href="http://download.oracle.com/javase/7/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a>&lt;<a href="http://download.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="../../../../../org/apache/solr/cloud/AbstractFullDistribZkTestBase.CloudJettyRunner.html" title="class in org.apache.solr.cloud">AbstractFullDistribZkTestBase.CloudJettyRunner</a>&gt;&nbsp;shardToLeaderJetty)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/solr/cloud/ZkTestServer.html" title="class in org.apache.solr.cloud">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/solr/cloud/class-use/ZkTestServer.html" target="_top">Frames</a></li> <li><a href="ZkTestServer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
pulipulichen/ir-practice-solr
docs/solr-test-framework/org/apache/solr/cloud/class-use/ZkTestServer.html
HTML
apache-2.0
10,597
package org.openbel.framework.test; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.openbel.framework.test.WebAPIHelper.createWebAPI; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.xml.soap.SOAPFault; import javax.xml.ws.soap.SOAPFaultException; import org.junit.BeforeClass; import org.junit.Test; import org.openbel.framework.ws.model.*; /** * A JUnit test case to check that all BEL Framework Web API requests that take * a KAM handle must validate the handle, and, if the handle is invalid, must issue a * SOAP fault with a message containing the provided handle name. * * The requests that are checked are: * <ul> * <li>GetKam</li> * <li>GetBelDocuments</li> * <li>GetAnnotationTypes</li> * <li>GetNamespaces</li> * <li>GetCitations</li> * <li>GetNewInstance</li> * <li>MapData</li> * <li>UnionKams</li> * <li>IntersectKams</li> * <li>DifferenceKams</li> * <li>ResolveNodes</li> * <li>ResolveEdges</li> * <li>ReleaseKam</li> * <li>FindEdges</li> * <li>FindKamNodesByIds</li> * <li>FindKamNodesByLabels</li> * <li>FindKamNodesByPatterns</li> * </ul> */ public class TestEndPointKamHandleValidation { private final static ObjectFactory factory = new ObjectFactory(); private static WebAPI webAPI = createWebAPI(); private static final KamHandle invalidKamHandle = new KamHandle(); private static final String invalidKamHandleName = "This is probably not a valid KAM handle!"; static { invalidKamHandle.setHandle(invalidKamHandleName); } private static KamHandle validKamHandle = null; private static Namespace validNamespace = null; @BeforeClass public static void establishWebAPI() { assertThat(webAPI, is(not(nullValue()))); // Acquire a valid KAM handle and a valid namespace which will // be used for some tests. final GetCatalogResponse catres = webAPI.getCatalog(null); assertThat(catres, is(not(nullValue()))); final List<Kam> catalog = catres.getKams(); if (hasItems(catalog)) { validKamHandle = loadKam(catalog.get(0)); final GetNamespacesRequest nsRequest = factory.createGetNamespacesRequest(); nsRequest.setHandle(validKamHandle); final GetNamespacesResponse nsResponse = webAPI.getNamespaces(nsRequest); if (nsResponse != null) { final List<Namespace> namespaces = nsResponse.getNamespaces(); if (hasItems(namespaces)) { validNamespace = namespaces.get(0); } } } } @Test public void testThatGetKamValidatesKamHandle() { check("getKam", factory.createGetKamRequest()); } @Test public void testThatGetBelDocumentsValidatesKamHandle() { check("getBelDocuments", factory.createGetBelDocumentsRequest()); } @Test public void testThatGetAnnotationTypesValidatesKamHandle() { check("getAnnotationTypes", factory.createGetAnnotationTypesRequest()); } @Test public void testThatGetNamespacesValidatesKamHandle() { check("getNamespaces", factory.createGetNamespacesRequest()); } @Test public void testThatGetCitationsValidatesKamHandle() { testThatGetCitationsValidatesKamHandle(CitationType.BOOK); } private void testThatGetCitationsValidatesKamHandle(final CitationType citationType) { final GetCitationsRequest request = factory.createGetCitationsRequest(); request.setCitationType(citationType); check("getCitations", request); } @Test public void testThatGetNewInstanceValidatesKamHandle() { check("getNewInstance", factory.createGetNewInstanceRequest()); } @Test public void testThatMapDataValidatesKamHandle() { if (validNamespace != null) { testThatMapDataValidatesKamHandle(validNamespace); } } private void testThatMapDataValidatesKamHandle(final Namespace namespace) { final MapDataRequest request = factory.createMapDataRequest(); request.setNamespace(namespace); check("mapData", request); } @Test public void testThatUnionKamsValidatesKamHandle() { if (validKamHandle != null) { testThatUnionKamsValidatesKamHandle(validKamHandle); } } private void testThatUnionKamsValidatesKamHandle(final KamHandle validKamHandle) { final UnionKamsRequest request1 = factory.createUnionKamsRequest(); request1.setKam2(validKamHandle); check("unionKams", request1, "setKam1"); final UnionKamsRequest request2 = factory.createUnionKamsRequest(); request2.setKam1(validKamHandle); check("unionKams", request2, "setKam2"); } @Test public void testThatIntersectKamsValidatesKamHandle() { if (validKamHandle != null) { testThatIntersectKamsValidatesKamHandle(validKamHandle); } } private void testThatIntersectKamsValidatesKamHandle(final KamHandle validKamHandle) { final IntersectKamsRequest request1 = factory.createIntersectKamsRequest(); request1.setKam2(validKamHandle); check("intersectKams", request1, "setKam1"); final IntersectKamsRequest request2 = factory.createIntersectKamsRequest(); request2.setKam1(validKamHandle); check("intersectKams", request2, "setKam2"); } @Test public void testThatDifferenceKamsValidatesKamHandle() { if (validKamHandle != null) { testThatDifferenceKamsValidatesKamHandle(validKamHandle); } } private void testThatDifferenceKamsValidatesKamHandle(final KamHandle validKamHandle) { final DifferenceKamsRequest request1 = factory.createDifferenceKamsRequest(); request1.setKam2(validKamHandle); check("differenceKams", request1, "setKam1"); final DifferenceKamsRequest request2 = factory.createDifferenceKamsRequest(); request2.setKam1(validKamHandle); check("differenceKams", request2, "setKam2"); } @Test public void testThatResolveNodesValidatesKamHandle() { testThatResolveNodesValidatesKamHandle(new ArrayList<Node>()); } private void testThatResolveNodesValidatesKamHandle(final List<Node> nodes) { final ResolveNodesRequest request = factory.createResolveNodesRequest(); request.getNodes().addAll(nodes); check("resolveNodes", request); } @Test public void testThatResolveEdgesValidatesKamHandle() { testThatResolveEdgesValidatesKamHandle(new ArrayList<Edge>()); } private void testThatResolveEdgesValidatesKamHandle(final List<Edge> edges) { final ResolveEdgesRequest request = factory.createResolveEdgesRequest(); request.getEdges().addAll(edges); check("resolveEdges", request); } @Test public void testThatReleaseKamValidatesKamHandle() { check("releaseKam", factory.createReleaseKamRequest(), "setKam"); } @Test public void testThatFindEdgesValidatesKamHandle() { testThatFindEdgesValidatesKamHandle(new EdgeFilter()); } private void testThatFindEdgesValidatesKamHandle(final EdgeFilter edgeFilter) { final FindKamEdgesRequest request = factory.createFindKamEdgesRequest(); request.setFilter(edgeFilter); check("findKamEdges", request); } @Test public void testThatFindKamNodesByIdsValidatesKamHandle() { testThatFindKamNodesByIdsValidatesKamHandle( asList(new String[] { "some id", "another id" })); } private void testThatFindKamNodesByIdsValidatesKamHandle(final List<String> ids) { final FindKamNodesByIdsRequest request = factory.createFindKamNodesByIdsRequest(); request.getIds().addAll(ids); check("findKamNodesByIds", request); } @Test public void testThatFindKamNodesByLabelsValidatesKamHandle() { testThatFindKamNodesByLabelsValidatesKamHandle( asList(new String[] { "some label", "another label" })); } private void testThatFindKamNodesByLabelsValidatesKamHandle(final List<String> labels) { final FindKamNodesByLabelsRequest request = factory.createFindKamNodesByLabelsRequest(); request.getLabels().addAll(labels); check("findKamNodesByLabels", request); } @Test public void testThatFindKamNodesByPatternsValidatesKamHandle() { testThatFindKamNodesByPatternsValidateKamHandle(asList(new String[] { ".*" })); } private void testThatFindKamNodesByPatternsValidateKamHandle(final List<String> patterns) { final FindKamNodesByPatternsRequest request = factory.createFindKamNodesByPatternsRequest(); request.getPatterns().addAll(patterns); check("findKamNodesByPatterns", request); } /* * Utility functions: */ private static <T> boolean hasItems(Collection<T> c) { return (c != null && ! c.isEmpty()); } private static KamHandle loadKam(final Kam kam) { final LoadKamRequest lkreq = factory.createLoadKamRequest(); lkreq.setKam(kam); LoadKamResponse lkres = webAPI.loadKam(lkreq); KAMLoadStatus status = lkres.getLoadStatus(); while (status == KAMLoadStatus.IN_PROCESS) { // sleep 1/2 a second and retry try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } lkres = webAPI.loadKam(lkreq); status = lkres.getLoadStatus(); } final KamHandle handle = lkres.getHandle(); assertThat(handle, is(not(nullValue()))); return handle; } private <T> void check(final String apiMethodName, final T request) { check(apiMethodName, request, "setHandle"); } private <T> void check(final String apiMethodName, final T request, final String setHandleMethodName) { Method apiMethod = null; Method setHandle = null; try { apiMethod = WebAPI.class.getDeclaredMethod(apiMethodName, request.getClass()); setHandle = request.getClass().getDeclaredMethod(setHandleMethodName, KamHandle.class); } catch (NoSuchMethodException e) { fail("Caught NoSuchMethodException: " + e.getMessage()); return; } catch (SecurityException e) { fail("Caught SecurityException: " + e.getMessage()); return; } try { setHandle.invoke(request, invalidKamHandle); apiMethod.invoke(webAPI, request); } catch (IllegalAccessException e) { fail("Caught IllegalAccessException: " + e.getMessage()); } catch (IllegalArgumentException e) { fail("Caught IllegalArgumentException: " + e.getMessage()); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof SOAPFaultException) { final SOAPFaultException ex = (SOAPFaultException) cause; final SOAPFault fault = ex.getFault(); assertThat(fault, is(not(nullValue()))); final String faultString = fault.getFaultString(); assertThat(faultString, is(not(nullValue()))); assertThat(faultString, containsString(invalidKamHandleName)); } else { fail("Caught InvocationTargetException: " + e.getMessage()); } } } }
OpenBEL/openbel-framework
tests/functional/src/test/java/org/openbel/framework/test/TestEndPointKamHandleValidation.java
Java
apache-2.0
11,969
// Copyright (C) 2014 Open Data ("Open Data" refers to // one or more of the following companies: Open Data Partners LLC, // Open Data Research LLC, or Open Data Capital LLC.) // // This file is part of Hadrian. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package test.scala.shared import org.junit.runner.RunWith import org.scalatest.FlatSpec import org.scalatest.junit.JUnitRunner import org.scalatest.Matchers import org.apache.avro.Schema import com.opendatagroup.hadrian.shared._ import com.opendatagroup.hadrian.datatype._ import test.scala._ @RunWith(classOf[JUnitRunner]) class SharedSuite extends FlatSpec with Matchers { "Shared state" must "read and write values in a single thread" taggedAs(Shared) in { val state = new SharedMapInMemory() state.initialize(Set[String](), (x: String) => null) state.put("one", Array[PathIndex](), 1) state.put("two", Array[PathIndex](), 2.2) state.put("three", Array[PathIndex](), "THREE") state.put("three", Array[PathIndex](), "Three") state.update("four", Array[PathIndex](), 0, (x: Int) => x + 1, Schema.create(Schema.Type.INT)) state.update("four", Array[PathIndex](), 0, (x: Int) => x + 1, Schema.create(Schema.Type.INT)) state.update("four", Array[PathIndex](), 0, (x: Int) => x + 1, Schema.create(Schema.Type.INT)) state.update("five", Array[PathIndex](), List[Int](), (x: List[Int]) => 5 :: x, Schema.create(Schema.Type.INT)) state.update("five", Array[PathIndex](), List[Int](), (x: List[Int]) => 5 :: x, Schema.create(Schema.Type.INT)) state.update("five", Array[PathIndex](), List[Int](), (x: List[Int]) => 5 :: x, Schema.create(Schema.Type.INT)) state.get("one", Array[PathIndex]()) should be (Right(1)) state.get("two", Array[PathIndex]()) should be (Right(2.2)) state.get("three", Array[PathIndex]()) should be (Right("Three")) state.get("four", Array[PathIndex]()) should be (Right(3)) state.get("five", Array[PathIndex]()) should be (Right(List(5, 5, 5))) state.get("six", Array[PathIndex]()).isLeft should be (true) state.remove("one") state.get("one", Array[PathIndex]()).isLeft should be (true) state.remove("one") state.get("one", Array[PathIndex]()).isLeft should be (true) } it must "store null differently from no-entry" taggedAs(Shared) in { val state = new SharedMapInMemory() state.initialize(Set[String](), (x: String) => null) state.get("x", Array[PathIndex]()).isLeft should be (true) state.put("x", Array[PathIndex](), null) state.get("x", Array[PathIndex]()) should be (Right(null)) } it must "read multiple times during write" taggedAs(Shared, MultiThreaded) in { val state = new SharedMapInMemory() state.initialize(Set[String](), (x: String) => null) state.put("x", Array[PathIndex](), 5) val reader = new Thread(new Runnable { def run(): Unit = { for (i <- 0 until 5) { val value = state.get("x", Array[PathIndex]()) if (i < 2) value should be (Right(5)) else if (i < 4) value should be (Right(99)) else value.isLeft should be (true) Thread.sleep(100) } } }) reader.start state.update("x", Array[PathIndex](), 5, {(x: Int) => Thread.sleep(150); 99}, Schema.create(Schema.Type.INT)) Thread.sleep(200) state.remove("x") Thread.sleep(150) } it must "write atomically" taggedAs(Shared, MultiThreaded) in { val state = new SharedMapInMemory() state.initialize(Set[String](), (x: String) => null) class Increment extends Runnable { def run(): Unit = state.update("x", Array[PathIndex](), 0, {(x: Int) => Thread.sleep(100); x + 1}, Schema.create(Schema.Type.INT)) } val thread1 = new Thread(new Increment) val thread2 = new Thread(new Increment) val thread3 = new Thread(new Increment) val thread4 = new Thread(new Increment) val thread5 = new Thread(new Increment) thread1.start Thread.sleep(10) thread2.start Thread.sleep(10) thread3.start Thread.sleep(10) thread4.start Thread.sleep(10) thread5.start Thread.sleep(550) state.get("x", Array[PathIndex]()) should be (Right(5)) // and not, for instance, Right(1) because the Incrementers overwrote each other } }
opendatagroup/hadrian
hadrian/src/test/scala/shared.scala
Scala
apache-2.0
4,842
/* Copyright 2009-2021 EPFL, Lausanne */ package stainless package verification import org.scalatest._ trait DottyVerificationSuite extends VerificationComponentTestSuite { override def configurations = super.configurations.map { seq => optFailInvalid(true) +: seq } override protected def optionsString(options: inox.Options): String = { super.optionsString(options) + (if (options.findOptionOrDefault(evaluators.optCodeGen)) " codegen" else "") } def keepOnly(f: String): Boolean = { val noLongerCompiles = Set( "ConstructorRefinement.scala", "IdentityRefinement.scala", "PositiveInt.scala", "PositiveIntAlias.scala", "RefinedTypeMember.scala", "SortedListHead.scala", "ErasedTerms1.scala" ) noLongerCompiles.forall(s => !f.endsWith(s)) } testPosAll("dotty-specific/valid", keepOnly = keepOnly) testNegAll("dotty-specific/invalid") } class SMTZ3DottyVerificationSuite extends DottyVerificationSuite { override def configurations = super.configurations.map { seq => Seq( inox.optSelectedSolvers(Set("smt-z3:z3-4.8.12")), inox.solvers.optCheckModels(true) ) ++ seq } }
epfl-lara/stainless
frontends/dotty/src/it/scala/stainless/verification/DottyVerificationSuite.scala
Scala
apache-2.0
1,184
Public Class ConfigForm Private Sub ConfigForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim Reg As Microsoft.Win32.RegistryKey, s As String Reg = My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", False) s = Reg.GetValue("LaoUnicode.exe", "") Reg.Close() ' We won't worry about correct path comparisons here StartWithWindowsCheckbox.Checked = s.Equals(Process.GetCurrentProcess().MainModule.FileName, StringComparison.InvariantCultureIgnoreCase) End Sub Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click Dim Reg As Microsoft.Win32.RegistryKey Reg = My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", False) If StartWithWindowsCheckbox.Checked Then Reg.SetValue("LaoUnicode", Process.GetCurrentProcess().MainModule.FileName) Else Reg.DeleteValue("LaoUnicode", False) End If Reg.Close() DialogResult = Windows.Forms.DialogResult.OK End Sub End Class
tavultesoft/keymanweb
windows/src/developer/samples/Products/LaoUnicode/LaoUnicode/Config.vb
Visual Basic
apache-2.0
1,185
/* * Copyright (C) 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.twitter.sdk.android.mopub; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.mopub.nativeads.BaseNativeAd; import com.mopub.nativeads.MoPubAdRenderer; import com.mopub.nativeads.NativeImageHelper; import com.mopub.nativeads.NativeRendererHelper; import com.mopub.nativeads.StaticNativeAd; public class TwitterStaticNativeAdRenderer implements MoPubAdRenderer<StaticNativeAd> { private static final int DEFAULT_STYLE = R.style.tw__ad_LightStyle; private final int styleResId; public TwitterStaticNativeAdRenderer() { this.styleResId = DEFAULT_STYLE; } public TwitterStaticNativeAdRenderer(int styleResId) { this.styleResId = styleResId; } @Override public View createAdView(final Context context, final ViewGroup parent) { return new TwitterStaticNativeAd(context, null, styleResId); } @Override public void renderAdView(final View view, final StaticNativeAd staticNativeAd) { update((TwitterStaticNativeAd) view, staticNativeAd); } @Override public boolean supports(final BaseNativeAd nativeAd) { return nativeAd instanceof StaticNativeAd; } private void update(final TwitterStaticNativeAd staticNativeView, final StaticNativeAd staticNativeAd) { NativeRendererHelper.addTextView(staticNativeView.adTitleView, staticNativeAd.getTitle()); NativeRendererHelper.addTextView(staticNativeView.adTextView, staticNativeAd.getText()); NativeRendererHelper.addTextView(staticNativeView.callToActionView, staticNativeAd.getCallToAction()); NativeImageHelper.loadImageView(staticNativeAd.getMainImageUrl(), staticNativeView.mainImageView); NativeImageHelper.loadImageView(staticNativeAd.getIconImageUrl(), staticNativeView.adIconView); NativeRendererHelper.addPrivacyInformationIcon( staticNativeView.privacyInfoView, staticNativeAd.getPrivacyInformationIconImageUrl(), staticNativeAd.getPrivacyInformationIconClickThroughUrl()); } }
twitter/twitter-kit-android
twitter-mopub/src/main/java/com/twitter/sdk/android/mopub/TwitterStaticNativeAdRenderer.java
Java
apache-2.0
2,781
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Copyright 2008 Google Inc. All Rights Reserved. package com.google.location.suplclient.asn1.base; import java.nio.ByteBuffer; import java.util.Collection; /** * */ public class Asn1ParameterObject extends Asn1Object { private Asn1Object realObject; protected Asn1Object getRealObject() { return realObject; } protected void setRealObject(Asn1Object realObject) { this.realObject = realObject; } public static Collection<Asn1Tag> getPossibleFirstTags() { throw new UnsupportedOperationException("Not implemented for BER"); } @Override Asn1Tag getDefaultTag() { throw new UnsupportedOperationException("Not implemented for BER"); } @Override int getBerValueLength() { throw new UnsupportedOperationException("Not implemented for BER"); } @Override void encodeBerValue(ByteBuffer buf) { throw new UnsupportedOperationException("Not implemented for BER"); } @Override void decodeBerValue(ByteBuffer buf) { throw new UnsupportedOperationException("Not implemented for BER"); } @Override public Iterable<BitStream> encodePerUnaligned() { return realObject.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return realObject.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { realObject.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { realObject.decodePerAligned(reader); } }
google/supl-client
src/main/java/com/google/location/suplclient/asn1/base/Asn1ParameterObject.java
Java
apache-2.0
2,092
# =============================================================================== # Copyright 2013 Jake Ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== # ============= enthought library imports ======================= from __future__ import absolute_import import time # ============= standard library imports ======================== from threading import Thread from pyface.tasks.action.schema import SToolBar from pyface.tasks.task_layout import TaskLayout, PaneItem, Splitter, VSplitter from pyface.ui.qt4.tasks.advanced_editor_area_pane import EditorWidget from traits.api import Any, Instance, on_trait_change # ============= local library imports ========================== from pychron.core.ui.gui import invoke_in_main_thread from pychron.envisage.tasks.editor_task import EditorTask from pychron.spectrometer.tasks.editor import PeakCenterEditor, ScanEditor, CoincidenceEditor, ScannerEditor from pychron.spectrometer.tasks.spectrometer_actions import StopScanAction from pychron.spectrometer.tasks.spectrometer_panes import ControlsPane, \ ReadoutPane, IntensitiesPane, RecordControlsPane, DACScannerPane, MassScannerPane class SpectrometerTask(EditorTask): scan_manager = Any name = 'Spectrometer' id = 'pychron.spectrometer' _scan_editor = Instance(ScanEditor) tool_bars = [SToolBar(StopScanAction(), )] def info(self, msg, *args, **kw): super(SpectrometerTask, self).info(msg) def spy_position_magnet(self, *args, **kw): self.scan_manager.position_magnet(*args, **kw) def spy_peak_center(self, name): peak_kw = dict(confirm_save=False, warn=True, new_thread=False, message='spectrometer script peakcenter', on_end=self._on_peak_center_end) setup_kw = dict(config_name=name) return self._peak_center(setup_kw=setup_kw, peak_kw=peak_kw) def populate_mftable(self): sm = self.scan_manager cfg = sm.setup_populate_mftable() if cfg: def func(): refiso = cfg.isotope ion = sm.ion_optics_manager ion.backup_mftable() odefl = [] dets = cfg.get_detectors() self.debug('setting deflections') for det, defl in dets: odefl.append((det, sm.spectrometer.get_deflection(det))) sm.spectrometer.set_deflection(det, defl) for di in dets: ion.setup_peak_center(detector=[di.name], isotope=refiso, config_name=cfg.peak_center_config.active_item.name, standalone_graph=False, new=True, show_label=True, use_configuration_dac=False) ion.peak_center.update_others = False name = 'Pop MFTable {}-{}'.format(di.name, refiso) invoke_in_main_thread(self._open_editor, PeakCenterEditor(model=ion.peak_center, name=name)) self._on_peak_center_start() ion.do_peak_center(new_thread=False, save=True, warn=True) self._on_peak_center_end() if not ion.peak_center.isAlive(): break self.debug('unset deflections') for det, defl in odefl: sm.spectrometer.set_deflection(det, defl) fp = cfg.get_finish_position() self.debug('move to end position={}'.format(fp)) if fp: iso, det = fp if iso and det: ion.position(iso, det) t = Thread(target=func) t.start() def stop_scan(self): self.debug('stop scan fired') editor = self.active_editor self.debug('active editor {}'.format(editor)) if editor: if isinstance(editor, (ScanEditor, PeakCenterEditor, CoincidenceEditor)): self.debug('editor stop') editor.stop() def do_coincidence(self): es = [int(e.name.split(' ')[-1]) for e in self.editor_area.editors if isinstance(e, CoincidenceEditor)] i = max(es) + 1 if es else 1 man = self.scan_manager.ion_optics_manager name = 'Coincidence {:02d}'.format(i) if man.setup_coincidence(): self._open_editor(CoincidenceEditor(model=man.coincidence, name=name)) man.do_coincidence_scan() def do_peak_center(self): peak_kw = dict(confirm_save=True, warn=True, message='manual peakcenter', on_end=self._on_peak_center_end) self._peak_center(peak_kw=peak_kw) def define_peak_center(self): from pychron.spectrometer.ion_optics.define_peak_center_view import DefinePeakCenterView man = self.scan_manager.ion_optics_manager spec = man.spectrometer dets = spec.detector_names isos = spec.isotopes dpc = DefinePeakCenterView(detectors=dets, isotopes=isos, detector=dets[0], isotope=isos[0]) info = dpc.edit_traits() if info.result: det = dpc.detector isotope = dpc.isotope dac = dpc.dac self.debug('manually setting mftable to {}:{}:{}'.format(det, isotope, dac)) message = 'manually define peak center {}:{}:{}'.format(det, isotope, dac) man.spectrometer.magnet.update_field_table(det, isotope, dac, message) def _on_peak_center_start(self): self.scan_manager.log_events_enabled = False self.scan_manager.scan_enabled = False def _on_peak_center_end(self): self.scan_manager.log_events_enabled = True self.scan_manager.scan_enabled = True def send_configuration(self): self.scan_manager.spectrometer.send_configuration() def prepare_destroy(self): for e in self.editor_area.editors: if hasattr(e, 'stop'): e.stop() self.scan_manager.prepare_destroy() super(SpectrometerTask, self).prepare_destroy() # def activated(self): # self.scan_manager.activate() # self._scan_factory() # super(SpectrometerTask, self).activated() def create_dock_panes(self): panes = [ ControlsPane(model=self.scan_manager), RecordControlsPane(model=self.scan_manager), MassScannerPane(model=self.scan_manager), DACScannerPane(model=self.scan_manager), ReadoutPane(model=self.scan_manager), IntensitiesPane(model=self.scan_manager)] panes = self._add_canvas_pane(panes) return panes # def _active_editor_changed(self, new): # if not new: # try: # self._scan_factory() # except AttributeError: # pass # private def _peak_center(self, setup_kw=None, peak_kw=None): if setup_kw is None: setup_kw = {} if peak_kw is None: peak_kw = {} es = [] for e in self.editor_area.editors: if isinstance(e, PeakCenterEditor): try: es.append(int(e.name.split(' ')[-1])) except ValueError: pass i = max(es) + 1 if es else 1 ret = -1 ion = self.scan_manager.ion_optics_manager self._peak_center_start_hook() time.sleep(2) name = 'Peak Center {:02d}'.format(i) if ion.setup_peak_center(new=True, **setup_kw): self._on_peak_center_start() invoke_in_main_thread(self._open_editor, PeakCenterEditor(model=ion.peak_center, name=name)) ion.do_peak_center(**peak_kw) ret = ion.peak_center_result self._peak_center_stop_hook() return ret def _peak_center_start_hook(self): pass def _peak_center_stop_hook(self): pass def _scan_factory(self): sim = self.scan_manager.spectrometer.simulation name = 'Scan (Simulation)' if sim else 'Scan' # self._open_editor(ScanEditor(model=self.scan_manager, name=name)) # print 'asdfas', self.editor_area.control # print [e for e in self.editor_area.control.children() if isinstance(e, EditorWidget)] # super(SpectrometerTask, self).activated() se = ScanEditor(model=self.scan_manager, name=name) self._open_editor(se) def _default_layout_default(self): return TaskLayout( left=Splitter( PaneItem('pychron.spectrometer.controls'), orientation='vertical'), right=VSplitter(PaneItem('pychron.spectrometer.intensities'), PaneItem('pychron.spectrometer.readout'))) # def create_central_pane(self): # g = ScanPane(model=self.scan_manager) # return g @on_trait_change('scan_manager:mass_scanner:new_scanner') def _handle_mass_scan_event(self): self._scan_event(self.scan_manager.mass_scanner) @on_trait_change('scan_manager:dac_scanner:new_scanner') def _handle_dac_scan_event(self): self._scan_event(self.scan_manager.dac_scanner) def _scan_event(self, scanner): sim = self.scan_manager.spectrometer.simulation name = 'Magnet Scan (Simulation)' if sim else 'Magnet Scan' editor = next((e for e in self.editor_area.editors if e.id == 'pychron.scanner'), None) if editor is not None: scanner.reset() else: editor = ScannerEditor(model=scanner, name=name, id='pychron.scanner') self._open_editor(editor, activate=False) self.split_editors(0, 1, h2=300, orientation='vertical') self.activate_editor(editor) @on_trait_change('window:opened') def _opened(self): self.scan_manager.activate() self._scan_factory() ee = [e for e in self.editor_area.control.children() if isinstance(e, EditorWidget)][0] # print int(ee.features()) # ee.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures) # print int(ee.features()) # ee.update_title() # ============= EOF =============================================
UManPychron/pychron
pychron/spectrometer/tasks/spectrometer_task.py
Python
apache-2.0
11,184
/* * Copyright 2020 The Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package v1 import ( corev1 "k8s.io/api/core/v1" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" v1 "knative.dev/serving/pkg/apis/serving/v1" ) // GetCondition returns the condition currently associated with the given type, // or nil. func (ts *TopicStatus) GetCondition(t apis.ConditionType) *apis.Condition { return topicCondSet.Manage(ts).GetCondition(t) } // GetTopLevelCondition returns the top level condition func (ts *TopicStatus) GetTopLevelCondition() *apis.Condition { return topicCondSet.Manage(ts).GetTopLevelCondition() } // IsReady returns true if the resource is ready overall. func (ts *TopicStatus) IsReady() bool { return topicCondSet.Manage(ts).IsHappy() } // InitializeConditions sets relevant unset conditions to Unknown state. func (ts *TopicStatus) InitializeConditions() { topicCondSet.Manage(ts).InitializeConditions() } func (ts *TopicStatus) SetAddress(url *apis.URL) { if ts.Address == nil { ts.Address = &duckv1.Addressable{} } if url != nil { ts.Address.URL = url topicCondSet.Manage(ts).MarkTrue(TopicConditionAddressable) } else { ts.Address.URL = nil topicCondSet.Manage(ts).MarkFalse(TopicConditionAddressable, "emptyUrl", "url is the empty string") // The TopicConditionAddressable is not included in the ready set as we don't want to create Publishers for Sources. // We therefore need to set the ConditionReady to false here. topicCondSet.Manage(ts).MarkFalse(apis.ConditionReady, "emptyUrl", "url is the empty string") } } func (ts *TopicStatus) PropagatePublisherStatus(ss *v1.ServiceStatus) { sc := ss.GetCondition(apis.ConditionReady) if sc == nil { ts.MarkPublisherNotConfigured() return } switch { case sc.Status == corev1.ConditionUnknown: ts.MarkPublisherUnknown(sc.Reason, sc.Message) case sc.Status == corev1.ConditionTrue: ts.SetAddress(ss.Address.URL) ts.MarkPublisherDeployed() case sc.Status == corev1.ConditionFalse: ts.MarkPublisherNotDeployed(sc.Reason, sc.Message) default: ts.MarkPublisherUnknown("TopicUnknown", "The status of Topic is invalid: %v", sc.Status) } } // MarkPublisherDeployed sets the condition that the publisher has been deployed. func (ts *TopicStatus) MarkPublisherDeployed() { topicCondSet.Manage(ts).MarkTrue(TopicConditionPublisherReady) } // MarkPublisherUnknown sets the condition that the status of publisher is Unknown. func (ts *TopicStatus) MarkPublisherUnknown(reason, messageFormat string, messageA ...interface{}) { topicCondSet.Manage(ts).MarkUnknown(TopicConditionPublisherReady, reason, messageFormat, messageA...) // The TopicConditionPublisherReady is not included in the ready set as we don't want to create Publishers for Sources. // We therefore need to set the ConditionReady to unknown here. topicCondSet.Manage(ts).MarkUnknown(apis.ConditionReady, reason, messageFormat, messageA...) } // MarkPublisherNotDeployed sets the condition that the publisher has not been deployed. func (ts *TopicStatus) MarkPublisherNotDeployed(reason, messageFormat string, messageA ...interface{}) { topicCondSet.Manage(ts).MarkFalse(TopicConditionPublisherReady, reason, messageFormat, messageA...) // The TopicConditionPublisherReady is not included in the ready set as we don't want to create Publishers for Sources. // We therefore need to set the ConditionReady to false here. topicCondSet.Manage(ts).MarkFalse(apis.ConditionReady, reason, messageFormat, messageA...) } // MarkPublisherNotConfigured changes the PublisherReady condition to be unknown to reflect // that the Publisher does not yet have a Status. func (ts *TopicStatus) MarkPublisherNotConfigured() { topicCondSet.Manage(ts).MarkUnknown(TopicConditionPublisherReady, "PublisherNotConfigured", "Publisher has not yet been reconciled") // The TopicConditionPublisherReady is not included in the ready set as we don't want to create Publishers for Sources. // We therefore need to set the ConditionReady to unknown here. topicCondSet.Manage(ts).MarkUnknown(apis.ConditionReady, "PublisherNotConfigured", "Publisher has not yet been reconciled") } // MarkTopicReady sets the condition that the topic has been created. func (ts *TopicStatus) MarkTopicReady() { topicCondSet.Manage(ts).MarkTrue(TopicConditionTopicExists) } // MarkNoTopic sets the condition that signals there is not a topic for this // Topic. This could be because of an error or the Topic is being deleted. func (ts *TopicStatus) MarkNoTopic(reason, messageFormat string, messageA ...interface{}) { topicCondSet.Manage(ts).MarkFalse(TopicConditionTopicExists, reason, messageFormat, messageA...) }
google/knative-gcp
pkg/apis/intevents/v1/topic_lifecycle.go
GO
apache-2.0
5,205
#!/usr/bin/perl -w ## Raquel Norel (rnorel@us.ibm.com) 01/2015 #validate format of predictions for DREAM9.5 Olfactory Prediciton Challenge (sub challenge 1) #not using gold standard here, hardcode or build needed info use strict; use Cwd qw(abs_path cwd); ## command line arguments if (@ARGV != 3) { print "\nUSAGE:perl $0 <input file to validate> <output file> <flag L for Leaderboard or F for final submission> \n\n"; print "Format validation for DREAM9.5 Olfactory Prediction Sub Challenge 1\n"; print "example: perl $0 my_prediction.txt errors.txt L\n"; exit; } ##PARAMETERS my @header = ('#oID','individual','descriptor','value');#just in case, since values for different columns are quite different my $DATA_POINTS = 71001; # number of entries to get my $Ncols = 4; # #oID descriptor value sigma #global variables my %oIDs = (); my %descriptors = (); my %individuals = (); my $dir = cwd(); #prediction file my $file = $ARGV[0]; #input file, predictions my $out_fn = "$dir/$ARGV[1]"; #output file, results from validaiton script my $phase = $ARGV[2]; #use F for Final scoring and L for Leaderboard if (($phase ne 'F') && ($phase ne 'L')){ die "phase has to be either L or F not $phase. Bye...\n"; } print STDERR "reading $file\n"; #generate expected ids my ($ref_val) = generate_ids($phase); my %val = %$ref_val; my $lines; { open my $fh, "<", $file or die $!; local $/; # enable localized slurp mode $lines = <$fh>; close $fh; } my @all = split(/[\r\n]+/,$lines); #Mac, Unix and DOS files my $valid_data_lines=0; #how many valid data lines have been seen my $check_header_flag=0; my $errors = ''; #keep all errors to be reported to user #while (<IN>) { my $ln=1; foreach (@all){ #print STDERR "processing $_"; my $line = $_; if ($line =~ /^\s*$/) {next;} ## skip blank lines #need to check for columns number before other check to avoid warning if less columns than expected my @tmp = split ("\t", $line); #separating line by comma, separate only once for all the tests $tmp[2] =~ s/\s//g; #remove spaces; detected on CHEMICAL my $n_cols = scalar @tmp; #number of columns if (!check_column_number($n_cols,$ln)){last;} #correct number of columns? if (/^#/) { ## check header, assume is 1st line $check_header_flag++ ; #header detected for (my $i=0; $i< scalar(@header); $i++){ if ($tmp[$i] ne $header[$i]) { $errors .= "\n".'ERROR in the header '; my $tmpi = $i + 1; $errors .= "Column $tmpi is $tmp[$i] and should be $header[$i]. Error at input line # $ln.\n"; last; } } } else{ if (!check_format_labels($tmp[0],$tmp[1],$tmp[2],$ln)){last;} #correct "labels", is it repeated? if (!check_format_cols4($tmp[3],$ln)){last;} #correct format of col 4; nuemeric betwwen 0 and 100 $valid_data_lines++; } $ln++; } if ($check_header_flag != 1) { $errors .= "We didn't detect the correct header in the prediction file.\n";} #error reporting open (FH, "> $out_fn") or die "cannot open $out_fn (why? $!) \n"; if (($errors eq '' ) && ($valid_data_lines == $DATA_POINTS)) {print FH "OK\nValid data file\n";} #all good; still need to check for header count elsif (($errors eq '' ) && ($valid_data_lines < $DATA_POINTS)){ check_missing(); #only check for missing prediction if no other errors are found, since quiting at 1st error print FH "NOT_OK\nYou have the following error(s): $errors\n"; print FH "Please see the template file and resubmit the updated file.\n"; } else { print FH "NOT_OK\nYou have the following error(s): $errors\n"; print FH "Please see the template file and resubmit the updated file.\n"; } close FH; ###########subroutines############## #check id combinations with no predictions sub check_missing{ foreach my $k1 (sort keys %oIDs){ for (my $i=1; $i<50; $i++){ foreach my $k2 (sort keys %descriptors){ if ( $val{$k1}{$i}{$k2} < 0){ $errors .= "Missing predictions for $k1 $i $k2 entry\n";} } } } return(1); } sub check_format_labels{ # checking the ID has not been used twice, and the name is correct my ($oid, $ind, $des, $ln) = @_; my $flag =1; #so far so good if (!defined($oIDs{$oid})) { $errors .= "$oid is not a valid odor ID. Error at input line # $ln.\n"; return(0);} #failed test if (!defined($descriptors{$des})) { $errors .= "$des is not a valid odor descriptor. Error at input line # $ln.\n"; return(0);} #failed test if (!defined($individuals{$ind})) { $errors .= "$ind is not a valid individual id. Error at input line # $ln.\n"; return(0);} #failed test if($val{$oid}{$ind}{$des} == -1){ $val{$oid}{$ind}{$des} = 1; } else {$errors .= "$oid, $ind with $des is a duplicated entry. Error at input line # $ln.\n"; return(0);}; #failed test return(1); } sub check_format_cols4{ #is numeric? is it between 0 and 100? my ($val,$ln) = @_; # if (( $val =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) && ($val >= 0) && ($val <= 1) || ($val == 1) || ($val==0)){ if (( $val =~ /^([+]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) && ($val <= 100)){ #force to be positive return(1); } #test ok; #test failed $errors .= "Value must be a positive float number, less or equal to 100. Got $val, which is incorrect.\nError at input line # $ln.\n"; return(0);#failed test } #since I don;t read the gold standard, I need to generate the expected full set if IDs on the prediction file, to check against it sub generate_ids{ my ($phase) = @_; my @Ldescriptors = qw(ACID AMMONIA/URINOUS BAKERY BURNT CHEMICAL COLD DECAYED FISH FLOWER FRUIT GARLIC GRASS INTENSITY/STRENGTH MUSKY SOUR SPICES SWEATY SWEET VALENCE/PLEASANTNESS WARM WOOD); my @LoIDs; if ($phase eq 'F'){ @LoIDs = qw(1031 10857465 10886 11567 12020 12265 12377 1549025 15654 16537 17898 180 18467 21363 251531 262 264 2733294 27440 3102 31219 31276 31283 323 3314 440917 5281167 5281168 5318599); my @tmp1 = qw(5352837 5364231 5371102 5862 5962 60998 61523 62089 62351 62465 6274 6322 637758 6506 6544 6561 6669 702 7092 7137 7302 7476 750 753 7559); my @tmp2 = qw(7657 7770 7793 7797 8025 8049 8094 8419 8438 8468 853433 8815 8878 9012 962); push (@LoIDs, @tmp1); push (@LoIDs, @tmp2); } elsif ($phase eq 'L'){ @LoIDs = qw(1030 1060 10722 11124 11419 12206 12348 12748 13187 13204 13216 13436 14328 1549778 1550470 15606 16220109 22386 24020 243 24473 2682 31210); my @tmp1 = qw(31266 33032 454 520108 5352539 5355850 5363233 5367698 61024 6114390 61151 61155 61177 61252 6137 61771 62572 638024 6386 641256 679 6826 6989); my @tmp2 = qw(7047 7409 7601 7632 778574 7792 7820 7826 8038 8048 8051 8078 8137 8159 8163 8175 8180 8205 8294 8452 8467 8615 9024); push (@LoIDs, @tmp1); push (@LoIDs, @tmp2); } my $No = scalar (@LoIDs); #print "there are $No elements in oIDs\n"; my $Nd = scalar(@Ldescriptors); #print "there are $Nd descriptors\n"; my %val = (); my %sigma = (); #convinient to have as hash as well for ease of checking for (my $i=0; $i<$No; $i++){ $oIDs{$LoIDs[$i]} = 1; #print ".$LoIDs[$i].\n"; } for (my $i=0; $i<$Nd; $i++){ $descriptors{$Ldescriptors[$i]} = 1; #print ".$Ldescriptors[$i].\n"; } for (my $i=1; $i<50; $i++){ $individuals{$i} = 1; } for (my $i=0; $i<$No; $i++){ for (my $k=1; $k<50; $k++){ for (my $j=0; $j<$Nd;$j++){ $val{$LoIDs[$i]}{$k}{$Ldescriptors[$j]} = -1; } } } #return(\%val,\%sigma); #it is enough to check for one of the values, since I alrwady check for number of columns return(\%val); } #check that the number of columns per line is ok sub check_column_number{ my ($n_cols, $ln) = @_; if ($n_cols != $Ncols) { $errors .= "Please note that the numbers of expected columns is $Ncols not $n_cols. Error at input line # $ln.\n"; return(0);#failed test } return(1); #test ok }
Sage-Bionetworks/OlfactionDREAMChallenge
src/main/resources/DREAM_Olfactory_S1_validation.pl
Perl
apache-2.0
7,965
--- layout: model title: Translate Brazilian Sign Language to Swedish Pipeline author: John Snow Labs name: translate_bzs_sv date: 2021-06-04 tags: [open_source, pipeline, seq2seq, translation, bzs, sv, xx, multilingual] task: Translation language: xx edition: Spark NLP 3.1.0 spark_version: 3.0 supported: true article_header: type: cover use_language_switcher: "Python-Scala-Java" --- ## Description Marian is an efficient, free Neural Machine Translation framework written in pure C++ with minimal dependencies. It is mainly being developed by the Microsoft Translator team. Many academic (most notably the University of Edinburgh and in the past the Adam Mickiewicz University in Poznań) and commercial contributors help with its development. It is currently the engine behind the Microsoft Translator Neural Machine Translation services and being deployed by many companies, organizations and research projects (see below for an incomplete list). source languages: bzs target languages: sv {:.btn-box} [Live Demo](https://demo.johnsnowlabs.com/public/TRANSLATION_MARIAN/){:.button.button-orange} [Open in Colab](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/TRANSLATION_MARIAN.ipynb){:.button.button-orange.button-orange-trans.co.button-icon} [Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/translate_bzs_sv_xx_3.1.0_2.4_1622846150423.zip){:.button.button-orange.button-orange-trans.arr.button-icon} ## How to use <div class="tabs-box" markdown="1"> {% include programmingLanguageSelectScalaPythonNLU.html %} ```python from sparknlp.pretrained import PretrainedPipeline pipeline = PretrainedPipeline("translate_bzs_sv", lang = "xx") pipeline.annotate("Your sentence to translate!") ``` ```scala import com.johnsnowlabs.nlp.pretrained.PretrainedPipeline val pipeline = new PretrainedPipeline("translate_bzs_sv", lang = "xx") pipeline.annotate("Your sentence to translate!") ``` {:.nlu-block} ```python import nlu text = ["text to translate"] translate_df = nlu.load('xx.Brazilian Sign Language.translate_to.Swedish').predict(text, output_level='sentence') translate_df ``` </div> {:.model-param} ## Model Information {:.table-model} |---|---| |Model Name:|translate_bzs_sv| |Type:|pipeline| |Compatibility:|Spark NLP 3.1.0+| |License:|Open Source| |Edition:|Official| |Language:|xx| ## Data Source [https://huggingface.co/Helsinki-NLP/opus-mt-bzs-sv](https://huggingface.co/Helsinki-NLP/opus-mt-bzs-sv) ## Included Models - DocumentAssembler - SentenceDetectorDLModel - MarianTransformer
JohnSnowLabs/spark-nlp
docs/_posts/maziyarpanahi/2021-06-04-translate_bzs_sv_xx.md
Markdown
apache-2.0
2,646
<?php namespace Google\AdsApi\AdManager\v202202; /** * This file was generated from WSDL. DO NOT EDIT. */ class CreativeSetError extends \Google\AdsApi\AdManager\v202202\ApiError { /** * @var string $reason */ protected $reason = null; /** * @param string $fieldPath * @param \Google\AdsApi\AdManager\v202202\FieldPathElement[] $fieldPathElements * @param string $trigger * @param string $errorString * @param string $reason */ public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null) { parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString); $this->reason = $reason; } /** * @return string */ public function getReason() { return $this->reason; } /** * @param string $reason * @return \Google\AdsApi\AdManager\v202202\CreativeSetError */ public function setReason($reason) { $this->reason = $reason; return $this; } }
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/v202202/CreativeSetError.php
PHP
apache-2.0
1,078
# Miltonia binoti Cogn. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Miltonia/Miltonia binoti/README.md
Markdown
apache-2.0
171
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config.update; import com.thoughtworks.go.config.BasicCruiseConfig; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.exceptions.EntityType; import com.thoughtworks.go.domain.config.*; import com.thoughtworks.go.domain.packagerepository.PackageDefinition; import com.thoughtworks.go.domain.packagerepository.PackageRepositories; import com.thoughtworks.go.domain.packagerepository.PackageRepository; import com.thoughtworks.go.helper.GoConfigMother; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.server.service.materials.PackageDefinitionService; import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import static com.thoughtworks.go.serverhealth.HealthStateType.forbidden; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class CreatePackageConfigCommandTest { private Username currentUser; private BasicCruiseConfig cruiseConfig; private PackageDefinition packageDefinition; private String packageId; private String packageUuid; private String repoId; private PackageRepository repository; private Configuration configuration; private HttpLocalizedOperationResult result; @Mock private PackageDefinitionService packageDefinitionService; @Mock private GoConfigService goConfigService; @BeforeEach public void setup() throws Exception { currentUser = new Username(new CaseInsensitiveString("user")); result = new HttpLocalizedOperationResult(); cruiseConfig = new GoConfigMother().defaultCruiseConfig(); packageId = "prettyjson"; packageUuid = "random-uuid"; configuration = new Configuration(new ConfigurationProperty(new ConfigurationKey("PACKAGE_ID"), new ConfigurationValue(packageId))); packageDefinition = new PackageDefinition(packageUuid, "prettyjson", configuration); PackageRepositories repositories = cruiseConfig.getPackageRepositories(); repoId = "repoId"; Configuration configuration = new Configuration(new ConfigurationProperty(new ConfigurationKey("foo"), new ConfigurationValue("bar"))); PluginConfiguration pluginConfiguration = new PluginConfiguration("plugin-id", "1"); repository = new PackageRepository(repoId, "repoName", pluginConfiguration, configuration); repositories.add(repository); cruiseConfig.setPackageRepositories(repositories); } @Test public void shouldAddTheSpecifiedPackage() throws Exception { CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, packageDefinition, repoId, currentUser, result, packageDefinitionService); assertNull(cruiseConfig.getPackageRepositories().findPackageDefinitionWith(packageId)); command.update(cruiseConfig); assertThat(cruiseConfig.getPackageRepositories().find(repoId).getPackages().find(packageUuid), is(packageDefinition)); } @Test public void shouldNotContinueIfTheUserDontHavePermissionsToOperateOnPackages() throws Exception { CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, packageDefinition, repoId, currentUser, result, packageDefinitionService); when(goConfigService.isUserAdmin(currentUser)).thenReturn(false); HttpLocalizedOperationResult expectedResult = new HttpLocalizedOperationResult(); expectedResult.forbidden(EntityType.PackageDefinition.forbiddenToEdit(packageDefinition.getId(), currentUser.getUsername()), forbidden()); assertThat(command.canContinue(cruiseConfig), is(false)); assertThat(result, is(expectedResult)); } @Test public void shouldValidateIfPackageNameIsNull() { PackageDefinition pkg = new PackageDefinition("Id", null, new Configuration()); PackageRepository repository = new PackageRepository(repoId, null, null, null); repository.addPackage(pkg); cruiseConfig.setPackageRepositories(new PackageRepositories(repository)); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, pkg, repoId, currentUser, result, packageDefinitionService); assertFalse(command.isValid(cruiseConfig)); assertThat(pkg.errors().getAllOn("name"), is(Arrays.asList("Package name is mandatory"))); } @Test public void shouldValidateIfPackageNameIsInvalid() { PackageRepository repository = cruiseConfig.getPackageRepositories().find(repoId); PackageDefinition pkg = new PackageDefinition("Id", "!$#", new Configuration()); pkg.setRepository(repository); repository.addPackage(pkg); cruiseConfig.setPackageRepositories(new PackageRepositories(repository)); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, pkg, repoId, currentUser, result, packageDefinitionService); assertFalse(command.isValid(cruiseConfig)); assertThat(pkg.errors().getAllOn("name"), is(Arrays.asList("Invalid Package name '!$#'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."))); } @Test public void shouldValidateDuplicatePropertiesInConfiguration() { PackageRepository repository = cruiseConfig.getPackageRepositories().find(repoId); ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("key"), new ConfigurationValue("value")); Configuration configuration = new Configuration(); configuration.add(property); configuration.add(property); PackageDefinition pkg = new PackageDefinition("Id", "name", configuration); pkg.setRepository(repository); repository.addPackage(pkg); cruiseConfig.setPackageRepositories(new PackageRepositories(repository)); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, pkg, repoId, currentUser, result, packageDefinitionService); assertFalse(command.isValid(cruiseConfig)); assertThat(pkg.getAllErrors().toString(), containsString("Duplicate key 'key' found for Package 'name'")); } @Test public void shouldValidateDuplicatePackageName() throws Exception { PackageRepository repository = cruiseConfig.getPackageRepositories().find(repoId); PackageDefinition pkg = new PackageDefinition("Id", "prettyjson", new Configuration()); pkg.setRepository(repository); repository.addPackage(pkg); cruiseConfig.setPackageRepositories(new PackageRepositories(repository)); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, packageDefinition, repoId, currentUser, result, packageDefinitionService); command.update(cruiseConfig); assertFalse(command.isValid(cruiseConfig)); assertThat(packageDefinition.errors().size(), is(1)); assertThat(packageDefinition.errors().firstError(), is("You have defined multiple packages called 'prettyjson'. Package names are case-insensitive and must be unique within a repository.")); } @Test public void shouldValidateDuplicateIdentity() throws Exception { PackageRepository repository = cruiseConfig.getPackageRepositories().find(repoId); PackageDefinition pkg = new PackageDefinition("Id", "name", configuration); pkg.setRepository(repository); repository.addPackage(pkg); cruiseConfig.setPackageRepositories(new PackageRepositories(repository)); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, packageDefinition, repoId, currentUser, result, packageDefinitionService); command.update(cruiseConfig); assertFalse(command.isValid(cruiseConfig)); assertThat(packageDefinition.errors().size(), is(1)); assertThat(packageDefinition.errors().firstError(), is("Cannot save package or repo, found duplicate packages. [Repo Name: 'repoName', Package Name: 'name'], [Repo Name: 'repoName', Package Name: 'prettyjson']")); } @Test public void shouldNotContinueIfTheRepositoryWithSpecifiedRepoIdDoesNotexist() throws Exception { when(goConfigService.isUserAdmin(currentUser)).thenReturn(true); cruiseConfig.setPackageRepositories(new PackageRepositories()); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, packageDefinition, repoId, currentUser, result, packageDefinitionService); HttpLocalizedOperationResult expectedResult = new HttpLocalizedOperationResult(); expectedResult.unprocessableEntity(EntityType.PackageRepository.notFoundMessage(repoId)); assertThat(command.canContinue(cruiseConfig), is(false)); assertThat(result, is(expectedResult)); } @Test public void shouldContinueWithConfigSaveIfUserIsAdmin() { when(goConfigService.isUserAdmin(currentUser)).thenReturn(true); lenient().when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(false); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, packageDefinition, repoId, currentUser, result, packageDefinitionService); assertThat(command.canContinue(cruiseConfig), is(true)); } @Test public void shouldContinueWithConfigSaveIfUserIsGroupAdmin() { when(goConfigService.isUserAdmin(currentUser)).thenReturn(false); when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(true); CreatePackageConfigCommand command = new CreatePackageConfigCommand(goConfigService, packageDefinition, repoId, currentUser, result, packageDefinitionService); assertThat(command.canContinue(cruiseConfig), is(true)); } }
GaneshSPatil/gocd
server/src/test-fast/java/com/thoughtworks/go/config/update/CreatePackageConfigCommandTest.java
Java
apache-2.0
11,054
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vgrechka.phizdetsidea.phizdets.psi.impl; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiInvalidElementAccessException; import com.intellij.psi.impl.light.LightElement; import vgrechka.phizdetsidea.phizdets.psi.resolve.RatedResolveResult; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author yole */ public class ResolveResultList extends ArrayList<RatedResolveResult> { public static List<RatedResolveResult> to(PsiElement element) { if (element== null) { return Collections.emptyList(); } final ResolveResultList list = new ResolveResultList(); list.poke(element, RatedResolveResult.RATE_NORMAL); return list; } // Allows to add non-null elements and discard nulls in a hassle-free way. public boolean poke(final PsiElement what, final int rate) { PyPsiUtils.assertValid(what); if (what == null) return false; if (!(what instanceof LightElement) && !what.isValid()) { throw new PsiInvalidElementAccessException(what, "Trying to resolve a reference to an invalid element"); } super.add(new RatedResolveResult(rate, what)); return true; } }
vovagrechka/fucking-everything
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/psi/impl/ResolveResultList.java
Java
apache-2.0
1,778
namespace ChatSystem.Server.Models.Account { public class LoginStatus { public bool Success { get; set; } public string Message { get; set; } public string TargetURL { get; set; } } }
deyantodorov/Zeus-WebServicesCould-TeamWork
Source/ChatSystem/Server/ChatSystem.Server/Models/Account/LoginStatus.cs
C#
apache-2.0
224
package cz.cuni.mff.d3s.deeco.demo.parkinglotbooking; import java.io.Serializable; public class Position implements Serializable { private static final long serialVersionUID = -1251527172175834548L; public int latitude; public int longitude; public Position(int latitude, int longitude) { this.latitude = latitude; this.longitude = longitude; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if (obj == null) return false; if ( !(obj instanceof Position) ) return false; Position other = (Position) obj; return (latitude == other.latitude) && (longitude == other.longitude); } @Override public int hashCode() { return latitude * 1024 + longitude; } @Override public String toString() { return String.format("[%d,%d]", latitude, longitude); } }
d3scomp/JDEECo-old
src/cz/cuni/mff/d3s/deeco/demo/parkinglotbooking/Position.java
Java
apache-2.0
883
package au.com.dius.pact.provider.junitsupport.filter; import au.com.dius.pact.core.model.Interaction; import au.com.dius.pact.core.model.RequestResponseInteraction; import java.util.Arrays; import java.util.function.Predicate; public interface InteractionFilter<I extends Interaction> { Predicate<I> buildPredicate(String[] values); /** * Filter interactions by any of their provider state. If one matches any of the values, the interaction * is kept and verified. */ class ByProviderState<I extends Interaction> implements InteractionFilter<I> { @Override public Predicate<I> buildPredicate(String[] values) { return interaction -> Arrays.stream(values).anyMatch( value -> interaction.getProviderStates().stream().anyMatch( state -> state .getName() != null && state.getName().matches(value) ) ); } } /** * Filter interactions by their request path, e.g. with value "^\\/somepath.*". */ class ByRequestPath<I extends Interaction> implements InteractionFilter<I> { @Override public Predicate<I> buildPredicate(String[] values) { return interaction -> { if (interaction instanceof RequestResponseInteraction) { return Arrays.stream(values).anyMatch(value -> ((RequestResponseInteraction) interaction).getRequest().getPath().matches(value) ); } else { return false; } }; } } }
DiUS/pact-jvm
provider/src/main/java/au/com/dius/pact/provider/junitsupport/filter/InteractionFilter.java
Java
apache-2.0
1,617
/* * Copyright (c) 2008-2018 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.haulmont.cuba.web.widgets; import com.haulmont.cuba.web.widgets.client.timefield.CubaTimeFieldState; import com.haulmont.cuba.web.widgets.client.timefield.TimeResolution; import com.vaadin.event.FieldEvents; import com.vaadin.shared.communication.FieldRpc; import com.vaadin.shared.ui.textfield.AbstractTextFieldServerRpc; import com.vaadin.ui.AbstractField; import elemental.json.Json; import org.apache.commons.lang3.StringUtils; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkNotNull; public class CubaTimeField extends AbstractField<LocalTime> { protected final class AbstractTextFieldServerRpcImpl implements AbstractTextFieldServerRpc { @Override public void setText(String text, int cursorPosition) { updateDiffstate("text", Json.create(text)); LocalTime value = parseValue(text); setValue(value, true); } } protected final class AbstractTextFieldFocusAndBlurRpcImpl implements FieldRpc.FocusAndBlurServerRpc { @Override public void blur() { fireEvent(new FieldEvents.BlurEvent(CubaTimeField.this)); } @Override public void focus() { fireEvent(new FieldEvents.FocusEvent(CubaTimeField.this)); } } protected String placeholder; protected String timeFormat; protected LocalTime value; public CubaTimeField() { getState(false).maskedMode = true; getState().resolution = TimeResolution.MINUTE; registerRpc(new AbstractTextFieldServerRpcImpl()); registerRpc(new AbstractTextFieldFocusAndBlurRpcImpl()); } @Override protected CubaTimeFieldState getState() { return (CubaTimeFieldState) super.getState(); } @Override protected CubaTimeFieldState getState(boolean markAsDirty) { return (CubaTimeFieldState) super.getState(markAsDirty); } @Override protected boolean setValue(LocalTime value, boolean userOriginated) { value = applyResolutionToValue(value); return super.setValue(value, userOriginated); } @Override protected void doSetValue(LocalTime value) { this.value = value; getState().text = formatValue(value); } protected LocalTime applyResolutionToValue(LocalTime value) { if (value == null) { return null; } LocalTime result = LocalTime.MIDNIGHT; List<TimeResolution> resolutions = getResolutionsHigherOrEqualTo(getResolution()) .collect(Collectors.toList()); for (TimeResolution resolution : resolutions) { switch (resolution) { case HOUR: result = result.withHour(value.getHour()); break; case MINUTE: result = result.withMinute(value.getMinute()); break; case SECOND: result = result.withSecond(value.getSecond()); break; default: throw new IllegalArgumentException("Cannot detect resolution type"); } } return result; } @Override public LocalTime getValue() { return this.value; } public String getTimeFormat() { return this.timeFormat; } public void setTimeFormat(String timeFormat) { this.timeFormat = timeFormat; updateTimeFormat(); } protected void updateTimeFormat() { String mask = StringUtils.replaceChars(timeFormat, "Hhmsa", "####U"); placeholder = StringUtils.replaceChars(mask, "#U", "__"); getState().mask = mask; } public TimeResolution getResolution() { return getState(false).resolution; } public void setResolution(TimeResolution resolution) { getState().resolution = resolution; updateResolution(); } protected void updateResolution() { this.timeFormat = getResolutionsHigherOrEqualTo(getResolution()) .map(this::getResolutionFormat) .collect(Collectors.joining(":")); // By default, only visual representation is updated after the resolution is changed. // As a result, the actual value and the visual representation are different values. // Since we want to update the field value and fire value change event, we reset the value, // taking into account the fact that the setValue(LocalTime, boolean) method applies current // resolution to value. if (getValue() != null) { setValue(getValue(), true); } updateTimeFormat(); } protected Stream<TimeResolution> getResolutionsHigherOrEqualTo(TimeResolution resolution) { return Stream.of(TimeResolution.values()) .skip(resolution.ordinal()) .sorted(Comparator.reverseOrder()); } protected String getResolutionFormat(TimeResolution resolution) { checkNotNull(resolution, "Resolution can't be null"); switch (resolution) { case HOUR: return "HH"; case MINUTE: return "mm"; case SECOND: return "ss"; default: throw new IllegalArgumentException("Cannot detect resolution type"); } } protected LocalTime parseValue(String text) { if (StringUtils.isNotEmpty(text) && !text.equals(placeholder)) { DateTimeFormatter dateTimeFormatter = getDateTimeFormatter(); return LocalTime.parse(text, dateTimeFormatter); } else { return null; } } protected String formatValue(LocalTime value) { if (value == null) { return ""; } DateTimeFormatter dateTimeFormatter = getDateTimeFormatter(); return value.format(dateTimeFormatter); } protected DateTimeFormatter getDateTimeFormatter() { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(timeFormat); Locale locale = getLocale(); if (locale != null) { dateTimeFormatter = dateTimeFormatter.withLocale(locale); } return dateTimeFormatter; } public boolean isCaptionManagedByLayout() { return getState(false).captionManagedByLayout; } public void setCaptionManagedByLayout(boolean captionManagedByLayout) { if (isCaptionManagedByLayout() != captionManagedByLayout) { getState().captionManagedByLayout = captionManagedByLayout; } } }
dimone-kun/cuba
modules/web-widgets/src/com/haulmont/cuba/web/widgets/CubaTimeField.java
Java
apache-2.0
7,434
/* * Copyright 2014-2018 JKOOL, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jkoolcloud.tnt4j.streams.configure.jaxb; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * Java class for JavaObject complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="JavaObject"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="param" type="{}Parameter" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="property" type="{}Property" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{}EntityAttributeGroup"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "JavaObject", propOrder = { "param", "property" }) @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") public class JavaObject { @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") protected List<Parameter> param; @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") protected List<Property> property; @XmlAttribute(name = "name", required = true) @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") protected String name; @XmlAttribute(name = "class", required = true) @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") protected String clazz; /** * Gets the value of the param property. * * <p> * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for * the param property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getParam().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Parameter } * * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") public List<Parameter> getParam() { if (param == null) { param = new ArrayList<Parameter>(); } return this.param; } public void addParam(Parameter p) { getParam().add(p); } public void addParam(String name, String type) { getParam().add(new Parameter(name, type)); } public void addParam(String name, String value, String type) { getParam().add(new Parameter(name, value, type)); } /** * Gets the value of the property property. * * <p> * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for * the property property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getProperty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Property } * * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") public List<Property> getProperty() { if (property == null) { property = new ArrayList<Property>(); } return this.property; } public void addProperty(Property p) { getProperty().add(p); } public void addProperty(String name, String value) { getProperty().add(new Property(name, value)); } /** * Gets the value of the name property. * * @return possible object is {@link String } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is {@link String } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") public void setName(String value) { this.name = value; } /** * Gets the value of the clazz property. * * @return possible object is {@link String } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is {@link String } * */ @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-04-25T04:53:31+03:00", comments = "JAXB RI v2.2.4-2") public void setClazz(String value) { this.clazz = value; } }
Nastel/tnt4j-streams
tnt4j-streams-core/src/main/java/com/jkoolcloud/tnt4j/streams/configure/jaxb/JavaObject.java
Java
apache-2.0
5,842
public class JumpGame { public boolean canJump(int[] A) { int maxIndex = 0; for(int i=0;i<A.length;i++) { if(i>maxIndex) return false; maxIndex = Math.max(maxIndex, i+A[i]); if(maxIndex>=A.length-1) break; } return false; } public int jump(int[] A) { if(A==null || A.length==0) return 0; int size = A.length; int start=0 ,end=0, max=0,step=0; while(end<size) { while(start<=end) { max = Math.max(max, start+A[start]); if(max>=size-1) return step+1; ++start; } start = end +1; end = max; ++step; } return step; } public static String minWindow(String S, String T) { int[] needToFind = new int[256]; int[] hasFind = new int[256]; int minlen = Integer.MAX_VALUE; String res = ""; int start = 0, end =0,count=0; for(int i=0;i<T.length();i++) { char index = T.charAt(i); ++needToFind[index]; } for(;end<S.length();end++) { char cur = S.charAt(end); if(needToFind[cur] ==0 ) continue; ++hasFind[cur]; if(hasFind[cur]<=needToFind[cur]) ++count; if(count == T.length()) { char startChar = S.charAt(start); while(needToFind[startChar]==0 || hasFind[startChar] > needToFind[startChar]) { ++start; if(hasFind[startChar] > needToFind[startChar]) --hasFind[startChar]; startChar = S.charAt(start); } int len = end - start +1; if(len<minlen) { minlen = len; res = S.substring(start, end+1); } } } return res; } public static void main(String[] args) { minWindow("a", "aa"); } }
EricDong4/LeetCode
src/JumpGame.java
Java
apache-2.0
1,584
<a href="../juguetes-toxicos" class="text-primary"> <div class="articulo thumbnail-link animated pulse col-xs-6 col-sm-6 col-md-4"> <img src="../juguetes-toxicos/toxicos_md.jpg" alt="Juguetes toxicos"> <div class="thumbnail-parrafo"> <h4 class="service-heading">¿Cómo saber si los juguetes sexuales son seguros para mi cuerpo?</h4> <p>No todos los juguetes sexuales son seguros para el cuerpo, algunos contienen químicos tóxicos para el cuerpo o no se pueden limpiar. Conoce cómo identificarlos y escoger productos seguros.</p> <a href="../juguetes-toxicos" class="leer-mas text-center text-primary"> <i class="fa fa-eye fa-2x"></i> </a> </div> </div> </a>
mayaibuki/explora
juguetes-toxicos/thumb.php
PHP
apache-2.0
777
angular.module('Angular').config([ '$routeProvider', function ($routeProvider) { $routeProvider.when('/exampleRoute', { templateUrl: 'app/exampleRoute/exampleRoute.html', controller: 'exampleRoute', controllerAs: 'exampleRoute' }); }]);
MartinKilonzo/Sandbox
src/app/exampleRoute/index.js
JavaScript
apache-2.0
259
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx; import static com.google.common.base.Predicates.notNull; import com.facebook.buck.io.MorePaths; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.args.Arg; import com.facebook.buck.rules.args.SanitizedArg; import com.facebook.buck.rules.args.SourcePathArg; import com.facebook.buck.rules.args.StringArg; import com.facebook.buck.rules.coercer.FrameworkPath; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import java.nio.file.Path; import java.util.EnumSet; import javax.annotation.Nullable; public class CxxLinkableEnhancer { private static final EnumSet<Linker.LinkType> SONAME_REQUIRED_LINK_TYPES = EnumSet.of( Linker.LinkType.SHARED, Linker.LinkType.MACH_O_BUNDLE ); // Utility class doesn't instantiate. private CxxLinkableEnhancer() {} /** * Construct a {@link CxxLink} rule that builds a native linkable from top-level input objects * and a dependency tree of {@link NativeLinkable} dependencies. */ public static CxxLink createCxxLinkableBuildRule( TargetGraph targetGraph, CxxPlatform cxxPlatform, BuildRuleParams params, final SourcePathResolver resolver, BuildTarget target, Linker.LinkType linkType, Optional<String> soname, Path output, ImmutableList<Arg> args, Linker.LinkableDepType depType, Iterable<? extends BuildRule> nativeLinkableDeps, Optional<Linker.CxxRuntimeType> cxxRuntimeType, Optional<SourcePath> bundleLoader, ImmutableSet<BuildTarget> blacklist, ImmutableSet<FrameworkPath> frameworks) { // Soname should only ever be set when linking a "shared" library. Preconditions.checkState(!soname.isPresent() || SONAME_REQUIRED_LINK_TYPES.contains(linkType)); // Bundle loaders are only supported for Mach-O bundle libraries Preconditions.checkState( !bundleLoader.isPresent() || linkType == Linker.LinkType.MACH_O_BUNDLE); Linker linker = cxxPlatform.getLd(); // Collect and topologically sort our deps that contribute to the link. NativeLinkableInput linkableInput = NativeLinkables.getTransitiveNativeLinkableInput( targetGraph, cxxPlatform, nativeLinkableDeps, depType, blacklist, /* reverse */ true); // Build up the arguments to pass to the linker. ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder(); // Pass any platform specific or extra linker flags. argsBuilder.addAll( SanitizedArg.from( cxxPlatform.getDebugPathSanitizer().sanitize(Optional.<Path>absent()), cxxPlatform.getLdflags())); // If we're doing a shared build, pass the necessary flags to the linker, including setting // the soname. if (linkType == Linker.LinkType.SHARED) { argsBuilder.add(new StringArg("-shared")); } else if (linkType == Linker.LinkType.MACH_O_BUNDLE) { argsBuilder.add(new StringArg("-bundle")); // It's possible to build a Mach-O bundle without a bundle loader (logic tests, for example). if (bundleLoader.isPresent()) { argsBuilder.add( new StringArg("-bundle_loader"), new SourcePathArg(resolver, bundleLoader.get())); } } if (soname.isPresent()) { argsBuilder.addAll(StringArg.from(linker.soname(soname.get()))); } // Add all the top-level arguments. argsBuilder.addAll(args); // Add all arguments from our dependencies. argsBuilder.addAll(linkableInput.getArgs()); // Add all shared libraries addSharedLibrariesLinkerArgs( cxxPlatform, resolver, ImmutableSortedSet.<FrameworkPath>copyOf(linkableInput.getLibraries()), argsBuilder); // Add framework args - from both linkable dependancies and the frameworks for the binary addFrameworkLinkerArgs( cxxPlatform, resolver, mergeFrameworks(linkableInput, frameworks), argsBuilder); // Add all arguments needed to link in the C/C++ platform runtime. Linker.LinkableDepType runtimeDepType = depType; if (cxxRuntimeType.or(Linker.CxxRuntimeType.DYNAMIC) == Linker.CxxRuntimeType.STATIC) { runtimeDepType = Linker.LinkableDepType.STATIC; } argsBuilder.addAll(StringArg.from(cxxPlatform.getRuntimeLdflags().get(runtimeDepType))); final ImmutableList<Arg> allArgs = argsBuilder.build(); // Build the C/C++ link step. return new CxxLink( // Construct our link build rule params. The important part here is combining the build // rules that construct our object file inputs and also the deps that build our // dependencies. params.copyWithChanges( target, new Supplier<ImmutableSortedSet<BuildRule>>() { @Override public ImmutableSortedSet<BuildRule> get() { return FluentIterable.from(allArgs) .transformAndConcat(Arg.getDepsFunction(resolver)) .toSortedSet(Ordering.natural()); } }, Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of())), resolver, cxxPlatform.getLd(), output, allArgs); } private static ImmutableSortedSet<FrameworkPath> mergeFrameworks( NativeLinkableInput nativeLinkable, ImmutableSet<FrameworkPath> frameworkPaths) { return ImmutableSortedSet.<FrameworkPath>naturalOrder() .addAll(nativeLinkable.getFrameworks()) .addAll(frameworkPaths) .build(); } private static void addSharedLibrariesLinkerArgs( CxxPlatform cxxPlatform, SourcePathResolver resolver, ImmutableSortedSet<FrameworkPath> allLibraries, ImmutableList.Builder<Arg> argsBuilder) { Optional<ImmutableSortedSet<FrameworkPath>> libraries = Optional.of(allLibraries); ImmutableSet<Path> librarySearchPaths = CxxDescriptionEnhancer.getFrameworkSearchPaths( libraries, cxxPlatform, resolver); for (Path unsanitizedLibrarySearchPath : getLibrarySearchDirectories(librarySearchPaths)) { argsBuilder.add(new StringArg("-L")); argsBuilder.add( new SanitizedArg( cxxPlatform.getDebugPathSanitizer().sanitize(Optional.<Path>absent()), unsanitizedLibrarySearchPath.toString())); } // Add all libraries link args ImmutableList<String> librariesStringArgs = libraries .transform(librariesToLinkerFlagsFunction(resolver)) .get(); for (String libraryStringArg : librariesStringArgs) { argsBuilder.add(new StringArg(libraryStringArg)); } } private static ImmutableSet<Path> getLibrarySearchDirectories(ImmutableSet<Path> libraries) { return FluentIterable.from(libraries) .transform( new Function<Path, Path>() { @Nullable @Override public Path apply(Path input) { return input.getParent(); } } ).filter(notNull()) .toSet(); } private static void addFrameworkLinkerArgs( CxxPlatform cxxPlatform, SourcePathResolver resolver, ImmutableSortedSet<FrameworkPath> allFrameworks, ImmutableList.Builder<Arg> argsBuilder) { Optional<ImmutableSortedSet<FrameworkPath>> frameworks = Optional.of(allFrameworks); // Add all framework search path args ImmutableSet<Path> frameworkSearchPaths = CxxDescriptionEnhancer.getFrameworkSearchPaths( frameworks, cxxPlatform, resolver); for (Path unsanitizedFrameworkSearchPath : frameworkSearchPaths) { argsBuilder.add(new StringArg("-F")); argsBuilder.add( new SanitizedArg( cxxPlatform.getDebugPathSanitizer().sanitize(Optional.<Path>absent()), unsanitizedFrameworkSearchPath.toString())); } // Add all framework link args ImmutableList<String> frameworkStringArgs = frameworks .transform(frameworksToLinkerFlagsFunction(resolver)) .get(); for (String frameworkStringArg : frameworkStringArgs) { argsBuilder.add(new StringArg(frameworkStringArg)); } } public static final Predicate<String> CONTAINS_LIBRARY_NAME = new Predicate<String>() { @Override public boolean apply(@Nullable String input) { return (input != null && !input.equals("-l")); } }; @VisibleForTesting static Function< ImmutableSortedSet<FrameworkPath>, ImmutableList<String>> librariesToLinkerFlagsFunction(final SourcePathResolver resolver) { return new Function<ImmutableSortedSet<FrameworkPath>, ImmutableList<String>>() { @Override public ImmutableList<String> apply(ImmutableSortedSet<FrameworkPath> input) { return FluentIterable .from(input) .transform(linkerFlagsForLibraryFunction(resolver.deprecatedPathFunction())) // libraries set can contain path-qualified libraries, or just library search paths. // Assume these end in '../lib' and filter out here. .filter(CONTAINS_LIBRARY_NAME) .toList(); } }; } private static Function<FrameworkPath, String> linkerFlagsForLibraryFunction( final Function<SourcePath, Path> resolver) { return new Function<FrameworkPath, String>() { @Override public String apply(FrameworkPath input) { return "-l" + MorePaths.stripPathPrefixAndExtension(input.getFileName(resolver), "lib"); } }; } @VisibleForTesting static Function< ImmutableSortedSet<FrameworkPath>, ImmutableList<String>> frameworksToLinkerFlagsFunction(final SourcePathResolver resolver) { return new Function<ImmutableSortedSet<FrameworkPath>, ImmutableList<String>>() { @Override public ImmutableList<String> apply(ImmutableSortedSet<FrameworkPath> input) { return FluentIterable .from(input) .transformAndConcat( linkerFlagsForFrameworkPathFunction(resolver.deprecatedPathFunction())) .toList(); } }; } private static Function<FrameworkPath, Iterable<String>> linkerFlagsForFrameworkPathFunction( final Function<SourcePath, Path> resolver) { return new Function<FrameworkPath, Iterable<String>>() { @Override public Iterable<String> apply(FrameworkPath input) { return ImmutableList.of("-framework", input.getName(resolver)); } }; } }
tgummerer/buck
src/com/facebook/buck/cxx/CxxLinkableEnhancer.java
Java
apache-2.0
11,888
import slayer from "./s_layer"; let params; export function jsApiCall(callback) { WeixinJSBridge.invoke( 'getBrandWCPayRequest', params, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { slayer.alert('支付成功'); if (callback) { callback(); } } else if (res.err_msg == "get_brand_wcpay_request:cancel") { slayer.alert('用户取消支付'); } } ); } export function callpay(callback) { if (typeof('WeixinJSBridge') == "undefined") { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } } else { jsApiCall(callback); } } export default { pay(jsApiParams, callback) { params = jsApiParams; callpay(callback); } }
seed-builder/umbrella-wx
src/assets/js/wechat_pay.js
JavaScript
apache-2.0
969
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.sql.planner.iterative.rule; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.prestosql.sql.planner.PlanNodeIdAllocator; import io.prestosql.sql.planner.Symbol; import io.prestosql.sql.planner.iterative.GroupReference; import io.prestosql.sql.planner.iterative.rule.test.BaseRuleTest; import io.prestosql.sql.planner.iterative.rule.test.PlanBuilder; import io.prestosql.sql.planner.optimizations.joins.JoinGraph; import io.prestosql.sql.planner.plan.Assignments; import io.prestosql.sql.planner.plan.JoinNode; import io.prestosql.sql.planner.plan.JoinNode.EquiJoinClause; import io.prestosql.sql.planner.plan.PlanNode; import io.prestosql.sql.planner.plan.ProjectNode; import io.prestosql.sql.planner.plan.ValuesNode; import io.prestosql.sql.tree.ArithmeticUnaryExpression; import io.prestosql.sql.tree.Expression; import io.prestosql.sql.tree.SymbolReference; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Optional; import java.util.function.Function; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static io.prestosql.SystemSessionProperties.JOIN_REORDERING_STRATEGY; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.any; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.join; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.node; import static io.prestosql.sql.planner.iterative.rule.EliminateCrossJoins.getJoinOrder; import static io.prestosql.sql.planner.iterative.rule.EliminateCrossJoins.isOriginalOrder; import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER; import static io.prestosql.sql.tree.ArithmeticUnaryExpression.Sign.MINUS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestEliminateCrossJoins extends BaseRuleTest { private final PlanNodeIdAllocator idAllocator = new PlanNodeIdAllocator(); @Test public void testEliminateCrossJoin() { tester().assertThat(new EliminateCrossJoins()) .setSystemProperty(JOIN_REORDERING_STRATEGY, "ELIMINATE_CROSS_JOINS") .on(crossJoinAndJoin(INNER)) .matches( join(INNER, ImmutableList.of(aliases -> new EquiJoinClause(new Symbol("cySymbol"), new Symbol("bySymbol"))), join(INNER, ImmutableList.of(aliases -> new EquiJoinClause(new Symbol("axSymbol"), new Symbol("cxSymbol"))), any(), any()), any())); } @Test public void testRetainOutgoingGroupReferences() { tester().assertThat(new EliminateCrossJoins()) .setSystemProperty(JOIN_REORDERING_STRATEGY, "ELIMINATE_CROSS_JOINS") .on(crossJoinAndJoin(INNER)) .matches( node(JoinNode.class, node(JoinNode.class, node(GroupReference.class), node(GroupReference.class)), node(GroupReference.class))); } @Test public void testDoNotReorderOuterJoin() { tester().assertThat(new EliminateCrossJoins()) .setSystemProperty(JOIN_REORDERING_STRATEGY, "ELIMINATE_CROSS_JOINS") .on(crossJoinAndJoin(JoinNode.Type.LEFT)) .doesNotFire(); } @Test public void testIsOriginalOrder() { assertTrue(isOriginalOrder(ImmutableList.of(0, 1, 2, 3, 4))); assertFalse(isOriginalOrder(ImmutableList.of(0, 2, 1, 3, 4))); } @Test public void testJoinOrder() { PlanNode plan = joinNode( joinNode( values(symbol("a")), values(symbol("b"))), values(symbol("c")), symbol("a"), symbol("c"), symbol("c"), symbol("b")); JoinGraph joinGraph = getOnlyElement(JoinGraph.buildFrom(plan)); assertEquals( getJoinOrder(joinGraph), ImmutableList.of(0, 2, 1)); } @Test public void testJoinOrderWithRealCrossJoin() { PlanNode leftPlan = joinNode( joinNode( values(symbol("a")), values(symbol("b"))), values(symbol("c")), symbol("a"), symbol("c"), symbol("c"), symbol("b")); PlanNode rightPlan = joinNode( joinNode( values(symbol("x")), values(symbol("y"))), values(symbol("z")), symbol("x"), symbol("z"), symbol("z"), symbol("y")); PlanNode plan = joinNode(leftPlan, rightPlan); JoinGraph joinGraph = getOnlyElement(JoinGraph.buildFrom(plan)); assertEquals( getJoinOrder(joinGraph), ImmutableList.of(0, 2, 1, 3, 5, 4)); } @Test public void testJoinOrderWithMultipleEdgesBetweenNodes() { PlanNode plan = joinNode( joinNode( values(symbol("a")), values(symbol("b1"), symbol("b2"))), values(symbol("c1"), symbol("c2")), symbol("a"), symbol("c1"), symbol("c1"), symbol("b1"), symbol("c2"), symbol("b2")); JoinGraph joinGraph = getOnlyElement(JoinGraph.buildFrom(plan)); assertEquals( getJoinOrder(joinGraph), ImmutableList.of(0, 2, 1)); } @Test public void testDonNotChangeOrderWithoutCrossJoin() { PlanNode plan = joinNode( joinNode( values(symbol("a")), values(symbol("b")), symbol("a"), symbol("b")), values(symbol("c")), symbol("c"), symbol("b")); JoinGraph joinGraph = getOnlyElement(JoinGraph.buildFrom(plan)); assertEquals( getJoinOrder(joinGraph), ImmutableList.of(0, 1, 2)); } @Test public void testDoNotReorderCrossJoins() { PlanNode plan = joinNode( joinNode( values(symbol("a")), values(symbol("b"))), values(symbol("c")), symbol("c"), symbol("b")); JoinGraph joinGraph = getOnlyElement(JoinGraph.buildFrom(plan)); assertEquals( getJoinOrder(joinGraph), ImmutableList.of(0, 1, 2)); } @Test public void testGiveUpOnNonIdentityProjections() { PlanNode plan = joinNode( projectNode( joinNode( values(symbol("a1")), values(symbol("b"))), symbol("a2"), new ArithmeticUnaryExpression(MINUS, new SymbolReference("a1"))), values(symbol("c")), symbol("a2"), symbol("c"), symbol("c"), symbol("b")); assertEquals(JoinGraph.buildFrom(plan).size(), 2); } private Function<PlanBuilder, PlanNode> crossJoinAndJoin(JoinNode.Type secondJoinType) { return p -> { Symbol axSymbol = p.symbol("axSymbol"); Symbol bySymbol = p.symbol("bySymbol"); Symbol cxSymbol = p.symbol("cxSymbol"); Symbol cySymbol = p.symbol("cySymbol"); // (a inner join b) inner join c on c.x = a.x and c.y = b.y return p.join(INNER, p.join(secondJoinType, p.values(axSymbol), p.values(bySymbol)), p.values(cxSymbol, cySymbol), new EquiJoinClause(cxSymbol, axSymbol), new EquiJoinClause(cySymbol, bySymbol)); }; } private PlanNode projectNode(PlanNode source, String symbol, Expression expression) { return new ProjectNode( idAllocator.getNextId(), source, Assignments.of(new Symbol(symbol), expression)); } private String symbol(String name) { return name; } private JoinNode joinNode(PlanNode left, PlanNode right, String... symbols) { checkArgument(symbols.length % 2 == 0); ImmutableList.Builder<JoinNode.EquiJoinClause> criteria = ImmutableList.builder(); for (int i = 0; i < symbols.length; i += 2) { criteria.add(new JoinNode.EquiJoinClause(new Symbol(symbols[i]), new Symbol(symbols[i + 1]))); } return new JoinNode( idAllocator.getNextId(), JoinNode.Type.INNER, left, right, criteria.build(), ImmutableList.<Symbol>builder() .addAll(left.getOutputSymbols()) .addAll(right.getOutputSymbols()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), ImmutableMap.of()); } private ValuesNode values(String... symbols) { return new ValuesNode( idAllocator.getNextId(), Arrays.stream(symbols).map(Symbol::new).collect(toImmutableList()), ImmutableList.of()); } }
wyukawa/presto
presto-main/src/test/java/io/prestosql/sql/planner/iterative/rule/TestEliminateCrossJoins.java
Java
apache-2.0
11,033
// // SignInViewController.h // ContentBox // // Created by Igor Sapyanik on 22.01.14. /** * Copyright (c) 2014 Kinvey Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ #import <UIKit/UIKit.h> @interface SignInViewController : UIViewController <UIWebViewDelegate, CLLocationManagerDelegate> + (void)presentSignInFlowOnViewController:(UIViewController *)vc animated:(BOOL)animated onCompletion:(STEmptyBlock)success; @property (nonatomic, copy) STEmptyBlock completionBlock; @end
jenkinsairwdemo/finalnearme
QuoteApp/Classes/View Controllers/SignInViewController.h
C
apache-2.0
994
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_27) on Mon Dec 16 23:53:28 EST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFilter.PercentFilter (hadoop-mapreduce-client-core 2.2.0 API)</title> <meta name="date" content="2013-12-16"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFilter.PercentFilter (hadoop-mapreduce-client-core 2.2.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/input/SequenceFileInputFilter.PercentFilter.html" title="class in org.apache.hadoop.mapreduce.lib.input">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/input//class-useSequenceFileInputFilter.PercentFilter.html" target="_top">FRAMES</a></li> <li><a href="SequenceFileInputFilter.PercentFilter.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFilter.PercentFilter" class="title">Uses of Class<br>org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFilter.PercentFilter</h2> </div> <div class="classUseContainer">No usage of org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFilter.PercentFilter</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/mapreduce/lib/input/SequenceFileInputFilter.PercentFilter.html" title="class in org.apache.hadoop.mapreduce.lib.input">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/mapreduce/lib/input//class-useSequenceFileInputFilter.PercentFilter.html" target="_top">FRAMES</a></li> <li><a href="SequenceFileInputFilter.PercentFilter.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2013 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.</small></p> </body> </html>
arrowli/RsyncHadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/target/org/apache/hadoop/mapreduce/lib/input/class-use/SequenceFileInputFilter.PercentFilter.html
HTML
apache-2.0
4,938
import basepage class NavigationBars(basepage.BasePage): def expand_project_panel(self): elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-project"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def expand_admin_panel(self): elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-admin"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def expand_identity_panel(self): elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-identity"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def expand_developer_panel(self): elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-developer"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass """ Project > Compute > Resource """ def expand_project_compute(self): NavigationBars.expand_project_panel(self) elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-project-compute"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def click_project_compute_overview(self): NavigationBars.expand_project_compute(self) self.driver.find_element_by_css_selector( 'a[href="/project/"]').click() def click_project_compute_instance(self): NavigationBars.expand_project_compute(self) self.driver.find_element_by_css_selector( 'a[href="/project/instances/"]').click() def click_project_compute_volumes(self): NavigationBars.expand_project_compute(self) self.driver.find_element_by_css_selector( 'a[href="/project/volumes/"]').click() def click_project_compute_images(self): NavigationBars.expand_project_compute(self) self.driver.find_element_by_css_selector( 'a[href="/project/images/"]').click() def click_project_compute_access_and_security(self): NavigationBars.expand_project_compute(self) self.driver.find_element_by_css_selector( 'a[href="/project/access_and_security/"]').click() """ Project > Network > Resource """ def expand_project_network(self): NavigationBars.expand_project_panel(self) elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-project-network"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def click_project_network_network_topology(self): NavigationBars.expand_project_network(self) self.driver.find_element_by_css_selector( 'a[href="/project/network_topology/"]').click() def click_project_network_networks(self): NavigationBars.expand_project_network(self) self.driver.find_element_by_css_selector( 'a[href="/project/networks/"]').click() def click_project_network_routers(self): NavigationBars.expand_project_network(self) self.driver.find_element_by_css_selector( 'a[href="/project/routers/"]').click() def click_project_network_loadbalancers(self): NavigationBars.expand_project_network(self) self.driver.find_element_by_css_selector( 'a[href="/project/ngloadbalancersv2/"]').click() """ Project > Orchestration > Resource """ def expand_project_orchestration(self): NavigationBars.expand_project_panel(self) elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-project-orchestration"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def click_project_orchestration_stacks(self): NavigationBars.expand_project_orchestration(self) self.driver.find_element_by_css_selector( 'a[href="/project/stacks/"]').click() def click_project_orchestration_resource_types(self): NavigationBars.expand_project_orchestration(self) self.driver.find_element_by_css_selector( 'a[href="/project/stacks/resource_types/"]').click() def click_project_orchestration_template_versions(self): NavigationBars.expand_project_orchestration(self) self.driver.find_element_by_css_selector( 'a[href="/project/stacks/template_versions/"]').click() """ Project > Object Store > Resource """ def expand_project_object_store(self): NavigationBars.expand_project_panel(self) elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-project-object_store"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def click_project_object_store_containers(self): NavigationBars.expand_project_object_store(self) self.driver.find_element_by_css_selector( 'a[href="/project/containers/"]').click() """ Admin > System > Resource """ def expand_admin_system(self): NavigationBars.expand_admin_panel(self) elm = self.driver.find_element_by_css_selector( 'a[data-target="#sidebar-accordion-admin-admin"]') state = elm.get_attribute('class') if 'collapsed' in state: elm.click() else: pass def click_admin_system_overview(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/"]').click() def click_admin_system_hypervisors(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/hypervisors/"]').click() def click_admin_system_host_aggregates(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/aggregates/"]').click() def click_admin_system_instances(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/instances/"]').click() def click_admin_system_volumes(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/volumes/"]').click() def click_admin_system_flavors(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/flavors/"]').click() def click_admin_system_images(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/images/"]').click() def click_admin_system_networks(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/networks/"]').click() def click_admin_system_routers(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/routers/"]').click() def click_admin_system_floating_ips(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/floating_ips/"]').click() def click_admin_system_defaults(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/defaults/"]').click() def click_admin_system_metadata_definitions(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/metadata_defs/"]').click() def click_admin_system_info(self): NavigationBars.expand_admin_system(self) self.driver.find_element_by_css_selector( 'a[href="/admin/info/"]').click() """ Identity > Resource """ def click_identity_projects(self): NavigationBars.expand_identity_panel(self) self.driver.find_element_by_css_selector( 'a[href="/identity/"]').click() def click_identity_users(self): NavigationBars.expand_identity_panel(self) self.driver.find_element_by_css_selector( 'a[href="/identity/users/"]').click() def click_identity_groups(self): NavigationBars.expand_identity_panel(self) self.driver.find_element_by_css_selector( 'a[href="/identity/groups/"]').click() def click_identity_roles(self): NavigationBars.expand_identity_panel(self) self.driver.find_element_by_css_selector( 'a[href="/identity/roles/"]').click()
rcbops-qe/horizon-selenium
pages/navigation_bars.py
Python
apache-2.0
9,234
/** * cms 新增js */ $(document).ready(function(){ // 数据回显 if(bzptCmsId){ intaddBzptCms(bzptCmsId); } //保存 $("#btn_save").on("click",function(){ addBzptCms.saveData(); }); // //确认 // $("#btn_affirm").on("click",function(){ // addArchives.affirmData(); // }); //返回 $("#btn_back").on("click",function(){ window.history.go(-1); }); }); /** * 数据回显 * @param id */ function intaddBzptCms(id){ $.ajax({ url:ctxManager+"/bzptCms/getDetail", data:{id : id}, dataType:"json", type:"post", success:function(res){ if(res.flag){ if(res.bzptCms){ var bzptCms = res.bzptCms; var content = bzptCms.content; $('.summernote').code(content); $('#cms_type').val(bzptCms.cmsType); $('#title').val(bzptCms.title); } } else { console.log("获取失败"); } }, error:function(){ console.log("获取失败"); } }) } var addBzptCms = { /** * 表单校验 */ check : function(){ if($("#cms_type").val() == null || $("#cms_type").val() == "" || $("#cms_type").val() == undefined){ layer.alert("请选择信息类型"); return false; } if($("#title").val() == null || $("#title").val() == "" || $("#title").val() == undefined){ layer.alert("请录入标题"); return false; } else if($("#title").val().length > 30){ layer.alert("标题不得超过30个字符"); return false; } var content= $('.summernote').code(); if(content == null || content == "" || content == undefined){ layer.alert("请录入内容"); return false; } return true; }, /** * 保存表单数据 */ saveData:function(){ //校验 if(!addBzptCms.check()){ return; } var content= $('.summernote').code(); var cmsType = $('#cms_type').val(); var title = $('#title').val(); $.ajax({ url:ctxManager+"/bzptCms/addOrUpdateBzptCms", data:{ id : bzptCmsId, content : content, cmsType : cmsType, title : title }, dataType:"json", type:"post", success:function(res){ if(res.flag){ layer.alert("保存成功!",function(){ // window.history.go(-1); //location.href = ctxManager + '/bzptCms/listBzptCms'; window.parent.OptApi.closeNowTab(); }); }else{ layer.msg("保存失败:"+res.msg); } }, error:function(){ layer.msg("信息保存失败。"); } }) }, /** * 取消、返回上一页 */ cancel:function(){ //location.href = ctxManager + '/bzptCms/listBzptCms'; window.parent.OptApi.closeNowTab(); } };
1461862234/kzf
BZGZPT/bzgzpt-web/src/main/webapp/static/scripts/archives/bzptCms/addBzptCms.js
JavaScript
apache-2.0
2,580
/** * Created by kev on 15-08-14. */ define(['underscore', 'base_sketch', 'snow_2/noiseBuffer'], function (_, BaseSketch, NoiseBuffer) { Number.prototype.mod = function (n) { return ((this % n) + n) % n; }; var HALF_PI = Math.PI / 2; var QUART_PI = Math.PI / 4; var DBL_PI = Math.PI * 2; var ParticleBuffer = function (buffer,img) { buffer.length = 50; buffer.numAngles = 30; buffer.resize(100,buffer.numAngles * 100); var inc = DBL_PI / buffer.numAngles; buffer.ctx.globalAlpha = 0.7; for (var i = 0; i < buffer.numAngles; i++) { buffer.ctx.save(); buffer.ctx.translate(0,i * 100); buffer.ctx.translate(buffer.width >> 1,buffer.width >> 1); buffer.ctx.rotate(i * inc); buffer.ctx.drawImage(img,-buffer.width >> 1,-img.naturalHeight >> 1,buffer.length,img.naturalHeight); buffer.ctx.restore(); } return buffer; }; var Particle = function (noiseBuffer,particleBuffer) { this.noiseBuffer = noiseBuffer; this.particleBuffer = particleBuffer; }; _.extend(Particle.prototype,{ length:Math.random() * 10 + 10, pos :{x:0,y:0}, angle :QUART_PI, count :0, resize:function (w,h) { this.pos = { x:Math.random() * w, y:Math.random() * h }; }, update:function (bounds) { var noiseAmt = this.noiseBuffer.getNoiseByRatio(this.pos.x / (bounds.right - bounds.left),this.pos.y / (bounds.bottom - bounds.top)) * 0.4; this.angle = noiseAmt * HALF_PI;//- QUART_PI/10; var speed = ((noiseAmt + 1) / 2) * 400; var x = this.pos.x - Math.sin(this.angle) * speed; var y = this.pos.y + Math.cos(this.angle) * speed; if (x > bounds.right || x < bounds.left || y > bounds.bottom) { x = Math.random() * (bounds.right - bounds.left) + bounds.left; y = Math.random() * -speed - speed; } this.pos = { x:x, y:y }; }, draw:function (ctx) { var angle = (this.angle + HALF_PI).mod(DBL_PI); var ratio = (angle / DBL_PI); var angleIndex = Math.floor(ratio * this.particleBuffer.numAngles); ctx.drawImage(this.particleBuffer.canvas,0,angleIndex * 100,100,100, this.pos.x,this.pos.y,100,100); } }); return BaseSketch.extend({ particleBuffer:null, noiseBuffer :null, mainBuffer :null, numParticles :1000, frameRate :30, lastUpdate :-1, initialize:function () { this.particles = []; this.snowImg = []; this.mainBuffer = this.createBuffer(); this.ctx = this.mainBuffer.ctx; this.el.appendChild(this.mainBuffer.canvas); var _this = this; this.loadImages(["img/snow.png","img/snow10x10.png","img/LANDING_SECTION.png"]).then(function (imgs) { for (var i = 0; i < imgs.length; i++) { if (imgs[i].src.indexOf("img/LANDING_SECTION.png") !== -1) { _this.bgImage = imgs.splice(i,1)[0]; } } _this.noiseBuffer = new NoiseBuffer({w:100,h:100}); //_this.particle = new Particle(imgs[1],_this.noiseBuffer,_this.createBuffer()); _this.snowImg = imgs; _this.createParticles(); _this.loaded = true; _this.invalidated = true; _this.resize(_this.mainBuffer.width,_this.mainBuffer.height); }).catch(function (e) { console.error(e); }) } , createParticles:function () { this.particleBuffer = new ParticleBuffer(this.createBuffer(),this.snowImg[1]); for (var i = 0; i < this.numParticles; i++) { var particle = new Particle(this.noiseBuffer,this.particleBuffer); particle.resize(this.mainBuffer.width,this.mainBuffer.height); this.particles.push(particle); } }, resize:function (w,h) { //this causes redraw! this.mainBuffer.resize(w,h); if (this.loaded) { } } , draw :function (time) { if (!this.loaded) { return; } if (time - this.lastUpdate > 50) { this.lastUpdate = time; this.noiseBuffer.renderNoise(); this.ctx.fillStyle = "#000"; this.ctx.fillRect(0,0,this.mainBuffer.width,this.mainBuffer.height); // this.ctx.drawImage(this.particleBuffer.canvas,0,0); for (var i = 0; i < this.numParticles; i++) { var particle = this.particles[i];//new Particle(imgs[1],this.noiseBuffer,this.createBuffer()); particle.draw(this.ctx); particle.update({left:-400, top : 0, right:this.mainBuffer.width + 400,bottom:this.mainBuffer.height}); } } } }) });
k-may/sketches
app/scripts/ts/sketches/Clima/snow_2/snow_sketch_2.js
JavaScript
apache-2.0
5,894
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import sys import yaml_util from run import check_run_quick class Processor(object): def __init__(self, config, environ_path, yml_path, aws_path): with open(environ_path, 'r') as f: self.__environ_content = f.read() if not self.__environ_content.endswith('\n'): self.__environ_content += '\n' with open(yml_path, 'r') as f: self.__output = f.read() self.__bindings = yaml_util.YamlBindings() self.__bindings.import_string(config) self.__write_yml_path = yml_path self.__write_aws_path = aws_path self.__write_environ_path = environ_path self.__environ_keys = set() def update_environ(self, key, name): value = self.lookup(key) if value is None: return self.__environ_keys.add(key) assignment = '{name}={value}'.format(name=name, value=value) match = re.search('^{name}=.*'.format(name=name), self.__environ_content, re.MULTILINE) if match: self.__environ_content = ''.join([ self.__environ_content[0:match.start(0)], assignment, self.__environ_content[match.end(0):] ]) else: self.__environ_content += assignment + '\n' def update_in_place(self, key): self.__output = self.__bindings.transform_yaml_source(self.__output, key) def lookup(self, key): try: return self.__bindings.get(key) except KeyError: return None def update_remaining_keys(self): stack = [('', self.__bindings.map)] while stack: prefix, root = stack.pop() for name, value in root.items(): key = '{prefix}{child}'.format(prefix=prefix, child=name) if isinstance(value, dict): stack.append((key + '.', value)) elif not key in self.__environ_keys: try: self.update_in_place(key) except ValueError: pass def process(self): self.update_environ('providers.aws.enabled', 'SPINNAKER_AWS_ENABLED') self.update_environ('providers.aws.defaultRegion', 'SPINNAKER_AWS_DEFAULT_REGION') self.update_environ('providers.google.enabled', 'SPINNAKER_GOOGLE_ENABLED') self.update_environ('providers.google.primaryCredentials.project', 'SPINNAKER_GOOGLE_PROJECT_ID') self.update_environ('providers.google.defaultRegion', 'SPINNAKER_GOOGLE_DEFAULT_REGION') self.update_environ('providers.google.defaultZone', 'SPINNAKER_GOOGLE_DEFAULT_ZONE') self.update_in_place('providers.aws.primaryCredentials.name') aws_name = self.lookup('providers.aws.primaryCredentials.name') aws_key = self.lookup('providers.aws.primaryCredentials.access_key_id') aws_secret = self.lookup('providers.aws.primaryCredentials.secret_key') if aws_key and aws_secret: with open(self.__write_aws_path, 'w') as f: f.write(""" [default] aws_secret_access_key = {secret} aws_access_key_id = {key} """.format(name=aws_name, secret=aws_secret, key=aws_key)) self.update_remaining_keys() with open(self.__write_environ_path, 'w') as f: f.write(self.__environ_content) with open(self.__write_yml_path, 'w') as f: f.write(self.__output) if __name__ == '__main__': if len(sys.argv) != 5: sys.stderr.write('Usage: <content> <environ-path> <local-yml-path> <aws-cred-path>\n') sys.exit(-1) content = sys.argv[1] environ_path = sys.argv[2] local_yml_path = sys.argv[3] aws_credentials_path = sys.argv[4] processor = Processor(content, environ_path, local_yml_path, aws_credentials_path) processor.process() sys.exit(0)
tgracchus/spinnaker
pylib/spinnaker/transform_old_config.py
Python
apache-2.0
4,498
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Mon Oct 13 16:43:26 CST 2014 --> <TITLE> PagerSlidingTabStrip.IconTabProvider (MyMusic 1.0 API Reference) </TITLE> <META NAME="date" CONTENT="2014-10-13"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PagerSlidingTabStrip.IconTabProvider (MyMusic 1.0 API Reference)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../com/tcl/lzhang1/mymusic/ui/widget/PagerSlidingTabStrip.html" title="class in com.tcl.lzhang1.mymusic.ui.widget"><B>PREV CLASS</B></A>&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/tcl/lzhang1/mymusic/ui/widget/PagerSlidingTabStrip.IconTabProvider.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PagerSlidingTabStrip.IconTabProvider.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> com.tcl.lzhang1.mymusic.ui.widget</FONT> <BR> Interface PagerSlidingTabStrip.IconTabProvider</H2> <DL> <DT><B>Enclosing class:</B><DD><A HREF="../../../../../../com/tcl/lzhang1/mymusic/ui/widget/PagerSlidingTabStrip.html" title="class in com.tcl.lzhang1.mymusic.ui.widget">PagerSlidingTabStrip</A></DD> </DL> <HR> <DL> <DT><PRE>public static interface <B>PagerSlidingTabStrip.IconTabProvider</B></DL> </PRE> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/tcl/lzhang1/mymusic/ui/widget/PagerSlidingTabStrip.IconTabProvider.html#getPageIconResId(int)">getPageIconResId</A></B>(int&nbsp;position)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getPageIconResId(int)"><!-- --></A><H3> getPageIconResId</H3> <PRE> int <B>getPageIconResId</B>(int&nbsp;position)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../com/tcl/lzhang1/mymusic/ui/widget/PagerSlidingTabStrip.html" title="class in com.tcl.lzhang1.mymusic.ui.widget"><B>PREV CLASS</B></A>&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/tcl/lzhang1/mymusic/ui/widget/PagerSlidingTabStrip.IconTabProvider.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="PagerSlidingTabStrip.IconTabProvider.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
zhanglei920802/MyMusic
target/javadoc/com/tcl/lzhang1/mymusic/ui/widget/PagerSlidingTabStrip.IconTabProvider.html
HTML
apache-2.0
8,214
package bpool import "testing" func TestBytePool(t *testing.T) { var size int = 4 var width int = 10 bufPool := NewBytePool(size, width) // Check the width if bufPool.Width() != width { t.Fatalf("bytepool width invalid: got %v want %v", bufPool.Width(), width) } // Check that retrieved buffer are of the expected width b := bufPool.Get() if len(b) != width { t.Fatalf("bytepool length invalid: got %v want %v", len(b), width) } // Try putting some invalid buffers into pool bufPool.Put(make([]byte, width-1)) bufPool.Put(make([]byte, width)[2:]) if len(bufPool.c) > 0 { t.Fatal("bytepool should have rejected invalid packets") } // Try putting a short slice into pool bufPool.Put(make([]byte, width)[:2]) if len(bufPool.c) != 1 { t.Fatal("bytepool should have accepted short slice with sufficient capacity") } b = bufPool.Get() if len(b) != width { t.Fatalf("bytepool length invalid: got %v want %v", len(b), width) } // Fill the pool beyond the capped pool size. for i := 0; i < size*2; i++ { bufPool.Put(make([]byte, bufPool.w)) } // Close the channel so we can iterate over it. close(bufPool.c) // Check the size of the pool. if bufPool.NumPooled() != size { t.Fatalf("bytepool size invalid: got %v want %v", len(bufPool.c), size) } }
oxtoacart/bpool
bytepool_test.go
GO
apache-2.0
1,295
/* Drop old Tables */ DROP TABLE IF EXISTS RGMS_DB.Sessions; DROP TABLE IF EXISTS RGMS_DB.Notifications; DROP TABLE IF EXISTS RGMS_DB.AccessRecords; DROP TABLE IF EXISTS RGMS_DB.DiscussionPosts; DROP TABLE IF EXISTS RGMS_DB.Documents; DROP TABLE IF EXISTS RGMS_DB.DiscussionThreads; DROP TABLE IF EXISTS RGMS_DB.DiscussionTypes; DROP TABLE IF EXISTS RGMS_DB.Meetings; DROP TABLE IF EXISTS RGMS_DB.GroupUserMaps; DROP TABLE IF EXISTS RGMS_DB.Coordinators; DROP TABLE IF EXISTS RGMS_DB.Users; DROP TABLE IF EXISTS RGMS_DB.Groups; /* Re-create Database */ DROP DATABASE IF EXISTS RGMS_DB; CREATE DATABASE RGMS_DB; /* Create new Tables */ CREATE TABLE RGMS_DB.Groups ( Id INT PRIMARY KEY NOT NULL auto_increment, GroupName VARCHAR(100) NOT NULL, Description VARCHAR(500), CoordinatorId INT REFERENCES RGMS_DB.Users(Id) ); CREATE TABLE RGMS_DB.Users ( Id INT PRIMARY KEY NOT NULL auto_increment, FirstName VARCHAR(64), LastName VARCHAR(64), Username VARCHAR(64) NOT NULL UNIQUE, StudentId VARCHAR(64) NOT NULL UNIQUE, Passphrase VARCHAR(64)NOT NULL, ImageReference VARCHAR(512), IsAdmin BOOLEAN DEFAULT 0, IsActive BOOLEAN DEFAULT 0, Description VARCHAR(512) ); CREATE TABLE RGMS_DB.Coordinators ( Id INT PRIMARY KEY NOT NULL auto_increment, UserId INT NOT NULL REFERENCES RGMS_DB.Users(Id) ); CREATE TABLE RGMS_DB.GroupUserMaps ( GroupId INT NOT NULL REFERENCES RGMS_DB.Groups(Id), UserId INT NOT NULL REFERENCES RGMS_DB.Users(Id) ); CREATE TABLE RGMS_DB.Meetings ( Id INT PRIMARY KEY NOT NULL auto_increment, Description VARCHAR(128), CreatedByUserId INT NOT NULL REFERENCES RGMS_DB.Users(Id), DateCreated DATETIME DEFAULT NOW(), DateDue DATETIME NULL DEFAULT NOW(), /* NOW() + 1 */ GroupId INT REFERENCES RGMS_DB.Groups(Id) ); CREATE TABLE RGMS_DB.DiscussionThreads ( Id INT PRIMARY KEY NOT NULL auto_increment, GroupId INT NOT NULL REFERENCES RGMS_DB.Groups(Id), ThreadName VARCHAR(100) ); CREATE TABLE RGMS_DB.Documents ( Id INT PRIMARY KEY NOT NULL auto_increment, DocumentPath VARCHAR(128) NOT NULL, /* Root Folder */ DocumentName VARCHAR(64) NOT NULL, VersionNumber INT NOT NULL, UploadDate DATETIME NOT NULL DEFAULT NOW() , ThreadId INT NOT NULL REFERENCES RGMS_DB.DiscussionThreads(Id), GroupId INT NOT NULL REFERENCES RGMS_DB.Groups(Id) ); CREATE TABLE RGMS_DB.DiscussionPosts ( Id INT PRIMARY KEY NOT NULL auto_increment, ThreadId INT NOT NULL REFERENCES RGMS_DB.DiscussionThread(Id), UserId INT NOT NULL REFERENCES RGMS_DB.Users(Id), Message VARCHAR(512) ); CREATE TABLE RGMS_DB.AccessRecords ( Id INT PRIMARY KEY NOT NULL auto_increment, UserId INT NOT NULL REFERENCES RGMS_DB.Users(Id), DateAccessed DATETIME NOT NULL DEFAULT NOW(), DocumentId INT NOT NULL REFERENCES RGMS_DB.Documents(Id) ); CREATE TABLE RGMS_DB.Notifications ( Id INT PRIMARY KEY NOT NULL auto_increment, UserId INT NOT NULL REFERENCES RGMS_DB.Users(Id), /* Receiving User */ GroupId INT REFERENCES RGMS_DB.Groups(Id), /* Receiving Group */ Description VARCHAR(128), Link VARCHAR(512) ); CREATE TABLE RGMS_DB.Sessions ( Id INT PRIMARY KEY NOT NULL auto_increment, DateAccessed DATETIME NOT NULL DEFAULT NOW(), Persistent BOOLEAN NOT NULL DEFAULT false, UserId INT NOT NULL REFERENCES RGMS_DB.Users(Id) ); /* Create Database User */ GRANT USAGE ON *.* TO 'rgms'@'localhost'; DROP USER 'rgms'@'localhost'; CREATE USER 'rgms'@'localhost' IDENTIFIED BY 'seng2050'; GRANT ALL PRIVILEGES ON *.* TO 'rgms'@'localhost' WITH GRANT OPTION; FLUSH PRIVILEGES; /* Insert Data */ INSERT INTO RGMS_DB.Groups (GroupName) VALUES ('Aggregates'); INSERT INTO RGMS_DB.Users (FirstName, LastName, Username, StudentId, Passphrase, IsAdmin, IsActive) VALUES('Admin', 'Admin', 'admin@rgms.com', 'admin', '8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918', true, true); INSERT INTO RGMS_DB.GroupUserMaps (GroupId, UserId) VALUES (1,1);
TylerHaigh/seng2050-assignment3
SqlScripts/CreateDatabase.sql
SQL
apache-2.0
3,882
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_252) on Fri Aug 20 17:47:56 BST 2021 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface psidev.psi.mi.jami.datasource.ModelledBinaryInteractionSource (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)</title> <meta name="date" content="2021-08-20"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface psidev.psi.mi.jami.datasource.ModelledBinaryInteractionSource (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../psidev/psi/mi/jami/datasource/ModelledBinaryInteractionSource.html" title="interface in psidev.psi.mi.jami.datasource">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?psidev/psi/mi/jami/datasource/class-use/ModelledBinaryInteractionSource.html" target="_top">Frames</a></li> <li><a href="ModelledBinaryInteractionSource.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface psidev.psi.mi.jami.datasource.ModelledBinaryInteractionSource" class="title">Uses of Interface<br>psidev.psi.mi.jami.datasource.ModelledBinaryInteractionSource</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../psidev/psi/mi/jami/datasource/ModelledBinaryInteractionSource.html" title="interface in psidev.psi.mi.jami.datasource">ModelledBinaryInteractionSource</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#psidev.psi.mi.jami.xml.model.extension.datasource">psidev.psi.mi.jami.xml.model.extension.datasource</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="psidev.psi.mi.jami.xml.model.extension.datasource"> <!-- --> </a> <h3>Uses of <a href="../../../../../../psidev/psi/mi/jami/datasource/ModelledBinaryInteractionSource.html" title="interface in psidev.psi.mi.jami.datasource">ModelledBinaryInteractionSource</a> in <a href="../../../../../../psidev/psi/mi/jami/xml/model/extension/datasource/package-summary.html">psidev.psi.mi.jami.xml.model.extension.datasource</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../psidev/psi/mi/jami/xml/model/extension/datasource/package-summary.html">psidev.psi.mi.jami.xml.model.extension.datasource</a> that implement <a href="../../../../../../psidev/psi/mi/jami/datasource/ModelledBinaryInteractionSource.html" title="interface in psidev.psi.mi.jami.datasource">ModelledBinaryInteractionSource</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../psidev/psi/mi/jami/xml/model/extension/datasource/XmlModelledBinarySource.html" title="class in psidev.psi.mi.jami.xml.model.extension.datasource">XmlModelledBinarySource</a></span></code> <div class="block">PSI-XML 2.5 data source that provides modelled binary interactions (ignore experimental details).</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../psidev/psi/mi/jami/datasource/ModelledBinaryInteractionSource.html" title="interface in psidev.psi.mi.jami.datasource">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?psidev/psi/mi/jami/datasource/class-use/ModelledBinaryInteractionSource.html" target="_top">Frames</a></li> <li><a href="ModelledBinaryInteractionSource.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </body> </html>
MICommunity/psi-jami
docs/psidev/psi/mi/jami/datasource/class-use/ModelledBinaryInteractionSource.html
HTML
apache-2.0
7,410
package main func main() { messages := make(chan bool) go func() { messages <- true }() println(<-messages && true) } // Output: // true
containous/yaegi
_test/chan8.go
GO
apache-2.0
144
<!doctype html> <html> <head> <meta charset=utf-8> <meta name=description content="Keine Werbung! Schnell und einfach myspass.de benutzen!"> <meta name=viewport content="width=device-width, initial-scale=1, minimal-ui"> <title>Werbefrei myspass.de</title> <meta name=mobile-web-app-capable content=yes> <link rel=apple-touch-icon-precomposed sizes=144x144 href="images/touch/apple-touch-icon-144x144-precomposed.png"> <link rel=apple-touch-icon-precomposed sizes=114x114 href="images/touch/apple-touch-icon-114x114-precomposed.png"> <link rel=apple-touch-icon-precomposed sizes=72x72 href="images/touch/apple-touch-icon-72x72-precomposed.png"> <link rel=apple-touch-icon-precomposed href="images/touch/apple-touch-icon-57x57-precomposed.png"> <meta name=msapplication-TileImage content="images/touch/ms-touch-icon-144x144-precomposed.png"> <meta name=msapplication-TileColor content="#3372DF"> <link rel="shortcut icon" href="images/touch/touch-icon-57x57.png"> <link rel="shortcut icon" sizes=196x196 href="images/touch/touch-icon-196x196.png"> <link rel=stylesheet href="styles/min.h5bp.css"> <link rel=stylesheet href="styles/components/min.components.css"> <link rel=stylesheet href="styles/min.main.css"> </head> <body> <header class="app-bar promote-layer"> <div class=app-bar-container> <button class=menu><img src="images/hamburger.svg"></button> <h1 class=logo>Werbefrei myspass.de</h1> <section class=app-bar-actions> </section> </div> </header> <nav class="navdrawer-container promote-layer"> <h4>Navigation</h4> <ul> <li><a href="#hello">Link öffnen</a></li> <li><a href="#get-started">Hilfe</a></li> </ul> </nav> <main> <h1 id=hello>Schnell und einfach!</h1> <div class=code-sample id=err style="display:none;"> <div class="highlight-module highlight-module--left highlight-module--remember "> <div class="highlight-module__container icon-exclamation "> <div class="highlight-module__content g-wide--push-1 g-wide--pull-1 g-medium--push-1 "> <p class=highlight-module__title> Oooops!</p> <p class=highlight-module__text> Das hätte nicht passieren dürfen, ist der Link korrekt? </p> </div> </div> </div> </div> <p>Video Link hier eintragen:</p> <p><input style="width:100%;" type=search placeholder="http://www.myspass.de/myspass/shows/tvshows/tv-total/TV-total-Sendung-vom-04062014--/17759/" size="100%" id=searchinput /></p> <p><a href="#0" class=button--primary id=searchbtn>Los!</a></p> <video controls style="display:none;" id=videlem type="video/mp4" src="#leer" autobuffer autoplay> <p>Dein Browser unterstützt kein Video Element. Bitte die neuste Version von Google Chrome installieren.</p> </video> </main> <div class=loading style="display:none;">Loading&#8230;</div> <script src="scripts/zepto.min.js"></script> <script src="scripts/min.main.js"></script> <script> (function(a,e,f,g,b,c,d){a.GoogleAnalyticsObject=b;a[b]=a[b]||function(){(a[b].q=a[b].q||[]).push(arguments)};a[b].l=1*new Date;c=e.createElement(f);d=e.getElementsByTagName(f)[0];c.async=1;c.src=g;d.parentNode.insertBefore(c,d)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create","UA-52132685-1","awhitepage.com");ga("send","pageview"); </script> </body> </html>
patrickjaja/awhitepage.com
app/index.html
HTML
apache-2.0
3,201
# Copyright 2021, Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the single_task_evaluator.""" from mint.ctl import single_task_evaluator from mint.ctl import single_task_trainer from third_party.tf_models import orbit import tensorflow as tf import tensorflow_datasets as tfds class SingleTaskEvaluatorTest(tf.test.TestCase): def test_single_task_evaluation(self): iris = tfds.load('iris') train_ds = iris['train'].batch(32) model = tf.keras.Sequential([ tf.keras.Input(shape=(4,), name='features'), tf.keras.layers.Dense(10, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.relu), tf.keras.layers.Dense(3) ]) trainer = single_task_trainer.SingleTaskTrainer( train_ds, label_key='label', model=model, loss_fn=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.SGD( learning_rate=tf.keras.optimizers.schedules.PiecewiseConstantDecay( [0], [0.01, 0.01]))) evaluator = single_task_evaluator.SingleTaskEvaluator( train_ds, label_key='label', model=model, metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) controller = orbit.Controller( trainer=trainer, evaluator=evaluator, steps_per_loop=100, global_step=trainer.optimizer.iterations) controller.train(train_ds.cardinality().numpy()) controller.evaluate() accuracy = evaluator.metrics[0].result().numpy() self.assertGreater(0.925, accuracy) if __name__ == '__main__': tf.test.main()
google-research/mint
mint/ctl/single_task_evaluator_test.py
Python
apache-2.0
2,149
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using IdentityModel; using IdentityServer4.Endpoints.Results; using IdentityServer4.Events; using IdentityServer4.Extensions; using IdentityServer4.Hosting; using IdentityServer4.ResponseHandling; using IdentityServer4.Services; using IdentityServer4.Validation; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace IdentityServer4.Endpoints { /// <summary> /// The device authorization endpoint /// </summary> /// <seealso cref="IdentityServer4.Hosting.IEndpointHandler" /> internal class DeviceAuthorizationEndpoint : IEndpointHandler { private readonly IClientSecretValidator _clientValidator; private readonly IDeviceAuthorizationRequestValidator _requestValidator; private readonly IDeviceAuthorizationResponseGenerator _responseGenerator; private readonly IEventService _events; private readonly ILogger<DeviceAuthorizationEndpoint> _logger; public DeviceAuthorizationEndpoint( IClientSecretValidator clientValidator, IDeviceAuthorizationRequestValidator requestValidator, IDeviceAuthorizationResponseGenerator responseGenerator, IEventService events, ILogger<DeviceAuthorizationEndpoint> logger) { _clientValidator = clientValidator; _requestValidator = requestValidator; _responseGenerator = responseGenerator; _events = events; _logger = logger; } /// <summary> /// Processes the request. /// </summary> /// <param name="context">The HTTP context.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public async Task<IEndpointResult> ProcessAsync(HttpContext context) { _logger.LogTrace("Processing device authorize request."); // validate HTTP if (!HttpMethods.IsPost(context.Request.Method) || !context.Request.HasApplicationFormContentType()) { _logger.LogWarning("Invalid HTTP request for device authorize endpoint"); return Error(OidcConstants.TokenErrors.InvalidRequest); } return await ProcessDeviceAuthorizationRequestAsync(context); } private async Task<IEndpointResult> ProcessDeviceAuthorizationRequestAsync(HttpContext context) { _logger.LogDebug("Start device authorize request."); // validate client var clientResult = await _clientValidator.ValidateAsync(context); if (clientResult.Client == null) return Error(OidcConstants.TokenErrors.InvalidClient); // validate request var form = (await context.Request.ReadFormAsync()).AsNameValueCollection(); var requestResult = await _requestValidator.ValidateAsync(form, clientResult); if (requestResult.IsError) { await _events.RaiseAsync(new DeviceAuthorizationFailureEvent(requestResult)); return Error(requestResult.Error, requestResult.ErrorDescription); } var baseUrl = context.GetIdentityServerBaseUrl().EnsureTrailingSlash(); // create response _logger.LogTrace("Calling into device authorize response generator: {type}", _responseGenerator.GetType().FullName); var response = await _responseGenerator.ProcessAsync(requestResult, baseUrl); await _events.RaiseAsync(new DeviceAuthorizationSuccessEvent(response, requestResult)); // return result _logger.LogDebug("Device authorize request success."); return new DeviceAuthorizationResult(response); } private TokenErrorResult Error(string error, string errorDescription = null, Dictionary<string, object> custom = null) { var response = new TokenErrorResponse { Error = error, ErrorDescription = errorDescription, Custom = custom }; _logger.LogError("Device authorization error: {error}:{errorDescriptions}", error, error ?? "-no message-"); return new TokenErrorResult(response); } private void LogResponse(DeviceAuthorizationResponse response, DeviceAuthorizationRequestValidationResult requestResult) { var clientId = $"{requestResult.ValidatedRequest.Client.ClientId} ({requestResult.ValidatedRequest.Client?.ClientName ?? "no name set"})"; if (response.DeviceCode != null) { _logger.LogTrace("Device code issued for {clientId}: {deviceCode}", clientId, response.DeviceCode); } if (response.UserCode != null) { _logger.LogTrace("User code issued for {clientId}: {userCode}", clientId, response.UserCode); } if (response.VerificationUri != null) { _logger.LogTrace("Verification URI issued for {clientId}: {verificationUri}", clientId, response.VerificationUri); } if (response.VerificationUriComplete != null) { _logger.LogTrace("Verification URI (Complete) issued for {clientId}: {verificationUriComplete}", clientId, response.VerificationUriComplete); } } } }
IdentityServer/IdentityServer4
src/IdentityServer4/src/Endpoints/DeviceAuthorizationEndpoint.cs
C#
apache-2.0
5,657
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vfs.newvfs.impl; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileTooBigException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VFileProperty; import com.intellij.openapi.vfs.VfsBundle; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingRegistry; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.psi.SingleRootFileViewProvider; import com.intellij.util.LocalTimeCounter; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.text.StringFactory; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.Charset; /** * @author max */ public abstract class VirtualFileSystemEntry extends NewVirtualFile { public static final VirtualFileSystemEntry[] EMPTY_ARRAY = new VirtualFileSystemEntry[0]; protected static final PersistentFS ourPersistence = PersistentFS.getInstance(); private static final Key<String> SYMLINK_TARGET = Key.create("local.vfs.symlink.target"); static final int IS_WRITABLE_FLAG = 0x01000000; static final int IS_HIDDEN_FLAG = 0x02000000; private static final int INDEXED_FLAG = 0x04000000; static final int CHILDREN_CACHED = 0x08000000; // makes sense for directory only private static final int DIRTY_FLAG = 0x10000000; static final int IS_SYMLINK_FLAG = 0x20000000; private static final int HAS_SYMLINK_FLAG = 0x40000000; static final int IS_SPECIAL_FLAG = 0x80000000; static final int SYSTEM_LINE_SEPARATOR_DETECTED = CHILDREN_CACHED; // makes sense only for non-directory file static final int ALL_FLAGS_MASK = DIRTY_FLAG | IS_SYMLINK_FLAG | HAS_SYMLINK_FLAG | IS_SPECIAL_FLAG | IS_WRITABLE_FLAG | IS_HIDDEN_FLAG | INDEXED_FLAG | CHILDREN_CACHED; protected final VfsData.Segment mySegment; private final VirtualDirectoryImpl myParent; private final int myId; static { //noinspection ConstantConditions assert (~ALL_FLAGS_MASK) == LocalTimeCounter.TIME_MASK; } public VirtualFileSystemEntry(int id, VfsData.Segment segment, VirtualDirectoryImpl parent) { mySegment = segment; myId = id; myParent = parent; } void updateLinkStatus() { boolean isSymLink = is(VFileProperty.SYMLINK); if (isSymLink) { String target = getParent().getFileSystem().resolveSymLink(this); setLinkTarget(target != null ? FileUtil.toSystemIndependentName(target) : null); } setFlagInt(HAS_SYMLINK_FLAG, isSymLink || getParent().getFlagInt(HAS_SYMLINK_FLAG)); } @Override @NotNull public String getName() { return getNameSequence().toString(); } @NotNull @Override public CharSequence getNameSequence() { return FileNameCache.getVFileName(mySegment.getNameId(myId)); } @Override public VirtualDirectoryImpl getParent() { VirtualDirectoryImpl changedParent = VfsData.getChangedParent(myId); return changedParent != null ? changedParent : myParent; } @Override public boolean isDirty() { return getFlagInt(DIRTY_FLAG); } @Override public long getModificationStamp() { return mySegment.getModificationStamp(myId); } public void setModificationStamp(long modificationStamp) { mySegment.setModificationStamp(myId, modificationStamp); } boolean getFlagInt(int mask) { return mySegment.getFlag(myId, mask); } void setFlagInt(int mask, boolean value) { mySegment.setFlag(myId, mask, value); } public boolean isFileIndexed() { return getFlagInt(INDEXED_FLAG); } public void setFileIndexed(boolean indexed) { setFlagInt(INDEXED_FLAG, indexed); } @Override public void markClean() { setFlagInt(DIRTY_FLAG, false); } @Override public void markDirty() { if (!isDirty()) { markDirtyInternal(); VirtualFileSystemEntry parent = getParent(); if (parent != null) parent.markDirty(); } } protected void markDirtyInternal() { setFlagInt(DIRTY_FLAG, true); } @Override public void markDirtyRecursively() { markDirty(); for (VirtualFile file : getCachedChildren()) { ((NewVirtualFile)file).markDirtyRecursively(); } } protected char[] appendPathOnFileSystem(int accumulatedPathLength, int[] positionRef) { CharSequence name = FileNameCache.getVFileName(mySegment.getNameId(myId)); char[] chars = getParent().appendPathOnFileSystem(accumulatedPathLength + 1 + name.length(), positionRef); int i = positionRef[0]; chars[i] = '/'; positionRef[0] = copyString(chars, i + 1, name); return chars; } protected static int copyString(@NotNull char[] chars, int pos, @NotNull CharSequence s) { int length = s.length(); CharArrayUtil.getChars(s, chars, 0, pos, length); return pos + length; } @Override @NotNull public String getUrl() { String protocol = getFileSystem().getProtocol(); int prefixLen = protocol.length() + "://".length(); char[] chars = appendPathOnFileSystem(prefixLen, new int[]{prefixLen}); copyString(chars, copyString(chars, 0, protocol), "://"); return StringFactory.createShared(chars); } @Override @NotNull public String getPath() { return StringFactory.createShared(appendPathOnFileSystem(0, new int[]{0})); } @Override public void delete(final Object requestor) throws IOException { ourPersistence.deleteFile(requestor, this); } @Override public void rename(final Object requestor, @NotNull @NonNls final String newName) throws IOException { if (getName().equals(newName)) return; if (!isValidName(newName)) { throw new IOException(VfsBundle.message("file.invalid.name.error", newName)); } ourPersistence.renameFile(requestor, this, newName); } @Override @NotNull public VirtualFile createChildData(final Object requestor, @NotNull final String name) throws IOException { validateName(name); return ourPersistence.createChildFile(requestor, this, name); } @Override public boolean isWritable() { return getFlagInt(IS_WRITABLE_FLAG); } @Override public void setWritable(boolean writable) throws IOException { ourPersistence.setWritable(this, writable); } @Override public long getTimeStamp() { return ourPersistence.getTimeStamp(this); } @Override public void setTimeStamp(final long time) throws IOException { ourPersistence.setTimeStamp(this, time); } @Override public long getLength() { return ourPersistence.getLength(this); } @Override public VirtualFile copy(final Object requestor, @NotNull final VirtualFile newParent, @NotNull final String copyName) throws IOException { if (getFileSystem() != newParent.getFileSystem()) { throw new IOException(VfsBundle.message("file.copy.error", newParent.getPresentableUrl())); } if (!newParent.isDirectory()) { throw new IOException(VfsBundle.message("file.copy.target.must.be.directory")); } return EncodingRegistry.doActionAndRestoreEncoding(this, new ThrowableComputable<VirtualFile, IOException>() { @Override public VirtualFile compute() throws IOException { return ourPersistence.copyFile(requestor, VirtualFileSystemEntry.this, newParent, copyName); } }); } @Override public void move(final Object requestor, @NotNull final VirtualFile newParent) throws IOException { if (getFileSystem() != newParent.getFileSystem()) { throw new IOException(VfsBundle.message("file.move.error", newParent.getPresentableUrl())); } EncodingRegistry.doActionAndRestoreEncoding(this, new ThrowableComputable<VirtualFile, IOException>() { @Override public VirtualFile compute() throws IOException { ourPersistence.moveFile(requestor, VirtualFileSystemEntry.this, newParent); return VirtualFileSystemEntry.this; } }); } @Override public int getId() { return VfsData.isFileValid(myId) ? myId : -myId; } @Override public boolean equals(Object o) { return this == o || o instanceof VirtualFileSystemEntry && myId == ((VirtualFileSystemEntry)o).myId; } @Override public int hashCode() { return myId; } @Override @NotNull public VirtualFile createChildDirectory(final Object requestor, @NotNull final String name) throws IOException { validateName(name); return ourPersistence.createChildDirectory(requestor, this, name); } private static void validateName(@NotNull String name) throws IOException { if (!isValidName(name)) { throw new IOException(VfsBundle.message("file.invalid.name.error", name)); } } @Override public boolean exists() { return VfsData.isFileValid(myId); } @Override public boolean isValid() { return exists(); } public String toString() { return getUrl(); } public void setNewName(@NotNull String newName) { if (!isValidName(newName)) { throw new IllegalArgumentException(VfsBundle.message("file.invalid.name.error", newName)); } VirtualDirectoryImpl parent = getParent(); parent.removeChild(this); mySegment.setNameId(myId, FileNameCache.storeName(newName)); parent.addChild(this); } public void setParent(@NotNull VirtualFile newParent) { VirtualDirectoryImpl parent = getParent(); parent.removeChild(this); VirtualDirectoryImpl directory = (VirtualDirectoryImpl)newParent; VfsData.changeParent(myId, directory); directory.addChild(this); updateLinkStatus(); } @Override public boolean isInLocalFileSystem() { return getFileSystem() instanceof LocalFileSystem; } public void invalidate() { VfsData.invalidateFile(myId); } @NotNull @Override public Charset getCharset() { return isCharsetSet() ? super.getCharset() : computeCharset(); } @NotNull private Charset computeCharset() { Charset charset; if (isDirectory()) { Charset configured = EncodingManager.getInstance().getEncoding(this, true); charset = configured == null ? Charset.defaultCharset() : configured; setCharset(charset); } else if (SingleRootFileViewProvider.isTooLargeForContentLoading(this)) { charset = super.getCharset(); } else { try { final byte[] content; try { content = contentsToByteArray(); } catch (FileNotFoundException e) { // file has already been deleted on disk return super.getCharset(); } charset = LoadTextUtil.detectCharsetAndSetBOM(this, content); } catch (FileTooBigException e) { return super.getCharset(); } catch (IOException e) { throw new RuntimeException(e); } } return charset; } @Override public String getPresentableName() { if (UISettings.getInstance().HIDE_KNOWN_EXTENSION_IN_TABS && !isDirectory()) { final String nameWithoutExtension = getNameWithoutExtension(); return nameWithoutExtension.isEmpty() ? getName() : nameWithoutExtension; } return getName(); } @Override public boolean is(@NotNull VFileProperty property) { if (property == VFileProperty.SPECIAL) return getFlagInt(IS_SPECIAL_FLAG); if (property == VFileProperty.HIDDEN) return getFlagInt(IS_HIDDEN_FLAG); if (property == VFileProperty.SYMLINK) return getFlagInt(IS_SYMLINK_FLAG); return super.is(property); } public void updateProperty(String property, boolean value) { if (property == PROP_WRITABLE) setFlagInt(IS_WRITABLE_FLAG, value); if (property == PROP_HIDDEN) setFlagInt(IS_HIDDEN_FLAG, value); } public void setLinkTarget(@Nullable String target) { putUserData(SYMLINK_TARGET, target); } @Override public String getCanonicalPath() { if (getFlagInt(HAS_SYMLINK_FLAG)) { if (is(VFileProperty.SYMLINK)) { return getUserData(SYMLINK_TARGET); } VirtualFileSystemEntry parent = getParent(); if (parent != null) { return parent.getCanonicalPath() + "/" + getName(); } return getName(); } return getPath(); } @Override public NewVirtualFile getCanonicalFile() { if (getFlagInt(HAS_SYMLINK_FLAG)) { final String path = getCanonicalPath(); return path != null ? (NewVirtualFile)getFileSystem().findFileByPath(path) : null; } return this; } }
ol-loginov/intellij-community
platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualFileSystemEntry.java
Java
apache-2.0
13,465
/** * Copyright (C) 2009 GIP RECIA http://www.recia.fr * @Author (C) 2009 GIP RECIA <contact@recia.fr> * @Contributor (C) 2009 SOPRA http://www.sopragroup.com/ * @Contributor (C) 2011 Pierre Legay <pierre.legay@recia.fr> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * ESUP-Portail Commons - Copyright (c) 2006-2009 ESUP-Portail consortium. */ package org.esupportail.commons.services.application; import org.esupportail.commons.exceptions.ConfigException; import org.esupportail.commons.services.database.DatabaseUtils; import org.esupportail.commons.services.exceptionHandling.ExceptionUtils; import org.esupportail.commons.services.logging.Logger; import org.esupportail.commons.services.logging.LoggerImpl; import org.esupportail.commons.utils.BeanUtils; /** * Utilities for versionning management. */ public class VersionningUtils { /** * The initial version. */ public static final String VERSION_0 = "0.0.0"; /** * The name of the bean for the versionning service. */ private static final String VERSIONNING_SERVICE_BEAN = "versionningService"; /** * A logger. */ private static final Logger LOG = new LoggerImpl(VersionningUtils.class); /** * Constructor. */ protected VersionningUtils() { throw new UnsupportedOperationException(); } /** * Print the syntax and exit. */ private static void syntax() { throw new IllegalArgumentException( "syntax: " + VersionningUtils.class.getSimpleName() + " <options>" + "\nwhere option can be:" + "\n- check-version: initialize the database" + "\n- init: initialize the database" + "\n- upgrade: upgrade the database"); } /** * @return the versionning service. */ public static VersionningService createVersionningService() { return (VersionningService) BeanUtils.getBean(VERSIONNING_SERVICE_BEAN); } /** * @param t * @throws ConfigException */ private static void closeAndRethrowException(final Throwable t) throws ConfigException { ConfigException ex = null; if (t instanceof ConfigException) { ex = (ConfigException) t; } else { ex = new ConfigException(t); } DatabaseUtils.close(); throw ex; } /** * Initialize the database. */ private static void doInitDatabase() { try { DatabaseUtils.open(); DatabaseUtils.begin(); createVersionningService().initDatabase(); DatabaseUtils.commit(); DatabaseUtils.close(); } catch (Throwable t) { closeAndRethrowException(t); } doUpgradeDatabase(); } /** * check the database version, silently upgrade if possible. * @param throwException * @param printLatestVersion * @throws ConfigException */ public static void checkVersion( final boolean throwException, final boolean printLatestVersion) throws ConfigException { createVersionningService().checkVersion(throwException, printLatestVersion); } /** * check the database version, silently upgrade if possible. * @param throwException * @param printLatestVersion * @throws ConfigException */ private static void doCheckVersion( final boolean throwException, final boolean printLatestVersion) throws ConfigException { try { DatabaseUtils.open(); DatabaseUtils.begin(); checkVersion(throwException, printLatestVersion); DatabaseUtils.commit(); DatabaseUtils.close(); } catch (Throwable t) { closeAndRethrowException(t); } } /** * Upgrade the database. */ private static void doUpgradeDatabase() { while (true) { try { DatabaseUtils.open(); DatabaseUtils.begin(); boolean recall = createVersionningService().upgradeDatabase(); DatabaseUtils.commit(); DatabaseUtils.close(); if (!recall) { return; } } catch (Throwable t) { closeAndRethrowException(t); } } } /** * Dispatch dependaing on the arguments. * @param args */ protected static void dispatch(final String[] args) { switch (args.length) { case 0: syntax(); break; case 1: if ("init".equals(args[0])) { doInitDatabase(); } else if ("upgrade".equals(args[0])) { doUpgradeDatabase(); } else if ("check-version".equals(args[0])) { doCheckVersion(false, true); } else { syntax(); } break; default: syntax(); break; } } /** * The main method, called by ant. * @param args */ public static void main(final String[] args) { try { ApplicationService applicationService = ApplicationUtils.createApplicationService(); LOG.info(applicationService.getName() + " v" + applicationService.getVersion()); dispatch(args); } catch (Throwable t) { ExceptionUtils.catchException(t); } } }
GIP-RECIA/esco-grouper-ui
ext/esup-commons/src/main/java/org/esupportail/commons/services/application/VersionningUtils.java
Java
apache-2.0
5,336
package org.jetbrains.plugins.scala package lang package psi package impl package base import com.intellij.lang.ASTNode import org.jetbrains.plugins.scala.lang.parser.ScalaElementTypes import org.jetbrains.plugins.scala.lang.psi.api.base._ import org.jetbrains.plugins.scala.lang.psi.api.base.patterns._ import org.jetbrains.plugins.scala.lang.psi.stubs.ScPatternListStub /** * @author Alexander Podkhalyuzin * Date: 22.02.2008 */ class ScPatternListImpl private () extends ScalaStubBasedElementImpl[ScPatternList] with ScPatternList{ def this(node: ASTNode) = {this(); setNode(node)} def this(stub: ScPatternListStub) = {this(); setStub(stub); setNullNode()} override def toString: String = "ListOfPatterns" def patterns: Seq[ScPattern] = { val stub = getStub if (stub != null && allPatternsSimple) { return stub.getChildrenByType(ScalaElementTypes.REFERENCE_PATTERN, JavaArrayFactoryUtil.ScReferencePatternFactory) } findChildrenByClass[ScPattern](classOf[ScPattern]) } def allPatternsSimple: Boolean = { val stub = getStub if (stub != null) { return stub.asInstanceOf[ScPatternListStub].allPatternsSimple } !patterns.exists(p => !(p.isInstanceOf[ScReferencePattern])) } }
triggerNZ/intellij-scala
src/org/jetbrains/plugins/scala/lang/psi/impl/base/ScPatternListImpl.scala
Scala
apache-2.0
1,238
# Nemophila menziesii subsp. integrifolia (Parish) Munz SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Nemophila/Nemophila menziesii/ Syn. Nemophila menziesii integrifolia/README.md
Markdown
apache-2.0
213
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * Copyright (C) 2010-2017 Eugene Fradkin (eugene.fradkin@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.oracle.model; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.sql.ResultSet; /** * Oracle sequence */ public class OracleQueue extends OracleSchemaObject { private static final Log log = Log.getLog(OracleQueue.class); public enum QueueType { NORMAL_QUEUE, EXCEPTION_QUEUE, NON_PERSISTENT_QUEUE, }; private String queueTable; private int qId; private QueueType queueType; private Integer maxRetries; private Integer retryDelay; private String enqueueEnabled; private String dequeueEnabled; private String retention; private String userComment; private String networkName; public OracleQueue(OracleSchema schema, String name) { super(schema, name, false); } public OracleQueue(OracleSchema schema, ResultSet dbResult) { super(schema, JDBCUtils.safeGetString(dbResult, "NAME"), true); this.queueTable = JDBCUtils.safeGetString(dbResult, "QUEUE_TABLE"); try { this.queueType = QueueType.valueOf(JDBCUtils.safeGetString(dbResult, "QUEUE_TYPE")); } catch (IllegalArgumentException e) { this.queueType = null; } this.maxRetries = JDBCUtils.safeGetInteger(dbResult, "MAX_RETRIES"); this.retryDelay = JDBCUtils.safeGetInteger(dbResult, "RETRY_DELAY"); this.qId = JDBCUtils.safeGetInt(dbResult, "QID"); this.enqueueEnabled = JDBCUtils.safeGetString(dbResult, "ENQUEUE_ENABLED"); this.dequeueEnabled = JDBCUtils.safeGetString(dbResult, "DEQUEUE_ENABLED"); this.retention = JDBCUtils.safeGetString(dbResult, "RETENTION"); this.userComment = JDBCUtils.safeGetString(dbResult, "USER_COMMENT"); this.networkName = JDBCUtils.safeGetString(dbResult, "NETWORK_NAME"); } @NotNull @Property(viewable = true, order = 2) public OracleTableBase getQueueTable(DBRProgressMonitor monitor) throws DBException { return this.parent.tableCache.getObject(monitor, parent, queueTable); } @NotNull @Property(viewable = true, order = 3) public int getQId() { return qId; } @Property(viewable = true, order = 4) public QueueType getQueueType() { return queueType; } @Property(viewable = true, order = 5) public Integer getMaxRetries() { return maxRetries; } @Property(viewable = true, order = 6) public Integer getRetryDelay() { return retryDelay; } @Property(viewable = true, order = 7) public String getEnqueueEnabled() { return enqueueEnabled; } @Property(viewable = true, order = 8) public String getDequeueEnabled() { return dequeueEnabled; } @Property(viewable = true, order = 9) public String getRetention() { return retention; } @Property(viewable = true, order = 10) public String getUserComment() { return userComment; } @Property(viewable = true, order = 11) public String getNetworkName() { return networkName; } }
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/model/OracleQueue.java
Java
apache-2.0
4,024
package com.zm.paipai.pinglunactivity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.TextView; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import com.zm.paipai.R; import com.zm.paipai.proj.ListactivityBean; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.util.ArrayList; public class listActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "listActivity"; private ListView lv_pinglun; private BaseAdapter adapter; private TextView tv_content; private TextView tv_dianzan; // 一个listview对应的list是不可以变化的(引用) final ArrayList<ListactivityBean.PingLun> pinglunList = new ArrayList<ListactivityBean.PingLun>(); private ProgressBar progressbar; private RadioButton rb3; private TextView tv5; private EditText et; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); lv_pinglun = ((ListView) findViewById(R.id.lv_pinglun)); progressbar = ((ProgressBar) findViewById(R.id.progressbar)); rb3 = ((RadioButton) findViewById(R.id.rb3)); tv5 = ((TextView) findViewById(R.id.tv5)); et = ((EditText) findViewById(R.id.et)); et.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { ((TextView) v).setHint("请输入..."); } else { ((TextView) v).setHint(" "); } } }); LayoutInflater infla = LayoutInflater.from(this); View headView = infla.inflate(R.layout.head_item, null); imageView = ((ImageView) headView.findViewById(R.id.iv)); lv_pinglun.addHeaderView(headView, null, true); Intent intent=getIntent(); String imageUrl=intent.getExtras().getString("imageUrl"); Picasso.with(this).load(imageUrl).placeholder(R.drawable.amc).error(R.mipmap.ic_launcher).fit().into(imageView); rb3.setOnClickListener(this); adapter = new BaseAdapter() { @Override public int getCount() { return pinglunList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 打气筒 view就是指每一个listview item View view = View.inflate(listActivity.this, R.layout.activity, null); View view1=View.inflate(listActivity.this,R.layout.activity_list,null); TextView tv_name = ((TextView) view.findViewById(R.id.tv_name)); tv_content = ((TextView) view.findViewById(R.id.tv_content)); tv_dianzan = ((TextView) findViewById(R.id.tv_dianzan)); ListactivityBean.PingLun pinglun = pinglunList.get(position); tv_name.setText(pinglun.name); tv_content.setText(pinglun.content); tv_dianzan.setText(pinglun.dianzan); return view; } }; lv_pinglun.setAdapter(adapter); getpinglunList(); } private void getpinglunList() { RequestParams params = new RequestParams("http://10.40.5.24:8080/webpro4/getpinglun"); x.http().get(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { Gson gson = new Gson(); ListactivityBean bean = gson.fromJson(result, ListactivityBean.class); pinglunList.addAll(bean.pinglunlist); adapter.notifyDataSetChanged(); progressbar.setVisibility(View.GONE); } @Override public void onError(Throwable ex, boolean isOnCallback) { progressbar.setVisibility(View.VISIBLE); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } @Override public void onClick(View v) { Intent intent=new Intent(this,XinxiActivity.class); startActivity(intent); } }
wsd325888/paike1
app/src/main/java/com/zm/paipai/pinglunactivity/listActivity.java
Java
apache-2.0
5,270
/* Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by injection-gen. DO NOT EDIT. package filtered import ( context "context" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" cache "k8s.io/client-go/tools/cache" apiskedav1alpha1 "knative.dev/eventing-autoscaler-keda/third_party/pkg/apis/keda/v1alpha1" versioned "knative.dev/eventing-autoscaler-keda/third_party/pkg/client/clientset/versioned" v1alpha1 "knative.dev/eventing-autoscaler-keda/third_party/pkg/client/informers/externalversions/keda/v1alpha1" client "knative.dev/eventing-autoscaler-keda/third_party/pkg/client/injection/client" filtered "knative.dev/eventing-autoscaler-keda/third_party/pkg/client/injection/informers/factory/filtered" kedav1alpha1 "knative.dev/eventing-autoscaler-keda/third_party/pkg/client/listers/keda/v1alpha1" controller "knative.dev/pkg/controller" injection "knative.dev/pkg/injection" logging "knative.dev/pkg/logging" ) func init() { injection.Default.RegisterFilteredInformers(withInformer) injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) } // Key is used for associating the Informer inside the context.Context. type Key struct { Selector string } func withInformer(ctx context.Context) (context.Context, []controller.Informer) { untyped := ctx.Value(filtered.LabelKey{}) if untyped == nil { logging.FromContext(ctx).Panic( "Unable to fetch labelkey from context.") } labelSelectors := untyped.([]string) infs := []controller.Informer{} for _, selector := range labelSelectors { f := filtered.Get(ctx, selector) inf := f.Keda().V1alpha1().ClusterTriggerAuthentications() ctx = context.WithValue(ctx, Key{Selector: selector}, inf) infs = append(infs, inf.Informer()) } return ctx, infs } func withDynamicInformer(ctx context.Context) context.Context { untyped := ctx.Value(filtered.LabelKey{}) if untyped == nil { logging.FromContext(ctx).Panic( "Unable to fetch labelkey from context.") } labelSelectors := untyped.([]string) for _, selector := range labelSelectors { inf := &wrapper{client: client.Get(ctx), selector: selector} ctx = context.WithValue(ctx, Key{Selector: selector}, inf) } return ctx } // Get extracts the typed informer from the context. func Get(ctx context.Context, selector string) v1alpha1.ClusterTriggerAuthenticationInformer { untyped := ctx.Value(Key{Selector: selector}) if untyped == nil { logging.FromContext(ctx).Panicf( "Unable to fetch knative.dev/eventing-autoscaler-keda/third_party/pkg/client/informers/externalversions/keda/v1alpha1.ClusterTriggerAuthenticationInformer with selector %s from context.", selector) } return untyped.(v1alpha1.ClusterTriggerAuthenticationInformer) } type wrapper struct { client versioned.Interface selector string } var _ v1alpha1.ClusterTriggerAuthenticationInformer = (*wrapper)(nil) var _ kedav1alpha1.ClusterTriggerAuthenticationLister = (*wrapper)(nil) func (w *wrapper) Informer() cache.SharedIndexInformer { return cache.NewSharedIndexInformer(nil, &apiskedav1alpha1.ClusterTriggerAuthentication{}, 0, nil) } func (w *wrapper) Lister() kedav1alpha1.ClusterTriggerAuthenticationLister { return w } func (w *wrapper) List(selector labels.Selector) (ret []*apiskedav1alpha1.ClusterTriggerAuthentication, err error) { reqs, err := labels.ParseToRequirements(w.selector) if err != nil { return nil, err } selector = selector.Add(reqs...) lo, err := w.client.KedaV1alpha1().ClusterTriggerAuthentications().List(context.TODO(), v1.ListOptions{ LabelSelector: selector.String(), // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. }) if err != nil { return nil, err } for idx := range lo.Items { ret = append(ret, &lo.Items[idx]) } return ret, nil } func (w *wrapper) Get(name string) (*apiskedav1alpha1.ClusterTriggerAuthentication, error) { // TODO(mattmoor): Check that the fetched object matches the selector. return w.client.KedaV1alpha1().ClusterTriggerAuthentications().Get(context.TODO(), name, v1.GetOptions{ // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. }) }
knative-sandbox/eventing-autoscaler-keda
third_party/pkg/client/injection/informers/keda/v1alpha1/clustertriggerauthentication/filtered/clustertriggerauthentication.go
GO
apache-2.0
4,685
# Euphorbia orygis Dinter SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Euphorbia/Euphorbia orygis/README.md
Markdown
apache-2.0
173
# Herpesvirales ORDER #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Viruses/Herpesvirales/README.md
Markdown
apache-2.0
169
# Ciminalis aquatica (L.) Zuev SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Gentiana aquatica auct. non L. ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Gentianaceae/Ciminalis/Ciminalis aquatica/README.md
Markdown
apache-2.0
204
# Primula knuthiana Pax SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Primulaceae/Primula/Primula knuthiana/README.md
Markdown
apache-2.0
171
# Candollea amoena (R.Br.) F.Muell. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Stylidium amoenum R.Br. ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Stylidiaceae/Stylidium/Candollea amoena/README.md
Markdown
apache-2.0
202
# Isoetes rimbachiana H.P.Fuchs SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Lycopodiophyta/Lycopodiopsida/Isoetales/Isoetaceae/Isoetes/Isoetes rimbachiana/README.md
Markdown
apache-2.0
179
# Chassalia lurida (Blume) Miq. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Chassalia/Chassalia curviflora/ Syn. Chassalia lurida/README.md
Markdown
apache-2.0
186
# Geopyxis marasmioides Speg. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Syll. fung. (Abellini) 8: 66 (1889) #### Original name Geopyxis marasmioides Speg. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Pyronemataceae/Geopyxis/Geopyxis marasmioides/README.md
Markdown
apache-2.0
214
# Nocardia Trevis. GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Nocardia Trevis. ### Remarks null
mdoering/backbone
life/Bacteria/Actinobacteria/Actinobacteria/Actinomycetales/Nocardiaceae/Nocardia/README.md
Markdown
apache-2.0
184
# Eryngium biebersteinianum Nevski ex Bobrov SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Eryngium/Eryngium caeruleum/ Syn. Eryngium biebersteinianum/README.md
Markdown
apache-2.0
199
# Otidea reisneri Velen. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Ceské Houby 4-5: 872 (1922) #### Original name Otidea reisneri Velen. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Pyronemataceae/Otidea/Otidea reisneri/README.md
Markdown
apache-2.0
197
package com.yy.cloud.core.assess.data.repositories; /** * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 5/8/18 9:07 PM<br/> * * @author chenxj * @see * @since JDK 1.8 */ public interface PerAssessAnswerCount { Integer getCompletedCount(); }
YY-ORG/yycloud
yy-core/yy-assess/src/main/java/com/yy/cloud/core/assess/data/repositories/PerAssessAnswerCount.java
Java
apache-2.0
289
class User(object): def __init__(self, username=None, password=None, email=None): self.username = username self.password = password self.email = email @classmethod def admin(cls): return cls(username="admin", password="admin") #random values for username and password @classmethod def random_data(cls): from random import randint return cls(username="user" + str(randint(0, 1000)), password="pass" + str(randint(0, 1000)))
ArtemVavilov88/php4dvd_tests
php4dvd/model/user.py
Python
apache-2.0
512
package com.baofeng.fengmi.remoter; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.abooc.util.Debug; import com.baofeng.fengmi.lib.voice.dialog.AudioRecorderButton; import com.baofeng.fengmi.remoter.KeyboardRemoter.KeyCode; /** * 遥控器 * * @author zhangjunpu * @date 16/4/21 */ public class RemoteControlFragment extends Fragment implements View.OnLongClickListener, View.OnTouchListener { private View mPower; //电源 private View mHome; //主页 private View mBack; //返回 private View mMenu; //菜单 private AudioRecorderButton mBiu; //Biu键 private View mVolumeUp; //音量加 private View mVolumeDown; //音量键 private KeyboardView mKeyboardView; private TouchSweepView mTouchSweepEventView; private KeyboardRemoter mRemoter; private SoundPool mSoundPool; private int mSoundID; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_tv_control, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mKeyboardView = (KeyboardView) view.findViewById(R.id.Keyboard); mTouchSweepEventView = (TouchSweepView) view.findViewById(R.id.view_touch); mKeyboardView.setOnItemKeyLongClickListener(this); mKeyboardView.setOnItemKeyTouchListener(this); mTouchSweepEventView.setOnSweepEventListener(new TouchSweepView.OnSweepEventListener() { @Override public void onSweepEvent(int keyCode, int action) { mRemoter.send(keyCode, MotionEvent.ACTION_DOWN); mRemoter.send(keyCode, MotionEvent.ACTION_UP); } }); init(view); // mSoundPool = new SoundPool.Builder().build(); mSoundPool = new SoundPool(5, AudioManager.STREAM_RING, 0); mSoundID = mSoundPool.load(getContext().getApplicationContext(), R.raw.fm_controller_button_pressed, 1); } private void init(View view) { mPower = view.findViewById(R.id.power); mHome = view.findViewById(R.id.home); mBack = view.findViewById(R.id.back); mMenu = view.findViewById(R.id.menu); mBiu = (AudioRecorderButton) view.findViewById(R.id.biu); mVolumeUp = view.findViewById(R.id.volume_up); mVolumeDown = view.findViewById(R.id.volume_down); mPower.setOnTouchListener(this); mHome.setOnTouchListener(this); mBack.setOnTouchListener(this); mMenu.setOnTouchListener(this); mVolumeUp.setOnTouchListener(this); mVolumeDown.setOnTouchListener(this); mPower.setOnLongClickListener(this); mHome.setOnLongClickListener(this); mBack.setOnLongClickListener(this); mMenu.setOnLongClickListener(this); mVolumeUp.setOnLongClickListener(this); mVolumeDown.setOnLongClickListener(this); mBiu.setOnTouchListener(getOnBiuTouchListener()); mBiu.setOnClickListener(getOnBiuClickListener()); mBiu.setOnLongClickListener(this); mBiu.setOnAudioFinishRecordListener(new AudioRecorderButton.OnAudioFinishRecordListener() { @Override public void onFinish(String result) { if (result != null && result.length() > 0) { mRemoter.sendVoice(KeyCode.BIU, result); Debug.anchor("语音输出结果:" + result); } } }); } public void setRemoter(KeyboardRemoter remoter) { mRemoter = remoter; } @Override public void onResume() { super.onResume(); } public void doKeyboardSwitch() { if (mTouchSweepEventView.getVisibility() == View.VISIBLE) { showKeyboardView(); } else { showSweepEventView(); } } private void showKeyboardView() { mKeyboardView.setVisibility(View.VISIBLE); mTouchSweepEventView.setVisibility(View.GONE); } private void showSweepEventView() { mTouchSweepEventView.setVisibility(View.VISIBLE); mKeyboardView.setVisibility(View.GONE); } private int getKeyCodeByView(View v) { int i = v.getId(); if (i == R.id.power) { return KeyCode.POWER; } else if (i == R.id.home) { return KeyCode.HOME; } else if (i == R.id.back) { return KeyCode.BACK; } else if (i == R.id.menu) { return KeyCode.MENU; } else if (i == R.id.biu) { return KeyCode.BIU; } else if (i == R.id.volume_up) { return KeyCode.VOLUME_UP; } else if (i == R.id.volume_down) { return KeyCode.VOLUME_DOWN; } else if (i == R.id.up) { return KeyCode.UP; } else if (i == R.id.down) { return KeyCode.DOWN; } else if (i == R.id.left) { return KeyCode.LEFT; } else if (i == R.id.right) { return KeyCode.RIGHT; } else if (i == R.id.submit) { return KeyCode.OK; } return 0; } private void playSound() { mSoundPool.play( mSoundID, 1.0f, //左耳道音量【0~1】 1.0f, //右耳道音量【0~1】 0, //播放优先级【0表示最低优先级】 1, //循环模式【0表示循环一次,-1表示一直循环,其他表示数字+1表示当前数字对应的循环次数】 1 //播放速度【1是正常,范围从0~2】 ); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { longPressing = false; playSound(); int keyCode = getKeyCodeByView(v); mRemoter.send(keyCode, MotionEvent.ACTION_DOWN); break; } case MotionEvent.ACTION_UP: { longPressing = false; int keyCode = getKeyCodeByView(v); mRemoter.send(keyCode, MotionEvent.ACTION_UP); break; } } return false; } private boolean longPressing = false; private Handler GoGo = new Handler() { @Override public void handleMessage(Message msg) { if (longPressing) { mRemoter.send(msg.what, MotionEvent.ACTION_MOVE); GoGo.sendEmptyMessageDelayed(msg.what, 100); } } }; @Override public boolean onLongClick(View v) { longPressing = true; if (v.getId() == R.id.biu) { onBiuLongClick(); return true; } int keyCode = getKeyCodeByView(v); mRemoter.send(keyCode, MotionEvent.ACTION_DOWN); GoGo.sendEmptyMessage(keyCode); return true; } /** * BIU键长按事件 */ void onBiuLongClick() { mBiu.start(); //TODO 去掉语音 } private View.OnTouchListener getOnBiuTouchListener() { return new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (longPressing && MotionEvent.ACTION_UP == event.getAction()) { longPressing = false; mBiu.release(); //TODO 去掉语音 } return false; } }; } private View.OnClickListener getOnBiuClickListener() { return new View.OnClickListener() { @Override public void onClick(View v) { playSound(); mRemoter.send(KeyCode.BIU, MotionEvent.ACTION_DOWN); } }; } @Override public void onDestroy() { super.onDestroy(); mBiu.destroy(); mSoundPool.release(); } }
battleground/joker
tv-remoter/src/main/java/com/baofeng/fengmi/remoter/RemoteControlFragment.java
Java
apache-2.0
8,424
<div> <span>This is a comma separated list of Ant-style GLOB paths (relative to workspace root) of source or binary files.</span> <span>Ex: src/main/java/**/*.java or bin/**/*.class.</span> <span>Any files matching the supplied paths will be included in the zip sent to Code Dx.</span> <span>For some information about the Ant GLOB format look <a href="https://ant.apache.org/manual/dirtasks.html">here</a>.</span> </div>
jenkinsci/codedx-plugin
src/main/webapp/help-sourceAndBinaryFiles.html
HTML
apache-2.0
422
/** * Copyright [2013] [runrightfast.co] * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ module.exports = function(objectSchemaDatabase, log) { 'use strict'; var extend = require('extend'); var uuid = require('runrightfast-commons').uuid; var hapi = require('hapi'); var types = hapi.types; var when = require('when'); var lodash = require('lodash'); var querystring = require('querystring'); var ObjectSchema = require('runrightfast-validator').validatorDomain.ObjectSchema; var apiVersion = '/v1'; var resource = 'objectschemas'; var path = function(resourcePath) { var routePath = apiVersion + '/resources/' + resource; if (resourcePath) { routePath += resourcePath; } if (log.isDebugEnabled()) { log.debug('path(): ' + routePath); } return routePath; }; var ResponseMetaData = function(path, request) { this.path = path; this.method = request.method; this.id = uuid(); this.receivedOn = new Date(); }; ResponseMetaData.prototype.stopTimer = function() { this.processingTime = Date.now() - this.receivedOn.getTime(); }; var handleError = function(request, responseMessage, err) { responseMessage.error = { code: err.code || 500, developerMessage: err.toString(), userMessage: { server_error: 'Failed to retrieve object schemas because of unexpected server error' } }; request.reply(responseMessage).code(responseMessage.error.code); responseMessage.meta.stopTimer(); }; var getObjectSchemas = function getObjectSchemas(_path, request) { var defaultGetObjectSchemasParams = { limit: 10, offset: 0, dataOnly: false, links: true, actions: true, version: false, raw: false }; var getParams = function() { var params = { limit: request.query.limit, offset: request.query.offset, dataFields: request.query.dataFields, timeout: request.query.timeout, version: request.query.version, dataOnly: request.query.dataOnly, actions: request.query.actions, links: request.query.links, sort: request.query.sort, raw: request.query.raw }; params = extend(defaultGetObjectSchemasParams, params); if (log.isDebugEnabled()) { log.debug('getObjectSchemas(): request.query: ' + JSON.stringify(request.query, undefined, 2)); log.debug('getObjectSchemas(): getParams(): ' + JSON.stringify(params, undefined, 2)); } return params; }; var toSearchOptions = function(params) { var findAllOptions = { pageSize: params.limit, from: params.offset, returnFields: (params.dataFields ? params.dataFields.split(',') : undefined), timeout: params.timeout, version: params.version }; if (params.sort) { var tokens; findAllOptions.multiFieldSort = params.sort.split(',').map(function(sortField) { tokens = sortField.split('|'); return { field: tokens[0], descending: (tokens.length > 1 ? tokens[1] === 'desc' : false) }; }); } if (log.isDebugEnabled()) { log.debug('getObjectSchemas(): toSearchOptions(): ' + JSON.stringify(findAllOptions, undefined, 2)); } return findAllOptions; }; var responseMessage = { meta: new ResponseMetaData(_path, request) }; var params = getParams(); var findAllOptions = toSearchOptions(params); when(objectSchemaDatabase.database.findAll(findAllOptions), function(results) { responseMessage.meta.searchResult = { limit: params.limit, offset: params.offset, total: results.hits.total, count: results.hits.hits.length }; if (params.raw) { responseMessage.data = results; } else { if (params.version) { if (params.dataFields) { responseMessage.data = { hits: lodash.map(results.hits.hits, function(hit) { return { version: hit._version, data: hit.fields }; }) }; } else { responseMessage.data = { hits: lodash.map(results.hits.hits, function(hit) { return { version: hit._version, data: hit._source }; }) }; } } else { if (params.dataFields) { responseMessage.data = { hits: lodash.pluck(results.hits.hits, 'fields') }; } else { responseMessage.data = { hits: lodash.pluck(results.hits.hits, '_source') }; } } } var addActions = function() { if (params.actions) { responseMessage.actions = [{ name: 'create', title: 'Create Object Schema', method: 'POST', auth: ['hawk'], href: path() }, { name: 'count', title: 'Total Number of Object Schemas', method: 'GET', auth: ['hawk'], href: path('/count') }]; } }; var addLinks = function() { if (params.links) { var linkQueryString = '?' + querystring.stringify(request.query); responseMessage.links = [{ rel: 'self', href: path() + linkQueryString, title: 'Get Object Schemas', auth: ['hawk'] }]; if (responseMessage.meta.searchResult.total > 0) { linkQueryString = lodash.clone(request.query); linkQueryString.offset = 0; linkQueryString = '?' + querystring.stringify(linkQueryString); responseMessage.links.push({ rel: 'firstPage', href: path() + linkQueryString, title: 'Get Object Schemas - First Page', auth: ['hawk'] }); if (responseMessage.meta.searchResult.total > params.limit) { linkQueryString = lodash.clone(request.query); linkQueryString.offset = responseMessage.meta.searchResult.total - params.limit; if (linkQueryString.offset < (params.offset + params.limit)) { linkQueryString.offset = (params.offset + params.limit); } linkQueryString = '?' + querystring.stringify(linkQueryString); responseMessage.links.push({ rel: 'lastPage', href: path() + linkQueryString, title: 'Get Object Schemas - Last Page', auth: ['hawk'] }); } if (responseMessage.meta.searchResult.count < responseMessage.meta.searchResult.total) { linkQueryString = lodash.clone(request.query); linkQueryString.offset = (params.offset + params.limit); if (linkQueryString.offset < responseMessage.meta.searchResult.total) { linkQueryString = '?' + querystring.stringify(linkQueryString); responseMessage.links.push({ rel: 'nextPage', href: path() + linkQueryString, title: 'Get Object Schemas - Next Page', auth: ['hawk'] }); } } if (responseMessage.meta.searchResult.offset > 0) { linkQueryString = lodash.clone(request.query); linkQueryString.offset = params.offset - params.limit; if (linkQueryString.offset > 0) { linkQueryString = '?' + querystring.stringify(linkQueryString); responseMessage.links.push({ rel: 'prevPage', href: path() + linkQueryString, title: 'Get Object Schemas - Previous Page', auth: ['hawk'] }); } } } } }; addActions(); addLinks(); request.reply(responseMessage); responseMessage.meta.stopTimer(); }, handleError.bind(request, responseMessage)); }; var createObjectSchema = function createObjectSchema(_path, request) { var responseMessage = { meta: new ResponseMetaData(_path, request) }; var defaultParams = { dataOnly: false, actions: true, links: true, raw: false }; var getParams = function() { var params = { dataOnly: request.query.dataOnly, actions: request.query.actions, links: request.query.links, raw: request.query.raw }; params = extend(defaultParams, params); if (log.isDebugEnabled()) { log.debug('createObjectSchema(): request.query: ' + JSON.stringify(request.query, undefined, 2)); log.debug('createObjectSchema(): getParams(): ' + JSON.stringify(params, undefined, 2)); } return params; }; var params = getParams(); var addActions = function(responseMessage, objectSchema) { if (params.actions) { responseMessage.actions = [{ name: 'delete', title: 'Delete Object Schema', method: 'DELETE', auth: ['hawk'], href: path() + '/' + objectSchema.id }, { name: 'replace', title: 'Replace Object Schema', method: 'PUT', auth: ['hawk'], href: path() + '/' + objectSchema.id }]; } }; var addLinks = function(responseMessage, objectSchema) { if (params.links) { responseMessage.links = [{ rel: 'self', href: path() + '/' + objectSchema.id, title: 'Get Object Schema', auth: ['hawk'] }]; } }; var objectSchema; try { objectSchema = new ObjectSchema(request.payload); when(objectSchemaDatabase.findByNamespaceVersion(objectSchema.namespace, objectSchema.version), function(result) { if (result.hits.total > 0) { responseMessage.error = { code: 409, developerMessage: 'An ObjectSchema with the same namespace and version already exists. Namespace and version must be unique.', userMessage: { dup_err: 'An Object Schema with the same namespace and version already exists.' } }; request.reply(responseMessage).code(responseMessage.error.code); responseMessage.meta.stopTimer(); return; } when(objectSchemaDatabase.createObjectSchema(objectSchema), function(result) { if (params.raw) { responseMessage.data = result; } else { responseMessage.data = { id: objectSchema.id }; } addActions(responseMessage, objectSchema); addLinks(responseMessage, objectSchema); request.reply(responseMessage).code(201); responseMessage.meta.stopTimer(); }, handleError.bind(request, responseMessage)); }, handleError.bind(request, responseMessage)); } catch (err) { responseMessage.error = { code: 400, developerMessage: err.message, userMessage: { bad_data: 'Invalid Object Schema.' } }; request.reply(responseMessage).code(responseMessage.error.code); responseMessage.meta.stopTimer(); } }; var replaceObjectSchema = function createObjectSchema(_path, request) { var responseMessage = { meta: new ResponseMetaData(_path, request) }; var defaultParams = { dataOnly: false, actions: true, links: true, raw: false }; var getParams = function() { var params = { dataOnly: request.query.dataOnly, actions: request.query.actions, links: request.query.links, raw: request.query.raw }; params = extend(defaultParams, params); if (log.isDebugEnabled()) { log.debug('replaceObjectSchema(): request.query: ' + JSON.stringify(request.query, undefined, 2)); log.debug('replaceObjectSchema(): getParams(): ' + JSON.stringify(params, undefined, 2)); } return params; }; var params = getParams(); var addActions = function(responseMessage, objectSchema) { if (params.actions) { responseMessage.actions = [{ name: 'delete', title: 'Delete Object Schema', method: 'DELETE', auth: ['hawk'], href: path() + '/' + objectSchema.id }, { name: 'replace', title: 'Replace Object Schema', method: 'PUT', auth: ['hawk'], href: path() + '/' + objectSchema.id }]; } }; var addLinks = function(responseMessage, objectSchema) { if (params.links) { responseMessage.links = [{ rel: 'self', href: path() + '/' + objectSchema.id, title: 'Get Object Schema', auth: ['hawk'] }]; } }; var objectSchema; try { objectSchema = new ObjectSchema(request.payload); if (log.isDebugEnabled()) { log.debug('replaceObjectSchema() : objectSchema : ' + JSON.stringify(objectSchema, undefined, 2)); } if (objectSchema.id !== request.params.id) { var idNotMatchingErr = new Error('ObjectSchema.id in the payload does not match the id specified in the URL : ' + objectSchema.id + ' !== ' + request.params.id); idNotMatchingErr.code = 400; throw idNotMatchingErr; } when(objectSchemaDatabase.getObjectSchema(objectSchema.id), function() { when(objectSchemaDatabase.setObjectSchema(objectSchema, request.params.version), function(result) { if (params.raw) { responseMessage.data = result; } else { responseMessage.data = { id: result._id, version: result._version }; } addActions(responseMessage, objectSchema); addLinks(responseMessage, objectSchema); request.reply(responseMessage).code(200); responseMessage.meta.stopTimer(); }, handleError.bind(request, responseMessage)); }, handleError.bind(request, responseMessage)); } catch (err) { responseMessage.error = { code: 400, developerMessage: err.message, userMessage: { bad_data: 'Invalid Object Schema.' } }; request.reply(responseMessage).code(responseMessage.error.code); responseMessage.meta.stopTimer(); } }; var getObjectSchema = function createObjectSchema(_path, request) { var responseMessage = { meta: new ResponseMetaData(_path, request) }; var defaultParams = { dataOnly: false, links: true, actions: true, version: false, raw: false }; var getParams = function() { var params = { timeout: request.query.timeout, version: request.query.version, dataOnly: request.query.dataOnly, actions: request.query.actions, links: request.query.links, raw: request.query.raw }; params = extend(defaultParams, params); if (log.isDebugEnabled()) { log.debug('getObjectSchema(): request.query: ' + JSON.stringify(request.query, undefined, 2)); log.debug('getObjectSchema(): getParams(): ' + JSON.stringify(params, undefined, 2)); } return params; }; var params = getParams(); var addActions = function(responseMessage) { if (params.actions) { responseMessage.actions = [{ name: 'delete', title: 'Delete Object Schema', method: 'DELETE', auth: ['hawk'], href: path() + '/' + request.params.id }, { name: 'replace', title: 'Replace Object Schema', method: 'PUT', auth: ['hawk'], href: path() + '/' + request.params.id }]; } }; var addLinks = function(responseMessage) { if (params.links) { responseMessage.links = [{ rel: 'self', href: path() + '/' + request.params.id, title: 'Get Object Schema', auth: ['hawk'] }]; } }; try { when(objectSchemaDatabase.getObjectSchema(request.params.id), function(result) { if (params.raw) { responseMessage.data = result; } else { if (params.version) { responseMessage.data = { version: result._version, data: result._source }; } else { responseMessage.data = result._source; } } addActions(responseMessage); addLinks(responseMessage); request.reply(responseMessage).code(200); responseMessage.meta.stopTimer(); }, handleError.bind(request, responseMessage) ); } catch (err) { responseMessage.error = { code: 400, developerMessage: err.message, userMessage: { bad_data: 'Invalid Object Schema.' } }; request.reply(responseMessage).code(responseMessage.error.code); responseMessage.meta.stopTimer(); } }; var deleteObjectSchema = function createObjectSchema(_path, request) { var responseMessage = { meta: new ResponseMetaData(_path, request) }; var defaultParams = { raw: false }; var getParams = function() { var params = { timeout: request.query.timeout, raw: request.query.raw }; params = extend(defaultParams, params); if (log.isDebugEnabled()) { log.debug('getObjectSchema(): request.query: ' + JSON.stringify(request.query, undefined, 2)); log.debug('getObjectSchema(): getParams(): ' + JSON.stringify(params, undefined, 2)); } return params; }; var params = getParams(); try { when(objectSchemaDatabase.database.deleteEntity(request.params.id, true), function(result) { if (params.raw) { responseMessage.data = result; } else { responseMessage.data = { found: result.found, id: result._id, version: result._version }; } if (result.found) { request.reply(responseMessage).code(200); } else { request.reply(responseMessage).code(404); } responseMessage.meta.stopTimer(); }, handleError.bind(request, responseMessage) ); } catch (err) { responseMessage.error = { code: 400, developerMessage: err.message, userMessage: { bad_data: 'Invalid Object Schema.' } }; request.reply(responseMessage).code(responseMessage.error.code); responseMessage.meta.stopTimer(); } }; return [{ method: 'GET', path: path(), config: { description: 'Used to page through ObjectSchemas. By default, the first 10 are returned sorted by updatedOn in descending order.', tags: ['objectschemas', 'paging'], validate: { query: { limit: types.Number(), offset: types.Number(), sort: types.String(), dataFields: types.String(), dataOnly: types.Boolean(), actions: types.Boolean(), links: types.Boolean(), timeout: types.Number(), version: types.Boolean(), raw: types.Boolean() } }, handler: getObjectSchemas.bind(null, path()) } }, { method: 'POST', path: path(), config: { description: 'Used to create a new ObjectSchema.', tags: ['objectschemas', 'create'], validate: { query: { raw: types.Boolean() } }, handler: createObjectSchema.bind(null, path()) } }, { method: 'PUT', path: path() + '/{id}/{version}', config: { description: 'Used to perform full replace of an existing ObjectSchema.', tags: ['objectschemas', 'replace'], validate: { query: { raw: types.Boolean() }, path: { id: types.String(), version: types.Number().min(1) } }, handler: replaceObjectSchema.bind(null, path()) } }, { method: 'GET', path: path() + '/{id}', config: { description: 'Retrieves an ObjectSchema', tags: ['objectschemas', 'get'], validate: { query: { dataOnly: types.Boolean(), actions: types.Boolean(), links: types.Boolean(), timeout: types.Number(), version: types.Boolean(), raw: types.Boolean() }, path: { id: types.String() } }, handler: getObjectSchema.bind(null, path()) } }, { method: 'DELETE', path: path() + '/{id}', config: { description: 'Deletes an ObjectSchema', tags: ['objectschemas', 'delete'], validate: { query: { actions: types.Boolean(), links: types.Boolean(), timeout: types.Number(), raw: types.Boolean() }, path: { id: types.String() } }, handler: deleteObjectSchema.bind(null, path()) } }]; };
runrightfast-archived/runrightfast-object-schema-registry-hapi-plugin
lib/object-schema-routes.js
JavaScript
apache-2.0
19,523