gt
stringclasses
1 value
context
stringlengths
2.05k
161k
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.storage.common.implementation; import com.azure.core.util.UrlBuilder; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.storage.common.Utility; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.util.Base64; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import static com.azure.storage.common.Utility.urlDecode; /** * Utility class which is used internally. */ public class StorageImplUtils { private static final ClientLogger LOGGER = new ClientLogger(StorageImplUtils.class); private static final String ARGUMENT_NULL_OR_EMPTY = "The argument must not be null or an empty string. Argument name: %s."; private static final String PARAMETER_NOT_IN_RANGE = "The value of the parameter '%s' should be between %s and %s."; private static final String NO_PATH_SEGMENTS = "URL %s does not contain path segments."; /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> Map<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (CoreUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws NullPointerException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new NullPointerException(String.format(Locale.ROOT, ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT, PARAMETER_NOT_IN_RANGE, param, min, max))); } } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToUrlPath(String baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toUrl(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the last path segment from the passed URL. * * @param baseUrl URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseUrl) { UrlBuilder builder = UrlBuilder.parse(baseUrl); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, NO_PATH_SEGMENTS, baseUrl)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toUrl(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the account name from host part of the URL object. * * @param url URL having its hostanme * @return account name. */ public static String getAccountName(URL url) { UrlBuilder builder = UrlBuilder.parse(url); String accountName = null; String host = builder.getHost(); //Parse host to get account name // host will look like this : <accountname>.blob.core.windows.net if (!CoreUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { // host only contains account name accountName = host; } else { // if host is separated by . accountName = host.substring(0, accountNameIndex); } } return accountName; } /** Returns an empty string if value is {@code null}, otherwise returns value * @param value The value to check and return. * @return The value or empty string. */ public static String emptyIfNull(String value) { return value == null ? "" : value; } /** * Reads data from an input stream and writes it to an output stream. * @param source {@link InputStream source} * @param writeLength The length of data to write. * @param destination {@link OutputStream destination} * @throws IOException If an I/O error occurs. */ public static void copyToOutputStream(InputStream source, long writeLength, OutputStream destination) throws IOException { StorageImplUtils.assertNotNull("source", source); StorageImplUtils.assertNotNull("destination", destination); final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; int nextCopy = (int) Math.min(retrievedBuff.length, writeLength); int count = source.read(retrievedBuff, 0, nextCopy); while (nextCopy > 0 && count != -1) { destination.write(retrievedBuff, 0, count); nextCopy = (int) Math.min(retrievedBuff.length, writeLength); count = source.read(retrievedBuff, 0, nextCopy); } } }
/* * The MIT License (MIT) * * Copyright (c) 2014 Marcel Mika, marcelmika.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.marcelmika.lims.persistence.manager; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.marcelmika.lims.api.environment.Environment; import com.marcelmika.lims.api.environment.Environment.BuddyListSocialRelation; import com.marcelmika.lims.api.environment.Environment.BuddyListStrategy; import com.marcelmika.lims.persistence.domain.Buddy; import com.marcelmika.lims.persistence.generated.service.SettingsLocalServiceUtil; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * @author Ing. Marcel Mika * @link http://marcelmika.com * Date: 23/09/14 * Time: 10:03 */ public class SearchManagerImpl implements SearchManager { // Log @SuppressWarnings("unused") private static Log log = LogFactoryUtil.getLog(SearchManagerImpl.class); /** * Returns a list of buddies based on the search query. The search will be performed * in first name, middle name, last name, screen name and email. * * @param userId Long * @param searchQuery String * @param start of the list * @param end of the list * @return List of buddies * @throws Exception */ @Override public List<Buddy> searchBuddies(Long userId, String searchQuery, int start, int end) throws Exception { // Get selected list strategy Environment.BuddyListStrategy strategy = Environment.getBuddyListStrategy(); // Get the info if the deactivated user should be ignored boolean ignoreDeactivatedUser = Environment.getBuddyListIgnoreDeactivatedUser(); // Some sites or groups may be excluded String[] excludedSites = Environment.getBuddyListSiteExcludes(); String[] excludedGroups = Environment.getBuddyListGroupExcludes(); // Relation types Environment.BuddyListSocialRelation[] relationTypes = Environment.getBuddyListSocialRelations(); // All buddies if (strategy == BuddyListStrategy.ALL) { return searchAllBuddies( userId, searchQuery, true, ignoreDeactivatedUser, start, end ); } // Buddies from sites else if (strategy == BuddyListStrategy.SITES) { return searchSitesBuddies( userId, searchQuery, true, ignoreDeactivatedUser, excludedSites, start, end ); } // Buddies by social relations else if (strategy == BuddyListStrategy.SOCIAL) { return searchSocialBuddies( userId, searchQuery, true, ignoreDeactivatedUser, relationTypes, start, end ); } // Buddies by social relations together with sites else if (strategy == BuddyListStrategy.SITES_AND_SOCIAL) { return searchSitesAndSocialBuddies( userId, searchQuery, true, ignoreDeactivatedUser, excludedSites, relationTypes, start, end ); } // Buddies by user groups else if (strategy == BuddyListStrategy.USER_GROUPS) { return searchUserGroupsBuddies( userId, searchQuery, true, ignoreDeactivatedUser, excludedGroups, start, end ); } // Unknown else { throw new Exception("Unknown buddy list strategy"); } } /** * Returns a list of buddies related to the user based on the search query * * @param userId Long * @param searchQuery String * @param ignoreDefaultUser boolean set to true if the default user should be excluded * @param ignoreDeactivatedUser boolean set to true if the deactivated user should be excluded * @param start of the list * @param end of the list * @return List of buddies * @throws Exception */ private List<Buddy> searchAllBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, int start, int end) throws Exception { // Get from persistence List<Object[]> users = SettingsLocalServiceUtil.searchAllBuddies( userId, searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, start, end ); // Return deserialized result return deserializeBuddyListFromUserObjects(users); } /** * Returns a list of buddies. The list is made of all buddies based on the search query in the sites * where the user participates * * @param userId which should be excluded from the list * @param searchQuery search query string * @param ignoreDefaultUser boolean set to true if the default user should be excluded * @param ignoreDeactivatedUser boolean set to true if the deactivated user should be excluded * @param excludedSites names of sites (groups) that should be excluded from the group collection * @param start of the list * @param end of the list * @return List of buddies * @throws Exception */ private List<Buddy> searchSitesBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedSites, int start, int end) throws Exception { // Get from persistence List<Object[]> users = SettingsLocalServiceUtil.searchSitesBuddies( userId, searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, excludedSites, start, end ); // Return deserialized result return deserializeBuddyListFromUserObjects(users); } /** * Returns a list of buddies. This list is made of all buddies based on the search query with whom the user * has a social relationships given in the parameter. * * @param userId which should be excluded from the list * @param searchQuery search query string * @param ignoreDefaultUser boolean set to true if the default user should be excluded * @param ignoreDeactivatedUser boolean set to true if the deactivated user should be excluded * @param relationTypes an array of relation types enums * @param start of the list * @param end of the list * @return List of buddies * @throws Exception */ private List<Buddy> searchSocialBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, BuddyListSocialRelation[] relationTypes, int start, int end) throws Exception { // Get int codes from relation types since the persistence consumes an int array only. int[] relationCodes = new int[relationTypes.length]; for (int i = 0; i < relationTypes.length; i++) { relationCodes[i] = relationTypes[i].getCode(); } // Get from persistence List<Object[]> users = SettingsLocalServiceUtil.searchSocialBuddies( userId, searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, relationCodes, start, end ); // Return deserialized result return deserializeBuddyListFromUserObjects(users); } /** * Returns a list of buddies. This list is made of all buddies based on the search query that are * in the same site and have a social relation given in parameter * * @param userId which should be excluded from the list * @param searchQuery search query string * @param ignoreDefaultUser boolean set to true if the default user should be excluded * @param ignoreDeactivatedUser boolean set to true if the deactivated user should be excluded * @param excludedSites names of sites (groups) that should be excluded from the group collection * @param relationTypes an array of relation types enums * @param start of the list * @param end of the list * @return a list of buddies * @throws Exception */ private List<Buddy> searchSitesAndSocialBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedSites, BuddyListSocialRelation[] relationTypes, int start, int end) throws Exception { // Get site buddies List<Buddy> siteBuddies = searchSitesBuddies( userId, searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, excludedSites, start, end ); // Get social buddies List<Buddy> socialBuddies = searchSocialBuddies( userId, searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, relationTypes, start, end ); // Add it to set since we want to get rid of duplicates Set<Buddy> mergedBuddies = new HashSet<Buddy>(); mergedBuddies.addAll(siteBuddies); mergedBuddies.addAll(socialBuddies); return new LinkedList<Buddy>(mergedBuddies); } /** * Returns a list of buddies. This list is made of all buddies based on the search query that are * in the same user group as the user. * * @param userId which should be excluded from the list * @param searchQuery search query string * @param ignoreDefaultUser boolean set to true if the default user should be excluded * @param ignoreDeactivatedUser boolean set to true if the deactivated user should be excluded * @param excludedGroups names of groups that should be excluded from the list of buddies * @param start of the list * @param end of the list * @return a list of buddies * @throws Exception */ private List<Buddy> searchUserGroupsBuddies(Long userId, String searchQuery, boolean ignoreDefaultUser, boolean ignoreDeactivatedUser, String[] excludedGroups, int start, int end) throws Exception { // Get user groups List<Object[]> users = SettingsLocalServiceUtil.searchUserGroupsBuddies( userId, searchQuery, ignoreDefaultUser, ignoreDeactivatedUser, excludedGroups, start, end ); // Return deserialized result return deserializeBuddyListFromUserObjects(users); } /** * Deserialize user objects to the list of buddies * * @param userObjects a list of user data stored in an object array * @return List of buddies */ private List<Buddy> deserializeBuddyListFromUserObjects(List<Object[]> userObjects) { // Deserialize user info in plain objects to buddy List<Buddy> buddies = new LinkedList<Buddy>(); for (Object[] userObject : userObjects) { // Deserialize Buddy buddy = Buddy.fromPlainObject(userObject, 0); // Add to list buddies.add(buddy); } return buddies; } }
package com.acmeair.config; import java.util.ArrayList; import java.util.Map; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import com.acmeair.service.AuthService; import com.acmeair.service.BookingService; import com.acmeair.service.CustomerService; import com.acmeair.service.FlightService; import com.acmeair.service.ServiceLocator; @Path("/config") public class AcmeAirConfiguration { @Inject BeanManager beanManager; Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName()); private BookingService bs = ServiceLocator.instance().getService(BookingService.class); private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class); private AuthService authService = ServiceLocator.instance().getService(AuthService.class); private FlightService flightService = ServiceLocator.instance().getService(FlightService.class); public AcmeAirConfiguration() { super(); } @PostConstruct private void initialization() { if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/BeanManager"); } } if(beanManager == null){ logger.info("Attempting to look up BeanManager through JNDI at java:comp/env/BeanManager"); try { beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager"); } catch (NamingException e) { logger.severe("BeanManager not found at java:comp/env/BeanManager "); } } } @GET @Path("/dataServices") @Produces("application/json") public ArrayList<ServiceData> getDataServiceInfo() { try { ArrayList<ServiceData> list = new ArrayList<ServiceData>(); Map<String, String> services = ServiceLocator.instance().getServices(); logger.fine("Get data service configuration info"); for (Map.Entry<String, String> entry : services.entrySet()){ ServiceData data = new ServiceData(); data.name = entry.getKey(); data.description = entry.getValue(); list.add(data); } return list; } catch (Exception e) { e.printStackTrace(); return null; } } @GET @Path("/activeDataService") @Produces("application/json") public Response getActiveDataServiceInfo() { try { logger.fine("Get active Data Service info"); return Response.ok(ServiceLocator.instance().getServiceType()).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok("Unknown").build(); } } @GET @Path("/runtime") @Produces("application/json") public ArrayList<ServiceData> getRuntimeInfo() { try { logger.fine("Getting Runtime info"); ArrayList<ServiceData> list = new ArrayList<ServiceData>(); ServiceData data = new ServiceData(); data.name = "Runtime"; data.description = "Java"; list.add(data); data = new ServiceData(); data.name = "Version"; data.description = System.getProperty("java.version"); list.add(data); data = new ServiceData(); data.name = "Vendor"; data.description = System.getProperty("java.vendor"); list.add(data); return list; } catch (Exception e) { e.printStackTrace(); return null; } } class ServiceData { public String name = ""; public String description = ""; } @GET @Path("/countBookings") @Produces("application/json") public Response countBookings() { try { Long count = bs.count(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countCustomers") @Produces("application/json") public Response countCustomer() { try { Long customerCount = customerService.count(); return Response.ok(customerCount).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countSessions") @Produces("application/json") public Response countCustomerSessions() { try { Long customerCount = authService.countSessions(); return Response.ok(customerCount).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countFlights") @Produces("application/json") public Response countFlights() { try { Long count = flightService.countFlights(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countFlightSegments") @Produces("application/json") public Response countFlightSegments() { try { Long count = flightService.countFlightSegments(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } @GET @Path("/countAirports") @Produces("application/json") public Response countAirports() { try { Long count = flightService.countAirports(); return Response.ok(count).build(); } catch (Exception e) { e.printStackTrace(); return Response.ok(-1).build(); } } }
package liquibase.change; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.parser.core.ParsedNode; import liquibase.parser.core.ParsedNodeException; import liquibase.resource.ResourceAccessor; import liquibase.serializer.AbstractLiquibaseSerializable; import liquibase.util.StringUtils; /** * The standard configuration used by Change classes to represent a constraints on a column. */ public class ConstraintsConfig extends AbstractLiquibaseSerializable { private Boolean nullable; private String notNullConstraintName; private Boolean primaryKey; private String primaryKeyName; private String primaryKeyTablespace; private String references; private String referencedTableCatalogName; private String referencedTableSchemaName; private String referencedTableName; private String referencedColumnNames; private Boolean unique; private String uniqueConstraintName; private String checkConstraint; private Boolean deleteCascade; private String foreignKeyName; private Boolean initiallyDeferred; private Boolean deferrable; /** * Returns if the column should be nullable. Returns null if unspecified. */ public Boolean isNullable() { return nullable; } public ConstraintsConfig setNullable(Boolean nullable) { this.nullable = nullable; return this; } /** * Set the nullable parameter based on the passed string. * Sets true if the passed string is 1 or true or TRUE. * Sets false if the passed string is 0 or false or FALSE. * Sets null if the passed string is null or "null" or "NULL". * Throws an {@link UnexpectedLiquibaseException} if a different value is passed */ public ConstraintsConfig setNullable(String nullable) { this.nullable = parseBoolean(nullable); return this; } /** * Returns the name to use for the NOT NULL constraint. Returns null if not specified */ public String getNotNullConstraintName() { return notNullConstraintName; } public ConstraintsConfig setNotNullConstraintName(String notNullConstraintName) { this.notNullConstraintName = notNullConstraintName; return this; } /** * Returns true if the column should be part of the primary key. Returns null if unspecified */ public Boolean isPrimaryKey() { return primaryKey; } public ConstraintsConfig setPrimaryKey(Boolean primaryKey) { this.primaryKey = primaryKey; return this; } /** * Set the primaryKey parameter based on the passed string. * Sets true if the passed string is 1 or true or TRUE. * Sets false if the passed string is 0 or false or FALSE. * Sets null if the passed string is null or "null" or "NULL". * Throws an {@link UnexpectedLiquibaseException} if a different value is passed */ public ConstraintsConfig setPrimaryKey(String primaryKey) { this.primaryKey = parseBoolean(primaryKey); return this; } /** * Returns the name to use for the primary key constraint. Returns null if not specified */ public String getPrimaryKeyName() { return primaryKeyName; } public ConstraintsConfig setPrimaryKeyName(String primaryKeyName) { this.primaryKeyName = primaryKeyName; return this; } /** * Returns the "references" clause to use for the foreign key. Normally a string of the format TABLE(COLUMN_NAME). * Returns null if not specified */ public String getReferences() { return references; } public ConstraintsConfig setReferences(String references) { this.references = references; return this; } /** * Returns if the column is part of a unique constraint. Returns null if not specified */ public Boolean isUnique() { return unique; } public ConstraintsConfig setUnique(Boolean unique) { this.unique = unique; return this; } /** * Set the unique parameter based on the passed string. * Sets true if the passed string is 1 or true or TRUE. * Sets false if the passed string is 0 or false or FALSE. * Sets null if the passed string is null or "null" or "NULL". * Throws an {@link UnexpectedLiquibaseException} if a different value is passed */ public ConstraintsConfig setUnique(String unique) { this.unique = parseBoolean(unique); return this; } /** * Returns the name to use for the unique constraint. Returns null if not specified */ public String getUniqueConstraintName() { return uniqueConstraintName; } public ConstraintsConfig setUniqueConstraintName(String uniqueConstraintName) { this.uniqueConstraintName = uniqueConstraintName; return this; } /** * Returns the check constraint to use on this column. Returns null if not specified */ public String getCheckConstraint() { return checkConstraint; } public ConstraintsConfig setCheckConstraint(String checkConstraint) { this.checkConstraint = checkConstraint; return this; } /** * Returns if a foreign key defined for this column should cascade deletes. Returns null if not specified. */ public Boolean isDeleteCascade() { return deleteCascade; } public ConstraintsConfig setDeleteCascade(Boolean deleteCascade) { this.deleteCascade = deleteCascade; return this; } /** * Set the deleteCascade parameter based on the passed string. * Sets true if the passed string is 1 or true or TRUE. * Sets false if the passed string is 0 or false or FALSE. * Sets null if the passed string is null or "null" or "NULL". * Throws an {@link UnexpectedLiquibaseException} if a different value is passed */ public ConstraintsConfig setDeleteCascade(String deleteCascade) { this.deleteCascade = parseBoolean(deleteCascade); return this; } /** * Returns the name to use for the columns foreign key constraint. Returns null if not specified. */ public String getForeignKeyName() { return foreignKeyName; } public ConstraintsConfig setForeignKeyName(String foreignKeyName) { this.foreignKeyName = foreignKeyName; return this; } /** * Returns if a foreign key defined for this column should be "initially deferred"c. Returns null if not specified. */ public Boolean isInitiallyDeferred() { return initiallyDeferred; } public ConstraintsConfig setInitiallyDeferred(Boolean initiallyDeferred) { this.initiallyDeferred = initiallyDeferred; return this; } /** * Set the initiallyDeferred parameter based on the passed string. * Sets true if the passed string is 1 or true or TRUE. * Sets false if the passed string is 0 or false or FALSE. * Sets null if the passed string is null or "null" or "NULL". * Throws an {@link UnexpectedLiquibaseException} if a different value is passed */ public ConstraintsConfig setInitiallyDeferred(String initiallyDeferred) { this.initiallyDeferred = parseBoolean(initiallyDeferred); return this; } /** * Returns if a foreign key defined for this column should deferrable. Returns null if not specified. */ public Boolean isDeferrable() { return deferrable; } public ConstraintsConfig setDeferrable(Boolean deferrable) { this.deferrable = deferrable; return this; } /** * Set the deferrable parameter based on the passed string. * Sets true if the passed string is 1 or true or TRUE. * Sets false if the passed string is 0 or false or FALSE. * Sets null if the passed string is null or "null" or "NULL". * Throws an {@link UnexpectedLiquibaseException} if a different value is passed */ public ConstraintsConfig setDeferrable(String deferrable) { this.deferrable = parseBoolean(deferrable); return this; } /** * Returns the tablespace to use for the defined primary key. Returns null if not specified. */ public String getPrimaryKeyTablespace() { return primaryKeyTablespace; } public ConstraintsConfig setPrimaryKeyTablespace(String primaryKeyTablespace) { this.primaryKeyTablespace = primaryKeyTablespace; return this; } public String getReferencedTableCatalogName() { return referencedTableCatalogName; } public void setReferencedTableCatalogName(String referencedTableCatalogName) { this.referencedTableCatalogName = referencedTableCatalogName; } public String getReferencedTableSchemaName() { return referencedTableSchemaName; } public void setReferencedTableSchemaName(String referencedTableSchemaName) { this.referencedTableSchemaName = referencedTableSchemaName; } public String getReferencedTableName() { return referencedTableName; } public void setReferencedTableName(String referencedTableName) { this.referencedTableName = referencedTableName; } public String getReferencedColumnNames() { return referencedColumnNames; } public void setReferencedColumnNames(String referencedColumnNames) { this.referencedColumnNames = referencedColumnNames; } private Boolean parseBoolean(String value) { value = StringUtils.trimToNull(value); if ((value == null) || "null".equalsIgnoreCase(value)) { return null; } else { if ("true".equalsIgnoreCase(value) || "1".equals(value)) { return true; } else if ("false".equalsIgnoreCase(value) || "0".equals(value)) { return false; } else { throw new UnexpectedLiquibaseException("Unparsable boolean value: "+value); } } } @Override public String getSerializedObjectName() { return "constraints"; } @Override public String getSerializedObjectNamespace() { return STANDARD_CHANGELOG_NAMESPACE; } @Override public void load(ParsedNode parsedNode, ResourceAccessor resourceAccessor) throws ParsedNodeException { throw new RuntimeException("TODO"); } }
package org.apache.maven.repository.internal; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.maven.model.DistributionManagement; import org.apache.maven.model.Model; import org.apache.maven.model.Relocation; import org.apache.maven.model.building.DefaultModelBuilderFactory; import org.apache.maven.model.building.DefaultModelBuildingRequest; import org.apache.maven.model.building.FileModelSource; import org.apache.maven.model.building.ModelBuilder; import org.apache.maven.model.building.ModelBuildingException; import org.apache.maven.model.building.ModelBuildingRequest; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.model.resolution.UnresolvableModelException; import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.RepositoryEvent.EventType; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.RequestTrace; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.impl.ArtifactDescriptorReader; import org.eclipse.aether.impl.ArtifactResolver; import org.eclipse.aether.impl.RemoteRepositoryManager; import org.eclipse.aether.impl.RepositoryEventDispatcher; import org.eclipse.aether.impl.VersionRangeResolver; import org.eclipse.aether.impl.VersionResolver; import org.eclipse.aether.repository.WorkspaceReader; import org.eclipse.aether.repository.WorkspaceRepository; import org.eclipse.aether.resolution.ArtifactDescriptorException; import org.eclipse.aether.resolution.ArtifactDescriptorPolicy; import org.eclipse.aether.resolution.ArtifactDescriptorPolicyRequest; import org.eclipse.aether.resolution.ArtifactDescriptorRequest; import org.eclipse.aether.resolution.ArtifactDescriptorResult; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.VersionRequest; import org.eclipse.aether.resolution.VersionResolutionException; import org.eclipse.aether.resolution.VersionResult; import org.eclipse.aether.spi.locator.Service; import org.eclipse.aether.spi.locator.ServiceLocator; import org.eclipse.aether.transfer.ArtifactNotFoundException; /** * @author Benjamin Bentmann */ @Named @Singleton public class DefaultArtifactDescriptorReader implements ArtifactDescriptorReader, Service { private RemoteRepositoryManager remoteRepositoryManager; private VersionResolver versionResolver; private VersionRangeResolver versionRangeResolver; private ArtifactResolver artifactResolver; private RepositoryEventDispatcher repositoryEventDispatcher; private ModelBuilder modelBuilder; public DefaultArtifactDescriptorReader() { // enable no-arg constructor } @Inject DefaultArtifactDescriptorReader( RemoteRepositoryManager remoteRepositoryManager, VersionResolver versionResolver, VersionRangeResolver versionRangeResolver, ArtifactResolver artifactResolver, ModelBuilder modelBuilder, RepositoryEventDispatcher repositoryEventDispatcher ) { setRemoteRepositoryManager( remoteRepositoryManager ); setVersionResolver( versionResolver ); setVersionRangeResolver( versionRangeResolver ); setArtifactResolver( artifactResolver ); setModelBuilder( modelBuilder ); setRepositoryEventDispatcher( repositoryEventDispatcher ); } public void initService( ServiceLocator locator ) { setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) ); setVersionResolver( locator.getService( VersionResolver.class ) ); setVersionRangeResolver( locator.getService( VersionRangeResolver.class ) ); setArtifactResolver( locator.getService( ArtifactResolver.class ) ); modelBuilder = locator.getService( ModelBuilder.class ); if ( modelBuilder == null ) { setModelBuilder( new DefaultModelBuilderFactory().newInstance() ); } setRepositoryEventDispatcher( locator.getService( RepositoryEventDispatcher.class ) ); } public DefaultArtifactDescriptorReader setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager ) { this.remoteRepositoryManager = Objects.requireNonNull( remoteRepositoryManager, "remoteRepositoryManager cannot be null" ); return this; } public DefaultArtifactDescriptorReader setVersionResolver( VersionResolver versionResolver ) { this.versionResolver = Objects.requireNonNull( versionResolver, "versionResolver cannot be null" ); return this; } /** @since 3.2.2 */ public DefaultArtifactDescriptorReader setVersionRangeResolver( VersionRangeResolver versionRangeResolver ) { this.versionRangeResolver = Objects.requireNonNull( versionRangeResolver, "versionRangeResolver cannot be null" ); return this; } public DefaultArtifactDescriptorReader setArtifactResolver( ArtifactResolver artifactResolver ) { this.artifactResolver = Objects.requireNonNull( artifactResolver, "artifactResolver cannot be null" ); return this; } public DefaultArtifactDescriptorReader setRepositoryEventDispatcher( RepositoryEventDispatcher repositoryEventDispatcher ) { this.repositoryEventDispatcher = Objects.requireNonNull( repositoryEventDispatcher, "repositoryEventDispatcher cannot be null" ); return this; } public DefaultArtifactDescriptorReader setModelBuilder( ModelBuilder modelBuilder ) { this.modelBuilder = Objects.requireNonNull( modelBuilder, "modelBuilder cannot be null" ); return this; } public ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session, ArtifactDescriptorRequest request ) throws ArtifactDescriptorException { ArtifactDescriptorResult result = new ArtifactDescriptorResult( request ); Model model = loadPom( session, request, result ); if ( model != null ) { Map<String, Object> config = session.getConfigProperties(); ArtifactDescriptorReaderDelegate delegate = (ArtifactDescriptorReaderDelegate) config.get( ArtifactDescriptorReaderDelegate.class.getName() ); if ( delegate == null ) { delegate = new ArtifactDescriptorReaderDelegate(); } delegate.populateResult( session, result, model ); } return result; } private Model loadPom( RepositorySystemSession session, ArtifactDescriptorRequest request, ArtifactDescriptorResult result ) throws ArtifactDescriptorException { RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); Set<String> visited = new LinkedHashSet<>(); for ( Artifact a = request.getArtifact();; ) { Artifact pomArtifact = ArtifactDescriptorUtils.toPomArtifact( a ); try { VersionRequest versionRequest = new VersionRequest( a, request.getRepositories(), request.getRequestContext() ); versionRequest.setTrace( trace ); VersionResult versionResult = versionResolver.resolveVersion( session, versionRequest ); a = a.setVersion( versionResult.getVersion() ); versionRequest = new VersionRequest( pomArtifact, request.getRepositories(), request.getRequestContext() ); versionRequest.setTrace( trace ); versionResult = versionResolver.resolveVersion( session, versionRequest ); pomArtifact = pomArtifact.setVersion( versionResult.getVersion() ); } catch ( VersionResolutionException e ) { result.addException( e ); throw new ArtifactDescriptorException( result ); } if ( !visited.add( a.getGroupId() + ':' + a.getArtifactId() + ':' + a.getBaseVersion() ) ) { RepositoryException exception = new RepositoryException( "Artifact relocations form a cycle: " + visited ); invalidDescriptor( session, trace, a, exception ); if ( ( getPolicy( session, a, request ) & ArtifactDescriptorPolicy.IGNORE_INVALID ) != 0 ) { return null; } result.addException( exception ); throw new ArtifactDescriptorException( result ); } ArtifactResult resolveResult; try { ArtifactRequest resolveRequest = new ArtifactRequest( pomArtifact, request.getRepositories(), request.getRequestContext() ); resolveRequest.setTrace( trace ); resolveResult = artifactResolver.resolveArtifact( session, resolveRequest ); pomArtifact = resolveResult.getArtifact(); result.setRepository( resolveResult.getRepository() ); } catch ( ArtifactResolutionException e ) { if ( e.getCause() instanceof ArtifactNotFoundException ) { missingDescriptor( session, trace, a, (Exception) e.getCause() ); if ( ( getPolicy( session, a, request ) & ArtifactDescriptorPolicy.IGNORE_MISSING ) != 0 ) { return null; } } result.addException( e ); throw new ArtifactDescriptorException( result ); } Model model; // hack: don't rebuild model if it was already loaded during reactor resolution final WorkspaceReader workspace = session.getWorkspaceReader(); if ( workspace instanceof MavenWorkspaceReader ) { model = ( (MavenWorkspaceReader) workspace ).findModel( pomArtifact ); if ( model != null ) { return model; } } try { ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest(); modelRequest.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); modelRequest.setProcessPlugins( false ); modelRequest.setTwoPhaseBuilding( false ); modelRequest.setSystemProperties( toProperties( session.getUserProperties(), session.getSystemProperties() ) ); modelRequest.setModelCache( DefaultModelCache.newInstance( session ) ); modelRequest.setModelResolver( new DefaultModelResolver( session, trace.newChild( modelRequest ), request.getRequestContext(), artifactResolver, versionRangeResolver, remoteRepositoryManager, request.getRepositories() ) ); if ( resolveResult.getRepository() instanceof WorkspaceRepository ) { modelRequest.setPomFile( pomArtifact.getFile() ); } else { modelRequest.setModelSource( new FileModelSource( pomArtifact.getFile() ) ); } model = modelBuilder.build( modelRequest ).getEffectiveModel(); } catch ( ModelBuildingException e ) { for ( ModelProblem problem : e.getProblems() ) { if ( problem.getException() instanceof UnresolvableModelException ) { result.addException( problem.getException() ); throw new ArtifactDescriptorException( result ); } } invalidDescriptor( session, trace, a, e ); if ( ( getPolicy( session, a, request ) & ArtifactDescriptorPolicy.IGNORE_INVALID ) != 0 ) { return null; } result.addException( e ); throw new ArtifactDescriptorException( result ); } Relocation relocation = getRelocation( model ); if ( relocation != null ) { result.addRelocation( a ); a = new RelocatedArtifact( a, relocation.getGroupId(), relocation.getArtifactId(), relocation.getVersion() ); result.setArtifact( a ); } else { return model; } } } private Properties toProperties( Map<String, String> dominant, Map<String, String> recessive ) { Properties props = new Properties(); if ( recessive != null ) { props.putAll( recessive ); } if ( dominant != null ) { props.putAll( dominant ); } return props; } private Relocation getRelocation( Model model ) { Relocation relocation = null; DistributionManagement distMgmt = model.getDistributionManagement(); if ( distMgmt != null ) { relocation = distMgmt.getRelocation(); } return relocation; } private void missingDescriptor( RepositorySystemSession session, RequestTrace trace, Artifact artifact, Exception exception ) { RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_DESCRIPTOR_MISSING ); event.setTrace( trace ); event.setArtifact( artifact ); event.setException( exception ); repositoryEventDispatcher.dispatch( event.build() ); } private void invalidDescriptor( RepositorySystemSession session, RequestTrace trace, Artifact artifact, Exception exception ) { RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_DESCRIPTOR_INVALID ); event.setTrace( trace ); event.setArtifact( artifact ); event.setException( exception ); repositoryEventDispatcher.dispatch( event.build() ); } private int getPolicy( RepositorySystemSession session, Artifact a, ArtifactDescriptorRequest request ) { ArtifactDescriptorPolicy policy = session.getArtifactDescriptorPolicy(); if ( policy == null ) { return ArtifactDescriptorPolicy.STRICT; } return policy.getPolicy( session, new ArtifactDescriptorPolicyRequest( a, request.getRequestContext() ) ); } }
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.program; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import lombok.RequiredArgsConstructor; import org.apache.commons.collections4.SetValuedMap; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataentryform.DataEntryForm; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.program.jdbc.JdbcOrgUnitAssociationsStore; import org.hisp.dhis.trackedentity.TrackedEntityType; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; /** * @author Abyot Asalefew */ @RequiredArgsConstructor @Service( "org.hisp.dhis.program.ProgramService" ) public class DefaultProgramService implements ProgramService { // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private final ProgramStore programStore; private final CurrentUserService currentUserService; @Qualifier( "jdbcProgramOrgUnitAssociationsStore" ) private final JdbcOrgUnitAssociationsStore jdbcOrgUnitAssociationsStore; // ------------------------------------------------------------------------- // Implementation methods // ------------------------------------------------------------------------- @Override @Transactional public long addProgram( Program program ) { programStore.save( program ); return program.getId(); } @Override @Transactional public void updateProgram( Program program ) { programStore.update( program ); } @Override @Transactional public void deleteProgram( Program program ) { programStore.delete( program ); } @Override @Transactional( readOnly = true ) public List<Program> getAllPrograms() { return programStore.getAll(); } @Override @Transactional( readOnly = true ) public Program getProgram( long id ) { return programStore.get( id ); } @Override @Transactional( readOnly = true ) public Collection<Program> getPrograms( Collection<String> uids ) { return programStore.getByUid( uids ); } @Override @Transactional( readOnly = true ) public List<Program> getPrograms( OrganisationUnit organisationUnit ) { return programStore.get( organisationUnit ); } @Override @Transactional( readOnly = true ) public Program getProgram( String uid ) { return programStore.getByUid( uid ); } @Override @Transactional( readOnly = true ) public List<Program> getProgramsByTrackedEntityType( TrackedEntityType trackedEntityType ) { return programStore.getByTrackedEntityType( trackedEntityType ); } @Override @Transactional( readOnly = true ) public List<Program> getProgramsByDataEntryForm( DataEntryForm dataEntryForm ) { return programStore.getByDataEntryForm( dataEntryForm ); } @Override @Transactional( readOnly = true ) public List<Program> getUserPrograms() { return getUserPrograms( currentUserService.getCurrentUser() ); } @Override @Transactional( readOnly = true ) public List<Program> getUserPrograms( User user ) { if ( user == null || user.isSuper() ) { return getAllPrograms(); } return programStore.getDataReadAll( user ); } // ------------------------------------------------------------------------- // ProgramDataElement // ------------------------------------------------------------------------- @Override @Transactional( readOnly = true ) public List<ProgramDataElementDimensionItem> getGeneratedProgramDataElements( String programUid ) { Program program = getProgram( programUid ); List<ProgramDataElementDimensionItem> programDataElements = Lists.newArrayList(); if ( program == null ) { return programDataElements; } for ( DataElement element : program.getDataElements() ) { programDataElements.add( new ProgramDataElementDimensionItem( program, element ) ); } Collections.sort( programDataElements ); return programDataElements; } @Override public boolean hasOrgUnit( Program program, OrganisationUnit organisationUnit ) { return this.programStore.hasOrgUnit( program, organisationUnit ); } @Override public SetValuedMap<String, String> getProgramOrganisationUnitsAssociationsForCurrentUser( Set<String> programUids ) { return jdbcOrgUnitAssociationsStore.getOrganisationUnitsAssociationsForCurrentUser( programUids ); } @Override public SetValuedMap<String, String> getProgramOrganisationUnitsAssociations( Set<String> programUids ) { return jdbcOrgUnitAssociationsStore.getOrganisationUnitsAssociations( programUids ); } }
package sone.jiraworklogclient.boundary; import java.awt.Color; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JLabel; import javax.swing.text.JTextComponent; public abstract class InputChecker { protected boolean isRight = false; protected JTextComponent inputComponent = null; protected JLabel alertLabel = null; public InputChecker(final JTextComponent inputComponent) { this.inputComponent = inputComponent; } public boolean isRight() { return isRight; } public JTextComponent getInputComponent() { return inputComponent; } public void setAlertLabel(final JLabel alertLabel) { this.alertLabel = alertLabel; } public void updateAlertLabel() { String inputText = getInputText(); if( alertLabel != null ) { Pattern pattern = getPattern(); Matcher matcher = pattern.matcher(inputText); if( matcher.find() ) { alertLabel.setForeground(new Color(0, 180, 0)); // light green alertLabel.setText(getRightSignal()); isRight = true; } else { alertLabel.setForeground(Color.RED); alertLabel.setText(getRightExample()); isRight = false; } } } protected String getInputText() { return inputComponent.getText(); } protected abstract Pattern getPattern(); protected abstract String getRightSignal(); protected abstract String getRightExample(); } class IPChecker extends InputChecker { public IPChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { return Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}$"); } @Override protected String getRightSignal() { return "Yeah"; } @Override protected String getRightExample() { return "x, ex) 211.222.34.22"; } } class PortChecker extends InputChecker { public PortChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { // 0 ~ 65535 return Pattern.compile("^(?:\\d|[1-9]\\d{1,3}|[1-5]\\d{4}|6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])$"); } @Override protected String getRightSignal() { return "Wow"; } @Override protected String getRightExample() { return "Range : 0 ~ 65535"; } } class IdChecker extends InputChecker { public IdChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { return Pattern.compile("^\\w+$"); } @Override protected String getRightSignal() { return "That's you"; } @Override protected String getRightExample() { return "Type yourself"; } } class PasswordChecker extends InputChecker { public PasswordChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { return Pattern.compile("^.+$"); } @Override protected String getRightSignal() { return "Your secret.."; } @Override protected String getRightExample() { return "Type password"; } } class IssueKeyChecker extends InputChecker { public IssueKeyChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { return Pattern.compile("^\\w+-[1-9][0-9]* : \\S(.*\\S)*$"); } @Override protected String getRightSignal() { return "Excellent"; } @Override protected String getRightExample() { return "ex) KP-27 : Suicide"; } } class UserIdListChecker extends InputChecker { public UserIdListChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { return Pattern.compile("^\\w+(( )\\w+)*$"); // id separated by space } @Override protected String getRightSignal() { String userIds = getInputText(); String[] idList = userIds.split(" "); return idList.length + " people"; } @Override protected String getRightExample() { return "split by \" \""; } } class TimeSpentChecker extends InputChecker { public TimeSpentChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { String hourRegex = "[1-9][0-9]*h"; String minuteRegex = "[1-9][0-9]*m"; // should it "([1-9]|[1-5][0-9]|60)m"? return Pattern.compile("^(" + hourRegex + "|" + minuteRegex + "|" + hourRegex + " " + minuteRegex + ")$"); } @Override protected String getRightSignal() { return "Our time is running out"; } @Override protected String getRightExample() { return "ex) 2h, 45m, 1h 30m"; } } class BlankChecker extends InputChecker { public BlankChecker(final JTextComponent inputComponent) { super(inputComponent); } @Override protected Pattern getPattern() { return Pattern.compile("^(.|\n)+$"); } @Override protected String getRightSignal() { return "Ok"; } @Override protected String getRightExample() { return "Fill it!"; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.impl; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import javax.naming.Context; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.NoFactoryAvailableException; import org.apache.camel.PollingConsumer; import org.apache.camel.Producer; import org.apache.camel.TypeConverter; import org.apache.camel.health.HealthCheckRegistry; import org.apache.camel.impl.converter.BaseTypeConverterRegistry; import org.apache.camel.impl.converter.DefaultTypeConverter; import org.apache.camel.impl.health.DefaultHealthCheckRegistry; import org.apache.camel.impl.transformer.TransformerKey; import org.apache.camel.impl.validator.ValidatorKey; import org.apache.camel.model.transformer.TransformerDefinition; import org.apache.camel.model.validator.ValidatorDefinition; import org.apache.camel.runtimecatalog.RuntimeCamelCatalog; import org.apache.camel.runtimecatalog.impl.DefaultRuntimeCamelCatalog; import org.apache.camel.spi.AsyncProcessorAwaitManager; import org.apache.camel.spi.CamelContextNameStrategy; import org.apache.camel.spi.ClassResolver; import org.apache.camel.spi.ComponentResolver; import org.apache.camel.spi.DataFormatResolver; import org.apache.camel.spi.EndpointRegistry; import org.apache.camel.spi.ExecutorServiceManager; import org.apache.camel.spi.FactoryFinder; import org.apache.camel.spi.FactoryFinderResolver; import org.apache.camel.spi.HeadersMapFactory; import org.apache.camel.spi.InflightRepository; import org.apache.camel.spi.Injector; import org.apache.camel.spi.LanguageResolver; import org.apache.camel.spi.ManagementNameStrategy; import org.apache.camel.spi.ManagementStrategy; import org.apache.camel.spi.ManagementStrategyFactory; import org.apache.camel.spi.MessageHistoryFactory; import org.apache.camel.spi.ModelJAXBContextFactory; import org.apache.camel.spi.NodeIdFactory; import org.apache.camel.spi.PackageScanClassResolver; import org.apache.camel.spi.ProcessorFactory; import org.apache.camel.spi.Registry; import org.apache.camel.spi.RestRegistry; import org.apache.camel.spi.RouteController; import org.apache.camel.spi.ShutdownStrategy; import org.apache.camel.spi.StreamCachingStrategy; import org.apache.camel.spi.TransformerRegistry; import org.apache.camel.spi.TypeConverterRegistry; import org.apache.camel.spi.UnitOfWorkFactory; import org.apache.camel.spi.UuidGenerator; import org.apache.camel.spi.ValidatorRegistry; /** * Represents the context used to configure routes and the policies to use. */ public class DefaultCamelContext extends AbstractCamelContext { /** * Creates the {@link CamelContext} using {@link JndiRegistry} as registry, * but will silently fallback and use {@link SimpleRegistry} if JNDI cannot be used. * <p/> * Use one of the other constructors to force use an explicit registry / JNDI. */ public DefaultCamelContext() { super(); } /** * Creates the {@link CamelContext} using the given JNDI context as the registry * * @param jndiContext the JNDI context */ public DefaultCamelContext(Context jndiContext) { super(jndiContext); } /** * Creates the {@link CamelContext} using the given registry * * @param registry the registry */ public DefaultCamelContext(Registry registry) { super(registry); } public DefaultCamelContext(boolean init) { super(init); } /** * Lazily create a default implementation */ protected TypeConverter createTypeConverter() { BaseTypeConverterRegistry answer; answer = new DefaultTypeConverter(getPackageScanClassResolver(), getInjector(), getDefaultFactoryFinder(), isLoadTypeConverters()); answer.setCamelContext(this); setTypeConverterRegistry(answer); return answer; } @Override protected TypeConverterRegistry createTypeConverterRegistry() { TypeConverter typeConverter = getTypeConverter(); if (typeConverter instanceof TypeConverterRegistry) { return (TypeConverterRegistry) typeConverter; } return null; } /** * Lazily create a default implementation */ protected Injector createInjector() { FactoryFinder finder = getDefaultFactoryFinder(); try { return (Injector) finder.newInstance("Injector"); } catch (NoFactoryAvailableException e) { // lets use the default injector return new DefaultInjector(this); } } /** * Lazily create a default implementation */ protected ComponentResolver createComponentResolver() { return new DefaultComponentResolver(); } /** * Lazily create a default implementation */ protected Registry createRegistry() { JndiRegistry jndi = new JndiRegistry(); try { // getContext() will force setting up JNDI jndi.getContext(); return jndi; } catch (Throwable e) { log.debug("Cannot create javax.naming.InitialContext due " + e.getMessage() + ". Will fallback and use SimpleRegistry instead. This exception is ignored.", e); return new SimpleRegistry(); } } protected ManagementStrategy createManagementStrategy() { if (!isJMXDisabled()) { try { ServiceLoader<ManagementStrategyFactory> loader = ServiceLoader.load(ManagementStrategyFactory.class); Iterator<ManagementStrategyFactory> iterator = loader.iterator(); if (iterator.hasNext()) { return iterator.next().create(this); } } catch (Exception e) { log.warn("Cannot create JMX lifecycle strategy. Will fallback and disable JMX.", e); } } return new DefaultManagementStrategy(this); } protected UuidGenerator createUuidGenerator() { if (System.getProperty("com.google.appengine.runtime.environment") != null) { // either "Production" or "Development" return new JavaUuidGenerator(); } else { return new DefaultUuidGenerator(); } } protected ModelJAXBContextFactory createModelJAXBContextFactory() { return new DefaultModelJAXBContextFactory(); } protected NodeIdFactory createNodeIdFactory() { return new DefaultNodeIdFactory(); } protected FactoryFinderResolver createFactoryFinderResolver() { return new DefaultFactoryFinderResolver(); } protected ClassResolver createClassResolver() { return new DefaultClassResolver(this); } protected ProcessorFactory createProcessorFactory() { return new DefaultProcessorFactory(); } protected DataFormatResolver createDataFormatResolver() { return new DefaultDataFormatResolver(); } protected MessageHistoryFactory createMessageHistoryFactory() { return new DefaultMessageHistoryFactory(); } protected InflightRepository createInflightRepository() { return new DefaultInflightRepository(); } protected AsyncProcessorAwaitManager createAsyncProcessorAwaitManager() { return new DefaultAsyncProcessorAwaitManager(); } protected RouteController createRouteController() { return new DefaultRouteController(this); } protected HealthCheckRegistry createHealthCheckRegistry() { return new DefaultHealthCheckRegistry(this); } protected ShutdownStrategy createShutdownStrategy() { return new DefaultShutdownStrategy(this); } protected PackageScanClassResolver createPackageScanClassResolver() { PackageScanClassResolver packageScanClassResolver; // use WebSphere specific resolver if running on WebSphere if (WebSpherePackageScanClassResolver.isWebSphereClassLoader(this.getClass().getClassLoader())) { log.info("Using WebSphere specific PackageScanClassResolver"); packageScanClassResolver = new WebSpherePackageScanClassResolver("META-INF/services/org/apache/camel/TypeConverter"); } else { packageScanClassResolver = new DefaultPackageScanClassResolver(); } return packageScanClassResolver; } protected ExecutorServiceManager createExecutorServiceManager() { return new DefaultExecutorServiceManager(this); } protected ServicePool<Producer> createProducerServicePool() { return new ServicePool<>(Endpoint::createProducer, Producer::getEndpoint, 100); } protected ServicePool<PollingConsumer> createPollingConsumerServicePool() { return new ServicePool<>(Endpoint::createPollingConsumer, PollingConsumer::getEndpoint, 100); } protected UnitOfWorkFactory createUnitOfWorkFactory() { return new DefaultUnitOfWorkFactory(); } protected RuntimeCamelCatalog createRuntimeCamelCatalog() { return new DefaultRuntimeCamelCatalog(this, true); } protected CamelContextNameStrategy createCamelContextNameStrategy() { return new DefaultCamelContextNameStrategy(); } protected ManagementNameStrategy createManagementNameStrategy() { return new DefaultManagementNameStrategy(this); } protected HeadersMapFactory createHeadersMapFactory() { return new HeadersMapFactoryResolver().resolve(this); } protected LanguageResolver createLanguageResolver() { return new DefaultLanguageResolver(); } @Override protected RestRegistry createRestRegistry() { return new DefaultRestRegistry(); } protected EndpointRegistry<EndpointKey> createEndpointRegistry(Map<EndpointKey, Endpoint> endpoints) { return new DefaultEndpointRegistry(this, endpoints); } protected ValidatorRegistry<ValidatorKey> createValidatorRegistry(List<ValidatorDefinition> validators) throws Exception { return new DefaultValidatorRegistry(this, validators); } protected TransformerRegistry<TransformerKey> createTransformerRegistry(List<TransformerDefinition> transformers) throws Exception { return new DefaultTransformerRegistry(this, transformers); } @Override protected StreamCachingStrategy createStreamCachingStrategy() { return new DefaultStreamCachingStrategy(); } }
/* 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. */ package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Project; import java.awt.event.ActionEvent; import javax.swing.Action; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.CMain; import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase; import com.google.security.zynamics.binnavi.Gui.Actions.CActionProxy; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Actions.CLoadProjectAction; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.AddressSpace.CAddressSpaceNode; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Project.Component.CProjectNodeComponent; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Traces.CTracesNode; import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Views.Project.CProjectViewsContainerNode; import com.google.security.zynamics.binnavi.disassembly.CProject; import com.google.security.zynamics.binnavi.disassembly.CProjectContainer; import com.google.security.zynamics.binnavi.disassembly.CProjectListenerAdapter; import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace; import com.google.security.zynamics.binnavi.disassembly.INaviProject; import com.google.security.zynamics.binnavi.disassembly.AddressSpaces.CAddressSpace; import com.google.security.zynamics.zylib.gui.SwingInvoker; /** * Represents a project node in the project tree. */ public final class CProjectNode extends CProjectTreeNode<INaviProject> { /** * Used for serialization. */ private static final long serialVersionUID = -7833552492435605478L; /** * Icon used in the project tree if the project is loaded. */ private static final ImageIcon ICON_PROJECTS_CONTAINER = new ImageIcon( CMain.class.getResource("data/projecttreeicons/project3.png")); /** * Icon used in the project tree if the project is closed. */ private static final ImageIcon ICON_PROJECTS_CONTAINER_GRAY = new ImageIcon( CMain.class.getResource("data/projecttreeicons/project3_gray.png")); /** * The database the project belongs to. */ private final IDatabase m_database; /** * The project that is described by the node. */ private final INaviProject m_project; /** * Listens on the project and updates the node and its children if something import happens. */ private final InternalProjectListener m_listener; /** * View container object for the represented project. */ private final CProjectContainer m_container; /** * Creates a new project node. * * @param projectTree The project tree of the main window. * @param parentNode Parent node of the project node. * @param database Database the project belongs to. * @param project Project the node represents. * @param contextContainer The container in whose context the views are opened. */ public CProjectNode(final JTree projectTree, final DefaultMutableTreeNode parentNode, final IDatabase database, final INaviProject project, final CProjectContainer contextContainer) { super(projectTree, new CAbstractLazyComponent() { @Override protected CAbstractNodeComponent createComponent() { return new CProjectNodeComponent(projectTree, database, project, contextContainer); } }, new CProjectNodeMenuBuilder(projectTree, parentNode, database, new INaviProject[] {project}, null), project); Preconditions.checkNotNull(database, "IE01980: Database can't be null"); Preconditions.checkNotNull(project, "IE01981: Project can't be null"); m_project = project; m_database = database; m_container = contextContainer; createChildren(); m_listener = new InternalProjectListener(); m_project.addListener(m_listener); } /** * Creates the child nodes of project nodes. One child node is added for each address space found * in the project. */ @Override protected void createChildren() { if (m_project.isLoaded()) { for (final INaviAddressSpace addressSpace : m_project.getContent().getAddressSpaces()) { add(new CAddressSpaceNode(getProjectTree(), this, m_database, m_project, addressSpace, m_container)); } add(new CProjectViewsContainerNode(getProjectTree(), m_project, m_container)); add(new CTracesNode(getProjectTree(), m_container)); } } @Override public void dispose() { super.dispose(); m_container.dispose(); m_project.removeListener(m_listener); deleteChildren(); } @Override public void doubleClicked() { // Open projects on double-click. if (!m_project.isLoaded()) { final Action action = CActionProxy.proxy(new CLoadProjectAction(getProjectTree(), new INaviProject[] {m_project})); action.actionPerformed(new ActionEvent(this, 0, "")); } } @Override public CProjectNodeComponent getComponent() { return (CProjectNodeComponent) super.getComponent(); } @Override public Icon getIcon() { return m_project.isLoaded() ? ICON_PROJECTS_CONTAINER : ICON_PROJECTS_CONTAINER_GRAY; } @Override public String toString() { return m_project.getConfiguration().getName() + " (" + m_project.getAddressSpaceCount() + ")"; } /** * Listens on the project and updates the node and its children if something import happens. */ private class InternalProjectListener extends CProjectListenerAdapter { /** * When an address space is added to the project, a new node that represents this address space * must be added to the tree. */ @Override public void addedAddressSpace(final INaviProject project, final CAddressSpace space) { new SwingInvoker() { @Override protected void operation() { insert(new CAddressSpaceNode(getProjectTree(), CProjectNode.this, m_database, project, space, m_container), getChildCount() - 2); getTreeModel().nodeStructureChanged(CProjectNode.this); } }.invokeAndWait(); } @Override public void changedName(final INaviProject project, final String name) { getTreeModel().nodeChanged(CProjectNode.this); } /** * When a project is loaded, the nodes that represent the address spaces must be added as child * nodes to the project node. */ @Override public void loadedProject(final CProject project) { new SwingInvoker() { @Override protected void operation() { createChildren(); getTreeModel().nodeStructureChanged(CProjectNode.this); } }.invokeAndWait(); } /** * When an address space was removed from the project, the corresponding node must be removed * from the tree. */ @Override public void removedAddressSpace(final INaviProject project, final INaviAddressSpace addressSpace) { new SwingInvoker() { @Override protected void operation() { // Remove the node that represents the deleted address space. for (int i = 0; i < getChildCount(); i++) { if (getChildAt(i) instanceof CAddressSpaceNode) { final CAddressSpaceNode node = (CAddressSpaceNode) getChildAt(i); if (node.getObject() == addressSpace) { node.dispose(); remove(node); break; } } } getTreeModel().nodeStructureChanged(CProjectNode.this); } }.invokeAndWait(); } } }
/** * Copyright 2012 Christian Vielma <cvielma@librethinking.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 com.librethinking.simmodsys.models.pesm.parameters; import com.librethinking.simmodsys.SIMParameter; import com.librethinking.simmodsys.exceptions.ValueOutOfBoundsException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * This parameter represents Annual Estimated Rise in the income. * This is for the PESM (Personal Economy Simulation Model) * * @author Christian Vielma <cvielma@librethinking.com> */ public class IncomeAnnualRise extends PESMParameter { public static final String NAME = "INCOME.ANNUALRISE"; public static final boolean UNIQUE = false; public static final Object[] MINVALUE = {"", 0.0, 0.0, 0.0}; public static final Object[] MAXVALUE = {"", 1.0, 1.0, 1.0}; public static final Object[] DEFAULTVALUE = {"", 0.0, 0.0, 0.0}; public static final byte CATEGORYINDEX = 0; public static final byte MINPERCINDEX = 1; public static final byte MAXPERCINDEX = 2; public static final byte CURRVALINDEX = 3; private int status = 1; private String category = (String) DEFAULTVALUE[CATEGORYINDEX]; private double minPercentage = (Double) DEFAULTVALUE[MINPERCINDEX]; private double maxPercentage = (Double) DEFAULTVALUE[MAXPERCINDEX]; private double currentValue = (Double) DEFAULTVALUE[CURRVALINDEX]; /** This method returns the name of the SIMParameter. * * @return The SIMParameter's name */ @Override public String getName() { return NAME; } /** Returns the value stored in this parameter, in this case,the category, minPercentage, * maxPercentage and currentValue. * * @return Collection of four objects (String category, Double minPercentage, Double * maxPercentage, Double currentValue). */ @Override public Collection<Object> getValue() { Collection<Object> returnArray = new ArrayList<Object>(); returnArray.add(this.getCategory()); returnArray.add(this.getMinPercentage()); returnArray.add(this.getMaxPercentage()); returnArray.add(this.getCurrentValue()); return returnArray; } /** Sets the value of the category, minpercentage, maxpercentage and currentvalue at once. * This is is similar to call independently {@link setCategory}, {@link setMinPercentage} * {@link setMaxPercentage} and {@link setCurrentValue}, but this is the general version to * comply with the SIMParameter interface. * * @param value shoud be a Collection of four Objects (String, Double, Double, Double) * * @throws ClassCastException when passed value is wrong (i.e.: Collection is * larger than one element or contained object cannot be interpreted as expected) * @throws NullPointerException if the value passed is null. * @throws ValueOutOfBoundsException if value to be set is not between MINVALUE and MAXVALUE. */ @Override public void setValue(Collection<Object> value) { if(value==null){ throw new NullPointerException("Value to be set is null."); } else if(value.size()!=4){ throw new ClassCastException("'"+NAME+"' expects four values. " + "See documentation for reference."); } else{ try{ this.setCategory((String) value.toArray()[CATEGORYINDEX]); this.setMinPercentage((Double) value.toArray()[MINPERCINDEX]); this.setMaxPercentage((Double) value.toArray()[MAXPERCINDEX]); this.setCurrentValue((Double) value.toArray()[CURRVALINDEX]); } catch(ClassCastException e){ throw new ClassCastException("'"+NAME+"' expects a '[String, Double, Double, Double]' " + "and passed value was of type: '["+ (value.toArray()[CATEGORYINDEX]).getClass().getName()+", "+ (value.toArray()[MINPERCINDEX]).getClass().getName()+", "+ (value.toArray()[MAXPERCINDEX]).getClass().getName()+", "+ (value.toArray()[CURRVALINDEX]).getClass().getName()+"]'."); } } } /** Returns the current Status of this SIMParameter (e.g.: Disabled (currently 1) * or Enabled (currently 0). * @returns Int with the value of the estatus. @see Status Reference */ @Override public int getStatus() { return this.status; } /** Sets the current Status of this SIMParameter. * @param status the value of the new status. */ @Override public void setStatus(int status) { this.status = status; } /** Returns the MaxValue established for the SIMParameter. * Because this parameter have two values for MaxValue, it will return a Collection * with four values (String, Double, Double, Double). * * @return Collection of (String, Double, Double, Double). */ @Override public Collection<Object> getMaxValue() { return new ArrayList(Arrays.asList(MAXVALUE)); } /** Returns the DefaultValue established for the SIMParameter. * Because this parameter have two values for MinValue, it will return a Collection * with four values (String, Double, Double, Double). * * @return Collection of (String, Double, Double, Double). */ @Override public Collection<Object> getMinValue() { return new ArrayList(Arrays.asList(MINVALUE)); } /** @returns true if the SIMParameter is unique (no repeatable), false otherwise. */ @Override public boolean isUnique() { return UNIQUE; } /** This method is convenience method to return the category associated without * having to cast the result. Note that this method isn't part of the interface. * * @returns String with the category. */ public String getCategory(){ return this.category; } /** This method is convenience method to set the category associated without * having to cast the parameter or having to put it as a Collection. * Note that this method isn't part of the interface. * * @param category with the category value. * @throws ValueOutOfBounds if parameter passed is null. */ public void setCategory(String category){ if(category!=null){ this.category = category; } else{ StringBuilder sb = new StringBuilder(); sb.append("Category passed: '").append(category); sb.append("' cannot be 'null'."); throw new ValueOutOfBoundsException(sb.toString()); } } /** This method is convenience method to return the current value associated without * having to cast the result. Note that this method isn't part of the interface. * * @returns double with the current value. */ public double getCurrentValue(){ return this.currentValue; } /** This method is convenience method to set the current value associated without * having to cast the parameter or having to put it as a Collection. * Note that this method isn't part of the interface. * * @param category with the current value. * @throws ValueOutOfBoundsException if value to be set is not between MINVALUE and MAXVALUE. */ public void setCurrentValue(double current){ if(current>= (Double)this.MINVALUE[CURRVALINDEX] && current <= (Double) this.MAXVALUE[CURRVALINDEX]){ this.currentValue = current; } else{ StringBuilder sb = new StringBuilder(); sb.append("Current Value passed: ").append(current); sb.append(" is not in range: MIN ").append(this.MINVALUE[CURRVALINDEX]); sb.append(" and MAX ").append(this.MAXVALUE[CURRVALINDEX]); sb.append("."); throw new ValueOutOfBoundsException(sb.toString()); } } /** This method is convenience method to return the minPercentage associated without * having to cast the result. Note that this method isn't part of the interface. * * @returns double with the minpercentage. */ public double getMinPercentage(){ return this.minPercentage; } /** This method is convenience method to return the max percentage associated without * having to cast the result. Note that this method isn't part of the interface. * * @returns double with the max percentage. */ public double getMaxPercentage(){ return this.maxPercentage; } /** This method is convenience method to set the min percentage associated without * having to cast the parameter or having to put it as a Collection. * Note that this method isn't part of the interface. * * @param minperc with the min percentage value. * @throws ValueOutOfBoundsException if value to be set is not between MINVALUE and MAXVALUE. */ public void setMinPercentage(double minperc){ if(minperc>= (Double)this.MINVALUE[MINPERCINDEX] && minperc <= (Double) this.MAXVALUE[MINPERCINDEX]){ this.minPercentage = minperc; } else{ StringBuilder sb = new StringBuilder(); sb.append("MinPercentage passed: ").append(minperc); sb.append(" is not in range: MIN ").append(this.MINVALUE[MINPERCINDEX]); sb.append(" and MAX ").append(this.MAXVALUE[MINPERCINDEX]); sb.append("."); throw new ValueOutOfBoundsException(sb.toString()); } } /** This method is convenience method to set the max percentage associated without * having to cast the parameter or having to put it as a Collection. * Note that this method isn't part of the interface. * * @param maxperc with the max percentage value. * @throws ValueOutOfBoundsException if value to be set is not between MINVALUE and MAXVALUE. */ public void setMaxPercentage(double maxperc){ if(maxperc>= (Double)this.MINVALUE[MAXPERCINDEX] && maxperc <= (Double) this.MAXVALUE[MAXPERCINDEX]){ this.maxPercentage = maxperc; } else{ StringBuilder sb = new StringBuilder(); sb.append("Max Percentage passed: ").append(maxperc); sb.append(" is not in range: MIN ").append(this.MINVALUE[MAXPERCINDEX]); sb.append(" and MAX ").append(this.MAXVALUE[MAXPERCINDEX]); sb.append("."); throw new ValueOutOfBoundsException(sb.toString()); } } /** Returns the DefaultValue established for the SIMParameter. * Because this parameter have four values for DefaultValue, it will return a Collection * with four values (String. String, Double, Integer). * * @return Collection of (String. String, Double, Integer). */ @Override public Collection<Object> getDefaultValue() { return new ArrayList(Arrays.asList(DEFAULTVALUE)); } @Override public boolean equals(Object obj){ if (getClass() != this.getClass()){return false;} IncomeAnnualRise myparam = (IncomeAnnualRise) obj; return myparam.getMinPercentage() == this.getMinPercentage() && myparam.getMaxPercentage() == this.getMaxPercentage() && myparam.getCategory().equals(this.getCategory()) && myparam.getCurrentValue() == this.getCurrentValue() && myparam.getStatus() == this.getStatus(); } @Override public int hashCode(){ return (int) (this.getMinPercentage() + this.getMaxPercentage() + this.getCurrentValue() + this.getCategory().hashCode() + this.getStatus()); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("[Name: '").append(this.NAME).append("', MinValue: "); sb.append(this.MINVALUE).append(", MaxValue: ").append(this.MAXVALUE); sb.append(", DefaultValue: ").append(this.DEFAULTVALUE); sb.append(", Status: ").append(this.status); sb.append(", CATEGORY: ").append(this.category); sb.append(", MINPERCENTAGE: ").append(this.minPercentage); sb.append(", MAXPERCENTAGE: ").append(this.maxPercentage); sb.append(", CURRENTVALUE: ").append(this.currentValue); sb.append("."); return sb.toString(); } }
package org.opencb.opencga.storage.hadoop.variant.converters; import com.google.protobuf.InvalidProtocolBufferException; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.schema.types.*; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.avro.AlternateCoordinate; import org.opencb.biodata.models.variant.avro.OriginalCall; import org.opencb.biodata.models.variant.avro.VariantAnnotation; import org.opencb.biodata.models.variant.protobuf.VariantProto; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryException; import org.opencb.opencga.storage.hadoop.variant.GenomeHelper; import org.opencb.opencga.storage.hadoop.variant.adaptors.phoenix.PhoenixHelper; import org.opencb.opencga.storage.hadoop.variant.adaptors.phoenix.VariantPhoenixKeyFactory; import org.opencb.opencga.storage.hadoop.variant.converters.annotation.HBaseToVariantAnnotationConverter; import org.opencb.opencga.storage.hadoop.variant.converters.study.HBaseToStudyEntryConverter; import org.opencb.opencga.storage.hadoop.variant.gaps.VariantOverlappingStatus; import java.nio.ByteBuffer; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.List; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.IntConsumer; import static org.opencb.opencga.storage.hadoop.variant.adaptors.phoenix.VariantPhoenixHelper.*; public class VariantRow { private final Result result; private final ResultSet resultSet; private Variant variant; private VariantAnnotation variantAnnotation; public VariantRow(Result result) { this.result = Objects.requireNonNull(result); this.resultSet = null; } public VariantRow(ResultSet resultSet) { this.resultSet = Objects.requireNonNull(resultSet); this.result = null; } public static VariantRowWalkerBuilder walker(Result result) { return new VariantRow(result).walker(); } public static VariantRowWalkerBuilder walker(ResultSet resultSet) { return new VariantRow(resultSet).walker(); } public Variant getVariant() { if (variant == null) { if (result != null) { byte[] row = result.getRow(); Objects.requireNonNull(row, "Empty result. Missing variant rowkey."); variant = VariantPhoenixKeyFactory.extractVariantFromVariantRowKey(row); } else { variant = VariantPhoenixKeyFactory.extractVariantFromResultSet(resultSet); } } return variant; } public VariantAnnotation getVariantAnnotation() { if (variantAnnotation == null) { HBaseToVariantAnnotationConverter c = new HBaseToVariantAnnotationConverter(GenomeHelper.COLUMN_FAMILY_BYTES, -1); if (result != null) { variantAnnotation = c.convert(result); } else { variantAnnotation = c.convert(resultSet); } } return variantAnnotation; } public void forEachSample(Consumer<SampleColumn> consumer) { walker().onSample(consumer).walk(); } public void forEachFile(Consumer<FileColumn> consumer) { walker().onFile(consumer).walk(); } public VariantRowWalkerBuilder walker() { return new VariantRowWalkerBuilder(); } public void walk(VariantRowWalker walker) { walk(walker, true, true, true, true, true); } protected void walk(VariantRowWalker walker, boolean file, boolean sample, boolean cohort, boolean score, boolean annotation) { walker.variant(getVariant()); if (resultSet != null) { try { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String columnName = metaData.getColumnName(i); byte[] bytes = resultSet.getBytes(i); if (bytes == null) { continue; } if (file && columnName.endsWith(FILE_SUFIX)) { walker.file(new BytesFileColumn(bytes, extractStudyId(columnName), extractFileId(columnName))); } else if (sample && columnName.endsWith(SAMPLE_DATA_SUFIX)) { walker.sample(new BytesSampleColumn(bytes, extractStudyId(columnName), extractSampleId(columnName), extractFileIdFromSampleColumn(columnName, false))); } else if (columnName.endsWith(STUDY_SUFIX)) { walker.study(extractStudyId(columnName)); } else if (cohort && columnName.endsWith(COHORT_STATS_PROTOBUF_SUFFIX)) { walker.stats(new BytesStatsColumn(bytes, extractStudyId(columnName), extractCohortStatsId(columnName))); } else if (score && columnName.endsWith(VARIANT_SCORE_SUFIX)) { walker.score(new BytesVariantScoreColumn(bytes, extractStudyId(columnName), extractScoreId(columnName))); } else if (columnName.endsWith(FILL_MISSING_SUFIX)) { int studyId = Integer.valueOf(columnName.split("_")[1]); walker.fillMissing(studyId, resultSet.getInt(i)); } else if (annotation && columnName.equals(VariantColumn.FULL_ANNOTATION.column())) { walker.variantAnnotation(new BytesVariantAnnotationColumn(bytes)); } } } catch (SQLException e) { throw VariantQueryException.internalException(e); } } else { for (Cell cell : result.rawCells()) { String columnName = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()); if (file && columnName.endsWith(FILE_SUFIX)) { walker.file(new BytesFileColumn(cell, extractStudyId(columnName), extractFileId(columnName))); } else if (sample && columnName.endsWith(SAMPLE_DATA_SUFIX)) { walker.sample(new BytesSampleColumn(cell, extractStudyId(columnName), extractSampleId(columnName), extractFileIdFromSampleColumn(columnName, false))); } else if (columnName.endsWith(STUDY_SUFIX)) { walker.study(extractStudyId(columnName)); } else if (cohort && columnName.endsWith(COHORT_STATS_PROTOBUF_SUFFIX)) { walker.stats(new BytesStatsColumn(cell, extractStudyId(columnName), extractCohortStatsId(columnName))); } else if (score && columnName.endsWith(VARIANT_SCORE_SUFIX)) { walker.score(new BytesVariantScoreColumn(cell, extractStudyId(columnName), extractScoreId(columnName))); } else if (columnName.endsWith(FILL_MISSING_SUFIX)) { int studyId = Integer.valueOf(columnName.split("_")[1]); walker.fillMissing(studyId, ((Integer) PInteger.INSTANCE.toObject(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()))); } else if (annotation && columnName.equals(VariantColumn.FULL_ANNOTATION.column())) { walker.variantAnnotation(new BytesVariantAnnotationColumn(cell)); } } } } public abstract static class VariantRowWalker { protected void variant(Variant variant) { } protected void study(int studyId) { } protected void file(FileColumn fileColumn) { } protected void sample(SampleColumn sampleColumn) { } protected void stats(StatsColumn statsColumn) { } protected void score(VariantScoreColumn scoreColumn) { } protected void fillMissing(int studyId, int fillMissing) { } protected void variantAnnotation(VariantAnnotationColumn column) { } } public class VariantRowWalkerBuilder extends VariantRowWalker { private IntConsumer studyConsumer = r -> { }; private Consumer<FileColumn> fileConsumer = r -> { }; private boolean hasFileConsumer = false; private Consumer<SampleColumn> sampleConsumer = r -> { }; private boolean hasSampleConsumer = false; private Consumer<StatsColumn> statsConsumer = r -> { }; private boolean hasStatsConsumer = false; private Consumer<VariantScoreColumn> variantScoreConsumer = r -> { }; private boolean hasVariantScoreConsumer = false; private BiConsumer<Integer, Integer> fillMissingConsumer = (k, v) -> { }; private Consumer<VariantAnnotationColumn> variantAnnotationConsummer = (k) -> { }; private boolean hasVariantAnnotationConsummer = false; private Variant variant; public Variant getVariant() { return variant; } @Override protected void variant(Variant variant) { this.variant = variant; } @Override protected void study(int studyId) { studyConsumer.accept(studyId); } @Override protected void file(FileColumn fileColumn) { fileConsumer.accept(fileColumn); } @Override protected void sample(SampleColumn sampleColumn) { sampleConsumer.accept(sampleColumn); } @Override protected void stats(StatsColumn statsColumn) { statsConsumer.accept(statsColumn); } @Override protected void score(VariantScoreColumn scoreColumn) { variantScoreConsumer.accept(scoreColumn); } @Override protected void fillMissing(int studyId, int fillMissing) { fillMissingConsumer.accept(studyId, fillMissing); } @Override protected void variantAnnotation(VariantAnnotationColumn column) { variantAnnotationConsummer.accept(column); } public Variant walk() { VariantRow.this.walk(this, hasFileConsumer, hasSampleConsumer, hasStatsConsumer, hasVariantScoreConsumer, hasVariantAnnotationConsummer); return getVariant(); } public VariantRowWalkerBuilder onStudy(IntConsumer consumer) { studyConsumer = consumer; return this; } public VariantRowWalkerBuilder onFile(Consumer<FileColumn> consumer) { fileConsumer = consumer; hasFileConsumer = true; return this; } public VariantRowWalkerBuilder onSample(Consumer<SampleColumn> consumer) { sampleConsumer = consumer; hasSampleConsumer = true; return this; } public VariantRowWalkerBuilder onCohortStats(Consumer<StatsColumn> consumer) { statsConsumer = consumer; hasStatsConsumer = true; return this; } public VariantRowWalkerBuilder onVariantScore(Consumer<VariantScoreColumn> consumer) { variantScoreConsumer = consumer; hasVariantScoreConsumer = true; return this; } public VariantRowWalkerBuilder onFillMissing(BiConsumer<Integer, Integer> consumer) { fillMissingConsumer = consumer; return this; } public VariantRowWalkerBuilder onVariantAnnotation(Consumer<VariantAnnotationColumn> consumer) { variantAnnotationConsummer = consumer; hasVariantAnnotationConsummer = true; return this; } } public interface FileColumn extends Column { int getStudyId(); int getFileId(); PhoenixArray raw(); String getCallString(); default OriginalCall getCall() { String callString = getCallString(); if (callString == null) { return null; } else { int i = callString.lastIndexOf(':'); return new OriginalCall( callString.substring(0, i), Integer.valueOf(callString.substring(i + 1))); } } List<AlternateCoordinate> getSecondaryAlternates(); VariantOverlappingStatus getOverlappingStatus(); Double getQual(); String getQualString(); String getFilter(); String getString(int idx); } public interface SampleColumn extends Column { int getStudyId(); int getSampleId(); Integer getFileId(); List<String> getSampleData(); List<String> getMutableSampleData(); default String getGT() { return getSampleData(0); } String getSampleData(int idx); } public interface StatsColumn extends Column { int getStudyId(); int getCohortId(); VariantProto.VariantStats toProto(); } public interface VariantScoreColumn extends Column { int getStudyId(); int getScoreId(); float getScore(); float getPValue(); } public interface VariantAnnotationColumn extends Column { ImmutableBytesWritable toBytesWritable(); } public interface Column { } private static class BytesColumn { protected final byte[] valueArray; protected final int valueOffset; protected final int valueLength; BytesColumn(Cell cell) { valueArray = cell.getValueArray(); valueOffset = cell.getValueOffset(); valueLength = cell.getValueLength(); } BytesColumn(byte[] value) { valueArray = value; valueOffset = 0; valueLength = value.length; } public ImmutableBytesWritable toBytesWritable() { return new ImmutableBytesWritable(valueArray, valueOffset, valueLength); } public String getString(int arrayIndex) { return get(arrayIndex, PVarchar.INSTANCE); } public float getFloat(int arrayIndex) { return get(arrayIndex, PFloat.INSTANCE); } private <T> T get(int arrayIndex, PDataType<T> pDataType) { ImmutableBytesWritable ptr = new ImmutableBytesWritable( valueArray, valueOffset, valueLength); PhoenixHelper.positionAtArrayElement(ptr, arrayIndex, pDataType, null); return (T) pDataType.toObject(ptr); } } private static class BytesSampleColumn extends BytesColumn implements SampleColumn { private final int studyId; private final int sampleId; private final Integer fileId; // public static SampleColumn getOrNull(Cell cell) { // Integer sampleId = VariantPhoenixHelper.extractSampleId( // cell.getQualifierArray(), // cell.getQualifierOffset(), // cell.getQualifierLength()); // if (sampleId == null) { // return null; // } else { // return new BytesSampleColumn(cell, sampleId); // } // } BytesSampleColumn(Cell cell, int studyId, int sampleId, Integer fileId) { super(cell); this.studyId = studyId; this.sampleId = sampleId; this.fileId = fileId; } BytesSampleColumn(byte[] value, int studyId, int sampleId, Integer fileId) { super(value); this.studyId = studyId; this.sampleId = sampleId; this.fileId = fileId; } @Override public int getStudyId() { return studyId; } @Override public int getSampleId() { return sampleId; } @Override public Integer getFileId() { return fileId; } @Override public List<String> getSampleData() { PhoenixArray array = (PhoenixArray) PVarcharArray.INSTANCE.toObject( valueArray, valueOffset, valueLength); // return AbstractPhoenixConverter.toModifiableList(array); return AbstractPhoenixConverter.toList(array); } @Override public List<String> getMutableSampleData() { PhoenixArray array = (PhoenixArray) PVarcharArray.INSTANCE.toObject( valueArray, valueOffset, valueLength); return AbstractPhoenixConverter.toModifiableList(array); // return AbstractPhoenixConverter.toList(array); } @Override public String getSampleData(int idx) { return super.getString(idx); } } private static class BytesFileColumn extends BytesColumn implements FileColumn { private final int studyId; private final int fileId; // public static FileColumn getOrNull(Cell cell) { // Integer fileId = VariantPhoenixHelper.extractFileId( // cell.getQualifierArray(), // cell.getQualifierOffset(), // cell.getQualifierLength()); // if (fileId == null) { // return null; // } else { // return new BytesFileColumn(cell, fileId); // } // } BytesFileColumn(Cell cell, int studyId, int fileId) { super(cell); this.studyId = studyId; this.fileId = fileId; } BytesFileColumn(byte[] value, int studyId, int fileId) { super(value); this.studyId = studyId; this.fileId = fileId; } @Override public int getStudyId() { return studyId; } @Override public int getFileId() { return fileId; } @Override public PhoenixArray raw() { return (PhoenixArray) PVarcharArray.INSTANCE.toObject( valueArray, valueOffset, valueLength); } @Override public String getCallString() { return getString(HBaseToStudyEntryConverter.FILE_CALL_IDX); } @Override public List<AlternateCoordinate> getSecondaryAlternates() { String secAlt = getString(HBaseToStudyEntryConverter.FILE_SEC_ALTS_IDX); if (StringUtils.isNotEmpty(secAlt)) { return HBaseToStudyEntryConverter.getAlternateCoordinates(secAlt); } return null; } @Override public VariantOverlappingStatus getOverlappingStatus() { return VariantOverlappingStatus.valueFromShortString(getString(HBaseToStudyEntryConverter.FILE_VARIANT_OVERLAPPING_STATUS_IDX)); } @Override public Double getQual() { String qualStr = getQualString(); if (StringUtils.isNotEmpty(qualStr) && !(".").equals(qualStr)) { return Double.valueOf(qualStr); } else { return null; } } @Override public String getQualString() { return getString(HBaseToStudyEntryConverter.FILE_QUAL_IDX); } @Override public String getFilter() { return getString(HBaseToStudyEntryConverter.FILE_FILTER_IDX); } } private static class BytesStatsColumn extends BytesColumn implements StatsColumn { private final int studyId; private final int cohortId; BytesStatsColumn(Cell cell, int studyId, int cohortId) { super(cell); this.studyId = studyId; this.cohortId = cohortId; } BytesStatsColumn(byte[] value, int studyId, int cohortId) { super(value); this.studyId = studyId; this.cohortId = cohortId; } @Override public int getStudyId() { return studyId; } @Override public int getCohortId() { return cohortId; } @Override public VariantProto.VariantStats toProto() { try { return VariantProto.VariantStats.parseFrom(ByteBuffer.wrap(valueArray, valueOffset, valueLength)); } catch (InvalidProtocolBufferException e) { throw VariantQueryException.internalException(e); } } } private static class BytesVariantScoreColumn extends BytesColumn implements VariantScoreColumn { private final int studyId; private final int scoreId; BytesVariantScoreColumn(Cell cell, int studyId, int scoreId) { super(cell); this.studyId = studyId; this.scoreId = scoreId; } BytesVariantScoreColumn(byte[] value, int studyId, int scoreId) { super(value); this.studyId = studyId; this.scoreId = scoreId; } @Override public int getStudyId() { return studyId; } @Override public int getScoreId() { return scoreId; } @Override public float getScore() { return getFloat(0); } @Override public float getPValue() { return getFloat(1); } } private static class BytesVariantAnnotationColumn extends BytesColumn implements VariantAnnotationColumn { BytesVariantAnnotationColumn(Cell cell) { super(cell); } BytesVariantAnnotationColumn(byte[] value) { super(value); } } }
/* * Copyright 2004,2005 The Apache Software Foundation. * * 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.wso2.carbon.registry.ws.client.test; import org.wso2.carbon.registry.core.Comment; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.Tag; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.utils.RegistryUtils; import java.util.ArrayList; import java.util.List; public class ResourceHandling extends TestSetup { public ResourceHandling(String text) { super(text); } public void testResourceCopy() throws Exception { try { String path = "/f95/f2/r1"; String commentPath = path + RegistryConstants.URL_SEPARATOR + "comments"; String new_path = "/f96/f2/r1"; String commentPathNew = new_path + RegistryConstants.URL_SEPARATOR + "comments"; Resource r1 = registry.newResource(); r1.setDescription("This is a file to be renamed"); byte[] r1content = RegistryUtils.encodeString("R2 content"); r1.setContent(r1content); r1.setMediaType("txt"); Comment c1 = new Comment(); c1.setResourcePath(path); c1.setText("This is a test comment1"); Comment c2 = new Comment(); c2.setResourcePath(path); c2.setText("This is a test comment2"); r1.setProperty("key1", "value1"); r1.setProperty("key2", "value2"); registry.put(path, r1); registry.addComment(path, c1); registry.addComment(path, c2); registry.applyTag(path, "tag1"); registry.applyTag(path, "tag2"); registry.applyTag(path, "tag3"); registry.rateResource(path, 4); Resource r2 = registry.get(path); assertEquals("Properties are not equal", r1.getProperty("key1"), r2.getProperty("key1")); assertEquals("Properties are not equal", r1.getProperty("key2"), r2.getProperty("key2")); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) r1.getContent()), RegistryUtils.decodeBytes((byte[]) r2.getContent())); assertTrue(c1.getText() + " is not associated for resource" + path, containsComment(commentPath, c1.getText())); assertTrue(c2.getText() + " is not associated for resource" + path, containsComment(commentPath, c2.getText())); assertTrue("Tag1 is not exist", containsTag(path, "tag1")); assertTrue("Tag2 is not exist", containsTag(path, "tag2")); assertTrue("Tag3 is not exist", containsTag(path, "tag3")); float rating = registry.getAverageRating(path); assertEquals("Rating is not mathching", rating, (float) 4.0, (float) 0.01); assertEquals("Media type not exist", r1.getMediaType(), r2.getMediaType()); // assertEquals("Authour name is not exist", r1.getAuthorUserName(), r2.getAuthorUserName()); assertEquals("Description is not exist", r1.getDescription(), r2.getDescription()); String new_path_returned; new_path_returned = registry.rename(path, new_path); assertEquals("New resource path is not equal", new_path, new_path_returned); /*get renamed resource details*/ Resource r1Renamed = registry.get(new_path); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) r2.getContent()), RegistryUtils.decodeBytes((byte[]) r1Renamed.getContent())); assertEquals("Properties are not equal", r2.getProperty("key1"), r1Renamed.getProperty("key1")); assertEquals("Properties are not equal", r2.getProperty("key2"), r1Renamed.getProperty("key2")); assertTrue(c1.getText() + " is not associated for resource" + new_path, containsComment(commentPathNew, c1.getText())); assertTrue(c2.getText() + " is not associated for resource" + new_path, containsComment(commentPathNew, c2.getText())); assertTrue("Tag1 is not copied", containsTag(new_path, "tag1")); assertTrue("Tag2 is not copied", containsTag(new_path, "tag2")); assertTrue("Tag3 is not copied", containsTag(new_path, "tag3")); float rating1 = registry.getAverageRating(new_path); assertEquals("Rating is not copied", rating1, (float) 4.0, (float) 0.01); assertEquals("Media type not copied", r2.getMediaType(), r1Renamed.getMediaType()); assertEquals("Authour Name is not copied", r2.getAuthorUserName(), r1Renamed.getAuthorUserName()); assertEquals("Description is not exist", r2.getDescription(), r1Renamed.getDescription()); } catch (RegistryException e) { e.printStackTrace(); } } public void testCollectionCopy() throws Exception { try { String path = "/c9011/c1/c2"; String commentPath = path + RegistryConstants.URL_SEPARATOR + "comments"; String new_path = "/c9111/c1/c3"; String commentPathNew = new_path + RegistryConstants.URL_SEPARATOR + "comments"; Resource r1 = registry.newCollection(); r1.setDescription("This is a file to be renamed"); Comment c1 = new Comment(); c1.setResourcePath(path); c1.setText("This is first test comment"); Comment c2 = new Comment(); c2.setResourcePath(path); c2.setText("This is secound test comment"); r1.setProperty("key1", "value1"); r1.setProperty("key2", "value2"); registry.put(path, r1); registry.addComment(path, c1); registry.addComment(path, c2); registry.applyTag(path, "tag1"); registry.applyTag(path, "tag2"); registry.applyTag(path, "tag3"); registry.rateResource(path, 4); Resource r2 = registry.get(path); assertEquals("Properties are not equal", r1.getProperty("key1"), r2.getProperty("key1")); assertEquals("Properties are not equal", r1.getProperty("key2"), r2.getProperty("key2")); assertTrue(c1.getText() + " is not associated for resource" + path, containsComment(commentPath, c1.getText())); assertTrue(c2.getText() + " is not associated for resource" + path, containsComment(commentPath, c2.getText())); assertTrue("Tag1 is not copied", containsTag(path, "tag1")); assertTrue("Tag2 is not copied", containsTag(path, "tag2")); assertTrue("Tag3 is not copied", containsTag(path, "tag3")); float rating = registry.getAverageRating(path); assertEquals("Rating is not mathching", rating, (float) 4.0, (float) 0.01); // assertEquals("Authour name is not exist", r1.getAuthorUserName(), r2.getAuthorUserName()); String new_path_returned; new_path_returned = registry.rename(path, new_path); assertEquals("New resource path is not equal", new_path, new_path_returned); /*get renamed resource details*/ Resource r1Renamed = registry.get(new_path); assertEquals("Properties are not equal", r2.getProperty("key1"), r1Renamed.getProperty("key1")); assertEquals("Properties are not equal", r2.getProperty("key2"), r1Renamed.getProperty("key2")); assertTrue(c1.getText() + " is not associated for resource" + new_path, containsComment(commentPathNew, c1.getText())); assertTrue(c2.getText() + " is not associated for resource" + new_path, containsComment(commentPathNew, c2.getText())); assertTrue("Tag1 is not copied", containsTag(new_path, "tag1")); assertTrue("Tag2 is not copied", containsTag(new_path, "tag2")); assertTrue("Tag3 is not copied", containsTag(new_path, "tag3")); float rating1 = registry.getAverageRating(new_path); assertEquals("Rating is not copied", rating1, (float) 4.0, (float) 0.01); // assertEquals("Author Name is not copied", r1.getAuthorUserName(), r2.getAuthorUserName()); } catch (RegistryException e) { e.printStackTrace(); } } public void testGetResourceoperation() throws Exception { Resource r2 = registry.newResource(); String path = "/testk/testa/derby.log"; r2.setContent(RegistryUtils.encodeString("this is the content")); r2.setDescription("this is test desc this is test desc this is test desc this is test desc this is test desc " + "this is test desc this is test desc this is test desc this is test descthis is test desc "); r2.setMediaType("plain/text"); registry.put(path, r2); r2.discard(); Resource r3 = registry.newResource(); // assertEquals("Author names are not Equal", "admin", r3.getAuthorUserName()); r3 = registry.get(path); assertEquals("Author User names are not Equal", "admin", r3.getAuthorUserName()); assertNotNull("Created time is null", r3.getCreatedTime()); assertEquals("Author User names are not Equal", "admin", r3.getAuthorUserName()); assertEquals("Description is not Equal", "this is test desc this is test desc this is test desc this is test" + " desc this is test desc this is test desc this is test desc this is test desc this is test descthis is " + "test desc ", r3.getDescription()); assertNotNull("Get Id is null", r3.getId()); assertNotNull("LastModifiedDate is null", r3.getLastModified()); assertEquals("Last Updated names are not Equal", "admin", r3.getLastUpdaterUserName()); //System.out.println(r3.getMediaType()); assertEquals("Media Type is not equal", "plain/text", r3.getMediaType()); assertEquals("parent Path is not equal", "/testk/testa", r3.getParentPath()); assertEquals("parent Path is not equal", path, r3.getPath()); assertEquals("Get stated wrong", 0, r3.getState()); String st = r3.getPermanentPath(); // assertTrue("Permenent path contanin the string" + path + " verion", st.contains("/testk/testa/derby.log;version:")); } public void testGetCollectionoperation() throws Exception { Resource r2 = registry.newCollection(); String path = "/testk2/testa/testc"; r2.setDescription("this is test desc"); r2.setProperty("test2", "value2"); registry.put(path, r2); r2.discard(); Resource r3 = registry.get(path); // assertEquals("Author names are not Equal", "admin", r3.getAuthorUserName()); // assertEquals("Author User names are not Equal", "admin", r3.getAuthorUserName()); // System.out.println(r3.getCreatedTime()); //assertNotNull("Created time is null", r3.getCreatedTime()); // assertEquals("Author User names are not Equal", "admin", r3.getAuthorUserName()); //System.out.println("Desc" + r3.getDescription()); //assertEquals("Description is not Equal", "this is test desc", r3.getDescription()); assertNotNull("Get Id is null", r3.getId()); assertNotNull("LastModifiedDate is null", r3.getLastModified()); assertEquals("Last Updated names are not Equal", "admin", r3.getLastUpdaterUserName()); //System.out.println("Media Type:" + r3.getMediaType()); //assertEquals("Media Type is not equal","unknown",r3.getMediaType()); assertEquals("parent Path is not equal", "/testk2/testa", r3.getParentPath()); assertEquals("Get stated wrong", 0, r3.getState()); registry.createVersion(path); // System.out.println(r3.getParentPath()); // System.out.println(r3.getPath()); assertEquals("Permenent path doesn't contanin the string", "/testk2/testa", r3.getParentPath()); assertEquals("Path doesn't contanin the string", path, r3.getPath()); // String st = r3.getPermanentPath(); // assertTrue("Permenent path contanin the string" + path +" verion", st.contains("/testk2/testa/testc;version:")); } private boolean containsComment(String pathValue, String commentText) throws Exception { Comment[] commentsArray = null; List commentTexts = new ArrayList(); try { Resource commentsResource = registry.get(pathValue); commentsArray = (Comment[]) commentsResource.getContent(); for (Comment comment : commentsArray) { Resource commentResource = registry.get(comment.getPath()); commentTexts.add(commentResource.getContent()); } } catch (RegistryException e) { e.printStackTrace(); } boolean found = false; if (commentTexts.contains(commentText)) { found = true; } return found; } private boolean containsTag(String tagPath, String tagText) throws Exception { Tag[] tags = null; try { tags = registry.getTags(tagPath); } catch (RegistryException e) { e.printStackTrace(); } boolean tagFound = false; for (int i = 0; i < tags.length; i++) { if (tags[i].getTagName().equals(tagText)) { tagFound = true; break; } } return tagFound; } private boolean containsString(String[] array, String value) { boolean found = false; for (String anArray : array) { if (anArray.startsWith(value)) { found = true; break; } } return found; } }
package net.minidev.json; /* * Copyright 2011 JSON-SMART 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. */ import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Stack; import net.minidev.json.writer.JsonReaderI; /** * A JQuery like Json editor, accessor. * * @since 1.0.9 * * @author Uriel Chemouni &lt;uchemouni@gmail.com&gt; */ public class JSONNavi<T> { private JsonReaderI<? super T> mapper; private T root; private Stack<Object> stack = new Stack<Object>(); private Stack<Object> path = new Stack<Object>(); private Object current; private boolean failure = false; private String failureMessage; private boolean readonly = false; private Object missingKey = null; public static JSONNavi<JSONAwareEx> newInstance() { return new JSONNavi<JSONAwareEx>(JSONValue.defaultReader.DEFAULT_ORDERED); } public static JSONNavi<JSONObject> newInstanceObject() { JSONNavi<JSONObject> o = new JSONNavi<JSONObject>(JSONValue.defaultReader.getMapper(JSONObject.class)); o.object(); return o; } public static JSONNavi<JSONArray> newInstanceArray() { JSONNavi<JSONArray> o = new JSONNavi<JSONArray>(JSONValue.defaultReader.getMapper(JSONArray.class)); o.array(); return o; } public JSONNavi(JsonReaderI<? super T> mapper) { this.mapper = mapper; } @SuppressWarnings("unchecked") public JSONNavi(String json) { this.root = (T) JSONValue.parse(json); this.current = this.root; readonly = true; } public JSONNavi(String json, JsonReaderI<T> mapper) { this.root = JSONValue.parse(json, mapper); this.mapper = mapper; this.current = this.root; readonly = true; } public JSONNavi(String json, Class<T> mapTo) { this.root = JSONValue.parse(json, mapTo); this.mapper = JSONValue.defaultReader.getMapper(mapTo); this.current = this.root; readonly = true; } /** * return to root node * * @return the root node */ public JSONNavi<T> root() { this.current = this.root; this.stack.clear(); this.path.clear(); this.failure = false; this.missingKey = null; this.failureMessage = null; return this; } public boolean hasFailure() { return failure; } public Object getCurrentObject() { return current; } @SuppressWarnings({ "unchecked", "rawtypes" }) public Collection<String> getKeys() { if (current instanceof Map) return ((Map) current).keySet(); return null; } public int getSize() { if (current == null) return 0; if (isArray()) return ((List<?>) current).size(); if (isObject()) return ((Map<?, ?>) current).size(); return 1; } public String getString(String key) { String v = null; if (!hasKey(key)) return v; at(key); v = asString(); up(); return v; } public int getInt(String key) { int v = 0; if (!hasKey(key)) return v; at(key); v = asInt(); up(); return v; } public Integer getInteger(String key) { Integer v = null; if (!hasKey(key)) return v; at(key); v = asIntegerObj(); up(); return v; } public double getDouble(String key) { double v = 0; if (!hasKey(key)) return v; at(key); v = asDouble(); up(); return v; } public boolean hasKey(String key) { if (!isObject()) return false; return o(current).containsKey(key); } public JSONNavi<?> at(String key) { if (failure) return this; if (!isObject()) object(); if (!(current instanceof Map)) return failure("current node is not an Object", key); if (!o(current).containsKey(key)) { if (readonly) return failure("current Object have no key named " + key, key); stack.add(current); path.add(key); current = null; missingKey = key; return this; } Object next = o(current).get(key); stack.add(current); path.add(key); current = next; return this; } public Object get(String key) { if (failure) return this; if (!isObject()) object(); if (!(current instanceof Map)) return failure("current node is not an Object", key); return o(current).get(key); } public Object get(int index) { if (failure) return this; if (!isArray()) array(); if (!(current instanceof List)) return failure("current node is not an List", index); return a(current).get(index); } public JSONNavi<T> set(String key, String value) { object(); if (failure) return this; o(current).put(key, value); return this; } public JSONNavi<T> set(String key, Number value) { object(); if (failure) return this; o(current).put(key, value); return this; } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi<T> set(String key, long value) { return set(key, Long.valueOf(value)); } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi<T> set(String key, int value) { return set(key, Integer.valueOf(value)); } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi<T> set(String key, double value) { return set(key, Double.valueOf(value)); } /** * write an value in the current object * * @param key * key to access * @param value * new value * @return this */ public JSONNavi<T> set(String key, float value) { return set(key, Float.valueOf(value)); } /** * add value to the current arrays * * @param values * to add * @return this */ public JSONNavi<T> add(Object... values) { array(); if (failure) return this; List<Object> list = a(current); for (Object o : values) list.add(o); return this; } /** * get the current object value as String if the current Object is null * return null. * * @return value as string */ public String asString() { if (current == null) return null; if (current instanceof String) return (String) current; return current.toString(); } /** * get the current value as double if the current Object is null return * Double.NaN * * @return value as double */ public double asDouble() { if (current instanceof Number) return ((Number) current).doubleValue(); return Double.NaN; } /** * get the current object value as Double if the current Double can not be * cast as Integer return null. * * @return value as Double */ public Double asDoubleObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Double) return (Double) current; return Double.valueOf(((Number) current).doubleValue()); } return Double.NaN; } /** * get the current value as float if the current Object is null return * Float.NaN * * @return value as float */ public float asFloat() { if (current instanceof Number) return ((Number) current).floatValue(); return Float.NaN; } /** * get the current object value as Float if the current Float can not be * cast as Integer return null. */ public Float asFloatObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Float) return (Float) current; return Float.valueOf(((Number) current).floatValue()); } return Float.NaN; } /** * get the current value as int if the current Object is null return 0 * * @return value as Int */ public int asInt() { if (current instanceof Number) return ((Number) current).intValue(); return 0; } /** * get the current object value as Integer if the current Object can not be * cast as Integer return null. * @return the current node value as an Integer */ public Integer asIntegerObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Integer) return (Integer) current; if (current instanceof Long) { Long l = (Long) current; if (l.longValue() == l.intValue()) { return Integer.valueOf(l.intValue()); } } return null; } return null; } /** * get the current value as long if the current Object is null return 0 * * @return value as long */ public long asLong() { if (current instanceof Number) return ((Number) current).longValue(); return 0L; } /** * get the current object value as Long if the current Object can not be * cast as Long return null. * * @return value as Long */ public Long asLongObj() { if (current == null) return null; if (current instanceof Number) { if (current instanceof Long) return (Long) current; if (current instanceof Integer) return Long.valueOf(((Number) current).longValue()); return null; } return null; } /** * get the current value as boolean if the current Object is null or is not * a boolean return false * * @return boolean */ public boolean asBoolean() { if (current instanceof Boolean) return ((Boolean) current).booleanValue(); return false; } /** * get the current object value as Boolean if the current Object is not a * Boolean return null. * * @return Boolean object */ public Boolean asBooleanObj() { if (current == null) return null; if (current instanceof Boolean) return (Boolean) current; return null; } /** * Set current value as Json Object You can also skip this call, Objects can * be create automatically. * @return the current node as an object */ @SuppressWarnings("unchecked") public JSONNavi<T> object() { if (failure) return this; if (current == null && readonly) failure("Can not create Object child in readonly", null); if (current != null) { if (isObject()) return this; if (isArray()) failure("can not use Object feature on Array.", null); failure("Can not use current position as Object", null); } else { current = mapper.createObject(); } if (root == null) root = (T) current; else store(); return this; } /** * Set current value as Json Array You can also skip this call Arrays can be * create automatically. * * @return the current node as an array */ @SuppressWarnings("unchecked") public JSONNavi<T> array() { if (failure) return this; if (current == null && readonly) failure("Can not create Array child in readonly", null); if (current != null) { if (isArray()) return this; if (isObject()) failure("can not use Object feature on Array.", null); failure("Can not use current position as Object", null); } else { current = mapper.createArray(); } if (root == null) root = (T) current; else store(); return this; } /** * set current value as Number * @param num new value for the current node * @return this for code chaining */ public JSONNavi<T> set(Number num) { if (failure) return this; current = num; store(); return this; } /** * set current value as Boolean * @param bool new value for the current node * * @return this for code chaining */ public JSONNavi<T> set(Boolean bool) { if (failure) return this; current = bool; store(); return this; } /** * set current value as String * @param text text value * * @return this for code chaining */ public JSONNavi<T> set(String text) { if (failure) return this; current = text; store(); return this; } public T getRoot() { return root; } /** * internal store current Object in current non existing localization */ private void store() { Object parent = stack.peek(); if (isObject(parent)) o(parent).put((String) missingKey, current); else if (isArray(parent)) { int index = ((Number) missingKey).intValue(); List<Object> lst = a(parent); while (lst.size() <= index) lst.add(null); lst.set(index, current); } } /** * is the current node is an array * * @return true if the current node is an array */ public boolean isArray() { return isArray(current); } /** * is the current node is an object * * @return true if the current node is an object */ public boolean isObject() { return isObject(current); } /** * check if Object is an Array * * @return true if the object is an array */ private boolean isArray(Object obj) { if (obj == null) return false; return (obj instanceof List); } /** * check if Object is an Map * @return true if the object node is an object */ private boolean isObject(Object obj) { if (obj == null) return false; return (obj instanceof Map); } /** * internal cast to List * @return casted object */ @SuppressWarnings("unchecked") private List<Object> a(Object obj) { return (List<Object>) obj; } /** * internal cast to Map */ @SuppressWarnings("unchecked") private Map<String, Object> o(Object obj) { return (Map<String, Object>) obj; } /** * Access to the index position. * * If index is less than 0 access element index from the end like in python. * * @param index * 0 based desired position in Array */ public JSONNavi<?> at(int index) { if (failure) return this; if (!(current instanceof List)) return failure("current node is not an Array", index); @SuppressWarnings("unchecked") List<Object> lst = ((List<Object>) current); if (index < 0) { index = lst.size() + index; if (index < 0) index = 0; } if (index >= lst.size()) if (readonly) return failure("Out of bound exception for index", index); else { stack.add(current); path.add(index); current = null; missingKey = index; return this; } Object next = lst.get(index); stack.add(current); path.add(index); current = next; return this; } /** * Access to last + 1 the index position. * * this method can only be used in writing mode. */ public JSONNavi<?> atNext() { if (failure) return this; if (!(current instanceof List)) return failure("current node is not an Array", null); @SuppressWarnings("unchecked") List<Object> lst = ((List<Object>) current); return at(lst.size()); } /** * call up() level times. * * @param level * number of parent move. */ public JSONNavi<?> up(int level) { while (level-- > 0) { if (stack.size() > 0) { current = stack.pop(); path.pop(); } else break; } return this; } /** * Move one level up in Json tree. if no more level up is available the * statement had no effect. */ public JSONNavi<?> up() { if (stack.size() > 0) { current = stack.pop(); path.pop(); } return this; } private final static JSONStyle ERROR_COMPRESS = new JSONStyle(JSONStyle.FLAG_PROTECT_4WEB); /** * return the Object as a Json String */ public String toString() { if (failure) return JSONValue.toJSONString(failureMessage, ERROR_COMPRESS); return JSONValue.toJSONString(root); } /** * return the Object as a Json String * * @param compression */ public String toString(JSONStyle compression) { if (failure) return JSONValue.toJSONString(failureMessage, compression); return JSONValue.toJSONString(root, compression); } /** * Internally log errors. */ private JSONNavi<?> failure(String err, Object jPathPostfix) { failure = true; StringBuilder sb = new StringBuilder(); sb.append("Error: "); sb.append(err); sb.append(" at "); sb.append(getJPath()); if (jPathPostfix != null) if (jPathPostfix instanceof Integer) sb.append('[').append(jPathPostfix).append(']'); else sb.append('/').append(jPathPostfix); this.failureMessage = sb.toString(); return this; } /** * @return JPath to the current position */ public String getJPath() { StringBuilder sb = new StringBuilder(); for (Object o : path) { if (o instanceof String) sb.append('/').append(o.toString()); else sb.append('[').append(o.toString()).append(']'); } return sb.toString(); } }
/* * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle 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. */ /* * This source code is provided to illustrate the usage of a given feature * or technique and has been deliberately simplified. Additional steps * required for a production-quality application, such as security checks, * input validation and proper error handling, might not be present in * this sample code. */ import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; import java.awt.event.*; import java.io.*; import java.net.URL; /* A set of classes to parse, represent and display 3D wireframe models represented in Wavefront .obj format. */ @SuppressWarnings("serial") class FileFormatException extends Exception { public FileFormatException(String s) { super(s); } } /** The representation of a 3D model */ final class Model3D { float vert[]; int tvert[]; int nvert, maxvert; int con[]; int ncon, maxcon; boolean transformed; Matrix3D mat; float xmin, xmax, ymin, ymax, zmin, zmax; Model3D() { mat = new Matrix3D(); mat.xrot(20); mat.yrot(30); } /** Create a 3D model by parsing an input stream */ Model3D(InputStream is) throws IOException, FileFormatException { this(); StreamTokenizer st = new StreamTokenizer( new BufferedReader(new InputStreamReader(is, "UTF-8"))); st.eolIsSignificant(true); st.commentChar('#'); scan: while (true) { switch (st.nextToken()) { default: break scan; case StreamTokenizer.TT_EOL: break; case StreamTokenizer.TT_WORD: if ("v".equals(st.sval)) { double x = 0, y = 0, z = 0; if (st.nextToken() == StreamTokenizer.TT_NUMBER) { x = st.nval; if (st.nextToken() == StreamTokenizer.TT_NUMBER) { y = st.nval; if (st.nextToken() == StreamTokenizer.TT_NUMBER) { z = st.nval; } } } addVert((float) x, (float) y, (float) z); while (st.ttype != StreamTokenizer.TT_EOL && st.ttype != StreamTokenizer.TT_EOF) { st.nextToken(); } } else if ("f".equals(st.sval) || "fo".equals(st.sval) || "l". equals(st.sval)) { int start = -1; int prev = -1; int n = -1; while (true) { if (st.nextToken() == StreamTokenizer.TT_NUMBER) { n = (int) st.nval; if (prev >= 0) { add(prev - 1, n - 1); } if (start < 0) { start = n; } prev = n; } else if (st.ttype == '/') { st.nextToken(); } else { break; } } if (start >= 0) { add(start - 1, prev - 1); } if (st.ttype != StreamTokenizer.TT_EOL) { break scan; } } else { while (st.nextToken() != StreamTokenizer.TT_EOL && st.ttype != StreamTokenizer.TT_EOF) { // no-op } } } } is.close(); if (st.ttype != StreamTokenizer.TT_EOF) { throw new FileFormatException(st.toString()); } } /** Add a vertex to this model */ int addVert(float x, float y, float z) { int i = nvert; if (i >= maxvert) { if (vert == null) { maxvert = 100; vert = new float[maxvert * 3]; } else { maxvert *= 2; float nv[] = new float[maxvert * 3]; System.arraycopy(vert, 0, nv, 0, vert.length); vert = nv; } } i *= 3; vert[i] = x; vert[i + 1] = y; vert[i + 2] = z; return nvert++; } /** Add a line from vertex p1 to vertex p2 */ void add(int p1, int p2) { int i = ncon; if (p1 >= nvert || p2 >= nvert) { return; } if (i >= maxcon) { if (con == null) { maxcon = 100; con = new int[maxcon]; } else { maxcon *= 2; int nv[] = new int[maxcon]; System.arraycopy(con, 0, nv, 0, con.length); con = nv; } } if (p1 > p2) { int t = p1; p1 = p2; p2 = t; } con[i] = (p1 << 16) | p2; ncon = i + 1; } /** Transform all the points in this model */ void transform() { if (transformed || nvert <= 0) { return; } if (tvert == null || tvert.length < nvert * 3) { tvert = new int[nvert * 3]; } mat.transform(vert, tvert, nvert); transformed = true; } /* Quick Sort implementation */ private void quickSort(int a[], int left, int right) { int leftIndex = left; int rightIndex = right; int partionElement; if (right > left) { /* Arbitrarily establishing partition element as the midpoint of * the array. */ partionElement = a[(left + right) / 2]; // loop through the array until indices cross while (leftIndex <= rightIndex) { /* find the first element that is greater than or equal to * the partionElement starting from the leftIndex. */ while ((leftIndex < right) && (a[leftIndex] < partionElement)) { ++leftIndex; } /* find an element that is smaller than or equal to * the partionElement starting from the rightIndex. */ while ((rightIndex > left) && (a[rightIndex] > partionElement)) { --rightIndex; } // if the indexes have not crossed, swap if (leftIndex <= rightIndex) { swap(a, leftIndex, rightIndex); ++leftIndex; --rightIndex; } } /* If the right index has not reached the left side of array * must now sort the left partition. */ if (left < rightIndex) { quickSort(a, left, rightIndex); } /* If the left index has not reached the right side of array * must now sort the right partition. */ if (leftIndex < right) { quickSort(a, leftIndex, right); } } } private void swap(int a[], int i, int j) { int T; T = a[i]; a[i] = a[j]; a[j] = T; } /** eliminate duplicate lines */ void compress() { int limit = ncon; int c[] = con; quickSort(con, 0, ncon - 1); int d = 0; int pp1 = -1; for (int i = 0; i < limit; i++) { int p1 = c[i]; if (pp1 != p1) { c[d] = p1; d++; } pp1 = p1; } ncon = d; } static Color gr[]; /** Paint this model to a graphics context. It uses the matrix associated with this model to map from model space to screen space. The next version of the browser should have double buffering, which will make this *much* nicer */ void paint(Graphics g) { if (vert == null || nvert <= 0) { return; } transform(); if (gr == null) { gr = new Color[16]; for (int i = 0; i < 16; i++) { int grey = (int) (170 * (1 - Math.pow(i / 15.0, 2.3))); gr[i] = new Color(grey, grey, grey); } } int lg = 0; int lim = ncon; int c[] = con; int v[] = tvert; if (lim <= 0 || nvert <= 0) { return; } for (int i = 0; i < lim; i++) { int T = c[i]; int p1 = ((T >> 16) & 0xFFFF) * 3; int p2 = (T & 0xFFFF) * 3; int grey = v[p1 + 2] + v[p2 + 2]; if (grey < 0) { grey = 0; } if (grey > 15) { grey = 15; } if (grey != lg) { lg = grey; g.setColor(gr[grey]); } g.drawLine(v[p1], v[p1 + 1], v[p2], v[p2 + 1]); } } /** Find the bounding box of this model */ void findBB() { if (nvert <= 0) { return; } float v[] = vert; float _xmin = v[0], _xmax = _xmin; float _ymin = v[1], _ymax = _ymin; float _zmin = v[2], _zmax = _zmin; for (int i = nvert * 3; (i -= 3) > 0;) { float x = v[i]; if (x < _xmin) { _xmin = x; } if (x > _xmax) { _xmax = x; } float y = v[i + 1]; if (y < _ymin) { _ymin = y; } if (y > _ymax) { _ymax = y; } float z = v[i + 2]; if (z < _zmin) { _zmin = z; } if (z > _zmax) { _zmax = z; } } this.xmax = _xmax; this.xmin = _xmin; this.ymax = _ymax; this.ymin = _ymin; this.zmax = _zmax; this.zmin = _zmin; } } /** An applet to put a 3D model into a page */ @SuppressWarnings("serial") public class ThreeD extends Applet implements Runnable, MouseListener, MouseMotionListener { Model3D md; boolean painted = true; float xfac; int prevx, prevy; float scalefudge = 1; Matrix3D amat = new Matrix3D(), tmat = new Matrix3D(); String mdname = null; String message = null; @Override public void init() { mdname = getParameter("model"); try { scalefudge = Float.valueOf(getParameter("scale")).floatValue(); } catch (Exception ignored) { // fall back to default scalefudge = 1 } amat.yrot(20); amat.xrot(20); if (mdname == null) { mdname = "model.obj"; } resize(getSize().width <= 20 ? 400 : getSize().width, getSize().height <= 20 ? 400 : getSize().height); addMouseListener(this); addMouseMotionListener(this); } @Override public void destroy() { removeMouseListener(this); removeMouseMotionListener(this); } @Override public void run() { InputStream is = null; try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); is = getClass().getResourceAsStream(mdname); Model3D m = new Model3D(is); md = m; m.findBB(); m.compress(); float xw = m.xmax - m.xmin; float yw = m.ymax - m.ymin; float zw = m.zmax - m.zmin; if (yw > xw) { xw = yw; } if (zw > xw) { xw = zw; } float f1 = getSize().width / xw; float f2 = getSize().height / xw; xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge; } catch (Exception e) { md = null; message = e.toString(); } try { if (is != null) { is.close(); } } catch (Exception e) { } repaint(); } @Override public void start() { if (md == null && message == null) { new Thread(this).start(); } } @Override public void stop() { } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { prevx = e.getX(); prevy = e.getY(); e.consume(); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); tmat.unit(); float xtheta = (prevy - y) * 360.0f / getSize().width; float ytheta = (x - prevx) * 360.0f / getSize().height; tmat.xrot(xtheta); tmat.yrot(ytheta); amat.mult(tmat); if (painted) { painted = false; repaint(); } prevx = x; prevy = y; e.consume(); } @Override public void mouseMoved(MouseEvent e) { } @Override public void paint(Graphics g) { if (md != null) { md.mat.unit(); md.mat.translate(-(md.xmin + md.xmax) / 2, -(md.ymin + md.ymax) / 2, -(md.zmin + md.zmax) / 2); md.mat.mult(amat); md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width); md.mat.translate(getSize().width / 2, getSize().height / 2, 8); md.transformed = false; md.paint(g); setPainted(); } else if (message != null) { g.drawString("Error in model:", 3, 20); g.drawString(message, 10, 40); } } private synchronized void setPainted() { painted = true; notifyAll(); } @Override public String getAppletInfo() { return "Title: ThreeD \nAuthor: James Gosling? \n" + "An applet to put a 3D model into a page."; } @Override public String[][] getParameterInfo() { String[][] info = { { "model", "path string", "The path to the model to be displayed." }, { "scale", "float", "The scale of the model. Default is 1." } }; return info; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.network; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.advisory.AdvisoryBroker; import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.broker.region.DestinationStatistics; import org.apache.activemq.broker.region.virtual.CompositeTopic; import org.apache.activemq.broker.region.virtual.VirtualDestination; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.CommandTypes; import org.apache.activemq.plugin.java.JavaRuntimeConfigurationBroker; import org.apache.activemq.plugin.java.JavaRuntimeConfigurationPlugin; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.store.kahadb.disk.journal.Journal.JournalDiskSyncStrategy; import org.apache.activemq.util.Wait; import org.apache.activemq.util.Wait.Condition; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; @RunWith(Parameterized.class) public class DurableSyncNetworkBridgeTest extends DynamicNetworkTestSupport { protected static final Logger LOG = LoggerFactory.getLogger(DurableSyncNetworkBridgeTest.class); protected JavaRuntimeConfigurationBroker remoteRuntimeBroker; protected String staticIncludeTopics = "include.static.test"; protected String includedTopics = "include.test.>"; protected String testTopicName2 = "include.test.bar2"; private boolean dynamicOnly = false; private boolean forceDurable = false; private boolean useVirtualDestSubs = false; private byte remoteBrokerWireFormatVersion = CommandTypes.PROTOCOL_VERSION; public static enum FLOW {FORWARD, REVERSE} private BrokerService broker1; private BrokerService broker2; private Session session1; private Session session2; private final FLOW flow; @Rule public Timeout globalTimeout = new Timeout(30, TimeUnit.SECONDS); @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {FLOW.FORWARD}, {FLOW.REVERSE} }); } public static final String KEYSTORE_TYPE = "jks"; public static final String PASSWORD = "password"; public static final String SERVER_KEYSTORE = "src/test/resources/server.keystore"; public static final String TRUST_KEYSTORE = "src/test/resources/client.keystore"; static { System.setProperty("javax.net.ssl.trustStore", TRUST_KEYSTORE); System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD); System.setProperty("javax.net.ssl.trustStoreType", KEYSTORE_TYPE); System.setProperty("javax.net.ssl.keyStore", SERVER_KEYSTORE); System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE); System.setProperty("javax.net.ssl.keyStorePassword", PASSWORD); } public DurableSyncNetworkBridgeTest(final FLOW flow) { this.flow = flow; } @Before public void setUp() throws Exception { includedTopics = "include.test.>"; staticIncludeTopics = "include.static.test"; dynamicOnly = false; forceDurable = false; useVirtualDestSubs = false; remoteBrokerWireFormatVersion = CommandTypes.PROTOCOL_VERSION; doSetUp(true, true, tempFolder.newFolder(), tempFolder.newFolder()); } @After public void tearDown() throws Exception { doTearDown(); } @Test public void testRemoveSubscriptionPropagate() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); MessageConsumer sub1 = session1.createDurableSubscriber(topic, subName); sub1.close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); removeSubscription(broker1, topic, subName); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); } @Test public void testRemoveSubscriptionPropegateAfterRestart() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); MessageConsumer sub1 = session1.createDurableSubscriber(topic, subName); sub1.close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); restartBrokers(true); assertBridgeStarted(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); removeSubscription(broker1, topic, subName); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); } @Test public void testRemoveSubscriptionWithBridgeOffline() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); MessageConsumer sub1 = session1.createDurableSubscriber(topic, subName); sub1.close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); doTearDown(); restartBroker(broker1, false); restartBroker(broker2, false); //Send some messages to the NC sub and make sure it can still be deleted MessageProducer prod = session2.createProducer(topic); for (int i = 0; i < 10; i++) { prod.send(session2.createTextMessage("test")); } assertSubscriptionsCount(broker1, topic, 1); removeSubscription(broker1, topic, subName); assertSubscriptionsCount(broker1, topic, 0); doTearDown(); //Test that on successful reconnection of the bridge that //the NC sub will be removed restartBroker(broker2, true); assertNCDurableSubsCount(broker2, topic, 1); restartBroker(broker1, true); assertBridgeStarted(); assertNCDurableSubsCount(broker2, topic, 0); } @Test public void testRemoveSubscriptionWithBridgeOfflineIncludedChanged() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); MessageConsumer sub1 = session1.createDurableSubscriber(topic, subName); sub1.close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); doTearDown(); //change the included topics to make sure we still cleanup non-matching NC durables includedTopics = "different.topic"; restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 1); removeSubscription(broker1, topic, subName); assertSubscriptionsCount(broker1, topic, 0); //Test that on successful reconnection of the bridge that //the NC sub will be removed restartBroker(broker2, true); assertNCDurableSubsCount(broker2, topic, 1); restartBroker(broker1, true); assertBridgeStarted(); assertNCDurableSubsCount(broker2, topic, 0); } @Test public void testSubscriptionRemovedAfterIncludedChanged() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); MessageConsumer sub1 = session1.createDurableSubscriber(topic, subName); sub1.close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); doTearDown(); //change the included topics to make sure we still cleanup non-matching NC durables includedTopics = "different.topic"; restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 1); //Test that on successful reconnection of the bridge that //the NC sub will be removed because even though the local subscription exists, //it no longer matches the included filter restartBroker(broker2, true); assertNCDurableSubsCount(broker2, topic, 1); restartBroker(broker1, true); assertBridgeStarted(); assertNCDurableSubsCount(broker2, topic, 0); assertSubscriptionsCount(broker1, topic, 1); } @Test public void testSubscriptionRemovedAfterStaticChanged() throws Exception { forceDurable = true; this.restartBrokers(true); final ActiveMQTopic topic = new ActiveMQTopic(this.staticIncludeTopics); MessageConsumer sub1 = session1.createDurableSubscriber(topic, subName); sub1.close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); doTearDown(); //change the included topics to make sure we still cleanup non-matching NC durables staticIncludeTopics = "different.topic"; this.restartBrokers(false); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); //Send some messages to the NC sub and make sure it can still be deleted MessageProducer prod = session2.createProducer(topic); for (int i = 0; i < 10; i++) { prod.send(session2.createTextMessage("test")); } //Test that on successful reconnection of the bridge that //the NC sub will be removed because even though the local subscription exists, //it no longer matches the included static filter restartBroker(broker2, true); assertNCDurableSubsCount(broker2, topic, 1); restartBroker(broker1, true); assertBridgeStarted(); assertNCDurableSubsCount(broker2, topic, 0); assertSubscriptionsCount(broker1, topic, 1); } @Test public void testAddAndRemoveSubscriptionWithBridgeOfflineMultiTopics() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); final ActiveMQTopic topic2 = new ActiveMQTopic(testTopicName2); MessageConsumer sub1 = session1.createDurableSubscriber(topic, subName); sub1.close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); doTearDown(); restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 1); session1.createDurableSubscriber(topic2, "sub2"); removeSubscription(broker1, topic, subName); assertSubscriptionsCount(broker1, topic, 0); assertSubscriptionsCount(broker1, topic2, 1); //Test that on successful reconnection of the bridge that //the NC sub will be removed for topic1 but will stay for topic2 //before sync, the old NC should exist restartBroker(broker2, true); assertNCDurableSubsCount(broker2, topic, 1); assertNCDurableSubsCount(broker2, topic2, 0); //After sync, remove old NC and create one for topic 2 restartBroker(broker1, true); assertBridgeStarted(); assertNCDurableSubsCount(broker2, topic, 0); assertNCDurableSubsCount(broker2, topic2, 1); } @Test public void testAddSubscriptionsWithBridgeOffline() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); final ActiveMQTopic topic2 = new ActiveMQTopic(testTopicName2); final ActiveMQTopic excludeTopic = new ActiveMQTopic(excludeTopicName); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); doTearDown(); restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 0); //add three subs, should only create 2 NC subs because of conduit session1.createDurableSubscriber(topic, subName).close(); session1.createDurableSubscriber(topic, "sub2").close(); session1.createDurableSubscriber(topic2, "sub3").close(); assertSubscriptionsCount(broker1, topic, 2); assertSubscriptionsCount(broker1, topic2, 1); restartBrokers(true); assertBridgeStarted(); assertNCDurableSubsCount(broker2, topic, 1); assertNCDurableSubsCount(broker2, topic2, 1); assertNCDurableSubsCount(broker2, excludeTopic, 0); } @Test public void testSyncLoadTest() throws Exception { String subName = this.subName; //Create 1000 subs for (int i = 0; i < 100; i++) { for (int j = 0; j < 10; j++) { session1.createDurableSubscriber(new ActiveMQTopic("include.test." + i), subName + i + j).close(); } } for (int i = 0; i < 100; i++) { assertNCDurableSubsCount(broker2, new ActiveMQTopic("include.test." + i), 1); } doTearDown(); restartBroker(broker1, false); //with bridge off, remove 100 subs for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { removeSubscription(broker1, new ActiveMQTopic("include.test." + i), subName + i + j); } } //restart test that 900 are resynced and 100 are deleted restartBrokers(true); for (int i = 0; i < 10; i++) { assertNCDurableSubsCount(broker2, new ActiveMQTopic("include.test." + i), 0); } for (int i = 10; i < 100; i++) { assertNCDurableSubsCount(broker2, new ActiveMQTopic("include.test." + i), 1); } assertBridgeStarted(); } /** * Using an older version of openwire should not sync but the network bridge * should still start without error */ @Test public void testAddSubscriptionsWithBridgeOfflineOpenWire11() throws Exception { this.remoteBrokerWireFormatVersion = CommandTypes.PROTOCOL_VERSION_DURABLE_SYNC - 1; final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); doTearDown(); restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 0); session1.createDurableSubscriber(topic, subName).close(); assertSubscriptionsCount(broker1, topic, 1); //Since we are using an old version of openwire, the NC should //not be added restartBrokers(true); assertNCDurableSubsCount(broker2, topic, 0); assertBridgeStarted(); } @Test public void testAddOfflineSubscriptionWithBridgeOfflineDynamicTrue() throws Exception { //set dynamicOnly to true this.dynamicOnly = true; final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); doTearDown(); restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 0); session1.createDurableSubscriber(topic, subName).close(); assertSubscriptionsCount(broker1, topic, 1); restartBrokers(true); assertNCDurableSubsCount(broker2, topic, 0); assertBridgeStarted(); } @Test public void testAddOnlineSubscriptionWithBridgeOfflineDynamicTrue() throws Exception { //set dynamicOnly to true this.dynamicOnly = true; final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); doTearDown(); restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 0); session1.createDurableSubscriber(topic, subName).close(); assertSubscriptionsCount(broker1, topic, 1); restartBrokers(true); assertNCDurableSubsCount(broker2, topic, 0); //bring online again session1.createDurableSubscriber(topic, subName); assertNCDurableSubsCount(broker2, topic, 1); assertBridgeStarted(); } @Test public void testAddAndRemoveSubscriptionsWithBridgeOffline() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); final ActiveMQTopic excludeTopic = new ActiveMQTopic(excludeTopicName); session1.createDurableSubscriber(topic, subName).close(); assertSubscriptionsCount(broker1, topic, 1); assertNCDurableSubsCount(broker2, topic, 1); doTearDown(); restartBroker(broker1, false); assertSubscriptionsCount(broker1, topic, 1); removeSubscription(broker1, topic, subName); session1.createDurableSubscriber(topic, "sub2").close(); assertSubscriptionsCount(broker1, topic, 1); restartBrokers(true); assertNCDurableSubsCount(broker2, topic, 1); assertNCDurableSubsCount(broker2, excludeTopic, 0); assertBridgeStarted(); } @Test public void testAddOnlineSubscriptionsWithBridgeOffline() throws Exception { Assume.assumeTrue(flow == FLOW.FORWARD); final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); final ActiveMQTopic excludeTopic = new ActiveMQTopic(excludeTopicName); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); doTearDown(); restartBrokers(false); assertSubscriptionsCount(broker1, topic, 0); //create durable that shouldn't be propagated session1.createDurableSubscriber(excludeTopic, "sub-exclude"); //Add 3 online subs session1.createDurableSubscriber(topic, subName); session1.createDurableSubscriber(topic, "sub2"); session1.createDurableSubscriber(topic, "sub3"); assertSubscriptionsCount(broker1, topic, 3); //Restart brokers and make sure we don't have duplicate NCs created //between the sync command and the online durables that are added over //the consumer advisory restartBrokers(true); assertBridgeStarted(); //Re-create session1.createDurableSubscriber(topic, subName); session1.createDurableSubscriber(topic, "sub2"); session1.createDurableSubscriber(topic, "sub3"); session1.createDurableSubscriber(excludeTopic, "sub-exclude"); Thread.sleep(1000); assertNCDurableSubsCount(broker2, topic, 1); assertNCDurableSubsCount(broker2, excludeTopic, 0); } //Test that durable sync works with more than one bridge @Test public void testAddOnlineSubscriptionsTwoBridges() throws Exception { final ActiveMQTopic topic = new ActiveMQTopic(testTopicName); final ActiveMQTopic excludeTopic = new ActiveMQTopic(excludeTopicName); final ActiveMQTopic topic2 = new ActiveMQTopic("include.new.topic"); assertSubscriptionsCount(broker1, topic, 0); assertNCDurableSubsCount(broker2, topic, 0); //create durable that shouldn't be propagated session1.createDurableSubscriber(excludeTopic, "sub-exclude"); //Add 3 online subs session1.createDurableSubscriber(topic, subName); session1.createDurableSubscriber(topic, "sub2"); session1.createDurableSubscriber(topic, "sub3"); //Add sub on second topic/bridge session1.createDurableSubscriber(topic2, "secondTopicSubName"); assertSubscriptionsCount(broker1, topic, 3); assertSubscriptionsCount(broker1, topic2, 1); //Add the second network connector NetworkConnector secondConnector = configureLocalNetworkConnector(); secondConnector.setName("networkConnector2"); secondConnector.setDynamicallyIncludedDestinations( Lists.<ActiveMQDestination>newArrayList( new ActiveMQTopic("include.new.topic?forceDurable=" + forceDurable))); localBroker.addNetworkConnector(secondConnector); secondConnector.start(); //Make sure both bridges are connected assertTrue(Wait.waitFor(new Condition() { @Override public boolean isSatisified() throws Exception { return localBroker.getNetworkConnectors().get(0).activeBridges().size() == 1 && localBroker.getNetworkConnectors().get(1).activeBridges().size() == 1; } }, 10000, 500)); //Make sure NC durables exist for both bridges assertNCDurableSubsCount(broker2, topic2, 1); assertNCDurableSubsCount(broker2, topic, 1); assertNCDurableSubsCount(broker2, excludeTopic, 0); //Make sure message can reach remote broker MessageProducer producer = session2.createProducer(topic2); producer.send(session2.createTextMessage("test")); waitForDispatchFromLocalBroker(broker2.getDestination(topic2).getDestinationStatistics(), 1); assertLocalBrokerStatistics(broker2.getDestination(topic2).getDestinationStatistics(), 1); } @Test(timeout = 60 * 1000) public void testVirtualDestSubForceDurableSync() throws Exception { Assume.assumeTrue(flow == FLOW.FORWARD); forceDurable = true; useVirtualDestSubs = true; this.restartBrokers(true); //configure a virtual destination that forwards messages from topic testQueueName CompositeTopic compositeTopic = createCompositeTopic(testTopicName, new ActiveMQQueue("include.test.bar.bridge")); remoteRuntimeBroker.setVirtualDestinations(new VirtualDestination[] {compositeTopic}, true); MessageProducer includedProducer = localSession.createProducer(included); Message test = localSession.createTextMessage("test"); final DestinationStatistics destinationStatistics = localBroker.getDestination(included).getDestinationStatistics(); final DestinationStatistics remoteDestStatistics = remoteBroker.getDestination( new ActiveMQQueue("include.test.bar.bridge")).getDestinationStatistics(); //Make sure that the NC durable is created because of the compositeTopic waitForConsumerCount(destinationStatistics, 1); assertNCDurableSubsCount(localBroker, included, 1); //Send message and make sure it is dispatched across the bridge includedProducer.send(test); waitForDispatchFromLocalBroker(destinationStatistics, 1); assertLocalBrokerStatistics(destinationStatistics, 1); assertEquals("remote dest messages", 1, remoteDestStatistics.getMessages().getCount()); //Stop the remote broker so the bridge stops and then send 500 messages so //the messages build up on the NC durable this.stopRemoteBroker(); for (int i = 0; i < 500; i++) { includedProducer.send(test); } this.stopLocalBroker(); //Restart the brokers this.restartRemoteBroker(); remoteRuntimeBroker.setVirtualDestinations(new VirtualDestination[] {compositeTopic}, true); this.restartLocalBroker(true); //We now need to verify that 501 messages made it to the queue on the remote side //which means that the NC durable was not deleted and recreated during the sync final DestinationStatistics remoteDestStatistics2 = remoteBroker.getDestination( new ActiveMQQueue("include.test.bar.bridge")).getDestinationStatistics(); assertTrue(Wait.waitFor(new Condition() { @Override public boolean isSatisified() throws Exception { return remoteDestStatistics2.getMessages().getCount() == 501; } })); } @Test(timeout = 60 * 1000) public void testForceDurableTopicSubSync() throws Exception { Assume.assumeTrue(flow == FLOW.FORWARD); forceDurable = true; this.restartBrokers(true); //configure a virtual destination that forwards messages from topic testQueueName remoteSession.createConsumer(included); MessageProducer includedProducer = localSession.createProducer(included); Message test = localSession.createTextMessage("test"); final DestinationStatistics destinationStatistics = localBroker.getDestination(included).getDestinationStatistics(); //Make sure that the NC durable is created because of the compositeTopic waitForConsumerCount(destinationStatistics, 1); assertNCDurableSubsCount(localBroker, included, 1); //Send message and make sure it is dispatched across the bridge includedProducer.send(test); waitForDispatchFromLocalBroker(destinationStatistics, 1); assertLocalBrokerStatistics(destinationStatistics, 1); //Stop the network connector and send messages to the local broker so they build //up on the durable this.localBroker.getNetworkConnectorByName("networkConnector").stop(); for (int i = 0; i < 500; i++) { includedProducer.send(test); } //restart the local broker and bridge this.stopLocalBroker(); this.restartLocalBroker(true); //We now need to verify that the 500 messages on the NC durable are dispatched //on bridge sync which shows that the durable wasn't destroyed/recreated final DestinationStatistics destinationStatistics2 = localBroker.getDestination(included).getDestinationStatistics(); waitForDispatchFromLocalBroker(destinationStatistics2, 500); assertLocalBrokerStatistics(destinationStatistics2, 500); } protected CompositeTopic createCompositeTopic(String name, ActiveMQDestination...forwardTo) { CompositeTopic compositeTopic = new CompositeTopic(); compositeTopic.setName(name); compositeTopic.setForwardOnly(true); compositeTopic.setForwardTo( Lists.newArrayList(forwardTo)); return compositeTopic; } protected void restartBroker(BrokerService broker, boolean startNetworkConnector) throws Exception { if (broker.getBrokerName().equals("localBroker")) { restartLocalBroker(startNetworkConnector); } else { restartRemoteBroker(); } } protected void restartBrokers(boolean startNetworkConnector) throws Exception { doTearDown(); doSetUp(false, startNetworkConnector, localBroker.getDataDirectoryFile(), remoteBroker.getDataDirectoryFile()); } protected void doSetUp(boolean deleteAllMessages, boolean startNetworkConnector, File localDataDir, File remoteDataDir) throws Exception { included = new ActiveMQTopic(testTopicName); doSetUpRemoteBroker(deleteAllMessages, remoteDataDir, 0); doSetUpLocalBroker(deleteAllMessages, startNetworkConnector, localDataDir); //Give time for advisories to propagate Thread.sleep(1000); } protected void restartLocalBroker(boolean startNetworkConnector) throws Exception { stopLocalBroker(); doSetUpLocalBroker(false, startNetworkConnector, localBroker.getDataDirectoryFile()); } protected void restartRemoteBroker() throws Exception { int port = 0; if (remoteBroker != null) { List<TransportConnector> transportConnectors = remoteBroker.getTransportConnectors(); port = transportConnectors.get(0).getConnectUri().getPort(); } stopRemoteBroker(); doSetUpRemoteBroker(false, remoteBroker.getDataDirectoryFile(), port); } protected void doSetUpLocalBroker(boolean deleteAllMessages, boolean startNetworkConnector, File dataDir) throws Exception { localBroker = createLocalBroker(dataDir, startNetworkConnector); localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); localBroker.start(); localBroker.waitUntilStarted(); URI localURI = localBroker.getVmConnectorURI(); ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); fac.setAlwaysSyncSend(true); fac.setDispatchAsync(false); localConnection = fac.createConnection(); localConnection.setClientID("clientId"); localConnection.start(); if (startNetworkConnector) { Wait.waitFor(new Condition() { @Override public boolean isSatisified() throws Exception { return localBroker.getNetworkConnectors().get(0).activeBridges().size() == 1; } }, 5000, 500); } localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); if (flow.equals(FLOW.FORWARD)) { broker1 = localBroker; session1 = localSession; } else { broker2 = localBroker; session2 = localSession; } } protected void doSetUpRemoteBroker(boolean deleteAllMessages, File dataDir, int port) throws Exception { remoteBroker = createRemoteBroker(dataDir, port); remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); remoteBroker.start(); remoteBroker.waitUntilStarted(); URI remoteURI = remoteBroker.getVmConnectorURI(); ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(remoteURI); remoteConnection = fac.createConnection(); remoteConnection.setClientID("clientId"); remoteConnection.start(); remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); if (flow.equals(FLOW.FORWARD)) { broker2 = remoteBroker; session2 = remoteSession; remoteRuntimeBroker = (JavaRuntimeConfigurationBroker) remoteBroker.getBroker().getAdaptor(JavaRuntimeConfigurationBroker.class); } else { broker1 = remoteBroker; session1 = remoteSession; } } protected BrokerService createLocalBroker(File dataDir, boolean startNetworkConnector) throws Exception { BrokerService brokerService = new BrokerService(); brokerService.setMonitorConnectionSplits(true); brokerService.setBrokerName("localBroker"); brokerService.setDataDirectoryFile(dataDir); KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); adapter.setDirectory(dataDir); adapter.setJournalDiskSyncStrategy(JournalDiskSyncStrategy.PERIODIC.name()); brokerService.setPersistenceAdapter(adapter); brokerService.setUseVirtualDestSubs(useVirtualDestSubs); brokerService.setUseVirtualDestSubsOnCreation(useVirtualDestSubs); if (startNetworkConnector) { brokerService.addNetworkConnector(configureLocalNetworkConnector()); } //Use auto+nio+ssl to test out the transport works with bridging brokerService.addConnector("auto+nio+ssl://localhost:0"); return brokerService; } protected NetworkConnector configureLocalNetworkConnector() throws Exception { List<TransportConnector> transportConnectors = remoteBroker.getTransportConnectors(); URI remoteURI = transportConnectors.get(0).getConnectUri(); String uri = "static:(" + remoteURI + ")"; NetworkConnector connector = new DiscoveryNetworkConnector(new URI(uri)); connector.setName("networkConnector"); connector.setDynamicOnly(dynamicOnly); connector.setDecreaseNetworkConsumerPriority(false); connector.setConduitSubscriptions(true); connector.setDuplex(true); connector.setStaticBridge(false); connector.setSyncDurableSubs(true); connector.setUseVirtualDestSubs(useVirtualDestSubs); connector.setStaticallyIncludedDestinations( Lists.<ActiveMQDestination>newArrayList(new ActiveMQTopic(staticIncludeTopics + "?forceDurable=" + forceDurable))); connector.setDynamicallyIncludedDestinations( Lists.<ActiveMQDestination>newArrayList(new ActiveMQTopic(includedTopics + "?forceDurable=" + forceDurable))); connector.setExcludedDestinations( Lists.<ActiveMQDestination>newArrayList(new ActiveMQTopic(excludeTopicName))); return connector; } protected AdvisoryBroker remoteAdvisoryBroker; protected BrokerService createRemoteBroker(File dataDir, int port) throws Exception { BrokerService brokerService = new BrokerService(); brokerService.setBrokerName("remoteBroker"); brokerService.setUseJmx(false); brokerService.setDataDirectoryFile(dataDir); KahaDBPersistenceAdapter adapter = new KahaDBPersistenceAdapter(); adapter.setDirectory(dataDir); adapter.setJournalDiskSyncStrategy(JournalDiskSyncStrategy.PERIODIC.name()); brokerService.setPersistenceAdapter(adapter); brokerService.setUseVirtualDestSubs(useVirtualDestSubs); brokerService.setUseVirtualDestSubsOnCreation(useVirtualDestSubs); if (useVirtualDestSubs) { brokerService.setPlugins(new BrokerPlugin[] {new JavaRuntimeConfigurationPlugin()}); } remoteAdvisoryBroker = (AdvisoryBroker) brokerService.getBroker().getAdaptor(AdvisoryBroker.class); //Need a larger cache size in order to handle all of the durables //Use auto+nio+ssl to test out the transport works with bridging brokerService.addConnector("auto+nio+ssl://localhost:" + port + "?wireFormat.cacheSize=2048&wireFormat.version=" + remoteBrokerWireFormatVersion); return brokerService; } }
package org.jboss.resteasy.test.nextgen.finegrain; import junit.framework.Assert; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.core.Dispatcher; import org.jboss.resteasy.core.MessageBodyParameterInjector; import org.jboss.resteasy.spi.BadRequestException; import org.jboss.resteasy.spi.InternalDispatcher; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.test.EmbeddedContainer; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.util.Stack; import static org.jboss.resteasy.test.TestPortProvider.generateBaseUrl; /** * Test for InternalDispatcher * * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a> * @version $Revision: 1 $ */ public class InternalDispatcherTest { private static Dispatcher dispatcher; private static ForwardingResource forwardingResource; private static ResteasyClient client; @Path("/") public interface Client { @GET @Path("basic") @Produces("text/plain") String getBasic(); @PUT @Path("basic") @Consumes("text/plain") void putBasic(String body); @GET @Path("forward/basic") @Produces("text/plain") String getForwardBasic(); @PUT @Path("forward/basic") @Consumes("text/plain") void putForwardBasic(String body); @POST @Path("forward/basic") @Consumes("text/plain") void postForwardBasic(String body); @DELETE @Path("/forward/basic") void deleteForwardBasic(); @GET @Produces("text/plain") @Path("/forward/object/{id}") Response getForwardedObject(@PathParam("id") Integer id); @GET @Produces("text/plain") @Path("/object/{id}") Response getObject(@PathParam("id") Integer id); @GET @Produces("text/plain") @Path("/infinite-forward") int infiniteForward(); } @Path("/") public static class ForwardingResource { public Stack<String> uriStack = new Stack<String>(); String basic = "basic"; @Context UriInfo uriInfo; @GET @Produces("text/plain") @Path("/basic") public String getBasic() { uriStack.push(uriInfo.getAbsolutePath().toString()); return basic; } @GET @Produces("text/plain") @Path("/forward/basic") public String forwardBasic(@Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); return (String) dispatcher.getEntity("/basic"); } @PUT @POST @Consumes("text/plain") @Path("/basic") public void putBasic(String basic) { uriStack.push(uriInfo.getAbsolutePath().toString()); this.basic = basic; } @DELETE @Path("/basic") public void deleteBasic() { uriStack.push(uriInfo.getAbsolutePath().toString()); this.basic = "basic"; } @PUT @Consumes("text/plain") @Path("/forward/basic") public void putForwardBasic(String basic, @Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); dispatcher.putEntity("/basic", basic); } @POST @Consumes("text/plain") @Path("/forward/basic") public void postForwardBasic(String basic, @Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); dispatcher.postEntity("/basic", basic); } @DELETE @Path("/forward/basic") public void deleteForwardBasic(@Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); dispatcher.delete("/basic"); } @GET @Produces("text/plain") @Path("/object/{id}") public Response getObject(@PathParam("id") Integer id) { uriStack.push(uriInfo.getAbsolutePath().toString()); if (id == 0) return Response.noContent().build(); else return Response.ok("object" + id).build(); } @GET @Path("/forward/object/{id}") public Response forwardObject(@PathParam("id") Integer id, @Context InternalDispatcher dispatcher) { uriStack.push(uriInfo.getAbsolutePath().toString()); return dispatcher.getResponse("/object/" + id); } @GET @Path("/infinite-forward") @Produces("text/plain") public int infinitFoward(@Context InternalDispatcher dispatcher, @QueryParam("count") @DefaultValue("0") int count) { uriStack.push(uriInfo.getAbsolutePath().toString()); try { dispatcher.getEntity("/infinite-forward?count=" + (count + 1)); // we'll never reach 20, since the max count of times through the // system is 20, and first time through is 0 Assert.assertNotSame(20, count); } catch (BadRequestException e) { } finally { Assert .assertEquals(count, MessageBodyParameterInjector.bodyCount()); Assert.assertEquals(count + 1, ResteasyProviderFactory .getContextDataLevelCount()); } return ResteasyProviderFactory.getContextDataLevelCount(); } } @BeforeClass public static void before() throws Exception { dispatcher = EmbeddedContainer.start().getDispatcher(); forwardingResource = new ForwardingResource(); dispatcher.getRegistry().addSingletonResource(forwardingResource); client = new ResteasyClientBuilder().build(); } @Before public void setup() { forwardingResource.uriStack.clear(); } @AfterClass public static void after() throws Exception { client.close(); EmbeddedContainer.stop(); } @Test public void testClientResponse() throws Exception { Client proxy = client.target(generateBaseUrl()).proxy(Client.class); Assert.assertEquals("basic", proxy.getBasic()); Assert.assertEquals("basic", proxy.getForwardBasic()); Assert.assertEquals("object1", proxy.getObject(1).readEntity(String.class)); Assert.assertEquals("object1", proxy.getForwardedObject(1).readEntity(String.class)); Response cr = proxy.getObject(0); Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus()); cr.close(); cr = proxy.getForwardedObject(0); Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), cr.getStatus()); cr.close(); proxy.putForwardBasic("testBasic"); Assert.assertEquals("testBasic", proxy.getBasic()); proxy.postForwardBasic("testBasic1"); Assert.assertEquals("testBasic1", proxy.getBasic()); proxy.deleteForwardBasic(); Assert.assertEquals("basic", proxy.getBasic()); } @Test public void testInfinitForward() { Client proxy = client.target(generateBaseUrl()).proxy(Client.class); // assert that even though there were infinite forwards, there still was // only 1 level of "context" data and that clean up occurred correctly. // This should not spin forever, since RESTEasy stops the recursive loop // after 20 internal dispatches Assert.assertEquals(1, proxy.infiniteForward()); } @Test public void testUriInfoBasic() { String baseUrl = generateBaseUrl(); Client proxy = client.target(generateBaseUrl()).proxy(Client.class); proxy.getBasic(); Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop()); Assert.assertTrue(forwardingResource.uriStack.isEmpty()); } @Test public void testUriInfoForwardBasic() { String baseUrl = generateBaseUrl(); Client proxy = client.target(generateBaseUrl()).proxy(Client.class); proxy.getForwardBasic(); Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop()); Assert.assertEquals(baseUrl + "/forward/basic", forwardingResource.uriStack.pop()); Assert.assertTrue(forwardingResource.uriStack.isEmpty()); } }
package org.saiku.olap.query2.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.lang.StringUtils; import org.olap4j.Axis; import org.olap4j.impl.NamedListImpl; import org.olap4j.metadata.Measure; import org.olap4j.metadata.Member; import org.olap4j.metadata.NamedList; import org.saiku.olap.dto.SaikuCube; import org.saiku.olap.query2.ThinAxis; import org.saiku.olap.query2.ThinCalculatedMeasure; import org.saiku.olap.query2.ThinDetails; import org.saiku.olap.query2.ThinHierarchy; import org.saiku.olap.query2.ThinLevel; import org.saiku.olap.query2.ThinMeasure; import org.saiku.olap.query2.ThinMeasure.Type; import org.saiku.olap.query2.ThinMember; import org.saiku.olap.query2.ThinQuery; import org.saiku.olap.query2.ThinQueryModel; import org.saiku.olap.query2.ThinQueryModel.AxisLocation; import org.saiku.olap.query2.ThinSelection; import org.saiku.olap.query2.common.ThinQuerySet; import org.saiku.olap.query2.common.ThinSortableQuerySet; import org.saiku.olap.query2.common.ThinSortableQuerySet.HierarchizeMode; import org.saiku.olap.query2.common.ThinSortableQuerySet.SortOrder; import org.saiku.olap.query2.filter.ThinFilter; import org.saiku.olap.query2.filter.ThinFilter.FilterFlavour; import org.saiku.olap.query2.filter.ThinFilter.FilterFunction; import org.saiku.olap.query2.filter.ThinFilter.FilterOperator; import org.saiku.olap.util.SaikuDictionary.DateFlag; import org.saiku.query.IQuerySet; import org.saiku.query.ISortableQuerySet; import org.saiku.query.Query; import org.saiku.query.QueryAxis; import org.saiku.query.QueryDetails; import org.saiku.query.QueryHierarchy; import org.saiku.query.QueryLevel; import org.saiku.query.mdx.GenericFilter; import org.saiku.query.mdx.IFilterFunction; import org.saiku.query.mdx.NFilter; import org.saiku.query.mdx.NameFilter; import org.saiku.query.mdx.NameLikeFilter; import org.saiku.query.metadata.CalculatedMeasure; public class Thin { public static ThinQuery convert(Query query, SaikuCube cube) throws Exception { ThinQuery tq = new ThinQuery(query.getName(), cube); ThinQueryModel tqm = convert(query, tq); tq.setQueryModel(tqm); if (query.getParameters() != null) { query.retrieveParameters(); tq.setParameters(query.getParameters()); } tq.setMdx(query.getMdx()); return tq; } private static ThinQueryModel convert(Query query, ThinQuery tq) { ThinQueryModel tqm = new ThinQueryModel(); tqm.setAxes(convertAxes(query.getAxes(), tq)); ThinDetails td = convert(query.getDetails()); tqm.setDetails(td); List<ThinCalculatedMeasure> cms = convert(query.getCalculatedMeasures()); tqm.setCalculatedMeasures(cms); tqm.setVisualTotals(query.isVisualTotals()); tqm.setVisualTotalsPattern(query.getVisualTotalsPattern()); return tqm; } private static List<ThinCalculatedMeasure> convert(List<CalculatedMeasure> qcms) { List<ThinCalculatedMeasure> tcms = new ArrayList<ThinCalculatedMeasure>(); if (qcms != null && qcms.size() > 0) { for (CalculatedMeasure qcm : qcms) { ThinCalculatedMeasure tcm = new ThinCalculatedMeasure( qcm.getHierarchy().getUniqueName(), qcm.getName(), qcm.getUniqueName(), qcm.getCaption(), qcm.getFormula(), qcm.getFormatProperties()); tcms.add(tcm); } } return tcms; } private static ThinDetails convert(QueryDetails details) { ThinDetails.Location location = ThinDetails.Location.valueOf(details.getLocation().toString()); AxisLocation axis = AxisLocation.valueOf(details.getAxis().toString()); List<ThinMeasure> measures = new ArrayList<ThinMeasure>(); if (details != null && details.getMeasures().size() > 0) { for (Measure m : details.getMeasures()) { ThinMeasure.Type type = Type.EXACT; if (m instanceof CalculatedMeasure) { type = Type.CALCULATED; } ThinMeasure tm = new ThinMeasure(m.getName(), m.getUniqueName(), m.getCaption(), type); measures.add(tm); } } return new ThinDetails(axis, location, measures); } private static Map<AxisLocation, ThinAxis> convertAxes(Map<Axis, QueryAxis> axes, ThinQuery tq) { Map<ThinQueryModel.AxisLocation, ThinAxis> thinAxes = new TreeMap<ThinQueryModel.AxisLocation, ThinAxis>(); if (axes != null) { for (Axis axis : sortAxes(axes.keySet())) { if (axis != null) { ThinAxis ta = convertAxis(axes.get(axis), tq); thinAxes.put(ta.getLocation(), ta); } } } return thinAxes; } private static List<Axis> sortAxes(Set<Axis> axes) { List<Axis> ax = new ArrayList<Axis>(); for (Axis a : Axis.Standard.values()) { if (axes.contains(a)){ ax.add(a); } } return ax; } private static ThinAxis convertAxis(QueryAxis queryAxis, ThinQuery tq) { AxisLocation loc = getLocation(queryAxis); List<String> aggs = queryAxis.getQuery().getAggregators(queryAxis.getLocation().toString()); ThinAxis ta = new ThinAxis(loc, convertHierarchies(queryAxis.getQueryHierarchies(), tq), queryAxis.isNonEmpty(), aggs); extendSortableQuerySet(ta, queryAxis); return ta; } private static NamedList<ThinHierarchy> convertHierarchies(List<QueryHierarchy> queryHierarchies, ThinQuery tq) { NamedListImpl<ThinHierarchy> hs = new NamedListImpl<ThinHierarchy>(); if (queryHierarchies != null) { for (QueryHierarchy qh : queryHierarchies) { ThinHierarchy th = convertHierarchy(qh, tq); hs.add(th); } } return hs; } private static ThinHierarchy convertHierarchy(QueryHierarchy qh, ThinQuery tq) { ThinHierarchy th = new ThinHierarchy(qh.getUniqueName(), qh.getCaption(), qh.getHierarchy().getDimension().getName(), convertLevels(qh.getActiveQueryLevels(), tq)); extendSortableQuerySet(th, qh); return th; } private static Map<String, ThinLevel> convertLevels(List<QueryLevel> levels, ThinQuery tq) { Map<String, ThinLevel> tl = new HashMap<String, ThinLevel>(); if (levels != null) { for (QueryLevel ql : levels) { ThinLevel l = convertLevel(ql, tq); tl.put(ql.getName(), l); } } return tl; } private static ThinLevel convertLevel(QueryLevel ql, ThinQuery tq) { List<ThinMember> inclusions = convertMembers(ql.getInclusions()); List<ThinMember> exclusions = convertMembers(ql.getExclusions()); ThinSelection ts = new ThinSelection(ThinSelection.Type.INCLUSION, null); if (inclusions.size() > 0) { ts = new ThinSelection(ThinSelection.Type.INCLUSION, inclusions); } else if (exclusions.size() > 0) { ts = new ThinSelection(ThinSelection.Type.EXCLUSION, exclusions); } else if (ql.isRange()){ List<ThinMember> range = new ArrayList<ThinMember>(); ThinMember rangeStart = getLastNotNull( convertMember(ql.getRangeStart()), convertPseudoMember(ql.getRangeStartExpr()), convertPseudoMember(ql.getRangeStartSyn())); ThinMember rangeEnd = getLastNotNull( convertMember(ql.getRangeEnd()), convertPseudoMember(ql.getRangeEndExpr()), convertPseudoMember(ql.getRangeEndSyn())); if ( ("F:" + DateFlag.IGNORE.toString()).equals(ql.getRangeEndSyn())) { rangeEnd = null; } if (rangeStart != null) { range.add(rangeStart); } if (rangeEnd != null) { range.add(rangeEnd); } ts = new ThinSelection(ThinSelection.Type.RANGE, range); } if (ql.hasParameter() && ts != null) { ts.setParameterName(ql.getParameterName()); tq.addParameter(ql.getParameterName()); } List<String> aggs = ql.getQueryHierarchy().getQuery().getAggregators(ql.getUniqueName()); ThinLevel l = new ThinLevel(ql.getName(), ql.getCaption(), ts, aggs); extendQuerySet(l, ql); return l; } private static ThinMember getLastNotNull(ThinMember ...members) { if (members != null) { if (members.length > 1) { ThinMember m = members[0]; for (int i = 1; i < members.length; i++) { if (members[i] != null) m = members[i]; } return m; } else { return members[0]; } } return null; } private static List<ThinMember> convertMembers(List<Member> members) { List<ThinMember> ms = new ArrayList<ThinMember>(); if (members != null) { for (Member m : members) { ms.add(convertMember(m)); } } return ms; } private static ThinMember convertMember(Member m) { if (m != null) { return new ThinMember(m.getName(), m.getUniqueName(), m.getCaption()); } return null; } private static ThinMember convertPseudoMember(String uniqueName) { if (uniqueName != null) { return new ThinMember(uniqueName, uniqueName, uniqueName); } return null; } private static AxisLocation getLocation(QueryAxis axis) { Axis ax = axis.getLocation(); if (Axis.ROWS.equals(ax)) { return AxisLocation.ROWS; } else if (Axis.COLUMNS.equals(ax)) { return AxisLocation.COLUMNS; } else if (Axis.FILTER.equals(ax)) { return AxisLocation.FILTER; } else if (Axis.PAGES.equals(ax)) { return AxisLocation.PAGES; } return null; } private static void extendQuerySet(ThinQuerySet ts, IQuerySet qs) { if (StringUtils.isNotBlank(qs.getMdxSetExpression())) { ts.setMdx(qs.getMdxSetExpression()); } if (qs.getFilters() != null && qs.getFilters().size() > 0) { List<ThinFilter> filters = convertFilters(qs.getFilters()); ts.getFilters().addAll(filters); } } private static List<ThinFilter> convertFilters(List<IFilterFunction> filters) { List<ThinFilter> tfs = new ArrayList<ThinFilter>(); for (IFilterFunction f : filters) { if (f instanceof NameFilter) { NameFilter nf = (NameFilter) f; List<String> expressions = nf.getFilterExpression(); expressions.add(0, nf.getHierarchy().getUniqueName()); ThinFilter tf = new ThinFilter(FilterFlavour.Name, FilterOperator.EQUALS, FilterFunction.Filter, expressions); tfs.add(tf); } if (f instanceof NameLikeFilter) { NameLikeFilter nf = (NameLikeFilter) f; List<String> expressions = nf.getFilterExpression(); expressions.add(0, nf.getHierarchy().getUniqueName()); ThinFilter tf = new ThinFilter(FilterFlavour.NameLike, FilterOperator.LIKE, FilterFunction.Filter, expressions); tfs.add(tf); } if (f instanceof GenericFilter) { GenericFilter nf = (GenericFilter) f; List<String> expressions = new ArrayList<String>(); expressions.add(nf.getFilterExpression()); ThinFilter tf = new ThinFilter(FilterFlavour.Generic, null, FilterFunction.Filter, expressions); tfs.add(tf); } if (f instanceof NFilter) { NFilter nf = (NFilter) f; List<String> expressions = new ArrayList<String>(); expressions.add(Integer.toString(nf.getN())); if (nf.getFilterExpression() != null) { expressions.add(nf.getFilterExpression()); } FilterFunction type = FilterFunction.valueOf(nf.getFunctionType().toString()); ThinFilter tf = new ThinFilter(FilterFlavour.N, null, type, expressions); tfs.add(tf); } } return tfs; } private static void extendSortableQuerySet(ThinSortableQuerySet ts, ISortableQuerySet qs) { extendQuerySet(ts, qs); if (qs.getHierarchizeMode() != null) { ts.setHierarchizeMode(HierarchizeMode.valueOf(qs.getHierarchizeMode().toString())); } if (qs.getSortOrder() != null) { ts.sort(SortOrder.valueOf(qs.getSortOrder().toString()), qs.getSortEvaluationLiteral()); } } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models.sessions.infinispan.initializer; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.infinispan.Cache; import org.infinispan.context.Flag; import org.infinispan.distexec.DefaultExecutorService; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.remoting.transport.Transport; import org.jboss.logging.Logger; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.KeycloakSessionTask; import org.keycloak.models.utils.KeycloakModelUtils; /** * Startup initialization for reading persistent userSessions/clientSessions to be filled into infinispan/memory . In cluster, * the initialization is distributed among all cluster nodes, so the startup time is even faster * * TODO: Move to clusterService. Implementation is already pretty generic and doesn't contain any "userSession" specific stuff. All sessions-specific logic is in the SessionLoader implementation * * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class InfinispanUserSessionInitializer { private static final String STATE_KEY_PREFIX = "distributed::"; private static final Logger log = Logger.getLogger(InfinispanUserSessionInitializer.class); private final KeycloakSessionFactory sessionFactory; private final Cache<String, Serializable> workCache; private final SessionLoader sessionLoader; private final int maxErrors; private final int sessionsPerSegment; private final String stateKey; public InfinispanUserSessionInitializer(KeycloakSessionFactory sessionFactory, Cache<String, Serializable> workCache, SessionLoader sessionLoader, int maxErrors, int sessionsPerSegment, String stateKeySuffix) { this.sessionFactory = sessionFactory; this.workCache = workCache; this.sessionLoader = sessionLoader; this.maxErrors = maxErrors; this.sessionsPerSegment = sessionsPerSegment; this.stateKey = STATE_KEY_PREFIX + stateKeySuffix; } public void initCache() { this.workCache.getAdvancedCache().getComponentRegistry().registerComponent(sessionFactory, KeycloakSessionFactory.class); } public void loadPersistentSessions() { if (isFinished()) { return; } while (!isFinished()) { if (!isCoordinator()) { try { Thread.sleep(1000); } catch (InterruptedException ie) { log.error("Interrupted", ie); } } else { startLoading(); } } } private boolean isFinished() { InitializerState state = (InitializerState) workCache.get(stateKey); return state != null && state.isFinished(); } private InitializerState getOrCreateInitializerState() { InitializerState state = (InitializerState) workCache.get(stateKey); if (state == null) { final int[] count = new int[1]; // Rather use separate transactions for update and counting KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() { @Override public void run(KeycloakSession session) { sessionLoader.init(session); } }); KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() { @Override public void run(KeycloakSession session) { count[0] = sessionLoader.getSessionsCount(session); } }); state = new InitializerState(); state.init(count[0], sessionsPerSegment); saveStateToCache(state); } return state; } private void saveStateToCache(final InitializerState state) { // 3 attempts to send the message (it may fail if some node fails in the meantime) retry(3, new Runnable() { @Override public void run() { // Save this synchronously to ensure all nodes read correct state InfinispanUserSessionInitializer.this.workCache.getAdvancedCache(). withFlags(Flag.IGNORE_RETURN_VALUES, Flag.FORCE_SYNCHRONOUS) .put(stateKey, state); } }); } private boolean isCoordinator() { Transport transport = workCache.getCacheManager().getTransport(); return transport == null || transport.isCoordinator(); } // Just coordinator will run this private void startLoading() { InitializerState state = getOrCreateInitializerState(); // Assume each worker has same processor's count int processors = Runtime.getRuntime().availableProcessors(); ExecutorService localExecutor = Executors.newCachedThreadPool(); Transport transport = workCache.getCacheManager().getTransport(); boolean distributed = transport != null; ExecutorService executorService = distributed ? new DefaultExecutorService(workCache, localExecutor) : localExecutor; int errors = 0; try { while (!state.isFinished()) { int nodesCount = transport==null ? 1 : transport.getMembers().size(); int distributedWorkersCount = processors * nodesCount; log.debugf("Starting next iteration with %d workers", distributedWorkersCount); List<Integer> segments = state.getUnfinishedSegments(distributedWorkersCount); if (log.isTraceEnabled()) { log.trace("unfinished segments for this iteration: " + segments); } List<Future<WorkerResult>> futures = new LinkedList<>(); for (Integer segment : segments) { SessionInitializerWorker worker = new SessionInitializerWorker(); worker.setWorkerEnvironment(segment, sessionsPerSegment, sessionLoader); if (!distributed) { worker.setEnvironment(workCache, null); } Future<WorkerResult> future = executorService.submit(worker); futures.add(future); } for (Future<WorkerResult> future : futures) { try { WorkerResult result = future.get(); if (result.getSuccess()) { int computedSegment = result.getSegment(); state.markSegmentFinished(computedSegment); } else { if (log.isTraceEnabled()) { log.tracef("Segment %d failed to compute", result.getSegment()); } } } catch (InterruptedException ie) { errors++; log.error("Interruped exception when computed future. Errors: " + errors, ie); } catch (ExecutionException ee) { errors++; log.error("ExecutionException when computed future. Errors: " + errors, ee); } } if (errors >= maxErrors) { throw new RuntimeException("Maximum count of worker errors occured. Limit was " + maxErrors + ". See server.log for details"); } saveStateToCache(state); if (log.isDebugEnabled()) { log.debug("New initializer state pushed. The state is: " + state.printState()); } } } finally { if (distributed) { executorService.shutdown(); } localExecutor.shutdown(); } } private void retry(int retry, Runnable runnable) { while (true) { try { runnable.run(); return; } catch (RuntimeException e) { ComponentStatus status = workCache.getStatus(); if (status.isStopping() || status.isTerminated()) { log.warn("Failed to put initializerState to the cache. Cache is already terminating"); log.debug(e.getMessage(), e); return; } retry--; if (retry == 0) { throw e; } } } } public static class WorkerResult implements Serializable { private Integer segment; private Boolean success; public static WorkerResult create (Integer segment, boolean success) { WorkerResult res = new WorkerResult(); res.setSegment(segment); res.setSuccess(success); return res; } public Integer getSegment() { return segment; } public void setSegment(Integer segment) { this.segment = segment; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } } }
/* Copyright 2015 RoboterHund87 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 net.roboterhund.kitsune; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; /** * Conversion of other data types to and from * {@link KNumRegister}. * <p> * The converter will always try to produce exact results. * However, it can have various degrees of success, which should be checked * by examining {@link #lastConversionStatus}, * or the return value of * {@link #lastConversionValid()} and/or related methods. */ public class KConverter { /** * Maximum number of decimals accepted in a string to convert. */ private static final int MAX_DECIMALS = 18; /** * Denominator corresponding to each number of decimals. */ private static final long[] DENOMINATORS; // compute denominator for each number of decimals static { final int numDenominators = MAX_DECIMALS + 1; DENOMINATORS = new long[numDenominators]; long exponent = 1; for (int i = 1; i < numDenominators; i++) { exponent *= 10; DENOMINATORS[i] = exponent; } } /** * Default precision of numbers with infinite decimal expansion. */ public static final int DEFAULT_PRECISION = 24; /** * Settings for exact conversions. */ public final MathContext exactMathContext; /** * Settings for rounding of infinite decimal expansions. */ public final MathContext inexactMathContext; /** * Status of last conversion. * Set to one of the constants defined in {@link KConversionStatus}. * <p> * Several methods, like {@link #lastConversionValid()}, * are provided for convenience. */ public int lastConversionStatus; /** * Converter with {@link #DEFAULT_PRECISION} for inexact results * and {@link RoundingMode#HALF_UP HALF_UP} rounding mode. * * @see MathContext#precision * @see #KConverter(MathContext) */ public KConverter () { this (DEFAULT_PRECISION); } /** * Converter with specified precision for inexact results * and {@link RoundingMode#HALF_UP HALF_UP} rounding mode. * * @param precision {@link MathContext} {@code precision} setting. * @see MathContext#precision * @see #KConverter(MathContext) */ public KConverter (int precision) { this (new MathContext (precision)); } /** * Converter with specified precision and rounding mode. * <p> * The specified rounding mode is used for all conversions. * <p> * The specified precision is only used when a value with finite number * of digits cannot be produced * (the converter will generally try to use * {@link #exactMathContext}). * * @param mathContext {@link #inexactMathContext}. */ public KConverter (MathContext mathContext) { this.inexactMathContext = mathContext; this.exactMathContext = new MathContext ( 0, mathContext.getRoundingMode () ); } /** * Convert to {@code int}. * <p> * Rounded. * <p> * May overflow. * * @param fromRegister number to convert. * @return {@code int} with value as close to * {@code fromRegister} as possible. */ public int toInt (KNumRegister fromRegister) { switch (fromRegister.profile) { case KProfile.BIG_RATIONAL: BigInteger bigValue = fromRegister.bigNumerator .divide (fromRegister.bigDenominator); if (bigValue.compareTo (KEdges.MAX_INT) <= 0 && bigValue.compareTo (KEdges.MIN_INT) >= 0) { lastConversionStatus = KConversionStatus.INEXACT; return bigValue.intValue (); } else { lastConversionStatus = KConversionStatus.OVERFLOW; } break; case KProfile.LONG_RATIONAL: long longValue = fromRegister.numerator / fromRegister.denominator; if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) { lastConversionStatus = KConversionStatus.INEXACT; return (int) longValue; } else { lastConversionStatus = KConversionStatus.OVERFLOW; } break; case KProfile.INT_RATIONAL: lastConversionStatus = KConversionStatus.INEXACT; return (int) (fromRegister.numerator / fromRegister.denominator); case KProfile.BIG_INTEGER: case KProfile.LONG_INTEGER: lastConversionStatus = KConversionStatus.OVERFLOW; break; case KProfile.INT_INTEGER: lastConversionStatus = KConversionStatus.OK; return (int) fromRegister.numerator; default: throw newIllegalProfileException (fromRegister); } return 0; } /** * Convert to {@code long}. * <p> * Rounded. * <p> * May overflow. * * @param fromRegister number to convert. * @return {@code long} with value as close to * {@code fromRegister} as possible. */ public long toLong (KNumRegister fromRegister) { switch (fromRegister.profile) { case KProfile.BIG_RATIONAL: BigInteger bigValue = fromRegister.bigNumerator .divide (fromRegister.bigDenominator); if (bigValue.compareTo (KEdges.MAX_LONG) <= 0 && bigValue.compareTo (KEdges.MIN_LONG) >= 0) { lastConversionStatus = KConversionStatus.INEXACT; return bigValue.longValue (); } else { lastConversionStatus = KConversionStatus.OVERFLOW; } break; case KProfile.LONG_RATIONAL: case KProfile.INT_RATIONAL: lastConversionStatus = KConversionStatus.INEXACT; return fromRegister.numerator / fromRegister.denominator; case KProfile.BIG_INTEGER: lastConversionStatus = KConversionStatus.OVERFLOW; break; case KProfile.LONG_INTEGER: case KProfile.INT_INTEGER: lastConversionStatus = KConversionStatus.OK; return fromRegister.numerator; default: throw newIllegalProfileException (fromRegister); } return 0; } /** * Convert to {@code double}. * <p> * <b>Note</b>: this method may involve object creation and * is subject to the limitations of the {@code double} data type. * * @param fromRegister number to convert. * @return {@code double} with value as close to * {@code fromRegister} as possible. */ public double toDouble (KNumRegister fromRegister) { double doubleValue; switch (fromRegister.profile) { case KProfile.BIG_RATIONAL: doubleValue = toBigDecimal (fromRegister).doubleValue (); break; case KProfile.LONG_RATIONAL: case KProfile.INT_RATIONAL: lastConversionStatus = KConversionStatus.INEXACT; return (double) fromRegister.numerator / fromRegister.denominator; case KProfile.BIG_INTEGER: doubleValue = fromRegister.bigNumerator.doubleValue (); break; case KProfile.LONG_INTEGER: lastConversionStatus = KConversionStatus.INEXACT; return fromRegister.numerator; case KProfile.INT_INTEGER: lastConversionStatus = KConversionStatus.OK; return fromRegister.numerator; default: throw newIllegalProfileException (fromRegister); } if (doubleValue == Double.POSITIVE_INFINITY || doubleValue == Double.NEGATIVE_INFINITY) { lastConversionStatus = KConversionStatus.OVERFLOW; } else { lastConversionStatus = KConversionStatus.INEXACT; } return doubleValue; } /** * Convert to {@code BigInteger}. * <p> * Rounded. * * @param fromRegister number to convert. * @return {@link BigInteger} with value as close to * {@code fromRegister} as possible. */ public BigInteger toBigInteger (KNumRegister fromRegister) { switch (fromRegister.profile) { case KProfile.BIG_RATIONAL: lastConversionStatus = KConversionStatus.INEXACT; return fromRegister.bigNumerator .divide (fromRegister.bigDenominator); case KProfile.LONG_RATIONAL: case KProfile.INT_RATIONAL: lastConversionStatus = KConversionStatus.INEXACT; return BigInteger.valueOf ( fromRegister.numerator / fromRegister.denominator ); case KProfile.BIG_INTEGER: lastConversionStatus = KConversionStatus.OK; return fromRegister.bigNumerator; case KProfile.LONG_INTEGER: case KProfile.INT_INTEGER: lastConversionStatus = KConversionStatus.OK; if (fromRegister.bigNumerator != null) { fromRegister.bigNumerator = BigInteger.valueOf (fromRegister.numerator); } return fromRegister.bigNumerator; default: throw newIllegalProfileException (fromRegister); } } /** * Convert to {@code BigDecimal}. * <p> * Will fail to produce exact result * if {@code fromRegister} contains a number * with infinite decimal expansion. * * @param fromRegister number to convert. * @return {@link BigDecimal} with value as close to * {@code fromRegister} as possible. */ public BigDecimal toBigDecimal (KNumRegister fromRegister) { BigDecimal bigNumerator; BigDecimal bigDenominator; switch (fromRegister.profile) { case KProfile.BIG_RATIONAL: fromRegister.setBigIntegers (); bigNumerator = new BigDecimal (fromRegister.bigNumerator); bigDenominator = new BigDecimal (fromRegister.bigDenominator); return divideFraction (bigNumerator, bigDenominator); case KProfile.LONG_RATIONAL: case KProfile.INT_RATIONAL: bigNumerator = BigDecimal.valueOf (fromRegister.numerator); bigDenominator = BigDecimal.valueOf (fromRegister.denominator); return divideFraction (bigNumerator, bigDenominator); case KProfile.BIG_INTEGER: lastConversionStatus = KConversionStatus.OK; return new BigDecimal (fromRegister.bigNumerator); case KProfile.LONG_INTEGER: case KProfile.INT_INTEGER: lastConversionStatus = KConversionStatus.OK; return BigDecimal.valueOf (fromRegister.numerator); default: throw newIllegalProfileException (fromRegister); } } /** * Divide numerator and denominator * to get a single {@code BigDecimal}. * <p> * Set {@link #lastConversionStatus}. */ private BigDecimal divideFraction ( BigDecimal bigNumerator, BigDecimal bigDenominator) { BigDecimal bigDecimal; try { lastConversionStatus = KConversionStatus.OK; bigDecimal = bigNumerator.divide ( bigDenominator, exactMathContext ); } catch (ArithmeticException e) { lastConversionStatus = KConversionStatus.INEXACT; bigDecimal = bigNumerator.divide ( bigDenominator, inexactMathContext ); } return bigDecimal.stripTrailingZeros (); } /** * Convert to {@code String}. * * @param fromRegister number to convert. * @return String in format * {@code ['+'|'-'] {0..9}+ ['.' {0..9}+] } * (signed or unsigned integer, may be followed by point and decimals). */ public String toString (KNumRegister fromRegister) { switch (fromRegister.profile) { case KProfile.BIG_RATIONAL: case KProfile.LONG_RATIONAL: case KProfile.INT_RATIONAL: return toBigDecimal (fromRegister) .toPlainString (); case KProfile.BIG_INTEGER: lastConversionStatus = KConversionStatus.OK; return fromRegister.bigNumerator.toString (); case KProfile.LONG_INTEGER: case KProfile.INT_INTEGER: lastConversionStatus = KConversionStatus.OK; return String.valueOf (fromRegister.numerator); default: throw newIllegalProfileException (fromRegister); } } /** * Read value from {@code int}. * * @param toRegister register where to write number value. * @param value new numeric value. */ public void fromInt ( KNumRegister toRegister, int value) { toRegister.setValue (value); } /** * Read value from {@code long}. * * @param toRegister register where to write number value. * @param value new numeric value. */ public void fromLong ( KNumRegister toRegister, long value) { toRegister.setValue (value); } /** * Read value from {@code double}. * <p> * <b>Note</b>: this method involves object creation and * is subject to the limitations of the {@code double} data type. * * @param toRegister register where to write number value. * @param value new numeric value. */ public void fromDouble ( KNumRegister toRegister, double value) { if (Double.isInfinite (value) || Double.isNaN (value)) { // TODO actually handle this values throw new IllegalArgumentException ("value not supported"); } BigDecimal bigDecimalValue; try { bigDecimalValue = new BigDecimal (value, exactMathContext); } catch (ArithmeticException e) { bigDecimalValue = new BigDecimal (value, inexactMathContext); } fromBigDecimal ( toRegister, bigDecimalValue ); } /** * Read value from {@code BigInteger}. * * @param toRegister register where to write number value. * @param value new numeric value. */ public void fromBigInteger ( KNumRegister toRegister, BigInteger value) { toRegister.setValue (value); } /** * Read value from {@code BigDecimal}. * * @param toRegister register where to write number value. * @param value new numeric value. */ public void fromBigDecimal ( KNumRegister toRegister, BigDecimal value) { fromString (toRegister, value.toPlainString ()); } /** * Read value from {@code String}. * * @param toRegister register where to write number value. * @param value string in format * {@code ['+'|'-'] {0..9}+ ['.' {0..9}+] } * (signed or unsigned integer, may be followed by point and decimals). * @throws NumberFormatException unable to parse string. */ public void fromString ( KNumRegister toRegister, String value) { String integerValue = value; String decimalValue = null; int decPointPos = value.indexOf ('.'); if (decPointPos == -1) { // no decimals if (setLongIntValue (toRegister, value)) { return; } } else { // with decimals // get integer part integerValue = value.substring (0, decPointPos); // locate trailing zero digits int lastNonZero; for (lastNonZero = value.length () - 1; lastNonZero > decPointPos; lastNonZero--) { if (value.charAt (lastNonZero) != '0') { break; } } if (lastNonZero == decPointPos) { // all decimal digits are zero if (setLongIntValue (toRegister, integerValue)) { return; } } else { // get decimal part decimalValue = value.substring (decPointPos + 1, lastNonZero + 1); // without this check, // a sign can be prepended to the decimal part if (!Character.isDigit (decimalValue.charAt (0))) { throw new NumberFormatException (); } // parse integer and decimal part if (setLongIntValue (toRegister, integerValue, decimalValue)) { return; } } } BigInteger bigIntegerValue = new BigInteger (integerValue); if (decimalValue == null) { // set integer value toRegister.setValue (bigIntegerValue); } else { BigInteger bigDecimalValue = new BigInteger (decimalValue); // get denominator as power of 10 BigInteger bigDenominator = BigInteger.TEN.pow (decimalValue.length ()); // multiply numerator by power of 10 BigInteger bigNumerator = bigIntegerValue.multiply (bigDenominator); // add decimal part to numerator if (integerValue.charAt (0) == '-') { bigNumerator = bigNumerator.subtract (bigDecimalValue); } else { bigNumerator = bigNumerator.add (bigDecimalValue); } // normalize fraction toRegister.setValue (bigNumerator, bigDenominator); } } /** * Try to parse string as * an integer numeric value. * * @param integerValue integer part of number. * @return {@code true} iff successful. */ private boolean setLongIntValue ( KNumRegister toRegister, String integerValue) { try { toRegister.setValue (Long.parseLong (integerValue)); return true; } catch (NumberFormatException e) { return false; } } /** * Try to parse strings * as the integer part * and the decimals. * * @param integerValue integer part of number. * @param decimalValue decimals of number. * @return {@code true} iff successful. */ private boolean setLongIntValue ( KNumRegister toRegister, String integerValue, String decimalValue) { try { // store integer part in numerator long numerator = Long.parseLong (integerValue); // get denominator as power of 10 int numDecimals = decimalValue.length (); if (numDecimals > 18) { // too many decimals return false; } long denominator = DENOMINATORS[numDecimals]; // multiply numerator by power of 10 if (numerator > Long.MAX_VALUE / denominator || numerator < Long.MIN_VALUE / denominator) { // factor_1 * factor_2 > Long.MAX_VALUE // or factor_1 * factor_2 < Long.MIN_VALUE return false; } numerator *= denominator; // add decimal part to numerator long decimalPart = Long.parseLong (decimalValue); if (integerValue.charAt (0) == '-') { numerator -= decimalPart; } else { numerator += decimalPart; } // normalize fraction toRegister.setValue (numerator, denominator); return true; } catch (NumberFormatException e) { return false; } } /** * Convenience method to throw exception. * * @param register number with invalid profile. * @return New {@link IllegalArgumentException}. */ private static IllegalArgumentException newIllegalProfileException ( KNumRegister register) { return new IllegalArgumentException ( "Invalid KNumRegister profile: " + register.profile + "."); } /** * Possible results of a conversion (whether it was exact or not, etc.) */ public static abstract class KConversionStatus { /** * Last conversion was unsuccessful, because * the numeric value is outside of the range * of the destination data type. */ public static final int OVERFLOW = -1; /** * Last conversion produced the exact value, guaranteed. */ public static final int OK = 0; /** * Last conversion produced an value * that is not guaranteed to be exact. */ public static final int INEXACT = 1; } /** * Convenience method to check last conversion. * <p> * This is the inverse of {@link #lastConversionValid()}. * * @return {@code true} iff the last conversion was impossible. */ public boolean lastConversionFailed () { return lastConversionStatus == KConversionStatus.OVERFLOW; } /** * Convenience method to check last conversion. * <p> * This is a weaker version of {@link #lastConversionExact()} * and the inverse of {@link #lastConversionFailed()}. * * @return {@code true} iff the last conversion yielded * an exact <b>or</b> approximate value. */ public boolean lastConversionValid () { return lastConversionStatus >= KConversionStatus.OK; } /** * Convenience method to check last conversion. * <p> * This is a stronger version of {@link #lastConversionValid()}. * * @return {@code true} iff the last conversion yielded the exact value. */ public boolean lastConversionExact () { return lastConversionStatus == KConversionStatus.OK; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.contrib.index.mapred; import java.io.File; import java.io.IOException; import java.text.NumberFormat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.contrib.index.lucene.FileSystemDirectory; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.mapred.MiniMRCluster; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy; import org.apache.lucene.index.MultiReader; import org.apache.lucene.index.Term; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import junit.framework.TestCase; public class TestIndexUpdater extends TestCase { private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(); static { NUMBER_FORMAT.setMinimumIntegerDigits(5); NUMBER_FORMAT.setGroupingUsed(false); } // however, "we only allow 0 or 1 reducer in local mode" - from // LocalJobRunner private Configuration conf; private Path localInputPath = new Path(System.getProperty("build.test") + "/sample/data.txt"); private Path inputPath = new Path("/myexample/data.txt"); private Path outputPath = new Path("/myoutput"); private Path indexPath = new Path("/myindex"); private int initNumShards = 3; private int numMapTasks = 5; private int numDataNodes = 3; private int numTaskTrackers = 3; private int numRuns = 3; private int numDocsPerRun = 10; // num of docs in local input path private FileSystem fs; private MiniDFSCluster dfsCluster; private MiniMRCluster mrCluster; public TestIndexUpdater() throws IOException { super(); if (System.getProperty("hadoop.log.dir") == null) { String base = new File(".").getPath(); // getAbsolutePath(); System.setProperty("hadoop.log.dir", new Path(base).toString() + "/logs"); } conf = new Configuration(); } protected void setUp() throws Exception { super.setUp(); try { dfsCluster = new MiniDFSCluster(conf, numDataNodes, true, (String[]) null); fs = dfsCluster.getFileSystem(); if (fs.exists(inputPath)) { fs.delete(inputPath, true); } fs.copyFromLocalFile(localInputPath, inputPath); if (fs.exists(outputPath)) { // do not create, mapred will create fs.delete(outputPath, true); } if (fs.exists(indexPath)) { fs.delete(indexPath, true); } mrCluster = new MiniMRCluster(numTaskTrackers, fs.getUri().toString(), 1); } catch (IOException e) { if (dfsCluster != null) { dfsCluster.shutdown(); dfsCluster = null; } if (fs != null) { fs.close(); fs = null; } if (mrCluster != null) { mrCluster.shutdown(); mrCluster = null; } throw e; } } protected void tearDown() throws Exception { if (dfsCluster != null) { dfsCluster.shutdown(); dfsCluster = null; } if (fs != null) { fs.close(); fs = null; } if (mrCluster != null) { mrCluster.shutdown(); mrCluster = null; } super.tearDown(); } public void testIndexUpdater() throws IOException { IndexUpdateConfiguration iconf = new IndexUpdateConfiguration(conf); // max field length, compound file and number of segments will be checked // later iconf.setIndexMaxFieldLength(2); iconf.setIndexUseCompoundFile(true); iconf.setIndexMaxNumSegments(1); iconf.setMaxRAMSizeInBytes(20480); long versionNumber = -1; long generation = -1; for (int i = 0; i < numRuns; i++) { if (fs.exists(outputPath)) { fs.delete(outputPath, true); } Shard[] shards = new Shard[initNumShards + i]; for (int j = 0; j < shards.length; j++) { shards[j] = new Shard(versionNumber, new Path(indexPath, NUMBER_FORMAT.format(j)).toString(), generation); } run(i + 1, shards); } } private void run(int numRuns, Shard[] shards) throws IOException { IIndexUpdater updater = new IndexUpdater(); updater.run(conf, new Path[] { inputPath }, outputPath, numMapTasks, shards); // verify the done files Path[] doneFileNames = new Path[shards.length]; int count = 0; FileStatus[] fileStatus = fs.listStatus(outputPath); for (int i = 0; i < fileStatus.length; i++) { FileStatus[] doneFiles = fs.listStatus(fileStatus[i].getPath()); for (int j = 0; j < doneFiles.length; j++) { doneFileNames[count++] = doneFiles[j].getPath(); } } assertEquals(shards.length, count); for (int i = 0; i < count; i++) { assertTrue(doneFileNames[i].getName().startsWith( IndexUpdateReducer.DONE.toString())); } // verify the index IndexReader[] readers = new IndexReader[shards.length]; for (int i = 0; i < shards.length; i++) { Directory dir = new FileSystemDirectory(fs, new Path(shards[i].getDirectory()), false, conf); readers[i] = IndexReader.open(dir); } IndexReader reader = new MultiReader(readers); IndexSearcher searcher = new IndexSearcher(reader); Hits hits = searcher.search(new TermQuery(new Term("content", "apache"))); assertEquals(numRuns * numDocsPerRun, hits.length()); int[] counts = new int[numDocsPerRun]; for (int i = 0; i < hits.length(); i++) { Document doc = hits.doc(i); counts[Integer.parseInt(doc.get("id"))]++; } for (int i = 0; i < numDocsPerRun; i++) { assertEquals(numRuns, counts[i]); } // max field length is 2, so "dot" is also indexed but not "org" hits = searcher.search(new TermQuery(new Term("content", "dot"))); assertEquals(numRuns, hits.length()); hits = searcher.search(new TermQuery(new Term("content", "org"))); assertEquals(0, hits.length()); searcher.close(); reader.close(); // open and close an index writer with KeepOnlyLastCommitDeletionPolicy // to remove earlier checkpoints for (int i = 0; i < shards.length; i++) { Directory dir = new FileSystemDirectory(fs, new Path(shards[i].getDirectory()), false, conf); IndexWriter writer = new IndexWriter(dir, false, null, new KeepOnlyLastCommitDeletionPolicy()); writer.close(); } // verify the number of segments, must be done after an writer with // KeepOnlyLastCommitDeletionPolicy so that earlier checkpoints are removed for (int i = 0; i < shards.length; i++) { PathFilter cfsFilter = new PathFilter() { public boolean accept(Path path) { return path.getName().endsWith(".cfs"); } }; FileStatus[] cfsFiles = fs.listStatus(new Path(shards[i].getDirectory()), cfsFilter); assertEquals(1, cfsFiles.length); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.test.checkpointing; import org.apache.flink.api.common.functions.ReduceFunction; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.common.state.ValueState; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.java.tuple.Tuple; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple4; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.TaskManagerOptions; import org.apache.flink.contrib.streaming.state.RocksDBStateBackend; import org.apache.flink.core.fs.Path; import org.apache.flink.runtime.minicluster.LocalFlinkMiniCluster; import org.apache.flink.runtime.state.AbstractStateBackend; import org.apache.flink.runtime.state.CheckpointListener; import org.apache.flink.runtime.state.filesystem.FsStateBackend; import org.apache.flink.runtime.state.memory.MemoryStateBackend; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.checkpoint.ListCheckpointed; import org.apache.flink.streaming.api.functions.sink.RichSinkFunction; import org.apache.flink.streaming.api.functions.source.RichSourceFunction; import org.apache.flink.streaming.api.functions.windowing.RichWindowFunction; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.streaming.util.TestStreamEnvironment; import org.apache.flink.test.util.SuccessException; import org.apache.flink.util.Collector; import org.apache.flink.util.TestLogger; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.flink.test.util.TestUtils.tryExecute; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * This verifies that checkpointing works correctly with event time windows. This is more * strict than {@link WindowCheckpointingITCase} because for event-time the contents * of the emitted windows are deterministic. * * <p>Split into multiple test classes in order to decrease the runtime per backend * and not run into CI infrastructure limits like no std output being emitted for * I/O heavy variants. */ @SuppressWarnings("serial") public abstract class AbstractEventTimeWindowCheckpointingITCase extends TestLogger { private static final int MAX_MEM_STATE_SIZE = 10 * 1024 * 1024; private static final int PARALLELISM = 4; private static LocalFlinkMiniCluster cluster; private static TestStreamEnvironment env; @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); private StateBackendEnum stateBackendEnum; private AbstractStateBackend stateBackend; AbstractEventTimeWindowCheckpointingITCase(StateBackendEnum stateBackendEnum) { this.stateBackendEnum = stateBackendEnum; } enum StateBackendEnum { MEM, FILE, ROCKSDB_FULLY_ASYNC, ROCKSDB_INCREMENTAL, MEM_ASYNC, FILE_ASYNC } @BeforeClass public static void startTestCluster() { Configuration config = new Configuration(); config.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, 2); config.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, PARALLELISM / 2); config.setLong(TaskManagerOptions.MANAGED_MEMORY_SIZE, 48L); // the default network buffers size (10% of heap max =~ 150MB) seems to much for this test case config.setLong(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX, 80L << 20); // 80 MB cluster = new LocalFlinkMiniCluster(config, false); cluster.start(); env = new TestStreamEnvironment(cluster, PARALLELISM); env.getConfig().setUseSnapshotCompression(true); } @AfterClass public static void stopTestCluster() { if (cluster != null) { cluster.stop(); } } @Before public void initStateBackend() throws IOException { switch (stateBackendEnum) { case MEM: this.stateBackend = new MemoryStateBackend(MAX_MEM_STATE_SIZE, false); break; case FILE: { String backups = tempFolder.newFolder().getAbsolutePath(); this.stateBackend = new FsStateBackend("file://" + backups, false); break; } case MEM_ASYNC: this.stateBackend = new MemoryStateBackend(MAX_MEM_STATE_SIZE, true); break; case FILE_ASYNC: { String backups = tempFolder.newFolder().getAbsolutePath(); this.stateBackend = new FsStateBackend("file://" + backups, true); break; } case ROCKSDB_FULLY_ASYNC: { String rocksDb = tempFolder.newFolder().getAbsolutePath(); RocksDBStateBackend rdb = new RocksDBStateBackend(new MemoryStateBackend(MAX_MEM_STATE_SIZE)); rdb.setDbStoragePath(rocksDb); this.stateBackend = rdb; break; } case ROCKSDB_INCREMENTAL: { String rocksDb = tempFolder.newFolder().getAbsolutePath(); String backups = tempFolder.newFolder().getAbsolutePath(); // we use the fs backend with small threshold here to test the behaviour with file // references, not self contained byte handles RocksDBStateBackend rdb = new RocksDBStateBackend( new FsStateBackend( new Path("file://" + backups).toUri(), 16), true); rdb.setDbStoragePath(rocksDb); this.stateBackend = rdb; break; } } } // ------------------------------------------------------------------------ @Test public void testTumblingTimeWindow() { final int numElementsPerKey = numElementsPerKey(); final int windowSize = windowSize(); final int numKeys = numKeys(); FailingSource.reset(); try { env.setParallelism(PARALLELISM); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.enableCheckpointing(100); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 0)); env.getConfig().disableSysoutLogging(); env.setStateBackend(this.stateBackend); env .addSource(new FailingSource(numKeys, numElementsPerKey, numElementsPerKey / 3)) .rebalance() .keyBy(0) .timeWindow(Time.of(windowSize, MILLISECONDS)) .apply(new RichWindowFunction<Tuple2<Long, IntType>, Tuple4<Long, Long, Long, IntType>, Tuple, TimeWindow>() { private boolean open = false; @Override public void open(Configuration parameters) { assertEquals(PARALLELISM, getRuntimeContext().getNumberOfParallelSubtasks()); open = true; } @Override public void apply( Tuple tuple, TimeWindow window, Iterable<Tuple2<Long, IntType>> values, Collector<Tuple4<Long, Long, Long, IntType>> out) { // validate that the function has been opened properly assertTrue(open); int sum = 0; long key = -1; for (Tuple2<Long, IntType> value : values) { sum += value.f1.value; key = value.f0; } out.collect(new Tuple4<>(key, window.getStart(), window.getEnd(), new IntType(sum))); } }) .addSink(new ValidatingSink(numKeys, numElementsPerKey / windowSize)).setParallelism(1); tryExecute(env, "Tumbling Window Test"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testTumblingTimeWindowWithKVStateMinMaxParallelism() { doTestTumblingTimeWindowWithKVState(PARALLELISM); } @Test public void testTumblingTimeWindowWithKVStateMaxMaxParallelism() { doTestTumblingTimeWindowWithKVState(1 << 15); } public void doTestTumblingTimeWindowWithKVState(int maxParallelism) { final int numElementsPerKey = numElementsPerKey(); final int windowSize = windowSize(); final int numKeys = numKeys(); FailingSource.reset(); try { env.setParallelism(PARALLELISM); env.setMaxParallelism(maxParallelism); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.enableCheckpointing(100); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 0)); env.getConfig().disableSysoutLogging(); env.setStateBackend(this.stateBackend); env .addSource(new FailingSource(numKeys, numElementsPerKey, numElementsPerKey / 3)) .rebalance() .keyBy(0) .timeWindow(Time.of(windowSize, MILLISECONDS)) .apply(new RichWindowFunction<Tuple2<Long, IntType>, Tuple4<Long, Long, Long, IntType>, Tuple, TimeWindow>() { private boolean open = false; private ValueState<Integer> count; @Override public void open(Configuration parameters) { assertEquals(PARALLELISM, getRuntimeContext().getNumberOfParallelSubtasks()); open = true; count = getRuntimeContext().getState( new ValueStateDescriptor<>("count", Integer.class, 0)); } @Override public void apply( Tuple tuple, TimeWindow window, Iterable<Tuple2<Long, IntType>> values, Collector<Tuple4<Long, Long, Long, IntType>> out) throws Exception { // the window count state starts with the key, so that we get // different count results for each key if (count.value() == 0) { count.update(tuple.<Long>getField(0).intValue()); } // validate that the function has been opened properly assertTrue(open); count.update(count.value() + 1); out.collect(new Tuple4<>(tuple.<Long>getField(0), window.getStart(), window.getEnd(), new IntType(count.value()))); } }) .addSink(new CountValidatingSink(numKeys, numElementsPerKey / windowSize)).setParallelism(1); tryExecute(env, "Tumbling Window Test"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testSlidingTimeWindow() { final int numElementsPerKey = numElementsPerKey(); final int windowSize = windowSize(); final int windowSlide = windowSlide(); final int numKeys = numKeys(); FailingSource.reset(); try { env.setMaxParallelism(2 * PARALLELISM); env.setParallelism(PARALLELISM); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.enableCheckpointing(100); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 0)); env.getConfig().disableSysoutLogging(); env.setStateBackend(this.stateBackend); env.getConfig().setUseSnapshotCompression(true); env .addSource(new FailingSource(numKeys, numElementsPerKey, numElementsPerKey / 3)) .rebalance() .keyBy(0) .timeWindow(Time.of(windowSize, MILLISECONDS), Time.of(windowSlide, MILLISECONDS)) .apply(new RichWindowFunction<Tuple2<Long, IntType>, Tuple4<Long, Long, Long, IntType>, Tuple, TimeWindow>() { private boolean open = false; @Override public void open(Configuration parameters) { assertEquals(PARALLELISM, getRuntimeContext().getNumberOfParallelSubtasks()); open = true; } @Override public void apply( Tuple tuple, TimeWindow window, Iterable<Tuple2<Long, IntType>> values, Collector<Tuple4<Long, Long, Long, IntType>> out) { // validate that the function has been opened properly assertTrue(open); int sum = 0; long key = -1; for (Tuple2<Long, IntType> value : values) { sum += value.f1.value; key = value.f0; } out.collect(new Tuple4<>(key, window.getStart(), window.getEnd(), new IntType(sum))); } }) .addSink(new ValidatingSink(numKeys, numElementsPerKey / windowSlide)).setParallelism(1); tryExecute(env, "Tumbling Window Test"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testPreAggregatedTumblingTimeWindow() { final int numElementsPerKey = numElementsPerKey(); final int windowSize = windowSize(); final int numKeys = numKeys(); FailingSource.reset(); try { env.setParallelism(PARALLELISM); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.enableCheckpointing(100); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 0)); env.getConfig().disableSysoutLogging(); env.setStateBackend(this.stateBackend); env .addSource(new FailingSource(numKeys, numElementsPerKey, numElementsPerKey / 3)) .rebalance() .keyBy(0) .timeWindow(Time.of(windowSize, MILLISECONDS)) .reduce( new ReduceFunction<Tuple2<Long, IntType>>() { @Override public Tuple2<Long, IntType> reduce( Tuple2<Long, IntType> a, Tuple2<Long, IntType> b) { return new Tuple2<>(a.f0, new IntType(a.f1.value + b.f1.value)); } }, new RichWindowFunction<Tuple2<Long, IntType>, Tuple4<Long, Long, Long, IntType>, Tuple, TimeWindow>() { private boolean open = false; @Override public void open(Configuration parameters) { assertEquals(PARALLELISM, getRuntimeContext().getNumberOfParallelSubtasks()); open = true; } @Override public void apply( Tuple tuple, TimeWindow window, Iterable<Tuple2<Long, IntType>> input, Collector<Tuple4<Long, Long, Long, IntType>> out) { // validate that the function has been opened properly assertTrue(open); for (Tuple2<Long, IntType> in: input) { out.collect(new Tuple4<>(in.f0, window.getStart(), window.getEnd(), in.f1)); } } }) .addSink(new ValidatingSink(numKeys, numElementsPerKey / windowSize)).setParallelism(1); tryExecute(env, "Tumbling Window Test"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testPreAggregatedSlidingTimeWindow() { final int numElementsPerKey = numElementsPerKey(); final int windowSize = windowSize(); final int windowSlide = windowSlide(); final int numKeys = numKeys(); FailingSource.reset(); try { env.setParallelism(PARALLELISM); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.enableCheckpointing(100); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 0)); env.getConfig().disableSysoutLogging(); env.setStateBackend(this.stateBackend); env .addSource(new FailingSource(numKeys, numElementsPerKey, numElementsPerKey / 3)) .rebalance() .keyBy(0) .timeWindow(Time.of(windowSize, MILLISECONDS), Time.of(windowSlide, MILLISECONDS)) .reduce( new ReduceFunction<Tuple2<Long, IntType>>() { @Override public Tuple2<Long, IntType> reduce( Tuple2<Long, IntType> a, Tuple2<Long, IntType> b) { // validate that the function has been opened properly return new Tuple2<>(a.f0, new IntType(a.f1.value + b.f1.value)); } }, new RichWindowFunction<Tuple2<Long, IntType>, Tuple4<Long, Long, Long, IntType>, Tuple, TimeWindow>() { private boolean open = false; @Override public void open(Configuration parameters) { assertEquals(PARALLELISM, getRuntimeContext().getNumberOfParallelSubtasks()); open = true; } @Override public void apply( Tuple tuple, TimeWindow window, Iterable<Tuple2<Long, IntType>> input, Collector<Tuple4<Long, Long, Long, IntType>> out) { // validate that the function has been opened properly assertTrue(open); for (Tuple2<Long, IntType> in: input) { out.collect(new Tuple4<>(in.f0, window.getStart(), window.getEnd(), in.f1)); } } }) .addSink(new ValidatingSink(numKeys, numElementsPerKey / windowSlide)).setParallelism(1); tryExecute(env, "Tumbling Window Test"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ private static class FailingSource extends RichSourceFunction<Tuple2<Long, IntType>> implements ListCheckpointed<Integer>, CheckpointListener { private static volatile boolean failedBefore = false; private final int numKeys; private final int numElementsToEmit; private final int failureAfterNumElements; private volatile int numElementsEmitted; private volatile int numSuccessfulCheckpoints; private volatile boolean running = true; private FailingSource(int numKeys, int numElementsToEmitPerKey, int failureAfterNumElements) { this.numKeys = numKeys; this.numElementsToEmit = numElementsToEmitPerKey; this.failureAfterNumElements = failureAfterNumElements; } @Override public void open(Configuration parameters) { // non-parallel source assertEquals(1, getRuntimeContext().getNumberOfParallelSubtasks()); } @Override public void run(SourceContext<Tuple2<Long, IntType>> ctx) throws Exception { // we loop longer than we have elements, to permit delayed checkpoints // to still cause a failure while (running) { if (!failedBefore) { // delay a bit, if we have not failed before Thread.sleep(1); if (numSuccessfulCheckpoints >= 2 && numElementsEmitted >= failureAfterNumElements) { // cause a failure if we have not failed before and have reached // enough completed checkpoints and elements failedBefore = true; throw new Exception("Artificial Failure"); } } if (numElementsEmitted < numElementsToEmit && (failedBefore || numElementsEmitted <= failureAfterNumElements)) { // the function failed before, or we are in the elements before the failure synchronized (ctx.getCheckpointLock()) { int next = numElementsEmitted++; for (long i = 0; i < numKeys; i++) { ctx.collectWithTimestamp(new Tuple2<Long, IntType>(i, new IntType(next)), next); } ctx.emitWatermark(new Watermark(next)); } } else { // if our work is done, delay a bit to prevent busy waiting Thread.sleep(1); } } } @Override public void cancel() { running = false; } @Override public void notifyCheckpointComplete(long checkpointId) { numSuccessfulCheckpoints++; } @Override public List<Integer> snapshotState(long checkpointId, long timestamp) throws Exception { return Collections.singletonList(this.numElementsEmitted); } @Override public void restoreState(List<Integer> state) throws Exception { if (state.isEmpty() || state.size() > 1) { throw new RuntimeException("Test failed due to unexpected recovered state size " + state.size()); } this.numElementsEmitted = state.get(0); } public static void reset() { failedBefore = false; } } private static class ValidatingSink extends RichSinkFunction<Tuple4<Long, Long, Long, IntType>> implements ListCheckpointed<HashMap<Long, Integer>> { private final HashMap<Long, Integer> windowCounts = new HashMap<>(); private final int numKeys; private final int numWindowsExpected; private ValidatingSink(int numKeys, int numWindowsExpected) { this.numKeys = numKeys; this.numWindowsExpected = numWindowsExpected; } @Override public void open(Configuration parameters) throws Exception { // this sink can only work with DOP 1 assertEquals(1, getRuntimeContext().getNumberOfParallelSubtasks()); // it can happen that a checkpoint happens when the complete success state is // already set. In that case we restart with the final state and would never // finish because no more elements arrive. if (windowCounts.size() == numKeys) { boolean seenAll = true; for (Integer windowCount: windowCounts.values()) { if (windowCount != numWindowsExpected) { seenAll = false; break; } } if (seenAll) { throw new SuccessException(); } } } @Override public void close() throws Exception { boolean seenAll = true; if (windowCounts.size() == numKeys) { for (Integer windowCount: windowCounts.values()) { if (windowCount < numWindowsExpected) { seenAll = false; break; } } } assertTrue("The sink must see all expected windows.", seenAll); } @Override public void invoke(Tuple4<Long, Long, Long, IntType> value) throws Exception { // verify the contents of that window, Tuple4.f1 and .f2 are the window start/end // the sum should be "sum (start .. end-1)" int expectedSum = 0; for (long i = value.f1; i < value.f2; i++) { // only sum up positive vals, to filter out the negative start of the // first sliding windows if (i > 0) { expectedSum += i; } } assertEquals("Window start: " + value.f1 + " end: " + value.f2, expectedSum, value.f3.value); Integer curr = windowCounts.get(value.f0); if (curr != null) { windowCounts.put(value.f0, curr + 1); } else { windowCounts.put(value.f0, 1); } if (windowCounts.size() == numKeys) { boolean seenAll = true; for (Integer windowCount: windowCounts.values()) { if (windowCount < numWindowsExpected) { seenAll = false; break; } else if (windowCount > numWindowsExpected) { fail("Window count to high: " + windowCount); } } if (seenAll) { // exit throw new SuccessException(); } } } @Override public List<HashMap<Long, Integer>> snapshotState(long checkpointId, long timestamp) throws Exception { return Collections.singletonList(this.windowCounts); } @Override public void restoreState(List<HashMap<Long, Integer>> state) throws Exception { if (state.isEmpty() || state.size() > 1) { throw new RuntimeException("Test failed due to unexpected recovered state size " + state.size()); } windowCounts.putAll(state.get(0)); } } // Sink for validating the stateful window counts private static class CountValidatingSink extends RichSinkFunction<Tuple4<Long, Long, Long, IntType>> implements ListCheckpointed<HashMap<Long, Integer>> { private final HashMap<Long, Integer> windowCounts = new HashMap<>(); private final int numKeys; private final int numWindowsExpected; private CountValidatingSink(int numKeys, int numWindowsExpected) { this.numKeys = numKeys; this.numWindowsExpected = numWindowsExpected; } @Override public void open(Configuration parameters) throws Exception { // this sink can only work with DOP 1 assertEquals(1, getRuntimeContext().getNumberOfParallelSubtasks()); } @Override public void close() throws Exception { boolean seenAll = true; if (windowCounts.size() == numKeys) { for (Integer windowCount: windowCounts.values()) { if (windowCount < numWindowsExpected) { seenAll = false; break; } } } assertTrue("The source must see all expected windows.", seenAll); } @Override public void invoke(Tuple4<Long, Long, Long, IntType> value) throws Exception { Integer curr = windowCounts.get(value.f0); if (curr != null) { windowCounts.put(value.f0, curr + 1); } else { windowCounts.put(value.f0, 1); } // verify the contents of that window, the contents should be: // (key + num windows so far) assertEquals("Window counts don't match for key " + value.f0 + ".", value.f0.intValue() + windowCounts.get(value.f0), value.f3.value); boolean seenAll = true; if (windowCounts.size() == numKeys) { for (Integer windowCount: windowCounts.values()) { if (windowCount < numWindowsExpected) { seenAll = false; break; } else if (windowCount > numWindowsExpected) { fail("Window count to high: " + windowCount); } } if (seenAll) { // exit throw new SuccessException(); } } } @Override public List<HashMap<Long, Integer>> snapshotState(long checkpointId, long timestamp) throws Exception { return Collections.singletonList(this.windowCounts); } @Override public void restoreState(List<HashMap<Long, Integer>> state) throws Exception { if (state.isEmpty() || state.size() > 1) { throw new RuntimeException("Test failed due to unexpected recovered state size " + state.size()); } this.windowCounts.putAll(state.get(0)); } } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ private static class IntType { public int value; public IntType() {} public IntType(int value) { this.value = value; } } protected int numElementsPerKey() { return 300; } protected int windowSize() { return 100; } protected int windowSlide() { return 100; } protected int numKeys() { return 20; } }
/* * "Copyright (c) 2014 Capgemini Technology Services (hereinafter "Capgemini") * * License/Terms of Use * Permission is hereby granted, free of charge and for the term of intellectual * property rights on the Software, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to use, copy, modify and * propagate free of charge, anywhere in the world, all or part of the Software * subject to the following mandatory conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Any failure to comply with the above shall automatically terminate the license * and be construed as a breach of these Terms of Use causing significant harm to * Capgemini. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, PEACEFUL ENJOYMENT, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of Capgemini shall not be used in * advertising or otherwise to promote the use or other dealings in this Software * without prior written authorization from Capgemini. * * These Terms of Use are subject to French law. * * IMPORTANT NOTICE: The WUIC software implements software components governed by * open source software licenses (BSD and Apache) of which CAPGEMINI is not the * author or the editor. The rights granted on the said software components are * governed by the specific terms and conditions specified by Apache 2.0 and BSD * licenses." */ package com.github.wuic.engine.impl.embedded; import com.github.wuic.engine.NodeEngine; import com.github.wuic.exception.WuicException; import com.github.wuic.exception.wrapper.StreamException; import com.github.wuic.nut.core.ByteArrayNut; import com.github.wuic.nut.Nut; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.github.wuic.engine.EngineRequest; import com.github.wuic.util.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * This {@link NodeEngine engine} defines the base treatments to execute when * compressing a set of files. It could be extended by different sub-classes * which provide compression support. * </p> * * <p> * The compression is never performed if the {@link CGAbstractCompressorEngine#doCompression} flag is set to {@code true}. * </p> * * @author Guillaume DROUET * @version 1.7 * @since 0.1.0 */ public abstract class CGAbstractCompressorEngine extends NodeEngine { /** * Logger. */ private final Logger log = LoggerFactory.getLogger(this.getClass()); /** * Activate compression or not. */ private Boolean doCompression; /** * The extension prefix used to compute new nut name after compression. */ private String renameExtensionPrefix; /** * <p> * Compress a stream (the source) into a target. The target is overridden if * it already exists. * </p> * * @param source the source * @param target the path where to compressed content should be written * @throws com.github.wuic.exception.wrapper.StreamException if an I/O error occurs during compression */ protected abstract void compress(InputStream source, OutputStream target) throws StreamException; /** * <p> * Builds a new instance. * </p> * * @param compress activate compression or not * @param rnp the extension prefix used to compute new nut name after compression. */ public CGAbstractCompressorEngine(final Boolean compress, final String rnp) { doCompression = compress; renameExtensionPrefix = rnp; } /** * {@inheritDoc} */ @Override public List<Nut> internalParse(final EngineRequest request) throws WuicException { // Return the same number of files final List<Nut> retval = new ArrayList<Nut>(request.getNuts().size()); // Compress only if needed if (works()) { // Compress each path for (final Nut nut : request.getNuts()) { final Nut compress = compress(nut); compress.setProxyUri(request.getHeap().proxyUriFor(compress)); retval.add(compress); } } else { retval.addAll(request.getNuts()); } if (getNext() != null) { return getNext().parse(new EngineRequest(retval, request)); } else { return retval; } } /** * <p> * Compresses the given nut. * </p> * * @param nut the nut to be compressed * @return the compressed nut * @throws WuicException if an I/O error occurs */ private Nut compress(final Nut nut) throws WuicException { if (!nut.isTextCompressible() || nut.getName().contains(renameExtensionPrefix)) { return nut; } // Compression has to be implemented by sub-classes InputStream is = null; try { log.debug("Compressing {}", nut.getName()); // Source is = nut.openStream(); // Where compression result will be written final ByteArrayOutputStream os = new ByteArrayOutputStream(); // Do compression compress(is, os); // Build new name final StringBuilder nameBuilder = new StringBuilder(nut.getName()); nameBuilder.insert(nut.getName().lastIndexOf('.'), renameExtensionPrefix); // Now create nut final Nut res = new ByteArrayNut(os.toByteArray(), nameBuilder.toString(), nut.getNutType(), Arrays.asList(nut)); res.setAggregatable(nut.isAggregatable()); res.setBinaryCompressible(nut.isBinaryCompressible()); res.setTextCompressible(nut.isTextCompressible()); res.setCacheable(nut.isCacheable()); // Also compress referenced nuts if (nut.getReferencedNuts() != null) { for (Nut ref : nut.getReferencedNuts()) { res.addReferencedNut(compress(ref)); } } return res; } finally { IOUtils.close(is); } } /** * {@inheritDoc} */ @Override public Boolean works() { return doCompression; } }
/* * Copyright 2012 Hai Bison * * 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 haibison.android.lockpattern; import android.app.Activity; import android.app.Fragment; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.os.ResultReceiver; import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.TextView; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import haibison.android.lockpattern.util.AlpSettings; import haibison.android.lockpattern.util.AlpSettings.Display; import haibison.android.lockpattern.util.AlpSettings.Security; import haibison.android.lockpattern.util.IEncrypter; import haibison.android.lockpattern.util.InvalidEncrypterException; import haibison.android.lockpattern.util.LoadingView; import haibison.android.lockpattern.util.ResourceUtils; import haibison.android.lockpattern.util.UI; import haibison.android.lockpattern.widget.LockPatternUtils; import haibison.android.lockpattern.widget.LockPatternView; import haibison.android.lockpattern.widget.LockPatternView.Cell; import haibison.android.lockpattern.widget.LockPatternView.DisplayMode; import static android.text.format.DateUtils.SECOND_IN_MILLIS; import static haibison.android.lockpattern.BuildConfig.DEBUG; import static haibison.android.lockpattern.util.AlpSettings.Display.METADATA_CAPTCHA_WIRED_DOTS; import static haibison.android.lockpattern.util.AlpSettings.Display.METADATA_MAX_RETRIES; import static haibison.android.lockpattern.util.AlpSettings.Display.METADATA_MIN_WIRED_DOTS; import static haibison.android.lockpattern.util.AlpSettings.Display.METADATA_STEALTH_MODE; import static haibison.android.lockpattern.util.AlpSettings.Security.METADATA_AUTO_SAVE_PATTERN; import static haibison.android.lockpattern.util.AlpSettings.Security.METADATA_ENCRYPTER_CLASS; /** * Main activity for this library. <p> You can deliver result to {@link PendingIntent}'s and/ or {@link ResultReceiver} * too. See {@link #EXTRA_PENDING_INTENT_OK}, {@link #EXTRA_PENDING_INTENT_CANCELLED} and {@link #EXTRA_RESULT_RECEIVER} * for more details. </p> * <p/> * <h1>NOTES</h1> <ul> <li> You must use one of built-in actions when calling this activity. They start with {@code * ACTION_*}. Otherwise the library might behave strangely (we don't cover those cases).</li> <li>You must use one of * the themes that this library supports. They start with {@code R.style.Alp_42447968_Theme_*}. The reason is the themes * contain resources that the library needs.</li> <li>With {@link #ACTION_COMPARE_PATTERN}, there are <b><i>4 possible * result codes</i></b>: {@link Activity#RESULT_OK}, {@link Activity#RESULT_CANCELED}, {@link #RESULT_FAILED} and {@link * #RESULT_FORGOT_PATTERN}.</li> <li>With {@link #ACTION_VERIFY_CAPTCHA}, there are <b><i>3 possible result * codes</i></b>: {@link Activity#RESULT_OK}, {@link Activity#RESULT_CANCELED}, and {@link #RESULT_FAILED}.</li> </ul> * * @author Hai Bison * @since v1.0 */ public class LockPatternActivity extends Activity { private static final String CLASSNAME = LockPatternActivity.class.getName(); /** * Use this action to create new pattern. You can provide an {@link IEncrypter} with {@link * Security#setEncrypterClass(android.content.Context, Class)} to improve security. * <p/> * If the user created a pattern, {@link Activity#RESULT_OK} returns with the pattern ({@link #EXTRA_PATTERN}). * Otherwise {@link Activity#RESULT_CANCELED} returns. * * @see #EXTRA_PENDING_INTENT_OK * @see #EXTRA_PENDING_INTENT_CANCELLED * @since v2.4 beta */ public static final String ACTION_CREATE_PATTERN = CLASSNAME + ".CREATE_PATTERN"; /** * Creates new intent with {@link #ACTION_CREATE_PATTERN}. You must call this intent from a UI thread. * * @param context the context. * @return new intent. */ public static Intent newIntentToCreatePattern(Context context) { Intent result = new Intent(ACTION_CREATE_PATTERN, null, context, LockPatternActivity.class); return result; }// newIntentToCreatePattern() /** * This method is a shortcut to call {@link #newIntentToCreatePattern(Context)} from a UI thread. * * @param caller must be an instance of {@link Activity}, or {@link Fragment} or support library's {@code * Fragment}. <b>Warning:</b> Have a look at description of {@link * #call_startActivityForResult(Object, Intent, int)}. * @param context the context. * @param requestCode request code for {@link Activity#startActivityForResult(Intent, int)} or counterpart methods * of fragments. * @throws NullPointerException if caller or context is {@code null}. * @throws RuntimeException if any, while calling {@link #call_startActivityForResult(Object, Intent, int)}. */ public static void startToCreatePattern(Object caller, Context context, int requestCode) { call_startActivityForResult(caller, newIntentToCreatePattern(context), requestCode); }// startToCreatePattern() /** * This methods tries to find and call {@code startActivityForResult(Intent, int)} from given caller. Note that if * you use ProGuard, it will work fine with {@link Activity} (or its descendants), framework {@link Fragment}. But * it won't work with support library {@code Fragment} (or its descendants), unless you tell ProGuard to ignore it. * * @param caller the caller. * @param intent the intent. * @param requestCode request code. * @throws NullPointerException if caller or intent is {@code null}. * @throws RuntimeException which wraps any exception while invoking original method from the caller. */ public static void call_startActivityForResult(Object caller, Intent intent, int requestCode) { try { Method method = caller.getClass().getMethod("startActivityForResult", Intent.class, int.class); method.setAccessible(true); method.invoke(caller, intent, requestCode); } catch (Throwable t) { Log.e(CLASSNAME, t.getMessage(), t); // Re-throw it throw new RuntimeException(t); } }// call_startActivityForResult() /** * Use this action to compare pattern. You provide the pattern to be compared with {@link #EXTRA_PATTERN}. * <p/> * If you enabled feature auto-save pattern before (with {@link Security#setAutoSavePattern(android.content.Context, * boolean)} ), then you don't need {@link #EXTRA_PATTERN} at this time. But if you use this extra, its priority is * higher than the one stored in shared preferences. * <p/> * You can use {@link #EXTRA_PENDING_INTENT_FORGOT_PATTERN} to help your users in case they forgot the patterns. * <p/> * If the user passes, {@link Activity#RESULT_OK} returns. If not, {@link #RESULT_FAILED} returns. * <p/> * If the user cancels the task, {@link Activity#RESULT_CANCELED} returns. * <p/> * In any case, there will have extra {@link #EXTRA_RETRY_COUNT} available in the intent result. * * @see #EXTRA_PATTERN * @see #EXTRA_PENDING_INTENT_OK * @see #EXTRA_PENDING_INTENT_CANCELLED * @see #RESULT_FAILED * @see #EXTRA_RETRY_COUNT * @since v2.4 beta */ public static final String ACTION_COMPARE_PATTERN = CLASSNAME + ".COMPARE_PATTERN"; /** * Creates new intent with {@link #ACTION_COMPARE_PATTERN}. You must call this intent from a UI thread. * * @param context the context. * @param pattern optional, see {@link #EXTRA_PATTERN}. * @return new intent. */ public static Intent newIntentToComparePattern(Context context, char[] pattern) { Intent result = new Intent(ACTION_COMPARE_PATTERN, null, context, LockPatternActivity.class); if (pattern != null) result.putExtra(EXTRA_PATTERN, pattern); return result; }// newIntentToComparePattern() /** * This method is a shortcut to call {@link #newIntentToComparePattern(Context, char[])} from a UI thread. * * @param caller must be an instance of {@link Activity}, or {@link Fragment} or support library's {@code * Fragment}. <b>Warning:</b> Have a look at description of {@link * #call_startActivityForResult(Object, Intent, int)}. * @param context the context. * @param requestCode request code for {@link Activity#startActivityForResult(Intent, int)} or counterpart methods * of fragments. * @param pattern optional, see {@link #EXTRA_PATTERN}. * @throws NullPointerException if caller or context is {@code null}. * @throws RuntimeException if any, while calling {@link #call_startActivityForResult(Object, Intent, int)}. */ public static void startToComparePattern(Object caller, Context context, int requestCode, char[] pattern) { call_startActivityForResult(caller, newIntentToComparePattern(context, pattern), requestCode); }// startToComparePattern() /** * Use this action to let the activity generate a random pattern and ask the user to re-draw it to verify. * <p/> * The default length of the auto-generated pattern is {@code 4}. You can change it with {@link * Display#setCaptchaWiredDots(android.content.Context, int)}. * * @since v2.7 beta */ public static final String ACTION_VERIFY_CAPTCHA = CLASSNAME + ".VERIFY_CAPTCHA"; /** * Creates new intent with {@link #ACTION_VERIFY_CAPTCHA}. You must call this intent from a UI thread. * * @param context the context. * @return new intent. */ public static Intent newIntentToVerifyCaptcha(Context context) { Intent result = new Intent(ACTION_VERIFY_CAPTCHA, null, context, LockPatternActivity.class); return result; }// newIntentToVerifyCaptcha() /** * This method is a shortcut to call {@link #newIntentToVerifyCaptcha(Context)} from a UI thread. * * @param caller must be an instance of {@link Activity}, or {@link Fragment} or support library's {@code * Fragment}. <b>Warning:</b> Have a look at description of {@link * #call_startActivityForResult(Object, Intent, int)}. * @param context the context. * @param requestCode request code for {@link Activity#startActivityForResult(Intent, int)} or counterpart methods * of fragments. * @throws NullPointerException if caller or context is {@code null}. * @throws RuntimeException if any, while calling {@link #call_startActivityForResult(Object, Intent, int)}. */ public static void startToVerifyCaptcha(Object caller, Context context, int requestCode) { call_startActivityForResult(caller, newIntentToVerifyCaptcha(context), requestCode); }// startToVerifyCaptcha() /** * If you use {@link #ACTION_COMPARE_PATTERN} and the user fails to "login" after a number of tries, this activity * will finish with this result code. * * @see #ACTION_COMPARE_PATTERN * @see #EXTRA_RETRY_COUNT */ public static final int RESULT_FAILED = RESULT_FIRST_USER + 1; /** * If you use {@link #ACTION_COMPARE_PATTERN} and the user forgot his/ her pattern and decided to ask for your help * with recovering the pattern ( {@link #EXTRA_PENDING_INTENT_FORGOT_PATTERN}), this activity will finish with this * result code. * * @see #ACTION_COMPARE_PATTERN * @see #EXTRA_RETRY_COUNT * @see #EXTRA_PENDING_INTENT_FORGOT_PATTERN * @since v2.8 beta */ public static final int RESULT_FORGOT_PATTERN = RESULT_FIRST_USER + 2; /** * For actions {@link #ACTION_COMPARE_PATTERN} and {@link #ACTION_VERIFY_CAPTCHA}, this key holds the number of * tries that the user attempted to verify the input pattern. */ public static final String EXTRA_RETRY_COUNT = CLASSNAME + ".RETRY_COUNT"; /** * Sets value of this key to a theme in {@code R.style.Alp_42447968_Theme_*} . Default is the one you set in your * {@code AndroidManifest.xml}. Note that theme {@link R.style#Alp_42447968_Theme_Light_DarkActionBar} is available * in API 4+, but it only works in API 14+. * * @since v1.5.3 beta */ public static final String EXTRA_THEME = CLASSNAME + ".THEME"; /** * Key to hold the pattern. It must be a {@code char[]} array. * <p/> * <ul> <li>If you use encrypter, it should be an encrypted array.</li> <li>If you don't use encrypter, it should be * the SHA-1 value of the actual pattern. You can generate the value by {@link LockPatternUtils#patternToSha1 * (List)}.</li> </ul> * * @since v2 beta */ public static final String EXTRA_PATTERN = CLASSNAME + ".PATTERN"; /** * You can provide an {@link ResultReceiver} with this key. The activity will notify your receiver the same result * code and intent data as you will receive them in {@link #onActivityResult(int, int, Intent)}. * * @since v2.4 beta */ public static final String EXTRA_RESULT_RECEIVER = CLASSNAME + ".RESULT_RECEIVER"; /** * Put a {@link PendingIntent} into this key. It will be sent before {@link Activity#RESULT_OK} will be returning. * If you were calling this activity with {@link #ACTION_CREATE_PATTERN}, key {@link #EXTRA_PATTERN} will be * attached to the original intent which the pending intent holds. * <p/> * <h1>Notes</h1> <ul> <li>If you're going to use an activity, you don't need {@link Intent#FLAG_ACTIVITY_NEW_TASK} * for the intent, since the library will call it inside {@link LockPatternActivity} .</li> </ul> */ public static final String EXTRA_PENDING_INTENT_OK = CLASSNAME + ".PENDING_INTENT_OK"; /** * Put a {@link PendingIntent} into this key. It will be sent before {@link Activity#RESULT_CANCELED} will be * returning. * <p/> * <h1>Notes</h1> <ul> <li>If you're going to use an activity, you don't need {@link Intent#FLAG_ACTIVITY_NEW_TASK} * for the intent, since the library will call it inside {@link LockPatternActivity} .</li> </ul> */ public static final String EXTRA_PENDING_INTENT_CANCELLED = CLASSNAME + ".PENDING_INTENT_CANCELLED"; /** * You put a {@link PendingIntent} into this extra. The library will show a button <i>"Forgot pattern?"</i> and call * your intent later when the user taps it. * <p/> * <h1>Notes</h1> <ul> <li>If you use an activity, you don't need {@link Intent#FLAG_ACTIVITY_NEW_TASK} for the * intent, since the library will call it inside {@link LockPatternActivity} .</li> <li>{@link LockPatternActivity} * will finish with {@link #RESULT_FORGOT_PATTERN} <i><b>after</b> making a call</i> to start your pending * intent.</li> <li>It is your responsibility to make sure the Intent is good. The library doesn't cover any errors * when calling your intent.</li> </ul> * * @author Thanks to Yan Cheng Cheok for his idea. * @see #ACTION_COMPARE_PATTERN * @since v2.8 beta */ public static final String EXTRA_PENDING_INTENT_FORGOT_PATTERN = CLASSNAME + ".PENDING_INTENT_FORGOT_PATTERN"; /** * Helper enum for button OK commands. (Because we use only one "OK" button for different commands). * * @author Hai Bison */ private enum ButtonOkCommand { CONTINUE, FORGOT_PATTERN, DONE }// ButtonOkCommand /** * Delay time to reload the lock pattern view after a wrong pattern. */ private static final long DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW = SECOND_IN_MILLIS; ///////// // FIELDS ///////// private int mMaxRetries, mMinWiredDots, mRetryCount = 0, mCaptchaWiredDots; private boolean mAutoSave, mStealthMode; private IEncrypter mEncrypter; private ButtonOkCommand mBtnOkCmd; private Intent mIntentResult; private LoadingView<Void, Void, Object> mLoadingView; /////////// // CONTROLS /////////// private TextView mTextInfo; private LockPatternView mLockPatternView; private View mFooter; private Button mBtnConfirm, mBtnCancel; private View mViewGroupProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { if (DEBUG) Log.d(CLASSNAME, "onCreate()"); /** * EXTRA_THEME */ if (getIntent().hasExtra(EXTRA_THEME)) setTheme(getIntent().getIntExtra(EXTRA_THEME, R.style.Alp_42447968_Theme_Dark)); /** * Apply theme resources */ final int resThemeResources = ResourceUtils.resolveAttribute(this, R.attr.alp_42447968_theme_resources); if (resThemeResources == 0) throw new RuntimeException( "Please provide theme resource via attribute `alp_42447968_theme_resources`." + " For example: <item name=\"alp_42447968_theme_resources\">@style/Alp_42447968" + ".ThemeResources.Light</item>"); getTheme().applyStyle(resThemeResources, true); super.onCreate(savedInstanceState); loadSettings(); mIntentResult = new Intent(); setResult(RESULT_CANCELED, mIntentResult); initContentView(); }// onCreate() @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (DEBUG) Log.d(CLASSNAME, "onConfigurationChanged()"); initContentView(); }// onConfigurationChanged() @Override public boolean onKeyDown(int keyCode, KeyEvent event) { /** * Use this hook instead of onBackPressed(), because onBackPressed() is not available in API 4. */ if (keyCode == KeyEvent.KEYCODE_BACK && ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { if (mLoadingView != null) mLoadingView.cancel(true); finishWithNegativeResult(RESULT_CANCELED); return true; }// if return super.onKeyDown(keyCode, event); }// onKeyDown() @Override public boolean onTouchEvent(MotionEvent event) { /** * Support canceling dialog on touching outside in APIs < 11. * * This piece of code is copied from android.view.Window. You can find it by searching for methods * shouldCloseOnTouch() and isOutOfBounds(). */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && event.getAction() == MotionEvent.ACTION_DOWN && getWindow().peekDecorView() != null) { final int x = (int) event.getX(); final int y = (int) event.getY(); final int slop = ViewConfiguration.get(this).getScaledWindowTouchSlop(); final View decorView = getWindow().getDecorView(); boolean isOutOfBounds = (x < -slop) || (y < -slop) || (x > (decorView.getWidth() + slop)) || (y > (decorView.getHeight() + slop)); if (isOutOfBounds) { finishWithNegativeResult(RESULT_CANCELED); return true; } }// if return super.onTouchEvent(event); }// onTouchEvent() @Override protected void onDestroy() { if (mLoadingView != null) mLoadingView.cancel(true); super.onDestroy(); }// onDestroy() /** * Loads settings, either from manifest or {@link AlpSettings}. */ private void loadSettings() { Bundle metaData = null; try { metaData = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA).metaData; } catch (NameNotFoundException e) { /** * Never catch this. */ e.printStackTrace(); } if (metaData != null && metaData.containsKey(METADATA_MIN_WIRED_DOTS)) mMinWiredDots = AlpSettings.Display.validateMinWiredDots(this, metaData.getInt(METADATA_MIN_WIRED_DOTS)); else mMinWiredDots = AlpSettings.Display.getMinWiredDots(this); if (metaData != null && metaData.containsKey(METADATA_MAX_RETRIES)) mMaxRetries = AlpSettings.Display.validateMaxRetries(this, metaData.getInt(METADATA_MAX_RETRIES)); else mMaxRetries = AlpSettings.Display.getMaxRetries(this); if (metaData != null && metaData.containsKey(METADATA_AUTO_SAVE_PATTERN)) mAutoSave = metaData.getBoolean(METADATA_AUTO_SAVE_PATTERN); else mAutoSave = AlpSettings.Security.isAutoSavePattern(this); if (metaData != null && metaData.containsKey(METADATA_CAPTCHA_WIRED_DOTS)) mCaptchaWiredDots = AlpSettings.Display.validateCaptchaWiredDots( this, metaData.getInt(METADATA_CAPTCHA_WIRED_DOTS)); else mCaptchaWiredDots = AlpSettings.Display.getCaptchaWiredDots(this); if (metaData != null && metaData.containsKey(METADATA_STEALTH_MODE)) mStealthMode = metaData.getBoolean(METADATA_STEALTH_MODE); else mStealthMode = AlpSettings.Display.isStealthMode(this); /** * Encrypter. */ char[] encrypterClass; if (metaData != null && metaData.containsKey(METADATA_ENCRYPTER_CLASS)) encrypterClass = metaData.getString(METADATA_ENCRYPTER_CLASS).toCharArray(); else encrypterClass = AlpSettings.Security.getEncrypterClass(this); if (encrypterClass != null) { try { mEncrypter = (IEncrypter) Class.forName(new String(encrypterClass), false, getClassLoader()) .newInstance(); } catch (Throwable t) { throw new InvalidEncrypterException(); } } }// loadSettings() /** * Initializes UI... */ private void initContentView() { /** * Save all controls' state to restore later. */ CharSequence infoText = mTextInfo != null ? mTextInfo.getText() : null; Boolean btnOkEnabled = mBtnConfirm != null ? mBtnConfirm.isEnabled() : null; LockPatternView.DisplayMode lastDisplayMode = mLockPatternView != null ? mLockPatternView.getDisplayMode() : null; List<Cell> lastPattern = mLockPatternView != null ? mLockPatternView.getPattern() : null; setContentView(R.layout.alp_42447968_lock_pattern_activity); UI.adjustDialogSizeForLargeScreens(getWindow()); /** * MAP CONTROLS */ mTextInfo = (TextView) findViewById(R.id.alp_42447968_textview_info); mLockPatternView = (LockPatternView) findViewById(R.id.alp_42447968_view_lock_pattern); mFooter = findViewById(R.id.alp_42447968_viewgroup_footer); mBtnCancel = (Button) findViewById(R.id.alp_42447968_button_cancel); mBtnConfirm = (Button) findViewById(R.id.alp_42447968_button_confirm); mViewGroupProgressBar = findViewById(R.id.alp_42447968_view_group_progress_bar); /** * SETUP CONTROLS */ mViewGroupProgressBar.setOnClickListener(mViewGroupProgressBarOnClickListener); /** * LOCK PATTERN VIEW */ switch (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) { case Configuration.SCREENLAYOUT_SIZE_LARGE: case Configuration.SCREENLAYOUT_SIZE_XLARGE: { final int size = getResources().getDimensionPixelSize( R.dimen.alp_42447968_lockpatternview_size); LayoutParams lp = mLockPatternView.getLayoutParams(); lp.width = size; lp.height = size; mLockPatternView.setLayoutParams(lp); break; }// LARGE / XLARGE } // Haptic feedback boolean hapticFeedbackEnabled = false; try { /** * This call requires permission WRITE_SETTINGS. Since it's not necessary, we don't need to declare that * permission in manifest. Don't scare our users :-D */ hapticFeedbackEnabled = Settings.System.getInt(getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) != 0; } catch (Throwable t) { // Ignore it t.printStackTrace(); } mLockPatternView.setTactileFeedbackEnabled(hapticFeedbackEnabled); mLockPatternView.setInStealthMode(mStealthMode && !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())); mLockPatternView.setOnPatternListener(mLockPatternViewListener); if (lastPattern != null && lastDisplayMode != null && !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) mLockPatternView.setPattern(lastDisplayMode, lastPattern); /** * COMMAND BUTTONS */ if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { mBtnCancel.setOnClickListener(mBtnCancelOnClickListener); mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener); mBtnCancel.setVisibility(View.VISIBLE); mFooter.setVisibility(View.VISIBLE); if (infoText != null) mTextInfo.setText(infoText); else mTextInfo.setText(R.string.alp_42447968_msg_draw_an_unlock_pattern); /** * BUTTON OK */ if (mBtnOkCmd == null) mBtnOkCmd = ButtonOkCommand.CONTINUE; switch (mBtnOkCmd) { case CONTINUE: mBtnConfirm.setText(R.string.alp_42447968_cmd_continue); break; case DONE: mBtnConfirm.setText(R.string.alp_42447968_cmd_confirm); break; default: /** * Do nothing. */ break; } if (btnOkEnabled != null) mBtnConfirm.setEnabled(btnOkEnabled); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { if (TextUtils.isEmpty(infoText)) mTextInfo.setText(R.string.alp_42447968_msg_draw_pattern_to_unlock); else mTextInfo.setText(infoText); if (getIntent().hasExtra(EXTRA_PENDING_INTENT_FORGOT_PATTERN)) { mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener); mBtnConfirm.setText(R.string.alp_42447968_cmd_forgot_pattern); mBtnConfirm.setEnabled(true); mFooter.setVisibility(View.VISIBLE); } }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { mTextInfo.setText(R.string.alp_42447968_msg_redraw_pattern_to_confirm); /** * NOTE: EXTRA_PATTERN should hold a char[] array. In this case we use it as a temporary variable to hold * a list of Cell. */ final ArrayList<Cell> pattern; if (getIntent().hasExtra(EXTRA_PATTERN)) pattern = getIntent().getParcelableArrayListExtra(EXTRA_PATTERN); else getIntent().putParcelableArrayListExtra(EXTRA_PATTERN, pattern = LockPatternUtils.genCaptchaPattern(mCaptchaWiredDots)); mLockPatternView.setPattern(DisplayMode.Animate, pattern); }// ACTION_VERIFY_CAPTCHA }// initContentView() /** * Compares {@code pattern} to the given pattern ( {@link #ACTION_COMPARE_PATTERN}) or to the generated "CAPTCHA" * pattern ( {@link #ACTION_VERIFY_CAPTCHA}). Then finishes the activity if they match. * * @param pattern the pattern to be compared. */ private void doComparePattern(final List<Cell> pattern) { if (pattern == null) return; /** * Use a LoadingView because decrypting pattern might take time... */ mLoadingView = new LoadingView<Void, Void, Object>(this, mViewGroupProgressBar) { @Override protected Object doInBackground(Void... params) { if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { char[] currentPattern = getIntent().getCharArrayExtra(EXTRA_PATTERN); if (currentPattern == null) currentPattern = AlpSettings.Security.getPattern(LockPatternActivity.this); if (currentPattern != null) { if (mEncrypter != null) return pattern.equals(mEncrypter.decrypt(LockPatternActivity.this, currentPattern)); else return Arrays.equals(currentPattern, LockPatternUtils.patternToSha1(pattern).toCharArray()); } }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { return pattern.equals(getIntent().getParcelableArrayListExtra(EXTRA_PATTERN)); }// ACTION_VERIFY_CAPTCHA return false; }// doInBackground() @Override protected void onPostExecute(Object result) { super.onPostExecute(result); if ((Boolean) result) finishWithResultOk(null); else { mRetryCount++; mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount); if (mRetryCount >= mMaxRetries) finishWithNegativeResult(RESULT_FAILED); else { mLockPatternView.setDisplayMode(DisplayMode.Wrong); mTextInfo.setText(R.string.alp_42447968_msg_try_again); mLockPatternView.postDelayed(mLockPatternViewReloader, DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW); } } }// onPostExecute() }; mLoadingView.execute(); }// doComparePattern() /** * Checks and creates the pattern. * * @param pattern the current pattern of lock pattern view. */ private void doCheckAndCreatePattern(final List<Cell> pattern) { if (pattern.size() < mMinWiredDots) { mLockPatternView.setDisplayMode(DisplayMode.Wrong); mTextInfo.setText(getResources().getQuantityString( R.plurals.alp_42447968_pmsg_connect_x_dots, mMinWiredDots, mMinWiredDots)); mLockPatternView.postDelayed(mLockPatternViewReloader, DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW); return; }// if if (getIntent().hasExtra(EXTRA_PATTERN)) { /** * Use a LoadingView because decrypting pattern might take time... */ mLoadingView = new LoadingView<Void, Void, Object>(this, mViewGroupProgressBar) { @Override protected Object doInBackground(Void... params) { if (mEncrypter != null) return pattern.equals(mEncrypter.decrypt(LockPatternActivity.this, getIntent() .getCharArrayExtra(EXTRA_PATTERN))); else return Arrays.equals(getIntent().getCharArrayExtra(EXTRA_PATTERN), LockPatternUtils.patternToSha1(pattern).toCharArray()); }// doInBackground() @Override protected void onPostExecute(Object result) { super.onPostExecute(result); if ((Boolean) result) { mTextInfo.setText(R.string.alp_42447968_msg_your_new_unlock_pattern); mBtnConfirm.setEnabled(true); } else { mTextInfo.setText(R.string.alp_42447968_msg_redraw_pattern_to_confirm); mBtnConfirm.setEnabled(false); mLockPatternView.setDisplayMode(DisplayMode.Wrong); mLockPatternView.postDelayed(mLockPatternViewReloader, DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW); } }// onPostExecute() }; mLoadingView.execute(); } else { /** * Use a LoadingView because encrypting pattern might take time... */ mLoadingView = new LoadingView<Void, Void, Object>(this, mViewGroupProgressBar) { @Override protected Object doInBackground(Void... params) { return mEncrypter != null ? mEncrypter.encrypt(LockPatternActivity.this, pattern) : LockPatternUtils.patternToSha1(pattern).toCharArray(); }// onCancel() @Override protected void onPostExecute(Object result) { super.onPostExecute(result); getIntent().putExtra(EXTRA_PATTERN, (char[]) result); mTextInfo.setText(R.string.alp_42447968_msg_pattern_recorded); mBtnConfirm.setEnabled(true); }// onPostExecute() }; mLoadingView.execute(); } }// doCheckAndCreatePattern() /** * Finishes activity with {@link Activity#RESULT_OK}. * * @param pattern the pattern, if this is in mode creating pattern. In any cases, it can be set to {@code null}. */ private void finishWithResultOk(char[] pattern) { if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) mIntentResult.putExtra(EXTRA_PATTERN, pattern); else { /** * If the user was "logging in", minimum try count can not be zero. */ mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount + 1); } setResult(RESULT_OK, mIntentResult); /** * ResultReceiver */ ResultReceiver receiver = getIntent().getParcelableExtra(EXTRA_RESULT_RECEIVER); if (receiver != null) { Bundle bundle = new Bundle(); if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) bundle.putCharArray(EXTRA_PATTERN, pattern); else { /** * If the user was "logging in", minimum try count can not be zero. */ bundle.putInt(EXTRA_RETRY_COUNT, mRetryCount + 1); } receiver.send(RESULT_OK, bundle); } /** * PendingIntent */ PendingIntent pi = getIntent().getParcelableExtra(EXTRA_PENDING_INTENT_OK); if (pi != null) { try { pi.send(this, RESULT_OK, mIntentResult); } catch (Throwable t) { Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t); } }//if finish(); }// finishWithResultOk() /** * Finishes the activity with negative result ( {@link Activity#RESULT_CANCELED}, {@link #RESULT_FAILED} or {@link * #RESULT_FORGOT_PATTERN}). */ private void finishWithNegativeResult(int resultCode) { if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount); setResult(resultCode, mIntentResult); /** * ResultReceiver */ ResultReceiver receiver = getIntent().getParcelableExtra(EXTRA_RESULT_RECEIVER); if (receiver != null) { Bundle resultBundle = null; if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { resultBundle = new Bundle(); resultBundle.putInt(EXTRA_RETRY_COUNT, mRetryCount); } receiver.send(resultCode, resultBundle); }//if /** * PendingIntent */ PendingIntent pi = getIntent().getParcelableExtra(EXTRA_PENDING_INTENT_CANCELLED); if (pi != null) { try { pi.send(this, resultCode, mIntentResult); } catch (Throwable t) { Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t); } }//if finish(); }// finishWithNegativeResult() //////////// // LISTENERS //////////// /** * Pattern listener for LockPatternView. */ private final LockPatternView.OnPatternListener mLockPatternViewListener = new LockPatternView.OnPatternListener() { @Override public void onPatternStart() { mLockPatternView.removeCallbacks(mLockPatternViewReloader); mLockPatternView.setDisplayMode(DisplayMode.Correct); if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { mTextInfo.setText(R.string.alp_42447968_msg_release_finger_when_done); mBtnConfirm.setEnabled(false); if (mBtnOkCmd == ButtonOkCommand.CONTINUE) getIntent().removeExtra(EXTRA_PATTERN); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { mTextInfo.setText(R.string.alp_42447968_msg_draw_pattern_to_unlock); }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { mTextInfo.setText(R.string.alp_42447968_msg_redraw_pattern_to_confirm); }// ACTION_VERIFY_CAPTCHA }// onPatternStart() @Override public void onPatternDetected(List<Cell> pattern) { if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { doCheckAndCreatePattern(pattern); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { doComparePattern(pattern); }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { if (!DisplayMode.Animate.equals(mLockPatternView.getDisplayMode())) doComparePattern(pattern); }// ACTION_VERIFY_CAPTCHA }// onPatternDetected() @Override public void onPatternCleared() { mLockPatternView.removeCallbacks(mLockPatternViewReloader); if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { mLockPatternView.setDisplayMode(DisplayMode.Correct); mBtnConfirm.setEnabled(false); if (mBtnOkCmd == ButtonOkCommand.CONTINUE) { getIntent().removeExtra(EXTRA_PATTERN); mTextInfo.setText(R.string.alp_42447968_msg_draw_an_unlock_pattern); } else mTextInfo.setText(R.string.alp_42447968_msg_redraw_pattern_to_confirm); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { mLockPatternView.setDisplayMode(DisplayMode.Correct); mTextInfo.setText(R.string.alp_42447968_msg_draw_pattern_to_unlock); }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { mTextInfo.setText(R.string.alp_42447968_msg_redraw_pattern_to_confirm); List<Cell> pattern = getIntent().getParcelableArrayListExtra(EXTRA_PATTERN); mLockPatternView.setPattern(DisplayMode.Animate, pattern); }// ACTION_VERIFY_CAPTCHA }// onPatternCleared() @Override public void onPatternCellAdded(List<Cell> pattern) { // Nothing to do }// onPatternCellAdded() };// mLockPatternViewListener /** * Click listener for button Cancel. */ private final View.OnClickListener mBtnCancelOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { finishWithNegativeResult(RESULT_CANCELED); }// onClick() };// mBtnCancelOnClickListener /** * Click listener for button Confirm. */ private final View.OnClickListener mBtnConfirmOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { if (mBtnOkCmd == ButtonOkCommand.CONTINUE) { mBtnOkCmd = ButtonOkCommand.DONE; mLockPatternView.clearPattern(); mTextInfo.setText(R.string.alp_42447968_msg_redraw_pattern_to_confirm); mBtnConfirm.setText(R.string.alp_42447968_cmd_confirm); mBtnConfirm.setEnabled(false); } else { final char[] pattern = getIntent().getCharArrayExtra(EXTRA_PATTERN); if (mAutoSave) AlpSettings.Security.setPattern(LockPatternActivity.this, pattern); finishWithResultOk(pattern); } }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { /** * We don't need to verify the extra. First, this button is only visible if there is this extra in * the intent. Second, it is the responsibility of the caller to make sure the extra is good. */ PendingIntent pi = null; try { pi = getIntent().getParcelableExtra(EXTRA_PENDING_INTENT_FORGOT_PATTERN); if (pi != null) pi.send(); } catch (Throwable t) { Log.e(CLASSNAME, "Error sending pending intent: " + pi, t); } finishWithNegativeResult(RESULT_FORGOT_PATTERN); }// ACTION_COMPARE_PATTERN }// onClick() };// mBtnConfirmOnClickListener /** * This reloads the {@link #mLockPatternView} after a wrong pattern. */ private final Runnable mLockPatternViewReloader = new Runnable() { @Override public void run() { mLockPatternView.clearPattern(); mLockPatternViewListener.onPatternCleared(); }// run() };// mLockPatternViewReloader /** * Click listener for view group progress bar. */ private final View.OnClickListener mViewGroupProgressBarOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { /** * Do nothing. We just don't want the user to interact with controls behind this view. */ }// onClick() };// mViewGroupProgressBarOnClickListener }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.samza.system.kafka; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; import kafka.producer.ProducerClosedException; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.Cluster; import org.apache.kafka.common.Metric; import org.apache.kafka.common.MetricName; import org.apache.kafka.common.PartitionInfo; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.record.Record; import org.apache.kafka.common.record.RecordBatch; import org.apache.kafka.test.TestUtils; public class MockKafkaProducer implements Producer<byte[], byte[]> { private Cluster _cluster; private List<FutureTask<RecordMetadata>> _callbacksList = new ArrayList<FutureTask<RecordMetadata>>(); private boolean shouldBuffer = false; private boolean errorNext = false; private boolean errorInCallback = true; private Exception exception = null; private AtomicInteger msgsSent = new AtomicInteger(0); private boolean closed = false; private int openCount = 0; /* * Helps mock out buffered behavior seen in KafkaProducer. This MockKafkaProducer enables you to: * - Create send that will instantly succeed & return a successful future * - Set error for the next message that is sent (using errorNext). In this case, the next call to send returns a * future with exception. * Please note that errorNext is reset to false once a message send has failed. This means that errorNext has to be * manually set to true in the unit test, before expecting failure for another message. * - "shouldBuffer" can be turned on to start buffering messages. This will store all the callbacks and execute it * at a later point of time in a separate thread. This thread NEEDS to be triggered from the unit test itself * using "startDelayedSendThread" method * - "Offset" in RecordMetadata is not guranteed to be correct */ public MockKafkaProducer(int numNodes, String topicName, int numPartitions) { this._cluster = TestUtils.clusterWith(numNodes, topicName, numPartitions); } public void setShouldBuffer(boolean shouldBuffer) { this.shouldBuffer = shouldBuffer; } public void setErrorNext(boolean errorNext, boolean errorInCallback, Exception exception) { this.errorNext = errorNext; this.errorInCallback = errorInCallback; this.exception = exception; } public int getMsgsSent() { return this.msgsSent.get(); } public Thread startDelayedSendThread(final int sleepTime) { Thread t = new Thread(new FlushRunnable(sleepTime)); t.start(); return t; } @Override public Future<RecordMetadata> send(ProducerRecord record) { return send(record, null); } private RecordMetadata getRecordMetadata(ProducerRecord record) { return new RecordMetadata(new TopicPartition(record.topic(), record.partition() == null ? 0 : record.partition()), 0, this.msgsSent.get(), -1L, -1, -1, -1); } @Override public Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) { if (closed) { throw new ProducerClosedException(); } if (errorNext) { if (!errorInCallback) { this.errorNext = false; throw (RuntimeException)exception; } if (shouldBuffer) { FutureTask<RecordMetadata> f = new FutureTask<RecordMetadata>(new Callable<RecordMetadata>() { @Override public RecordMetadata call() throws Exception { callback.onCompletion(null, exception); return getRecordMetadata(record); } }); _callbacksList.add(f); this.errorNext = false; return f; } else { callback.onCompletion(null, this.exception); this.errorNext = false; return new FutureFailure(this.exception); } } else { if (shouldBuffer) { FutureTask<RecordMetadata> f = new FutureTask<RecordMetadata>(new Callable<RecordMetadata>() { @Override public RecordMetadata call() throws Exception { msgsSent.incrementAndGet(); RecordMetadata metadata = getRecordMetadata(record); callback.onCompletion(metadata, null); return metadata; } }); _callbacksList.add(f); return f; } else { int offset = msgsSent.incrementAndGet(); final RecordMetadata metadata = getRecordMetadata(record); callback.onCompletion(metadata, null); return new FutureSuccess(record, offset); } } } @Override public List<PartitionInfo> partitionsFor(String topic) { return this._cluster.partitionsForTopic(topic); } @Override public Map<MetricName, Metric> metrics() { return null; } @Override public void close() { close(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } @Override public void close(long timeout, TimeUnit timeUnit) { closed = true; // The real producer will flush messages as part of closing. We'll invoke flush here to approximate that behavior. new FlushRunnable(0).run(); } public void open() { this.closed = false; openCount++; } public boolean isClosed() { return closed; } public int getOpenCount() { return openCount; } public synchronized void flush () { new FlushRunnable(0).run(); } public void initTransactions() { } public void abortTransaction() { } public void beginTransaction() { } public void commitTransaction() { } public void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, String consumerGroupId) { } private static class FutureFailure implements Future<RecordMetadata> { private final ExecutionException exception; public FutureFailure(Exception exception) { this.exception = new ExecutionException(exception); } @Override public boolean cancel(boolean interrupt) { return false; } @Override public RecordMetadata get() throws ExecutionException { throw this.exception; } @Override public RecordMetadata get(long timeout, TimeUnit unit) throws ExecutionException { throw this.exception; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } } private static class FutureSuccess implements Future<RecordMetadata> { private ProducerRecord record; private final RecordMetadata _metadata; public FutureSuccess(ProducerRecord record, int offset) { this.record = record; this._metadata = new RecordMetadata(new TopicPartition(record.topic(), record.partition() == null ? 0 : record.partition()), 0, offset, RecordBatch.NO_TIMESTAMP, -1, -1, -1); } @Override public boolean cancel(boolean interrupt) { return false; } @Override public RecordMetadata get() throws ExecutionException { return this._metadata; } @Override public RecordMetadata get(long timeout, TimeUnit unit) throws ExecutionException { return this._metadata; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } } private class FlushRunnable implements Runnable { private final int _sleepTime; public FlushRunnable(int sleepTime) { _sleepTime = sleepTime; } public void run() { FutureTask[] callbackArray = new FutureTask[_callbacksList.size()]; AtomicReferenceArray<FutureTask> _bufferList = new AtomicReferenceArray<FutureTask>(_callbacksList.toArray(callbackArray)); ExecutorService executor = Executors.newFixedThreadPool(10); try { for (int i = 0; i < _bufferList.length(); i++) { Thread.sleep(_sleepTime); FutureTask f = _bufferList.get(i); if (!f.isDone()) { executor.submit(f).get(); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException ee) { ee.printStackTrace(); } finally { executor.shutdownNow(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.bean; import org.w3c.dom.Document; import org.apache.camel.ContextTestSupport; import org.apache.camel.Endpoint; import org.apache.camel.InvalidPayloadException; import org.apache.camel.builder.ProxyBuilder; import org.apache.camel.builder.RouteBuilder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class BeanProxyTest extends ContextTestSupport { @Test public void testBeanProxyStringReturnString() throws Exception { // START SNIPPET: e2 Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); String reply = service.submitOrderStringReturnString("<order type=\"book\">Camel in action</order>"); assertEquals("<order id=\"123\">OK</order>", reply); // END SNIPPET: e2 } @Test public void testBeanProxyStringReturnDocument() throws Exception { Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); Document reply = service.submitOrderStringReturnDocument("<order type=\"book\">Camel in action</order>"); assertNotNull(reply); String s = context.getTypeConverter().convertTo(String.class, reply); assertEquals("<order id=\"123\">OK</order>", s); } @Test public void testBeanProxyDocumentReturnString() throws Exception { Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); Document doc = context.getTypeConverter().convertTo(Document.class, "<order type=\"book\">Camel in action</order>"); String reply = service.submitOrderDocumentReturnString(doc); assertEquals("<order id=\"123\">OK</order>", reply); } @Test public void testBeanProxyDocumentReturnDocument() throws Exception { // START SNIPPET: e3 Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); Document doc = context.getTypeConverter().convertTo(Document.class, "<order type=\"book\">Camel in action</order>"); Document reply = service.submitOrderDocumentReturnDocument(doc); assertNotNull(reply); String s = context.getTypeConverter().convertTo(String.class, reply); assertEquals("<order id=\"123\">OK</order>", s); // END SNIPPET: e3 } @Test public void testBeanProxyFailure() throws Exception { Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); String reply = service.submitOrderStringReturnString("<order type=\"beer\">Carlsberg</order>"); assertEquals("<order>FAIL</order>", reply); } @Test public void testBeanProxyFailureNotXMLBody() throws Exception { Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); try { service.submitOrderStringReturnString("Hello World"); fail("Should have thrown exception"); } catch (Exception e) { // expected } } @Test public void testBeanProxyVoidReturnType() throws Exception { Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); service.doNothing("<order>ping</order>"); } @Test public void testBeanProxyFailureInvalidReturnType() throws Exception { Endpoint endpoint = context.getEndpoint("direct:start"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); try { service.invalidReturnType("<order type=\"beer\">Carlsberg</order>"); fail("Should have thrown exception"); } catch (Exception e) { // expected InvalidPayloadException cause = assertIsInstanceOf(InvalidPayloadException.class, e.getCause()); assertEquals(Integer.class, cause.getType()); } } @Test public void testBeanProxyCallAnotherBean() throws Exception { Endpoint endpoint = context.getEndpoint("direct:bean"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); String reply = service.submitOrderStringReturnString("World"); assertEquals("Hello World", reply); } // START SNIPPET: e4 @Test public void testProxyBuilderProxyCallAnotherBean() throws Exception { // use ProxyBuilder to easily create the proxy OrderService service = new ProxyBuilder(context).endpoint("direct:bean").build(OrderService.class); String reply = service.submitOrderStringReturnString("World"); assertEquals("Hello World", reply); } // END SNIPPET: e4 @Test public void testBeanProxyCallAnotherBeanWithNoArgs() throws Exception { Endpoint endpoint = context.getEndpoint("direct:bean"); OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); String reply = service.doAbsolutelyNothing(); assertEquals("Hi nobody", reply); } @Test public void testProxyBuilderProxyCallAnotherBeanWithNoArgs() throws Exception { Endpoint endpoint = context.getEndpoint("direct:bean"); OrderService service = new ProxyBuilder(context).endpoint(endpoint).build(OrderService.class); String reply = service.doAbsolutelyNothing(); assertEquals("Hi nobody", reply); } @Test public void testBeanProxyVoidAsInOut() throws Exception { Endpoint endpoint = context.getEndpoint("seda:delay"); // will by default let all exchanges be InOut OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class); getMockEndpoint("mock:delay").expectedBodiesReceived("Hello World", "Bye World"); service.doNothing("Hello World"); template.sendBody("mock:delay", "Bye World"); assertMockEndpointsSatisfied(); } @Test public void testProxyBuilderVoidAsInOut() throws Exception { // will by default let all exchanges be InOut OrderService service = new ProxyBuilder(context).endpoint("seda:delay").build(OrderService.class); getMockEndpoint("mock:delay").expectedBodiesReceived("Hello World", "Bye World"); service.doNothing("Hello World"); template.sendBody("mock:delay", "Bye World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { // START SNIPPET: e1 from("direct:start").choice().when(xpath("/order/@type = 'book'")).to("direct:book").otherwise() .to("direct:other").end(); from("direct:book").transform(constant("<order id=\"123\">OK</order>")); from("direct:other").transform(constant("<order>FAIL</order>")); // END SNIPPET: e1 from("direct:bean").bean(MyFooBean.class, "hello"); from("seda:delay").delay(1000).to("mock:delay"); } }; } public static class MyFooBean { public String hello(String name) { if (name != null) { return "Hello " + name; } else { return "Hi nobody"; } } } }
/* * ASReferral Class * * Copyright (C) 2013 Red Line Labs, Inc. * By Justin Butler (justin@redline-labs.com) */ package com.appspin.android.example; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; public class ASReferral { private static String APPSPIN_API_ENDPOINT = "http://api.appsp.in/"; private static String APPSPIN_APP_NAME = "ExampleApp"; // YOUR APP NAME GOES HERE private static String APPSPIN_APP_ID = "4"; // YOUR APP ID GOES HERE (FROM APP DASHBOARD) private static String APPSPIN_DEVELOPER_TOKEN = Constants.key; // YOUR DEVELOPER TOKEN GOES HERE (FROM MAIN MENU) private Activity context; private String campaignInfoURL; private int campaignID; // Constructor which accepts activity context of creator public ASReferral (Activity activity) { context = activity; } public void checkForOffers() { if (context != null) { // async check for campaign data new AppSpinTask().execute(new String[] { APPSPIN_APP_ID, APPSPIN_DEVELOPER_TOKEN }); } return; } /* * This simple example uses a system dialog to present the offer * Modify to display a modal container with a more stylized / branded appearance */ public void presentOffer() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("Earn rewards!"); String message = "Would you like to earn rewards by sharing "; // YOUR OFFER MESSAGE GOES HERE message += APPSPIN_APP_NAME + "?"; alertDialogBuilder .setMessage(message) .setCancelable(false) .setPositiveButton("Yes, please!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { /* * If your app already has the user's contact info, you can generate affiliate * links on the fly via the API's "generate" endpoint * http://docs.appsp.in/#!/affiliate */ launchReward(); } }) .setNegativeButton("No, thanks", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); context = null; } }) .setNeutralButton("Learn more", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { launchReward(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); if (campaignID != 0) { // Fire pixel to track that this campaign was offered String trackingPixel = APPSPIN_API_ENDPOINT + "offer?"; trackingPixel += "campaign_id=" + campaignID + "&"; trackingPixel += "token=" + APPSPIN_DEVELOPER_TOKEN; try { @SuppressWarnings("unused") InputStream pixelStream = (InputStream) new URL(trackingPixel).getContent(); } catch (Exception e) { e.printStackTrace(); Log.e("AppSpin", "Campaign tracking pixel did not fire"); } } return; } private void launchReward() { if (campaignInfoURL != null) { /* * Launch browser to display campaign details * * If you want to display the details natively, you make make * a request for JSON data via the API's "campaigns" endpoint * http://docs.appsp.in/#!/campaign */ Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(campaignInfoURL)); context.startActivity(browserIntent); } // drop reference to help with GC context = null; return; } private class AppSpinTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... param) { String result; HttpClient httpclient = new DefaultHttpClient(); String url = APPSPIN_API_ENDPOINT + "campaigns?"; url += "app_id=" + param[0] + "&"; url += "token=" + param[1]; HttpGet get = new HttpGet(url); try { HttpResponse response = httpclient.execute(get); StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == HttpStatus.SC_OK){ ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); String responseString = out.toString(); result = responseString; } else { response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (IOException e) { e.printStackTrace(); result = "{\"error\":\"Error: Server data is not available\"}"; } return result; } @Override protected void onPostExecute(String result) { requestStateChanged(result); } } private void requestStateChanged(String result) { String error = null; String url = null; try { JSONObject json = new JSONObject(result); if (json.has("error")) { error = json.getString("error"); } else { JSONObject data = json.getJSONObject("data"); JSONArray campaigns = data.getJSONArray("campaigns"); if (campaigns.length() > 0) { /* * Here we just grab the first campaign, * but we could write business logic to choose a specific campaign * TODO: provide example of server-side implementation of business logic */ JSONObject campaign = campaigns.getJSONObject(0); url = campaign.getString("info_link"); campaignID = campaign.getInt("id"); } } } catch (Exception e) { e.printStackTrace(); error = "Error: Server data has invalid format"; } if (error!=null) { Log.e("AppSpin", error); // Toast.makeText(context.getApplicationContext(), error, Toast.LENGTH_SHORT).show(); context = null; } else { if (url!=null) { if (!url.startsWith("http://") && !url.startsWith("https://")) { url = "http://" + url; } campaignInfoURL = url; presentOffer(); } else { String message = "Sorry! There are currently no offers available."; Log.i("AppSpin", message); // Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show(); context = null; } } return; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper.object; import com.google.common.collect.Iterables; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.Term; import org.apache.lucene.queries.TermFilter; import org.apache.lucene.search.Filter; import org.apache.lucene.util.BytesRef; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.CopyOnWriteHashMap; import org.elasticsearch.common.joda.FormatDateTimeFormatter; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.ContentPath; import org.elasticsearch.index.mapper.DocumentMapperParser; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.FieldMapperListener; import org.elasticsearch.index.mapper.InternalMapper; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperBuilders; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.mapper.MergeContext; import org.elasticsearch.index.mapper.MergeMappingException; import org.elasticsearch.index.mapper.ObjectMapperListener; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.ParseContext.Document; import org.elasticsearch.index.mapper.StrictDynamicMappingException; import org.elasticsearch.index.mapper.internal.AllFieldMapper; import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.settings.IndexSettings; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import static com.google.common.collect.Lists.newArrayList; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue; import static org.elasticsearch.index.mapper.MapperBuilders.binaryField; import static org.elasticsearch.index.mapper.MapperBuilders.booleanField; import static org.elasticsearch.index.mapper.MapperBuilders.dateField; import static org.elasticsearch.index.mapper.MapperBuilders.doubleField; import static org.elasticsearch.index.mapper.MapperBuilders.floatField; import static org.elasticsearch.index.mapper.MapperBuilders.integerField; import static org.elasticsearch.index.mapper.MapperBuilders.longField; import static org.elasticsearch.index.mapper.MapperBuilders.object; import static org.elasticsearch.index.mapper.MapperBuilders.stringField; import static org.elasticsearch.index.mapper.core.TypeParsers.parsePathType; /** * */ public class ObjectMapper implements Mapper, AllFieldMapper.IncludeInAll { public static final String CONTENT_TYPE = "object"; public static final String NESTED_CONTENT_TYPE = "nested"; public static class Defaults { public static final boolean ENABLED = true; public static final Nested NESTED = Nested.NO; public static final Dynamic DYNAMIC = null; // not set, inherited from root public static final ContentPath.Type PATH_TYPE = ContentPath.Type.FULL; } public static enum Dynamic { TRUE, FALSE, STRICT } public static class Nested { public static final Nested NO = new Nested(false, false, false); public static Nested newNested(boolean includeInParent, boolean includeInRoot) { return new Nested(true, includeInParent, includeInRoot); } private final boolean nested; private final boolean includeInParent; private final boolean includeInRoot; private Nested(boolean nested, boolean includeInParent, boolean includeInRoot) { this.nested = nested; this.includeInParent = includeInParent; this.includeInRoot = includeInRoot; } public boolean isNested() { return nested; } public boolean isIncludeInParent() { return includeInParent; } public boolean isIncludeInRoot() { return includeInRoot; } } public static class Builder<T extends Builder, Y extends ObjectMapper> extends Mapper.Builder<T, Y> { protected boolean enabled = Defaults.ENABLED; protected Nested nested = Defaults.NESTED; protected Dynamic dynamic = Defaults.DYNAMIC; protected ContentPath.Type pathType = Defaults.PATH_TYPE; protected Boolean includeInAll; protected final List<Mapper.Builder> mappersBuilders = newArrayList(); public Builder(String name) { super(name); this.builder = (T) this; } public T enabled(boolean enabled) { this.enabled = enabled; return builder; } public T dynamic(Dynamic dynamic) { this.dynamic = dynamic; return builder; } public T nested(Nested nested) { this.nested = nested; return builder; } public T pathType(ContentPath.Type pathType) { this.pathType = pathType; return builder; } public T includeInAll(boolean includeInAll) { this.includeInAll = includeInAll; return builder; } public T add(Mapper.Builder builder) { mappersBuilders.add(builder); return this.builder; } @Override public Y build(BuilderContext context) { ContentPath.Type origPathType = context.path().pathType(); context.path().pathType(pathType); context.path().add(name); Map<String, Mapper> mappers = new HashMap<>(); for (Mapper.Builder builder : mappersBuilders) { Mapper mapper = builder.build(context); mappers.put(mapper.name(), mapper); } context.path().pathType(origPathType); context.path().remove(); ObjectMapper objectMapper = createMapper(name, context.path().fullPathAsText(name), enabled, nested, dynamic, pathType, mappers, context.indexSettings()); objectMapper.includeInAllIfNotSet(includeInAll); return (Y) objectMapper; } protected ObjectMapper createMapper(String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic, ContentPath.Type pathType, Map<String, Mapper> mappers, @Nullable @IndexSettings Settings settings) { return new ObjectMapper(name, fullPath, enabled, nested, dynamic, pathType, mappers); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { ObjectMapper.Builder builder = createBuilder(name); parseNested(name, node, builder); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (parseObjectOrDocumentTypeProperties(fieldName, fieldNode, parserContext, builder) || parseObjectProperties(name, fieldName, fieldNode, builder)) { iterator.remove(); } } return builder; } protected static boolean parseObjectOrDocumentTypeProperties(String fieldName, Object fieldNode, ParserContext parserContext, ObjectMapper.Builder builder) { if (fieldName.equals("dynamic")) { String value = fieldNode.toString(); if (value.equalsIgnoreCase("strict")) { builder.dynamic(Dynamic.STRICT); } else { builder.dynamic(nodeBooleanValue(fieldNode) ? Dynamic.TRUE : Dynamic.FALSE); } return true; } else if (fieldName.equals("enabled")) { builder.enabled(nodeBooleanValue(fieldNode)); return true; } else if (fieldName.equals("properties")) { if (fieldNode instanceof Collection && ((Collection) fieldNode).isEmpty()) { // nothing to do here, empty (to support "properties: []" case) } else if (!(fieldNode instanceof Map)) { throw new ElasticsearchParseException("properties must be a map type"); } else { parseProperties(builder, (Map<String, Object>) fieldNode, parserContext); } return true; } else if (fieldName.equals("include_in_all")) { builder.includeInAll(nodeBooleanValue(fieldNode)); return true; } return false; } protected static boolean parseObjectProperties(String name, String fieldName, Object fieldNode, ObjectMapper.Builder builder) { if (fieldName.equals("path")) { builder.pathType(parsePathType(name, fieldNode.toString())); return true; } return false; } protected static void parseNested(String name, Map<String, Object> node, ObjectMapper.Builder builder) { boolean nested = false; boolean nestedIncludeInParent = false; boolean nestedIncludeInRoot = false; Object fieldNode = node.get("type"); if (fieldNode!=null) { String type = fieldNode.toString(); if (type.equals(CONTENT_TYPE)) { builder.nested = Nested.NO; } else if (type.equals(NESTED_CONTENT_TYPE)) { nested = true; } else { throw new MapperParsingException("Trying to parse an object but has a different type [" + type + "] for [" + name + "]"); } } fieldNode = node.get("include_in_parent"); if (fieldNode != null) { nestedIncludeInParent = nodeBooleanValue(fieldNode); node.remove("include_in_parent"); } fieldNode = node.get("include_in_root"); if (fieldNode != null) { nestedIncludeInRoot = nodeBooleanValue(fieldNode); node.remove("include_in_root"); } if (nested) { builder.nested = Nested.newNested(nestedIncludeInParent, nestedIncludeInRoot); } } protected static void parseProperties(ObjectMapper.Builder objBuilder, Map<String, Object> propsNode, ParserContext parserContext) { Iterator<Map.Entry<String, Object>> iterator = propsNode.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Object> entry = iterator.next(); String propName = entry.getKey(); // Should accept empty arrays, as a work around for when the // user can't provide an empty Map. (PHP for example) boolean isEmptyList = entry.getValue() instanceof List && ((List<?>) entry.getValue()).isEmpty(); if (entry.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> propNode = (Map<String, Object>) entry.getValue(); String type; Object typeNode = propNode.get("type"); if (typeNode != null) { type = typeNode.toString(); } else { // lets see if we can derive this... if (propNode.get("properties") != null) { type = ObjectMapper.CONTENT_TYPE; } else if (propNode.size() == 1 && propNode.get("enabled") != null) { // if there is a single property with the enabled // flag on it, make it an object // (usually, setting enabled to false to not index // any type, including core values, which type = ObjectMapper.CONTENT_TYPE; } else { throw new MapperParsingException("No type specified for property [" + propName + "]"); } } Mapper.TypeParser typeParser = parserContext.typeParser(type); if (typeParser == null) { throw new MapperParsingException("No handler for type [" + type + "] declared on field [" + propName + "]"); } objBuilder.add(typeParser.parse(propName, propNode, parserContext)); propNode.remove("type"); DocumentMapperParser.checkNoRemainingFields(propName, propNode, parserContext.indexVersionCreated()); iterator.remove(); } else if (isEmptyList) { iterator.remove(); } else { throw new MapperParsingException("Expected map for property [fields] on field [" + propName + "] but got a " + propName.getClass()); } } DocumentMapperParser.checkNoRemainingFields(propsNode, parserContext.indexVersionCreated(), "DocType mapping definition has unsupported parameters: "); } protected Builder createBuilder(String name) { return object(name); } } private final String name; private final String fullPath; private final boolean enabled; private final Nested nested; private final String nestedTypePathAsString; private final BytesRef nestedTypePathAsBytes; private final Filter nestedTypeFilter; private volatile Dynamic dynamic; private final ContentPath.Type pathType; private Boolean includeInAll; private volatile CopyOnWriteHashMap<String, Mapper> mappers; private final Object mutex = new Object(); ObjectMapper(String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic, ContentPath.Type pathType, Map<String, Mapper> mappers) { this.name = name; this.fullPath = fullPath; this.enabled = enabled; this.nested = nested; this.dynamic = dynamic; this.pathType = pathType; if (mappers == null) { this.mappers = new CopyOnWriteHashMap<>(); } else { this.mappers = CopyOnWriteHashMap.copyOf(mappers); } this.nestedTypePathAsString = "__" + fullPath; this.nestedTypePathAsBytes = new BytesRef(nestedTypePathAsString); this.nestedTypeFilter = new TermFilter(new Term(TypeFieldMapper.NAME, nestedTypePathAsBytes)); } @Override public String name() { return this.name; } @Override public void includeInAll(Boolean includeInAll) { if (includeInAll == null) { return; } this.includeInAll = includeInAll; // when called from outside, apply this on all the inner mappers for (Mapper mapper : mappers.values()) { if (mapper instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) mapper).includeInAll(includeInAll); } } } @Override public void includeInAllIfNotSet(Boolean includeInAll) { if (this.includeInAll == null) { this.includeInAll = includeInAll; } // when called from outside, apply this on all the inner mappers for (Mapper mapper : mappers.values()) { if (mapper instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) mapper).includeInAllIfNotSet(includeInAll); } } } @Override public void unsetIncludeInAll() { includeInAll = null; // when called from outside, apply this on all the inner mappers for (Mapper mapper : mappers.values()) { if (mapper instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) mapper).unsetIncludeInAll(); } } } public Nested nested() { return this.nested; } public Filter nestedTypeFilter() { return this.nestedTypeFilter; } public ObjectMapper putMapper(Mapper mapper) { if (mapper instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) mapper).includeInAllIfNotSet(includeInAll); } synchronized (mutex) { mappers = mappers.copyAndPut(mapper.name(), mapper); } return this; } @Override public void traverse(FieldMapperListener fieldMapperListener) { for (Mapper mapper : mappers.values()) { mapper.traverse(fieldMapperListener); } } @Override public void traverse(ObjectMapperListener objectMapperListener) { objectMapperListener.objectMapper(this); for (Mapper mapper : mappers.values()) { mapper.traverse(objectMapperListener); } } public String fullPath() { return this.fullPath; } public String nestedTypePathAsString() { return nestedTypePathAsString; } public final Dynamic dynamic() { return this.dynamic == null ? Dynamic.TRUE : this.dynamic; } protected boolean allowValue() { return true; } public void parse(ParseContext context) throws IOException { if (!enabled) { context.parser().skipChildren(); return; } XContentParser parser = context.parser(); String currentFieldName = parser.currentName(); XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NULL) { // the object is null ("obj1" : null), simply bail return; } if (token.isValue() && !allowValue()) { // if we are parsing an object but it is just a value, its only allowed on root level parsers with there // is a field name with the same name as the type throw new MapperParsingException("object mapping for [" + name + "] tried to parse field [" + currentFieldName + "] as object, but found a concrete value"); } if (nested.isNested()) { context = context.createNestedContext(fullPath); Document nestedDoc = context.doc(); Document parentDoc = nestedDoc.getParent(); // pre add the uid field if possible (id was already provided) IndexableField uidField = parentDoc.getField(UidFieldMapper.NAME); if (uidField != null) { // we don't need to add it as a full uid field in nested docs, since we don't need versioning // we also rely on this for UidField#loadVersion // this is a deeply nested field nestedDoc.add(new Field(UidFieldMapper.NAME, uidField.stringValue(), UidFieldMapper.Defaults.NESTED_FIELD_TYPE)); } // the type of the nested doc starts with __, so we can identify that its a nested one in filters // note, we don't prefix it with the type of the doc since it allows us to execute a nested query // across types (for example, with similar nested objects) nestedDoc.add(new Field(TypeFieldMapper.NAME, nestedTypePathAsString, TypeFieldMapper.Defaults.FIELD_TYPE)); } ContentPath.Type origPathType = context.path().pathType(); context.path().pathType(pathType); // if we are at the end of the previous object, advance if (token == XContentParser.Token.END_OBJECT) { token = parser.nextToken(); } if (token == XContentParser.Token.START_OBJECT) { // if we are just starting an OBJECT, advance, this is the object we are parsing, we need the name first token = parser.nextToken(); } while (token != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.START_OBJECT) { serializeObject(context, currentFieldName); } else if (token == XContentParser.Token.START_ARRAY) { serializeArray(context, currentFieldName); } else if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NULL) { serializeNullValue(context, currentFieldName); } else if (token == null) { throw new MapperParsingException("object mapping for [" + name + "] tried to parse field [" + currentFieldName + "] as object, but got EOF, has a concrete value been provided to it?"); } else if (token.isValue()) { serializeValue(context, currentFieldName, token); } token = parser.nextToken(); } // restore the enable path flag context.path().pathType(origPathType); if (nested.isNested()) { Document nestedDoc = context.doc(); Document parentDoc = nestedDoc.getParent(); if (nested.isIncludeInParent()) { for (IndexableField field : nestedDoc.getFields()) { if (field.name().equals(UidFieldMapper.NAME) || field.name().equals(TypeFieldMapper.NAME)) { continue; } else { parentDoc.add(field); } } } if (nested.isIncludeInRoot()) { Document rootDoc = context.rootDoc(); // don't add it twice, if its included in parent, and we are handling the master doc... if (!nested.isIncludeInParent() || parentDoc != rootDoc) { for (IndexableField field : nestedDoc.getFields()) { if (field.name().equals(UidFieldMapper.NAME) || field.name().equals(TypeFieldMapper.NAME)) { continue; } else { rootDoc.add(field); } } } } } } private void serializeNullValue(ParseContext context, String lastFieldName) throws IOException { // we can only handle null values if we have mappings for them Mapper mapper = mappers.get(lastFieldName); if (mapper != null) { if (mapper instanceof FieldMapper) { if (!((FieldMapper) mapper).supportsNullValue()) { throw new MapperParsingException("no object mapping found for null value in [" + lastFieldName + "]"); } } mapper.parse(context); } } private void serializeObject(final ParseContext context, String currentFieldName) throws IOException { if (currentFieldName == null) { throw new MapperParsingException("object mapping [" + name + "] trying to serialize an object with no field associated with it, current value [" + context.parser().textOrNull() + "]"); } context.path().add(currentFieldName); Mapper objectMapper = mappers.get(currentFieldName); if (objectMapper != null) { objectMapper.parse(context); } else { Dynamic dynamic = this.dynamic; if (dynamic == null) { dynamic = context.root().dynamic(); } if (dynamic == Dynamic.STRICT) { throw new StrictDynamicMappingException(fullPath, currentFieldName); } else if (dynamic == Dynamic.TRUE) { // we sync here just so we won't add it twice. Its not the end of the world // to sync here since next operations will get it before synchronized (mutex) { objectMapper = mappers.get(currentFieldName); if (objectMapper == null) { // remove the current field name from path, since template search and the object builder add it as well... context.path().remove(); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "object"); if (builder == null) { builder = MapperBuilders.object(currentFieldName).enabled(true).pathType(pathType); // if this is a non root object, then explicitly set the dynamic behavior if set if (!(this instanceof RootObjectMapper) && this.dynamic != Defaults.DYNAMIC) { ((Builder) builder).dynamic(this.dynamic); } } BuilderContext builderContext = new BuilderContext(context.indexSettings(), context.path()); objectMapper = builder.build(builderContext); putDynamicMapper(context, currentFieldName, objectMapper); } else { objectMapper.parse(context); } } } else { // not dynamic, read everything up to end object context.parser().skipChildren(); } } context.path().remove(); } private void serializeArray(ParseContext context, String lastFieldName) throws IOException { String arrayFieldName = lastFieldName; Mapper mapper = mappers.get(lastFieldName); if (mapper != null) { // There is a concrete mapper for this field already. Need to check if the mapper // expects an array, if so we pass the context straight to the mapper and if not // we serialize the array components if (mapper instanceof ArrayValueMapperParser) { mapper.parse(context); } else { serializeNonDynamicArray(context, lastFieldName, arrayFieldName); } } else { Dynamic dynamic = this.dynamic; if (dynamic == null) { dynamic = context.root().dynamic(); } if (dynamic == Dynamic.STRICT) { throw new StrictDynamicMappingException(fullPath, arrayFieldName); } else if (dynamic == Dynamic.TRUE) { // we sync here just so we won't add it twice. Its not the end of the world // to sync here since next operations will get it before synchronized (mutex) { mapper = mappers.get(arrayFieldName); if (mapper == null) { Mapper.Builder builder = context.root().findTemplateBuilder(context, arrayFieldName, "object"); if (builder == null) { serializeNonDynamicArray(context, lastFieldName, arrayFieldName); return; } BuilderContext builderContext = new BuilderContext(context.indexSettings(), context.path()); mapper = builder.build(builderContext); if (mapper != null && mapper instanceof ArrayValueMapperParser) { putDynamicMapper(context, arrayFieldName, mapper); } else { serializeNonDynamicArray(context, lastFieldName, arrayFieldName); } } else { serializeNonDynamicArray(context, lastFieldName, arrayFieldName); } } } else { serializeNonDynamicArray(context, lastFieldName, arrayFieldName); } } } private void putDynamicMapper(ParseContext context, String arrayFieldName, Mapper mapper) throws IOException { // ...now re add it context.path().add(arrayFieldName); context.setMappingsModified(); if (context.isWithinNewMapper()) { // within a new mapper, no need to traverse, // just parse mapper.parse(context); } else { // create a context of new mapper, so we batch // aggregate all the changes within // this object mapper once, and traverse all of // them to add them in a single go context.setWithinNewMapper(); try { mapper.parse(context); FieldMapperListener.Aggregator newFields = new FieldMapperListener.Aggregator(); ObjectMapperListener.Aggregator newObjects = new ObjectMapperListener.Aggregator(); mapper.traverse(newFields); mapper.traverse(newObjects); // callback on adding those fields! context.docMapper().addFieldMappers(newFields.mappers); context.docMapper().addObjectMappers(newObjects.mappers); } finally { context.clearWithinNewMapper(); } } // only put after we traversed and did the // callbacks, so other parsing won't see it only // after we // properly traversed it and adding the mappers putMapper(mapper); } private void serializeNonDynamicArray(ParseContext context, String lastFieldName, String arrayFieldName) throws IOException { XContentParser parser = context.parser(); XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { serializeObject(context, lastFieldName); } else if (token == XContentParser.Token.START_ARRAY) { serializeArray(context, lastFieldName); } else if (token == XContentParser.Token.FIELD_NAME) { lastFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NULL) { serializeNullValue(context, lastFieldName); } else if (token == null) { throw new MapperParsingException("object mapping for [" + name + "] with array for [" + arrayFieldName + "] tried to parse as array, but got EOF, is there a mismatch in types for the same field?"); } else { serializeValue(context, lastFieldName, token); } } } private void serializeValue(final ParseContext context, String currentFieldName, XContentParser.Token token) throws IOException { if (currentFieldName == null) { throw new MapperParsingException("object mapping [" + name + "] trying to serialize a value with no field associated with it, current value [" + context.parser().textOrNull() + "]"); } Mapper mapper = mappers.get(currentFieldName); if (mapper != null) { mapper.parse(context); } else { parseDynamicValue(context, currentFieldName, token); } } public void parseDynamicValue(final ParseContext context, String currentFieldName, XContentParser.Token token) throws IOException { Dynamic dynamic = this.dynamic; if (dynamic == null) { dynamic = context.root().dynamic(); } if (dynamic == Dynamic.STRICT) { throw new StrictDynamicMappingException(fullPath, currentFieldName); } if (dynamic == Dynamic.FALSE) { return; } // we sync here since we don't want to add this field twice to the document mapper // its not the end of the world, since we add it to the mappers once we create it // so next time we won't even get here for this field synchronized (mutex) { Mapper mapper = mappers.get(currentFieldName); if (mapper == null) { BuilderContext builderContext = new BuilderContext(context.indexSettings(), context.path()); if (token == XContentParser.Token.VALUE_STRING) { boolean resolved = false; // do a quick test to see if its fits a dynamic template, if so, use it. // we need to do it here so we can handle things like attachment templates, where calling // text (to see if its a date) causes the binary value to be cleared if (!resolved) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "string", null); if (builder != null) { mapper = builder.build(builderContext); resolved = true; } } if (!resolved && context.root().dateDetection()) { String text = context.parser().text(); // a safe check since "1" gets parsed as well if (Strings.countOccurrencesOf(text, ":") > 1 || Strings.countOccurrencesOf(text, "-") > 1 || Strings.countOccurrencesOf(text, "/") > 1) { for (FormatDateTimeFormatter dateTimeFormatter : context.root().dynamicDateTimeFormatters()) { try { dateTimeFormatter.parser().parseMillis(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "date"); if (builder == null) { builder = dateField(currentFieldName).dateTimeFormatter(dateTimeFormatter); } mapper = builder.build(builderContext); resolved = true; break; } catch (Exception e) { // failure to parse this, continue } } } } if (!resolved && context.root().numericDetection()) { String text = context.parser().text(); try { Long.parseLong(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = longField(currentFieldName); } mapper = builder.build(builderContext); resolved = true; } catch (Exception e) { // not a long number } if (!resolved) { try { Double.parseDouble(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = doubleField(currentFieldName); } mapper = builder.build(builderContext); resolved = true; } catch (Exception e) { // not a long number } } } if (!resolved) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "string"); if (builder == null) { builder = stringField(currentFieldName); } mapper = builder.build(builderContext); } } else if (token == XContentParser.Token.VALUE_NUMBER) { XContentParser.NumberType numberType = context.parser().numberType(); if (numberType == XContentParser.NumberType.INT) { if (context.parser().estimatedNumberType()) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = longField(currentFieldName); } mapper = builder.build(builderContext); } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "integer"); if (builder == null) { builder = integerField(currentFieldName); } mapper = builder.build(builderContext); } } else if (numberType == XContentParser.NumberType.LONG) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = longField(currentFieldName); } mapper = builder.build(builderContext); } else if (numberType == XContentParser.NumberType.FLOAT) { if (context.parser().estimatedNumberType()) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = doubleField(currentFieldName); } mapper = builder.build(builderContext); } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "float"); if (builder == null) { builder = floatField(currentFieldName); } mapper = builder.build(builderContext); } } else if (numberType == XContentParser.NumberType.DOUBLE) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = doubleField(currentFieldName); } mapper = builder.build(builderContext); } } else if (token == XContentParser.Token.VALUE_BOOLEAN) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "boolean"); if (builder == null) { builder = booleanField(currentFieldName); } mapper = builder.build(builderContext); } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "binary"); if (builder == null) { builder = binaryField(currentFieldName); } mapper = builder.build(builderContext); } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, null); if (builder != null) { mapper = builder.build(builderContext); } else { // TODO how do we identify dynamically that its a binary value? throw new ElasticsearchIllegalStateException("Can't handle serializing a dynamic type with content token [" + token + "] and field name [" + currentFieldName + "]"); } } if (context.isWithinNewMapper()) { mapper.parse(context); } else { context.setWithinNewMapper(); try { mapper.parse(context); FieldMapperListener.Aggregator newFields = new FieldMapperListener.Aggregator(); mapper.traverse(newFields); context.docMapper().addFieldMappers(newFields.mappers); } finally { context.clearWithinNewMapper(); } } // only put after we traversed and did the callbacks, so other parsing won't see it only after we // properly traversed it and adding the mappers putMapper(mapper); context.setMappingsModified(); } else { mapper.parse(context); } } } @Override public void merge(final Mapper mergeWith, final MergeContext mergeContext) throws MergeMappingException { if (!(mergeWith instanceof ObjectMapper)) { mergeContext.addConflict("Can't merge a non object mapping [" + mergeWith.name() + "] with an object mapping [" + name() + "]"); return; } ObjectMapper mergeWithObject = (ObjectMapper) mergeWith; if (nested().isNested()) { if (!mergeWithObject.nested().isNested()) { mergeContext.addConflict("object mapping [" + name() + "] can't be changed from nested to non-nested"); return; } } else { if (mergeWithObject.nested().isNested()) { mergeContext.addConflict("object mapping [" + name() + "] can't be changed from non-nested to nested"); return; } } if (!mergeContext.mergeFlags().simulate()) { if (mergeWithObject.dynamic != null) { this.dynamic = mergeWithObject.dynamic; } } doMerge(mergeWithObject, mergeContext); List<Mapper> mappersToPut = new ArrayList<>(); FieldMapperListener.Aggregator newFieldMappers = new FieldMapperListener.Aggregator(); ObjectMapperListener.Aggregator newObjectMappers = new ObjectMapperListener.Aggregator(); synchronized (mutex) { for (Mapper mapper : mergeWithObject.mappers.values()) { Mapper mergeWithMapper = mapper; Mapper mergeIntoMapper = mappers.get(mergeWithMapper.name()); if (mergeIntoMapper == null) { // no mapping, simply add it if not simulating if (!mergeContext.mergeFlags().simulate()) { mappersToPut.add(mergeWithMapper); mergeWithMapper.traverse(newFieldMappers); mergeWithMapper.traverse(newObjectMappers); } } else { mergeIntoMapper.merge(mergeWithMapper, mergeContext); } } if (!newFieldMappers.mappers.isEmpty()) { mergeContext.docMapper().addFieldMappers(newFieldMappers.mappers); } if (!newObjectMappers.mappers.isEmpty()) { mergeContext.docMapper().addObjectMappers(newObjectMappers.mappers); } // and the mappers only after the administration have been done, so it will not be visible to parser (which first try to read with no lock) for (Mapper mapper : mappersToPut) { putMapper(mapper); } } } protected void doMerge(ObjectMapper mergeWith, MergeContext mergeContext) { } @Override public void close() { for (Mapper mapper : mappers.values()) { mapper.close(); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { toXContent(builder, params, null, Mapper.EMPTY_ARRAY); return builder; } public void toXContent(XContentBuilder builder, Params params, ToXContent custom, Mapper... additionalMappers) throws IOException { builder.startObject(name); if (nested.isNested()) { builder.field("type", NESTED_CONTENT_TYPE); if (nested.isIncludeInParent()) { builder.field("include_in_parent", true); } if (nested.isIncludeInRoot()) { builder.field("include_in_root", true); } } else if (mappers.isEmpty()) { // only write the object content type if there are no properties, otherwise, it is automatically detected builder.field("type", CONTENT_TYPE); } if (dynamic != null) { builder.field("dynamic", dynamic.name().toLowerCase(Locale.ROOT)); } if (enabled != Defaults.ENABLED) { builder.field("enabled", enabled); } if (pathType != Defaults.PATH_TYPE) { builder.field("path", pathType.name().toLowerCase(Locale.ROOT)); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } if (custom != null) { custom.toXContent(builder, params); } doXContent(builder, params); // sort the mappers so we get consistent serialization format Mapper[] sortedMappers = Iterables.toArray(mappers.values(), Mapper.class); Arrays.sort(sortedMappers, new Comparator<Mapper>() { @Override public int compare(Mapper o1, Mapper o2) { return o1.name().compareTo(o2.name()); } }); // check internal mappers first (this is only relevant for root object) for (Mapper mapper : sortedMappers) { if (mapper instanceof InternalMapper) { mapper.toXContent(builder, params); } } if (additionalMappers != null && additionalMappers.length > 0) { TreeMap<String, Mapper> additionalSortedMappers = new TreeMap<>(); for (Mapper mapper : additionalMappers) { additionalSortedMappers.put(mapper.name(), mapper); } for (Mapper mapper : additionalSortedMappers.values()) { mapper.toXContent(builder, params); } } if (!mappers.isEmpty()) { builder.startObject("properties"); for (Mapper mapper : sortedMappers) { if (!(mapper instanceof InternalMapper)) { mapper.toXContent(builder, params); } } builder.endObject(); } builder.endObject(); } protected void doXContent(XContentBuilder builder, Params params) throws IOException { } }
/* * Copyright (C) 2008 The Guava 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 com.google.common.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.google.MultisetTestSuiteBuilder; import com.google.common.collect.testing.google.SortedMultisetTestSuiteBuilder; import com.google.common.collect.testing.google.TestStringMultisetGenerator; import java.util.ArrayList; import java.util.Collections; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Collection tests on wrappers from {@link Multisets}. * * @author Jared Levy */ @GwtIncompatible // suite // TODO(cpovirk): set up collect/gwt/suites version public class MultisetsCollectionTest extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest( MultisetTestSuiteBuilder.using(unmodifiableMultisetGenerator()) .withFeatures( CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_QUERIES) .named("Multisets.unmodifiableMultiset[LinkedHashMultiset]") .createTestSuite()); suite.addTest( SortedMultisetTestSuiteBuilder.using(unmodifiableSortedMultisetGenerator()) .withFeatures( CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, CollectionFeature.ALLOWS_NULL_QUERIES) .named("Multisets.unmodifiableMultiset[TreeMultiset]") .createTestSuite()); suite.addTest( MultisetTestSuiteBuilder.using(unionGenerator()) .withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES) .named("Multisets.union") .createTestSuite()); suite.addTest( MultisetTestSuiteBuilder.using(intersectionGenerator()) .withFeatures( CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER) .named("Multisets.intersection") .createTestSuite()); suite.addTest( MultisetTestSuiteBuilder.using(sumGenerator()) .withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES) .named("Multisets.sum") .createTestSuite()); suite.addTest( MultisetTestSuiteBuilder.using(differenceGenerator()) .withFeatures( CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER) .named("Multisets.difference") .createTestSuite()); suite.addTest( MultisetTestSuiteBuilder.using(filteredGenerator()) .withFeatures( CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE) .named("Multiset.filter[Multiset, Predicate]") .createTestSuite()); return suite; } private static TestStringMultisetGenerator unmodifiableMultisetGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return Multisets.unmodifiableMultiset(LinkedHashMultiset.create(asList(elements))); } @Override public List<String> order(List<String> insertionOrder) { List<String> order = new ArrayList<>(); for (String s : insertionOrder) { int index = order.indexOf(s); if (index == -1) { order.add(s); } else { order.add(index, s); } } return order; } }; } private static TestStringMultisetGenerator unmodifiableSortedMultisetGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return Multisets.unmodifiableSortedMultiset(TreeMultiset.create(asList(elements))); } @Override public List<String> order(List<String> insertionOrder) { Collections.sort(insertionOrder); return insertionOrder; } }; } private static TestStringMultisetGenerator unionGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { Multiset<String> multiset1 = LinkedHashMultiset.create(); Multiset<String> multiset2 = LinkedHashMultiset.create(); for (int i = 0; i < elements.length; i++) { String element = elements[i]; if (multiset1.contains(element) || multiset2.contains(element)) { // add to both; the one already containing it will have more multiset1.add(element); multiset2.add(element); } else if (i % 2 == 0) { multiset1.add(elements[i]); } else { multiset2.add(elements[i]); } } return Multisets.union(multiset1, multiset2); } }; } private static TestStringMultisetGenerator intersectionGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { Multiset<String> multiset1 = LinkedHashMultiset.create(); Multiset<String> multiset2 = LinkedHashMultiset.create(); multiset1.add("only1"); multiset2.add("only2"); for (int i = 0; i < elements.length; i++) { multiset1.add(elements[i]); multiset2.add(elements[elements.length - 1 - i]); } if (elements.length > 0) { multiset1.add(elements[0]); } if (elements.length > 1) { /* * When a test requests a multiset with duplicates, our plan of * "add an extra item 0 to A and an extra item 1 to B" really means * "add an extra item 0 to A and B," which isn't what we want. */ if (!Objects.equal(elements[0], elements[1])) { multiset2.add(elements[1], 2); } } return Multisets.intersection(multiset1, multiset2); } }; } private static TestStringMultisetGenerator sumGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { Multiset<String> multiset1 = LinkedHashMultiset.create(); Multiset<String> multiset2 = LinkedHashMultiset.create(); for (int i = 0; i < elements.length; i++) { // add to either; sum should contain all if (i % 2 == 0) { multiset1.add(elements[i]); } else { multiset2.add(elements[i]); } } return Multisets.sum(multiset1, multiset2); } }; } private static TestStringMultisetGenerator differenceGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { Multiset<String> multiset1 = LinkedHashMultiset.create(); Multiset<String> multiset2 = LinkedHashMultiset.create(); multiset1.add("equalIn1"); multiset1.add("fewerIn1"); multiset2.add("equalIn1"); multiset2.add("fewerIn1", 3); multiset2.add("onlyIn2", 2); for (int i = 0; i < elements.length; i++) { // add 1 more copy of each element to multiset1 than multiset2 multiset1.add(elements[i], i + 2); multiset2.add(elements[i], i + 1); } return Multisets.difference(multiset1, multiset2); } }; } private static final ImmutableMultiset<String> ELEMENTS_TO_FILTER_OUT = ImmutableMultiset.of("foobar", "bazfoo", "foobar", "foobar"); private static final Predicate<String> PREDICATE = Predicates.not(Predicates.in(ELEMENTS_TO_FILTER_OUT)); private static TestStringMultisetGenerator filteredGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { Multiset<String> multiset = LinkedHashMultiset.create(); Collections.addAll(multiset, elements); multiset.addAll(ELEMENTS_TO_FILTER_OUT); return Multisets.filter(multiset, PREDICATE); } @Override public List<String> order(List<String> insertionOrder) { return Lists.newArrayList(LinkedHashMultiset.create(insertionOrder)); } }; } }
/** * Copyright (c) 2007, Swedish Institute of Computer Science. * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. * * This file is part of MSPSim. * * $Id$ * * ----------------------------------------------------------------- * * ADC12 * * Each time a sample is converted the ADC12 system will check for EOS flag * and if not set it just continues with the next conversion (x + 1). * If EOS next conversion is startMem. * Interrupt is triggered when the IE flag are set! * * * Author : Joakim Eriksson * Created : Sun Oct 21 22:00:00 2007 * Updated : $Date$ * $Revision$ */ package se.sics.mspsim.core; import java.util.Arrays; import edu.umass.energy.Capacitor; public class ADC12 extends IOUnit { public static final int ADC12CTL0 = 0x01A0;// Reset with POR public static final int ADC12CTL1 = 0x01A2;// Reset with POR public static final int ADC12IFG = 0x01A4; //Reset with POR public static final int ADC12IE = 0x01A6; //Reset with POR public static final int ADC12IV = 0x01A8; //Reset with POR public static final int ADC12MEM0 = 0x0140; //Unchanged public static final int ADC12MEM1 = 0x0142; //Unchanged public static final int ADC12MEM2 = 0x0144; //Unchanged public static final int ADC12MEM3 = 0x0146; //Unchanged public static final int ADC12MEM4 = 0x0148; //Unchanged public static final int ADC12MEM5 = 0x014A; //Unchanged public static final int ADC12MEM6 = 0x014C; //Unchanged public static final int ADC12MEM7 = 0x014E; //Unchanged public static final int ADC12MEM8 = 0x0150; //Unchanged public static final int ADC12MEM9 = 0x0152; //Unchanged public static final int ADC12MEM10 = 0x0154; //Unchanged public static final int ADC12MEM11 = 0x0156; //Unchanged public static final int ADC12MEM12 = 0x0158; //Unchanged public static final int ADC12MEM13 = 0x015A; //Unchanged public static final int ADC12MEM14 = 0x015C; //Unchanged public static final int ADC12MEM15 = 0x015E; //Unchanged public static final int ADC12MCTL0 = 0x080; //Reset with POR public static final int ADC12MCTL1 = 0x081; //Reset with POR public static final int ADC12MCTL2 = 0x082; //Reset with POR public static final int ADC12MCTL3 = 0x083; //Reset with POR public static final int ADC12MCTL4 = 0x084; //Reset with POR public static final int ADC12MCTL5 = 0x085; //Reset with POR public static final int ADC12MCTL6 = 0x086; //Reset with POR public static final int ADC12MCTL7 = 0x087; //Reset with POR public static final int ADC12MCTL8 = 0x088; //Reset with POR public static final int ADC12MCTL9 = 0x089; //Reset with POR public static final int ADC12MCTL10 = 0x08A; //Reset with POR public static final int ADC12MCTL11 = 0x08B; //Reset with POR public static final int ADC12MCTL12 = 0x08C; //Reset with POR public static final int ADC12MCTL13 = 0x08D; //Reset with POR public static final int ADC12MCTL14 = 0x08E; //Reset with POR public static final int ADC12MCTL15 = 0x08F; //Reset with POR public static final int[] SHTBITS = new int[] { 4, 8, 16, 32, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1024, 1024, 1024 }; public static final int BUSY_MASK = 0x01; public static final int EOS_MASK = 0x80; public static final int CONSEQ_SINGLE = 0x00; public static final int CONSEQ_SEQUENCE = 0x01; public static final int CONSEQ_REPEAT_SINGLE = 0x02; public static final int CONSEQ_REPEAT_SEQUENCE = 0x03; public static final int CONSEQ_SEQUENCE_MASK = 0x01; private int adc12ctl0 = 0; private int adc12ctl1 = 0; private int[] adc12mctl = new int[16]; private int[] adc12mem = new int[16]; private int adc12Pos = 0; private int shTime0 = 4; private int shTime1 = 4; private boolean adc12On = false; private boolean enableConversion; private boolean startConversion; private boolean isConverting; private int shSource = 0; private int startMem = 0; private int adcDiv = 1; private ADCInput adcInput[] = new ADCInput[16]; private int conSeq; private int adc12ie; private int adc12ifg; private int adc12iv; private int adcSSel; private int adc12Vector = 7; private TimeEvent adcTrigger = new TimeEvent(0) { public void execute(long t) { // System.out.println(getName() + " **** executing update timers at " + t + " cycles=" + cpu.cycles); convert(); cpu.getCapacitor().setPowerMode(Capacitor.POWERMODE_ACTIVE); } }; public ADC12(MSP430Core cpu) { super("ADC12", cpu, cpu.memory, 0); } public void reset(int type) { enableConversion = false; startConversion = false; isConverting = false; adc12ctl0 = 0; adc12ctl1 = 0; shTime0 = shTime1 = 4; adc12On = false; shSource = 0; startMem = adc12Pos = 0; adcDiv = 1; conSeq = 0; adc12ie = 0; adc12ifg = 0; adc12iv = 0; adcSSel = 0; Arrays.fill(adc12mctl, 0); } public void setADCInput(int adindex, ADCInput input) { adcInput[adindex] = input; } // write a value to the IO unit public void write(int address, int value, boolean word, long cycles) { switch (address) { case ADC12CTL0: if (enableConversion) { // Ongoing conversion: only some parts may be changed adc12ctl0 = (adc12ctl0 & 0xfff0) + (value & 0xf); } else { adc12ctl0 = value; shTime0 = SHTBITS[(value >> 8) & 0x0f]; shTime1 = SHTBITS[(value >> 12) & 0x0f]; adc12On = (value & 0x10) > 0; } enableConversion = (value & 0x02) > 0; startConversion = (value & 0x01) > 0; if (DEBUG) log("Set SHTime0: " + shTime0 + " SHTime1: " + shTime1 + " ENC:" + enableConversion + " Start: " + startConversion + " ADC12ON: " + adc12On); if (adc12On && enableConversion && startConversion && !isConverting) { // Set the start time to be now! isConverting = true; adc12Pos = startMem; int delay = adcDiv * ((adc12Pos < 8 ? shTime0 : shTime1) + 13); cpu.scheduleTimeEvent(adcTrigger, cpu.getTime() + delay); } break; case ADC12CTL1: if (enableConversion) { // Ongoing conversion: only some parts may be changed adc12ctl1 = (adc12ctl1 & 0xfff8) + (value & 0x6); } else { adc12ctl1 = value & 0xfffe; startMem = (value >> 12) & 0xf; shSource = (value >> 10) & 0x3; adcDiv = ((value >> 5) & 0x7) + 1; adcSSel = (value >> 3) & 0x03; } conSeq = (value >> 1) & 0x03; if (DEBUG) log("Set startMem: " + startMem + " SHSource: " + shSource + " ConSeq-mode:" + conSeq + " Div: " + adcDiv + " ADCSSEL: " + adcSSel); break; case ADC12IE: adc12ie = value; break; case ADC12IFG: adc12ifg = value; break; default: if (address >= ADC12MCTL0 && address <= ADC12MCTL15) { if (enableConversion) { /* Ongoing conversion: not possible to modify */ } else { adc12mctl[address - ADC12MCTL0] = value & 0xff; if (DEBUG) log("ADC12MCTL" + (address - ADC12MCTL0) + " source = " + (value & 0xf) + (((value & EOS_MASK) != 0) ? " EOS bit set" : "")); } } } } // read a value from the IO unit public int read(int address, boolean word, long cycles) { switch(address) { case ADC12CTL0: return adc12ctl0; case ADC12CTL1: return isConverting ? (adc12ctl1 | BUSY_MASK) : adc12ctl1; case ADC12IE: return adc12ie; case ADC12IFG: return adc12ifg; default: if (address >= ADC12MCTL0 && address <= ADC12MCTL15) { return adc12mctl[address - ADC12MCTL0]; } else if (address >= ADC12MEM0 && address <= ADC12MEM15) { int reg = (address - ADC12MEM0) / 2; // Clear ifg! adc12ifg &= ~(1 << reg); // System.out.println("Read ADCMEM" + (reg / 2)); if (adc12iv == reg * 2 + 6) { cpu.flagInterrupt(adc12Vector, this, false); adc12iv = 0; // System.out.println("** de-Trigger ADC12 IRQ for ADCMEM" + adc12Pos); } return adc12mem[reg]; } } return 0; } int smp = 0; private void convert() { // If off then just return... if (!adc12On) { isConverting = false; return; } boolean runAgain = enableConversion && conSeq != CONSEQ_SINGLE; // Some noise... ADCInput input = adcInput[adc12mctl[adc12Pos] & 0xf]; adc12mem[adc12Pos] = input != null ? input.nextData(adc12Pos) : 2048 + 100 - smp & 255; smp += 7; adc12ifg |= (1 << adc12Pos); if ((adc12ie & (1 << adc12Pos)) > 0) { // This should check if there already is an higher iv! adc12iv = adc12Pos * 2 + 6; //System.out.println("** Trigger ADC12 IRQ for ADCMEM" + adc12Pos); cpu.flagInterrupt(adc12Vector, this, true); } if ((conSeq & CONSEQ_SEQUENCE_MASK) != 0) { // Increase if ((adc12mctl[adc12Pos] & EOS_MASK) == EOS_MASK) { adc12Pos = startMem; if (conSeq == CONSEQ_SEQUENCE) { // Single sequence only runAgain = false; } } else { adc12Pos = (adc12Pos + 1) & 0x0f; } } if (!runAgain) { isConverting = false; } else { int delay = adcDiv * ((adc12Pos < 8 ? shTime0 : shTime1) + 13); cpu.scheduleTimeEvent(adcTrigger, adcTrigger.time + delay); } int delay = adcDiv * (shTime0 + 13) + 647/*XXX*/; System.err.println("cycles="+cpu.cycles); cpu.scheduleTimeEvent(adcTrigger, adcTrigger.time + delay); } public void interruptServiced(int vector) { } }
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.sagemaker.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/CreateCompilationJob" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateCompilationJobRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * A name for the model compilation job. The name must be unique within the AWS Region and within your AWS account. * </p> */ private String compilationJobName; /** * <p> * The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your behalf. * </p> * <p> * During model compilation, Amazon SageMaker needs your permission to: * </p> * <ul> * <li> * <p> * Read input data from an S3 bucket * </p> * </li> * <li> * <p> * Write model artifacts to an S3 bucket * </p> * </li> * <li> * <p> * Write logs to Amazon CloudWatch Logs * </p> * </li> * <li> * <p> * Publish metrics to Amazon CloudWatch * </p> * </li> * </ul> * <p> * You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the caller of * this API must have the <code>iam:PassRole</code> permission. For more information, see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon SageMaker Roles.</a> * </p> */ private String roleArn; /** * <p> * Provides information about the location of input model artifacts, the name and shape of the expected data inputs, * and the framework in which the model was trained. * </p> */ private InputConfig inputConfig; /** * <p> * Provides information about the output location for the compiled model and the target device the model runs on. * </p> */ private OutputConfig outputConfig; /** * <p> * Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, Amazon * SageMaker ends the compilation job. Use this API to cap model training costs. * </p> */ private StoppingCondition stoppingCondition; /** * <p> * A name for the model compilation job. The name must be unique within the AWS Region and within your AWS account. * </p> * * @param compilationJobName * A name for the model compilation job. The name must be unique within the AWS Region and within your AWS * account. */ public void setCompilationJobName(String compilationJobName) { this.compilationJobName = compilationJobName; } /** * <p> * A name for the model compilation job. The name must be unique within the AWS Region and within your AWS account. * </p> * * @return A name for the model compilation job. The name must be unique within the AWS Region and within your AWS * account. */ public String getCompilationJobName() { return this.compilationJobName; } /** * <p> * A name for the model compilation job. The name must be unique within the AWS Region and within your AWS account. * </p> * * @param compilationJobName * A name for the model compilation job. The name must be unique within the AWS Region and within your AWS * account. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCompilationJobRequest withCompilationJobName(String compilationJobName) { setCompilationJobName(compilationJobName); return this; } /** * <p> * The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your behalf. * </p> * <p> * During model compilation, Amazon SageMaker needs your permission to: * </p> * <ul> * <li> * <p> * Read input data from an S3 bucket * </p> * </li> * <li> * <p> * Write model artifacts to an S3 bucket * </p> * </li> * <li> * <p> * Write logs to Amazon CloudWatch Logs * </p> * </li> * <li> * <p> * Publish metrics to Amazon CloudWatch * </p> * </li> * </ul> * <p> * You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the caller of * this API must have the <code>iam:PassRole</code> permission. For more information, see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon SageMaker Roles.</a> * </p> * * @param roleArn * The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your * behalf. </p> * <p> * During model compilation, Amazon SageMaker needs your permission to: * </p> * <ul> * <li> * <p> * Read input data from an S3 bucket * </p> * </li> * <li> * <p> * Write model artifacts to an S3 bucket * </p> * </li> * <li> * <p> * Write logs to Amazon CloudWatch Logs * </p> * </li> * <li> * <p> * Publish metrics to Amazon CloudWatch * </p> * </li> * </ul> * <p> * You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the * caller of this API must have the <code>iam:PassRole</code> permission. For more information, see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon SageMaker Roles.</a> */ public void setRoleArn(String roleArn) { this.roleArn = roleArn; } /** * <p> * The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your behalf. * </p> * <p> * During model compilation, Amazon SageMaker needs your permission to: * </p> * <ul> * <li> * <p> * Read input data from an S3 bucket * </p> * </li> * <li> * <p> * Write model artifacts to an S3 bucket * </p> * </li> * <li> * <p> * Write logs to Amazon CloudWatch Logs * </p> * </li> * <li> * <p> * Publish metrics to Amazon CloudWatch * </p> * </li> * </ul> * <p> * You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the caller of * this API must have the <code>iam:PassRole</code> permission. For more information, see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon SageMaker Roles.</a> * </p> * * @return The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your * behalf. </p> * <p> * During model compilation, Amazon SageMaker needs your permission to: * </p> * <ul> * <li> * <p> * Read input data from an S3 bucket * </p> * </li> * <li> * <p> * Write model artifacts to an S3 bucket * </p> * </li> * <li> * <p> * Write logs to Amazon CloudWatch Logs * </p> * </li> * <li> * <p> * Publish metrics to Amazon CloudWatch * </p> * </li> * </ul> * <p> * You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the * caller of this API must have the <code>iam:PassRole</code> permission. For more information, see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon SageMaker Roles.</a> */ public String getRoleArn() { return this.roleArn; } /** * <p> * The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your behalf. * </p> * <p> * During model compilation, Amazon SageMaker needs your permission to: * </p> * <ul> * <li> * <p> * Read input data from an S3 bucket * </p> * </li> * <li> * <p> * Write model artifacts to an S3 bucket * </p> * </li> * <li> * <p> * Write logs to Amazon CloudWatch Logs * </p> * </li> * <li> * <p> * Publish metrics to Amazon CloudWatch * </p> * </li> * </ul> * <p> * You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the caller of * this API must have the <code>iam:PassRole</code> permission. For more information, see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon SageMaker Roles.</a> * </p> * * @param roleArn * The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your * behalf. </p> * <p> * During model compilation, Amazon SageMaker needs your permission to: * </p> * <ul> * <li> * <p> * Read input data from an S3 bucket * </p> * </li> * <li> * <p> * Write model artifacts to an S3 bucket * </p> * </li> * <li> * <p> * Write logs to Amazon CloudWatch Logs * </p> * </li> * <li> * <p> * Publish metrics to Amazon CloudWatch * </p> * </li> * </ul> * <p> * You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the * caller of this API must have the <code>iam:PassRole</code> permission. For more information, see <a * href="https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html">Amazon SageMaker Roles.</a> * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCompilationJobRequest withRoleArn(String roleArn) { setRoleArn(roleArn); return this; } /** * <p> * Provides information about the location of input model artifacts, the name and shape of the expected data inputs, * and the framework in which the model was trained. * </p> * * @param inputConfig * Provides information about the location of input model artifacts, the name and shape of the expected data * inputs, and the framework in which the model was trained. */ public void setInputConfig(InputConfig inputConfig) { this.inputConfig = inputConfig; } /** * <p> * Provides information about the location of input model artifacts, the name and shape of the expected data inputs, * and the framework in which the model was trained. * </p> * * @return Provides information about the location of input model artifacts, the name and shape of the expected data * inputs, and the framework in which the model was trained. */ public InputConfig getInputConfig() { return this.inputConfig; } /** * <p> * Provides information about the location of input model artifacts, the name and shape of the expected data inputs, * and the framework in which the model was trained. * </p> * * @param inputConfig * Provides information about the location of input model artifacts, the name and shape of the expected data * inputs, and the framework in which the model was trained. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCompilationJobRequest withInputConfig(InputConfig inputConfig) { setInputConfig(inputConfig); return this; } /** * <p> * Provides information about the output location for the compiled model and the target device the model runs on. * </p> * * @param outputConfig * Provides information about the output location for the compiled model and the target device the model runs * on. */ public void setOutputConfig(OutputConfig outputConfig) { this.outputConfig = outputConfig; } /** * <p> * Provides information about the output location for the compiled model and the target device the model runs on. * </p> * * @return Provides information about the output location for the compiled model and the target device the model * runs on. */ public OutputConfig getOutputConfig() { return this.outputConfig; } /** * <p> * Provides information about the output location for the compiled model and the target device the model runs on. * </p> * * @param outputConfig * Provides information about the output location for the compiled model and the target device the model runs * on. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCompilationJobRequest withOutputConfig(OutputConfig outputConfig) { setOutputConfig(outputConfig); return this; } /** * <p> * Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, Amazon * SageMaker ends the compilation job. Use this API to cap model training costs. * </p> * * @param stoppingCondition * Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, Amazon * SageMaker ends the compilation job. Use this API to cap model training costs. */ public void setStoppingCondition(StoppingCondition stoppingCondition) { this.stoppingCondition = stoppingCondition; } /** * <p> * Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, Amazon * SageMaker ends the compilation job. Use this API to cap model training costs. * </p> * * @return Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, * Amazon SageMaker ends the compilation job. Use this API to cap model training costs. */ public StoppingCondition getStoppingCondition() { return this.stoppingCondition; } /** * <p> * Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, Amazon * SageMaker ends the compilation job. Use this API to cap model training costs. * </p> * * @param stoppingCondition * Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, Amazon * SageMaker ends the compilation job. Use this API to cap model training costs. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCompilationJobRequest withStoppingCondition(StoppingCondition stoppingCondition) { setStoppingCondition(stoppingCondition); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCompilationJobName() != null) sb.append("CompilationJobName: ").append(getCompilationJobName()).append(","); if (getRoleArn() != null) sb.append("RoleArn: ").append(getRoleArn()).append(","); if (getInputConfig() != null) sb.append("InputConfig: ").append(getInputConfig()).append(","); if (getOutputConfig() != null) sb.append("OutputConfig: ").append(getOutputConfig()).append(","); if (getStoppingCondition() != null) sb.append("StoppingCondition: ").append(getStoppingCondition()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateCompilationJobRequest == false) return false; CreateCompilationJobRequest other = (CreateCompilationJobRequest) obj; if (other.getCompilationJobName() == null ^ this.getCompilationJobName() == null) return false; if (other.getCompilationJobName() != null && other.getCompilationJobName().equals(this.getCompilationJobName()) == false) return false; if (other.getRoleArn() == null ^ this.getRoleArn() == null) return false; if (other.getRoleArn() != null && other.getRoleArn().equals(this.getRoleArn()) == false) return false; if (other.getInputConfig() == null ^ this.getInputConfig() == null) return false; if (other.getInputConfig() != null && other.getInputConfig().equals(this.getInputConfig()) == false) return false; if (other.getOutputConfig() == null ^ this.getOutputConfig() == null) return false; if (other.getOutputConfig() != null && other.getOutputConfig().equals(this.getOutputConfig()) == false) return false; if (other.getStoppingCondition() == null ^ this.getStoppingCondition() == null) return false; if (other.getStoppingCondition() != null && other.getStoppingCondition().equals(this.getStoppingCondition()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCompilationJobName() == null) ? 0 : getCompilationJobName().hashCode()); hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode()); hashCode = prime * hashCode + ((getInputConfig() == null) ? 0 : getInputConfig().hashCode()); hashCode = prime * hashCode + ((getOutputConfig() == null) ? 0 : getOutputConfig().hashCode()); hashCode = prime * hashCode + ((getStoppingCondition() == null) ? 0 : getStoppingCondition().hashCode()); return hashCode; } @Override public CreateCompilationJobRequest clone() { return (CreateCompilationJobRequest) super.clone(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package freemarker.template; import static freemarker.test.hamcerst.Matchers.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.junit.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import freemarker.ext.beans.BeansWrapper; import freemarker.ext.beans.HashAdapter; import freemarker.ext.util.WrapperTemplateModel; public class DefaultObjectWrapperTest { private final static DefaultObjectWrapper OW0 = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_0) .build(); private final static DefaultObjectWrapper OW22 = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_22) .build(); private final static DefaultObjectWrapper OW22NM = new DefaultObjectWrapper(Configuration.VERSION_2_3_22); static { OW22NM.setNullModel(NullModel.INSTANCE); } private final static DefaultObjectWrapper OW22_FUTURE = new DefaultObjectWrapper(Configuration.VERSION_2_3_22); static { OW22_FUTURE.setForceLegacyNonListCollections(false); } @Test public void testIncompatibleImprovementsVersionBreakPoints() throws Exception { List<Version> expected = new ArrayList<Version>(); for (int u = 0; u < 21; u++) { expected.add(Configuration.VERSION_2_3_0); } expected.add(Configuration.VERSION_2_3_21); expected.add(Configuration.VERSION_2_3_22); expected.add(Configuration.VERSION_2_3_22); List<Version> actual = new ArrayList<Version>(); for (int i = _TemplateAPI.VERSION_INT_2_3_0; i <= Configuration.getVersion().intValue(); i++) { if (i > _TemplateAPI.VERSION_INT_2_3_22 && i < _TemplateAPI.VERSION_INT_2_4_0) { continue; } int major = i / 1000000; int minor = i % 1000000 / 1000; int micro = i % 1000; final Version version = new Version(major, minor, micro); final Version normalizedVersion = DefaultObjectWrapper.normalizeIncompatibleImprovementsVersion(version); actual.add(normalizedVersion); final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(version); assertEquals(normalizedVersion, builder.getIncompatibleImprovements()); assertEquals(normalizedVersion, builder.build().getIncompatibleImprovements()); } assertEquals(expected, actual); } @Test public void testIncompatibleImprovementsVersionOutOfBounds() throws Exception { try { DefaultObjectWrapper.normalizeIncompatibleImprovementsVersion(new Version(2, 2, 0)); fail(); } catch (IllegalArgumentException e) { // expected } Version curVersion = Configuration.getVersion(); final Version futureVersion = new Version(curVersion.getMajor(), curVersion.getMicro(), curVersion.getMicro() + 1); try { DefaultObjectWrapper.normalizeIncompatibleImprovementsVersion(futureVersion); fail(); } catch (IllegalArgumentException e) { // expected } try { new DefaultObjectWrapperBuilder(futureVersion); fail(); } catch (IllegalArgumentException e) { // expected } } @SuppressWarnings("boxing") @Test public void testBuilder() throws Exception { { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_19); DefaultObjectWrapper bw = builder.build(); assertSame(bw, builder.build()); assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals(Configuration.VERSION_2_3_0, bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertTrue(bw.isClassIntrospectionCacheRestricted()); assertFalse(bw.getUseAdaptersForContainers()); assertTrue(bw.getForceLegacyNonListCollections()); assertTrue(bw.wrap(new HashMap()) instanceof SimpleHash); assertTrue(bw.wrap(new ArrayList()) instanceof SimpleSequence); assertTrue(bw.wrap(new String[] {}) instanceof SimpleSequence); assertTrue(bw.wrap(new HashSet()) instanceof SimpleSequence); } for (boolean simpleMapWrapper : new boolean[] { true, false }) { { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_21); builder.setSimpleMapWrapper(simpleMapWrapper); // Shouldn't mater DefaultObjectWrapper bw = builder.build(); assertSame(bw, builder.build()); assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals(Configuration.VERSION_2_3_21, bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertEquals(simpleMapWrapper, bw.isSimpleMapWrapper()); assertFalse(bw.getUseAdaptersForContainers()); assertTrue(bw.getForceLegacyNonListCollections()); assertTrue(bw.wrap(new HashMap()) instanceof SimpleHash); assertTrue(bw.wrap(new ArrayList()) instanceof SimpleSequence); assertTrue(bw.wrap(new String[] {}) instanceof SimpleSequence); assertTrue(bw.wrap(new HashSet()) instanceof SimpleSequence); assertTrue(bw.wrap('c') instanceof TemplateScalarModel); // StringModel now, but should change later } { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_22); builder.setSimpleMapWrapper(simpleMapWrapper); // Shouldn't mater DefaultObjectWrapper bw = builder.build(); assertSame(bw, builder.build()); assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals(Configuration.VERSION_2_3_22, bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertEquals(simpleMapWrapper, bw.isSimpleMapWrapper()); assertTrue(bw.getUseAdaptersForContainers()); assertTrue(bw.getForceLegacyNonListCollections()); assertTrue(bw.wrap(new HashMap()) instanceof DefaultMapAdapter); assertTrue(bw.wrap(new ArrayList()) instanceof DefaultListAdapter); assertTrue(bw.wrap(new String[] {}) instanceof DefaultArrayAdapter); assertTrue(bw.wrap(new HashSet()) instanceof SimpleSequence); } } { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.getVersion()); builder.setSimpleMapWrapper(true); BeansWrapper bw = builder.build(); assertSame(bw, builder.build()); assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals( DefaultObjectWrapper.normalizeIncompatibleImprovementsVersion(Configuration.getVersion()), bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertTrue(bw.isSimpleMapWrapper()); assertTrue(bw.wrap(new HashMap()) instanceof DefaultMapAdapter); } { DefaultObjectWrapper bw = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_19).build(); assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals(Configuration.VERSION_2_3_0, bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertFalse(bw.isSimpleMapWrapper()); assertTrue(bw.wrap(new HashMap()) instanceof SimpleHash); assertSame(bw, new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_20).build()); assertSame(bw, new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_0).build()); assertSame(bw, new DefaultObjectWrapperBuilder(new Version(2, 3, 5)).build()); } { DefaultObjectWrapper bw = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_21).build(); assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals(Configuration.VERSION_2_3_21, bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertFalse(bw.isSimpleMapWrapper()); assertTrue(bw.wrap(new HashMap()) instanceof SimpleHash); assertTrue(bw.isClassIntrospectionCacheRestricted()); assertSame(bw, new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_21).build()); } { DefaultObjectWrapper bw = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_19).build(); assertEquals(Configuration.VERSION_2_3_0, bw.getIncompatibleImprovements()); } { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_19); builder.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY); DefaultObjectWrapper bw = builder.build(); DefaultObjectWrapper bw2 = builder.build(); assertSame(bw, bw2); // not cached assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals(Configuration.VERSION_2_3_0, bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertFalse(bw.isSimpleMapWrapper()); assertTrue(bw.wrap(new HashMap()) instanceof SimpleHash); assertEquals(BeansWrapper.EXPOSE_PROPERTIES_ONLY, bw.getExposureLevel()); } { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_19); builder.setExposeFields(true); BeansWrapper bw = builder.build(); BeansWrapper bw2 = builder.build(); assertSame(bw, bw2); // not cached assertSame(bw.getClass(), DefaultObjectWrapper.class); assertEquals(Configuration.VERSION_2_3_0, bw.getIncompatibleImprovements()); assertTrue(bw.isWriteProtected()); assertFalse(bw.isSimpleMapWrapper()); assertTrue(bw.wrap(new HashMap()) instanceof SimpleHash); assertEquals(true, bw.isExposeFields()); } { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_21); builder.setForceLegacyNonListCollections(false); DefaultObjectWrapper bw = builder.build(); assertSame(bw, builder.build()); assertFalse(bw.getForceLegacyNonListCollections()); assertTrue(bw.wrap(new HashMap()) instanceof SimpleHash); assertTrue(bw.wrap(new ArrayList()) instanceof SimpleSequence); assertTrue(bw.wrap(new String[] {}) instanceof SimpleSequence); assertTrue(bw.wrap(new HashSet()) instanceof SimpleSequence); } { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_22); builder.setForceLegacyNonListCollections(false); DefaultObjectWrapper bw = builder.build(); assertSame(bw, builder.build()); assertFalse(bw.getForceLegacyNonListCollections()); assertTrue(bw.wrap(new HashMap()) instanceof DefaultMapAdapter); assertTrue(bw.wrap(new ArrayList()) instanceof DefaultListAdapter); assertTrue(bw.wrap(new String[] {}) instanceof DefaultArrayAdapter); assertTrue(bw.wrap(new HashSet()) instanceof DefaultNonListCollectionAdapter); } } @Test public void testConstructors() throws Exception { { DefaultObjectWrapper ow = new DefaultObjectWrapper(); assertEquals(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS, ow.getIncompatibleImprovements()); assertFalse(ow.isWriteProtected()); assertFalse(ow.getUseAdaptersForContainers()); assertTrue(ow.getForceLegacyNonListCollections()); } { DefaultObjectWrapper ow = new DefaultObjectWrapper(Configuration.VERSION_2_3_20); assertEquals(Configuration.VERSION_2_3_0, ow.getIncompatibleImprovements()); assertFalse(ow.isWriteProtected()); assertFalse(ow.getUseAdaptersForContainers()); assertTrue(ow.getForceLegacyNonListCollections()); } { DefaultObjectWrapper ow = new DefaultObjectWrapper(Configuration.VERSION_2_3_21); assertEquals(Configuration.VERSION_2_3_21, ow.getIncompatibleImprovements()); assertFalse(ow.isWriteProtected()); assertFalse(ow.getUseAdaptersForContainers()); assertTrue(ow.getForceLegacyNonListCollections()); } { DefaultObjectWrapper ow = new DefaultObjectWrapper(Configuration.VERSION_2_3_22); assertEquals(Configuration.VERSION_2_3_22, ow.getIncompatibleImprovements()); assertFalse(ow.isWriteProtected()); assertTrue(ow.getUseAdaptersForContainers()); assertTrue(ow.getForceLegacyNonListCollections()); } try { new DefaultObjectWrapper(new Version(99, 9, 9)); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("version")); } } @Test public void testCustomization() throws TemplateModelException { { CustomizedDefaultObjectWrapper ow = new CustomizedDefaultObjectWrapper(Configuration.VERSION_2_3_22); assertEquals(Configuration.VERSION_2_3_22, ow.getIncompatibleImprovements()); assertTrue(ow.getUseAdaptersForContainers()); testCustomizationCommonPart(ow, DefaultMapAdapter.class, DefaultListAdapter.class, DefaultArrayAdapter.class); } { CustomizedDefaultObjectWrapper ow = new CustomizedDefaultObjectWrapper(Configuration.VERSION_2_3_21); assertFalse(ow.getUseAdaptersForContainers()); assertEquals(Configuration.VERSION_2_3_21, ow.getIncompatibleImprovements()); testCustomizationCommonPart(ow, SimpleHash.class, SimpleSequence.class, SimpleSequence.class); } { CustomizedDefaultObjectWrapper ow = new CustomizedDefaultObjectWrapper(Configuration.VERSION_2_3_20); assertFalse(ow.getUseAdaptersForContainers()); assertEquals(Configuration.VERSION_2_3_0, ow.getIncompatibleImprovements()); testCustomizationCommonPart(ow, SimpleHash.class, SimpleSequence.class, SimpleSequence.class); } } @SuppressWarnings("boxing") private void testCustomizationCommonPart(CustomizedDefaultObjectWrapper ow, Class<? extends TemplateHashModel> mapTMClass, Class<? extends TemplateSequenceModel> listTMClass, Class<? extends TemplateSequenceModel> arrayTMClass) throws TemplateModelException { assertFalse(ow.isWriteProtected()); TemplateSequenceModel seq = (TemplateSequenceModel) ow.wrap(new Tupple(11, 22)); assertEquals(2, seq.size()); assertEquals(11, ow.unwrap(seq.get(0))); assertEquals(22, ow.unwrap(seq.get(1))); assertTrue(ow.wrap("x") instanceof SimpleScalar); assertTrue(ow.wrap(1.5) instanceof SimpleNumber); assertTrue(ow.wrap(new Date()) instanceof SimpleDate); assertEquals(TemplateBooleanModel.TRUE, ow.wrap(true)); assertTrue(mapTMClass.isInstance(ow.wrap(Collections.emptyMap()))); assertTrue(listTMClass.isInstance(ow.wrap(Collections.emptyList()))); assertTrue(arrayTMClass.isInstance(ow.wrap(new boolean[] { }))); assertTrue(ow.wrap(new HashSet()) instanceof SimpleSequence); // at least until IcI 2.4 assertTrue(ow.wrap('c') instanceof TemplateScalarModel); // StringModel right now, but should change later TemplateHashModel bean = (TemplateHashModel) ow.wrap(new TestBean()); assertEquals(1, ow.unwrap(bean.get("x"))); { // Check method calls, and also if the return value is wrapped with the overidden "wrap". final TemplateModel mr = (TemplateModel) ((TemplateMethodModelEx) bean.get("m")).exec(Collections.emptyList()); assertEquals( Collections.singletonList(1), ow.unwrap(mr)); assertTrue(listTMClass.isInstance(mr)); } { // Check custom TM usage and round trip: final TemplateModel mr = (TemplateModel) ((TemplateMethodModelEx) bean.get("incTupple")) .exec(Collections.singletonList(ow.wrap(new Tupple<Integer, Integer>(1, 2)))); assertEquals(new Tupple<Integer, Integer>(2, 3), ow.unwrap(mr)); assertTrue(TuppleAdapter.class.isInstance(mr)); } } @SuppressWarnings("boxing") @Test public void testRoundtripping() throws TemplateModelException, ClassNotFoundException { DefaultObjectWrapper dow21 = new DefaultObjectWrapper(Configuration.VERSION_2_3_21); DefaultObjectWrapper dow22 = new DefaultObjectWrapper(Configuration.VERSION_2_3_22); final Map hashMap = new HashMap(); inintTestMap(hashMap); final Map treeMap = new TreeMap(); inintTestMap(treeMap); final Map linkedHashMap = new LinkedHashMap(); inintTestMap(linkedHashMap); final Map gMap = ImmutableMap.<String, Object> of("a", 1, "b", 2, "c", 3); final LinkedList linkedList = new LinkedList(); linkedList.add("a"); linkedList.add("b"); linkedList.add("c"); final int[] intArray = new int[] { 1, 2, 3 }; final String[] stringArray = new String[] { "a", "b", "c" }; assertRoundtrip(dow21, linkedHashMap, SimpleHash.class, HashAdapter.class, linkedHashMap.toString()); assertRoundtrip(dow21, treeMap, SimpleHash.class, HashAdapter.class, treeMap.toString()); assertRoundtrip(dow21, gMap, SimpleHash.class, HashAdapter.class, hashMap.toString()); assertRoundtrip(dow21, linkedList, SimpleSequence.class, Class.forName("freemarker.ext.beans.SequenceAdapter"), linkedList.toString()); assertRoundtrip(dow21, intArray, SimpleSequence.class, Class.forName("freemarker.ext.beans.SequenceAdapter"), "[1, 2, 3]"); assertRoundtrip(dow21, stringArray, SimpleSequence.class, Class.forName("freemarker.ext.beans.SequenceAdapter"), "[a, b, c]"); assertRoundtrip(dow22, linkedHashMap, DefaultMapAdapter.class, LinkedHashMap.class, linkedHashMap.toString()); assertRoundtrip(dow22, treeMap, DefaultMapAdapter.class, TreeMap.class, treeMap.toString()); assertRoundtrip(dow22, gMap, DefaultMapAdapter.class, ImmutableMap.class, gMap.toString()); assertRoundtrip(dow22, linkedList, DefaultListAdapter.class, LinkedList.class, linkedList.toString()); assertRoundtrip(dow22, intArray, DefaultArrayAdapter.class, int[].class, null); assertRoundtrip(dow22, stringArray, DefaultArrayAdapter.class, String[].class, null); } @SuppressWarnings("boxing") private void inintTestMap(Map map) { map.put("a", 1); map.put("b", 2); map.put("c", 3); } @SuppressWarnings("boxing") @Test public void testMapAdapter() throws TemplateModelException { HashMap<String, Object> testMap = new LinkedHashMap<String, Object>(); testMap.put("a", 1); testMap.put("b", null); testMap.put("c", "C"); testMap.put("d", Collections.singletonList("x")); { TemplateHashModelEx hash = (TemplateHashModelEx) OW22.wrap(testMap); assertEquals(4, hash.size()); assertFalse(hash.isEmpty()); assertNull(hash.get("e")); assertEquals(1, ((TemplateNumberModel) hash.get("a")).getAsNumber()); assertNull(hash.get("b")); assertEquals("C", ((TemplateScalarModel) hash.get("c")).getAsString()); assertTrue(hash.get("d") instanceof DefaultListAdapter); assertCollectionTMEquals(hash.keys(), "a", "b", "c", "d"); assertCollectionTMEquals(hash.values(), 1, null, "C", Collections.singletonList("x")); assertSizeThroughAPIModel(4, hash); } { assertTrue(((TemplateHashModel) OW22.wrap(Collections.emptyMap())).isEmpty()); } { final TemplateHashModelEx hash = (TemplateHashModelEx) OW22NM.wrap(testMap); assertSame(NullModel.INSTANCE, hash.get("b")); assertNull(hash.get("e")); assertCollectionTMEquals(hash.keys(), "a", "b", "c", "d"); assertCollectionTMEquals(hash.values(), 1, null, "C", Collections.singletonList("x")); } } private void assertCollectionTMEquals(TemplateCollectionModel coll, Object... expectedItems) throws TemplateModelException { for (int i = 0; i < 2; i++) { // Run twice to check if we always get a new iterator int idx = 0; TemplateModelIterator it2 = null; for (TemplateModelIterator it = coll.iterator(); it.hasNext(); ) { TemplateModel actualItem = it.next(); if (idx >= expectedItems.length) { fail("Number of items is more than the expected " + expectedItems.length); } assertEquals(expectedItems[idx], OW22.unwrap(actualItem)); if (i == 1) { // In the 2nd round we also test with two iterators in parallel. // This 2nd iterator is also special in that its hasNext() is never called. if (it2 == null) { it2 = coll.iterator(); } assertEquals(expectedItems[idx], OW22.unwrap(it2.next())); } idx++; } if (expectedItems.length != idx) { fail("Number of items is " + idx + ", which is less than the expected " + expectedItems.length); } } } @SuppressWarnings("boxing") @Test public void testListAdapter() throws TemplateModelException { { List testList = new ArrayList<Object>(); testList.add(1); testList.add(null); testList.add("c"); testList.add(new String[] { "x" }); TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(testList); assertTrue(seq instanceof DefaultListAdapter); assertFalse(seq instanceof TemplateCollectionModel); // Maybe changes at 2.4.0 assertEquals(4, seq.size()); assertNull(seq.get(-1)); assertEquals(1, ((TemplateNumberModel) seq.get(0)).getAsNumber()); assertNull(seq.get(1)); assertEquals("c", ((TemplateScalarModel) seq.get(2)).getAsString()); assertTrue(seq.get(3) instanceof DefaultArrayAdapter); assertNull(seq.get(4)); assertSizeThroughAPIModel(4, seq); } { List testList = new LinkedList<Object>(); testList.add(1); testList.add(null); testList.add("c"); TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(testList); assertTrue(seq instanceof DefaultListAdapter); assertTrue(seq instanceof TemplateCollectionModel); // Maybe changes at 2.4.0 assertEquals(3, seq.size()); assertNull(seq.get(-1)); assertEquals(1, ((TemplateNumberModel) seq.get(0)).getAsNumber()); assertNull(seq.get(1)); assertEquals("c", ((TemplateScalarModel) seq.get(2)).getAsString()); assertNull(seq.get(3)); assertCollectionTMEquals((TemplateCollectionModel) seq, 1, null, "c"); TemplateModelIterator it = ((TemplateCollectionModel) seq).iterator(); it.next(); it.next(); it.next(); try { it.next(); fail(); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsString("no more")); } } { List testList = new ArrayList<Object>(); testList.add(null); final TemplateSequenceModel seq = (TemplateSequenceModel) OW22NM.wrap(testList); assertSame(NullModel.INSTANCE, seq.get(0)); assertNull(seq.get(1)); } } @Test public void testArrayAdapterTypes() throws TemplateModelException { assertArrayAdapterClass("Object", OW22.wrap(new Object[] {})); assertArrayAdapterClass("Object", OW22.wrap(new String[] {})); assertArrayAdapterClass("byte", OW22.wrap(new byte[] {})); assertArrayAdapterClass("short", OW22.wrap(new short[] {})); assertArrayAdapterClass("int", OW22.wrap(new int[] {})); assertArrayAdapterClass("long", OW22.wrap(new long[] {})); assertArrayAdapterClass("float", OW22.wrap(new float[] {})); assertArrayAdapterClass("double", OW22.wrap(new double[] {})); assertArrayAdapterClass("boolean", OW22.wrap(new boolean[] {})); assertArrayAdapterClass("char", OW22.wrap(new char[] {})); } private void assertArrayAdapterClass(String adapterCompType, TemplateModel adaptedArray) { assertTrue(adaptedArray instanceof DefaultArrayAdapter); assertThat(adaptedArray.getClass().getName(), containsString("$" + adapterCompType.substring(0, 1).toUpperCase() + adapterCompType.substring(1))); } @SuppressWarnings("boxing") @Test public void testArrayAdapters() throws TemplateModelException { { final String[] testArray = new String[] { "a", null, "c" }; { TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(testArray); assertEquals(3, seq.size()); assertNull(seq.get(-1)); assertEquals("a", ((TemplateScalarModel) seq.get(0)).getAsString()); assertNull(seq.get(1)); assertEquals("c", ((TemplateScalarModel) seq.get(2)).getAsString()); assertNull(seq.get(3)); } { TemplateSequenceModel seq = (TemplateSequenceModel) OW22NM.wrap(testArray); assertNull(seq.get(-1)); assertEquals("a", ((TemplateScalarModel) seq.get(0)).getAsString()); assertSame(NullModel.INSTANCE, seq.get(1)); assertEquals("c", ((TemplateScalarModel) seq.get(2)).getAsString()); assertNull(seq.get(3)); } } { final int[] testArray = new int[] { 11, 22 }; TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(testArray); assertEquals(2, seq.size()); assertNull(seq.get(-1)); assertEqualsAndSameClass(Integer.valueOf(11), ((TemplateNumberModel) seq.get(0)).getAsNumber()); assertEqualsAndSameClass(Integer.valueOf(22), ((TemplateNumberModel) seq.get(1)).getAsNumber()); assertNull(seq.get(2)); } { final double[] testArray = new double[] { 11, 22 }; TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(testArray); assertEquals(2, seq.size()); assertNull(seq.get(-1)); assertEqualsAndSameClass(Double.valueOf(11), ((TemplateNumberModel) seq.get(0)).getAsNumber()); assertEqualsAndSameClass(Double.valueOf(22), ((TemplateNumberModel) seq.get(1)).getAsNumber()); assertNull(seq.get(2)); } { final boolean[] testArray = new boolean[] { true, false }; TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(testArray); assertEquals(2, seq.size()); assertNull(seq.get(-1)); assertEqualsAndSameClass(Boolean.valueOf(true), ((TemplateBooleanModel) seq.get(0)).getAsBoolean()); assertEqualsAndSameClass(Boolean.valueOf(false), ((TemplateBooleanModel) seq.get(1)).getAsBoolean()); assertNull(seq.get(2)); } { final char[] testArray = new char[] { 'a', 'b' }; TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(testArray); assertEquals(2, seq.size()); assertNull(seq.get(-1)); assertEquals("a", ((TemplateScalarModel) seq.get(0)).getAsString()); assertEquals("b", ((TemplateScalarModel) seq.get(1)).getAsString()); assertNull(seq.get(2)); } } private void assertEqualsAndSameClass(Object expected, Object actual) { assertEquals(expected, actual); if (expected != null) { assertEquals(expected.getClass(), actual.getClass()); } } private void assertRoundtrip(DefaultObjectWrapper dow, Object obj, Class expectedTMClass, Class expectedPojoClass, String expectedPojoToString) throws TemplateModelException { final TemplateModel objTM = dow.wrap(obj); assertTrue(expectedTMClass.isAssignableFrom(objTM.getClass())); final TemplateHashModel testBeanTM = (TemplateHashModel) dow.wrap(new RoundtripTesterBean()); { TemplateMethodModelEx getClassM = (TemplateMethodModelEx) testBeanTM.get("getClass"); Object r = getClassM.exec(Collections.singletonList(objTM)); final Class rClass = (Class) ((WrapperTemplateModel) r).getWrappedObject(); assertTrue(rClass + " instanceof " + expectedPojoClass, expectedPojoClass.isAssignableFrom(rClass)); } if (expectedPojoToString != null) { TemplateMethodModelEx getToStringM = (TemplateMethodModelEx) testBeanTM.get("toString"); Object r = getToStringM.exec(Collections.singletonList(objTM)); assertEquals(expectedPojoToString, ((TemplateScalarModel) r).getAsString()); } } @SuppressWarnings("boxing") @Test public void testCollectionAdapterBasics() throws TemplateModelException { { Set set = new TreeSet(); set.add("a"); set.add("b"); set.add("c"); TemplateCollectionModelEx coll = (TemplateCollectionModelEx) OW22_FUTURE.wrap(set); assertTrue(coll instanceof DefaultNonListCollectionAdapter); assertEquals(3, coll.size()); assertFalse(coll.isEmpty()); assertCollectionTMEquals(coll, "a", "b", "c"); assertTrue(coll.contains(OW22_FUTURE.wrap("a"))); assertTrue(coll.contains(OW22_FUTURE.wrap("b"))); assertTrue(coll.contains(OW22_FUTURE.wrap("c"))); assertTrue(coll.contains(OW22_FUTURE.wrap("c"))); assertFalse(coll.contains(OW22_FUTURE.wrap("d"))); try { assertFalse(coll.contains(OW22_FUTURE.wrap(1))); fail(); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsString("Integer")); } assertRoundtrip(OW22_FUTURE, set, DefaultNonListCollectionAdapter.class, TreeSet.class, "[a, b, c]"); assertSizeThroughAPIModel(3, coll); } { Set set = new HashSet(); final List<String> list = Collections.singletonList("b"); set.add(list); set.add(null); TemplateCollectionModelEx coll = (TemplateCollectionModelEx) OW22_FUTURE.wrap(set); TemplateModelIterator it = coll.iterator(); final TemplateModel tm1 = it.next(); Object obj1 = OW22_FUTURE.unwrap(tm1); final TemplateModel tm2 = it.next(); Object obj2 = OW22_FUTURE.unwrap(tm2); assertTrue(obj1 == null || obj2 == null); assertTrue(obj1 != null && obj1.equals(list) || obj2 != null && obj2.equals(list)); assertTrue(tm1 instanceof DefaultListAdapter || tm2 instanceof DefaultListAdapter); List similarList = new ArrayList(); similarList.add("b"); assertTrue(coll.contains(OW22_FUTURE.wrap(similarList))); assertTrue(coll.contains(OW22_FUTURE.wrap(null))); assertFalse(coll.contains(OW22_FUTURE.wrap("a"))); assertFalse(coll.contains(OW22_FUTURE.wrap(1))); assertRoundtrip(OW22_FUTURE, set, DefaultNonListCollectionAdapter.class, HashSet.class, "[" + obj1 + ", " + obj2 + "]"); } } @SuppressWarnings("boxing") @Test public void testCollectionAdapterOutOfBounds() throws TemplateModelException { Set set = Collections.singleton(123); TemplateCollectionModelEx coll = (TemplateCollectionModelEx) OW22_FUTURE.wrap(set); TemplateModelIterator it = coll.iterator(); for (int i = 0; i < 3; i++) { assertTrue(it.hasNext()); } assertEquals(123, OW22_FUTURE.unwrap(it.next())); for (int i = 0; i < 3; i++) { assertFalse(it.hasNext()); try { it.next(); fail(); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsStringIgnoringCase("no more")); } } } @Test public void testCollectionAdapterAndNulls() throws TemplateModelException { Set set = new HashSet(); set.add(null); { DefaultObjectWrapper dow = new DefaultObjectWrapper(Configuration.VERSION_2_3_22); dow.setForceLegacyNonListCollections(false); TemplateCollectionModelEx coll = (TemplateCollectionModelEx) dow.wrap(set); assertEquals(1, coll.size()); assertFalse(coll.isEmpty()); assertNull(coll.iterator().next()); } { DefaultObjectWrapper dow = new DefaultObjectWrapper(Configuration.VERSION_2_3_22); dow.setForceLegacyNonListCollections(false); dow.setNullModel(NullModel.INSTANCE); TemplateCollectionModelEx coll = (TemplateCollectionModelEx) dow.wrap(set); assertEquals(1, coll.size()); assertFalse(coll.isEmpty()); assertEquals(NullModel.INSTANCE, coll.iterator().next()); } } @Test public void testLegacyNonListCollectionWrapping() throws TemplateModelException { Set set = new TreeSet(); set.add("a"); set.add("b"); set.add("c"); TemplateSequenceModel seq = (TemplateSequenceModel) OW22.wrap(set); assertTrue(seq instanceof SimpleSequence); assertEquals(3, seq.size()); assertEquals("a", OW22.unwrap(seq.get(0))); assertEquals("b", OW22.unwrap(seq.get(1))); assertEquals("c", OW22.unwrap(seq.get(2))); } @Test public void testIteratorWrapping() throws TemplateModelException, ClassNotFoundException { testIteratorWrapping(OW0, SimpleCollection.class, Class.forName("freemarker.ext.beans.SetAdapter")); testIteratorWrapping(OW22, DefaultIteratorAdapter.class, Iterator.class); } private void testIteratorWrapping(DefaultObjectWrapper ow, Class<?> expectedTMClass, Class<?> expectedPOJOClass) throws TemplateModelException { final List<String> list = ImmutableList.<String> of("a", "b", "c"); Iterator<String> it = list.iterator(); TemplateCollectionModel coll = (TemplateCollectionModel) ow.wrap(it); assertRoundtrip(ow, coll, expectedTMClass, expectedPOJOClass, null); TemplateModelIterator itIt = coll.iterator(); TemplateModelIterator itIt2 = coll.iterator(); // used later assertTrue(itIt.hasNext()); assertEquals("a", ow.unwrap(itIt.next())); assertTrue(itIt.hasNext()); assertEquals("b", ow.unwrap(itIt.next())); assertTrue(itIt.hasNext()); assertEquals("c", ow.unwrap(itIt.next())); assertFalse(itIt.hasNext()); try { itIt.next(); fail(); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsStringIgnoringCase("no more")); } try { itIt2.hasNext(); fail(); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsString("can be listed only once")); } TemplateModelIterator itIt3 = coll.iterator(); try { itIt3.hasNext(); fail(); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsString("can be listed only once")); } } @SuppressWarnings("boxing") @Test public void testCharKeyFallback() throws TemplateModelException { Map hashMapS = new HashMap<String, Integer>(); hashMapS.put("a", 1); Map sortedMapS = new TreeMap<String, Integer>(); sortedMapS.put("a", 1); Map hashMapC = new HashMap<Character, Integer>(); hashMapC.put('a', 1); Map sortedMapC = new TreeMap<Character, Integer>(); sortedMapC.put('a', 1); for (DefaultObjectWrapper ow : new DefaultObjectWrapper[] { OW0, OW22 } ) { assertEquals(1, ow.unwrap(((TemplateHashModel) ow.wrap(hashMapS)).get("a"))); assertEquals(1, ow.unwrap(((TemplateHashModel) ow.wrap(hashMapC)).get("a"))); assertEquals(1, ow.unwrap(((TemplateHashModel) ow.wrap(sortedMapS)).get("a"))); try { ((TemplateHashModel) ow.wrap(sortedMapC)).get("a"); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsStringIgnoringCase("String key")); } assertNull(((TemplateHashModel) ow.wrap(hashMapS)).get("b")); assertNull(((TemplateHashModel) ow.wrap(hashMapC)).get("b")); assertNull(((TemplateHashModel) ow.wrap(sortedMapS)).get("b")); try { ((TemplateHashModel) ow.wrap(sortedMapC)).get("b"); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsStringIgnoringCase("String key")); } } } @Test public void assertCanWrapDOM() throws SAXException, IOException, ParserConfigurationException, TemplateModelException { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader("<doc><sub a='1' /></doc>")); Document doc = db.parse(is); assertTrue(OW22.wrap(doc) instanceof TemplateNodeModel); } private void assertSizeThroughAPIModel(int expectedSize, TemplateModel normalModel) throws TemplateModelException { if (!(normalModel instanceof TemplateModelWithAPISupport)) { fail(); } TemplateHashModel apiModel = (TemplateHashModel) ((TemplateModelWithAPISupport) normalModel).getAPI(); TemplateMethodModelEx sizeMethod = (TemplateMethodModelEx) apiModel.get("size"); TemplateNumberModel r = (TemplateNumberModel) sizeMethod.exec(Collections.emptyList()); assertEquals(expectedSize, r.getAsNumber().intValue()); } public static class RoundtripTesterBean { public Class getClass(Object o) { return o.getClass(); } public String toString(Object o) { return o.toString(); } } private static final class NullModel implements TemplateModel, AdapterTemplateModel { final static NullModel INSTANCE = new NullModel(); public Object getAdaptedObject(Class hint) { return null; } } private static class Tupple<E1, E2> { private final E1 e1; private final E2 e2; public Tupple(E1 e1, E2 e2) { if (e1 == null || e2 == null) throw new NullPointerException(); this.e1 = e1; this.e2 = e2; } public E1 getE1() { return e1; } public E2 getE2() { return e2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((e1 == null) ? 0 : e1.hashCode()); result = prime * result + ((e2 == null) ? 0 : e2.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tupple other = (Tupple) obj; if (e1 == null) { if (other.e1 != null) return false; } else if (!e1.equals(other.e1)) return false; if (e2 == null) { if (other.e2 != null) return false; } else if (!e2.equals(other.e2)) return false; return true; } } @SuppressWarnings("boxing") public static class TestBean { public int getX() { return 1; } public List<Integer> m() { return Collections.singletonList(1); } public Tupple incTupple(Tupple<Integer, Integer> tupple) { return new Tupple(tupple.e1 + 1, tupple.e2 + 1); } } private static class CustomizedDefaultObjectWrapper extends DefaultObjectWrapper { private CustomizedDefaultObjectWrapper(Version incompatibleImprovements) { super(incompatibleImprovements); } @Override protected TemplateModel handleUnknownType(final Object obj) throws TemplateModelException { if (obj instanceof Tupple) { return new TuppleAdapter((Tupple<?, ?>) obj, this); } return super.handleUnknownType(obj); } } private static class TuppleAdapter extends WrappingTemplateModel implements TemplateSequenceModel, AdapterTemplateModel { private final Tupple<?, ?> tupple; public TuppleAdapter(Tupple<?, ?> tupple, ObjectWrapper ow) { super(ow); this.tupple = tupple; } public int size() throws TemplateModelException { return 2; } public TemplateModel get(int index) throws TemplateModelException { switch (index) { case 0: return wrap(tupple.getE1()); case 1: return wrap(tupple.getE2()); default: return null; } } public Object getAdaptedObject(Class hint) { return tupple; } }; }
/* * Copyright (c) 2014 MrEngineer13 * 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.mrengineer13.snackbar.sample; import android.os.Bundle; import android.os.Parcelable; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Spinner; import android.widget.Toast; import com.github.mrengineer13.about.AboutActivity; import com.github.mrengineer13.snackbar.SnackBar; public class SnackBarActivity extends ActionBarActivity implements SnackBar.OnMessageClickListener { public static final String SAVED_SNACKBAR = "SAVED_SNACKBAR"; static final int SHORT_MSG = 0, LONG_MSG = 1; static final int SHORT_SNACK = 0, MED_SNACK = 1, LONG_SNACK = 2; static final int DEFAULT = 0, ALERT = 1, CONFIRM = 2, INFO = 3; static final int ACTION_BTN = 0, NO_ACTION_BTN = 1; static final int STRING_TYPE_STRING = 0, STRING_TYPE_RESOURCE = 1; private Spinner mMsgLengthOptions, mDurationOptions, mActionBtnOptions, mActionBtnColorOptions, mBGColorOptions, mStringTypeOptions; private SnackBar mSnackBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_snack_bar); mMsgLengthOptions = (Spinner) findViewById(R.id.message_length_selector); mDurationOptions = (Spinner) findViewById(R.id.snack_duration_selector); mActionBtnOptions = (Spinner) findViewById(R.id.action_btn_presence_selector); mActionBtnColorOptions = (Spinner) findViewById(R.id.action_btn_color); mBGColorOptions = (Spinner) findViewById(R.id.bg_color); mStringTypeOptions = (Spinner) findViewById(R.id.action_btn_string_type); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.snack_bar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_about) { startActivity(AboutActivity.getAboutActivityIntent(this, "MrEngineer13", "https://github.com/MrEngineer13", "MrEngineer13@live.com", "@MrEngineer13", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=K6PSQMTJYG5VJ", true, "MrEngineer13", null)); return true; } return super.onOptionsItemSelected(item); } public void onCreateClicked(View view) { String message = ""; int messageRes = -1; short duration = 0; SnackBar.Style style; SnackBar.Style bgStyle; int bgColor; int selectedStringType = mStringTypeOptions.getSelectedItemPosition(); int selectedMessageLength = mMsgLengthOptions.getSelectedItemPosition(); switch (selectedMessageLength) { case SHORT_MSG: if (selectedStringType == STRING_TYPE_STRING) { message = "This is a one-line message."; } else { messageRes = R.string.short_message; } break; case LONG_MSG: if (selectedStringType == STRING_TYPE_STRING) { message = "This message is a lot longer, it should stretch at least two lines. "; } else { messageRes = R.string.long_message; } break; } int selectedDuration = mDurationOptions.getSelectedItemPosition(); switch (selectedDuration) { case SHORT_SNACK: duration = SnackBar.SHORT_SNACK; break; case MED_SNACK: duration = SnackBar.MED_SNACK; break; case LONG_SNACK: duration = SnackBar.LONG_SNACK; break; } int selectedActionBtnColor = mActionBtnColorOptions.getSelectedItemPosition(); switch (selectedActionBtnColor) { default: case DEFAULT: style = SnackBar.Style.DEFAULT; break; case ALERT: style = SnackBar.Style.ALERT; break; case CONFIRM: style = SnackBar.Style.CONFIRM; break; case INFO: style = SnackBar.Style.INFO; break; } int selectedBGColor = mBGColorOptions.getSelectedItemPosition(); switch (selectedBGColor) { default: case DEFAULT: bgColor = R.color.sb__snack_bkgnd; break; case ALERT: bgColor = R.color.sb__snack_alert_bkgnd; break; } int selectedActionBtnExistance = mActionBtnOptions.getSelectedItemPosition(); switch (selectedActionBtnExistance) { case ACTION_BTN: if (messageRes <= 0) { mSnackBar = new SnackBar.Builder(this) .withOnClickListener(this) .withMessage(message) .withActionMessage("Action") .withStyle(style) .withBackgroundColorId(bgColor) .withDuration(duration) .show(); } else { mSnackBar = new SnackBar.Builder(this) .withOnClickListener(this) .withMessageId(messageRes) .withActionMessageId(R.string.action) .withStyle(style) .withBackgroundColorId(bgColor) .withDuration(duration) .show(); } break; case NO_ACTION_BTN: if (messageRes <= 0) { mSnackBar = new SnackBar.Builder(this) .withMessage(message) .withBackgroundColorId(bgColor) .withDuration(duration) .show(); } else { mSnackBar = new SnackBar.Builder(this) .withMessageId(messageRes) .withBackgroundColorId(bgColor) .withDuration(duration) .show(); } break; } } @Override protected void onSaveInstanceState(Bundle saveState) { super.onSaveInstanceState(saveState); // use this to save your snacks for later //saveState.putBundle(SAVED_SNACKBAR, mSnackBar.onSaveInstanceState()); } @Override protected void onRestoreInstanceState(Bundle loadState) { super.onRestoreInstanceState(loadState); // use this to load your snacks for later //mSnackBar.onRestoreInstanceState(loadState.getBundle(SAVED_SNACKBAR)); } @Override public void onMessageClick(Parcelable token) { Toast.makeText(this, "Button clicked!", Toast.LENGTH_LONG).show(); } }
package io.github.rampantlions.codetools.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.logging.Level; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.logging.LogFactory; import org.apache.http.client.HttpClient; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.IncorrectnessListener; import com.gargoylesoftware.htmlunit.InteractivePage; import com.gargoylesoftware.htmlunit.ScriptException; import com.gargoylesoftware.htmlunit.SilentCssErrorHandler; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HTMLParserListener; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.javascript.JavaScriptErrorListener; @SuppressWarnings( "deprecation" ) public class StandAloneUtilities { public static String get( URL url ) throws IOException, NoSuchAlgorithmException, KeyManagementException { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( X509Certificate[] certs, String authType ) {} public void checkServerTrusted( X509Certificate[] certs, String authType ) {} } }; SSLContext sc = SSLContext.getInstance( "SSL" ); sc.init( null, trustAllCerts, new java.security.SecureRandom() ); HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory() ); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify( String hostname, SSLSession session ) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier( allHostsValid ); String input = ""; URLConnection conn = url.openConnection(); BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ) ); String inputLine; while ( ( inputLine = br.readLine() ) != null ) { input += inputLine; } br.close(); return input; } /** * The Class HostVerifier. */ public static class HostVerifier implements X509HostnameVerifier { /** * verify * (non-Javadoc) * * @param hostname * @param session * @return * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSession) */ @Override public boolean verify( String hostname, SSLSession session ) { return true; } /** * verify * (non-Javadoc) * * @param host * @param ssl * @throws IOException * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSocket) */ @Override public void verify( String host, SSLSocket ssl ) throws IOException { } /** * verify * (non-Javadoc) * * @param host * @param cns * @param subjectAlts * @throws SSLException * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.lang.String[], java.lang.String[]) */ @Override public void verify( String host, String[] cns, String[] subjectAlts ) throws SSLException { } /** * verify * (non-Javadoc) * * @param host * @param cert * @throws SSLException * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.security.cert.X509Certificate) */ @Override public void verify( String host, X509Certificate cert ) throws SSLException { } } /** * A factory for creating TrustSSLSocket objects. */ public class TrustSSLSocketFactory extends SSLSocketFactory { /** The ssl context. */ SSLContext sslContext = SSLContext.getInstance( "TLS" ); /** * Instantiates a new trust ssl socket factory. * * @param truststore the truststore * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyManagementException the key management exception * @throws KeyStoreException the key store exception * @throws UnrecoverableKeyException the unrecoverable key exception */ public TrustSSLSocketFactory( KeyStore truststore ) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super( truststore ); TrustManager tm = new X509TrustManager() { public void checkClientTrusted( X509Certificate[] chain, String authType ) throws CertificateException {} public void checkServerTrusted( X509Certificate[] chain, String authType ) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init( null, new TrustManager[] { tm }, null ); } /** * createSocket * (non-Javadoc) * * @return * @throws IOException * @see org.apache.http.conn.ssl.SSLSocketFactory#createSocket() */ @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } /** * createSocket * (non-Javadoc) * * @param socket * @param host * @param port * @param autoClose * @return * @throws IOException * @throws UnknownHostException * @see org.apache.http.conn.ssl.SSLSocketFactory#createSocket(java.net.Socket, java.lang.String, int, boolean) */ @Override public Socket createSocket( Socket socket, String host, int port, boolean autoClose ) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket( socket, host, port, autoClose ); } } /* * Host name verifier. * * @return the hostname verifier */ public static X509HostnameVerifier hostNameVerifier() { // HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; X509HostnameVerifier allHostsValid = new HostVerifier(); return allHostsValid; } /** * New web client. * * @return the web client */ public static WebClient newWebClient() { LogFactory.getFactory().setAttribute( "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog" ); java.util.logging.Logger.getLogger( "org.apache.http.wire" ).setLevel( Level.OFF ); java.util.logging.Logger.getLogger( "com.gargoylesoftware" ).setLevel( Level.OFF ); java.util.logging.Logger.getLogger( "com.gargoylesoftware.htmlunit" ).setLevel( Level.OFF ); java.util.logging.Logger.getLogger( "org.apache.commons.httpclient" ).setLevel( Level.OFF ); java.util.logging.Logger.getLogger( "o.a.axis" ).setLevel( Level.OFF ); java.util.logging.Logger.getLogger( "o.a.axis.transport.http" ).setLevel( Level.OFF ); java.util.logging.Logger.getLogger( "org.apache.axis" ).setLevel( Level.OFF ); System.setProperty( "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog" ); // WebClient webClient = new WebClient( BrowserVersion.INTERNET_EXPLORER_8 ); WebClient webClient = new WebClient( BrowserVersion.FIREFOX_38 ); // WebClient webClient = new WebClient( BrowserVersion.CHROME ); webClient.getOptions().setJavaScriptEnabled( false ); webClient.getOptions().setThrowExceptionOnScriptError( false ); webClient.getOptions().setCssEnabled( true ); webClient.getOptions().setUseInsecureSSL( true ); webClient.getOptions().setRedirectEnabled( true ); webClient.getOptions().setThrowExceptionOnFailingStatusCode( true ); webClient.getOptions().setPrintContentOnFailingStatusCode( false ); // LogFactory.getFactory().setAttribute( "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog" ); // // System.setProperty( "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog" ); // java.util.logging.Logger.getLogger( "com.gargoylesoftware" ).setLevel( Level.OFF ); // java.util.logging.Logger.getLogger( "com.gargoylesoftware.htmlunit" ).setLevel( Level.OFF ); // java.util.logging.Logger.getLogger( "com.gargoylesoftware.htmlunit.level" ).setLevel( Level.OFF ); // java.util.logging.Logger.getLogger( "com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter.level" ).setLevel( Level.OFF ); // java.util.logging.Logger.getLogger( "com.gargoylesoftware.htmlunit.javascript.host.ActiveXObject.level" ).setLevel( Level.OFF ); // java.util.logging.Logger.getLogger( "com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument.level" ).setLevel( Level.OFF ); // java.util.logging.Logger.getLogger( "com.gargoylesoftware.htmlunit.html.HtmlScript.leve" ).setLevel( Level.OFF ); webClient.setIncorrectnessListener( new IncorrectnessListener() { @Override public void notify( final String arg0, final Object arg1 ) { // Ignore. } } ); webClient.setCssErrorHandler( new SilentCssErrorHandler() ); webClient.setJavaScriptErrorListener( new JavaScriptErrorListener() { public void loadScriptError( final HtmlPage arg0, final URL arg1, final Exception arg2 ) { // Ignore. } public void malformedScriptURL( final HtmlPage arg0, final String arg1, final MalformedURLException arg2 ) { // Ignore. } public void scriptException( final HtmlPage paramHtmlPage, final ScriptException paramScriptException ) { // Ignore. } public void timeoutError( final HtmlPage arg0, final long arg1, final long arg2 ) { // Ignore. } @Override public void loadScriptError(InteractivePage arg0, URL arg1, Exception arg2) { // TODO Auto-generated method stub } @Override public void malformedScriptURL(InteractivePage arg0, String arg1, MalformedURLException arg2) { // TODO Auto-generated method stub } @Override public void scriptException(InteractivePage arg0, ScriptException arg1) { // TODO Auto-generated method stub } @Override public void timeoutError(InteractivePage arg0, long arg1, long arg2) { // TODO Auto-generated method stub } } ); webClient.setHTMLParserListener( new HTMLParserListener() { @Override public void error( final String paramString1, final URL paramURL, final String paramString2, final int paramInt1, final int paramInt2, final String paramString3 ) { // Ignore. } @Override public void warning( final String paramString1, final URL paramURL, final String paramString2, final int paramInt1, final int paramInt2, final String paramString3 ) { // Ignore. } } ); return webClient; } /** * Setup ignore security cert. * * @param client2 the new up ignore security cert */ public static void setupIgnoreSecurityCert( final HttpClient client2 ) { // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance( "SSL" ); sc.init( null, ClientUtilities.trustManager(), new java.security.SecureRandom() ); SSLSocketFactory socketFactory = new SSLSocketFactory( sc ); socketFactory.setHostnameVerifier( hostNameVerifier() ); Scheme sch = new Scheme( "https", 443, socketFactory ); client2.getConnectionManager().getSchemeRegistry().register( sch ); } catch ( NoSuchAlgorithmException | KeyManagementException e ) { // e.printStackTrace(); } } /** * Trust manager. * * @return the trust manager[] */ public static TrustManager[] trustManager() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted( final X509Certificate[] certs, final String authType ) {} @Override public void checkServerTrusted( final X509Certificate[] certs, final String authType ) {} @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; return trustAllCerts; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.fielddata.plain; import org.apache.lucene.document.HalfFloatPoint; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.search.SortField; import org.apache.lucene.search.SortedNumericSelector; import org.apache.lucene.search.SortedNumericSortField; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.index.Index; import org.elasticsearch.index.fielddata.AtomicNumericFieldData; import org.elasticsearch.index.fielddata.FieldData; import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested; import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.fielddata.NumericDoubleValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.fieldcomparator.DoubleValuesComparatorSource; import org.elasticsearch.index.fielddata.fieldcomparator.FloatValuesComparatorSource; import org.elasticsearch.index.fielddata.fieldcomparator.LongValuesComparatorSource; import org.elasticsearch.search.MultiValueMode; import java.io.IOException; import java.util.Collection; import java.util.Collections; /** * FieldData backed by {@link LeafReader#getSortedNumericDocValues(String)} * @see DocValuesType#SORTED_NUMERIC */ public class SortedNumericDVIndexFieldData extends DocValuesIndexFieldData implements IndexNumericFieldData { private final NumericType numericType; public SortedNumericDVIndexFieldData(Index index, String fieldNames, NumericType numericType) { super(index, fieldNames); if (numericType == null) { throw new IllegalArgumentException("numericType must be non-null"); } this.numericType = numericType; } @Override public SortField sortField(Object missingValue, MultiValueMode sortMode, Nested nested, boolean reverse) { final XFieldComparatorSource source; switch (numericType) { case HALF_FLOAT: case FLOAT: source = new FloatValuesComparatorSource(this, missingValue, sortMode, nested); break; case DOUBLE: source = new DoubleValuesComparatorSource(this, missingValue, sortMode, nested); break; default: assert !numericType.isFloatingPoint(); source = new LongValuesComparatorSource(this, missingValue, sortMode, nested); break; } /** * Check if we can use a simple {@link SortedNumericSortField} compatible with index sorting and * returns a custom sort field otherwise. */ if (nested != null || (sortMode != MultiValueMode.MAX && sortMode != MultiValueMode.MIN) || numericType == NumericType.HALF_FLOAT) { return new SortField(fieldName, source, reverse); } final SortField sortField; final SortedNumericSelector.Type selectorType = sortMode == MultiValueMode.MAX ? SortedNumericSelector.Type.MAX : SortedNumericSelector.Type.MIN; switch (numericType) { case FLOAT: sortField = new SortedNumericSortField(fieldName, SortField.Type.FLOAT, reverse, selectorType); break; case DOUBLE: sortField = new SortedNumericSortField(fieldName, SortField.Type.DOUBLE, reverse, selectorType); break; default: assert !numericType.isFloatingPoint(); sortField = new SortedNumericSortField(fieldName, SortField.Type.LONG, reverse, selectorType); break; } sortField.setMissingValue(source.missingObject(missingValue, reverse)); return sortField; } @Override public NumericType getNumericType() { return numericType; } @Override public AtomicNumericFieldData loadDirect(LeafReaderContext context) throws Exception { return load(context); } @Override public AtomicNumericFieldData load(LeafReaderContext context) { final LeafReader reader = context.reader(); final String field = fieldName; switch (numericType) { case HALF_FLOAT: return new SortedNumericHalfFloatFieldData(reader, field); case FLOAT: return new SortedNumericFloatFieldData(reader, field); case DOUBLE: return new SortedNumericDoubleFieldData(reader, field); default: return new SortedNumericLongFieldData(reader, field, numericType); } } /** * FieldData implementation for integral types. * <p> * Order of values within a document is consistent with * {@link Long#compareTo(Long)}. * <p> * Although the API is multi-valued, most codecs in Lucene specialize * for the case where documents have at most one value. In this case * {@link DocValues#unwrapSingleton(SortedNumericDocValues)} will return * the underlying single-valued NumericDocValues representation. */ static final class SortedNumericLongFieldData extends AtomicLongFieldData { final LeafReader reader; final String field; SortedNumericLongFieldData(LeafReader reader, String field, NumericType numericType) { super(0L, numericType); this.reader = reader; this.field = field; } @Override public SortedNumericDocValues getLongValues() { try { return DocValues.getSortedNumeric(reader, field); } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } } /** * FieldData implementation for 16-bit float values. * <p> * Order of values within a document is consistent with * {@link Float#compareTo(Float)}, hence the following reversible * transformation is applied at both index and search: * {@code bits ^ (bits >> 15) & 0x7fff} * <p> * Although the API is multi-valued, most codecs in Lucene specialize * for the case where documents have at most one value. In this case * {@link FieldData#unwrapSingleton(SortedNumericDoubleValues)} will return * the underlying single-valued NumericDoubleValues representation. */ public static final class SortedNumericHalfFloatFieldData extends AtomicDoubleFieldData { final LeafReader reader; final String field; public SortedNumericHalfFloatFieldData(LeafReader reader, String field) { super(0L); this.reader = reader; this.field = field; } @Override public SortedNumericDoubleValues getDoubleValues() { try { SortedNumericDocValues raw = DocValues.getSortedNumeric(reader, field); NumericDocValues single = DocValues.unwrapSingleton(raw); if (single != null) { return FieldData.singleton(new SingleHalfFloatValues(single)); } else { return new MultiHalfFloatValues(raw); } } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } } /** * Wraps a NumericDocValues and exposes a single 16-bit float per document. */ static final class SingleHalfFloatValues extends NumericDoubleValues { final NumericDocValues in; SingleHalfFloatValues(NumericDocValues in) { this.in = in; } @Override public double doubleValue() throws IOException { return HalfFloatPoint.sortableShortToHalfFloat((short) in.longValue()); } @Override public boolean advanceExact(int doc) throws IOException { return in.advanceExact(doc); } } /** * Wraps a SortedNumericDocValues and exposes multiple 16-bit floats per document. */ static final class MultiHalfFloatValues extends SortedNumericDoubleValues { final SortedNumericDocValues in; MultiHalfFloatValues(SortedNumericDocValues in) { this.in = in; } @Override public boolean advanceExact(int target) throws IOException { return in.advanceExact(target); } @Override public double nextValue() throws IOException { return HalfFloatPoint.sortableShortToHalfFloat((short) in.nextValue()); } @Override public int docValueCount() { return in.docValueCount(); } } /** * FieldData implementation for 32-bit float values. * <p> * Order of values within a document is consistent with * {@link Float#compareTo(Float)}, hence the following reversible * transformation is applied at both index and search: * {@code bits ^ (bits >> 31) & 0x7fffffff} * <p> * Although the API is multi-valued, most codecs in Lucene specialize * for the case where documents have at most one value. In this case * {@link FieldData#unwrapSingleton(SortedNumericDoubleValues)} will return * the underlying single-valued NumericDoubleValues representation. */ static final class SortedNumericFloatFieldData extends AtomicDoubleFieldData { final LeafReader reader; final String field; SortedNumericFloatFieldData(LeafReader reader, String field) { super(0L); this.reader = reader; this.field = field; } @Override public SortedNumericDoubleValues getDoubleValues() { try { SortedNumericDocValues raw = DocValues.getSortedNumeric(reader, field); NumericDocValues single = DocValues.unwrapSingleton(raw); if (single != null) { return FieldData.singleton(new SingleFloatValues(single)); } else { return new MultiFloatValues(raw); } } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } } /** * Wraps a NumericDocValues and exposes a single 32-bit float per document. */ static final class SingleFloatValues extends NumericDoubleValues { final NumericDocValues in; SingleFloatValues(NumericDocValues in) { this.in = in; } @Override public double doubleValue() throws IOException { return NumericUtils.sortableIntToFloat((int) in.longValue()); } @Override public boolean advanceExact(int doc) throws IOException { return in.advanceExact(doc); } } /** * Wraps a SortedNumericDocValues and exposes multiple 32-bit floats per document. */ static final class MultiFloatValues extends SortedNumericDoubleValues { final SortedNumericDocValues in; MultiFloatValues(SortedNumericDocValues in) { this.in = in; } @Override public boolean advanceExact(int target) throws IOException { return in.advanceExact(target); } @Override public double nextValue() throws IOException { return NumericUtils.sortableIntToFloat((int) in.nextValue()); } @Override public int docValueCount() { return in.docValueCount(); } } /** * FieldData implementation for 64-bit double values. * <p> * Order of values within a document is consistent with * {@link Double#compareTo(Double)}, hence the following reversible * transformation is applied at both index and search: * {@code bits ^ (bits >> 63) & 0x7fffffffffffffffL} * <p> * Although the API is multi-valued, most codecs in Lucene specialize * for the case where documents have at most one value. In this case * {@link FieldData#unwrapSingleton(SortedNumericDoubleValues)} will return * the underlying single-valued NumericDoubleValues representation. */ static final class SortedNumericDoubleFieldData extends AtomicDoubleFieldData { final LeafReader reader; final String field; SortedNumericDoubleFieldData(LeafReader reader, String field) { super(0L); this.reader = reader; this.field = field; } @Override public SortedNumericDoubleValues getDoubleValues() { try { SortedNumericDocValues raw = DocValues.getSortedNumeric(reader, field); return FieldData.sortableLongBitsToDoubles(raw); } catch (IOException e) { throw new IllegalStateException("Cannot load doc values", e); } } @Override public Collection<Accountable> getChildResources() { return Collections.emptyList(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db; import java.io.IOException; import java.util.concurrent.TimeUnit; import com.google.common.annotations.VisibleForTesting; import org.apache.cassandra.net.Verb; import org.apache.cassandra.schema.TableMetadata; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.filter.*; import org.apache.cassandra.db.lifecycle.View; import org.apache.cassandra.db.partitions.*; import org.apache.cassandra.db.rows.BaseRowIterator; import org.apache.cassandra.db.transform.RTBoundValidator; import org.apache.cassandra.db.transform.Transformation; import org.apache.cassandra.dht.AbstractBounds; import org.apache.cassandra.dht.Bounds; import org.apache.cassandra.exceptions.RequestExecutionException; import org.apache.cassandra.index.Index; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.sstable.format.SSTableReadsListener; import org.apache.cassandra.io.util.DataInputPlus; import org.apache.cassandra.io.util.DataOutputPlus; import org.apache.cassandra.metrics.TableMetrics; import org.apache.cassandra.schema.IndexMetadata; import org.apache.cassandra.service.ClientState; import org.apache.cassandra.service.StorageProxy; import org.apache.cassandra.tracing.Tracing; /** * A read command that selects a (part of a) range of partitions. */ public class PartitionRangeReadCommand extends ReadCommand implements PartitionRangeReadQuery { protected static final SelectionDeserializer selectionDeserializer = new Deserializer(); private final DataRange dataRange; private PartitionRangeReadCommand(boolean isDigest, int digestVersion, boolean acceptsTransient, TableMetadata metadata, int nowInSec, ColumnFilter columnFilter, RowFilter rowFilter, DataLimits limits, DataRange dataRange, IndexMetadata index, boolean trackWarnings) { super(Kind.PARTITION_RANGE, isDigest, digestVersion, acceptsTransient, metadata, nowInSec, columnFilter, rowFilter, limits, index, trackWarnings); this.dataRange = dataRange; } public static PartitionRangeReadCommand create(TableMetadata metadata, int nowInSec, ColumnFilter columnFilter, RowFilter rowFilter, DataLimits limits, DataRange dataRange) { return new PartitionRangeReadCommand(false, 0, false, metadata, nowInSec, columnFilter, rowFilter, limits, dataRange, findIndex(metadata, rowFilter), false); } /** * Creates a new read command that query all the data in the table. * * @param metadata the table to query. * @param nowInSec the time in seconds to use are "now" for this query. * * @return a newly created read command that queries everything in the table. */ public static PartitionRangeReadCommand allDataRead(TableMetadata metadata, int nowInSec) { return new PartitionRangeReadCommand(false, 0, false, metadata, nowInSec, ColumnFilter.all(metadata), RowFilter.NONE, DataLimits.NONE, DataRange.allData(metadata.partitioner), null, false); } public DataRange dataRange() { return dataRange; } public ClusteringIndexFilter clusteringIndexFilter(DecoratedKey key) { return dataRange.clusteringIndexFilter(key); } public boolean isNamesQuery() { return dataRange.isNamesQuery(); } /** * Returns an equivalent command but that only queries data within the provided range. * * @param range the sub-range to restrict the command to. This method <b>assumes</b> that this is a proper sub-range * of the command this is applied to. * @param isRangeContinuation whether {@code range} is a direct continuation of whatever previous range we have * queried. This matters for the {@code DataLimits} that may contain states when we do paging and in the context of * parallel queries: that state only make sense if the range queried is indeed the follow-up of whatever range we've * previously query (that yield said state). In practice this means that ranges for which {@code isRangeContinuation} * is false may have to be slightly pessimistic when counting data and may include a little bit than necessary, and * this should be dealt with post-query (in the case of {@code StorageProxy.getRangeSlice()}, which uses this method * for replica queries, this is dealt with by re-counting results on the coordinator). Note that if this is the * first range we queried, then the {@code DataLimits} will have not state and the value of this parameter doesn't * matter. */ public PartitionRangeReadCommand forSubRange(AbstractBounds<PartitionPosition> range, boolean isRangeContinuation) { // If we're not a continuation of whatever range we've previously queried, we should ignore the states of the // DataLimits as it's either useless, or misleading. This is particularly important for GROUP BY queries, where // DataLimits.CQLGroupByLimits.GroupByAwareCounter assumes that if GroupingState.hasClustering(), then we're in // the middle of a group, but we can't make that assumption if we query and range "in advance" of where we are // on the ring. return new PartitionRangeReadCommand(isDigestQuery(), digestVersion(), acceptsTransient(), metadata(), nowInSec(), columnFilter(), rowFilter(), isRangeContinuation ? limits() : limits().withoutState(), dataRange().forSubRange(range), indexMetadata(), isTrackingWarnings()); } public PartitionRangeReadCommand copy() { return new PartitionRangeReadCommand(isDigestQuery(), digestVersion(), acceptsTransient(), metadata(), nowInSec(), columnFilter(), rowFilter(), limits(), dataRange(), indexMetadata(), isTrackingWarnings()); } @Override protected PartitionRangeReadCommand copyAsDigestQuery() { return new PartitionRangeReadCommand(true, digestVersion(), false, metadata(), nowInSec(), columnFilter(), rowFilter(), limits(), dataRange(), indexMetadata(), isTrackingWarnings()); } @Override protected PartitionRangeReadCommand copyAsTransientQuery() { return new PartitionRangeReadCommand(false, 0, true, metadata(), nowInSec(), columnFilter(), rowFilter(), limits(), dataRange(), indexMetadata(), isTrackingWarnings()); } @Override public PartitionRangeReadCommand withUpdatedLimit(DataLimits newLimits) { return new PartitionRangeReadCommand(isDigestQuery(), digestVersion(), acceptsTransient(), metadata(), nowInSec(), columnFilter(), rowFilter(), newLimits, dataRange(), indexMetadata(), isTrackingWarnings()); } @Override public PartitionRangeReadCommand withUpdatedLimitsAndDataRange(DataLimits newLimits, DataRange newDataRange) { return new PartitionRangeReadCommand(isDigestQuery(), digestVersion(), acceptsTransient(), metadata(), nowInSec(), columnFilter(), rowFilter(), newLimits, newDataRange, indexMetadata(), isTrackingWarnings()); } public long getTimeout(TimeUnit unit) { return DatabaseDescriptor.getRangeRpcTimeout(unit); } public boolean isReversed() { return dataRange.isReversed(); } public PartitionIterator execute(ConsistencyLevel consistency, ClientState clientState, long queryStartNanoTime) throws RequestExecutionException { return StorageProxy.getRangeSlice(this, consistency, queryStartNanoTime); } protected void recordLatency(TableMetrics metric, long latencyNanos) { metric.rangeLatency.addNano(latencyNanos); } @VisibleForTesting public UnfilteredPartitionIterator queryStorage(final ColumnFamilyStore cfs, ReadExecutionController controller) { ColumnFamilyStore.ViewFragment view = cfs.select(View.selectLive(dataRange().keyRange())); Tracing.trace("Executing seq scan across {} sstables for {}", view.sstables.size(), dataRange().keyRange().getString(metadata().partitionKeyType)); // fetch data from current memtable, historical memtables, and SSTables in the correct order. InputCollector<UnfilteredPartitionIterator> inputCollector = iteratorsForRange(view, controller); try { for (Memtable memtable : view.memtables) { @SuppressWarnings("resource") // We close on exception and on closing the result returned by this method Memtable.MemtableUnfilteredPartitionIterator iter = memtable.makePartitionIterator(columnFilter(), dataRange()); controller.updateMinOldestUnrepairedTombstone(iter.getMinLocalDeletionTime()); inputCollector.addMemtableIterator(RTBoundValidator.validate(iter, RTBoundValidator.Stage.MEMTABLE, false)); } SSTableReadsListener readCountUpdater = newReadCountUpdater(); for (SSTableReader sstable : view.sstables) { @SuppressWarnings("resource") // We close on exception and on closing the result returned by this method UnfilteredPartitionIterator iter = sstable.getScanner(columnFilter(), dataRange(), readCountUpdater); inputCollector.addSSTableIterator(sstable, RTBoundValidator.validate(iter, RTBoundValidator.Stage.SSTABLE, false)); if (!sstable.isRepaired()) controller.updateMinOldestUnrepairedTombstone(sstable.getMinLocalDeletionTime()); } // iterators can be empty for offline tools if (inputCollector.isEmpty()) return EmptyIterators.unfilteredPartition(metadata()); return checkCacheFilter(UnfilteredPartitionIterators.mergeLazily(inputCollector.finalizeIterators(cfs, nowInSec(), controller.oldestUnrepairedTombstone())), cfs); } catch (RuntimeException | Error e) { try { inputCollector.close(); } catch (Exception e1) { e.addSuppressed(e1); } throw e; } } /** * Creates a new {@code SSTableReadsListener} to update the SSTables read counts. * @return a new {@code SSTableReadsListener} to update the SSTables read counts. */ private static SSTableReadsListener newReadCountUpdater() { return new SSTableReadsListener() { @Override public void onScanningStarted(SSTableReader sstable) { sstable.incrementReadCount(); } }; } private UnfilteredPartitionIterator checkCacheFilter(UnfilteredPartitionIterator iter, final ColumnFamilyStore cfs) { class CacheFilter extends Transformation<BaseRowIterator<?>> { @Override public BaseRowIterator<?> applyToPartition(BaseRowIterator<?> iter) { // Note that we rely on the fact that until we actually advance 'iter', no really costly operation is actually done // (except for reading the partition key from the index file) due to the call to mergeLazily in queryStorage. DecoratedKey dk = iter.partitionKey(); // Check if this partition is in the rowCache and if it is, if it covers our filter CachedPartition cached = cfs.getRawCachedPartition(dk); ClusteringIndexFilter filter = dataRange().clusteringIndexFilter(dk); if (cached != null && cfs.isFilterFullyCoveredBy(filter, limits(), cached, nowInSec(), iter.metadata().enforceStrictLiveness())) { // We won't use 'iter' so close it now. iter.close(); return filter.getUnfilteredRowIterator(columnFilter(), cached); } return iter; } } return Transformation.apply(iter, new CacheFilter()); } @Override public Verb verb() { return Verb.RANGE_REQ; } protected void appendCQLWhereClause(StringBuilder sb) { String filterString = dataRange().toCQLString(metadata(), rowFilter()); if (!filterString.isEmpty()) sb.append(" WHERE ").append(filterString); } @Override public String loggableTokens() { return "token range: " + (dataRange.keyRange.inclusiveLeft() ? '[' : '(') + dataRange.keyRange.left.getToken().toString() + ", " + dataRange.keyRange.right.getToken().toString() + (dataRange.keyRange.inclusiveRight() ? ']' : ')'); } /** * Allow to post-process the result of the query after it has been reconciled on the coordinator * but before it is passed to the CQL layer to return the ResultSet. * * See CASSANDRA-8717 for why this exists. */ public PartitionIterator postReconciliationProcessing(PartitionIterator result) { ColumnFamilyStore cfs = Keyspace.open(metadata().keyspace).getColumnFamilyStore(metadata().name); Index index = getIndex(cfs); return index == null ? result : index.postProcessorFor(this).apply(result, this); } @Override public String toString() { return String.format("Read(%s columns=%s rowfilter=%s limits=%s %s)", metadata().toString(), columnFilter(), rowFilter(), limits(), dataRange().toString(metadata())); } protected void serializeSelection(DataOutputPlus out, int version) throws IOException { DataRange.serializer.serialize(dataRange(), out, version, metadata()); } protected long selectionSerializedSize(int version) { return DataRange.serializer.serializedSize(dataRange(), version, metadata()); } /* * We are currently using PartitionRangeReadCommand for most index queries, even if they are explicitly restricted * to a single partition key. Return true if that is the case. * * See CASSANDRA-11617 and CASSANDRA-11872 for details. */ public boolean isLimitedToOnePartition() { return dataRange.keyRange instanceof Bounds && dataRange.startKey().kind() == PartitionPosition.Kind.ROW_KEY && dataRange.startKey().equals(dataRange.stopKey()); } public boolean isRangeRequest() { return true; } private static class Deserializer extends SelectionDeserializer { public ReadCommand deserialize(DataInputPlus in, int version, boolean isDigest, int digestVersion, boolean acceptsTransient, TableMetadata metadata, int nowInSec, ColumnFilter columnFilter, RowFilter rowFilter, DataLimits limits, IndexMetadata index) throws IOException { DataRange range = DataRange.serializer.deserialize(in, version, metadata); return new PartitionRangeReadCommand(isDigest, digestVersion, acceptsTransient, metadata, nowInSec, columnFilter, rowFilter, limits, range, index, false); } } }
/* * GeometryUtils.java * * Created on April 20, 2005, 5:51 PM */ package ika.utils; import java.awt.geom.*; import java.util.*; /** * A variety of utilities for computational geometry. * @author Bernhard Jenny, Institute of Cartography, ETH Zurich. */ public class GeometryUtils { /** * Square distance between a point and a line defined by two other points. * See http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html * @param x0 The point not on the line. * @param y0 The point not on the line. * @param x1 A point on the line. * @param y1 A point on the line. * @param x2 Another point on the line. * @param y2 Another point on the line. */ public static double pointLineDistanceSquare( double x0, double y0, double x1, double y1, double x2, double y2) { final double x2_x1 = x2 - x1; final double y2_y1 = y2 - y1; final double d = (x2_x1) * (y1 - y0) - (x1 - x0) * (y2_y1); final double denominator = x2_x1 * x2_x1 + y2_y1 * y2_y1; return d * d / denominator; } /** * Square distance between a point and a line defined by two other points. * See http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html * @param p0 The point not on the line. * @param p1 A point on the line. * @param p2 Another point on the line. */ public static double pointLineDistanceSquare(Point2D p0, Point2D p1, Point2D p2) { return pointLineDistanceSquare(p0.getX(), p0.getY(), p1.getX(), p1.getY(), p2.getX(), p2.getY()); } /** * Returns the distance of p3 to the segment defined by p1,p2. * http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/ * Wrapper function for distanceToSegment. * @param x3 * @param y3 * @param x1 * @param y1 * @param x2 * @param y2 * @return */ public static double distanceToSegment(double x3, double y3, double x1, double y1, double x2, double y2) { final Point2D p3 = new Point2D.Double(x3, y3); final Point2D p1 = new Point2D.Double(x1, y1); final Point2D p2 = new Point2D.Double(x2, y2); return distanceToSegment(p1, p2, p3); } /** * Returns the distance of p3 to the segment defined by p1,p2. * http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/ * @param p1 First point of the segment * @param p2 Second point of the segment * @param p3 Point to which we want to know the distance of the segment * defined by p1,p2 * @return The distance of p3 to the segment defined by p1,p2 */ public static double distanceToSegment(Point2D p1, Point2D p2, Point2D p3) { final double xDelta = p2.getX() - p1.getX(); final double yDelta = p2.getY() - p1.getY(); if ((xDelta == 0) && (yDelta == 0)) { throw new IllegalArgumentException("p1 and p2 cannot be the same point"); } final double u = ((p3.getX() - p1.getX()) * xDelta + (p3.getY() - p1.getY()) * yDelta) / (xDelta * xDelta + yDelta * yDelta); final Point2D closestPoint; if (u < 0) { closestPoint = p1; } else if (u > 1) { closestPoint = p2; } else { closestPoint = new Point2D.Double(p1.getX() + u * xDelta, p1.getY() + u * yDelta); } return closestPoint.distance(p3); } /** * Test if four points lay on one line. */ public static boolean isStraightLine(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, double straightLineTolerance) { // length of segment double len = Math.sqrt((x4 - x1) * (x4 - x1) + (y4 - y1) * (y4 - y1)); if (len == 0.) { return true; // avoid endless recursion } double e = straightLineTolerance * len; /* common part of area calculation */ double q = (x1 - x4) * (y1 + y4); /* twice the area between p1, p2, and p4 */ double f = (x2 - x1) * (y1 + y2) + (x4 - x2) * (y2 + y4) + q; /* distance from point p2 to line p0_p1 is area f devided by length of line p0_p1 */ /* instead of distance compare area */ if (Math.abs(f) < e) { /* same procedure with p3 */ f = (x3 - x1) * (y1 + y3) + (x4 - x3) * (y3 + y4) + q; if (Math.abs(f) < e) { return true; } } return false; } /** * Test if two rectangles intersect. <br> * This test differs from Rectangle2D.intersects()in that it returns also true * if one of the rectangles has an height or a width that equals 0. * @param r1 Rectangle 1 * @param r2 Rectangle 2. * @return true if the two rectangles intersect, false if the rectangles do * not intersect or if they are identical. */ public static boolean rectanglesIntersect(Rectangle2D r1, Rectangle2D r2) { if (r1 == null || r2 == null) { return false; } final double xmin1 = r1.getMinX(); final double xmax1 = r1.getMaxX(); final double xmin2 = r2.getMinX(); final double xmax2 = r2.getMaxX(); final double xmin = xmin1 > xmin2 ? xmin1 : xmin2; final double xmax = xmax1 < xmax2 ? xmax1 : xmax2; if (xmin > xmax) { return false; } final double ymin1 = r1.getMinY(); final double ymax1 = r1.getMaxY(); final double ymin2 = r2.getMinY(); final double ymax2 = r2.getMaxY(); // test if rectangles are identical if (ymin1 == ymin2 && xmin1 == xmin2) { return false; } final double ymin = ymin1 > ymin2 ? ymin1 : ymin2; final double ymax = ymax1 < ymax2 ? ymax1 : ymax2; return (ymin <= ymax); } /** * Tests if a line intersects with a rectangle. This method differs from * Rectangle2D in that it accepts empty rectangles, i.e. the passed * rectangle can have a height or a width of 0. Returns false if the * line lies completely within the rectangle. * @param x0 Start point of the line. Horizontal coordinate. * @param y0 Start point of the line. Vertical coordinate. * @param x1 End point of the line. Horizontal coordinate. * @param y1 End point of the line. Vertical coordinate. * @param r The rectangle to test. Can be empty, i.e. the height or width * can be 0. * @return True if the line intersects with any of the four border lines * of the rectangle, false otherwise. */ public static boolean lineIntersectsRectangle(double x0, double y0, double x1, double y1, Rectangle2D r) { // use the Rectangle2D.intersectsLine() method. boolean intersection = r.intersectsLine(x0, y0, x1, y1); if (intersection) { return true; } // Rectangle2D.intersectsLine returns false when the rectangle is empty, // i.e. its width or height is zero. if (r.isEmpty()) { final double minX = r.getMinX(); final double minY = r.getMinY(); final double maxX = r.getMaxX(); final double maxY = r.getMaxY(); // test for intersection with lower horizontal line if (linesIntersect(x0, y0, x1, y1, minX, minY, maxX, minY) > 0 // test for intersection with right vertical line || linesIntersect(x0, y0, x1, y1, maxX, minY, maxX, maxY) > 0 // test for intersection with upper horizontal line || linesIntersect(x0, y0, x1, y1, minX, maxY, maxX, maxY) > 0 // test for intersection with left vertical line || linesIntersect(x0, y0, x1, y1, minX, minY, minX, maxY) > 0) { return true; } } return false; } /** * Enlarges the passed rectangle by d in all directions. * @param rect The rectangle to enlarge. * @param d The enlargement to apply. */ public static void enlargeRectangle(Rectangle2D rect, double d) { if (rect == null) { throw new IllegalArgumentException(); } rect.setRect(rect.getX() - d, rect.getY() - d, rect.getWidth() + 2 * d, rect.getHeight() + 2 * d); } /** * Tests whether a passed rectangle has valid coordinates, i.e. x, y, width * and height are not NaN and not infinite. * @param rect The rectangle to test. Can be null. * @return True if the passed rectangle is valid, false otherwise. */ public static boolean isRectangleValid(Rectangle2D rect) { if (rect == null) { return false; } final double x = rect.getX(); final double y = rect.getY(); final double w = rect.getWidth(); final double h = rect.getHeight(); return !Double.isInfinite(x) && !Double.isNaN(x) && !Double.isInfinite(y) && !Double.isNaN(y) && !Double.isInfinite(w) && !Double.isNaN(w) && !Double.isInfinite(h) && !Double.isNaN(h); } public static double length(double x1, double y1, double x2, double y2) { final double dx1 = x1 - x2; final double dy1 = y1 - y2; return Math.sqrt(dx1 * dx1 + dy1 * dy1); } /** * Computes the angle between two straight lines defined by three points * Line 1: p1-p2 and line 2: p2-p3. * @return The angle between the two lines in radian between -pi and +pi. */ public static double angle(double x1, double y1, double x2, double y2, double x3, double y3) { final double dx1 = x1 - x2; final double dy1 = y1 - y2; final double dx2 = x3 - x2; final double dy2 = y3 - y2; final double ang1 = Math.atan2(dx1, dy1); final double ang2 = Math.atan2(dx2, dy2); final double angle = ang2 - ang1; return GeometryUtils.trimAngle(angle); } // returns +1 if > 0, -1 if < 0, 0 if == 0 private static int SIGNTEST(double a) { return ((a) > 0.) ? 1 : ((a) < 0.) ? -1 : 0; } /** * Check if two lines intersect. * Line definition : * Line 1 (x0,y0)-(x1,y1) * Line 2 (x2,y2)-(x3,y3) * The return values depend on the intersection type: * 0: no intersection * 1: legal intersection * 2: point on line * 3: point on point * 4: line on line * @param x0 Start point of line 1. Horizontal coordinate. * @param y0 Start point of line 1. Vertical coordinate. * @param x1 End point of line 1. Horizontal coordinate. * @param y1 End point of line 1. Vertical coordinate. * @param x2 Start point of line 2. Horizontal coordinate. * @param y2 Start point of line 2. Vertical coordinate. * @param x3 End point of line 2. Horizontal coordinate. * @param y4 End point of line 2. Vertical coordinate. * @return 0 if no intersection; 1 if intersection; 2 if point on line; * 3 if point on point; 4 if line on line. */ public static int linesIntersect(double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3) { int k03_01, k01_02, k20_23, k23_21; int pos, neg, nul; k03_01 = SIGNTEST((x3 - x0) * (y1 - y0) - (y3 - y0) * (x1 - x0)); k01_02 = SIGNTEST((x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)); k20_23 = SIGNTEST((x0 - x2) * (y3 - y2) - (y0 - y2) * (x3 - x2)); k23_21 = SIGNTEST((x3 - x2) * (y1 - y2) - (y3 - y2) * (x1 - x2)); pos = neg = nul = 0; if (k03_01 < 0) { neg++; } else if (k03_01 > 0) { pos++; } else { nul++; } if (k01_02 < 0) { neg++; } else if (k01_02 > 0) { pos++; } else { nul++; } if (k20_23 < 0) { neg++; } else if (k20_23 > 0) { pos++; } else { nul++; } if (k23_21 < 0) { neg++; } else if (k23_21 > 0) { pos++; } else { nul++; } if (nul == 0) { if (neg == 4 || pos == 4) { return 1; } // legal intersection else { return 0; } // no intersection } else { if (neg == 3 || pos == 3) { return 2; } // point on line else if (neg == 2 || pos == 2) { return 3; } // point on point else { return 4; } // line on line } } // see http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/ // If an intersection point exists, it returns the intersection point and // the parameter m of p = p1 + m(p2-p1) // if the two line segments touch on an end point, an intersection is returned. public static double[] intersectLineSegments(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { final double denominator = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (denominator == 0.d) { return null; // lines are parallel } final double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator; if (ua <= 0.d || ua >= 1.d) { return null; // no intersection } final double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator; if (ub <= 0.d || ub >= 1.d) { return null; // no intersection } return new double[]{x1 + ua * (x2 - x1), y1 + ua * (y2 - y1), ua}; } static private class DistComp implements java.util.Comparator { public int compare(Object obj1, Object obj2) { Double a = new Double(((double[]) obj1)[2]); Double b = new Double(((double[]) obj2)[2]); return a.compareTo(b); } } // returns a set of intersection points public static double[][] intersectLineSegmentWithPolygon(double x1, double y1, double x2, double y2, double[][] polygon) { java.util.List intersectionList = new java.util.LinkedList(); // intersect the line segment with each side of the polygon for (int i = 1; i < polygon.length; i++) { double[] intersection = GeometryUtils.intersectLineSegments( x1, y1, x2, y2, polygon[i - 1][0], polygon[i - 1][1], polygon[i][0], polygon[i][1]); if (intersection != null) { intersectionList.add(intersection); } } if (intersectionList.isEmpty()) { return null; } // order the intersection points by increasing distance from the start point java.util.Collections.sort(intersectionList, new DistComp()); // copy the coordinates of the intersection points double[][] intersections = new double[intersectionList.size()][2]; for (int i = 0; i < intersections.length; ++i) { final double[] inter = (double[]) intersectionList.get(i); intersections[i][0] = inter[0]; intersections[i][1] = inter[1]; } return intersections; } // see http://astronomy.swin.edu.au/~pbourke/geometry/insidepoly/ /* The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> (see URL below) with some minor modifications for speed. It returns 1 for strictly interior points, 0 for strictly exterior, and 0 or 1 for points on the boundary. The boundary behavior is complex but determined; in particular, for a partition of a region into polygons, each point is "in" exactly one polygon. (See p.243 of [O'Rourke (C)] for a discussion of boundary behavior.) */ public static boolean pointInPolygon(double[] point, double[][] polygon) { int i, j; boolean c = false; for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { if ((((polygon[i][1] <= point[1]) && (point[1] < polygon[j][1])) || ((polygon[j][1] <= point[1]) && (point[1] < polygon[i][1]))) && (point[0] < (polygon[j][0] - polygon[i][0]) * (point[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0])) { c = !c; } } return c; } /* Same as public static boolean pointInPolygon(double[] point, double[][] polygon) * but with x and y as doubles */ public static boolean pointInPolygon(double x, double y, double[][] polygon) { int i, j; boolean c = false; for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { if ((((polygon[i][1] <= y) && (y < polygon[j][1])) || ((polygon[j][1] <= y) && (y < polygon[i][1]))) && (x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0])) { c = !c; } } return c; } /* 0 : point outside polygon 1 : point inside polygon 2 : point on polygon border */ public static int pointInPolygonOrOnBoundary(double[] point, double[][] polygon) { int nbrOfPoints = polygon.length; if (nbrOfPoints < 3) { return 0; } // find bounding box double w = Double.MAX_VALUE; double e = Double.MIN_VALUE; double s = Double.MAX_VALUE; double n = Double.MIN_VALUE; for (int i = 0; i < nbrOfPoints; i++) { if (polygon[i][0] < w) { w = polygon[i][0]; } if (polygon[i][0] > e) { e = polygon[i][0]; } if (polygon[i][0] < s) { s = polygon[i][1]; } if (polygon[i][0] > n) { n = polygon[i][1]; } } // test against bounding box if (point[0] < w || point[0] > e || point[1] < s || point[1] > n) { return 0; } /* Even-odd rule: Draw a line from the passed point to a point outside the path. Count the number of path segments that the line crosses. If the result is odd, the point is inside the path. If the result is even, the point is outside the path. */ double outY = n + 1000.; int nbrIntersections = 0; int lastPointID = nbrOfPoints - 1; for (int i = 0; i < lastPointID; i++) { // test intersection with a vertical line starting at the point to test int intersection = GeometryUtils.linesIntersect( point[0], point[1], point[0], outY, polygon[i][0], polygon[i][1], polygon[i + 1][0], polygon[i + 1][1]); /* GeometryUtils.linesIntersect may return the following values: 0 : no intersection 1 : legal intersection 2 : point on line 3 : point on point 4 : line on line */ if (intersection > 1) { return 2; // the point to test is laying on a line: return true } if (intersection == 1) { nbrIntersections++; // found a normal intersection } } return nbrIntersections % 2; } public static Vector clipPolylineWithPolygon(double[][] polyline, double[][] polygon) { // make sure the polygon is closed if (polygon[0][0] != polygon[polygon.length - 1][0] || polygon[0][1] != polygon[polygon.length - 1][1]) { throw new IllegalArgumentException("polygon not closed"); } // the polyline with additional intersection points Vector points = new Vector(); // add start point of polyline points.add(polyline[0]); // get all intersection points for (int i = 1; i < polyline.length; ++i) { double[][] intersections = GeometryUtils.intersectLineSegmentWithPolygon( polyline[i - 1][0], polyline[i - 1][1], polyline[i][0], polyline[i][1], polygon); // add intersection points if (intersections != null) { for (int j = 0; j < intersections.length; ++j) { points.add(intersections[j]); } } // add end point of line segment points.add(polyline[i]); } // return the lines in this vector Vector lines = new Vector(); // store each line in a new vector Vector line = new Vector(); // counter for all points int ptID = 0; // remember whether the last point was added to the line boolean addedLastPoint = false; // loop over all lines while (ptID < points.size() - 1) { // compute the middle point for each line segment final double[] pt1 = (double[]) points.get(ptID); final double[] pt2 = (double[]) points.get(ptID + 1); final double x = (pt1[0] + pt2[0]) / 2.d; final double y = (pt1[1] + pt2[1]) / 2.d; // test if the middle point is inside the polygon // the middle point is never on the border of the polygon, so no // special treatement for this case is needed. final boolean in = GeometryUtils.pointInPolygon(new double[]{x, y}, polygon); // the middle point is inside the polygon, so add the start point of // the current segment to the line if (in) { line.add(points.get(ptID)); addedLastPoint = true; } // the middle point is outside the polygon. Check if the start point // of the current line segment has to be added anyway. This is the // case when this is the first line segment outside the polygon. else if (addedLastPoint) { line.add(points.get(ptID)); // store the old line and create a new one if (line.size() > 1) { lines.add(line); } line = new Vector(); addedLastPoint = false; } ptID++; } // the last line segment needs special treatment if (addedLastPoint) { line.add(points.get(points.size() - 1)); } if (line.size() > 1) { lines.add(line); } // convert the Vectors to arrays for (int i = 0; i < lines.size(); i++) { Vector l = (Vector) lines.get(i); // only treat lines with 2 or more points (just to be sure) if (l.size() < 2) { continue; } double[][] a = new double[l.size()][2]; for (int j = 0; j < a.length; ++j) { a[j] = (double[]) l.get(j); } lines.set(i, a); } return lines; } /** Compute the difference between two angles. * The resulting angle is in the range of -pi..+pi if the input angle are * also in this range. */ public static float angleDif(float a1, float a2) { double val = a1 - a2; if (val > Math.PI) { val -= 2. * Math.PI; } if (val < -Math.PI) { val += 2. * Math.PI; } return (float) val; } /** Compute the difference between two angles. * The resulting angle is in the range of -pi..+pi if the input angle are * also in this range. */ public static double angleDif(double a1, double a2) { double val = a1 - a2; if (val > Math.PI) { val -= 2. * Math.PI; } if (val < -Math.PI) { val += 2. * Math.PI; } return val; } /** Sum of two angles. * The resulting angle is in the range of -pi..+pi if the input angle are * also in this range. */ public static float angleSum(float a1, float a2) { double val = a1 + a2; if (val > Math.PI) { val -= 2. * Math.PI; } if (val < -Math.PI) { val += 2. * Math.PI; } return (float) val; } public static double trimAngle(double angle) { if (angle > Math.PI) { return angle - 2. * Math.PI; } if (angle < -Math.PI) { return angle + 2. * Math.PI; } return angle; } }
/* * Copyright (C) 2007 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.android.dexgen.dex.file; import com.android.dexgen.dex.code.CatchTable; import com.android.dexgen.dex.code.CstInsn; import com.android.dexgen.dex.code.DalvCode; import com.android.dexgen.dex.code.DalvInsn; import com.android.dexgen.dex.code.DalvInsnList; import com.android.dexgen.dex.code.LocalList; import com.android.dexgen.dex.code.PositionList; import com.android.dexgen.rop.cst.Constant; import com.android.dexgen.rop.cst.CstMemberRef; import com.android.dexgen.rop.cst.CstMethodRef; import com.android.dexgen.rop.cst.CstType; import com.android.dexgen.rop.type.StdTypeList; import com.android.dexgen.rop.type.Type; import com.android.dexgen.rop.type.TypeList; import com.android.dexgen.util.AnnotatedOutput; import com.android.dexgen.util.ExceptionWithContext; import com.android.dexgen.util.Hex; import java.io.PrintWriter; import java.util.HashSet; /** * Representation of all the parts needed for concrete methods in a * {@code dex} file. */ public final class CodeItem extends OffsettedItem { /** file alignment of this class, in bytes */ private static final int ALIGNMENT = 4; /** write size of the header of this class, in bytes */ private static final int HEADER_SIZE = 16; /** {@code non-null;} method that this code implements */ private final CstMethodRef ref; /** {@code non-null;} the bytecode instructions and associated data */ private final DalvCode code; /** {@code null-ok;} the catches, if needed; set in {@link #addContents} */ private CatchStructs catches; /** whether this instance is for a {@code static} method */ private final boolean isStatic; /** * {@code non-null;} list of possibly-thrown exceptions; just used in * generating debugging output (listings) */ private final TypeList throwsList; /** * {@code null-ok;} the debug info or {@code null} if there is none; * set in {@link #addContents} */ private DebugInfoItem debugInfo; /** * Constructs an instance. * * @param ref {@code non-null;} method that this code implements * @param code {@code non-null;} the underlying code * @param isStatic whether this instance is for a {@code static} * method * @param throwsList {@code non-null;} list of possibly-thrown exceptions, * just used in generating debugging output (listings) */ public CodeItem(CstMethodRef ref, DalvCode code, boolean isStatic, TypeList throwsList) { super(ALIGNMENT, -1); if (ref == null) { throw new NullPointerException("ref == null"); } if (code == null) { throw new NullPointerException("code == null"); } if (throwsList == null) { throw new NullPointerException("throwsList == null"); } this.ref = ref; this.code = code; this.isStatic = isStatic; this.throwsList = throwsList; this.catches = null; this.debugInfo = null; } /** {@inheritDoc} */ @Override public ItemType itemType() { return ItemType.TYPE_CODE_ITEM; } /** {@inheritDoc} */ public void addContents(DexFile file) { MixedItemSection byteData = file.getByteData(); TypeIdsSection typeIds = file.getTypeIds(); if (code.hasPositions() || code.hasLocals()) { debugInfo = new DebugInfoItem(code, isStatic, ref); byteData.add(debugInfo); } if (code.hasAnyCatches()) { for (Type type : code.getCatchTypes()) { typeIds.intern(type); } catches = new CatchStructs(code); } for (Constant c : code.getInsnConstants()) { file.internIfAppropriate(c); } } /** {@inheritDoc} */ @Override public String toString() { return "CodeItem{" + toHuman() + "}"; } /** {@inheritDoc} */ @Override public String toHuman() { return ref.toHuman(); } /** * Gets the reference to the method this instance implements. * * @return {@code non-null;} the method reference */ public CstMethodRef getRef() { return ref; } /** * Does a human-friendly dump of this instance. * * @param out {@code non-null;} where to dump * @param prefix {@code non-null;} per-line prefix to use * @param verbose whether to be verbose with the output */ public void debugPrint(PrintWriter out, String prefix, boolean verbose) { out.println(ref.toHuman() + ":"); DalvInsnList insns = code.getInsns(); out.println("regs: " + Hex.u2(getRegistersSize()) + "; ins: " + Hex.u2(getInsSize()) + "; outs: " + Hex.u2(getOutsSize())); insns.debugPrint(out, prefix, verbose); String prefix2 = prefix + " "; if (catches != null) { out.print(prefix); out.println("catches"); catches.debugPrint(out, prefix2); } if (debugInfo != null) { out.print(prefix); out.println("debug info"); debugInfo.debugPrint(out, prefix2); } } /** {@inheritDoc} */ @Override protected void place0(Section addedTo, int offset) { final DexFile file = addedTo.getFile(); int catchesSize; /* * In order to get the catches and insns, all the code's * constants need to be assigned indices. */ code.assignIndices(new DalvCode.AssignIndicesCallback() { public int getIndex(Constant cst) { IndexedItem item = file.findItemOrNull(cst); if (item == null) { return -1; } return item.getIndex(); } }); if (catches != null) { catches.encode(file); catchesSize = catches.writeSize(); } else { catchesSize = 0; } /* * The write size includes the header, two bytes per code * unit, post-code padding if necessary, and however much * space the catches need. */ int insnsSize = code.getInsns().codeSize(); if ((insnsSize & 1) != 0) { insnsSize++; } setWriteSize(HEADER_SIZE + (insnsSize * 2) + catchesSize); } /** {@inheritDoc} */ @Override protected void writeTo0(DexFile file, AnnotatedOutput out) { boolean annotates = out.annotates(); int regSz = getRegistersSize(); int outsSz = getOutsSize(); int insSz = getInsSize(); int insnsSz = code.getInsns().codeSize(); boolean needPadding = (insnsSz & 1) != 0; int triesSz = (catches == null) ? 0 : catches.triesSize(); int debugOff = (debugInfo == null) ? 0 : debugInfo.getAbsoluteOffset(); if (annotates) { out.annotate(0, offsetString() + ' ' + ref.toHuman()); out.annotate(2, " registers_size: " + Hex.u2(regSz)); out.annotate(2, " ins_size: " + Hex.u2(insSz)); out.annotate(2, " outs_size: " + Hex.u2(outsSz)); out.annotate(2, " tries_size: " + Hex.u2(triesSz)); out.annotate(4, " debug_off: " + Hex.u4(debugOff)); out.annotate(4, " insns_size: " + Hex.u4(insnsSz)); // This isn't represented directly here, but it is useful to see. int size = throwsList.size(); if (size != 0) { out.annotate(0, " throws " + StdTypeList.toHuman(throwsList)); } } out.writeShort(regSz); out.writeShort(insSz); out.writeShort(outsSz); out.writeShort(triesSz); out.writeInt(debugOff); out.writeInt(insnsSz); writeCodes(file, out); if (catches != null) { if (needPadding) { if (annotates) { out.annotate(2, " padding: 0"); } out.writeShort(0); } catches.writeTo(file, out); } if (annotates) { /* * These are pointed at in the code header (above), but it's less * distracting to expand on them at the bottom of the code. */ if (debugInfo != null) { out.annotate(0, " debug info"); debugInfo.annotateTo(file, out, " "); } } } /** * Helper for {@link #writeTo0} which writes out the actual bytecode. * * @param file {@code non-null;} file we are part of * @param out {@code non-null;} where to write to */ private void writeCodes(DexFile file, AnnotatedOutput out) { DalvInsnList insns = code.getInsns(); try { insns.writeTo(out); } catch (RuntimeException ex) { throw ExceptionWithContext.withContext(ex, "...while writing " + "instructions for " + ref.toHuman()); } } /** * Get the in registers count. * * @return the count */ private int getInsSize() { return ref.getParameterWordCount(isStatic); } /** * Get the out registers count. * * @return the count */ private int getOutsSize() { return code.getInsns().getOutsSize(); } /** * Get the total registers count. * * @return the count */ private int getRegistersSize() { return code.getInsns().getRegistersSize(); } }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver12; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import com.google.common.collect.ImmutableSet; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFDescStatsReplyVer12 implements OFDescStatsReply { private static final Logger logger = LoggerFactory.getLogger(OFDescStatsReplyVer12.class); // version: 1.2 final static byte WIRE_VERSION = 3; final static int LENGTH = 1072; private final static long DEFAULT_XID = 0x0L; private final static Set<OFStatsReplyFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsReplyFlags>of(); private final static String DEFAULT_MFR_DESC = ""; private final static String DEFAULT_HW_DESC = ""; private final static String DEFAULT_SW_DESC = ""; private final static String DEFAULT_SERIAL_NUM = ""; private final static String DEFAULT_DP_DESC = ""; // OF message fields private final long xid; private final Set<OFStatsReplyFlags> flags; private final String mfrDesc; private final String hwDesc; private final String swDesc; private final String serialNum; private final String dpDesc; // // Immutable default instance final static OFDescStatsReplyVer12 DEFAULT = new OFDescStatsReplyVer12( DEFAULT_XID, DEFAULT_FLAGS, DEFAULT_MFR_DESC, DEFAULT_HW_DESC, DEFAULT_SW_DESC, DEFAULT_SERIAL_NUM, DEFAULT_DP_DESC ); // package private constructor - used by readers, builders, and factory OFDescStatsReplyVer12(long xid, Set<OFStatsReplyFlags> flags, String mfrDesc, String hwDesc, String swDesc, String serialNum, String dpDesc) { if(flags == null) { throw new NullPointerException("OFDescStatsReplyVer12: property flags cannot be null"); } if(mfrDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property mfrDesc cannot be null"); } if(hwDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property hwDesc cannot be null"); } if(swDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property swDesc cannot be null"); } if(serialNum == null) { throw new NullPointerException("OFDescStatsReplyVer12: property serialNum cannot be null"); } if(dpDesc == null) { throw new NullPointerException("OFDescStatsReplyVer12: property dpDesc cannot be null"); } this.xid = xid; this.flags = flags; this.mfrDesc = mfrDesc; this.hwDesc = hwDesc; this.swDesc = swDesc; this.serialNum = serialNum; this.dpDesc = dpDesc; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.STATS_REPLY; } @Override public long getXid() { return xid; } @Override public OFStatsType getStatsType() { return OFStatsType.DESC; } @Override public Set<OFStatsReplyFlags> getFlags() { return flags; } @Override public String getMfrDesc() { return mfrDesc; } @Override public String getHwDesc() { return hwDesc; } @Override public String getSwDesc() { return swDesc; } @Override public String getSerialNum() { return serialNum; } @Override public String getDpDesc() { return dpDesc; } public OFDescStatsReply.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFDescStatsReply.Builder { final OFDescStatsReplyVer12 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsReplyFlags> flags; private boolean mfrDescSet; private String mfrDesc; private boolean hwDescSet; private String hwDesc; private boolean swDescSet; private String swDesc; private boolean serialNumSet; private String serialNum; private boolean dpDescSet; private String dpDesc; BuilderWithParent(OFDescStatsReplyVer12 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.STATS_REPLY; } @Override public long getXid() { return xid; } @Override public OFDescStatsReply.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.DESC; } @Override public Set<OFStatsReplyFlags> getFlags() { return flags; } @Override public OFDescStatsReply.Builder setFlags(Set<OFStatsReplyFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } @Override public String getMfrDesc() { return mfrDesc; } @Override public OFDescStatsReply.Builder setMfrDesc(String mfrDesc) { this.mfrDesc = mfrDesc; this.mfrDescSet = true; return this; } @Override public String getHwDesc() { return hwDesc; } @Override public OFDescStatsReply.Builder setHwDesc(String hwDesc) { this.hwDesc = hwDesc; this.hwDescSet = true; return this; } @Override public String getSwDesc() { return swDesc; } @Override public OFDescStatsReply.Builder setSwDesc(String swDesc) { this.swDesc = swDesc; this.swDescSet = true; return this; } @Override public String getSerialNum() { return serialNum; } @Override public OFDescStatsReply.Builder setSerialNum(String serialNum) { this.serialNum = serialNum; this.serialNumSet = true; return this; } @Override public String getDpDesc() { return dpDesc; } @Override public OFDescStatsReply.Builder setDpDesc(String dpDesc) { this.dpDesc = dpDesc; this.dpDescSet = true; return this; } @Override public OFDescStatsReply build() { long xid = this.xidSet ? this.xid : parentMessage.xid; Set<OFStatsReplyFlags> flags = this.flagsSet ? this.flags : parentMessage.flags; if(flags == null) throw new NullPointerException("Property flags must not be null"); String mfrDesc = this.mfrDescSet ? this.mfrDesc : parentMessage.mfrDesc; if(mfrDesc == null) throw new NullPointerException("Property mfrDesc must not be null"); String hwDesc = this.hwDescSet ? this.hwDesc : parentMessage.hwDesc; if(hwDesc == null) throw new NullPointerException("Property hwDesc must not be null"); String swDesc = this.swDescSet ? this.swDesc : parentMessage.swDesc; if(swDesc == null) throw new NullPointerException("Property swDesc must not be null"); String serialNum = this.serialNumSet ? this.serialNum : parentMessage.serialNum; if(serialNum == null) throw new NullPointerException("Property serialNum must not be null"); String dpDesc = this.dpDescSet ? this.dpDesc : parentMessage.dpDesc; if(dpDesc == null) throw new NullPointerException("Property dpDesc must not be null"); // return new OFDescStatsReplyVer12( xid, flags, mfrDesc, hwDesc, swDesc, serialNum, dpDesc ); } } static class Builder implements OFDescStatsReply.Builder { // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsReplyFlags> flags; private boolean mfrDescSet; private String mfrDesc; private boolean hwDescSet; private String hwDesc; private boolean swDescSet; private String swDesc; private boolean serialNumSet; private String serialNum; private boolean dpDescSet; private String dpDesc; @Override public OFVersion getVersion() { return OFVersion.OF_12; } @Override public OFType getType() { return OFType.STATS_REPLY; } @Override public long getXid() { return xid; } @Override public OFDescStatsReply.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.DESC; } @Override public Set<OFStatsReplyFlags> getFlags() { return flags; } @Override public OFDescStatsReply.Builder setFlags(Set<OFStatsReplyFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } @Override public String getMfrDesc() { return mfrDesc; } @Override public OFDescStatsReply.Builder setMfrDesc(String mfrDesc) { this.mfrDesc = mfrDesc; this.mfrDescSet = true; return this; } @Override public String getHwDesc() { return hwDesc; } @Override public OFDescStatsReply.Builder setHwDesc(String hwDesc) { this.hwDesc = hwDesc; this.hwDescSet = true; return this; } @Override public String getSwDesc() { return swDesc; } @Override public OFDescStatsReply.Builder setSwDesc(String swDesc) { this.swDesc = swDesc; this.swDescSet = true; return this; } @Override public String getSerialNum() { return serialNum; } @Override public OFDescStatsReply.Builder setSerialNum(String serialNum) { this.serialNum = serialNum; this.serialNumSet = true; return this; } @Override public String getDpDesc() { return dpDesc; } @Override public OFDescStatsReply.Builder setDpDesc(String dpDesc) { this.dpDesc = dpDesc; this.dpDescSet = true; return this; } // @Override public OFDescStatsReply build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; Set<OFStatsReplyFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS; if(flags == null) throw new NullPointerException("Property flags must not be null"); String mfrDesc = this.mfrDescSet ? this.mfrDesc : DEFAULT_MFR_DESC; if(mfrDesc == null) throw new NullPointerException("Property mfrDesc must not be null"); String hwDesc = this.hwDescSet ? this.hwDesc : DEFAULT_HW_DESC; if(hwDesc == null) throw new NullPointerException("Property hwDesc must not be null"); String swDesc = this.swDescSet ? this.swDesc : DEFAULT_SW_DESC; if(swDesc == null) throw new NullPointerException("Property swDesc must not be null"); String serialNum = this.serialNumSet ? this.serialNum : DEFAULT_SERIAL_NUM; if(serialNum == null) throw new NullPointerException("Property serialNum must not be null"); String dpDesc = this.dpDescSet ? this.dpDesc : DEFAULT_DP_DESC; if(dpDesc == null) throw new NullPointerException("Property dpDesc must not be null"); return new OFDescStatsReplyVer12( xid, flags, mfrDesc, hwDesc, swDesc, serialNum, dpDesc ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFDescStatsReply> { @Override public OFDescStatsReply readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 3 byte version = bb.readByte(); if(version != (byte) 0x3) throw new OFParseError("Wrong version: Expected=OFVersion.OF_12(3), got="+version); // fixed value property type == 19 byte type = bb.readByte(); if(type != (byte) 0x13) throw new OFParseError("Wrong type: Expected=OFType.STATS_REPLY(19), got="+type); int length = U16.f(bb.readShort()); if(length != 1072) throw new OFParseError("Wrong length: Expected=1072(1072), got="+length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); // fixed value property statsType == 0 short statsType = bb.readShort(); if(statsType != (short) 0x0) throw new OFParseError("Wrong statsType: Expected=OFStatsType.DESC(0), got="+statsType); Set<OFStatsReplyFlags> flags = OFStatsReplyFlagsSerializerVer12.readFrom(bb); // pad: 4 bytes bb.skipBytes(4); String mfrDesc = ChannelUtils.readFixedLengthString(bb, 256); String hwDesc = ChannelUtils.readFixedLengthString(bb, 256); String swDesc = ChannelUtils.readFixedLengthString(bb, 256); String serialNum = ChannelUtils.readFixedLengthString(bb, 32); String dpDesc = ChannelUtils.readFixedLengthString(bb, 256); OFDescStatsReplyVer12 descStatsReplyVer12 = new OFDescStatsReplyVer12( xid, flags, mfrDesc, hwDesc, swDesc, serialNum, dpDesc ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", descStatsReplyVer12); return descStatsReplyVer12; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFDescStatsReplyVer12Funnel FUNNEL = new OFDescStatsReplyVer12Funnel(); static class OFDescStatsReplyVer12Funnel implements Funnel<OFDescStatsReplyVer12> { private static final long serialVersionUID = 1L; @Override public void funnel(OFDescStatsReplyVer12 message, PrimitiveSink sink) { // fixed value property version = 3 sink.putByte((byte) 0x3); // fixed value property type = 19 sink.putByte((byte) 0x13); // fixed value property length = 1072 sink.putShort((short) 0x430); sink.putLong(message.xid); // fixed value property statsType = 0 sink.putShort((short) 0x0); OFStatsReplyFlagsSerializerVer12.putTo(message.flags, sink); // skip pad (4 bytes) sink.putUnencodedChars(message.mfrDesc); sink.putUnencodedChars(message.hwDesc); sink.putUnencodedChars(message.swDesc); sink.putUnencodedChars(message.serialNum); sink.putUnencodedChars(message.dpDesc); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFDescStatsReplyVer12> { @Override public void write(ByteBuf bb, OFDescStatsReplyVer12 message) { // fixed value property version = 3 bb.writeByte((byte) 0x3); // fixed value property type = 19 bb.writeByte((byte) 0x13); // fixed value property length = 1072 bb.writeShort((short) 0x430); bb.writeInt(U32.t(message.xid)); // fixed value property statsType = 0 bb.writeShort((short) 0x0); OFStatsReplyFlagsSerializerVer12.writeTo(bb, message.flags); // pad: 4 bytes bb.writeZero(4); ChannelUtils.writeFixedLengthString(bb, message.mfrDesc, 256); ChannelUtils.writeFixedLengthString(bb, message.hwDesc, 256); ChannelUtils.writeFixedLengthString(bb, message.swDesc, 256); ChannelUtils.writeFixedLengthString(bb, message.serialNum, 32); ChannelUtils.writeFixedLengthString(bb, message.dpDesc, 256); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFDescStatsReplyVer12("); b.append("xid=").append(xid); b.append(", "); b.append("flags=").append(flags); b.append(", "); b.append("mfrDesc=").append(mfrDesc); b.append(", "); b.append("hwDesc=").append(hwDesc); b.append(", "); b.append("swDesc=").append(swDesc); b.append(", "); b.append("serialNum=").append(serialNum); b.append(", "); b.append("dpDesc=").append(dpDesc); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFDescStatsReplyVer12 other = (OFDescStatsReplyVer12) obj; if( xid != other.xid) return false; if (flags == null) { if (other.flags != null) return false; } else if (!flags.equals(other.flags)) return false; if (mfrDesc == null) { if (other.mfrDesc != null) return false; } else if (!mfrDesc.equals(other.mfrDesc)) return false; if (hwDesc == null) { if (other.hwDesc != null) return false; } else if (!hwDesc.equals(other.hwDesc)) return false; if (swDesc == null) { if (other.swDesc != null) return false; } else if (!swDesc.equals(other.swDesc)) return false; if (serialNum == null) { if (other.serialNum != null) return false; } else if (!serialNum.equals(other.serialNum)) return false; if (dpDesc == null) { if (other.dpDesc != null) return false; } else if (!dpDesc.equals(other.dpDesc)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * result + ((flags == null) ? 0 : flags.hashCode()); result = prime * result + ((mfrDesc == null) ? 0 : mfrDesc.hashCode()); result = prime * result + ((hwDesc == null) ? 0 : hwDesc.hashCode()); result = prime * result + ((swDesc == null) ? 0 : swDesc.hashCode()); result = prime * result + ((serialNum == null) ? 0 : serialNum.hashCode()); result = prime * result + ((dpDesc == null) ? 0 : dpDesc.hashCode()); return result; } }
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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 com.orientechnologies.common.console; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintStream; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.spi.ServiceRegistry; import com.orientechnologies.common.console.annotation.ConsoleCommand; import com.orientechnologies.common.console.annotation.ConsoleParameter; import com.orientechnologies.common.parser.OStringParser; import com.orientechnologies.common.util.OArrays; public class OConsoleApplication { protected enum RESULT { OK, ERROR, EXIT }; protected InputStream in = System.in; // System.in; protected PrintStream out = System.out; protected PrintStream err = System.err; protected String lineSeparator = "\n"; protected String commandSeparator = ";"; protected String wordSeparator = " "; protected String[] helpCommands = { "help", "?" }; protected String[] exitCommands = { "exit", "bye", "quit" }; protected Map<String, String> properties = new HashMap<String, String>(); // protected OConsoleReader reader = new TTYConsoleReader(); protected OConsoleReader reader = new DefaultConsoleReader(); protected boolean interactiveMode; protected String[] args; protected static final String COMMENT_PREFIX = "#"; public void setReader(OConsoleReader iReader) { this.reader = iReader; reader.setConsole(this); } public OConsoleApplication(String[] iArgs) { this.args = iArgs; } public int run() { interactiveMode = isInteractiveMode(args); onBefore(); int result = 0; if (interactiveMode) { // EXECUTE IN INTERACTIVE MODE // final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String consoleInput; while (true) { out.println(); out.print("orientdb> "); consoleInput = reader.readLine(); if (consoleInput == null || consoleInput.length() == 0) continue; if (!executeCommands(new Scanner(consoleInput), false)) break; } } else { // EXECUTE IN BATCH MODE result = executeBatch(getCommandLine(args)) ? 0 : 1; } onAfter(); return result; } protected boolean isInteractiveMode(String[] args) { return args.length == 0; } protected boolean executeBatch(final String commandLine) { final File commandFile = new File(commandLine); Scanner scanner = null; try { scanner = new Scanner(commandFile); } catch (FileNotFoundException e) { scanner = new Scanner(commandLine); } return executeCommands(scanner, true); } protected boolean executeCommands(final Scanner iScanner, final boolean iExitOnException) { final StringBuilder commandBuffer = new StringBuilder(); try { String commandLine = null; iScanner.useDelimiter(commandSeparator); while (iScanner.hasNext()) { commandLine = iScanner.next().trim(); if (commandLine.startsWith("--") || commandLine.startsWith("//")) // SKIP COMMENTS continue; // JS CASE: MANAGE ENSEMBLING ALL TOGETHER if (commandLine.startsWith("js")) { // BEGIN: START TO COLLECT commandBuffer.append(commandLine); commandLine = null; } else if (commandLine.startsWith("end") && commandBuffer.length() > 0) { // END: FLUSH IT commandLine = commandBuffer.toString(); commandBuffer.setLength(0); } else if (commandBuffer.length() > 0) { // BUFFER IT commandBuffer.append(';'); commandBuffer.append(commandLine); commandLine = null; } if (commandLine != null) { final RESULT status = execute(commandLine); commandLine = null; if (status == RESULT.EXIT || status == RESULT.ERROR && iExitOnException) return false; } } if (commandBuffer.length() > 0) { final RESULT status = execute(commandBuffer.toString()); if (status == RESULT.EXIT || status == RESULT.ERROR && iExitOnException) return false; } } finally { iScanner.close(); } return true; } protected RESULT execute(String iCommand) { iCommand = iCommand.trim(); if (iCommand.length() == 0) // NULL LINE: JUMP IT return RESULT.OK; if (iCommand.startsWith(COMMENT_PREFIX)) // COMMENT: JUMP IT return RESULT.OK; String[] commandWords = OStringParser.getWords(iCommand, wordSeparator); for (String cmd : helpCommands) if (cmd.equals(commandWords[0])) { help(); return RESULT.OK; } for (String cmd : exitCommands) if (cmd.equals(commandWords[0])) { return RESULT.EXIT; } Method lastMethodInvoked = null; final StringBuilder lastCommandInvoked = new StringBuilder(); final String commandLowerCase = iCommand.toLowerCase(); for (Entry<Method, Object> entry : getConsoleMethods().entrySet()) { final Method m = entry.getKey(); final String methodName = m.getName(); final ConsoleCommand ann = m.getAnnotation(ConsoleCommand.class); final StringBuilder commandName = new StringBuilder(); char ch; int commandWordCount = 1; for (int i = 0; i < methodName.length(); ++i) { ch = methodName.charAt(i); if (Character.isUpperCase(ch)) { commandName.append(" "); ch = Character.toLowerCase(ch); commandWordCount++; } commandName.append(ch); } if (!commandLowerCase.equals(commandName.toString()) && !commandLowerCase.startsWith(commandName.toString() + " ")) { if (ann == null) continue; String[] aliases = ann.aliases(); if (aliases == null || aliases.length == 0) continue; boolean aliasMatch = false; for (String alias : aliases) { if (iCommand.startsWith(alias.split(" ")[0])) { aliasMatch = true; commandWordCount = 1; break; } } if (!aliasMatch) continue; } Object[] methodArgs; // BUILD PARAMETERS if (ann != null && !ann.splitInWords()) { methodArgs = new String[] { iCommand.substring(iCommand.indexOf(' ') + 1) }; } else { if (m.getParameterTypes().length > commandWords.length - commandWordCount) { // METHOD PARAMS AND USED PARAMS MISMATCH: CHECK FOR OPTIONALS for (int paramNum = m.getParameterAnnotations().length - 1; paramNum > -1; paramNum--) { final Annotation[] paramAnn = m.getParameterAnnotations()[paramNum]; if (paramAnn != null) for (int annNum = paramAnn.length - 1; annNum > -1; annNum--) { if (paramAnn[annNum] instanceof ConsoleParameter) { final ConsoleParameter annotation = (ConsoleParameter) paramAnn[annNum]; if (annotation.optional()) commandWords = OArrays.copyOf(commandWords, commandWords.length + 1); break; } } } } methodArgs = OArrays.copyOfRange(commandWords, commandWordCount, commandWords.length); } try { m.invoke(entry.getValue(), methodArgs); } catch (IllegalArgumentException e) { lastMethodInvoked = m; // GET THE COMMAND NAME lastCommandInvoked.setLength(0); for (int i = 0; i < commandWordCount; ++i) { if (lastCommandInvoked.length() > 0) lastCommandInvoked.append(" "); lastCommandInvoked.append(commandWords[i]); } continue; } catch (Exception e) { // e.printStackTrace(); // err.println(); if (e.getCause() != null) onException(e.getCause()); else e.printStackTrace(); return RESULT.ERROR; } return RESULT.OK; } if (lastMethodInvoked != null) syntaxError(lastCommandInvoked.toString(), lastMethodInvoked); out.println("!Unrecognized command: '" + iCommand + "'"); return RESULT.ERROR; } protected void syntaxError(String iCommand, Method m) { out.print("!Wrong syntax. If you're using a file make sure all commands are delimited by ';'\n\r\n\r Expected: " + iCommand + " "); String paramName = null; String paramDescription = null; boolean paramOptional = false; StringBuilder buffer = new StringBuilder("\n\nWhere:\n\n"); for (Annotation[] annotations : m.getParameterAnnotations()) { for (Annotation ann : annotations) { if (ann instanceof com.orientechnologies.common.console.annotation.ConsoleParameter) { paramName = ((com.orientechnologies.common.console.annotation.ConsoleParameter) ann).name(); paramDescription = ((com.orientechnologies.common.console.annotation.ConsoleParameter) ann).description(); paramOptional = ((com.orientechnologies.common.console.annotation.ConsoleParameter) ann).optional(); break; } } if (paramName == null) paramName = "?"; if (paramOptional) out.print("[<" + paramName + ">] "); else out.print("<" + paramName + "> "); buffer.append("* "); buffer.append(String.format("%-15s", paramName)); if (paramDescription != null) buffer.append(String.format("%-15s", paramDescription)); buffer.append("\n"); } out.println(buffer); } /** * Returns a map of all console method and the object they can be called on. * * @return Map<Method,Object> */ protected Map<Method, Object> getConsoleMethods() { // search for declared command collections final Iterator<OConsoleCommandCollection> ite = ServiceRegistry.lookupProviders(OConsoleCommandCollection.class); final Collection<Object> candidates = new ArrayList<Object>(); candidates.add(this); while (ite.hasNext()) { try { // make a copy and set it's context final OConsoleCommandCollection cc = ite.next().getClass().newInstance(); cc.setContext(this); candidates.add(cc); } catch (InstantiationException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } catch (IllegalAccessException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } } final Map<Method, Object> consoleMethods = new TreeMap<Method, Object>(new Comparator<Method>() { public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); for (final Object candidate : candidates) { final Method[] methods = candidate.getClass().getMethods(); for (Method m : methods) { if (Modifier.isAbstract(m.getModifiers()) || Modifier.isStatic(m.getModifiers()) || !Modifier.isPublic(m.getModifiers())) { continue; } if (m.getReturnType() != Void.TYPE) { continue; } consoleMethods.put(m, candidate); } } return consoleMethods; } protected Map<String, Object> addCommand(Map<String, Object> commandsTree, String commandLine) { return commandsTree; } protected void help() { out.println(); out.println("AVAILABLE COMMANDS:"); out.println(); for (Method m : getConsoleMethods().keySet()) { com.orientechnologies.common.console.annotation.ConsoleCommand annotation = m .getAnnotation(com.orientechnologies.common.console.annotation.ConsoleCommand.class); if (annotation == null) continue; System.out.print(String.format("* %-70s%s\n", getCorrectMethodName(m), annotation.description())); } System.out.print(String.format("* %-70s%s\n", getClearName("help"), "Print this help")); System.out.print(String.format("* %-70s%s\n", getClearName("exit"), "Close the console")); } public static String getCorrectMethodName(Method m) { StringBuilder buffer = new StringBuilder(); buffer.append(getClearName(m.getName())); for (int i = 0; i < m.getParameterAnnotations().length; i++) { for (int j = 0; j < m.getParameterAnnotations()[i].length; j++) { if (m.getParameterAnnotations()[i][j] instanceof com.orientechnologies.common.console.annotation.ConsoleParameter) { buffer .append(" <" + ((com.orientechnologies.common.console.annotation.ConsoleParameter) m.getParameterAnnotations()[i][j]).name() + ">"); } } } return buffer.toString(); } public static String getClearName(String iJavaName) { StringBuilder buffer = new StringBuilder(); char c; if (iJavaName != null) { buffer.append(iJavaName.charAt(0)); for (int i = 1; i < iJavaName.length(); ++i) { c = iJavaName.charAt(i); if (Character.isUpperCase(c)) { buffer.append(' '); } buffer.append(Character.toLowerCase(c)); } } return buffer.toString(); } protected String getCommandLine(String[] iArguments) { StringBuilder command = new StringBuilder(); for (int i = 0; i < iArguments.length; ++i) { if (i > 0) command.append(" "); command.append(iArguments[i]); } return command.toString(); } protected void onBefore() { } protected void onAfter() { } protected void onException(Throwable throwable) { throwable.printStackTrace(); } }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.uimanager; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.graphics.Color; import android.util.DisplayMetrics; import android.view.Choreographer; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.react.ReactRootView; import com.facebook.react.animation.Animation; import com.facebook.react.animation.AnimationPropertyUpdater; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.SimpleArray; import com.facebook.react.bridge.SimpleMap; import com.facebook.react.views.text.ReactRawTextManager; import com.facebook.react.views.text.ReactTextShadowNode; import com.facebook.react.views.text.ReactTextViewManager; import com.facebook.react.views.view.ReactViewGroup; import com.facebook.react.views.view.ReactViewManager; import com.facebook.react.bridge.ReactTestHelper; import org.junit.Before; import org.junit.Rule; import org.junit.runner.RunWith; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for {@link UIManagerModule}. */ @PrepareForTest({Arguments.class, ReactChoreographer.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) public class UIManagerModuleTest { @Rule public PowerMockRule rule = new PowerMockRule(); private ReactApplicationContext mReactContext; private CatalystInstance mCatalystInstanceMock; private ArrayList<Choreographer.FrameCallback> mPendingChoreographerCallbacks; @Before public void setUp() { PowerMockito.mockStatic(Arguments.class, ReactChoreographer.class); ReactChoreographer choreographerMock = mock(ReactChoreographer.class); PowerMockito.when(Arguments.createArray()).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return new SimpleArray(); } }); PowerMockito.when(Arguments.createMap()).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return new SimpleMap(); } }); PowerMockito.when(ReactChoreographer.getInstance()).thenReturn(choreographerMock); mPendingChoreographerCallbacks = new ArrayList<>(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { mPendingChoreographerCallbacks .add((Choreographer.FrameCallback) invocation.getArguments()[1]); return null; } }).when(choreographerMock).postFrameCallback( any(ReactChoreographer.CallbackType.class), any(Choreographer.FrameCallback.class)); mCatalystInstanceMock = ReactTestHelper.createMockCatalystInstance(); mReactContext = new ReactApplicationContext(RuntimeEnvironment.application); mReactContext.initializeWithInstance(mCatalystInstanceMock); DisplayMetrics displayMetrics = mReactContext.getResources().getDisplayMetrics(); DisplayMetricsHolder.setWindowDisplayMetrics(displayMetrics); DisplayMetricsHolder.setScreenDisplayMetrics(displayMetrics); UIManagerModule uiManagerModuleMock = mock(UIManagerModule.class); when(mCatalystInstanceMock.getNativeModule(UIManagerModule.class)) .thenReturn(uiManagerModuleMock); } @Test public void testCreateSimpleHierarchy() { UIManagerModule uiManager = getUIManagerModule(); ViewGroup rootView = createSimpleTextHierarchy(uiManager, "Some text"); assertThat(rootView.getChildCount()).isEqualTo(1); View firstChild = rootView.getChildAt(0); assertThat(firstChild).isInstanceOf(TextView.class); assertThat(((TextView) firstChild).getText().toString()).isEqualTo("Some text"); } @Test public void testUpdateSimpleHierarchy() { UIManagerModule uiManager = getUIManagerModule(); ViewGroup rootView = createSimpleTextHierarchy(uiManager, "Some text"); TextView textView = (TextView) rootView.getChildAt(0); int rawTextTag = 3; uiManager.updateView( rawTextTag, ReactRawTextManager.REACT_CLASS, SimpleMap.of(ReactTextShadowNode.PROP_TEXT, "New text")); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(textView.getText().toString()).isEqualTo("New text"); } @Test public void testHierarchyWithView() { UIManagerModule uiManager = getUIManagerModule(); ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext()); int rootTag = uiManager.addMeasuredRootView(rootView); int viewTag = rootTag + 1; int subViewTag = viewTag + 1; uiManager.createView( viewTag, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( subViewTag, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.manageChildren( viewTag, null, null, SimpleArray.of(subViewTag), SimpleArray.of(0), null); uiManager.manageChildren( rootTag, null, null, SimpleArray.of(viewTag), SimpleArray.of(0), null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(rootView.getChildCount()).isEqualTo(1); ViewGroup child = (ViewGroup) rootView.getChildAt(0); assertThat(child.getChildCount()).isEqualTo(1); ViewGroup grandchild = (ViewGroup) child.getChildAt(0); assertThat(grandchild).isInstanceOf(ViewGroup.class); assertThat(grandchild.getChildCount()).isEqualTo(0); } @Test public void testMoveViews() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); View expectedViewAt0 = hierarchy.nativeRootView.getChildAt(1); View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(2); View expectedViewAt2 = hierarchy.nativeRootView.getChildAt(0); View expectedViewAt3 = hierarchy.nativeRootView.getChildAt(3); uiManager.manageChildren( hierarchy.rootView, SimpleArray.of(1, 0, 2), SimpleArray.of(0, 2, 1), null, null, null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertChildrenAreExactly( hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1, expectedViewAt2, expectedViewAt3); } @Test public void testDeleteViews() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); View expectedViewAt0 = hierarchy.nativeRootView.getChildAt(1); View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(2); uiManager.manageChildren( hierarchy.rootView, null, null, null, null, SimpleArray.of(0, 3)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertChildrenAreExactly( hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1); } @Test public void testMoveAndDeleteViews() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); View expectedViewAt0 = hierarchy.nativeRootView.getChildAt(0); View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(3); View expectedViewAt2 = hierarchy.nativeRootView.getChildAt(2); uiManager.manageChildren( hierarchy.rootView, SimpleArray.of(3), SimpleArray.of(1), null, null, SimpleArray.of(1)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertChildrenAreExactly( hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1, expectedViewAt2); } @Test(expected = IllegalViewOperationException.class) public void testMoveAndDeleteRemoveViewsDuplicateRemove() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); uiManager.manageChildren( hierarchy.rootView, SimpleArray.of(3), SimpleArray.of(1), null, null, SimpleArray.of(3)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); } @Test(expected = IllegalViewOperationException.class) public void testDuplicateRemove() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); uiManager.manageChildren( hierarchy.rootView, null, null, null, null, SimpleArray.of(3, 3)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); } @Test public void testMoveAndAddViews() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); int textViewTag = 1000; uiManager.createView( textViewTag, ReactTextViewManager.REACT_CLASS, hierarchy.rootView, SimpleMap.of("collapsable", false)); View expectedViewAt0 = hierarchy.nativeRootView.getChildAt(0); View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(3); View expectedViewAt3 = hierarchy.nativeRootView.getChildAt(1); View expectedViewAt4 = hierarchy.nativeRootView.getChildAt(2); uiManager.manageChildren( hierarchy.rootView, SimpleArray.of(1, 2, 3), SimpleArray.of(3, 4, 1), SimpleArray.of(textViewTag), SimpleArray.of(2), null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(hierarchy.nativeRootView.getChildCount()).isEqualTo(5); assertThat(hierarchy.nativeRootView.getChildAt(0)).isEqualTo(expectedViewAt0); assertThat(hierarchy.nativeRootView.getChildAt(1)).isEqualTo(expectedViewAt1); assertThat(hierarchy.nativeRootView.getChildAt(3)).isEqualTo(expectedViewAt3); assertThat(hierarchy.nativeRootView.getChildAt(4)).isEqualTo(expectedViewAt4); } @Test public void testMoveViewsWithChildren() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); View expectedViewAt0 = hierarchy.nativeRootView.getChildAt(0); View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(2); View expectedViewAt2 = hierarchy.nativeRootView.getChildAt(1); View expectedViewAt3 = hierarchy.nativeRootView.getChildAt(3); uiManager.manageChildren( hierarchy.rootView, SimpleArray.of(1, 2), SimpleArray.of(2, 1), null, null, null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertChildrenAreExactly( hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1, expectedViewAt2, expectedViewAt3); assertThat(((ViewGroup) hierarchy.nativeRootView.getChildAt(2)).getChildCount()).isEqualTo(2); } @Test public void testDeleteViewsWithChildren() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); View expectedViewAt0 = hierarchy.nativeRootView.getChildAt(0); View expectedViewAt1 = hierarchy.nativeRootView.getChildAt(2); View expectedViewAt2 = hierarchy.nativeRootView.getChildAt(3); uiManager.manageChildren( hierarchy.rootView, null, null, null, null, SimpleArray.of(1)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertChildrenAreExactly( hierarchy.nativeRootView, expectedViewAt0, expectedViewAt1, expectedViewAt2); } @Test public void testLayoutAppliedToNodes() throws Exception { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); int newViewTag = 10000; uiManager.createView( newViewTag, ReactViewManager.REACT_CLASS, hierarchy.rootView, SimpleMap .of("left", 10.0, "top", 20.0, "width", 30.0, "height", 40.0, "collapsable", false)); uiManager.manageChildren( hierarchy.rootView, null, null, SimpleArray.of(newViewTag), SimpleArray.of(4), null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); View newView = hierarchy.nativeRootView.getChildAt(4); assertThat(newView.getLeft()).isEqualTo(10); assertThat(newView.getTop()).isEqualTo(20); assertThat(newView.getWidth()).isEqualTo(30); assertThat(newView.getHeight()).isEqualTo(40); } /** * This is to make sure we execute enqueued operations in the order given by JS. */ @Test public void testAddUpdateRemoveInSingleBatch() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); int newViewTag = 10000; uiManager.createView( newViewTag, ReactViewManager.REACT_CLASS, hierarchy.rootView, SimpleMap.of("collapsable", false)); uiManager.manageChildren( hierarchy.rootView, null, null, SimpleArray.of(newViewTag), SimpleArray.of(4), null); uiManager.updateView( newViewTag, ReactViewManager.REACT_CLASS, SimpleMap.of("backgroundColor", Color.RED)); uiManager.manageChildren( hierarchy.rootView, null, null, null, null, SimpleArray.of(4)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(hierarchy.nativeRootView.getChildCount()).isEqualTo(4); } @Test public void testTagsAssignment() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); View view0 = hierarchy.nativeRootView.getChildAt(0); assertThat(view0.getId()).isEqualTo(hierarchy.view0); View viewWithChildren1 = hierarchy.nativeRootView.getChildAt(1); assertThat(viewWithChildren1.getId()).isEqualTo(hierarchy.viewWithChildren1); View childView0 = ((ViewGroup) viewWithChildren1).getChildAt(0); assertThat(childView0.getId()).isEqualTo(hierarchy.childView0); View childView1 = ((ViewGroup) viewWithChildren1).getChildAt(1); assertThat(childView1.getId()).isEqualTo(hierarchy.childView1); View view2 = hierarchy.nativeRootView.getChildAt(2); assertThat(view2.getId()).isEqualTo(hierarchy.view2); View view3 = hierarchy.nativeRootView.getChildAt(3); assertThat(view3.getId()).isEqualTo(hierarchy.view3); } @Test public void testLayoutPropertyUpdatingOnlyOnLayoutChange() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); // Update layout to some values, this way we can verify it hasn't been updated, because the // update process would normally reset it back to some non-negative value View view0 = hierarchy.nativeRootView.getChildAt(0); view0.layout(1, 2, 3, 4); // verify that X get updated when we update layout properties uiManager.updateView( hierarchy.view0, ReactViewManager.REACT_CLASS, SimpleMap.of("left", 10.0, "top", 20.0, "width", 30.0, "height", 40.0)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(view0.getLeft()).isGreaterThan(2); // verify that the layout doesn't get updated when we update style property not affecting the // position (e.g., background-color) view0.layout(1, 2, 3, 4); uiManager.updateView( hierarchy.view0, ReactViewManager.REACT_CLASS, SimpleMap.of("backgroundColor", Color.RED)); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(view0.getLeft()).isEqualTo(1); } private static class AnimationStub extends Animation { public AnimationStub(int animationID, AnimationPropertyUpdater propertyUpdater) { super(animationID, propertyUpdater); } @Override public void run() { } } @Test public void testAddAndRemoveAnimation() { UIManagerModule uiManagerModule = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManagerModule); AnimationPropertyUpdater mockPropertyUpdater = mock(AnimationPropertyUpdater.class); Animation mockAnimation = spy(new AnimationStub(1000, mockPropertyUpdater)); Callback callbackMock = mock(Callback.class); int rootTag = hierarchy.rootView; uiManagerModule.createView( hierarchy.rootView, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManagerModule.registerAnimation(mockAnimation); uiManagerModule.addAnimation(hierarchy.rootView, 1000, callbackMock); uiManagerModule.removeAnimation(hierarchy.rootView, 1000); uiManagerModule.onBatchComplete(); executePendingChoreographerCallbacks(); verify(callbackMock, times(1)).invoke(false); verify(mockAnimation).run(); verify(mockAnimation).cancel(); } /** * Makes sure replaceExistingNonRootView by replacing a view with a new view that has a background * color set. */ @Test public void testReplaceExistingNonRootView() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); int newViewTag = 1234; uiManager.createView( newViewTag, ReactViewManager.REACT_CLASS, hierarchy.rootView, SimpleMap.of("backgroundColor", Color.RED)); uiManager.replaceExistingNonRootView(hierarchy.view2, newViewTag); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(hierarchy.nativeRootView.getChildCount()).isEqualTo(4); assertThat(hierarchy.nativeRootView.getChildAt(2)).isInstanceOf(ReactViewGroup.class); ReactViewGroup view = (ReactViewGroup) hierarchy.nativeRootView.getChildAt(2); assertThat(view.getBackgroundColor()).isEqualTo(Color.RED); } /** * Verifies removeSubviewsFromContainerWithID works by adding subviews, removing them, and * checking that the final number of children is correct. */ @Test public void testRemoveSubviewsFromContainerWithID() { UIManagerModule uiManager = getUIManagerModule(); ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext()); int rootTag = uiManager.addMeasuredRootView(rootView); final int containerTag = rootTag + 1; final int containerSiblingTag = containerTag + 1; uiManager.createView( containerTag, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( containerSiblingTag, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); addChild(uiManager, rootTag, containerTag, 0); addChild(uiManager, rootTag, containerSiblingTag, 1); uiManager.createView( containerTag + 2, ReactTextViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( containerTag + 3, ReactTextViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); addChild(uiManager, containerTag, containerTag + 2, 0); addChild(uiManager, containerTag, containerTag + 3, 1); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(rootView.getChildCount()).isEqualTo(2); assertThat(((ViewGroup)rootView.getChildAt(0)).getChildCount()).isEqualTo(2); uiManager.removeSubviewsFromContainerWithID(containerTag); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); assertThat(rootView.getChildCount()).isEqualTo(2); assertThat(((ViewGroup)rootView.getChildAt(0)).getChildCount()).isEqualTo(0); } /** * Assuming no other views have been created, the root view will have tag 1, Text tag 2, and * RawText tag 3. */ private ViewGroup createSimpleTextHierarchy(UIManagerModule uiManager, String text) { ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext()); int rootTag = uiManager.addMeasuredRootView(rootView); int textTag = rootTag + 1; int rawTextTag = textTag + 1; uiManager.createView( textTag, ReactTextViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( rawTextTag, ReactRawTextManager.REACT_CLASS, rootTag, SimpleMap.of(ReactTextShadowNode.PROP_TEXT, text, "collapsable", false)); uiManager.manageChildren( textTag, null, null, SimpleArray.of(rawTextTag), SimpleArray.of(0), null); uiManager.manageChildren( rootTag, null, null, SimpleArray.of(textTag), SimpleArray.of(0), null); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); return rootView; } private TestMoveDeleteHierarchy createMoveDeleteHierarchy(UIManagerModule uiManager) { ReactRootView rootView = new ReactRootView(mReactContext); int rootTag = uiManager.addMeasuredRootView(rootView); TestMoveDeleteHierarchy hierarchy = new TestMoveDeleteHierarchy(rootView, rootTag); uiManager.createView( hierarchy.view0, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( hierarchy.viewWithChildren1, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( hierarchy.view2, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( hierarchy.view3, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( hierarchy.childView0, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); uiManager.createView( hierarchy.childView1, ReactViewManager.REACT_CLASS, rootTag, SimpleMap.of("collapsable", false)); addChild(uiManager, rootTag, hierarchy.view0, 0); addChild(uiManager, rootTag, hierarchy.viewWithChildren1, 1); addChild(uiManager, rootTag, hierarchy.view2, 2); addChild(uiManager, rootTag, hierarchy.view3, 3); addChild(uiManager, hierarchy.viewWithChildren1, hierarchy.childView0, 0); addChild(uiManager, hierarchy.viewWithChildren1, hierarchy.childView1, 1); uiManager.onBatchComplete(); executePendingChoreographerCallbacks(); return hierarchy; } private void addChild(UIManagerModule uiManager, int parentTag, int childTag, int index) { uiManager.manageChildren( parentTag, null, null, SimpleArray.of(childTag), SimpleArray.of(index), null); } private void assertChildrenAreExactly(ViewGroup parent, View... views) { assertThat(parent.getChildCount()).isEqualTo(views.length); for (int i = 0; i < views.length; i++) { assertThat(parent.getChildAt(i)) .describedAs("View at " + i) .isEqualTo(views[i]); } } /** * Holder for the tags that represent that represent views in the following hierarchy: * - View rootView * - View view0 * - View viewWithChildren1 * - View childView0 * - View childView1 * - View view2 * - View view3 * * This hierarchy is used to test move/delete functionality in manageChildren. */ private static class TestMoveDeleteHierarchy { public ReactRootView nativeRootView; public int rootView; public int view0; public int viewWithChildren1; public int view2; public int view3; public int childView0; public int childView1; public TestMoveDeleteHierarchy(ReactRootView nativeRootView, int rootViewTag) { this.nativeRootView = nativeRootView; rootView = rootViewTag; view0 = rootView + 1; viewWithChildren1 = rootView + 2; view2 = rootView + 3; view3 = rootView + 4; childView0 = rootView + 5; childView1 = rootView + 6; } } private void executePendingChoreographerCallbacks() { ArrayList<Choreographer.FrameCallback> callbacks = new ArrayList<>(mPendingChoreographerCallbacks); mPendingChoreographerCallbacks.clear(); for (Choreographer.FrameCallback frameCallback : callbacks) { frameCallback.doFrame(0); } } private UIManagerModule getUIManagerModule() { List<ViewManager> viewManagers = Arrays.<ViewManager>asList( new ReactViewManager(), new ReactTextViewManager(), new ReactRawTextManager()); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, new UIImplementation(mReactContext, viewManagers)); uiManagerModule.onHostResume(); return uiManagerModule; } }
/* * Author: Minho Kim (ISKU) * Date: August 8, 2018 * E-mail: minho.kim093@gmail.com * * https://github.com/ISKU/Algorithm * http://codeforces.com/problemset/problem/1017/A */ import java.util.*; import java.io.*; public class A { private static void solve() { int N = io.nextInt(); int[] scores = new int[N]; for (int i = 0; i < N; i++) for (int j = 0; j < 4; j++) scores[i] += io.nextInt(); TreeMap<Integer, Integer> map = new TreeMap<>(Collections.reverseOrder()); for (int score : scores) map.put(score, map.containsKey(score) ? map.get(score) + 1 : 1); int thomas = scores[0]; int rank = 1; for (int score : map.keySet()) { if (thomas == score) { io.print(rank); break; } rank += map.get(score); } } private static FastIO io; public static void main(String... args) { io = new FastIO(System.in, System.out); solve(); io.close(); } /** * https://github.com/ISKU/FastIO-Java * * @author Minho Kim <minho.kim093@gmail.com> */ private static class FastIO { public static final int DEFAULT_BUFFER_SIZE = 65536; public static final int DEFAULT_INTEGER_SIZE = 10; public static final int DEFAULT_LONG_SIZE = 19; public static final int DEFAULT_WORD_SIZE = 256; public static final int DEFAULT_LINE_SIZE = 1024; public static final int EOF = -1; private final InputStream in; private final OutputStream out; private byte[] inBuffer; private int nextIn, inLength; private byte[] outBuffer; private int nextOut; private char[] charBuffer; private byte[] byteBuffer; public FastIO(InputStream in, OutputStream out, int inBufferSize, int outBufferSize) { this.in = in; this.inBuffer = new byte[inBufferSize]; this.nextIn = 0; this.inLength = 0; this.out = out; this.outBuffer = new byte[outBufferSize]; this.nextOut = 0; this.charBuffer = new char[DEFAULT_LINE_SIZE]; this.byteBuffer = new byte[DEFAULT_LONG_SIZE]; } public FastIO(InputStream in, OutputStream out) { this(in, out, DEFAULT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE); } public FastIO(InputStream in, OutputStream out, int bufferSize) { this(in, out, bufferSize, bufferSize); } public char nextChar() { byte b; while (isSpace(b = read())) ; return (char) b; } public String next() { byte b; while (isSpace(b = read())) ; int pos = 0; do { charBuffer[pos++] = (char) b; } while (!isSpace(b = read())); return new String(charBuffer, 0, pos); } public String nextLine() { byte b; int pos = 0; while (!isLine(b = read())) charBuffer[pos++] = (char) b; return new String(charBuffer, 0, pos); } public int nextInt() { byte b; while (isSpace(b = read())) ; boolean negative = false; int result = b - '0'; if (b == '-') { negative = true; result = 0; } while (isDigit(b = read())) result = (result * 10) + (b - '0'); return negative ? -result : result; } public long nextLong() { byte b; while (isSpace(b = read())) ; boolean negative = false; long result = b - '0'; if (b == '-') { negative = true; result = 0; } while (isDigit(b = read())) result = (result * 10) + (b - '0'); return negative ? -result : result; } public float nextFloat() { byte b; while (isSpace(b = read())) ; int pos = 0; do { charBuffer[pos++] = (char) b; } while (!isSpace(b = read())); return Float.parseFloat(new String(charBuffer, 0, pos)); } public float nextFloat2() { byte b; while (isSpace(b = read())) ; boolean negative = false; float result = b - '0'; if (b == '-') { negative = true; result = 0; } while (isDigit(b = read())) result = (result * 10) + (b - '0'); float d = 1; if (b == '.') { while (isDigit(b = read())) result += (b - '0') / (d *= 10); } return negative ? -result : result; } public double nextDouble() { byte b; while (isSpace(b = read())) ; int pos = 0; do { charBuffer[pos++] = (char) b; } while (!isSpace(b = read())); return Double.parseDouble(new String(charBuffer, 0, pos)); } public double nextDouble2() { byte b; while (isSpace(b = read())) ; boolean negative = false; double result = b - '0'; if (b == '-') { negative = true; result = 0; } while (isDigit(b = read())) result = (result * 10) + (b - '0'); double d = 1; if (b == '.') { while (isDigit(b = read())) result += (b - '0') / (d *= 10); } return negative ? -result : result; } public char[] nextToCharArray() { byte b; while (isSpace(b = read())) ; int pos = 0; do { charBuffer[pos++] = (char) b; } while (!isSpace(b = read())); char[] array = new char[pos]; System.arraycopy(charBuffer, 0, array, 0, pos); return array; } public int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = nextInt(); return array; } public long[] nextLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) array[i] = nextLong(); return array; } public int[][] nextInt2DArray(int Y, int X) { int[][] array = new int[Y][X]; for (int y = 0; y < Y; y++) for (int x = 0; x < X; x++) array[y][x] = nextInt(); return array; } public void print(char c) { write((byte) c); } public void print(String s) { for (int i = 0; i < s.length(); i++) write((byte) s.charAt(i)); } public void print(int i) { if (i == 0) { write((byte) '0'); return; } if (i == Integer.MIN_VALUE) { write((byte) '-'); write((byte) '2'); write((byte) '1'); write((byte) '4'); write((byte) '7'); write((byte) '4'); write((byte) '8'); write((byte) '3'); write((byte) '6'); write((byte) '4'); write((byte) '8'); return; } if (i < 0) { write((byte) '-'); i = -i; } int pos = 0; while (i > 0) { byteBuffer[pos++] = (byte) ((i % 10) + '0'); i /= 10; } while (pos-- > 0) write(byteBuffer[pos]); } public void print(long l) { if (l == 0) { write((byte) '0'); return; } if (l == Long.MIN_VALUE) { write((byte) '-'); write((byte) '9'); write((byte) '2'); write((byte) '2'); write((byte) '3'); write((byte) '3'); write((byte) '7'); write((byte) '2'); write((byte) '0'); write((byte) '3'); write((byte) '6'); write((byte) '8'); write((byte) '5'); write((byte) '4'); write((byte) '7'); write((byte) '7'); write((byte) '5'); write((byte) '8'); write((byte) '0'); write((byte) '8'); return; } if (l < 0) { write((byte) '-'); l = -l; } int pos = 0; while (l > 0) { byteBuffer[pos++] = (byte) ((l % 10) + '0'); l /= 10; } while (pos-- > 0) write(byteBuffer[pos]); } public void print(float f) { String sf = Float.toString(f); for (int i = 0; i < sf.length(); i++) write((byte) sf.charAt(i)); } public void print(double d) { String sd = Double.toString(d); for (int i = 0; i < sd.length(); i++) write((byte) sd.charAt(i)); } public void printls(char c) { print(c); write((byte) ' '); } public void printls(String s) { print(s); write((byte) ' '); } public void printls(int i) { print(i); write((byte) ' '); } public void printls(long l) { print(l); write((byte) ' '); } public void printls(float f) { print(f); write((byte) ' '); } public void printls(double d) { print(d); write((byte) ' '); } public void println(char c) { print(c); write((byte) '\n'); } public void println(String s) { print(s); write((byte) '\n'); } public void println(int i) { print(i); write((byte) '\n'); } public void println(long l) { print(l); write((byte) '\n'); } public void println(float f) { print(f); write((byte) '\n'); } public void println(double d) { print(d); write((byte) '\n'); } public void printf(String format, Object... args) { String s = String.format(format, args); for (int i = 0; i < s.length(); i++) write((byte) s.charAt(i)); } public void fprint(char c) { print(c); flushBuffer(); } public void fprint(String s) { print(s); flushBuffer(); } public void fprint(int i) { print(i); flushBuffer(); } public void fprint(long l) { print(l); flushBuffer(); } public void fprint(float f) { print(f); flushBuffer(); } public void fprint(double d) { print(d); flushBuffer(); } public void fprintf(String format, Object... args) { printf(format, args); flushBuffer(); } private byte read() { if (nextIn >= inLength) { if ((inLength = fill()) == EOF) return EOF; nextIn = 0; } return inBuffer[nextIn++]; } private void write(byte b) { if (nextOut >= outBuffer.length) flushBuffer(); outBuffer[nextOut++] = b; } private int fill() { try { return in.read(inBuffer, 0, inBuffer.length); } catch (Exception e) { throw new RuntimeException(e); } } public void flush() { if (nextOut == 0) return; flushBuffer(); } private void flushBuffer() { try { out.write(outBuffer, 0, nextOut); } catch (Exception e) { throw new RuntimeException(e); } nextOut = 0; } public void close() { flush(); } private boolean isDigit(byte b) { return b >= '0' && b <= '9'; } private boolean isLine(byte b) { return b == '\n' || b == '\r' || b == EOF; } private boolean isSpace(byte b) { return b == ' ' || b == '\t' || b == '\n' || b == '\r' || b == '\f' || b == EOF; } } }
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.cx.v3beta1; import com.google.api.pathtemplate.PathTemplate; import com.google.api.resourcenames.ResourceName; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. @Generated("by gapic-generator-java") public class EnvironmentName implements ResourceName { private static final PathTemplate PROJECT_LOCATION_AGENT_ENVIRONMENT = PathTemplate.createWithoutUrlEncoding( "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}"); private volatile Map<String, String> fieldValuesMap; private final String project; private final String location; private final String agent; private final String environment; @Deprecated protected EnvironmentName() { project = null; location = null; agent = null; environment = null; } private EnvironmentName(Builder builder) { project = Preconditions.checkNotNull(builder.getProject()); location = Preconditions.checkNotNull(builder.getLocation()); agent = Preconditions.checkNotNull(builder.getAgent()); environment = Preconditions.checkNotNull(builder.getEnvironment()); } public String getProject() { return project; } public String getLocation() { return location; } public String getAgent() { return agent; } public String getEnvironment() { return environment; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } public static EnvironmentName of( String project, String location, String agent, String environment) { return newBuilder() .setProject(project) .setLocation(location) .setAgent(agent) .setEnvironment(environment) .build(); } public static String format(String project, String location, String agent, String environment) { return newBuilder() .setProject(project) .setLocation(location) .setAgent(agent) .setEnvironment(environment) .build() .toString(); } public static EnvironmentName parse(String formattedString) { if (formattedString.isEmpty()) { return null; } Map<String, String> matchMap = PROJECT_LOCATION_AGENT_ENVIRONMENT.validatedMatch( formattedString, "EnvironmentName.parse: formattedString not in valid format"); return of( matchMap.get("project"), matchMap.get("location"), matchMap.get("agent"), matchMap.get("environment")); } public static List<EnvironmentName> parseList(List<String> formattedStrings) { List<EnvironmentName> list = new ArrayList<>(formattedStrings.size()); for (String formattedString : formattedStrings) { list.add(parse(formattedString)); } return list; } public static List<String> toStringList(List<EnvironmentName> values) { List<String> list = new ArrayList<>(values.size()); for (EnvironmentName value : values) { if (value == null) { list.add(""); } else { list.add(value.toString()); } } return list; } public static boolean isParsableFrom(String formattedString) { return PROJECT_LOCATION_AGENT_ENVIRONMENT.matches(formattedString); } @Override public Map<String, String> getFieldValuesMap() { if (fieldValuesMap == null) { synchronized (this) { if (fieldValuesMap == null) { ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder(); if (project != null) { fieldMapBuilder.put("project", project); } if (location != null) { fieldMapBuilder.put("location", location); } if (agent != null) { fieldMapBuilder.put("agent", agent); } if (environment != null) { fieldMapBuilder.put("environment", environment); } fieldValuesMap = fieldMapBuilder.build(); } } } return fieldValuesMap; } public String getFieldValue(String fieldName) { return getFieldValuesMap().get(fieldName); } @Override public String toString() { return PROJECT_LOCATION_AGENT_ENVIRONMENT.instantiate( "project", project, "location", location, "agent", agent, "environment", environment); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o != null || getClass() == o.getClass()) { EnvironmentName that = ((EnvironmentName) o); return Objects.equals(this.project, that.project) && Objects.equals(this.location, that.location) && Objects.equals(this.agent, that.agent) && Objects.equals(this.environment, that.environment); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= Objects.hashCode(project); h *= 1000003; h ^= Objects.hashCode(location); h *= 1000003; h ^= Objects.hashCode(agent); h *= 1000003; h ^= Objects.hashCode(environment); return h; } /** * Builder for projects/{project}/locations/{location}/agents/{agent}/environments/{environment}. */ public static class Builder { private String project; private String location; private String agent; private String environment; protected Builder() {} public String getProject() { return project; } public String getLocation() { return location; } public String getAgent() { return agent; } public String getEnvironment() { return environment; } public Builder setProject(String project) { this.project = project; return this; } public Builder setLocation(String location) { this.location = location; return this; } public Builder setAgent(String agent) { this.agent = agent; return this; } public Builder setEnvironment(String environment) { this.environment = environment; return this; } private Builder(EnvironmentName environmentName) { this.project = environmentName.project; this.location = environmentName.location; this.agent = environmentName.agent; this.environment = environmentName.environment; } public EnvironmentName build() { return new EnvironmentName(this); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.springdata; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Optional; import java.util.TreeSet; import org.apache.ignite.springdata.misc.ApplicationConfiguration; import org.apache.ignite.springdata.misc.Person; import org.apache.ignite.springdata.misc.PersonRepository; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * */ public class IgniteSpringDataCrudSelfTest extends GridCommonAbstractTest { /** Repository. */ private static PersonRepository repo; /** Context. */ private static AnnotationConfigApplicationContext ctx; /** Number of entries to store */ private static int CACHE_SIZE = 1000; /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); ctx = new AnnotationConfigApplicationContext(); ctx.register(ApplicationConfiguration.class); ctx.refresh(); repo = ctx.getBean(PersonRepository.class); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); fillInRepository(); assertEquals(CACHE_SIZE, repo.count()); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { repo.deleteAll(); assertEquals(0, repo.count()); super.afterTest(); } /** * */ private void fillInRepository() { for (int i = 0; i < CACHE_SIZE - 5; i++) { repo.save(i, new Person("person" + Integer.toHexString(i), "lastName" + Integer.toHexString((i + 16) % 256))); } repo.save((int) repo.count(), new Person("uniquePerson", "uniqueLastName")); repo.save((int) repo.count(), new Person("nonUniquePerson", "nonUniqueLastName")); repo.save((int) repo.count(), new Person("nonUniquePerson", "nonUniqueLastName")); repo.save((int) repo.count(), new Person("nonUniquePerson", "nonUniqueLastName")); repo.save((int) repo.count(), new Person("nonUniquePerson", "nonUniqueLastName")); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { ctx.destroy(); } /** * */ @Test public void testPutGet() { Person person = new Person("some_name", "some_surname"); int id = CACHE_SIZE + 1; assertEquals(person, repo.save(id, person)); assertTrue(repo.existsById(id)); assertEquals(person, repo.findById(id).get()); try { repo.save(person); fail("Managed to save a Person without ID"); } catch (UnsupportedOperationException e) { //excepted } } /** * */ @Test public void testPutAllGetAll() { LinkedHashMap<Integer, Person> map = new LinkedHashMap<>(); for (int i = CACHE_SIZE; i < CACHE_SIZE + 50; i++) map.put(i, new Person("some_name" + i, "some_surname" + i)); Iterator<Person> persons = repo.save(map).iterator(); assertEquals(CACHE_SIZE + 50, repo.count()); Iterator<Person> origPersons = map.values().iterator(); while (persons.hasNext()) assertEquals(origPersons.next(), persons.next()); try { repo.saveAll(map.values()); fail("Managed to save a list of Persons with ids"); } catch (UnsupportedOperationException e) { //expected } persons = repo.findAllById(map.keySet()).iterator(); int counter = 0; while (persons.hasNext()) { persons.next(); counter++; } assertEquals(map.size(), counter); } /** * */ @Test public void testGetAll() { assertEquals(CACHE_SIZE, repo.count()); Iterator<Person> persons = repo.findAll().iterator(); int counter = 0; while (persons.hasNext()) { persons.next(); counter++; } assertEquals(repo.count(), counter); } /** * */ @Test public void testDelete() { assertEquals(CACHE_SIZE, repo.count()); repo.deleteById(0); assertEquals(CACHE_SIZE - 1, repo.count()); assertEquals(Optional.empty(),repo.findById(0)); try { repo.delete(new Person("", "")); fail("Managed to delete a Person without id"); } catch (UnsupportedOperationException e) { //expected } } /** * */ @Test public void testDeleteSet() { assertEquals(CACHE_SIZE, repo.count()); TreeSet<Integer> ids = new TreeSet<>(); for (int i = 0; i < CACHE_SIZE / 2; i++) ids.add(i); repo.deleteAllById(ids); assertEquals(CACHE_SIZE / 2, repo.count()); try { ArrayList<Person> persons = new ArrayList<>(); for (int i = 0; i < 3; i++) persons.add(new Person(String.valueOf(i), String.valueOf(i))); repo.deleteAll(persons); fail("Managed to delete Persons without ids"); } catch (UnsupportedOperationException e) { //expected } } /** * */ @Test public void testDeleteAll() { assertEquals(CACHE_SIZE, repo.count()); repo.deleteAll(); assertEquals(0, repo.count()); } /** * Delete existing record */ @Test public void testDeleteByFirstName() { assertEquals(repo.countByFirstNameLike("uniquePerson"), 1); long cnt = repo.deleteByFirstName("uniquePerson"); assertEquals(1, cnt); } /** * Delete NON existing record */ @Test public void testDeleteExpression() { long cnt = repo.deleteByFirstName("880"); assertEquals(0, cnt); } /** * Delete Multiple records due to where */ @Test public void testDeleteExpressionMultiple() { long count = repo.countByFirstName("nonUniquePerson"); long cnt = repo.deleteByFirstName("nonUniquePerson"); assertEquals(cnt, count); } /** * Remove should do the same than Delete */ @Test public void testRemoveExpression() { repo.removeByFirstName("person3f"); long count = repo.count(); assertEquals(CACHE_SIZE - 1, count); } /** * Delete unique record */ @Test public void testDeleteQuery() { repo.deleteBySecondNameQuery("uniqueLastName"); long countAfter = repo.count(); assertEquals(CACHE_SIZE - 1, countAfter); } /** * Try to delete with a wrong @Query */ @Test public void testWrongDeleteQuery() { long countBefore = repo.countByFirstNameLike("person3f"); try { repo.deleteWrongByFirstNameQuery("person3f"); } catch (Exception e) { //expected } long countAfter = repo.countByFirstNameLike("person3f"); assertEquals(countBefore, countAfter); } /** * Update with a @Query a record */ @Test public void testUpdateQuery() { final String newSecondName = "updatedUniqueSecondName"; int cnt = repo.setFixedSecondNameFor(newSecondName, "uniquePerson"); assertEquals(1, cnt); List<Person> person = repo.findByFirstName("uniquePerson"); assertEquals(person.get(0).getSecondName(), "updatedUniqueSecondName"); } /** * Update with a wrong @Query */ @Test public void testWrongUpdateQuery() { final String newSecondName = "updatedUniqueSecondName"; int rowsUpdated = 0; try { rowsUpdated = repo.setWrongFixedSecondName(newSecondName, "uniquePerson"); } catch (Exception e) { //expected } assertEquals(0, rowsUpdated); List<Person> person = repo.findByFirstName("uniquePerson"); assertEquals(person.get(0).getSecondName(), "uniqueLastName"); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iotwireless.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotwireless-2020-11-22/ListQueuedMessages" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListQueuedMessagesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * To retrieve the next set of results, the <code>nextToken</code> value from a previous response; otherwise * <b>null</b> to receive the first set of results. * </p> */ private String nextToken; /** * <p> * The messages in downlink queue. * </p> */ private java.util.List<DownlinkQueueMessage> downlinkQueueMessagesList; /** * <p> * To retrieve the next set of results, the <code>nextToken</code> value from a previous response; otherwise * <b>null</b> to receive the first set of results. * </p> * * @param nextToken * To retrieve the next set of results, the <code>nextToken</code> value from a previous response; otherwise * <b>null</b> to receive the first set of results. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * To retrieve the next set of results, the <code>nextToken</code> value from a previous response; otherwise * <b>null</b> to receive the first set of results. * </p> * * @return To retrieve the next set of results, the <code>nextToken</code> value from a previous response; otherwise * <b>null</b> to receive the first set of results. */ public String getNextToken() { return this.nextToken; } /** * <p> * To retrieve the next set of results, the <code>nextToken</code> value from a previous response; otherwise * <b>null</b> to receive the first set of results. * </p> * * @param nextToken * To retrieve the next set of results, the <code>nextToken</code> value from a previous response; otherwise * <b>null</b> to receive the first set of results. * @return Returns a reference to this object so that method calls can be chained together. */ public ListQueuedMessagesResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The messages in downlink queue. * </p> * * @return The messages in downlink queue. */ public java.util.List<DownlinkQueueMessage> getDownlinkQueueMessagesList() { return downlinkQueueMessagesList; } /** * <p> * The messages in downlink queue. * </p> * * @param downlinkQueueMessagesList * The messages in downlink queue. */ public void setDownlinkQueueMessagesList(java.util.Collection<DownlinkQueueMessage> downlinkQueueMessagesList) { if (downlinkQueueMessagesList == null) { this.downlinkQueueMessagesList = null; return; } this.downlinkQueueMessagesList = new java.util.ArrayList<DownlinkQueueMessage>(downlinkQueueMessagesList); } /** * <p> * The messages in downlink queue. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setDownlinkQueueMessagesList(java.util.Collection)} or * {@link #withDownlinkQueueMessagesList(java.util.Collection)} if you want to override the existing values. * </p> * * @param downlinkQueueMessagesList * The messages in downlink queue. * @return Returns a reference to this object so that method calls can be chained together. */ public ListQueuedMessagesResult withDownlinkQueueMessagesList(DownlinkQueueMessage... downlinkQueueMessagesList) { if (this.downlinkQueueMessagesList == null) { setDownlinkQueueMessagesList(new java.util.ArrayList<DownlinkQueueMessage>(downlinkQueueMessagesList.length)); } for (DownlinkQueueMessage ele : downlinkQueueMessagesList) { this.downlinkQueueMessagesList.add(ele); } return this; } /** * <p> * The messages in downlink queue. * </p> * * @param downlinkQueueMessagesList * The messages in downlink queue. * @return Returns a reference to this object so that method calls can be chained together. */ public ListQueuedMessagesResult withDownlinkQueueMessagesList(java.util.Collection<DownlinkQueueMessage> downlinkQueueMessagesList) { setDownlinkQueueMessagesList(downlinkQueueMessagesList); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getDownlinkQueueMessagesList() != null) sb.append("DownlinkQueueMessagesList: ").append(getDownlinkQueueMessagesList()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListQueuedMessagesResult == false) return false; ListQueuedMessagesResult other = (ListQueuedMessagesResult) obj; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getDownlinkQueueMessagesList() == null ^ this.getDownlinkQueueMessagesList() == null) return false; if (other.getDownlinkQueueMessagesList() != null && other.getDownlinkQueueMessagesList().equals(this.getDownlinkQueueMessagesList()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getDownlinkQueueMessagesList() == null) ? 0 : getDownlinkQueueMessagesList().hashCode()); return hashCode; } @Override public ListQueuedMessagesResult clone() { try { return (ListQueuedMessagesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
// The solution of the problem was written by Izaron // Date: 19:32:36 21 Aug 2016 // Execution time: 0.514 // Please do not copy-paste the solution. // Try to understand what is happening here and write your own. import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { FastScanner in; PrintWriter out; static final String FILE = ""; class Lca { int[] depth; int[] dfs_order; int cnt; int[] first; int[] minPos; int n; void dfs(List<Integer>[] tree, int u, int d) { depth[u] = d; dfs_order[cnt++] = u; for (int v : tree[u]) if (depth[v] == -1) { dfs(tree, v, d + 1); dfs_order[cnt++] = u; } } void buildTree(int node, int left, int right) { if (left == right) { minPos[node] = dfs_order[left]; return; } int mid = (left + right) >> 1; buildTree(2 * node + 1, left, mid); buildTree(2 * node + 2, mid + 1, right); minPos[node] = depth[minPos[2 * node + 1]] < depth[minPos[2 * node + 2]] ? minPos[2 * node + 1] : minPos[2 * node + 2]; } public Lca(List<Integer>[] tree, int root) { int nodes = tree.length; depth = new int[nodes]; Arrays.fill(depth, -1); n = 2 * nodes - 1; dfs_order = new int[n]; cnt = 0; dfs(tree, root, 0); minPos = new int[4 * n]; buildTree(0, 0, n - 1); first = new int[nodes]; Arrays.fill(first, -1); for (int i = 0; i < dfs_order.length; i++) if (first[dfs_order[i]] == -1) first[dfs_order[i]] = i; } public int lca(int a, int b) { return minPos(Math.min(first[a], first[b]), Math.max(first[a], first[b]), 0, 0, n - 1); } int minPos(int a, int b, int node, int left, int right) { if (a == left && right == b) return minPos[node]; int mid = (left + right) >> 1; if (a <= mid && b > mid) { int p1 = minPos(a, Math.min(b, mid), 2 * node + 1, left, mid); int p2 = minPos(Math.max(a, mid + 1), b, 2 * node + 2, mid + 1, right); return depth[p1] < depth[p2] ? p1 : p2; } else if (a <= mid) { return minPos(a, Math.min(b, mid), 2 * node + 1, left, mid); } else if (b > mid) { return minPos(Math.max(a, mid + 1), b, 2 * node + 2, mid + 1, right); } else { throw new RuntimeException(); } } } Map<Integer, Integer> map; int n; int get(int v) { if (v == -1) return -1; if (!map.containsKey(v)) map.put(v, map.size()); return map.get(v); } public void solve() { map = new TreeMap<>(); n = in.nextInt(); List<Integer>[] tree = new List[n]; for (int i = 0; i < n; i++) tree[i] = new ArrayList<>(); int root = -1; for (int i = 0; i < n; i++) { int a = get(in.nextInt()), b = get(in.nextInt()); if (b == -1) { root = a; } else { tree[a].add(b); tree[b].add(a); } } Lca lca = new Lca(tree, root); int m = in.nextInt(); for (int i = 0; i < m; i++) { int a = get(in.nextInt()), b = get(in.nextInt()); int parent = lca.lca(a, b); if (a == parent) out.println(1); else if (b == parent) out.println(2); else out.println(0); } } public void run() { if (FILE.equals("")) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { try { in = new FastScanner(new FileInputStream(FILE + ".in")); out = new PrintWriter(new FileOutputStream(FILE + ".out")); } catch (FileNotFoundException e) { e.printStackTrace(); } } solve(); out.close(); } public static void main(String[] args) { (new Main()).run(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public float nextFloat() { return Float.parseFloat(next()); } } class Pair<A extends Comparable<A>, B extends Comparable<B>> implements Comparable<Pair<A, B>> { public A a; public B b; public Pair(A a, B b) { this.a = a; this.b = b; } @Override public int compareTo(Pair<A, B> o) { if (o == null || o.getClass() != getClass()) return 1; int cmp = a.compareTo(o.a); if (cmp == 0) return b.compareTo(o.b); return cmp; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (a != null ? !a.equals(pair.a) : pair.a != null) return false; return !(b != null ? !b.equals(pair.b) : pair.b != null); } } class PairInt extends Pair<Integer, Integer> { public PairInt(Integer u, Integer v) { super(u, v); } } class PairLong extends Pair<Long, Long> { public PairLong(Long u, Long v) { super(u, v); } } }
// 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. package com.google.location.suplclient.asn1.supl2.lpp; // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // // import com.google.location.suplclient.asn1.base.Asn1BitString; import com.google.location.suplclient.asn1.base.Asn1Object; import com.google.location.suplclient.asn1.base.Asn1Sequence; import com.google.location.suplclient.asn1.base.Asn1Tag; import com.google.location.suplclient.asn1.base.BitStream; import com.google.location.suplclient.asn1.base.BitStreamReader; import com.google.location.suplclient.asn1.base.SequenceComponent; import com.google.common.collect.ImmutableList; import java.util.Collection; import javax.annotation.Nullable; /** * */ public class Sensor_ProvideCapabilities_r13 extends Asn1Sequence { // private static final Asn1Tag TAG_Sensor_ProvideCapabilities_r13 = Asn1Tag.fromClassAndNumber(-1, -1); public Sensor_ProvideCapabilities_r13() { super(); } @Override @Nullable protected Asn1Tag getTag() { return TAG_Sensor_ProvideCapabilities_r13; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_Sensor_ProvideCapabilities_r13 != null) { return ImmutableList.of(TAG_Sensor_ProvideCapabilities_r13); } else { return Asn1Sequence.getPossibleFirstTags(); } } /** * Creates a new Sensor_ProvideCapabilities_r13 from encoded stream. */ public static Sensor_ProvideCapabilities_r13 fromPerUnaligned(byte[] encodedBytes) { Sensor_ProvideCapabilities_r13 result = new Sensor_ProvideCapabilities_r13(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new Sensor_ProvideCapabilities_r13 from encoded stream. */ public static Sensor_ProvideCapabilities_r13 fromPerAligned(byte[] encodedBytes) { Sensor_ProvideCapabilities_r13 result = new Sensor_ProvideCapabilities_r13(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override protected boolean isExtensible() { return true; } @Override public boolean containsExtensionValues() { for (SequenceComponent extensionComponent : getExtensionComponents()) { if (extensionComponent.isExplicitlySet()) return true; } return false; } private Sensor_ProvideCapabilities_r13.sensor_Modes_r13Type sensor_Modes_r13_; public Sensor_ProvideCapabilities_r13.sensor_Modes_r13Type getSensor_Modes_r13() { return sensor_Modes_r13_; } /** * @throws ClassCastException if value is not a Sensor_ProvideCapabilities_r13.sensor_Modes_r13Type */ public void setSensor_Modes_r13(Asn1Object value) { this.sensor_Modes_r13_ = (Sensor_ProvideCapabilities_r13.sensor_Modes_r13Type) value; } public Sensor_ProvideCapabilities_r13.sensor_Modes_r13Type setSensor_Modes_r13ToNewInstance() { sensor_Modes_r13_ = new Sensor_ProvideCapabilities_r13.sensor_Modes_r13Type(); return sensor_Modes_r13_; } @Override public Iterable<? extends SequenceComponent> getComponents() { ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder(); builder.add(new SequenceComponent() { Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 0); @Override public boolean isExplicitlySet() { return getSensor_Modes_r13() != null; } @Override public boolean hasDefaultValue() { return false; } @Override public boolean isOptional() { return false; } @Override public Asn1Object getComponentValue() { return getSensor_Modes_r13(); } @Override public void setToNewInstance() { setSensor_Modes_r13ToNewInstance(); } @Override public Collection<Asn1Tag> getPossibleFirstTags() { return tag == null ? Sensor_ProvideCapabilities_r13.sensor_Modes_r13Type.getPossibleFirstTags() : ImmutableList.of(tag); } @Override public Asn1Tag getTag() { return tag; } @Override public boolean isImplicitTagging() { return true; } @Override public String toIndentedString(String indent) { return "sensor_Modes_r13 : " + getSensor_Modes_r13().toIndentedString(indent); } }); return builder.build(); } @Override public Iterable<? extends SequenceComponent> getExtensionComponents() { ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder(); return builder.build(); } // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // /** * */ public static class sensor_Modes_r13Type extends Asn1BitString { // // defined bit positions, if any public static final int standalone = 0; public static final int ue_assisted = 2; // setters public final void set_standalone() { ensureValuePopulated(); getValue().set(0); } public final void set_ue_assisted() { ensureValuePopulated(); getValue().set(2); } // clearers public final boolean get_standalone() { ensureValuePopulated(); return getValue().get(0); } public final boolean get_ue_assisted() { ensureValuePopulated(); return getValue().get(2); } private static final Asn1Tag TAG_sensor_Modes_r13Type = Asn1Tag.fromClassAndNumber(-1, -1); public sensor_Modes_r13Type() { super(); setMinSize(1); setMaxSize(8); } @Override @Nullable protected Asn1Tag getTag() { return TAG_sensor_Modes_r13Type; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_sensor_Modes_r13Type != null) { return ImmutableList.of(TAG_sensor_Modes_r13Type); } else { return Asn1BitString.getPossibleFirstTags(); } } /** * Creates a new sensor_Modes_r13Type from encoded stream. */ public static sensor_Modes_r13Type fromPerUnaligned(byte[] encodedBytes) { sensor_Modes_r13Type result = new sensor_Modes_r13Type(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new sensor_Modes_r13Type from encoded stream. */ public static sensor_Modes_r13Type fromPerAligned(byte[] encodedBytes) { sensor_Modes_r13Type result = new sensor_Modes_r13Type(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { return "sensor_Modes_r13Type = " + getValue() + ";\n"; } } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { StringBuilder builder = new StringBuilder(); builder.append("Sensor_ProvideCapabilities_r13 = {\n"); final String internalIndent = indent + " "; for (SequenceComponent component : getComponents()) { if (component.isExplicitlySet()) { builder.append(internalIndent) .append(component.toIndentedString(internalIndent)); } } if (isExtensible()) { builder.append(internalIndent).append("...\n"); for (SequenceComponent component : getExtensionComponents()) { if (component.isExplicitlySet()) { builder.append(internalIndent) .append(component.toIndentedString(internalIndent)); } } } builder.append(indent).append("};\n"); return builder.toString(); } }
// Copyright (C) 2013 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.google.gerrit.server.change; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.gerrit.common.ChangeHooks; import com.google.gerrit.common.TimeUtil; import com.google.gerrit.common.data.GroupDescription; import com.google.gerrit.common.errors.NoSuchGroupException; import com.google.gerrit.extensions.api.changes.AddReviewerInput; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.extensions.restapi.UnprocessableEntityException; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSetApproval; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.ApprovalsUtil; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.PatchSetUtil; import com.google.gerrit.server.account.AccountCache; import com.google.gerrit.server.account.AccountLoader; import com.google.gerrit.server.account.AccountsCollection; import com.google.gerrit.server.account.GroupMembers; import com.google.gerrit.server.change.ReviewerJson.PostResult; import com.google.gerrit.server.change.ReviewerJson.ReviewerInfo; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.git.BatchUpdate; import com.google.gerrit.server.git.BatchUpdate.ChangeContext; import com.google.gerrit.server.git.BatchUpdate.Context; import com.google.gerrit.server.git.UpdateException; import com.google.gerrit.server.group.GroupsCollection; import com.google.gerrit.server.group.SystemGroupBackend; import com.google.gerrit.server.mail.AddReviewerSender; import com.google.gerrit.server.project.ChangeControl; import com.google.gerrit.server.project.NoSuchProjectException; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import org.eclipse.jgit.lib.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.text.MessageFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @Singleton public class PostReviewers implements RestModifyView<ChangeResource, AddReviewerInput> { private static final Logger log = LoggerFactory .getLogger(PostReviewers.class); public static final int DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK = 10; public static final int DEFAULT_MAX_REVIEWERS = 20; private final AccountsCollection accounts; private final ReviewerResource.Factory reviewerFactory; private final ApprovalsUtil approvalsUtil; private final PatchSetUtil psUtil; private final AddReviewerSender.Factory addReviewerSenderFactory; private final GroupsCollection groupsCollection; private final GroupMembers.Factory groupMembersFactory; private final AccountLoader.Factory accountLoaderFactory; private final Provider<ReviewDb> dbProvider; private final BatchUpdate.Factory batchUpdateFactory; private final Provider<IdentifiedUser> user; private final IdentifiedUser.GenericFactory identifiedUserFactory; private final Config cfg; private final ChangeHooks hooks; private final AccountCache accountCache; private final ReviewerJson json; @Inject PostReviewers(AccountsCollection accounts, ReviewerResource.Factory reviewerFactory, ApprovalsUtil approvalsUtil, PatchSetUtil psUtil, AddReviewerSender.Factory addReviewerSenderFactory, GroupsCollection groupsCollection, GroupMembers.Factory groupMembersFactory, AccountLoader.Factory accountLoaderFactory, Provider<ReviewDb> db, BatchUpdate.Factory batchUpdateFactory, Provider<IdentifiedUser> user, IdentifiedUser.GenericFactory identifiedUserFactory, @GerritServerConfig Config cfg, ChangeHooks hooks, AccountCache accountCache, ReviewerJson json) { this.accounts = accounts; this.reviewerFactory = reviewerFactory; this.approvalsUtil = approvalsUtil; this.psUtil = psUtil; this.addReviewerSenderFactory = addReviewerSenderFactory; this.groupsCollection = groupsCollection; this.groupMembersFactory = groupMembersFactory; this.accountLoaderFactory = accountLoaderFactory; this.dbProvider = db; this.batchUpdateFactory = batchUpdateFactory; this.user = user; this.identifiedUserFactory = identifiedUserFactory; this.cfg = cfg; this.hooks = hooks; this.accountCache = accountCache; this.json = json; } @Override public PostResult apply(ChangeResource rsrc, AddReviewerInput input) throws UpdateException, OrmException, RestApiException, IOException { if (input.reviewer == null) { throw new BadRequestException("missing reviewer field"); } try { Account.Id accountId = accounts.parse(input.reviewer).getAccountId(); return putAccount(reviewerFactory.create(rsrc, accountId)); } catch (UnprocessableEntityException e) { try { return putGroup(rsrc, input); } catch (UnprocessableEntityException e2) { throw new UnprocessableEntityException(MessageFormat.format( ChangeMessages.get().reviewerNotFound, input.reviewer)); } } } private PostResult putAccount(ReviewerResource rsrc) throws OrmException, UpdateException, RestApiException { Account member = rsrc.getReviewerUser().getAccount(); ChangeControl control = rsrc.getReviewerControl(); PostResult result = new PostResult(); if (isValidReviewer(member, control)) { addReviewers(rsrc.getChangeResource(), result, ImmutableMap.of(member.getId(), control)); } return result; } private PostResult putGroup(ChangeResource rsrc, AddReviewerInput input) throws UpdateException, RestApiException, OrmException, IOException { GroupDescription.Basic group = groupsCollection.parseInternal(input.reviewer); PostResult result = new PostResult(); if (!isLegalReviewerGroup(group.getGroupUUID())) { result.error = MessageFormat.format( ChangeMessages.get().groupIsNotAllowed, group.getName()); return result; } Map<Account.Id, ChangeControl> reviewers = new HashMap<>(); ChangeControl control = rsrc.getControl(); Set<Account> members; try { members = groupMembersFactory.create(control.getUser()).listAccounts( group.getGroupUUID(), control.getProject().getNameKey()); } catch (NoSuchGroupException e) { throw new UnprocessableEntityException(e.getMessage()); } catch (NoSuchProjectException e) { throw new BadRequestException(e.getMessage()); } // if maxAllowed is set to 0, it is allowed to add any number of // reviewers int maxAllowed = cfg.getInt("addreviewer", "maxAllowed", DEFAULT_MAX_REVIEWERS); if (maxAllowed > 0 && members.size() > maxAllowed) { result.error = MessageFormat.format( ChangeMessages.get().groupHasTooManyMembers, group.getName()); return result; } // if maxWithoutCheck is set to 0, we never ask for confirmation int maxWithoutConfirmation = cfg.getInt("addreviewer", "maxWithoutConfirmation", DEFAULT_MAX_REVIEWERS_WITHOUT_CHECK); if (!input.confirmed() && maxWithoutConfirmation > 0 && members.size() > maxWithoutConfirmation) { result.confirm = true; result.error = MessageFormat.format( ChangeMessages.get().groupManyMembersConfirmation, group.getName(), members.size()); return result; } for (Account member : members) { if (isValidReviewer(member, control)) { reviewers.put(member.getId(), control); } } addReviewers(rsrc, result, reviewers); return result; } private boolean isValidReviewer(Account member, ChangeControl control) { if (member.isActive()) { IdentifiedUser user = identifiedUserFactory.create(member.getId()); // Does not account for draft status as a user might want to let a // reviewer see a draft. return control.forUser(user).isRefVisible(); } return false; } private void addReviewers( ChangeResource rsrc, PostResult result, Map<Account.Id, ChangeControl> reviewers) throws OrmException, RestApiException, UpdateException { try (BatchUpdate bu = batchUpdateFactory.create( dbProvider.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) { Op op = new Op(rsrc, reviewers); Change.Id id = rsrc.getChange().getId(); bu.addOp(id, op); bu.execute(); result.reviewers = Lists.newArrayListWithCapacity(op.added.size()); for (PatchSetApproval psa : op.added) { // New reviewers have value 0, don't bother normalizing. result.reviewers.add( json.format(new ReviewerInfo( psa.getAccountId()), reviewers.get(psa.getAccountId()), ImmutableList.of(psa))); } // We don't do this inside Op, since the accounts are in a different // table. accountLoaderFactory.create(true).fill(result.reviewers); } } private class Op extends BatchUpdate.Op { private final ChangeResource rsrc; private final Map<Account.Id, ChangeControl> reviewers; private List<PatchSetApproval> added; private PatchSet patchSet; Op(ChangeResource rsrc, Map<Account.Id, ChangeControl> reviewers) { this.rsrc = rsrc; this.reviewers = reviewers; } @Override public boolean updateChange(ChangeContext ctx) throws RestApiException, OrmException, IOException { added = approvalsUtil.addReviewers( ctx.getDb(), ctx.getNotes(), ctx.getUpdate(ctx.getChange().currentPatchSetId()), rsrc.getControl().getLabelTypes(), rsrc.getChange(), reviewers.keySet()); if (added.isEmpty()) { return false; } patchSet = psUtil.current(dbProvider.get(), rsrc.getNotes()); return true; } @Override public void postUpdate(Context ctx) throws Exception { emailReviewers(rsrc.getChange(), added); if (!added.isEmpty()) { for (PatchSetApproval psa : added) { Account account = accountCache.get(psa.getAccountId()).getAccount(); hooks.doReviewerAddedHook( rsrc.getChange(), account, patchSet, dbProvider.get()); } } } } private void emailReviewers(Change change, List<PatchSetApproval> added) { if (added.isEmpty()) { return; } // Email the reviewers // // The user knows they added themselves, don't bother emailing them. List<Account.Id> toMail = Lists.newArrayListWithCapacity(added.size()); Account.Id userId = user.get().getAccountId(); for (PatchSetApproval psa : added) { if (!psa.getAccountId().equals(userId)) { toMail.add(psa.getAccountId()); } } if (!toMail.isEmpty()) { try { AddReviewerSender cm = addReviewerSenderFactory .create(change.getProject(), change.getId()); cm.setFrom(userId); cm.addReviewers(toMail); cm.send(); } catch (Exception err) { log.error("Cannot send email to new reviewers of change " + change.getId(), err); } } } public static boolean isLegalReviewerGroup(AccountGroup.UUID groupUUID) { return !SystemGroupBackend.isSystemGroup(groupUUID); } }
/* * Copyright (C) 2012 Red Hat, 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 org.commonjava.maven.ext.core.impl; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.MavenArtifactRepository; import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.Versioning; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.DefaultMavenExecutionResult; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.repository.DefaultMirrorSelector; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusContainer; import org.commonjava.maven.atlas.ident.ref.ProjectRef; import org.commonjava.maven.atlas.ident.ref.ProjectVersionRef; import org.commonjava.maven.atlas.ident.ref.SimpleProjectRef; import org.commonjava.maven.atlas.ident.ref.SimpleProjectVersionRef; import org.commonjava.maven.ext.common.ManipulationException; import org.commonjava.maven.ext.common.model.Project; import org.commonjava.maven.ext.core.ManipulationSession; import org.commonjava.maven.ext.core.fixture.StubTransport; import org.commonjava.maven.ext.core.fixture.TestUtils; import org.commonjava.maven.ext.core.state.VersioningState; import org.commonjava.maven.ext.io.resolver.GalleyAPIWrapper; import org.commonjava.maven.ext.io.resolver.GalleyInfrastructure; import org.commonjava.maven.ext.io.resolver.MavenLocationExpander; import org.commonjava.maven.ext.io.rest.handler.AddSuffixJettyHandler; import org.commonjava.maven.galley.model.Location; import org.commonjava.maven.galley.spi.transport.Transport; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; public class VersioningCalculatorTest { private static final String GROUP_ID = "group.id"; private static final String ARTIFACT_ID = "artifact-id"; @Rule public TemporaryFolder temp = new TemporaryFolder(); private TestVersionCalculator modder; private ManipulationSession session; @Test public void initFailsWithoutSuffixProperty() throws Exception { final VersioningState session = setupSession( new Properties() ); assertThat( session.isEnabled(), equalTo( false ) ); } @Test public void applyNonSerialSuffix_NonNumericVersionTail_WithProperty() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "${property}"; final String result = calculate( v ); assertThat( result, equalTo( v + "-" + s ) ); } @Test public void osgi_fixups() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); String[][] data = new String[][] { {"1", "1.0.0"}, {"6.2.0-SNAPSHOT", "6.2.0"}, {"1.21", "1.21.0"}, {"1.21.0", "1.21.0"}, {"1.21-GA", "1.21.0.GA"}, {"1.21-GA-GA", "1.21.0.GA-GA"}, {"1.21.0.GA", "1.21.0.GA"}, {"1.21.GA", "1.21.0.GA"}, {"1.21.GA_FINAL", "1.21.0.GA_FINAL"}, {"1.21.GA_ALPHA123", "1.21.0.GA_ALPHA123"}, {"1.21.0-GA", "1.21.0.GA"} }; for ( String[] v : data ) { final String result = calculate( v[0] ); // If expected result contains a qualifier append a '-' instead of '.' if ( v[1].contains( "GA" )) { assertThat( result, equalTo( v[1] + "-" + s ) ); } else { assertThat( result, equalTo( v[1] + "." + s ) ); } } } /** * Not every version form know to man is converted...but we should try to * safely handle unknown forms. */ @Test public void osgi_fallback() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); String[][] data = new String[][] { {"GA-1-GA", "GA-1-GA"}, {"1.0.0.0.0-GA", "1.0.0.0-0-GA"} }; for ( String[] v : data ) { final String result = calculate( v[0] ); if ( v[1].contains( "GA" )) { assertThat( result, equalTo( v[1] + "-" + s ) ); } else { assertThat( result, equalTo( v[1] + "." + s ) ); } } } @Test public void applyNonSerialSuffix_NonNumericVersionTail_WithOSGiDisabled() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); props.setProperty( VersioningState.VERSION_OSGI_SYSPROP, "false" ); setupSession( props ); final String v = "1.2.GA"; final String result = calculate( v ); assertThat( result, equalTo( v + "-" + s ) ); } @Test public void idempotency() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0"; String result = calculate( v ); assertThat( result, equalTo( v + "." + s ) ); result = calculate( result ); assertThat( result, equalTo( v + "." + s ) ); } @Test public void applyNonSerialSuffix_NumericVersionTail() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0"; final String result = calculate( v ); assertThat( result, equalTo( v + "." + s ) ); } @Test public void applyNonSerialSuffix_NumericVersionTail_CompoundQualifier() throws Exception { final Properties props = new Properties(); final String s = "foo-bar"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0"; final String result = calculate( v ); assertThat( result, equalTo( v + "." + s ) ); } @Test public void applyNonSerialSuffix_NonNumericVersionTail() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0.GA"; final String result = calculate( v ); assertThat( result, equalTo( v + "-" + s ) ); } @Test public void applySerialSuffix_SPnVersionTail() throws Exception { final Properties props = new Properties(); final String s = "foo-1"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0.SP4"; final String result = calculate( v ); assertThat( result, equalTo( v + "-" + s ) ); } @Test public void applySerialSuffix_NumericVersionTail() throws Exception { final Properties props = new Properties(); final String s = "foo-1"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0"; final String result = calculate( v ); assertThat( result, equalTo( v + "." + s ) ); } @Test public void applySerialSuffix_NumericVersionTail_Snapshot() throws Exception { final Properties props = new Properties(); final String s = "ER2-rht-1"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "6.2.0-SNAPSHOT"; final String vr = "6.2.0"; final String result = calculate( v ); assertThat( result, equalTo( vr + "." + s ) ); } @Test public void applySerialSuffix_NumericVersionTail_CompoundQualifier() throws Exception { final Properties props = new Properties(); final String s = "foo-bar-1"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0"; final String result = calculate( v ); assertThat( result, equalTo( v + "." + s ) ); } @Test public void applySerialSuffix_NonNumericSuffixInVersionTail() throws Exception { final Properties props = new Properties(); final String s = "foo-1"; props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0.GA-foo"; final String result = calculate( v ); assertThat( result, equalTo( v + "-1" ) ); } @Test public void applySerialSuffix_Timestamp() throws Exception { final Properties props = new Properties(); final String s = "t-20170216-223844-555-foo"; props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0.t-20170216-223844-555-foo"; final String result = calculate( v ); assertThat( result, equalTo( v + "-1" ) ); } @Test public void applySerialSuffix_SimpleSuffixProperty() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, s ); setupSession( props ); final String originalVersion = "1.0.0.Final"; final String calcdVersion = "1.0.0.Final-foo-1"; final String result = calculate( originalVersion ); assertThat( result, equalTo( calcdVersion ) ); } @Test public void applySerialSuffixWithPadding_SimpleSuffixProperty() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, s ); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "3" ); setupSession( props ); final String originalVersion = "1.0.0.Final"; final String calcdVersion = "1.0.0.Final-foo-001"; final String result = calculate( originalVersion ); assertThat( result, equalTo( calcdVersion ) ); } @Test public void applySerialSuffix_NonNumericNonSuffixInVersionTail() throws Exception { final Properties props = new Properties(); final String s = "foo-1"; props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0.GA-jdcasey"; final String result = calculate( v ); assertThat( result, equalTo( v + "-" + s ) ); } @Test public void applySerialSuffix_NonNumericVersionTail() throws Exception { final Properties props = new Properties(); final String s = "foo-1"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0.GA"; final String result = calculate( v ); assertThat( result, equalTo( v + "-" + s ) ); } @Test public void applySerialSuffix_NumericVersionTail_OverwriteExisting() throws Exception { final Properties props = new Properties(); final String s = "foo-2"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0"; final String os = ".foo-1"; final String result = calculate( v + os ); assertThat( result, equalTo( v + "." + s ) ); } @Test public void applySerialSuffix_NonNumericVersionTail_OverwriteExisting() throws Exception { final Properties props = new Properties(); final String s = "foo-2"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String v = "1.2.0.GA"; final String os = "-foo-1"; final String result = calculate( v + os ); assertThat( result, equalTo( v + "-" + s ) ); } @Test public void applySuffixBeforeSNAPSHOT() throws Exception { final Properties props = new Properties(); final String s = "foo-2"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); props.setProperty( VersioningState.VERSION_SUFFIX_SNAPSHOT_SYSPROP, "true" ); setupSession( props ); final String v = "1.2.0.GA"; final String sn = "-SNAPSHOT"; final String result = calculate( v + sn ); assertThat( result, equalTo( v + "-" + s + sn ) ); } @Test public void applySuffixBeforeSNAPSHOT_OSGI() throws Exception { final Properties props = new Properties(); final String s = "foo-2"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); props.setProperty( VersioningState.VERSION_SUFFIX_SNAPSHOT_SYSPROP, "true" ); setupSession( props ); final String v = "1.2"; final String sn = "-SNAPSHOT"; final String result = calculate( v + sn ); assertThat( result, equalTo( v + ".0." + s + sn ) ); } @Test public void applySuffixBeforeSNAPSHOT_OSGI_2() throws Exception { final Properties props = new Properties(); final String s = "rebuild-2"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); props.setProperty( VersioningState.VERSION_SUFFIX_SNAPSHOT_SYSPROP, "true" ); setupSession( props ); final String v = "4.8-2"; final String sn = "-SNAPSHOT"; final String result = calculate( v + sn ); assertThat( result, equalTo( "4.8.2." + s + sn ) ); } @Test public void applySuffixBeforeSNAPSHOT_OverwriteExisting() throws Exception { final Properties props = new Properties(); final String s = "foo-2"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); props.setProperty( VersioningState.VERSION_SUFFIX_SNAPSHOT_SYSPROP, "true" ); setupSession( props ); final String v = "1.2.0.GA"; final String sn = "-SNAPSHOT"; final String os = "-foo-1"; final String result = calculate( v + os + sn ); assertThat( result, equalTo( v + "-" + s + sn ) ); } @Test public void applySuffixReplaceSNAPSHOT() throws Exception { final Properties props = new Properties(); final String s = "foo"; props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, s ); setupSession( props ); final String originalVersion = "1.0.0.Final-foo-SNAPSHOT"; final String calcdVersion = "1.0.0.Final-foo-1"; final String result = calculate( originalVersion ); assertThat( result, equalTo( calcdVersion ) ); } @Test public void applyManualSuffixReplaceSNAPSHOT() throws Exception { final Properties props = new Properties(); final String s = "201212-1"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String originalVersion = "1.0.0.Final-SNAPSHOT"; final String calcdVersion = "1.0.0.Final-201212-1"; final String result = calculate( originalVersion ); assertThat( result, equalTo( calcdVersion ) ); } @Test public void applyManualSuffixReplaceSNAPSHOT2() throws Exception { final Properties props = new Properties(); final String s = "jbossorg-201212"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, s ); setupSession( props ); final String originalVersion = "1.0.0.Final-SNAPSHOT"; final String calcdVersion = "1.0.0.Final-jbossorg-201212"; final String result = calculate( originalVersion ); assertThat( result, equalTo( calcdVersion ) ); } @Test public void applySerialSuffix_InvalidOSGi() throws Exception { final Properties props = new Properties(); final String origVersion = "1.2.3.4.Final"; final String suffix = "foo-1"; final String newVersion = "1.2.3.4-Final-foo-1"; props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, suffix ); setupSession( props ); final String result = calculate( origVersion ); assertThat( result, equalTo( newVersion ) ); } @Test public void incrementExistingSerialSuffix() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-0" ); setupSession( props ); final String v = "1.2.0.GA"; final String os = "-foo-1"; final String ns = "-foo-1"; final String result = calculate( v + os ); assertThat( result, equalTo( v + ns ) ); } @Test public void incrementExistingSerialSuffix2() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-0" ); setupSession( props, "1.2.0.foo-2" ); final String v = "1.2.0"; final String os = ".foo-1"; final String ns = ".foo-3"; final String result = calculate( v + os ); assertThat( result, equalTo( v + ns ) ); } @Test public void incrementExistingSerialSuffix3() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2.0-foo-1", "1.2.0-foo-2" ); final String v = "1.2.0.foo-3"; final String result = calculate( v ); assertThat( result, equalTo( v ) ); } @Test public void incrementExistingSerialSuffix4() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2.0-foo-1", "1.2.0-foo-2" ); final String v = "1.2.0.foo-4"; final String result = calculate( v ); assertThat( result, equalTo( v ) ); } @Test public void incrementExistingSerialSuffix5() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2.0-foo-1", "1.2.0-foo-4" ); final String origVersion = "1.2.0.foo-2"; final String newVersion = "1.2.0.foo-5"; final String result = calculate( origVersion ); assertThat( result, equalTo( newVersion ) ); } @Test public void incrementExistingSerialSuffix6() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2.0-foo-8", "1.2.0-foo-9" ); final String v = "1.2.0.foo-10"; final String result = calculate( v ); assertThat( result, equalTo( v ) ); } @Test public void incrementExistingSerialSuffixTimestamp1() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "t-20170216-223844-555-foo" ); setupSession( props, "1.2.0-t-20170216-223844-555-foo-8", "1.2.0-t-20170216-223844-555-foo-9" ); final String newVersion = "1.2.0.t-20170216-223844-555-foo-10"; final String v = "1.2.0.t-20170216-223844-555-foo-5"; final String result = calculate( v ); assertThat( result, equalTo( newVersion ) ); } @Test public void incrementExistingSerialSuffix7() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-bar" ); setupSession( props ); final String v = "7.0.0.beta-foo-bar-1"; final String newVersion = "7.0.0.beta-foo-bar-1"; final String result = calculate( v ); assertThat( result, equalTo( newVersion ) ); } @Test public void incrementExistingSerialSuffix8() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2.0-foo-1", "1.2.0-foo-4" ); final String origVersion = "1.2.0.foo_2"; final String newVersion = "1.2.0.foo_5"; final String result = calculate( origVersion ); assertThat( result, equalTo( newVersion ) ); } @Test public void incrementExistingSerialSuffixWithPadding() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "3" ); setupSession( props, "1.2.0-foo-8", "1.2.0-foo-9" ); final String v = "1.2.0.foo-010"; final String result = calculate( v ); assertThat( result, equalTo( v ) ); } @Test public void incrementExistingSuffixWithPadding() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, "foo-10" ); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "3" ); setupSession( props, "1.2.0" ); final String v = "1.2.0.foo-10"; final String result = calculate( v ); assertThat( result, equalTo( v ) ); } @Test public void incrementExistingSerialSuffix_CompoundQualifier() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-bar-0" ); setupSession( props, "1.2.0.GA-foo-bar-1", "1.2.0.GA-foo-bar-2" ); final String v = "1.2.0.GA"; final String os = "-foo-bar-1"; final String ns = "-foo-bar-3"; final String result = calculate( v + os ); assertThat( result, equalTo( v + ns ) ); } @Test public void incrementExistingSerialSuffix_InvalidOSGi() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2.0-GA-foo-1" ); final String origVer = "1.2.0-GA-foo-1"; final String updatedVer = "1.2.0.GA-foo-2"; final String result = calculate( origVer ); assertThat( result, equalTo( updatedVer ) ); } @Test public void incrementExistingSerialSuffix_InvalidOSGi_SNAPSHOT() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props ); final String origVer = "4.3.3-foo-SNAPSHOT"; final String updatedVer = "4.3.3.foo-1"; final String result = calculate( origVer ); assertThat( result, equalTo( updatedVer ) ); } @Test public void incrementExistingSerialSuffix_UsingRepositoryMetadata() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-0" ); setupSession( props, "1.2.0.GA-foo-3", "1.2.0.GA-foo-2", "1.2.0.GA-foo-9" ); final String v = "1.2.0.GA"; final String os = "-foo-1"; final String ns = "-foo-10"; final String result = calculate( v + os ); assertThat( result, equalTo( v + ns ) ); } @Test public void incrementExistingSerialSuffix_withOsgiVersionChangeExistingVersionsMicro() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2-foo-1", "1.2.foo-2" ); final String v = "1.2"; final String ns = "foo-3"; final String result = calculate( v ); assertThat( result, equalTo( v + ".0." + ns ) ); } @Test public void incrementExistingSerialSuffix_TwoProjects_UsingRepositoryMetadata_AvailableOnlyForOne() throws Exception { final String v = "1.2.0.GA"; final String os = "-foo-1"; final String ns = "foo-10"; final Model m1 = new Model(); m1.setGroupId( GROUP_ID ); m1.setArtifactId( ARTIFACT_ID ); m1.setVersion( v + os ); final Project p1 = new Project( m1 ); final String a2 = ARTIFACT_ID + "-dep"; final Model m2 = new Model(); m2.setGroupId( GROUP_ID ); m2.setArtifactId( a2 ); m2.setVersion( v + os ); final Project p2 = new Project( m2 ); final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-0" ); setupSession( props, "1.2.0.GA-foo-3", "1.2.0.GA-foo-2", "1.2.0.GA-foo-9" ); final Map<ProjectVersionRef, String> result = modder.calculateVersioningChanges( Arrays.asList( p1, p2 ), session ); assertThat( result.get( new SimpleProjectVersionRef( GROUP_ID, ARTIFACT_ID, v + os ) ), equalTo( v + "-" + ns ) ); assertThat( result.get( new SimpleProjectVersionRef( GROUP_ID, a2, v + os ) ), equalTo( v + "-" + ns ) ); } @Test public void incrementExistingSerialSuffix_TwoProjects_UsingRepositoryMetadata_DifferentAvailableIncrements() throws Exception { final String v = "1.2.0.GA"; final String os = "-foo-1"; final String ns = "foo-10"; final Model m1 = new Model(); m1.setGroupId( GROUP_ID ); m1.setArtifactId( ARTIFACT_ID ); m1.setVersion( v + os ); final Project p1 = new Project( m1 ); final String a2 = ARTIFACT_ID + "-dep"; final Model m2 = new Model(); m2.setGroupId( GROUP_ID ); m2.setArtifactId( a2 ); m2.setVersion( v + os ); final Project p2 = new Project( m2 ); final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-0" ); final Map<ProjectRef, String[]> versionMap = new HashMap<>(); versionMap.put( new SimpleProjectRef( p1.getGroupId(), p1.getArtifactId() ), new String[] { "1.2.0.GA-foo-3", "1.2.0.GA-foo-2", "1.2.0.GA-foo-9" } ); versionMap.put( new SimpleProjectRef( p2.getGroupId(), p2.getArtifactId() ), new String[] { "1.2.0.GA-foo-3", "1.2.0.GA-foo-2" } ); setupSession( props, versionMap ); final Map<ProjectVersionRef, String> result = modder.calculateVersioningChanges( Arrays.asList( p1, p2 ), session ); assertThat( result.get( new SimpleProjectVersionRef( GROUP_ID, ARTIFACT_ID, v + os ) ), equalTo( v + "-" + ns ) ); assertThat( result.get( new SimpleProjectVersionRef( GROUP_ID, a2, v + os ) ), equalTo( v + "-" + ns ) ); } @Test public void incrementExistingSerialSuffix_UsingRepositoryMetadataWithIrrelevantVersions() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "redhat-0" ); setupSession( props, "0.0.1", "0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7", "0.0.7.redhat-1" ); final String v = "0.0.7"; final String ns = AddSuffixJettyHandler.EXTENDED_SUFFIX; final String result = calculate( v ); assertThat( result, equalTo( v + "." + ns ) ); } @Test public void incrementExistingSerialSuffix_Property() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo-0" ); setupSession( props ); final String v = "${property}"; final String os = "-foo-1"; final String ns = "foo-1"; final String result = calculate( v + os ); assertThat( result, equalTo( v + "-" + ns ) ); } @Test public void incrementExistingSerialSuffix_withEmptySuffixBase() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "" ); setupSession( props, "1.2.0.1", "1.2.0.2" ); final String v = "1.2.0"; final String ns = "3"; final String result = calculate( v ); assertThat( result, equalTo( v + "." + ns ) ); } @Test public void alphaNumericSuffixBase() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, "test-jdk7" ); props.setProperty( VersioningState.VERSION_OSGI_SYSPROP, "false" ); setupSession( props ); final String v = "1.1"; final String os = ""; final String ns = ".test-jdk7"; final String result = calculate( v + os ); assertThat( result, equalTo( v + ns ) ); } @Test public void alphaNumericSuffixBaseOSGi() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, "Beta1" ); props.setProperty( VersioningState.VERSION_OSGI_SYSPROP, "true" ); setupSession( props ); final String v = "1"; final String os = ""; final String ns = ".Beta1"; final String result = calculate( v + os ); assertThat( result, equalTo( v + ".0.0" + ns ) ); } @Test public void alphaNumericSuffixBaseOSGiTimestamp() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, "t171222-2230-rebuild-1" ); props.setProperty( VersioningState.VERSION_OSGI_SYSPROP, "true" ); setupSession( props ); final String v = "1.1"; final String ns = ".t171222-2230-rebuild-1"; final String result = calculate( v ); assertThat( result, equalTo( v + ".0" + ns ) ); } @Test public void alphaNumericSuffixBaseWithSnapshot() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.VERSION_SUFFIX_SYSPROP, "test_jdk7" ); props.setProperty( VersioningState.VERSION_OSGI_SYSPROP, "false" ); props.setProperty( VersioningState.VERSION_SUFFIX_SNAPSHOT_SYSPROP, "true" ); setupSession( props ); final String v = "1.1-SNAPSHOT"; final String os = ""; final String ns = ".test_jdk7-SNAPSHOT"; final String result = calculate( v + os ); assertThat( result, equalTo( "1.1" + ns ) ); } @Test public void verifyPadding() throws Exception { final Properties props = new Properties(); setupSession( props ); int padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.2.0.GA-foo-0" ) ) ); assertEquals( 1, padding ); padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.2.0.GA-foo-01" ) ) ); assertEquals( 2, padding ); padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.2.0.GA-foo-101" ) ) ); assertEquals( 3, padding ); padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.2.0.GA-foo-001" ) ) ); assertEquals( 3, padding ); padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.2.0.GA-foo-9" ) ) ); assertEquals( 1, padding ); padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.0.0.redhat-1" ) ) ); assertEquals( 1, padding ); padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.0.0.Final.rebuild-01912-01" ) ) ); assertEquals( 2, padding ); padding = Version.getBuildNumberPadding( 0, new HashSet<>( Collections.singletonList( "1.0.0.GA.rebuild-010" ) ) ); assertEquals( 3, padding ); } @Test public void verifyPaddingSuffix() { String paddedBuildNum = StringUtils.leftPad( "1", 0, '0' ); System.out.println ("### got " + paddedBuildNum); assertEquals( "1", paddedBuildNum ); paddedBuildNum = StringUtils.leftPad( "1", 1, '0' ); System.out.println ("### got " + paddedBuildNum); assertEquals( "1", paddedBuildNum ); paddedBuildNum = StringUtils.leftPad( "1", 2, '0' ); System.out.println ("### got " + paddedBuildNum); assertEquals( "01", paddedBuildNum ); paddedBuildNum = StringUtils.leftPad( "1", 3, '0' ); System.out.println ("### got " + paddedBuildNum); assertEquals( "001", paddedBuildNum ); paddedBuildNum = StringUtils.leftPad( "10", 3, '0' ); System.out.println ("### got " + paddedBuildNum); assertEquals( "010", paddedBuildNum ); paddedBuildNum = StringUtils.leftPad( "010", 3, '0' ); System.out.println ("### got " + paddedBuildNum); assertEquals( "010", paddedBuildNum ); paddedBuildNum = StringUtils.leftPad( "010", 6, '0' ); System.out.println ("### got " + paddedBuildNum); assertEquals( "000010", paddedBuildNum ); } @Test public void incrementExistingSerialSuffix_TwoProjects_UsingRepositoryMetadata_AvailableOnlyForOne_Padding() throws Exception { final String v = "1.2.0.GA"; final String os = "-foo-001"; final String ns = "foo-010"; final Model m1 = new Model(); m1.setGroupId( GROUP_ID ); m1.setArtifactId( ARTIFACT_ID ); m1.setVersion( v + os ); final Project p1 = new Project( m1 ); final String a2 = ARTIFACT_ID + "-dep"; final Model m2 = new Model(); m2.setGroupId( GROUP_ID ); m2.setArtifactId( a2 ); m2.setVersion( v + os ); final Project p2 = new Project( m2 ); final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "foo" ); setupSession( props, "1.2.0.GA-foo-003", "1.2.0.GA-foo-002", "1.2.0.GA-foo-009" ); System.out.println ("### Calculating versioning changes for projects " + p1 + " and " + p2); final Map<ProjectVersionRef, String> result = modder.calculateVersioningChanges( Arrays.asList( p1, p2 ), session ); assertThat( result.get( new SimpleProjectVersionRef( GROUP_ID, ARTIFACT_ID, v + os ) ), equalTo( v + "-" + ns ) ); assertThat( result.get( new SimpleProjectVersionRef( GROUP_ID, a2, v + os ) ), equalTo( v + "-" + ns ) ); } @Test public void checkVersionStripping () { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "temporary-redhat" ); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "5" ); props.setProperty( VersioningState.VERSION_SUFFIX_ALT, "redhat" ); VersioningState vState = new VersioningState( props ); assertEquals( "1.0.0.temporary-redhat-1", VersionCalculator.handleAlternate( vState, "1.0.0.temporary-redhat-1" ) ); assertEquals( "1.0.0", VersionCalculator.handleAlternate( vState, "1.0.0" ) ); assertEquals( "1.0.0", VersionCalculator.handleAlternate( vState, "1.0.0.redhat-10" ) ); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "redhat" ); props.remove( VersioningState.VERSION_SUFFIX_ALT ); vState = new VersioningState( props ); assertEquals( "1.0.0.temporary-redhat-1", VersionCalculator.handleAlternate( vState, "1.0.0.temporary-redhat-1" ) ); assertEquals( "1.0.0", VersionCalculator.handleAlternate( vState, "1.0.0" ) ); assertEquals( "1.0.0.redhat-10", VersionCalculator.handleAlternate( vState, "1.0.0.redhat-10" ) ); } @Test public void incrementExistingSuffixWithTemporary() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "temporary-redhat" ); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "5" ); props.setProperty( VersioningState.VERSION_SUFFIX_ALT, "redhat" ); setupSession( props, "1.2.0.redhat-00002", "1.2.0.temporary-redhat-00001", "1.2.0.temporary-redhat-00002" ); String oldValue = "1.2.0.redhat-00001"; final String v = "1.2.0.temporary-redhat-00003"; final String result = calculate( oldValue ); assertThat( result, equalTo( v ) ); } @Test public void incrementUsingCustomCalculatorAndRESTMetadata() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "rebuild" ); final VersioningState state = setupSession( props ); final String origVersion = "1.2.0"; final String candidateVersion = "1.2.0.rebuild-1"; final String newVersion = "1.2.0.rebuild-2"; final ProjectVersionRef projectVersionRef = SimpleProjectVersionRef.parse( "org.jboss:bar:" + origVersion ); final Map<ProjectRef, Set<String>> metadata = new HashMap<>(); final Set<String> candidates = new HashSet<>(); candidates.add( candidateVersion ); metadata.put( projectVersionRef.asProjectRef(), candidates ); state.setRESTMetadata( metadata ); VersionCalculator vc = new VersionCalculator( null ); final String result = vc.calculate( "org.jboss", "bar", origVersion, state ); System.out.println(state); assertThat(result, equalTo( newVersion ) ); } @Test public void incrementUsingCustomCalculatorWithNoMetadata() throws Exception { final Properties props = new Properties(); props.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, "rebuild" ); final VersioningState state = setupSession( props ); final String origVersion = "1.2.0"; final String newVersion = "1.2.0.rebuild-1"; VersionCalculator vc = new VersionCalculator( null ); final String result = vc.calculate( "org.jboss", "bar", origVersion, state ); System.out.println(state); assertThat(result, equalTo( newVersion ) ); } private byte[] setupMetadataVersions( final String... versions ) throws IOException { final Metadata md = new Metadata(); final Versioning v = new Versioning(); md.setVersioning( v ); v.setVersions( Arrays.asList( versions ) ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); new MetadataXpp3Writer().write( baos, md ); return baos.toByteArray(); } private String calculate( final String version ) throws Exception { return modder.calculate( GROUP_ID, ARTIFACT_ID, version, session ); } private VersioningState setupSession( final Properties properties, final String... versions ) throws Exception { return setupSession( properties, Collections.singletonMap( new SimpleProjectRef( GROUP_ID, ARTIFACT_ID ), versions ) ); } @SuppressWarnings( "deprecation" ) private VersioningState setupSession( final Properties properties, final Map<ProjectRef, String[]> versionMap ) throws Exception { // Originally the default used to be 0, this was changed to be 5 but this affects this test suite so revert // just for these tests. if ( ! properties.containsKey( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP ) ) { properties.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "0" ); } final ArtifactRepository ar = new MavenArtifactRepository( "test", TestUtils.MVN_CENTRAL, new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy() ); final MavenExecutionRequest req = new DefaultMavenExecutionRequest().setUserProperties( properties ) .setRemoteRepositories( Collections.singletonList( ar ) ); final PlexusContainer container = new DefaultPlexusContainer(); final MavenSession mavenSession = new MavenSession( container, null, req, new DefaultMavenExecutionResult() ); session = new ManipulationSession(); session.setMavenSession( mavenSession ); final VersioningState state = new VersioningState( properties ); session.setState( state ); final Map<String, byte[]> dataMap = new HashMap<>(); if ( versionMap != null && !versionMap.isEmpty() ) { for ( final Map.Entry<ProjectRef, String[]> entry : versionMap.entrySet() ) { final String path = toMetadataPath( entry.getKey() ); final byte[] data = setupMetadataVersions( entry.getValue() ); dataMap.put( path, data ); } } final Location mdLoc = MavenLocationExpander.EXPANSION_TARGET; final Transport mdTrans = new StubTransport( dataMap ); modder = new TestVersionCalculator( new ManipulationSession(), mdLoc, mdTrans, temp.newFolder( "galley-cache" ) ); return state; } private String toMetadataPath( final ProjectRef key ) { return String.format( "%s/%s/maven-metadata.xml", key.getGroupId() .replace( '.', '/' ), key.getArtifactId() ); } public static final class TestVersionCalculator extends VersionCalculator { TestVersionCalculator( final ManipulationSession session, final Location mdLoc, final Transport mdTrans, final File cacheDir ) throws ManipulationException { super( new GalleyAPIWrapper( new GalleyInfrastructure( session, new DefaultMirrorSelector()).init(mdLoc, mdTrans, cacheDir ) ) ); } @Override public String calculate( final String groupId, final String artifactId, final String originalVersion, final ManipulationSession session ) throws ManipulationException { return super.calculate( groupId, artifactId, originalVersion, session ); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.reservation.planning; import java.util.HashMap; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.ReservationRequestInterpreter; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan; import org.apache.hadoop.yarn.server.resourcemanager.reservation.RLESparseResourceAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationInterval; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.ContractValidationException; import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException; import org.apache.hadoop.yarn.util.resource.Resources; /** * A planning algorithm consisting of two main phases. The algorithm iterates * over the job stages in descending order. For each stage, the algorithm: 1. * Determines an interval [stageArrivalTime, stageDeadline) in which the stage * is allocated. 2. Computes an allocation for the stage inside the interval. * * For ANY and ALL jobs, phase 1 sets the allocation window of each stage to be * [jobArrival, jobDeadline]. For ORDER and ORDER_NO_GAP jobs, the deadline of * each stage is set as succcessorStartTime - the starting time of its * succeeding stage (or jobDeadline if it is the last stage). * * The phases are set using the two functions: 1. setAlgEarliestStartTime 2. * setAlgComputeStageAllocation */ public class IterativePlanner extends PlanningAlgorithm { // Modifications performed by the algorithm that are not been reflected in the // actual plan while a request is still pending. private RLESparseResourceAllocation planModifications; // Data extracted from plan private Map<Long, Resource> planLoads; private Resource capacity; private long step; // Job parameters private ReservationRequestInterpreter jobType; private long jobArrival; private long jobDeadline; // Phase algorithms private StageEarliestStart algStageEarliestStart = null; private StageAllocator algStageAllocator = null; // Constructor public IterativePlanner(StageEarliestStart algEarliestStartTime, StageAllocator algStageAllocator) { setAlgStageEarliestStart(algEarliestStartTime); setAlgStageAllocator(algStageAllocator); } @Override public RLESparseResourceAllocation computeJobAllocation(Plan plan, ReservationId reservationId, ReservationDefinition reservation, String user) throws PlanningException { // Initialize initialize(plan, reservation); // If the job has been previously reserved, logically remove its allocation ReservationAllocation oldReservation = plan.getReservationById(reservationId); if (oldReservation != null) { ignoreOldAllocation(oldReservation); } // Create the allocations data structure RLESparseResourceAllocation allocations = new RLESparseResourceAllocation(plan.getResourceCalculator()); // Get a reverse iterator for the set of stages ListIterator<ReservationRequest> li = reservation .getReservationRequests() .getReservationResources() .listIterator( reservation.getReservationRequests().getReservationResources() .size()); // Current stage ReservationRequest currentReservationStage; // Index, points on the current node int index = reservation.getReservationRequests().getReservationResources().size(); // Stage deadlines long stageDeadline = stepRoundDown(reservation.getDeadline(), step); long successorStartingTime = -1; // Iterate the stages in reverse order while (li.hasPrevious()) { // Get current stage currentReservationStage = li.previous(); index -= 1; // Validate that the ReservationRequest respects basic constraints validateInputStage(plan, currentReservationStage); // Compute an adjusted earliestStart for this resource // (we need this to provision some space for the ORDER contracts) long stageArrivalTime = reservation.getArrival(); if (jobType == ReservationRequestInterpreter.R_ORDER || jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP) { stageArrivalTime = computeEarliestStartingTime(plan, reservation, index, currentReservationStage, stageDeadline); } stageArrivalTime = stepRoundUp(stageArrivalTime, step); stageArrivalTime = Math.max(stageArrivalTime, reservation.getArrival()); // Compute the allocation of a single stage Map<ReservationInterval, Resource> curAlloc = computeStageAllocation(plan, currentReservationStage, stageArrivalTime, stageDeadline, user, reservationId); // If we did not find an allocation, return NULL // (unless it's an ANY job, then we simply continue). if (curAlloc == null) { // If it's an ANY job, we can move to the next possible request if (jobType == ReservationRequestInterpreter.R_ANY) { continue; } // Otherwise, the job cannot be allocated return null; } // Get the start & end time of the current allocation Long stageStartTime = findEarliestTime(curAlloc); Long stageEndTime = findLatestTime(curAlloc); // If we did find an allocation for the stage, add it for (Entry<ReservationInterval, Resource> entry : curAlloc.entrySet()) { allocations.addInterval(entry.getKey(), entry.getValue()); } // If this is an ANY clause, we have finished if (jobType == ReservationRequestInterpreter.R_ANY) { break; } // If ORDER job, set the stageDeadline of the next stage to be processed if (jobType == ReservationRequestInterpreter.R_ORDER || jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP) { // Verify that there is no gap, in case the job is ORDER_NO_GAP if (jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP && successorStartingTime != -1 && successorStartingTime > stageEndTime) { return null; } // Store the stageStartTime and set the new stageDeadline successorStartingTime = stageStartTime; stageDeadline = stageStartTime; } } // If the allocation is empty, return an error if (allocations.isEmpty()) { return null; } return allocations; } protected void initialize(Plan plan, ReservationDefinition reservation) { // Get plan step & capacity capacity = plan.getTotalCapacity(); step = plan.getStep(); // Get job parameters (type, arrival time & deadline) jobType = reservation.getReservationRequests().getInterpreter(); jobArrival = stepRoundUp(reservation.getArrival(), step); jobDeadline = stepRoundDown(reservation.getDeadline(), step); // Dirty read of plan load planLoads = getAllLoadsInInterval(plan, jobArrival, jobDeadline); // Initialize the plan modifications planModifications = new RLESparseResourceAllocation(plan.getResourceCalculator()); } private Map<Long, Resource> getAllLoadsInInterval(Plan plan, long startTime, long endTime) { // Create map Map<Long, Resource> loads = new HashMap<Long, Resource>(); // Calculate the load for every time slot between [start,end) for (long t = startTime; t < endTime; t += step) { Resource load = plan.getTotalCommittedResources(t); loads.put(t, load); } // Return map return loads; } private void ignoreOldAllocation(ReservationAllocation oldReservation) { // If there is no old reservation, return if (oldReservation == null) { return; } // Subtract each allocation interval from the planModifications for (Entry<ReservationInterval, Resource> entry : oldReservation .getAllocationRequests().entrySet()) { // Read the entry ReservationInterval interval = entry.getKey(); Resource resource = entry.getValue(); // Find the actual request Resource negativeResource = Resources.multiply(resource, -1); // Insert it into planModifications as a 'negative' request, to // represent available resources planModifications.addInterval(interval, negativeResource); } } private void validateInputStage(Plan plan, ReservationRequest rr) throws ContractValidationException { // Validate concurrency if (rr.getConcurrency() < 1) { throw new ContractValidationException("Gang Size should be >= 1"); } // Validate number of containers if (rr.getNumContainers() <= 0) { throw new ContractValidationException("Num containers should be > 0"); } // Check that gangSize and numContainers are compatible if (rr.getNumContainers() % rr.getConcurrency() != 0) { throw new ContractValidationException( "Parallelism must be an exact multiple of gang size"); } // Check that the largest container request does not exceed the cluster-wide // limit for container sizes if (Resources.greaterThan(plan.getResourceCalculator(), capacity, rr.getCapability(), plan.getMaximumAllocation())) { throw new ContractValidationException( "Individual capability requests should not exceed cluster's " + "maxAlloc"); } } // Call algEarliestStartTime() protected long computeEarliestStartingTime(Plan plan, ReservationDefinition reservation, int index, ReservationRequest currentReservationStage, long stageDeadline) { return algStageEarliestStart.setEarliestStartTime(plan, reservation, index, currentReservationStage, stageDeadline); } // Call algStageAllocator protected Map<ReservationInterval, Resource> computeStageAllocation( Plan plan, ReservationRequest rr, long stageArrivalTime, long stageDeadline, String user, ReservationId oldId) throws PlanningException { return algStageAllocator.computeStageAllocation(plan, planLoads, planModifications, rr, stageArrivalTime, stageDeadline, user, oldId); } // Set the algorithm: algStageEarliestStart public IterativePlanner setAlgStageEarliestStart(StageEarliestStart alg) { this.algStageEarliestStart = alg; return this; // To allow concatenation of setAlg() functions } // Set the algorithm: algStageAllocator public IterativePlanner setAlgStageAllocator(StageAllocator alg) { this.algStageAllocator = alg; return this; // To allow concatenation of setAlg() functions } }
/** * Copyright 2015 Austin Keener & Michael Ritter * * 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 net.dv8tion.jda; import net.dv8tion.jda.entities.impl.JDAImpl; import net.dv8tion.jda.events.ReadyEvent; import net.dv8tion.jda.events.message.MessageReceivedEvent; import net.dv8tion.jda.hooks.EventListener; import net.dv8tion.jda.hooks.ListenerAdapter; import javax.security.auth.login.LoginException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * Used to create a new {@link net.dv8tion.jda.JDA} instance. This is useful for making sure all of * your {@link net.dv8tion.jda.hooks.EventListener EventListeners} as registered * before {@link net.dv8tion.jda.JDA} attempts to log in. * <p> * A single JDABuilder can be reused multiple times. Each call to * {@link net.dv8tion.jda.JDABuilder#build() build()} or * {@link net.dv8tion.jda.JDABuilder#buildBlocking() buildBlocking()} * creates a new {@link net.dv8tion.jda.JDA} instance using the same information. * This means that you can have listeners easily registered to multiple {@link net.dv8tion.jda.JDA} instances. */ public class JDABuilder { protected static boolean proxySet = false; protected static boolean jdaCreated = false; protected static String proxyUrl = null; protected static int proxyPort = -1; final List<EventListener> listeners; String email = null; String pass = null; boolean debug = false; protected final ListenerAdapter acknowledgeListener = new ListenerAdapter() { @Override public void onMessageReceived(MessageReceivedEvent event) { event.getMessage().acknowledge(); }; }; /** * Creates a completely empty JDABuilder.<br> * If you use this, you need to set the email and password using * {@link net.dv8tion.jda.JDABuilder#setEmail(String) setEmail(String)} * and {@link net.dv8tion.jda.JDABuilder#setPassword(String) setPassword(String)} * before calling {@link net.dv8tion.jda.JDABuilder#build() build()} * or {@link net.dv8tion.jda.JDABuilder#buildBlocking() buildBlocking()} */ public JDABuilder() { this(null, null); } /** * Creates a new JDABuilder using the provided email and password. * * @param email * The email of the account that will be used to log into Discord. * @param password * The password of the account that will be used to log into Discord. */ public JDABuilder(String email, String password) { this.email = email; this.pass = password; listeners = new LinkedList<>(); } /** * Sets the email that will be used by the {@link net.dv8tion.jda.JDA} instance to log in when * {@link net.dv8tion.jda.JDABuilder#build() build()} * or {@link net.dv8tion.jda.JDABuilder#buildBlocking() buildBlocking()} * is called. * * @param email * The email of the account that you would like to login with. * @return * Returns the {@link net.dv8tion.jda.JDABuilder JDABuilder} instance. Useful for chaining. */ public JDABuilder setEmail(String email) { this.email = email; return this; } /** * Sets the password that will be used by the {@link net.dv8tion.jda.JDA} instance to log in when * {@link net.dv8tion.jda.JDABuilder#build() build()} * or {@link net.dv8tion.jda.JDABuilder#buildBlocking() buildBlocking()} * is called. * * @param password * The password of the account that you would like to login with. * @return * Returns the {@link net.dv8tion.jda.JDABuilder JDABuilder} instance. Useful for chaining. */ public JDABuilder setPassword(String password) { this.pass = password; return this; } /** * Sets the proxy that will be used by <b>ALL</b> JDA instances.<br> * Once this is set <b>IT CANNOT BE CHANGED.</b><br> * After a JDA instance as been created, this method can never be called again, even if you are creating a new JDA object.<br> * <b>Note:</b> currently this only supports HTTP proxies. * * @param proxyUrl * The url of the proxy. * @param proxyPort * The port of the proxy. Usually this is 8080. * @return * Returns the {@link net.dv8tion.jda.JDABuilder JDABuilder} instance. Useful for chaining. * @throws UnsupportedOperationException * If this method is called after proxy settings have already been set or after at least 1 JDA object has been created. */ public JDABuilder setProxy(String proxyUrl, int proxyPort) { if (proxySet || jdaCreated) throw new UnsupportedOperationException("You cannot change the proxy after a proxy has been set or a JDA object has been created. Proxy settings are global among all instances!"); proxySet = true; JDABuilder.proxyUrl = proxyUrl; JDABuilder.proxyPort = proxyPort; return this; } /** * Enables developer debug of JDA.<br> * Enabling this will print stack traces instead of java logger message when exceptions are encountered. * * @param debug * True - enables debug printing. */ public void setDebug(boolean debug) { this.debug = debug; } /** * Adds a listener to the list of listeners that will be used to populate the {@link net.dv8tion.jda.JDA} object. * * @param listener * The listener to add to the list. * @return * Returns the {@link net.dv8tion.jda.JDABuilder JDABuilder} instance. Useful for chaining. */ public JDABuilder addListener(EventListener listener) { listeners.add(listener); return this; } /** * Removes a listener from the list of listeners. * * @param listener * The listener to remove from the list. * @return * Returns the {@link net.dv8tion.jda.JDABuilder JDABuilder} instance. Useful for chaining. */ public JDABuilder removeListener(EventListener listener) { listeners.remove(listener); return this; } /** * Builds a new {@link net.dv8tion.jda.JDA} instance and uses the provided email and password to start the login process.<br> * The login process runs in a different thread, so while this will return immediately, {@link net.dv8tion.jda.JDA} has not * finished loading, thus many {@link net.dv8tion.jda.JDA} methods have the chance to return incorrect information. * <p> * If you wish to be sure that the {@link net.dv8tion.jda.JDA} information is correct, please use * {@link net.dv8tion.jda.JDABuilder#buildBlocking() buildBlocking()} or register a * {@link net.dv8tion.jda.events.ReadyEvent ReadyEvent} {@link net.dv8tion.jda.hooks.EventListener EventListener}. * * @return * A {@link net.dv8tion.jda.JDA} instance that has started the login process. It is unknown as to whether or not loading has finished when this returns. * @throws LoginException * If the provided email-password combination fails the Discord security authentication. * @throws IllegalArgumentException * If either the provided email or password is empty or null. */ public JDA build() throws LoginException, IllegalArgumentException { jdaCreated = true; JDAImpl jda; if (proxySet) jda = new JDAImpl(proxyUrl, proxyPort); else jda = new JDAImpl(); jda.setDebug(debug); listeners.forEach(jda::addEventListener); jda.login(email, pass); return jda; } /** * Builds a new {@link net.dv8tion.jda.JDA} instance and uses the provided email and password to start the login process.<br> * This method will block until JDA has logged in and finished loading all resources. This is an alternative * to using {@link net.dv8tion.jda.events.ReadyEvent ReadyEvent}. * * @return * A {@link net.dv8tion.jda.JDA} Object that is <b>guaranteed</b> to be logged in and finished loading. * @throws LoginException * If the provided email-password combination fails the Discord security authentication. * @throws IllegalArgumentException * If either the provided email or password is empty or null. * @throws InterruptedException * If an interrupt request is received while waiting for {@link net.dv8tion.jda.JDA} to finish logging in. * This would most likely be caused by a JVM shutdown request. */ public JDA buildBlocking() throws LoginException, IllegalArgumentException, InterruptedException { //Create our ReadyListener and a thread safe Boolean. AtomicBoolean ready = new AtomicBoolean(false); ListenerAdapter readyListener = new ListenerAdapter() { @Override public void onReady(ReadyEvent event) { ready.set(true); } }; //Add it to our list of listeners, start the login process, wait for the ReadyEvent. listeners.add(readyListener); JDA jda = build(); while(!ready.get()) { Thread.sleep(50); } //We have logged in. Remove the temp ready listener from our local list and the jda listener list. listeners.remove(readyListener); jda.removeEventListener(readyListener); return jda; } /** * Tells the api if it should auto-acknowledge recieved Messages. * This does not affect Messages send before the api was build. * Will trigger the {@link net.dv8tion.jda.events.message.MessageAcknowledgedEvent MessageAcknowledgedEvent} and it's counterpart for each Message * * @param acknowledge * wether the api should auto-acknowledge Messages or not * @return * Returns the {@link net.dv8tion.jda.JDABuilder JDABuilder} instance. Useful for chaining. */ public JDABuilder setAutoAcknowledgeMessages(boolean acknowledge){ if (acknowledge) { this.addListener(acknowledgeListener); } else { this.removeListener(acknowledgeListener); } return this; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.deltaspike.security.impl.extension; import org.apache.deltaspike.core.spi.activation.Deactivatable; import org.apache.deltaspike.core.util.ClassDeactivationUtils; import org.apache.deltaspike.core.util.metadata.builder.AnnotatedTypeBuilder; import org.apache.deltaspike.security.api.authorization.Secures; import org.apache.deltaspike.security.api.authorization.SecurityDefinitionException; import org.apache.deltaspike.security.impl.util.SecurityUtils; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.AnnotatedMethod; import javax.enterprise.inject.spi.AnnotatedParameter; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.BeforeBeanDiscovery; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessAnnotatedType; /** * Extension for processing typesafe security annotations */ public class SecurityExtension implements Extension, Deactivatable { private static final SecurityInterceptorBinding INTERCEPTOR_BINDING = new SecurityInterceptorBindingLiteral(); private SecurityMetaDataStorage securityMetaDataStorage; private Boolean isActivated = null; protected void init(@Observes BeforeBeanDiscovery beforeBeanDiscovery) { isActivated = ClassDeactivationUtils.isActivated(getClass()); securityMetaDataStorage = new SecurityMetaDataStorage(); } //workaround for OWB public SecurityMetaDataStorage getMetaDataStorage() { return securityMetaDataStorage; } /** * Handles &#064;Secured beans */ public <X> void processAnnotatedType(@Observes ProcessAnnotatedType<X> event) { if (!isActivated) { return; } AnnotatedTypeBuilder<X> builder = null; AnnotatedType<X> type = event.getAnnotatedType(); boolean isSecured = false; // Add the security interceptor to the class if the class is annotated // with a security binding type for (final Annotation annotation : type.getAnnotations()) { if (SecurityUtils.isMetaAnnotatedWithSecurityBindingType(annotation)) { builder = new AnnotatedTypeBuilder<X>().readFromType(type); builder.addToClass(INTERCEPTOR_BINDING); getMetaDataStorage().addSecuredType(type); isSecured = true; break; } } // If the class isn't annotated with a security binding type, check if // any of its methods are, and if so, add the security interceptor to the // method if (!isSecured) { for (final AnnotatedMethod<? super X> m : type.getMethods()) { if (m.isAnnotationPresent(Secures.class)) { registerAuthorizer(m); continue; } for (final Annotation annotation : m.getAnnotations()) { if (SecurityUtils.isMetaAnnotatedWithSecurityBindingType(annotation)) { if (builder == null) { builder = new AnnotatedTypeBuilder<X>().readFromType(type); } builder.addToMethod(m, INTERCEPTOR_BINDING); getMetaDataStorage().addSecuredMethod(m); break; } } } } if (builder != null) { event.setAnnotatedType(builder.create()); } } public void validateBindings(@Observes AfterBeanDiscovery event, BeanManager beanManager) { if (!isActivated) { return; } SecurityMetaDataStorage metaDataStorage = getMetaDataStorage(); metaDataStorage.registerSecuredMethods(); for (final AnnotatedMethod<?> method : metaDataStorage.getSecuredMethods()) { // Here we simply want to validate that each method that is annotated with // one or more security bindings has a valid authorizer for each binding Class<?> targetClass = method.getDeclaringType().getJavaClass(); Method targetMethod = method.getJavaMember(); for (final Annotation annotation : SecurityUtils.getSecurityBindingTypes(targetClass, targetMethod)) { boolean found = false; Set<AuthorizationParameter> authorizationParameters = new HashSet<AuthorizationParameter>(); for (AnnotatedParameter<?> parameter : (List<AnnotatedParameter<?>>) (List<?>) method.getParameters()) { Set<Annotation> securityParameterBindings = null; for (Annotation a : parameter.getAnnotations()) { if (SecurityUtils.isMetaAnnotatedWithSecurityParameterBinding(a)) { if (securityParameterBindings == null) { securityParameterBindings = new HashSet<Annotation>(); } securityParameterBindings.add(a); } } if (securityParameterBindings != null) { AuthorizationParameter authorizationParameter = new AuthorizationParameter(parameter.getBaseType(), securityParameterBindings); authorizationParameters.add(authorizationParameter); } } // Validate the authorizer for (Authorizer auth : metaDataStorage.getAuthorizers()) { if (auth.matchesBindings(annotation, authorizationParameters, targetMethod.getReturnType())) { found = true; break; } } if (!found) { event.addDefinitionError(new SecurityDefinitionException("Secured type " + method.getDeclaringType().getJavaClass().getName() + " has no matching authorizer method for security binding @" + annotation.annotationType().getName())); } } for (final Annotation annotation : method.getAnnotations()) { if (SecurityUtils.isMetaAnnotatedWithSecurityBindingType(annotation)) { metaDataStorage.registerSecuredMethod(targetClass, targetMethod); break; } } } // Clear securedTypes, we don't require it any more metaDataStorage.resetSecuredMethods(); } /** * Registers the specified authorizer method (i.e. a method annotated with * the @Secures annotation) * * @throws SecurityDefinitionException */ private void registerAuthorizer(AnnotatedMethod<?> annotatedMethod) { if (!annotatedMethod.getJavaMember().getReturnType().equals(Boolean.class) && !annotatedMethod.getJavaMember().getReturnType().equals(Boolean.TYPE)) { throw new SecurityDefinitionException("Invalid authorizer method [" + annotatedMethod.getJavaMember().getDeclaringClass().getName() + "." + annotatedMethod.getJavaMember().getName() + "] - does not return a boolean."); } // Locate the binding type Annotation binding = null; for (Annotation annotation : annotatedMethod.getAnnotations()) { if (SecurityUtils.isMetaAnnotatedWithSecurityBindingType(annotation)) { if (binding != null) { throw new SecurityDefinitionException("Invalid authorizer method [" + annotatedMethod.getJavaMember().getDeclaringClass().getName() + "." + annotatedMethod.getJavaMember().getName() + "] - declares multiple security binding types"); } binding = annotation; } } Authorizer authorizer = new Authorizer(binding, annotatedMethod); getMetaDataStorage().addAuthorizer(authorizer); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper.internal; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.ParseContext; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import static org.elasticsearch.common.xcontent.support.XContentMapValues.lenientNodeBooleanValue; /** * A mapper that indexes the field names of a document under <code>_field_names</code>. This mapper is typically useful in order * to have fast <code>exists</code> and <code>missing</code> queries/filters. * * Added in Elasticsearch 1.3. */ public class FieldNamesFieldMapper extends MetadataFieldMapper { public static final String NAME = "_field_names"; public static final String CONTENT_TYPE = "_field_names"; public static class Defaults { public static final String NAME = FieldNamesFieldMapper.NAME; public static final boolean ENABLED = true; public static final MappedFieldType FIELD_TYPE = new FieldNamesFieldType(); static { FIELD_TYPE.setIndexOptions(IndexOptions.DOCS); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setStored(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.setSearchAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.setName(NAME); FIELD_TYPE.freeze(); } } public static class Builder extends MetadataFieldMapper.Builder<Builder, FieldNamesFieldMapper> { private boolean enabled = Defaults.ENABLED; public Builder(MappedFieldType existing) { super(Defaults.NAME, existing == null ? Defaults.FIELD_TYPE : existing, Defaults.FIELD_TYPE); indexName = Defaults.NAME; } @Override @Deprecated public Builder index(boolean index) { enabled(index); return super.index(index); } public Builder enabled(boolean enabled) { this.enabled = enabled; return this; } @Override public FieldNamesFieldMapper build(BuilderContext context) { setupFieldType(context); fieldType.setHasDocValues(false); FieldNamesFieldType fieldNamesFieldType = (FieldNamesFieldType)fieldType; fieldNamesFieldType.setEnabled(enabled); return new FieldNamesFieldMapper(fieldType, context.indexSettings()); } } public static class TypeParser implements MetadataFieldMapper.TypeParser { @Override public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Builder builder = new Builder(parserContext.mapperService().fullName(NAME)); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { builder.enabled(lenientNodeBooleanValue(fieldNode)); iterator.remove(); } } return builder; } @Override public MetadataFieldMapper getDefault(Settings indexSettings, MappedFieldType fieldType, String typeName) { return new FieldNamesFieldMapper(indexSettings, fieldType); } } public static final class FieldNamesFieldType extends MappedFieldType { private boolean enabled = Defaults.ENABLED; public FieldNamesFieldType() { setFieldDataType(new FieldDataType("string")); } protected FieldNamesFieldType(FieldNamesFieldType ref) { super(ref); this.enabled = ref.enabled; } @Override public FieldNamesFieldType clone() { return new FieldNamesFieldType(this); } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; FieldNamesFieldType that = (FieldNamesFieldType) o; return enabled == that.enabled; } @Override public int hashCode() { return Objects.hash(super.hashCode(), enabled); } @Override public String typeName() { return CONTENT_TYPE; } @Override public void checkCompatibility(MappedFieldType fieldType, List<String> conflicts, boolean strict) { super.checkCompatibility(fieldType, conflicts, strict); if (strict) { FieldNamesFieldType other = (FieldNamesFieldType)fieldType; if (isEnabled() != other.isEnabled()) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [enabled] across all types."); } } } public void setEnabled(boolean enabled) { checkIfFrozen(); this.enabled = enabled; } public boolean isEnabled() { return enabled; } @Override public String value(Object value) { if (value == null) { return null; } return value.toString(); } @Override public boolean useTermQueryWithQueryString() { return true; } } private FieldNamesFieldMapper(Settings indexSettings, MappedFieldType existing) { this(existing == null ? Defaults.FIELD_TYPE.clone() : existing.clone(), indexSettings); } private FieldNamesFieldMapper(MappedFieldType fieldType, Settings indexSettings) { super(NAME, fieldType, Defaults.FIELD_TYPE, indexSettings); } @Override public FieldNamesFieldType fieldType() { return (FieldNamesFieldType) super.fieldType(); } @Override public void preParse(ParseContext context) throws IOException { } @Override public void postParse(ParseContext context) throws IOException { super.parse(context); } @Override public Mapper parse(ParseContext context) throws IOException { // we parse in post parse return null; } static Iterable<String> extractFieldNames(final String fullPath) { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { int endIndex = nextEndIndex(0); private int nextEndIndex(int index) { while (index < fullPath.length() && fullPath.charAt(index) != '.') { index += 1; } return index; } @Override public boolean hasNext() { return endIndex <= fullPath.length(); } @Override public String next() { final String result = fullPath.substring(0, endIndex); endIndex = nextEndIndex(endIndex + 1); return result; } @Override public final void remove() { throw new UnsupportedOperationException(); } }; } }; } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { if (fieldType().isEnabled() == false) { return; } for (ParseContext.Document document : context.docs()) { final List<String> paths = new ArrayList<>(); for (IndexableField field : document.getFields()) { paths.add(field.name()); } for (String path : paths) { for (String fieldName : extractFieldNames(path)) { if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { document.add(new Field(fieldType().name(), fieldName, fieldType())); } } } } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { boolean includeDefaults = params.paramAsBoolean("include_defaults", false); if (includeDefaults == false && fieldType().isEnabled() == Defaults.ENABLED) { return builder; } builder.startObject(NAME); if (includeDefaults || fieldType().isEnabled() != Defaults.ENABLED) { builder.field("enabled", fieldType().isEnabled()); } builder.endObject(); return builder; } @Override public boolean isGenerated() { return true; } }
/* * Copyright (C) 2010 Moduad Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.Future; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Registration; import org.jivesoftware.smack.provider.ProviderManager; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Handler; import android.util.Log; /** * This class is to manage the XMPP connection between client and server. * * @author Sehwan Noh (devnoh@gmail.com) */ public class XmppManager { private static final String LOGTAG = LogUtil.makeLogTag(XmppManager.class); private static final String XMPP_RESOURCE_NAME = "AndroidpnClient"; private Context context; private NotificationService.TaskSubmitter taskSubmitter; private NotificationService.TaskTracker taskTracker; private SharedPreferences sharedPrefs; private String xmppHost; private int xmppPort; private XMPPConnection connection; private String username; private String password; private ConnectionListener connectionListener; private PacketListener notificationPacketListener; private Handler handler; private List<Runnable> taskList; private boolean running = false; private Future<?> futureTask; private Thread reconnection; public XmppManager(NotificationService notificationService) { context = notificationService; taskSubmitter = notificationService.getTaskSubmitter(); taskTracker = notificationService.getTaskTracker(); sharedPrefs = notificationService.getSharedPreferences(); xmppHost = sharedPrefs.getString(Constants.XMPP_HOST, "localhost"); xmppPort = sharedPrefs.getInt(Constants.XMPP_PORT, 5222); username = sharedPrefs.getString(Constants.XMPP_USERNAME, ""); password = sharedPrefs.getString(Constants.XMPP_PASSWORD, ""); connectionListener = new PersistentConnectionListener(this); notificationPacketListener = new NotificationPacketListener(this); handler = new Handler(); taskList = new ArrayList<Runnable>(); reconnection = new ReconnectionThread(this); } public Context getContext() { return context; } public void connect() { Log.d(LOGTAG, "connect()..."); submitLoginTask(); } public void disconnect() { Log.d(LOGTAG, "disconnect()..."); terminatePersistentConnection(); } public void terminatePersistentConnection() { Log.d(LOGTAG, "terminatePersistentConnection()..."); Runnable runnable = new Runnable() { final XmppManager xmppManager = XmppManager.this; public void run() { if (xmppManager.isConnected()) { Log.d(LOGTAG, "terminatePersistentConnection()... run()"); xmppManager.getConnection().removePacketListener( xmppManager.getNotificationPacketListener()); xmppManager.getConnection().disconnect(); } xmppManager.runTask(); } }; addTask(runnable); } public XMPPConnection getConnection() { return connection; } public void setConnection(XMPPConnection connection) { this.connection = connection; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public ConnectionListener getConnectionListener() { return connectionListener; } public PacketListener getNotificationPacketListener() { return notificationPacketListener; } public void startReconnectionThread() { synchronized (reconnection) { if (reconnection == null || !reconnection.isAlive()) { reconnection = new ReconnectionThread(this); reconnection.setName("Xmpp Reconnection Thread"); reconnection.start(); } } } public Handler getHandler() { return handler; } public void reregisterAccount() { removeAccount(); submitLoginTask(); runTask(); } public List<Runnable> getTaskList() { return taskList; } public Future<?> getFutureTask() { return futureTask; } public void runTask() { Log.d(LOGTAG, "runTask()..."); synchronized (taskList) { running = false; futureTask = null; if (!taskList.isEmpty()) { Runnable runnable = (Runnable) taskList.get(0); taskList.remove(0); running = true; futureTask = taskSubmitter.submit(runnable); if (futureTask == null) { taskTracker.decrease(); } } } taskTracker.decrease(); Log.d(LOGTAG, "runTask()...done"); } private String newRandomUUID() { String uuidRaw = UUID.randomUUID().toString(); return uuidRaw.replaceAll("-", ""); } private boolean isConnected() { return connection != null && connection.isConnected(); } private boolean isAuthenticated() { return connection != null && connection.isConnected() && connection.isAuthenticated(); } private boolean isRegistered() { return sharedPrefs.contains(Constants.XMPP_USERNAME) && sharedPrefs.contains(Constants.XMPP_PASSWORD); } private void submitConnectTask() { Log.d(LOGTAG, "submitConnectTask()..."); addTask(new ConnectTask()); } private void submitRegisterTask() { Log.d(LOGTAG, "submitRegisterTask()..."); submitConnectTask(); addTask(new RegisterTask()); } private void submitLoginTask() { Log.d(LOGTAG, "submitLoginTask()..."); submitRegisterTask(); addTask(new LoginTask()); } private void addTask(Runnable runnable) { Log.d(LOGTAG, "addTask(runnable)..."); taskTracker.increase(); synchronized (taskList) { if (taskList.isEmpty() && !running) { running = true; futureTask = taskSubmitter.submit(runnable); if (futureTask == null) { taskTracker.decrease(); } } else { taskList.add(runnable); } } Log.d(LOGTAG, "addTask(runnable)... done"); } private void removeAccount() { Editor editor = sharedPrefs.edit(); editor.remove(Constants.XMPP_USERNAME); editor.remove(Constants.XMPP_PASSWORD); editor.commit(); } private void dropTask(int dropCount) { synchronized (taskList) { if (taskList.size() >= dropCount) { for (int i = 0; i < dropCount; i++) { taskList.remove(0); taskTracker.decrease(); } } } } /** * A runnable task to connect the server. */ private class ConnectTask implements Runnable { final XmppManager xmppManager; private ConnectTask() { this.xmppManager = XmppManager.this; } public void run() { Log.i(LOGTAG, "ConnectTask.run()..."); if (!xmppManager.isConnected()) { // Create the configuration for this new connection ConnectionConfiguration connConfig = new ConnectionConfiguration( xmppHost, xmppPort); // connConfig.setSecurityMode(SecurityMode.disabled); connConfig.setSecurityMode(SecurityMode.required); connConfig.setSASLAuthenticationEnabled(false); connConfig.setCompressionEnabled(false); XMPPConnection connection = new XMPPConnection(connConfig); xmppManager.setConnection(connection); try { // Connect to the server connection.connect(); Log.i(LOGTAG, "XMPP connected successfully"); // packet provider ProviderManager.getInstance().addIQProvider("notification", "androidpn:iq:notification", new NotificationIQProvider()); xmppManager.runTask(); } catch (XMPPException e) { Log.e(LOGTAG, "XMPP connection failed", e); xmppManager.dropTask(2); xmppManager.runTask(); xmppManager.startReconnectionThread(); } } else { Log.i(LOGTAG, "XMPP connected already"); xmppManager.runTask(); } } } /** * A runnable task to register a new user onto the server. */ private class RegisterTask implements Runnable { final XmppManager xmppManager; boolean isRegisterSucceed; boolean hasDropTask; private RegisterTask() { xmppManager = XmppManager.this; isRegisterSucceed = false; hasDropTask = false; } public void run() { Log.i(LOGTAG, "RegisterTask.run()..."); if (!xmppManager.isRegistered()) { final String newUsername = newRandomUUID(); final String newPassword = newRandomUUID(); Registration registration = new Registration(); PacketFilter packetFilter = new AndFilter(new PacketIDFilter( registration.getPacketID()), new PacketTypeFilter( IQ.class)); PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) { synchronized (xmppManager) { Log.d("RegisterTask.PacketListener", "processPacket()....."); Log.d("RegisterTask.PacketListener", "packet=" + packet.toXML()); if (packet instanceof IQ) { IQ response = (IQ) packet; if (response.getType() == IQ.Type.ERROR) { if (!response.getError().toString().contains( "409")) { Log.e(LOGTAG, "Unknown error while registering XMPP account! " + response.getError() .getCondition()); } } else if (response.getType() == IQ.Type.RESULT) { xmppManager.setUsername(newUsername); xmppManager.setPassword(newPassword); Log.d(LOGTAG, "username=" + newUsername); Log.d(LOGTAG, "password=" + newPassword); Editor editor = sharedPrefs.edit(); editor.putString(Constants.XMPP_USERNAME, newUsername); editor.putString(Constants.XMPP_PASSWORD, newPassword); editor.commit(); isRegisterSucceed = true; Log .i(LOGTAG, "Account registered successfully"); if (!hasDropTask) { xmppManager.runTask(); } } } } } }; connection.addPacketListener(packetListener, packetFilter); registration.setType(IQ.Type.SET); // registration.setTo(xmppHost); // Map<String, String> attributes = new HashMap<String, String>(); // attributes.put("username", rUsername); // attributes.put("password", rPassword); // registration.setAttributes(attributes); registration.addAttribute("username", newUsername); registration.addAttribute("password", newPassword); connection.sendPacket(registration); try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (xmppManager) { if (!isRegisterSucceed) { xmppManager.dropTask(1); xmppManager.runTask(); xmppManager.startReconnectionThread(); hasDropTask = true; } } } else { Log.i(LOGTAG, "Account registered already"); xmppManager.runTask(); } } } /** * A runnable task to log into the server. */ private class LoginTask implements Runnable { final XmppManager xmppManager; private LoginTask() { this.xmppManager = XmppManager.this; } public void run() { Log.i(LOGTAG, "LoginTask.run()..."); if (!xmppManager.isAuthenticated()) { Log.d(LOGTAG, "username=" + username); Log.d(LOGTAG, "password=" + password); try { xmppManager.getConnection().login( xmppManager.getUsername(), xmppManager.getPassword(), XMPP_RESOURCE_NAME); Log.d(LOGTAG, "Loggedn in successfully"); // connection listener if (xmppManager.getConnectionListener() != null) { xmppManager.getConnection().addConnectionListener( xmppManager.getConnectionListener()); } // packet filter PacketFilter packetFilter = new PacketTypeFilter( NotificationIQ.class); // packet listener PacketListener packetListener = xmppManager .getNotificationPacketListener(); connection.addPacketListener(packetListener, packetFilter); connection.startHeartBeat(); } catch (XMPPException e) { Log.e(LOGTAG, "LoginTask.run()... xmpp error"); Log.e(LOGTAG, "Failed to login to xmpp server. Caused by: " + e.getMessage()); String INVALID_CREDENTIALS_ERROR_CODE = "401"; String errorMessage = e.getMessage(); if (errorMessage != null && errorMessage .contains(INVALID_CREDENTIALS_ERROR_CODE)) { xmppManager.reregisterAccount(); return; } xmppManager.startReconnectionThread(); } catch (Exception e) { Log.e(LOGTAG, "LoginTask.run()... other error"); Log.e(LOGTAG, "Failed to login to xmpp server. Caused by: " + e.getMessage()); xmppManager.startReconnectionThread(); } finally { xmppManager.runTask(); } } else { Log.i(LOGTAG, "Logged in already"); xmppManager.runTask(); } } } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2017_10_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in LoadBalancerBackendAddressPools. */ public class LoadBalancerBackendAddressPoolsInner { /** The Retrofit service to perform REST calls. */ private LoadBalancerBackendAddressPoolsService service; /** The service client containing this operation class. */ private NetworkManagementClientImpl client; /** * Initializes an instance of LoadBalancerBackendAddressPoolsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public LoadBalancerBackendAddressPoolsInner(Retrofit retrofit, NetworkManagementClientImpl client) { this.service = retrofit.create(LoadBalancerBackendAddressPoolsService.class); this.client = client; } /** * The interface defining all the services for LoadBalancerBackendAddressPools to be * used by Retrofit to perform actually REST calls. */ interface LoadBalancerBackendAddressPoolsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2017_10_01.LoadBalancerBackendAddressPools list" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools") Observable<Response<ResponseBody>> list(@Path("resourceGroupName") String resourceGroupName, @Path("loadBalancerName") String loadBalancerName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2017_10_01.LoadBalancerBackendAddressPools get" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}") Observable<Response<ResponseBody>> get(@Path("resourceGroupName") String resourceGroupName, @Path("loadBalancerName") String loadBalancerName, @Path("backendAddressPoolName") String backendAddressPoolName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2017_10_01.LoadBalancerBackendAddressPools listNext" }) @GET Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Gets all the load balancer backed address pools. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;BackendAddressPoolInner&gt; object if successful. */ public PagedList<BackendAddressPoolInner> list(final String resourceGroupName, final String loadBalancerName) { ServiceResponse<Page<BackendAddressPoolInner>> response = listSinglePageAsync(resourceGroupName, loadBalancerName).toBlocking().single(); return new PagedList<BackendAddressPoolInner>(response.body()) { @Override public Page<BackendAddressPoolInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets all the load balancer backed address pools. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<BackendAddressPoolInner>> listAsync(final String resourceGroupName, final String loadBalancerName, final ListOperationCallback<BackendAddressPoolInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSinglePageAsync(resourceGroupName, loadBalancerName), new Func1<String, Observable<ServiceResponse<Page<BackendAddressPoolInner>>>>() { @Override public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets all the load balancer backed address pools. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BackendAddressPoolInner&gt; object */ public Observable<Page<BackendAddressPoolInner>> listAsync(final String resourceGroupName, final String loadBalancerName) { return listWithServiceResponseAsync(resourceGroupName, loadBalancerName) .map(new Func1<ServiceResponse<Page<BackendAddressPoolInner>>, Page<BackendAddressPoolInner>>() { @Override public Page<BackendAddressPoolInner> call(ServiceResponse<Page<BackendAddressPoolInner>> response) { return response.body(); } }); } /** * Gets all the load balancer backed address pools. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BackendAddressPoolInner&gt; object */ public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> listWithServiceResponseAsync(final String resourceGroupName, final String loadBalancerName) { return listSinglePageAsync(resourceGroupName, loadBalancerName) .concatMap(new Func1<ServiceResponse<Page<BackendAddressPoolInner>>, Observable<ServiceResponse<Page<BackendAddressPoolInner>>>>() { @Override public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> call(ServiceResponse<Page<BackendAddressPoolInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets all the load balancer backed address pools. * ServiceResponse<PageImpl<BackendAddressPoolInner>> * @param resourceGroupName The name of the resource group. ServiceResponse<PageImpl<BackendAddressPoolInner>> * @param loadBalancerName The name of the load balancer. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;BackendAddressPoolInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> listSinglePageAsync(final String resourceGroupName, final String loadBalancerName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (loadBalancerName == null) { throw new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String apiVersion = "2017-10-01"; return service.list(resourceGroupName, loadBalancerName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BackendAddressPoolInner>>>>() { @Override public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<BackendAddressPoolInner>> result = listDelegate(response); return Observable.just(new ServiceResponse<Page<BackendAddressPoolInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<BackendAddressPoolInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<BackendAddressPoolInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<BackendAddressPoolInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets load balancer backend address pool. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the BackendAddressPoolInner object if successful. */ public BackendAddressPoolInner get(String resourceGroupName, String loadBalancerName, String backendAddressPoolName) { return getWithServiceResponseAsync(resourceGroupName, loadBalancerName, backendAddressPoolName).toBlocking().single().body(); } /** * Gets load balancer backend address pool. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<BackendAddressPoolInner> getAsync(String resourceGroupName, String loadBalancerName, String backendAddressPoolName, final ServiceCallback<BackendAddressPoolInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, loadBalancerName, backendAddressPoolName), serviceCallback); } /** * Gets load balancer backend address pool. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the BackendAddressPoolInner object */ public Observable<BackendAddressPoolInner> getAsync(String resourceGroupName, String loadBalancerName, String backendAddressPoolName) { return getWithServiceResponseAsync(resourceGroupName, loadBalancerName, backendAddressPoolName).map(new Func1<ServiceResponse<BackendAddressPoolInner>, BackendAddressPoolInner>() { @Override public BackendAddressPoolInner call(ServiceResponse<BackendAddressPoolInner> response) { return response.body(); } }); } /** * Gets load balancer backend address pool. * * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the BackendAddressPoolInner object */ public Observable<ServiceResponse<BackendAddressPoolInner>> getWithServiceResponseAsync(String resourceGroupName, String loadBalancerName, String backendAddressPoolName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (loadBalancerName == null) { throw new IllegalArgumentException("Parameter loadBalancerName is required and cannot be null."); } if (backendAddressPoolName == null) { throw new IllegalArgumentException("Parameter backendAddressPoolName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String apiVersion = "2017-10-01"; return service.get(resourceGroupName, loadBalancerName, backendAddressPoolName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<BackendAddressPoolInner>>>() { @Override public Observable<ServiceResponse<BackendAddressPoolInner>> call(Response<ResponseBody> response) { try { ServiceResponse<BackendAddressPoolInner> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<BackendAddressPoolInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<BackendAddressPoolInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<BackendAddressPoolInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets all the load balancer backed address pools. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;BackendAddressPoolInner&gt; object if successful. */ public PagedList<BackendAddressPoolInner> listNext(final String nextPageLink) { ServiceResponse<Page<BackendAddressPoolInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<BackendAddressPoolInner>(response.body()) { @Override public Page<BackendAddressPoolInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets all the load balancer backed address pools. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<BackendAddressPoolInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<BackendAddressPoolInner>> serviceFuture, final ListOperationCallback<BackendAddressPoolInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<BackendAddressPoolInner>>>>() { @Override public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets all the load balancer backed address pools. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BackendAddressPoolInner&gt; object */ public Observable<Page<BackendAddressPoolInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<BackendAddressPoolInner>>, Page<BackendAddressPoolInner>>() { @Override public Page<BackendAddressPoolInner> call(ServiceResponse<Page<BackendAddressPoolInner>> response) { return response.body(); } }); } /** * Gets all the load balancer backed address pools. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BackendAddressPoolInner&gt; object */ public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> listNextWithServiceResponseAsync(final String nextPageLink) { return listNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<BackendAddressPoolInner>>, Observable<ServiceResponse<Page<BackendAddressPoolInner>>>>() { @Override public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> call(ServiceResponse<Page<BackendAddressPoolInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets all the load balancer backed address pools. * ServiceResponse<PageImpl<BackendAddressPoolInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;BackendAddressPoolInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> listNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BackendAddressPoolInner>>>>() { @Override public Observable<ServiceResponse<Page<BackendAddressPoolInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<BackendAddressPoolInner>> result = listNextDelegate(response); return Observable.just(new ServiceResponse<Page<BackendAddressPoolInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<BackendAddressPoolInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<BackendAddressPoolInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<BackendAddressPoolInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } }
/* * Copyright 2015 Francois Steyn - Adept Internet (PTY) LTD (francois.s@adept.co.za). * * 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.adeptnet.jmx.addons.mikrotik; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import me.legrange.mikrotik.ApiConnection; import me.legrange.mikrotik.MikrotikApiException; /** * * @author Francois Steyn - Adept Internet (PTY) LTD (francois.s@adept.co.za) */ public class Bean implements BeanInterface { private static final Logger LOG = Logger.getLogger(Bean.class.getName()); private static final BeanData datas = new BeanData(); private final MapThread mapThread; private final Thread thread; public static class MapThread implements Runnable { private boolean running; public boolean isRunning() { return running; } public void setRunning(final boolean running) { this.running = running; } @Override public void run() { long current; long lastUsed; BeanData.Record record; try { while (isRunning()) { synchronized (datas) { current = System.currentTimeMillis(); LOG.log(Level.FINE, "mapThread Running: {0}", datas.getMap().size()); for (Iterator<String> keys = datas.getMap().keySet().iterator(); keys.hasNext();) { final String key = keys.next(); record = datas.getMap().get(key); lastUsed = current - record.getLastUsed(); //LOG.info(String.format("%s: %d", key, lastUsed)); if (lastUsed > 30 * 60 * 1000) { LOG.log(Level.INFO, "Removing old Reference: {0}", key); keys.remove(); } } } Thread.sleep(60 * 1000); } } catch (InterruptedException ex) { if (isRunning()) { LOG.log(Level.SEVERE, "mapThread", ex); } } } } public Bean() { mapThread = new MapThread(); thread = new Thread(mapThread); thread.setDaemon(true); mapThread.setRunning(true); } public void start() { thread.start(); } public void stop() { mapThread.setRunning(false); thread.interrupt(); } private BeanData.Record getRecord(final String reference) { synchronized (datas) { if (!datas.hasRecord(reference)) { throw new java.lang.NullPointerException("record is NULL, call loadFromAPI()"); } return datas.getRecord(reference); } } private void setRecord(final String reference, final List<Map<String, String>> data) { synchronized (data) { datas.setRecord(reference, data); } } private void loadFromConnection(final String reference, final ApiConnection con, final String user, final String password, final String cmd) throws MikrotikApiException { con.login(user, password); final List<Map<String, String>> data = con.execute(cmd); setRecord(reference, data); } @Override public void loadFromAPI(final String reference, final String host, final String user, final String password, final String cmd) throws IOException { loadFromAPI(reference, host, user, password, cmd, ApiConnection.DEFAULT_PORT); } @Override public void loadFromAPI(final String reference, final String host, final String user, final String password, final String cmd, final int port) throws IOException { loadFromAPI(reference, host, user, password, cmd, port, ApiConnection.DEFAULT_CONNECTION_TIMEOUT); } @Override public void loadFromAPI(final String reference, final String host, final String user, final String password, final String cmd, final int port, final int timeout) throws IOException { try { try (final ApiConnection con = ApiConnection.connect(SocketFactory.getDefault(), host, port, timeout)) { loadFromConnection(reference, con, user, password, cmd); } } catch (MikrotikApiException ex) { throw new IOException(ex); } } @Override public void loadFromAPITLS(final String reference, final String host, final String user, final String password, final String cmd) throws IOException { loadFromAPITLS(reference, host, user, password, cmd, ApiConnection.DEFAULT_TLS_PORT); } @Override public void loadFromAPITLS(final String reference, final String host, final String user, final String password, final String cmd, final int port) throws IOException { loadFromAPITLS(reference, host, user, password, cmd, port, ApiConnection.DEFAULT_CONNECTION_TIMEOUT); } @Override public void loadFromAPITLS(final String reference, final String host, final String user, final String password, final String cmd, final int port, final int timeout) throws IOException { try { try (final ApiConnection con = ApiConnection.connect(SSLSocketFactory.getDefault(), host, port, timeout)) { loadFromConnection(reference, con, user, password, cmd); } } catch (MikrotikApiException ex) { throw new IOException(ex); } } @Override public String asString(final String reference, final String matchName, final String matchValue, final String returnName) { final Map<String, String> map = asListEntry(reference, matchName, matchValue); if (!map.containsKey(returnName)) { throw new java.lang.NullPointerException(String.format("Cannot find %s in map", returnName)); } return map.get(returnName); } @Override public int asInt(final String reference, final String matchName, final String matchValue, final String returnName) { return Integer.valueOf(asString(reference, matchName, matchValue, returnName)); } @Override public List<Map<String, String>> asList(final String reference) { return getRecord(reference).getList(); } @Override public Map<String, String> asListEntry(final String reference, final String matchName, final String matchValue) { if (matchValue == null) { throw new java.lang.NullPointerException("matchValue is NULL"); } final List<Map<String, String>> list = asList(reference); for (final Map<String, String> data : list) { if (!data.containsKey(matchName)) { continue; } if (!matchValue.equalsIgnoreCase(data.get(matchName))) { continue; } return data; } throw new java.lang.NullPointerException(String.format("Cannot find %s in list", matchName)); } }
/* * 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. */ package com.google.sample.eddystoneurlconfigvalidator; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.ParcelUuid; import android.util.Log; import org.uribeacon.beacon.UriBeacon; import org.uribeacon.config.ProtocolV2; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; public class TestHelper { // Constants private static final String TAG = TestHelper.class.getCanonicalName(); private final long SCAN_TIMEOUT = TimeUnit.SECONDS.toMillis(5); // BLE Scan callback private final ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); if (mBluetoothDevice != null) { Log.d(TAG, "Looking for: " + mBluetoothDevice.getAddress()); } Log.d(TAG, "On scan Result: " + result.getDevice().getAddress()); // First time we see the beacon if(mScanResultSet.add(result.getDevice())) { mScanResults.add(result); } } }; // Gatt Variables private BluetoothGatt mGatt; private BluetoothGattService mService; private BluetoothDevice mBluetoothDevice; private final UUID mServiceUuid; //TODO: It seems that to maintain connection between tests a better idea would be to extract the Gatt service to the Test Runner private BluetoothGattCallback mOutSideGattCallback; private final BluetoothAdapter mBluetoothAdapter; public final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { super.onConnectionStateChange(gatt, status, newState); Log.d(TAG, "Status: " + status + "; New State: " + newState); mGatt = gatt; if (status == BluetoothGatt.GATT_SUCCESS) { if (newState == BluetoothProfile.STATE_CONNECTED) { mGatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { if (!failed) { mTestActions.remove(); disconnected = true; mGatt = null; dispatch(); } } } else { if (newState == BluetoothProfile.STATE_DISCONNECTED) { mGatt = null; } fail("Failed. Status: " + status + ". New State: " + newState); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); Log.d(TAG, "On services discovered"); mGatt = gatt; mService = mGatt.getService(mServiceUuid); if (mTestActions.peek().actionType == TestAction.CONNECT) { mTestActions.remove(); } mTestCallback.connectedToBeacon(); dispatch(); } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicRead(gatt, characteristic, status); Log.d(TAG, "On characteristic read"); mGatt = gatt; TestAction readTest = mTestActions.peek(); byte[] value = characteristic.getValue(); int actionType = readTest.actionType; if (readTest.expectedReturnCode != status) { fail("Incorrect status code: " + status + ". Expected: " + readTest.expectedReturnCode); } else if (actionType == TestAction.ASSERT_NOT_EQUALS && Arrays.equals(readTest.transmittedValue, value)) { fail("Values read are the same: " + Arrays.toString(value)); } else if (actionType == TestAction.ASSERT && !Arrays.equals(readTest.transmittedValue, value)) { fail("Result not the same. Expected: " + Arrays.toString(readTest.transmittedValue) + ". Received: " + Arrays.toString(value)); } else { mTestActions.remove(); dispatch(); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); Log.d(TAG, "On write"); mGatt = gatt; TestAction writeTest = mTestActions.peek(); int actionType = writeTest.actionType; if (actionType == TestAction.WRITE && writeTest.expectedReturnCode != status) { fail("Incorrect status code: " + status + ". Expected: " + writeTest.expectedReturnCode); } else if (actionType == TestAction.MULTIPLE_VALID_RETURN_CODES) { boolean match = false; for (int expected : writeTest.expectedReturnCodes) { if (expected == status) { match = true; } } if (!match) { fail("Error code didn't match any of the expected error codes."); } else { mTestActions.remove(); dispatch(); } } else { mTestActions.remove(); dispatch(); } } }; // Test Information private final String mName; private final String mReference; private final Context mContext; private HashSet<BluetoothDevice> mScanResultSet; private ArrayList<ScanResult> mScanResults; private LinkedList<TestAction> mTestActions; private final LinkedList<TestAction> mTestSteps; // Test State //TODO: there is probably no need to have so many variables. Defining states would be better. private boolean started; private boolean failed; private boolean finished; private boolean disconnected; private boolean stopped; private final TestCallback mTestCallback; private final Handler mHandler; private TestHelper( String name, String reference, Context context, UUID serviceUuid, TestCallback testCallback, LinkedList<TestAction> testActions, LinkedList<TestAction> testSteps) { mName = name; mReference = reference; mContext = context; mServiceUuid = serviceUuid; mTestCallback = testCallback; mTestActions = testActions; mTestSteps = testSteps; final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); mHandler = new Handler(Looper.myLooper()); } /** * @return name of the test */ public String getName() { return mName; } /** * @return A link to the reference in the spec regarding the correct behavior */ public String getReference() { return mReference; } /** * @return a linked list containing the tests */ public LinkedList<TestAction> getTestSteps() { return mTestSteps; } /** * @return whether the test failed or not */ public boolean isFailed() { return failed; } /** * @return whether or not the test has started */ public boolean isStarted() { return started; } /** * Start running the test * @param bluetoothDevice device to connect for the test. If no device is present the TestHelper * will scan for nearby beacons in config mode * @param gatt gatt connection if available. If no gatt connection is available the TestHelper * will try to connect to the bluetoothDevice * @param outsideCallback Outside callback for the gatt connection */ public void run(BluetoothDevice bluetoothDevice, BluetoothGatt gatt, BluetoothGattCallback outsideCallback) { Log.d(TAG, "Run Called for: " + getName()); // Reset Test state started = true; failed = false; finished = false; disconnected = false; stopped = false; // Initialize new list for results mScanResults = new ArrayList<>(); mScanResultSet = new HashSet<>(); mBluetoothDevice = bluetoothDevice; mGatt = gatt; if (mGatt != null) { mService = gatt.getService(mServiceUuid); } mOutSideGattCallback = outsideCallback; // Notify test started mTestCallback.testStarted(); dispatch(); } private void connectToGatt() { Log.d(TAG, "Connecting"); // If the test just disconnected from the beacon, wait a second // otherwise the connection will fail. if (disconnected) { try { disconnected = false; TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } // Notify runner that the test is currently waiting for a beacon mTestCallback.waitingForConfigMode(); // If there is no device defined scan for a beacon to connect to if (mBluetoothDevice == null) { scanForConfigBeacon(); } else { mBluetoothDevice.connectGatt(mContext, false, mOutSideGattCallback); } } private void readFromGatt() { Log.d(TAG, "reading"); TestAction readTest = mTestActions.peek(); BluetoothGattCharacteristic characteristic = mService .getCharacteristic(readTest.characteristicUuid); mGatt.readCharacteristic(characteristic); } private void writeToGatt() { Log.d(TAG, "Writing"); TestAction writeTest = mTestActions.peek(); BluetoothGattCharacteristic characteristic = mService .getCharacteristic(writeTest.characteristicUuid); // WriteType is WRITE_TYPE_NO_RESPONSE even though the one that requests a response // is called WRITE_TYPE_DEFAULT! if (characteristic.getWriteType() != BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) { Log.w(TAG, "writeCharacteristic default WriteType is being forced to WRITE_TYPE_DEFAULT"); characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); } characteristic.setValue(writeTest.transmittedValue); mGatt.writeCharacteristic(characteristic); } private void disconnectFromGatt() { Log.d(TAG, "Disconnecting"); mGatt.disconnect(); } /** * This function is in charge of dispatching the next action in the test */ private void dispatch() { Log.d(TAG, "Dispatching"); int actionType = mTestActions.peek().actionType; // If the test is stopped and connected to the beacon // disconnect from the beacon if (stopped) { if (mGatt != null) { disconnectFromGatt(); } } else if (actionType == TestAction.LAST) { Log.d(TAG, "Last"); finished = true; // Tell the test runner that the test has been completed. // Pass both the bluetoohDevice and the gatt connection for the next test to use. mTestCallback.testCompleted(mBluetoothDevice, mGatt); } else if (actionType == TestAction.CONNECT) { Log.d(TAG, "Connect"); connectToGatt(); } else if (actionType == TestAction.ADV_FLAGS) { Log.d(TAG, "ADV FLAGS"); lookForAdv(); } else if (actionType == TestAction.ADV_TX_POWER) { Log.d(TAG, "ADV TX POWER"); lookForAdv(); } else if (actionType == TestAction.ADV_URI) { Log.d(TAG, "ADV uri"); lookForAdv(); } else if (actionType == TestAction.ADV_PACKET) { Log.d(TAG, "ADV packet"); lookForAdv(); // There was no previous test or the previous test disconnected from the beacon so need to connect again } else if (mGatt == null) { Log.d(TAG, "no gatt. connecting"); connectToGatt(); } else if (actionType == TestAction.ASSERT || actionType == TestAction.ASSERT_NOT_EQUALS) { Log.d(TAG, "Read"); readFromGatt(); } else if (actionType == TestAction.WRITE || actionType == TestAction.MULTIPLE_VALID_RETURN_CODES) { Log.d(TAG, "Write"); writeToGatt(); } else if (actionType == TestAction.DISCONNECT) { Log.d(TAG, "Disconenct"); disconnectFromGatt(); } } /** * Function to start a scan for config beacon */ private void scanForConfigBeacon() { ScanSettings settings = new ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build(); List<ScanFilter> filters = new ArrayList<>(); ScanFilter filter = new ScanFilter.Builder() .setServiceUuid(ProtocolV2.CONFIG_SERVICE_UUID) .build(); filters.add(filter); getLeScanner().startScan(filters, settings, mScanCallback); Log.d(TAG, "Looking for new config beacons"); // Stop the test after a while mHandler.postDelayed(new Runnable() { @Override public void run() { stopSearchingForBeacons(); if (mScanResults.size() == 0) { fail("No beacons in Config Mode found"); } else if (mScanResults.size() == 1) { continueTest(0); } else { // Tell the runner that there are multiple beacons available mTestCallback.multipleBeacons(mScanResults); } } }, SCAN_TIMEOUT); } /** * Function to scan for broadcasting beacons (not configurable beacons). */ private void lookForAdv() { ScanSettings settings = new ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build(); List<ScanFilter> filters = new ArrayList<>(); ScanFilter filter = new ScanFilter.Builder() .setServiceUuid(mTestActions.peek().serviceUuid) .build(); filters.add(filter); getLeScanner().startScan(filters, settings, mScanCallback); // Stop after a while mHandler.postDelayed(new Runnable() { @Override public void run() { stopSearchingForBeacons(); // If a device is defined check its packet. // Otherwise notify runner that there are multiple beacons available to test. if (mBluetoothDevice != null) { for (ScanResult scanResult : mScanResults) { if (scanResult.getDevice().getAddress().equals(mBluetoothDevice.getAddress())) { checkPacket(scanResult); return; } } fail("Could not find adv packet. Looking for address: " + mBluetoothDevice.getAddress()); } else if (mScanResults.size() == 1) { Log.d(TAG, "Continuing test"); continueTest(0); } else if (mScanResults.size() > 1) { Log.d(TAG, "Multiple beacons"); mTestCallback.multipleBeacons(mScanResults); } else { fail("Could not find adv packet"); } } }, SCAN_TIMEOUT); } // Stop BLE scanner private void stopSearchingForBeacons() { getLeScanner().stopScan(mScanCallback); } /** * Function that checks that the packet has the correct value depending on the action. * @param result ScanResult from the scanner */ private void checkPacket(ScanResult result) { mHandler.removeCallbacksAndMessages(null); stopSearchingForBeacons(); Log.d(TAG, "Found beacon"); TestAction action = mTestActions.peek(); if (action.serviceUuid == CoreEddystoneURLTests.TEST_UUID) { checkEddystoneURLPacket(result, action); } else { checkUriBeaconPacket(result, action); } } private void checkUriBeaconPacket(ScanResult result, TestAction action) { if (action.actionType == TestAction.ADV_PACKET) { if (getAdvPacket(result, action.serviceUuid).length < 2) { fail("Invalid Adv Packet"); } else { mTestActions.remove(); dispatch(); } } else if (action.actionType == TestAction.ADV_FLAGS) { byte flags = getFlags(result); byte expectedFlags = action.transmittedValue[0]; if (expectedFlags != flags) { fail("Received: " + flags + ". Expected: " + expectedFlags); } else { mTestActions.remove(); dispatch(); } } else if (action.actionType == TestAction.ADV_TX_POWER) { byte txPowerLevel = getTxPowerLevel(result); byte expectedTxPowerLevel = action.transmittedValue[0]; if (expectedTxPowerLevel != txPowerLevel) { fail("Received: " + txPowerLevel + ". Expected: " + expectedTxPowerLevel); } else { mTestActions.remove(); dispatch(); } } else if (action.actionType == TestAction.ADV_URI) { byte[] uri = getUri(result); if (!Arrays.equals(action.transmittedValue, uri)) { fail("Received: " + Arrays.toString(uri) + ". Expected: " + Arrays.toString(action.transmittedValue)); } else { mTestActions.remove(); dispatch(); } } } private void checkEddystoneURLPacket(ScanResult result, TestAction action) { Log.d(TAG, "Address: " + result.getDevice().getAddress()); List<ParcelUuid> uuids = result.getScanRecord().getServiceUuids(); Log.d(TAG, "Packet: " + Arrays.toString(getAdvPacket(result, action.serviceUuid))); if (uuids == null || !uuids.contains(action.serviceUuid)) { fail("Eddystone-URL should contain service uuid: " + action.serviceUuid); return; } byte[] advPacket = getAdvPacket(result, action.serviceUuid); if (advPacket.length < 1 || advPacket[0] != 0x10) { fail("Invalid Adv Packet: " + Arrays.toString(advPacket)); return; } if (action.actionType == TestAction.ADV_URI) { byte[] url = Arrays.copyOfRange(advPacket, 2, advPacket.length); if (!Arrays.equals(action.transmittedValue, url)) { fail("Received: " + Arrays.toString(url) + ". Expected: " + Arrays.toString(action.transmittedValue)); } } else if (action.actionType == TestAction.ADV_TX_POWER) { byte txPowerLevel = advPacket[1]; byte expectedTxPowerLevel = action.transmittedValue[0]; if (expectedTxPowerLevel != txPowerLevel) { fail("Received: " + txPowerLevel + ". Expected: " + expectedTxPowerLevel); } } mTestActions.remove(); dispatch(); } private BluetoothLeScanner getLeScanner() { return mBluetoothAdapter.getBluetoothLeScanner(); } private byte getFlags(ScanResult result) { byte[] serviceData = result.getScanRecord().getServiceData(UriBeacon.URI_SERVICE_UUID); return serviceData[0]; } private byte getTxPowerLevel(ScanResult result) { byte[] serviceData = result.getScanRecord().getServiceData(UriBeacon.URI_SERVICE_UUID); return serviceData[1]; } private byte[] getUri(ScanResult result) { byte[] serviceData = result.getScanRecord().getServiceData(UriBeacon.URI_SERVICE_UUID); // Get the uri which should start at position 2 return Arrays.copyOfRange(serviceData, 2, serviceData.length); } private byte[] getAdvPacket(ScanResult result, ParcelUuid serviceUuid) { return result.getScanRecord().getServiceData(serviceUuid); } /** * Called when a test fails * @param reason */ private void fail(String reason) { Log.d(TAG, "Failing because: " + reason); mHandler.removeCallbacksAndMessages(null); failed = true; finished = true; // Update action to failed mTestActions.peek().failed = true; mTestActions.peek().reason = reason; mTestCallback.testCompleted(mBluetoothDevice, mGatt); } public boolean isFinished() { return finished; } // Stops the current running test public void stopTest() { stopped = true; stopSearchingForBeacons(); fail("Stopped by user"); } /** * Set the new bluetooth device to run the test on * @param which */ public void continueTest(int which) { //TODO: should probably have a better name mBluetoothDevice = mScanResults.get(which).getDevice(); dispatch(); } /** * Function to repeat a test * @param outSideGattCallback gatt callback to use */ public void repeat(BluetoothGattCallback outSideGattCallback) { Log.d(TAG, "Repeating"); mTestActions = new LinkedList<>(mTestSteps); // The test should use a new gatt connection but use the previous bluetooth device if available run(mBluetoothDevice, null, outSideGattCallback); } /** * Interface to communicate the test state to the runner */ public interface TestCallback { /** * Indicate the test started */ public void testStarted(); /** * Indicate the test completed * @param deviceBeingTested device to use for the next test * @param gatt gatt connection to use for the next test */ public void testCompleted(BluetoothDevice deviceBeingTested, BluetoothGatt gatt); /** * Indicate that the test is waiting for a connectable beacon */ public void waitingForConfigMode(); /** * Indicate that the test has connected to a beacon */ public void connectedToBeacon(); /** * Indicate that there are multiple beacons available to test * @param scanResults ArrayList containing the scan results of the beacons found */ public void multipleBeacons(ArrayList<ScanResult> scanResults); } /** * Builder class to build a test */ public static class Builder { private String mName; private String mReference = ""; private Context mContext; private UUID mServiceUuid; private TestCallback mTestCallback; private final LinkedList<TestAction> mTestActions = new LinkedList<>(); /** * Set the name of the test to show in the test adapter * @param name Name of the test * @return this builder */ public Builder name(String name) { mName = name; return this; } /** * Set the reference in the spec that shows the correct behavior * @param reference * @return */ public Builder reference(String reference) { mReference = reference; return this; } /** * Sets necessary parameters for the test * @param context used for bluetooth stack * @param serviceUuid service id of the config service * @param testCallback callback to communicate back with the runner * @return this builder */ public Builder setUp(Context context, ParcelUuid serviceUuid, TestCallback testCallback) { //TODO: since all the tests share these parameters it seems unnecessary to have to define them for each test. mContext = context; mServiceUuid = serviceUuid.getUuid(); mTestCallback = testCallback; return this; } /** * Adds a Connect action to the queue of actions * @return this builder */ public Builder connect() { mTestActions.add(new TestAction(TestAction.CONNECT)); return this; } /** * Adds a Disconnect action to the queue of actions * @return this builder */ public Builder disconnect() { mTestActions.add(new TestAction(TestAction.DISCONNECT)); return this; } /** * Adds a Assert action to the queue of actions. Reads a value from the beacon and compares it * to an expected value. * @param characteristicUuid UUID of the characteristic to read * @param expectedValue Expected value to read from the beacon * @param expectedReturnCode Expected return code from the beacon * @return this builder */ public Builder assertEquals(UUID characteristicUuid, byte[] expectedValue, int expectedReturnCode) { mTestActions.add( new TestAction(TestAction.ASSERT, characteristicUuid, expectedReturnCode, expectedValue)); return this; } /** * Adds a Assert Not Equal action to the queue of actions. Read a value from the beacon and * compares it to the not expected value. * @param characteristicUuid UUID of the characteristic to read * @param expectedValue Value that should not be returned from the beacon * @param expectedReturnCode Expected return code from the beacon * @return this builder */ public Builder assertNotEquals(UUID characteristicUuid, byte[] expectedValue, int expectedReturnCode) { mTestActions.add( new TestAction(TestAction.ASSERT_NOT_EQUALS, characteristicUuid, expectedReturnCode, expectedValue)); return this; } //TODO: The following actions share the same serviceUuid. It should be defined globally. /** * Adds an Assert Adv Flags action to the queue of actions. Assert the flags in the * Advertisement Packet are the expected ones. * @param expectedValue Expected value of the flags * @return this builder */ public Builder assertAdvFlags(ParcelUuid serviceUuid, byte expectedValue) { mTestActions.add(new TestAction(TestAction.ADV_FLAGS, serviceUuid, new byte[]{expectedValue})); return this; } /** * Adds an Assert Adv Tx Power action to the queue of actions. Assert the tx power in the * Advertisement packet is the expected one. * @param expectedValue Expected value of the tx power. * @return this builder */ public Builder assertAdvTxPower(ParcelUuid serviceUuid, byte expectedValue) { mTestActions.add(new TestAction(TestAction.ADV_TX_POWER, serviceUuid, new byte[]{expectedValue})); return this; } /** * Adds an Assert Adv URI actions to the queue of actions. Assert the URI in the Advertisement * packet is the expected one. * @param expectedValue Expected value of the URI * @return this builder */ public Builder assertAdvUri(ParcelUuid serviceUuid, byte[] expectedValue) { mTestActions.add(new TestAction(TestAction.ADV_URI, serviceUuid, expectedValue)); return this; } /** * Adds an Assert Adv Packet action to the queue of actions. Assert that the UriBeacon has a * valid advertisement packet according to spec. * @return this builder */ public Builder checkAdvPacket(ParcelUuid serviceUuid) { mTestActions.add(new TestAction(TestAction.ADV_PACKET, serviceUuid)); return this; } /** * Adds a Write action to the queue of actions * @param characteristicUuid UUID of the characteristic to write * @param value Value to write to the UriBeacon * @param expectedReturnCode Expected return code from the beacon * @return this builder */ public Builder write(UUID characteristicUuid, byte[] value, int expectedReturnCode) { mTestActions.add( new TestAction(TestAction.WRITE, characteristicUuid, expectedReturnCode, value)); return this; } /** * Adds a Write action to the queue of actions * @param characteristicUuid UUID of the characteristic to write * @param value Value to write to the UriBeacon * @param expectedReturnCodes Valid possible return codes from the beacon * @return this builder */ public Builder write(UUID characteristicUuid, byte[] value, int[] expectedReturnCodes) { mTestActions.add( new TestAction(TestAction.MULTIPLE_VALID_RETURN_CODES, characteristicUuid, value, expectedReturnCodes) ); return this; } /** * Adds a Write and then a Read action for each of the values. * @param characteristicUuid UUID of the characteristic to write and read * @param values array of values to write and read * @return this builder */ public Builder writeAndRead(UUID characteristicUuid, byte[][] values) { for (byte[] value : values) { writeAndRead(characteristicUuid, value); } return this; } /** * Adds a Write and then a Read action to the queue of actions. * @param characteristicUuid UUID of the characteristic to write and read * @param value value to write and expected to read * @return this builder */ public Builder writeAndRead(UUID characteristicUuid, byte[] value) { mTestActions.add( new TestAction(TestAction.WRITE, characteristicUuid, BluetoothGatt.GATT_SUCCESS, value)); mTestActions.add( new TestAction(TestAction.ASSERT, characteristicUuid, BluetoothGatt.GATT_SUCCESS, value)); return this; } /** * Adds the actions inside the provided Builder to the current test. * @param builder Builder to get the actions from * @return this builder */ public Builder insertActions(Builder builder) { for (TestAction action : builder.mTestActions) { mTestActions.add(action); } return this; } /** * Builds the test * @return this builder */ public TestHelper build() { mTestActions.add(new TestAction(TestAction.LAST)); // Keep a copy of the steps to show in the UI LinkedList<TestAction> testSteps = new LinkedList<>(mTestActions); return new TestHelper(mName, mReference, mContext, mServiceUuid, mTestCallback, mTestActions, testSteps); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.apex.malhar.lib.appdata.schemas; import java.io.Serializable; import java.text.DecimalFormat; /** * <p> * The {@link ResultFormatter} applies user specified {@link DecimalFormat} rules * to data. This class is used when serializing query results in order to define * out output data should be formatted before being sent back to the user. * </p> * <p> * Currently the ResultFormatter does not support applying special formatting to individual fields, * it can only support broad formatting rules based on field type. For example all float fields will be * formatted a certain way and all float fields could potentially be formatted in another way. In the * future the result formatter will support formatting data uniquely for each individual field. * </p> * @since 3.0.0 */ public class ResultFormatter implements Serializable { private static final long serialVersionUID = 201505121109L; /** * The {@link DecimalFormat} string for float data. */ private String floatFormatString; /** * The {@link DecimalFormat} string for double data. */ private String doubleFormatString; /** * The {@link DecimalFormat} string for byte data. */ private String byteFormatString; /** * The {@link DecimalFomrat} string for short data. */ private String shortFormatString; /** * The {@link DecimalFormat} string for int data. */ private String intFormatString; /** * The {@link DecimalFormat} string for long data. */ private String longFormatString; /** * The {@link DecimalFormat} string for discrete data. */ private String discreteFormatString; /** * The {@link DecimalFormat} string for continuous data. */ private String continuousFormatString; /** * The {@link DecimalFormat} object for floats. */ private transient DecimalFormat floatFormat; /** * The {@link DecimalFormat} object for doubles. */ private transient DecimalFormat doubleFormat; /** * The {@link DecimalFormat} object for bytes. */ private transient DecimalFormat byteFormat; /** * The {@link DecimalFormat} object for shorts. */ private transient DecimalFormat shortFormat; /** * The {@link DecimalFormat} object for ints. */ private transient DecimalFormat intFormat; /** * The {@link DecimalFormat} object for longs. */ private transient DecimalFormat longFormat; /** * Constructor for class. */ public ResultFormatter() { //Nothing needs to be done here } /** * Applies the correct formatting to the given object. * @param object The object to apply formatting to and convert to a String. * @return The formatted object string. */ public String format(Object object) { Type type = Type.CLASS_TO_TYPE.get(object.getClass()); if (type == null) { return object.toString(); } switch (type) { case FLOAT: { return format((float)((Float)object)); } case DOUBLE: { return format((double)((Double)object)); } case BYTE: { return format((byte)((Byte)object)); } case SHORT: { return format((short)((Short)object)); } case INTEGER: { return format((int)((Integer)object)); } case LONG: { return format((long)((Long)object)); } default: return object.toString(); } } /** * Formats the given float value. * @param val The float value to format. * @return The formatted float value. */ public String format(float val) { DecimalFormat df = getFloatFormat(); if (df != null) { return df.format(val); } return Float.toString(val); } /** * Formats the given double values. * @param val The double value to format. * @return The formatted double value. */ public String format(double val) { DecimalFormat df = getDoubleFormat(); if (df != null) { return df.format(val); } return Double.toString(val); } /** * Formats the given byte value. * @param val The byte value to format. * @return The formatted byte value. */ public String format(byte val) { DecimalFormat df = getByteFormat(); if (df != null) { return df.format(val); } return Byte.toString(val); } /** * Formats the given short value. * @param val The short value to format. * @return The formatted short value. */ public String format(short val) { DecimalFormat df = getShortFormat(); if (df != null) { return df.format(val); } return Short.toString(val); } /** * Formats the given int value. * @param val The int value to format. * @return The formatted int value. */ public String format(int val) { DecimalFormat df = getIntFormat(); if (df != null) { return df.format(val); } return Integer.toString(val); } /** * Formats the given long value. * @param val The long value to format. * @return The formatted long value. */ public String format(long val) { DecimalFormat df = getLongFormat(); if (df != null) { return df.format(val); } return Long.toString(val); } /** * Gets the {@link DecimalFormat} object to use for floats. * @return The {@link DecimalFormat} object to use for floats. */ public DecimalFormat getFloatFormat() { if (floatFormat == null && floatFormatString != null) { floatFormat = new DecimalFormat(floatFormatString); } return floatFormat; } /** * Gets the {@link DecimalFormat} for doubles. * @return The {@link DecimalFormat} object to use for doubles. */ public DecimalFormat getDoubleFormat() { if (doubleFormat == null && doubleFormatString != null) { doubleFormat = new DecimalFormat(doubleFormatString); } return doubleFormat; } /** * Gets the {@link DecimalFormat} for bytes. * @return The {@link DecimalFormat} object to use for bytes. */ public DecimalFormat getByteFormat() { if (byteFormat == null && byteFormatString != null) { byteFormat = new DecimalFormat(byteFormatString); } return byteFormat; } /** * Gets the {@link DecimalFormat} for shorts. * @return The {@link DecimalFormat} object to use for shorts. */ public DecimalFormat getShortFormat() { if (shortFormat == null && shortFormatString != null) { shortFormat = new DecimalFormat(shortFormatString); } return shortFormat; } /** * Gets the {@link DecimalFormat} for ints. * @return The {@link DecimalFormat} object to use for ints. */ public DecimalFormat getIntFormat() { if (intFormat == null && intFormatString != null) { intFormat = new DecimalFormat(intFormatString); } return intFormat; } /** * Gets the {@link DecimalFormat} for longs. * @return The {@link DecimalFormat} object to use for longs. */ public DecimalFormat getLongFormat() { if (longFormat == null && longFormatString != null) { longFormat = new DecimalFormat(longFormatString); } return longFormat; } /** * Gets the {@link DecimalFormat} for discrete values. * @return The {@link DecimalFormat} object to use for discrete values. */ public String getDiscreteFormatString() { return discreteFormatString; } /** * Sets the format string for discrete values. * @param discreteFormatString The format string for discrete values. */ public void setDiscreteFormatString(String discreteFormatString) { this.discreteFormatString = discreteFormatString; this.byteFormatString = discreteFormatString; this.shortFormatString = discreteFormatString; this.intFormatString = discreteFormatString; this.longFormatString = discreteFormatString; } /** * Gets the format string for continuous values. * @return The format string for continuous values. */ public String getContinuousFormatString() { return continuousFormatString; } /** * Sets the format string for continuous values. * @param continuousFormatString The format string for continuous values. */ public void setContinuousFormatString(String continuousFormatString) { this.continuousFormatString = continuousFormatString; this.floatFormatString = continuousFormatString; this.doubleFormatString = continuousFormatString; } /** * Gets the float format string. * @return The float format string. */ public String getFloatFormatString() { return floatFormatString; } /** * Sets the float format string. * @param decimalFormatString The float format string. */ public void setFloatFormatString(String decimalFormatString) { this.floatFormatString = decimalFormatString; } /** * Gets the double format string. * @return The double format string. */ public String getDoubleFormatString() { return doubleFormatString; } /** * Sets the double format string. * @param doubleFormatString The double format string. */ public void setDoubleFormatString(String doubleFormatString) { this.doubleFormatString = doubleFormatString; } /** * Gets the int format string. * @return The int format string. */ public String getIntFormatString() { return intFormatString; } /** * Sets the int format string. * @param intFormatString The int format string. */ public void setIntFormatString(String intFormatString) { this.intFormatString = intFormatString; } /** * Gets the byte format string. * @return The byte format string. */ public String getByteFormatString() { return byteFormatString; } /** * Sets the byte format string. * @param byteFormatString The byte format string to set. */ public void setByteFormatString(String byteFormatString) { this.byteFormatString = byteFormatString; } /** * Gets the short format string. * @return The short format string. */ public String getShortFormatString() { return shortFormatString; } /** * Sets the short format string. * @param shortFormatString The shortFormatString to set. */ public void setShortFormatString(String shortFormatString) { this.shortFormatString = shortFormatString; } /** * Gets the long format string. * @return The long format string to set. */ public String getLongFormatString() { return longFormatString; } /** * Sets the long format string. * @param longFormatString The long format string to set. */ public void setLongFormatString(String longFormatString) { this.longFormatString = longFormatString; } }
/* * Copyright 2012 Google 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.google.android.gcm.server; import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS; import static com.google.android.gcm.server.Constants.JSON_ERROR; import static com.google.android.gcm.server.Constants.JSON_FAILURE; import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID; import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID; import static com.google.android.gcm.server.Constants.JSON_PAYLOAD; import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS; import static com.google.android.gcm.server.Constants.JSON_RESULTS; import static com.google.android.gcm.server.Constants.JSON_SUCCESS; import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY; import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE; import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX; import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID; import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE; import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID; import static com.google.android.gcm.server.Constants.TOKEN_ERROR; import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.android.gcm.server.Result.Builder; /** * Helper class to send messages to the GCM service using an API Key. */ public class Sender { protected static final String UTF8 = "UTF-8"; /** * Initial delay before first retry, without jitter. */ protected static final int BACKOFF_INITIAL_DELAY = 1000; /** * Maximum delay before a retry. */ protected static final int MAX_BACKOFF_DELAY = 1024000; protected final Random random = new Random(); private final String key; /** * Default constructor. * * @param key * API key obtained through the Google API Console. */ public Sender(String key) { this.key = nonNull(key); } /** * Sends a message to one device, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message * message to be sent, including the device's registration id. * @param registrationId * device where the message will be sent. * @param retries * number of retries in case of service unavailability errors. * * @return result of the request (see its javadoc for more details) * * @throws IllegalArgumentException * if registrationId is {@literal null}. * @throws InvalidRequestException * if GCM didn't returned a 200 or 503 status. * @throws IOException * if message could not be sent. */ public Result send(Message message, String registrationId, int retries) throws IOException { int attempt = 0; Result result = null; int backoff = BACKOFF_INITIAL_DELAY; boolean tryAgain; do { attempt++; result = sendNoRetry(message, registrationId); tryAgain = result == null && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (result == null) { throw new IOException("Could not send message after " + attempt + " attempts"); } return result; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable. * * @throws InvalidRequestException * if GCM didn't returned a 200 or 503 status. * @throws IllegalArgumentException * if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = PARAM_PAYLOAD_PREFIX + entry.getKey(); String value = entry.getValue(); addParameter(body, key, URLEncoder.encode(value, UTF8)); } String requestBody = body.toString(); HttpURLConnection conn = post(GCM_SEND_ENDPOINT, requestBody); int status = conn.getResponseCode(); if (status == 503) { return null; } if (status != 200) { throw new InvalidRequestException(status); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); try { String line = reader.readLine(); if (line == null || line.equals("")) { throw new IOException("Received empty response from GCM service."); } String[] responseParts = split(line); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id line = reader.readLine(); if (line != null) { responseParts = split(line); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { } } Result result = builder.build(); return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Received invalid response from GCM: " + line); } } finally { reader.close(); } } finally { conn.disconnect(); } } /** * Sends a message to many devices, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message * message to be sent. * @param regIds * registration id of the devices that will receive the message. * @param retries * number of retries in case of service unavailability errors. * * @return combined result of all requests made. * * @throws IllegalArgumentException * if registrationIds is {@literal null} or empty. * @throws InvalidRequestException * if GCM didn't returned a 200 or 503 status. * @throws IOException * if message could not be sent. */ public MulticastResult send(Message message, List<String> regIds, int retries) throws IOException { int attempt = 0; MulticastResult multicastResult = null; int backoff = BACKOFF_INITIAL_DELAY; // Map of results by registration id, it will be updated after each // attempt // to send the messages Map<String, Result> results = new HashMap<String, Result>(); List<String> unsentRegIds = new ArrayList<String>(regIds); boolean tryAgain; List<Long> multicastIds = new ArrayList<Long>(); do { attempt++; multicastResult = sendNoRetry(message, unsentRegIds); long multicastId = multicastResult.getMulticastId(); multicastIds.add(multicastId); unsentRegIds = updateStatus(unsentRegIds, results, multicastResult); tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); // calculate summary int success = 0, failure = 0, canonicalIds = 0; for (Result result : results.values()) { if (result.getMessageId() != null) { success++; if (result.getCanonicalRegistrationId() != null) { canonicalIds++; } } else { failure++; } } // build a new object with the overall result long multicastId = multicastIds.remove(0); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId).retryMulticastIds(multicastIds); // add results, in the same order as the input for (String regId : regIds) { Result result = results.get(regId); builder.addResult(result); } return builder.build(); } /** * Updates the status of the messages sent to devices and the list of * devices that should be retried. * * @param unsentRegIds * list of devices that are still pending an update. * @param allResults * map of status that will be updated. * @param multicastResult * result of the last multicast sent. * * @return updated version of devices that should be retried. */ private List<String> updateStatus(List<String> unsentRegIds, Map<String, Result> allResults, MulticastResult multicastResult) { List<Result> results = multicastResult.getResults(); if (results.size() != unsentRegIds.size()) { // should never happen, unless there is a flaw in the algorithm throw new RuntimeException("Internal error: sizes do not match. " + "currentResults: " + results + "; unsentRegIds: " + unsentRegIds); } List<String> newUnsentRegIds = new ArrayList<String>(); for (int i = 0; i < unsentRegIds.size(); i++) { String regId = unsentRegIds.get(i); Result result = results.get(i); allResults.put(regId, result); String error = result.getErrorCodeName(); if (error != null && error.equals(Constants.ERROR_UNAVAILABLE)) { newUnsentRegIds.add(regId); } } return newUnsentRegIds; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return {@literal true} if the message was sent successfully, * {@literal false} if it failed but could be retried. * * @throws IllegalArgumentException * if registrationIds is {@literal null} or empty. * @throws InvalidRequestException * if GCM didn't returned a 200 status. * @throws IOException * if message could not be sent or received. */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); HttpURLConnection conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); int status = conn.getResponseCode(); String responseBody; if (status != 200) { responseBody = getString(conn.getErrorStream()); throw new InvalidRequestException(status, responseBody); } responseBody = getString(conn.getInputStream()); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder().messageId(messageId).canonicalRegistrationId(canonicalRegId).errorCode(error).build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } } private IOException newIoException(String responseBody, Exception e) { // log exception, as IOException constructor that takes a message and // cause // is only available on Java 6 String msg = "Error parsing JSON response (" + responseBody + ")"; return new IOException(msg + ":" + e); } /** * Sets a JSON field, but only if the value is not {@literal null}. */ private void setJsonField(Map<Object, Object> json, String field, Object value) { if (value != null) { json.put(field, value); } } private Number getNumber(Map<?, ?> json, String field) { Object value = json.get(field); if (value == null) { throw new CustomParserException("Missing field: " + field); } if (!(value instanceof Number)) { throw new CustomParserException("Field " + field + " does not contain a number: " + value); } return (Number) value; } class CustomParserException extends RuntimeException { /** * */ private static final long serialVersionUID = 6899454469986715109L; CustomParserException(String message) { super(message); } } private String[] split(String line) throws IOException { String[] split = line.split("=", 2); if (split.length != 2) { throw new IOException("Received invalid response line from GCM: " + line); } return split; } /** * Make an HTTP post to a given URL. * * @return HTTP response. */ protected HttpURLConnection post(String url, String body) throws IOException { return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); return conn; } /** * Creates a map with just one key-value pair. */ protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } /** * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. * * @param name * initial parameter for the POST. * @param value * initial value for that parameter. * @return StringBuilder to be used an HTTP POST body. */ protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } /** * Adds a new parameter to the HTTP POST body. * * @param body * HTTP POST body * @param name * parameter's name * @param value * parameter's value */ protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&').append(nonNull(name)).append('=').append(nonNull(value)); } /** * Gets an {@link HttpURLConnection} given an URL. */ protected HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * Convenience method to convert an InputStream to a String. * * <p> * If the stream ends in a newline character, it will be stripped. */ protected static String getString(InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(nonNull(stream))); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { // strip last newline content.setLength(content.length() - 1); } return content.toString(); } static <T> T nonNull(T argument) { if (argument == null) { throw new IllegalArgumentException("argument cannot be null"); } return argument; } void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
package org.jvnet.hyperjaxb3.ejb.strategy.annotate; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import javax.persistence.EnumType; import javax.persistence.GenerationType; import javax.persistence.JoinColumns; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedQueries; import javax.persistence.PrimaryKeyJoinColumns; import javax.persistence.SecondaryTables; import javax.persistence.SqlResultSetMappings; import javax.persistence.TemporalType; import org.jvnet.annox.model.XAnnotation; import org.jvnet.annox.model.annotation.field.XArrayAnnotationField; import org.jvnet.annox.model.annotation.field.XSingleAnnotationField; import org.jvnet.annox.model.annotation.value.XClassByNameAnnotationValue; import org.jvnet.annox.model.annotation.value.XEnumAnnotationValue; import org.jvnet.hyperjaxb3.annotation.util.AnnotationUtils; import com.sun.java.xml.ns.persistence.orm.AssociationOverride; import com.sun.java.xml.ns.persistence.orm.AttributeOverride; import com.sun.java.xml.ns.persistence.orm.Basic; import com.sun.java.xml.ns.persistence.orm.CascadeType; import com.sun.java.xml.ns.persistence.orm.Column; import com.sun.java.xml.ns.persistence.orm.ColumnResult; import com.sun.java.xml.ns.persistence.orm.DiscriminatorColumn; import com.sun.java.xml.ns.persistence.orm.Embeddable; import com.sun.java.xml.ns.persistence.orm.Embedded; import com.sun.java.xml.ns.persistence.orm.EmbeddedId; import com.sun.java.xml.ns.persistence.orm.EmptyType; import com.sun.java.xml.ns.persistence.orm.Entity; import com.sun.java.xml.ns.persistence.orm.EntityListener; import com.sun.java.xml.ns.persistence.orm.EntityListeners; import com.sun.java.xml.ns.persistence.orm.EntityResult; import com.sun.java.xml.ns.persistence.orm.FieldResult; import com.sun.java.xml.ns.persistence.orm.GeneratedValue; import com.sun.java.xml.ns.persistence.orm.Id; import com.sun.java.xml.ns.persistence.orm.IdClass; import com.sun.java.xml.ns.persistence.orm.Inheritance; import com.sun.java.xml.ns.persistence.orm.JoinColumn; import com.sun.java.xml.ns.persistence.orm.JoinTable; import com.sun.java.xml.ns.persistence.orm.Lob; import com.sun.java.xml.ns.persistence.orm.ManyToMany; import com.sun.java.xml.ns.persistence.orm.ManyToOne; import com.sun.java.xml.ns.persistence.orm.MapKey; import com.sun.java.xml.ns.persistence.orm.MappedSuperclass; import com.sun.java.xml.ns.persistence.orm.NamedNativeQuery; import com.sun.java.xml.ns.persistence.orm.NamedQuery; import com.sun.java.xml.ns.persistence.orm.OneToMany; import com.sun.java.xml.ns.persistence.orm.OneToOne; import com.sun.java.xml.ns.persistence.orm.PrimaryKeyJoinColumn; import com.sun.java.xml.ns.persistence.orm.QueryHint; import com.sun.java.xml.ns.persistence.orm.SecondaryTable; import com.sun.java.xml.ns.persistence.orm.SequenceGenerator; import com.sun.java.xml.ns.persistence.orm.SqlResultSetMapping; import com.sun.java.xml.ns.persistence.orm.Table; import com.sun.java.xml.ns.persistence.orm.TableGenerator; import com.sun.java.xml.ns.persistence.orm.Transient; import com.sun.java.xml.ns.persistence.orm.UniqueConstraint; import com.sun.java.xml.ns.persistence.orm.Version; public class CreateXAnnotations { // ================================================================== // 8.1 // ================================================================== // 8.1 public XAnnotation<javax.persistence.Entity> createEntity(Entity cEntity) { return cEntity == null ? null : // new XAnnotation<javax.persistence.Entity>( javax.persistence.Entity.class, // AnnotationUtils.create("name", cEntity.getName()) // ); } // 8.2 public XAnnotation<javax.persistence.EntityListeners> createEntityListeners( EntityListeners cEntityListeners) { if (cEntityListeners == null || cEntityListeners.getEntityListener().isEmpty()) { return null; } else { final List<String> classNames = new ArrayList<String>(); for (EntityListener entityListener : cEntityListeners .getEntityListener()) { if (entityListener.getClazz() != null) { classNames.add(entityListener.getClazz()); } } final String[] classNamesArray = classNames .toArray(new String[classNames.size()]); @SuppressWarnings("unchecked") final XClassByNameAnnotationValue<Object>[] values = new XClassByNameAnnotationValue[classNamesArray.length]; for (int index = 0; index < classNamesArray.length; index++) { values[index] = new XClassByNameAnnotationValue<Object>( classNamesArray[index]); } return new XAnnotation<javax.persistence.EntityListeners>( javax.persistence.EntityListeners.class, // new XArrayAnnotationField<Class<Object>>("value", Class[].class, values) // ); } } public XAnnotation<javax.persistence.ExcludeSuperclassListeners> createExcludeSuperclassListeners( EmptyType cExcludeSuperclassListeners) { return cExcludeSuperclassListeners == null ? null : // new XAnnotation<javax.persistence.ExcludeSuperclassListeners>( javax.persistence.ExcludeSuperclassListeners.class); } public XAnnotation<javax.persistence.ExcludeDefaultListeners> createExcludeDefaultListeners( EmptyType cExcludeDefaultListeners) { return cExcludeDefaultListeners == null ? null : // new XAnnotation<javax.persistence.ExcludeDefaultListeners>( javax.persistence.ExcludeDefaultListeners.class); } // public XAnnotation createEntityListeners(EntityListeners // cEntityListeners) // 8.3.1 public XAnnotation<javax.persistence.NamedQuery> createNamedQuery( NamedQuery cNamedQuery) { return cNamedQuery == null ? null : // new XAnnotation<javax.persistence.NamedQuery>( javax.persistence.NamedQuery.class, // AnnotationUtils.create("query", cNamedQuery.getQuery()), // AnnotationUtils.create("hints", createQueryHint(cNamedQuery.getHint()), javax.persistence.QueryHint.class), // AnnotationUtils.create("name", cNamedQuery.getName()) // ); } public XAnnotation<?> createNamedQueries( Collection<NamedQuery> cNamedQueries) { return transform( NamedQueries.class, javax.persistence.NamedQuery.class, cNamedQueries, new Transformer<NamedQuery, XAnnotation<javax.persistence.NamedQuery>>() { public XAnnotation<javax.persistence.NamedQuery> transform( NamedQuery input) { return createNamedQuery(input); } }); } public XAnnotation<javax.persistence.QueryHint> createQueryHint( QueryHint cQueryHint) { return cQueryHint == null ? null : // new XAnnotation<javax.persistence.QueryHint>( javax.persistence.QueryHint.class, // AnnotationUtils.create("name", cQueryHint.getName()), // AnnotationUtils.create("value", cQueryHint.getValue()) // ); } public XAnnotation<?>[] createQueryHint(Collection<QueryHint> cQueryHints) { return transform( cQueryHints, new Transformer<QueryHint, XAnnotation<javax.persistence.QueryHint>>() { public XAnnotation<javax.persistence.QueryHint> transform( QueryHint input) { return createQueryHint(input); } }); } // 8.3.2 public XAnnotation<javax.persistence.NamedNativeQuery> createNamedNativeQuery( NamedNativeQuery cNamedNativeQuery) { return cNamedNativeQuery == null ? null : // new XAnnotation<javax.persistence.NamedNativeQuery>( javax.persistence.NamedNativeQuery.class, // AnnotationUtils.create("name", cNamedNativeQuery.getName()), // AnnotationUtils.create("query", cNamedNativeQuery.getQuery()), // AnnotationUtils.create("hints", createQueryHint(cNamedNativeQuery.getHint()), javax.persistence.QueryHint.class), // cNamedNativeQuery.getResultClass() == null ? null : new XSingleAnnotationField<Class<Object>>( "resultClass", Class.class, new XClassByNameAnnotationValue<Object>( cNamedNativeQuery .getResultClass())), // AnnotationUtils.create("resultSetMapping", cNamedNativeQuery.getResultSetMapping()) // ); } public XAnnotation<?> createNamedNativeQuery( Collection<NamedNativeQuery> cNamedNativeQueries) { return transform( NamedNativeQueries.class, javax.persistence.NamedNativeQuery.class, cNamedNativeQueries, new Transformer<NamedNativeQuery, XAnnotation<javax.persistence.NamedNativeQuery>>() { public XAnnotation<javax.persistence.NamedNativeQuery> transform( NamedNativeQuery input) { return createNamedNativeQuery(input); } }); } public XAnnotation<javax.persistence.SqlResultSetMapping> createSqlResultSetMapping( SqlResultSetMapping cSqlResultSetMapping) { return cSqlResultSetMapping == null ? null : // new XAnnotation<javax.persistence.SqlResultSetMapping>( javax.persistence.SqlResultSetMapping.class, // AnnotationUtils.create("name", cSqlResultSetMapping.getName()), // AnnotationUtils.create("entityResult", createEntityResult(cSqlResultSetMapping .getEntityResult()), javax.persistence.EntityResult.class), // AnnotationUtils.create("columnResult", createColumnResult(cSqlResultSetMapping .getColumnResult()), javax.persistence.ColumnResult.class) // ); } public XAnnotation<?> createSqlResultSetMapping( Collection<SqlResultSetMapping> cSqlResultSetMappings) { return transform( SqlResultSetMappings.class, javax.persistence.SqlResultSetMapping.class, cSqlResultSetMappings, new Transformer<SqlResultSetMapping, XAnnotation<javax.persistence.SqlResultSetMapping>>() { public XAnnotation<javax.persistence.SqlResultSetMapping> transform( SqlResultSetMapping input) { return createSqlResultSetMapping(input); } }); } public XAnnotation<javax.persistence.EntityResult> createEntityResult( EntityResult cEntityResult) { return cEntityResult == null ? null : // new XAnnotation<javax.persistence.EntityResult>( javax.persistence.EntityResult.class, // new XSingleAnnotationField<Class<Object>>( "entityClass", Class.class, new XClassByNameAnnotationValue<Object>( cEntityResult.getEntityClass())), // AnnotationUtils.create("fields", createFieldResult(cEntityResult .getFieldResult()), javax.persistence.FieldResult.class), // AnnotationUtils.create("discriminatorColumn", cEntityResult.getDiscriminatorColumn()) // ); } public XAnnotation<?>[] createEntityResult(List<EntityResult> cEntityResults) { return transform( cEntityResults, new Transformer<EntityResult, XAnnotation<javax.persistence.EntityResult>>() { public XAnnotation<javax.persistence.EntityResult> transform( EntityResult cEntityResult) { return createEntityResult(cEntityResult); } }); } public XAnnotation<javax.persistence.FieldResult> createFieldResult( FieldResult cFieldResult) { return cFieldResult == null ? null : // new XAnnotation<javax.persistence.FieldResult>( javax.persistence.FieldResult.class, // AnnotationUtils.create("name", cFieldResult.getName()), // AnnotationUtils.create("column", cFieldResult.getColumn()) // ); } public XAnnotation<?>[] createFieldResult(List<FieldResult> cFieldResults) { return transform( cFieldResults, new Transformer<FieldResult, XAnnotation<javax.persistence.FieldResult>>() { public XAnnotation<javax.persistence.FieldResult> transform( FieldResult cFieldResult) { return createFieldResult(cFieldResult); } }); } public XAnnotation<javax.persistence.ColumnResult> createColumnResult( ColumnResult cColumnResult) { return cColumnResult == null ? null : // new XAnnotation<javax.persistence.ColumnResult>( javax.persistence.ColumnResult.class, // AnnotationUtils.create("name", cColumnResult.getName()) // ); } public XAnnotation<?>[] createColumnResult( Collection<ColumnResult> cColumnResults) { return transform( cColumnResults, new Transformer<ColumnResult, XAnnotation<javax.persistence.ColumnResult>>() { public XAnnotation<javax.persistence.ColumnResult> transform( ColumnResult cColumnResult) { return createColumnResult(cColumnResult); } }); } // ================================================================== // 9.1 // ================================================================== // 9.1.1 public XAnnotation<javax.persistence.Table> createTable(Table cTable) { return cTable == null ? null : // new XAnnotation<javax.persistence.Table>( javax.persistence.Table.class, // AnnotationUtils.create("name", cTable.getName()), // AnnotationUtils.create("catalog", cTable.getCatalog()), // AnnotationUtils.create("schema", cTable.getSchema()), // AnnotationUtils.create("uniqueConstraints", createUniqueConstraint(cTable .getUniqueConstraint()), javax.persistence.UniqueConstraint.class) // ); } // 9.1.2 public XAnnotation<javax.persistence.SecondaryTable> createSecondaryTable( SecondaryTable cSecondaryTable) { return cSecondaryTable == null ? null : // new XAnnotation<javax.persistence.SecondaryTable>( javax.persistence.SecondaryTable.class, // AnnotationUtils.create("name", cSecondaryTable.getName()), // AnnotationUtils.create("catalog", cSecondaryTable.getCatalog()), // AnnotationUtils.create("schema", cSecondaryTable.getSchema()), // AnnotationUtils.create("pkJoinColumns", createPrimaryKeyJoinColumn(cSecondaryTable .getPrimaryKeyJoinColumn()), javax.persistence.PrimaryKeyJoinColumn.class), // AnnotationUtils.create("uniqueConstraints", createUniqueConstraint(cSecondaryTable .getUniqueConstraint()), javax.persistence.UniqueConstraint.class) // ); } // 9.1.3 public XAnnotation<?> createSecondaryTables( List<SecondaryTable> cSecondaryTables) { return transform( SecondaryTables.class, javax.persistence.SecondaryTable.class, cSecondaryTables, new Transformer<SecondaryTable, XAnnotation<javax.persistence.SecondaryTable>>() { public XAnnotation<javax.persistence.SecondaryTable> transform( SecondaryTable input) { return createSecondaryTable(input); } }); } // 9.1.4 public XAnnotation<javax.persistence.UniqueConstraint> createUniqueConstraint( UniqueConstraint cUniqueConstraint) { return cUniqueConstraint == null ? null : // new XAnnotation<javax.persistence.UniqueConstraint>( javax.persistence.UniqueConstraint.class, // AnnotationUtils.create( "columnNames", cUniqueConstraint.getColumnName().toArray( new String[cUniqueConstraint .getColumnName().size()])) // ); } public XAnnotation<?>[] createUniqueConstraint( List<UniqueConstraint> cUniqueConstraints) { return transform( cUniqueConstraints, new Transformer<UniqueConstraint, XAnnotation<javax.persistence.UniqueConstraint>>() { public XAnnotation<javax.persistence.UniqueConstraint> transform( UniqueConstraint input) { return createUniqueConstraint(input); } }); } // 9.1.5 public XAnnotation<javax.persistence.Column> createColumn(Column cColumn) { return cColumn == null ? null : // new XAnnotation<javax.persistence.Column>( javax.persistence.Column.class, // AnnotationUtils.create("name", cColumn.getName()), // AnnotationUtils.create("unique", cColumn.isUnique()), // AnnotationUtils.create("nullable", cColumn.isNullable()), // AnnotationUtils.create("insertable", cColumn.isInsertable()), // AnnotationUtils.create("updatable", cColumn.isUpdatable()), // AnnotationUtils.create("columnDefinition", cColumn.getColumnDefinition()), // AnnotationUtils.create("table", cColumn.getTable()), // AnnotationUtils.create("length", cColumn.getLength()), // AnnotationUtils.create("precision", cColumn.getPrecision()), // AnnotationUtils.create("scale", cColumn.getScale())); } // 9.1.6 public XAnnotation<javax.persistence.JoinColumn> createJoinColumn( JoinColumn cJoinColumn) { return cJoinColumn == null ? null : // new XAnnotation<javax.persistence.JoinColumn>( javax.persistence.JoinColumn.class, // AnnotationUtils.create("name", cJoinColumn.getName()), // AnnotationUtils.create("referencedColumnName", cJoinColumn.getReferencedColumnName()), // AnnotationUtils.create("unique", cJoinColumn.isUnique()), // AnnotationUtils.create("nullable", cJoinColumn.isNullable()), // AnnotationUtils.create("insertable", cJoinColumn.isInsertable()), // AnnotationUtils.create("updatable", cJoinColumn.isUpdatable()), // AnnotationUtils.create("columnDefinition", cJoinColumn.getColumnDefinition()), // AnnotationUtils.create("table", cJoinColumn.getTable()) // ); } public XAnnotation<?>[] createJoinColumn(List<JoinColumn> cJoinColumns) { return transform( cJoinColumns, new Transformer<JoinColumn, XAnnotation<javax.persistence.JoinColumn>>() { public XAnnotation<javax.persistence.JoinColumn> transform( JoinColumn input) { return createJoinColumn(input); } }); } // 9.1.7 public XAnnotation<?> createJoinColumns(List<JoinColumn> cJoinColumns) { return transform( JoinColumns.class, javax.persistence.JoinColumn.class, cJoinColumns, new Transformer<JoinColumn, XAnnotation<javax.persistence.JoinColumn>>() { public XAnnotation<javax.persistence.JoinColumn> transform( JoinColumn input) { return createJoinColumn(input); } }); } public Collection<XAnnotation<?>> createAttributeAnnotations( Object attribute) { if (attribute == null) { return null; } else if (attribute instanceof Id) { return createIdAnnotations((Id) attribute); } else if (attribute instanceof EmbeddedId) { return createEmbeddedIdAnnotations((EmbeddedId) attribute); } else if (attribute instanceof Basic) { return createBasicAnnotations((Basic) attribute); } else if (attribute instanceof Version) { return createVersionAnnotations((Version) attribute); } else if (attribute instanceof ManyToOne) { return createManyToOneAnnotations((ManyToOne) attribute); } else if (attribute instanceof OneToMany) { return createOneToManyAnnotations((OneToMany) attribute); } else if (attribute instanceof OneToOne) { return createOneToOneAnnotations((OneToOne) attribute); } else if (attribute instanceof ManyToMany) { return createManyToManyAnnotations((ManyToMany) attribute); } else if (attribute instanceof Embedded) { return createEmbeddedAnnotations((Embedded) attribute); } else if (attribute instanceof Transient) { return createTransientAnnotations((Transient) attribute); } else { return null; } } // 9.1.8 public XAnnotation<javax.persistence.Id> createId(Id cId) { return cId == null ? null : // new XAnnotation<javax.persistence.Id>( javax.persistence.Id.class); } // 9.1.9 public XAnnotation<javax.persistence.GeneratedValue> createGeneratedValue( GeneratedValue cGeneratedValue) { return cGeneratedValue == null ? null : // new XAnnotation<javax.persistence.GeneratedValue>( javax.persistence.GeneratedValue.class, // AnnotationUtils.create("generator", cGeneratedValue.getGenerator()), // createGeneratedValue$Strategy(cGeneratedValue .getStrategy()) // ); } public XSingleAnnotationField<GenerationType> createGeneratedValue$Strategy( String strategy) { return strategy == null ? null : // new XSingleAnnotationField<GenerationType>("strategy", GenerationType.class, new XEnumAnnotationValue<GenerationType>( GenerationType.valueOf(strategy))); } // 9.1.10 public XAnnotation<javax.persistence.AttributeOverride> createAttributeOverride( AttributeOverride cAttributeOverride) { return cAttributeOverride == null ? null : // new XAnnotation<javax.persistence.AttributeOverride>( javax.persistence.AttributeOverride.class, // AnnotationUtils.create("name", cAttributeOverride.getName()), // AnnotationUtils.create("column", createColumn(cAttributeOverride.getColumn())) // ); } public XAnnotation<javax.persistence.AttributeOverride>[] createAttributeOverride( List<AttributeOverride> cAttributeOverrides) { return transform( cAttributeOverrides, new Transformer<AttributeOverride, XAnnotation<javax.persistence.AttributeOverride>>() { public XAnnotation<javax.persistence.AttributeOverride> transform( AttributeOverride input) { return createAttributeOverride(input); } }); } // 9.1.11 public XAnnotation<?> createAttributeOverrides( List<AttributeOverride> cAttributeOverrides) { return transform( javax.persistence.AttributeOverrides.class, javax.persistence.AttributeOverride.class, cAttributeOverrides, new Transformer<AttributeOverride, XAnnotation<javax.persistence.AttributeOverride>>() { public XAnnotation<javax.persistence.AttributeOverride> transform( AttributeOverride input) { return createAttributeOverride(input); } }); } // 9.1.12 public XAnnotation<javax.persistence.AssociationOverride> createAssociationOverride( AssociationOverride cAssociationOverride) { return cAssociationOverride == null ? null : // new XAnnotation<javax.persistence.AssociationOverride>( javax.persistence.AssociationOverride.class, // AnnotationUtils.create("name", cAssociationOverride.getName()), // AnnotationUtils.create("joinColumns", createJoinColumn(cAssociationOverride .getJoinColumn()), javax.persistence.JoinColumn.class) // ); } // 9.1.13 public XAnnotation<?> createAssociationOverrides( List<AssociationOverride> cAssociationOverrides) { return transform( javax.persistence.AssociationOverrides.class, javax.persistence.AssociationOverride.class, cAssociationOverrides, new Transformer<AssociationOverride, XAnnotation<javax.persistence.AssociationOverride>>() { public XAnnotation<javax.persistence.AssociationOverride> transform( AssociationOverride input) { return createAssociationOverride(input); } }); } // 9.1.14 public XAnnotation<javax.persistence.EmbeddedId> createEmbeddedId( EmbeddedId cEmbeddedId) { return cEmbeddedId == null ? null : // new XAnnotation<javax.persistence.EmbeddedId>( javax.persistence.EmbeddedId.class); } // 9.1.15 public XAnnotation<javax.persistence.IdClass> createIdClass(IdClass cIdClass) { return cIdClass == null ? null : // new XAnnotation<javax.persistence.IdClass>( javax.persistence.IdClass.class, // cIdClass.getClazz() == null ? null : new XSingleAnnotationField<Class<Object>>( "value", Class.class, new XClassByNameAnnotationValue<Object>( cIdClass.getClazz())) // ); } // 9.1.16 public XAnnotation<javax.persistence.Transient> createTransient( Transient cTransient) { return cTransient == null ? null : // new XAnnotation<javax.persistence.Transient>( javax.persistence.Transient.class); } // 9.1.17 public XAnnotation<javax.persistence.Version> createVersion(Version cVersion) { return cVersion == null ? null : // new XAnnotation<javax.persistence.Version>( javax.persistence.Version.class); } // 9.1.18 public XAnnotation<javax.persistence.Basic> createBasic(Basic cBasic) { return cBasic == null ? null : // new XAnnotation<javax.persistence.Basic>( javax.persistence.Basic.class, // AnnotationUtils.create("fetch", getFetchType(cBasic.getFetch())), // AnnotationUtils.create("optional", cBasic.isOptional()) // ); } // 9.1.19 public XAnnotation<javax.persistence.Lob> createLob(Lob cLob) { return cLob == null ? null : // new XAnnotation<javax.persistence.Lob>( javax.persistence.Lob.class); } // 9.1.20 public XAnnotation<javax.persistence.Temporal> createTemporal( String cTemporal) { return cTemporal == null ? null : // new XAnnotation<javax.persistence.Temporal>( javax.persistence.Temporal.class, // new XSingleAnnotationField<TemporalType>("value", TemporalType.class, new XEnumAnnotationValue<TemporalType>( TemporalType.valueOf(cTemporal)))); } // 9.1.21 public XAnnotation<javax.persistence.Enumerated> createEnumerated( String cEnumerated) { return cEnumerated == null ? null : // new XAnnotation<javax.persistence.Enumerated>( javax.persistence.Enumerated.class, // new XSingleAnnotationField<EnumType>("value", EnumType.class, new XEnumAnnotationValue<EnumType>( EnumType.valueOf(cEnumerated)))); } // 9.1.22 public XAnnotation<javax.persistence.ManyToOne> createManyToOne( ManyToOne cManyToOne) { return cManyToOne == null ? null : // new XAnnotation<javax.persistence.ManyToOne>( javax.persistence.ManyToOne.class, // cManyToOne.getTargetEntity() == null ? null : new XSingleAnnotationField<Class<Object>>( "targetEntity", Class.class, new XClassByNameAnnotationValue<Object>( cManyToOne.getTargetEntity())), // AnnotationUtils.create("cascade", getCascadeType(cManyToOne.getCascade())), // AnnotationUtils.create("fetch", getFetchType(cManyToOne.getFetch())), // AnnotationUtils.create("optional", cManyToOne.isOptional()) // ); } // 9.1.23 public XAnnotation<javax.persistence.OneToOne> createOneToOne( OneToOne cOneToOne) { return cOneToOne == null ? null : // new XAnnotation<javax.persistence.OneToOne>( javax.persistence.OneToOne.class, // cOneToOne.getTargetEntity() == null ? null : new XSingleAnnotationField<Class<Object>>( "targetEntity", Class.class, new XClassByNameAnnotationValue<Object>( cOneToOne.getTargetEntity())), // AnnotationUtils.create("cascade", getCascadeType(cOneToOne.getCascade())), // AnnotationUtils.create("fetch", getFetchType(cOneToOne.getFetch())), // AnnotationUtils.create("optional", cOneToOne.isOptional()), // AnnotationUtils.create("mappedBy", cOneToOne.getMappedBy()) // ); } // 9.1.24 public XAnnotation<javax.persistence.OneToMany> createOneToMany( OneToMany cOneToMany) { return cOneToMany == null ? null : // new XAnnotation<javax.persistence.OneToMany>( javax.persistence.OneToMany.class, // cOneToMany.getTargetEntity() == null ? null : new XSingleAnnotationField<Class<Object>>( "targetEntity", Class.class, new XClassByNameAnnotationValue<Object>( cOneToMany.getTargetEntity())), // AnnotationUtils.create("cascade", getCascadeType(cOneToMany.getCascade())), // AnnotationUtils.create("fetch", getFetchType(cOneToMany.getFetch())), // AnnotationUtils.create("mappedBy", cOneToMany.getMappedBy()) // ); } // 9.1.25 public XAnnotation<javax.persistence.JoinTable> createJoinTable( JoinTable cJoinTable) { return cJoinTable == null ? null : // new XAnnotation<javax.persistence.JoinTable>( javax.persistence.JoinTable.class, // AnnotationUtils.create("name", cJoinTable.getName()), // AnnotationUtils.create("catalog", cJoinTable.getCatalog()), // AnnotationUtils.create("schema", cJoinTable.getSchema()), // AnnotationUtils.create("joinColumns", createJoinColumn(cJoinTable.getJoinColumn()), javax.persistence.JoinColumn.class), // AnnotationUtils.create("inverseJoinColumns", createJoinColumn(cJoinTable .getInverseJoinColumn()), javax.persistence.JoinColumn.class), // AnnotationUtils.create("uniqueConstraints", createUniqueConstraint(cJoinTable .getUniqueConstraint()), javax.persistence.UniqueConstraint.class) // ); } // 9.1.26 public XAnnotation<javax.persistence.ManyToMany> createManyToMany( ManyToMany cManyToMany) { return cManyToMany == null ? null : // new XAnnotation<javax.persistence.ManyToMany>( javax.persistence.ManyToMany.class, // cManyToMany.getTargetEntity() == null ? null : new XSingleAnnotationField<Class<Object>>( "targetEntity", Class.class, new XClassByNameAnnotationValue<Object>( cManyToMany.getTargetEntity())), // AnnotationUtils.create("cascade", getCascadeType(cManyToMany.getCascade())), // AnnotationUtils.create("fetch", getFetchType(cManyToMany.getFetch())), // AnnotationUtils.create("mappedBy", cManyToMany.getMappedBy()) // ); } // 9.1.27 public XAnnotation<javax.persistence.MapKey> createMapKey(MapKey cMapKey) { return cMapKey == null ? null : // new XAnnotation<javax.persistence.MapKey>( javax.persistence.MapKey.class, // AnnotationUtils.create("name", cMapKey.getName()) // ); } // 9.1.28 public XAnnotation<javax.persistence.OrderBy> createOrderBy(String orderBy) { return orderBy == null ? null : // new XAnnotation<javax.persistence.OrderBy>( javax.persistence.OrderBy.class, AnnotationUtils.create("value", orderBy)); } // 9.1.29 public XAnnotation<javax.persistence.Inheritance> createInheritance( Inheritance cInheritance) { return cInheritance == null ? null : // new XAnnotation<javax.persistence.Inheritance>( javax.persistence.Inheritance.class, // AnnotationUtils.create("strategy", getInheritanceType(cInheritance.getStrategy())) // ); } // 9.1.30 public XAnnotation<javax.persistence.DiscriminatorColumn> createDiscriminatorColumn( DiscriminatorColumn cDiscriminatorColumn) { return cDiscriminatorColumn == null ? null : // new XAnnotation<javax.persistence.DiscriminatorColumn>( javax.persistence.DiscriminatorColumn.class, // AnnotationUtils.create("name", cDiscriminatorColumn.getName()), // AnnotationUtils.create("discriminatorType", getDiscriminatorType(cDiscriminatorColumn .getDiscriminatorType())), // AnnotationUtils.create("columnDefinition", cDiscriminatorColumn.getColumnDefinition()), // AnnotationUtils.create("length", cDiscriminatorColumn.getLength()) // ); } // 9.1.31 public XAnnotation<javax.persistence.DiscriminatorValue> createDiscriminatorValue( String cDiscriminatorValue) { return cDiscriminatorValue == null ? null : // new XAnnotation<javax.persistence.DiscriminatorValue>( javax.persistence.DiscriminatorValue.class, AnnotationUtils.create("value", cDiscriminatorValue)); } // 9.1.32 public XAnnotation<javax.persistence.PrimaryKeyJoinColumn> createPrimaryKeyJoinColumn( PrimaryKeyJoinColumn cPrimaryKeyJoinColumn) { return cPrimaryKeyJoinColumn == null ? null : // new XAnnotation<javax.persistence.PrimaryKeyJoinColumn>( javax.persistence.PrimaryKeyJoinColumn.class, // AnnotationUtils.create("name", cPrimaryKeyJoinColumn.getName()), // AnnotationUtils .create("referencedColumnName", cPrimaryKeyJoinColumn .getReferencedColumnName()), // AnnotationUtils.create("columnDefinition", cPrimaryKeyJoinColumn.getColumnDefinition()) // ); } public XAnnotation<javax.persistence.PrimaryKeyJoinColumn>[] createPrimaryKeyJoinColumn( List<PrimaryKeyJoinColumn> cPrimaryKeyJoinColumn) { return transform( cPrimaryKeyJoinColumn, new Transformer<PrimaryKeyJoinColumn, XAnnotation<javax.persistence.PrimaryKeyJoinColumn>>() { public XAnnotation<javax.persistence.PrimaryKeyJoinColumn> transform( PrimaryKeyJoinColumn input) { return createPrimaryKeyJoinColumn(input); } }); } // 9.1.33 public XAnnotation<?> createPrimaryKeyJoinColumns( List<PrimaryKeyJoinColumn> cPrimaryKeyJoinColumn) { return transform( PrimaryKeyJoinColumns.class, javax.persistence.PrimaryKeyJoinColumn.class, cPrimaryKeyJoinColumn, new Transformer<PrimaryKeyJoinColumn, XAnnotation<javax.persistence.PrimaryKeyJoinColumn>>() { public XAnnotation<javax.persistence.PrimaryKeyJoinColumn> transform( PrimaryKeyJoinColumn input) { return createPrimaryKeyJoinColumn(input); } }); } // 9.1.34 public XAnnotation<javax.persistence.Embeddable> createEmbeddable( Embeddable cEmbeddable) { return cEmbeddable == null ? null : // new XAnnotation<javax.persistence.Embeddable>( javax.persistence.Embeddable.class); } // 9.1.35 public XAnnotation<javax.persistence.Embedded> createEmbedded( Embedded cEmbedded) { return cEmbedded == null ? null : // new XAnnotation<javax.persistence.Embedded>( javax.persistence.Embedded.class); } // 9.1.36 public XAnnotation<javax.persistence.MappedSuperclass> createMappedSuperclass( MappedSuperclass cMappedSuperclass) { return cMappedSuperclass == null ? null : // new XAnnotation<javax.persistence.MappedSuperclass>( javax.persistence.MappedSuperclass.class); } // 9.1.37 public XAnnotation<javax.persistence.SequenceGenerator> createSequenceGenerator( SequenceGenerator cSequenceGenerator) { return cSequenceGenerator == null ? null : // new XAnnotation<javax.persistence.SequenceGenerator>( javax.persistence.SequenceGenerator.class, // AnnotationUtils.create("name", cSequenceGenerator.getName()), // AnnotationUtils.create("sequenceName", cSequenceGenerator.getSequenceName()), // AnnotationUtils.create("initialValue", cSequenceGenerator.getInitialValue()), // AnnotationUtils.create("allocationSize", cSequenceGenerator.getAllocationSize())); } // 9.1.38 public XAnnotation<javax.persistence.TableGenerator> createTableGenerator( TableGenerator cTableGenerator) { return cTableGenerator == null ? null : // new XAnnotation<javax.persistence.TableGenerator>( javax.persistence.TableGenerator.class, // AnnotationUtils.create("name", cTableGenerator.getName()), // AnnotationUtils.create("table", cTableGenerator.getTable()), // AnnotationUtils.create("catalog", cTableGenerator.getCatalog()), // AnnotationUtils.create("schema", cTableGenerator.getSchema()), // AnnotationUtils.create("pkColumnName", cTableGenerator.getPkColumnName()), // AnnotationUtils.create("valueColumnName", cTableGenerator.getValueColumnName()), // AnnotationUtils.create("pkColumnValue", cTableGenerator.getPkColumnValue()), // AnnotationUtils.create("initialValue", cTableGenerator.getInitialValue()), // AnnotationUtils.create("allocationSize", cTableGenerator.getAllocationSize()), // AnnotationUtils.create("uniqueConstraints", createUniqueConstraint(cTableGenerator .getUniqueConstraint()), javax.persistence.UniqueConstraint.class) // ); } // ================================================================== // 10.1 // ================================================================== // 10.1.3 public Collection<XAnnotation<?>> createEntityAnnotations(Entity cEntity) { return cEntity == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createEntity(cEntity), // createTable(cEntity.getTable()), // createSecondaryTables(cEntity.getSecondaryTable()), // createPrimaryKeyJoinColumns(cEntity .getPrimaryKeyJoinColumn()), // createIdClass(cEntity.getIdClass()), // createInheritance(cEntity.getInheritance()), // createDiscriminatorValue(cEntity .getDiscriminatorValue()), // createDiscriminatorColumn(cEntity .getDiscriminatorColumn()), // createSequenceGenerator(cEntity.getSequenceGenerator()), // createTableGenerator(cEntity.getTableGenerator()), // createNamedQueries(cEntity.getNamedQuery()), // createNamedNativeQuery(cEntity.getNamedNativeQuery()), // createSqlResultSetMapping(cEntity .getSqlResultSetMapping()), // createExcludeDefaultListeners(cEntity .getExcludeDefaultListeners()), // createExcludeSuperclassListeners(cEntity .getExcludeSuperclassListeners()), // createEntityListeners(cEntity.getEntityListeners()), // // "prePersist", // // "postPersist", // // "preRemove", // // "postRemove", // // "preUpdate", // // "postUpdate", // // "postLoad", // createAttributeOverrides(cEntity.getAttributeOverride()), // createAssociationOverrides(cEntity .getAssociationOverride()) // "attributes" // ); } // 10.1.3.22 public Collection<XAnnotation<?>> createIdAnnotations(Id cId) { return cId == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createId(cId), // createColumn(cId.getColumn()), // createGeneratedValue(cId.getGeneratedValue()), // createTemporal(cId.getTemporal()), // createTableGenerator(cId.getTableGenerator()), // createSequenceGenerator(cId.getSequenceGenerator()) // ); } // 10.1.3.23 public Collection<XAnnotation<?>> createEmbeddedIdAnnotations( EmbeddedId cEmbeddedId) { return cEmbeddedId == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createEmbeddedId(cEmbeddedId), // createAttributeOverrides(cEmbeddedId .getAttributeOverride()) // ); } // 10.1.3.24 public Collection<XAnnotation<?>> createBasicAnnotations(Basic cBasic) { return cBasic == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createBasic(cBasic), // createColumn(cBasic.getColumn()), // createLob(cBasic.getLob()), // createTemporal(cBasic.getTemporal()), // createEnumerated(cBasic.getEnumerated()) // ); } // 10.1.3.25 public Collection<XAnnotation<?>> createVersionAnnotations(Version cVersion) { return cVersion == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createVersion(cVersion), // createColumn(cVersion.getColumn()), // createTemporal(cVersion.getTemporal()) // ); } // 10.1.3.26 public Collection<XAnnotation<?>> createManyToOneAnnotations( ManyToOne cManyToOne) { return cManyToOne == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createManyToOne(cManyToOne), // createJoinColumns(cManyToOne.getJoinColumn()), // createJoinTable(cManyToOne.getJoinTable()) // ); } // 10.1.3.27 public Collection<XAnnotation<?>> createOneToManyAnnotations( OneToMany cOneToMany) { return cOneToMany == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createOneToMany(cOneToMany), // createOrderBy(cOneToMany.getOrderBy()), // createMapKey(cOneToMany.getMapKey()), // createJoinColumns(cOneToMany.getJoinColumn()), // createJoinTable(cOneToMany.getJoinTable()) // ); } // 10.1.3.28 public Collection<XAnnotation<?>> createOneToOneAnnotations( OneToOne cOneToOne) { return cOneToOne == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createOneToOne(cOneToOne), // createPrimaryKeyJoinColumns(cOneToOne .getPrimaryKeyJoinColumn()), // createJoinColumns(cOneToOne.getJoinColumn()), // createJoinTable(cOneToOne.getJoinTable()) // ); } // 10.1.3.29 public Collection<XAnnotation<?>> createManyToManyAnnotations( ManyToMany cManyToMany) { return cManyToMany == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createManyToMany(cManyToMany), // createOrderBy(cManyToMany.getOrderBy()), // createMapKey(cManyToMany.getMapKey()), // createJoinTable(cManyToMany.getJoinTable()) // ); } // 10.1.3.30 public Collection<XAnnotation<?>> createEmbeddedAnnotations( Embedded cEmbedded) { return cEmbedded == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createEmbedded(cEmbedded), // createAttributeOverrides(cEmbedded .getAttributeOverride()) // ); } // 10.1.3.31 public Collection<XAnnotation<?>> createTransientAnnotations( Transient cTransient) { return cTransient == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createTransient(cTransient) // ); } // 10.1.4 public Collection<XAnnotation<?>> createMappedSuperclassAnnotations( MappedSuperclass cMappedSuperclass) { return cMappedSuperclass == null ? Collections .<XAnnotation<?>> emptyList() : // annotations( // createMappedSuperclass(cMappedSuperclass), // createIdClass(cMappedSuperclass.getIdClass()), // createExcludeDefaultListeners(cMappedSuperclass .getExcludeDefaultListeners()), // createExcludeSuperclassListeners(cMappedSuperclass .getExcludeSuperclassListeners()), // createEntityListeners(cMappedSuperclass .getEntityListeners()) // // "prePersist", // // "postPersist", // // "preRemove", // // "postRemove", // // "preUpdate", // // "postUpdate", // // "postLoad", // ); } // 10.1.4 public Collection<XAnnotation<?>> createEmbeddableAnnotations( Embeddable cEmbeddable) { return cEmbeddable == null ? Collections.<XAnnotation<?>> emptyList() : // annotations( // createEmbeddable(cEmbeddable) // ); } public interface Transformer<I, O> { public O transform(I input); } public static <T, A1 extends Annotation, A2 extends Annotation> XAnnotation<?> transform( Class<A1> collectionClass, Class<A2> singleClass, Collection<T> collection, Transformer<T, XAnnotation<A2>> transformer) { if (collection == null || collection.isEmpty()) { return null; } else if (collection.size() == 1) { return transformer.transform(collection.iterator().next()); } else { return new XAnnotation<A1>(collectionClass, AnnotationUtils.create( "value", transform(collection, transformer), singleClass)); } } public static <T, A extends Annotation> XAnnotation<A>[] transform( Collection<T> collection, Transformer<T, XAnnotation<A>> transformer) { if (collection == null || collection.isEmpty()) { return null; } else { final Collection<XAnnotation<A>> annotations = new ArrayList<XAnnotation<A>>( collection.size()); for (T item : collection) { annotations.add(transformer.transform(item)); } @SuppressWarnings("unchecked") final XAnnotation<A>[] xannotations = annotations .toArray(new XAnnotation[annotations.size()]); return xannotations; } } public static Collection<XAnnotation<?>> annotations( XAnnotation<?>... annotations) { if (annotations == null) { return null; } else if (annotations.length == 0) { return Collections.emptyList(); } else { final List<XAnnotation<?>> xannotations = new ArrayList<XAnnotation<?>>( annotations.length); for (XAnnotation<?> annotation : annotations) { if (annotation != null) { xannotations.add(annotation); } } return xannotations; } } public static Collection<XAnnotation<?>> annotations( Collection<XAnnotation<?>> annotations, XAnnotation<?>... additionalAnnotations) { if (annotations == null) { return annotations(additionalAnnotations); } else if (additionalAnnotations == null) { return annotations; } else { final Collection<XAnnotation<?>> result = new ArrayList<XAnnotation<?>>( annotations.size() + additionalAnnotations.length); result.addAll(annotations); result.addAll(annotations(additionalAnnotations)); return result; } } @SuppressWarnings("unchecked") public static Collection<XAnnotation<?>> annotations(Object... annotations) { if (annotations == null) { return null; } else if (annotations.length == 0) { return Collections.emptyList(); } else { final List<XAnnotation<?>> xannotations = new ArrayList<XAnnotation<?>>( annotations.length); for (Object annotation : annotations) { if (annotation != null) { if (annotation instanceof XAnnotation) { final XAnnotation<?> xannotation = (XAnnotation<?>) annotation; xannotations.add(xannotation); } else if (annotation instanceof Collection) { final Collection<XAnnotation<?>> xannotation = (Collection<XAnnotation<?>>) annotation; xannotations.addAll(xannotation); } else { throw new IllegalArgumentException( "Expecting either annotations or collections of annotations."); } } } return xannotations; } } public javax.persistence.FetchType getFetchType(String fetch) { return fetch == null ? null : javax.persistence.FetchType .valueOf(fetch); } public javax.persistence.CascadeType[] getCascadeType(CascadeType cascade) { if (cascade == null) { return null; } else { final Collection<javax.persistence.CascadeType> cascades = new HashSet<javax.persistence.CascadeType>(); if (cascade.getCascadeAll() != null) { cascades.add(javax.persistence.CascadeType.ALL); } if (cascade.getCascadeMerge() != null) { cascades.add(javax.persistence.CascadeType.MERGE); } if (cascade.getCascadePersist() != null) { cascades.add(javax.persistence.CascadeType.PERSIST); } if (cascade.getCascadeRefresh() != null) { cascades.add(javax.persistence.CascadeType.REFRESH); } if (cascade.getCascadeRemove() != null) { cascades.add(javax.persistence.CascadeType.REMOVE); } return cascades.toArray(new javax.persistence.CascadeType[cascades .size()]); } } public javax.persistence.DiscriminatorType getDiscriminatorType( String discriminatorType) { return discriminatorType == null ? null : javax.persistence.DiscriminatorType .valueOf(discriminatorType); } public javax.persistence.InheritanceType getInheritanceType(String strategy) { return strategy == null ? null : javax.persistence.InheritanceType .valueOf(strategy); } }
package com.smict.person.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.smict.person.data.TreatmentRoomData; import com.smict.person.model.BranchModel; import com.smict.person.model.TreatmentRoomModel; import ldc.util.Auth; import ldc.util.Servlet; @SuppressWarnings("serial") public class TreatmentRoomAction extends ActionSupport { private TreatmentRoomModel treatRoomModel; private BranchModel branchModel; private int brand_id; private String doctor_name; private String brand_name, branch_id, branch_code, branch_name; private String room_id, room_name; /** * CONSTRUCTOR */ public TreatmentRoomAction(){ Auth.authCheck(false); } /** * @author anubissmile * Add new treatment room function. * @return String */ public String addNewRoom(){ // System.out.println("Room name : " + treatRoomModel.getRoom_name()); // System.out.println("Branch code : " + treatRoomModel.getRoom_branch_code()); TreatmentRoomData trData = new TreatmentRoomData(); trData.addRoom(treatRoomModel.getRoom_branch_code(), treatRoomModel.getRoom_name()); brand_id = branchModel.getBrand_id(); doctor_name = branchModel.getDoctor_name(); brand_name = branchModel.getBrand_name(); branch_id = branchModel.getBranch_id(); branch_code = branchModel.getBranch_code(); branch_name = branchModel.getBranch_name(); HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(false); HttpServletResponse response = ServletActionContext.getResponse(); String site = "branchM-" + branch_code; // session.setAttribute("branchModel", branchModel); /** * REDIRECTING. */ Servlet serve = new Servlet(); try { serve.redirect(request, response, site); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO: handle exception e.printStackTrace(); } return SUCCESS; } public void validateAddNewRoom(){ System.out.println("kdjfkd"); } public String deleteTreatmentRoom(){ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String site = "branchM-" + getBranch_code(); TreatmentRoomData trData = new TreatmentRoomData(); int[] rec = trData.deleteTreatmentRoom(getRoom_id(), getBranch_code()); if(rec[1]>0){ try { Servlet serv = new Servlet(); serv.redirect(request, response, site); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO: handle exception e.printStackTrace(); } } return NONE; } public String editTreatmentRoom(){ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String roomID = Integer.valueOf(treatRoomModel.getRoom_id()).toString(); String roomName = treatRoomModel.getRoom_name(); String roomBranchCode = treatRoomModel.getRoom_branch_code(); String site = "branchM-" + roomBranchCode; TreatmentRoomData trData = new TreatmentRoomData(); int rec = trData.editTreatmentRoom(roomID, roomName, roomBranchCode); if(rec>0){ try { new Servlet().redirect(request, response, site); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO: handle exception e.printStackTrace(); } } return NONE; } /** * GETTER SETTER ZONE. */ public TreatmentRoomModel getTreatRoomModel() { return treatRoomModel; } public void setTreatRoomModel(TreatmentRoomModel treatRoomModel) { this.treatRoomModel = treatRoomModel; } public BranchModel getBranchModel() { return branchModel; } public void setBranchModel(BranchModel branchModel) { this.branchModel = branchModel; } public int getBrand_id() { return brand_id; } public void setBrand_id(int brand_id) { this.brand_id = brand_id; } public String getDoctor_name() { return doctor_name; } public void setDoctor_name(String doctor_name) { this.doctor_name = doctor_name; } public String getBrand_name() { return brand_name; } public void setBrand_name(String brand_name) { this.brand_name = brand_name; } public String getBranch_id() { return branch_id; } public void setBranch_id(String branch_id) { this.branch_id = branch_id; } public String getBranch_code() { return branch_code; } public void setBranch_code(String branch_code) { this.branch_code = branch_code; } public String getBranch_name() { return branch_name; } public void setBranch_name(String branch_name) { this.branch_name = branch_name; } public String getRoom_id() { return room_id; } public void setRoom_id(String room_id) { this.room_id = room_id; } public String getRoom_name() { return room_name; } public void setRoom_name(String room_name) { this.room_name = room_name; } }
/* * Copyright 2014-2022 Web Firm Framework * * 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. * @author WFF */ package com.webfirmframework.wffweb.css; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import com.webfirmframework.wffweb.InvalidValueException; import com.webfirmframework.wffweb.NullValueException; import com.webfirmframework.wffweb.css.core.AbstractCssProperty; import com.webfirmframework.wffweb.css.core.CssProperty; import com.webfirmframework.wffweb.informer.StateChangeInformer; import com.webfirmframework.wffweb.util.CssValueUtil; import com.webfirmframework.wffweb.util.StringBuilderUtil; import com.webfirmframework.wffweb.util.StringUtil; import com.webfirmframework.wffweb.util.TagStringUtil; /** * <pre> * The border-right shorthand property sets all the right border properties in one declaration. * * The properties that can be set, are (in order): border-right-width, border-right-style, and border-right-color. * * If one of the values above are missing, e.g. border-right:solid #ff0000, the default value for the missing property will be inserted, if any. * Default value: medium none color * Inherited: no * Animatable: yes * Version: CSS1 * JavaScript syntax: object.style.borderRight="3px dashed blue" * </pre> * * @author WFF * @since 1.0.0 */ public class BorderRight extends AbstractCssProperty<BorderRight> implements StateChangeInformer<CssProperty> { private static final long serialVersionUID = 1_0_0L; private static final Logger LOGGER = Logger.getLogger(BorderRight.class.getName()); public static final String INITIAL = "initial"; public static final String INHERIT = "inherit"; private static final List<String> PREDEFINED_CONSTANTS = Arrays.asList(INITIAL, INHERIT); private String cssValue; private BorderRightWidth borderRightWidth; private BorderRightStyle borderRightStyle; private BorderRightColor borderRightColor; /** * The value <code>medium none black</code> will be assigned as the cssValue. * * @author WFF * @since 1.0.0 */ public BorderRight() { setCssValue("medium none black"); } /** * @param cssValue the css value to set. */ public BorderRight(final String cssValue) { setCssValue(cssValue); } /** * @param borderRight the {@code BorderRight} object from which the cssValue to * set.And, {@code null} will throw * {@code NullValueException} */ public BorderRight(final BorderRight borderRight) { if (borderRight == null) { throw new NullValueException("borderRight can not be null"); } setCssValue(borderRight.getCssValue()); } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.css.CssProperty#getCssName() * * @since 1.0.0 * * @author WFF */ @Override public String getCssName() { return CssNameConstants.BORDER_RIGHT; } /* * (non-Javadoc) * * @see com.webfirmframework.wffweb.css.CssProperty#getCssValue() * * @since 1.0.0 * * @author WFF */ @Override public String getCssValue() { return cssValue; } @Override public String toString() { return getCssName() + ": " + getCssValue(); } /** * @param cssValue the value should be in the format of * <code>medium none color</code>, <code>initial</code> or * <code>inherit</code>. {@code null} is considered as an * invalid value and it will throw {@code NullValueException}. * @since 1.0.0 * @author WFF */ @Override public BorderRight setCssValue(final String cssValue) { final String trimmedCssValue; if (cssValue == null) { throw new NullValueException( "null is an invalid value. The value format should be as for example medium none color Or initial/inherit."); } else if ((trimmedCssValue = TagStringUtil.toLowerCase(StringUtil.strip(cssValue))).isEmpty()) { throw new NullValueException(cssValue + " is an invalid value. The value format should be as for example medium none color Or initial/inherit."); } final List<String> cssValueParts = CssValueUtil.split(trimmedCssValue); if (cssValueParts.size() > 1) { if (trimmedCssValue.contains(BorderRightColor.INITIAL)) { throw new InvalidValueException( "The string 'initial' makes the given cssValue invalid, please remove 'initial' from it and try."); } if (trimmedCssValue.contains(BorderRightColor.INHERIT)) { throw new InvalidValueException( "The string 'inherit' makes the given cssValue invalid, please remove 'inherit' from it and try."); } } else { if (PREDEFINED_CONSTANTS.contains(trimmedCssValue)) { if (borderRightWidth != null) { borderRightWidth.setAlreadyInUse(false); borderRightWidth = null; } borderRightStyle = null; if (borderRightColor != null) { borderRightColor.setAlreadyInUse(false); borderRightColor = null; } this.cssValue = trimmedCssValue; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } return this; } } BorderRightWidth borderRightWidth = null; BorderRightStyle borderRightStyle = null; BorderRightColor borderRightColor = null; for (final String eachPart : cssValueParts) { if (borderRightWidth == null && BorderRightWidth.isValid(eachPart)) { if (this.borderRightWidth == null) { borderRightWidth = new BorderRightWidth(eachPart); borderRightWidth.setStateChangeInformer(this); borderRightWidth.setAlreadyInUse(true); } else { this.borderRightWidth.setCssValue(eachPart); borderRightWidth = this.borderRightWidth; } } else if (borderRightStyle == null && BorderRightStyle.isValid(eachPart)) { borderRightStyle = BorderRightStyle.getThis(eachPart); } else if (borderRightColor == null && BorderRightColor.isValid(eachPart)) { if (this.borderRightColor == null) { borderRightColor = new BorderRightColor(eachPart); borderRightColor.setStateChangeInformer(this); borderRightColor.setAlreadyInUse(true); } else { this.borderRightColor.setCssValue(eachPart); borderRightColor = this.borderRightColor; } } } final StringBuilder cssValueBuilder = new StringBuilder(); boolean invalid = true; if (borderRightWidth != null) { cssValueBuilder.append(borderRightWidth.getCssValue()).append(' '); invalid = false; } else if (this.borderRightWidth != null) { this.borderRightWidth.setAlreadyInUse(false); } if (borderRightStyle != null) { cssValueBuilder.append(borderRightStyle.getCssValue()).append(' '); invalid = false; } if (borderRightColor != null) { cssValueBuilder.append(borderRightColor.getCssValue()).append(' '); invalid = false; } else if (this.borderRightColor != null) { this.borderRightColor.setAlreadyInUse(false); } if (invalid) { throw new InvalidValueException(cssValue + " is an invalid value. The value format should be as for example medium none color Or initial/inherit."); } this.cssValue = StringBuilderUtil.getTrimmedString(cssValueBuilder); this.borderRightWidth = borderRightWidth; this.borderRightStyle = borderRightStyle; this.borderRightColor = borderRightColor; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } return this; } /** * checks the given css value is valid for this class. It does't do a strict * validation. * * @param cssValue * @return * @since 1.0.0 * @author WFF */ public static boolean isValid(final String cssValue) { // TODO modify to make a strict validation if (cssValue == null || StringUtil.isBlank(cssValue)) { return false; } final List<String> cssValueParts = CssValueUtil.split(cssValue); BorderRightWidth borderRightWidth = null; BorderRightStyle borderRightStyle = null; BorderRightColor borderRightColor = null; for (final String eachPart : cssValueParts) { boolean invalid = true; if (borderRightWidth == null && BorderRightWidth.isValid(eachPart)) { borderRightWidth = new BorderRightWidth(eachPart); invalid = false; } else if (borderRightStyle == null && BorderRightStyle.isValid(eachPart)) { borderRightStyle = BorderRightStyle.getThis(eachPart); invalid = false; } else if (borderRightColor == null && BorderRightColor.isValid(eachPart)) { borderRightColor = new BorderRightColor(eachPart); invalid = false; } if (invalid) { return false; } } return borderRightWidth != null || borderRightStyle != null || borderRightColor != null; } /** * sets as initial * * @since 1.0.0 * @author WFF */ public void setAsInitial() { setCssValue(INITIAL); } /** * sets as inherit * * @since 1.0.0 * @author WFF */ public void setAsInherit() { setCssValue(INHERIT); } public BorderRightColor getBorderRightColor() { return borderRightColor; } public BorderRightStyle getBorderRightStyle() { return borderRightStyle; } public BorderRightWidth getBorderRightWidth() { return borderRightWidth; } public BorderRight setBorderRightWidth(final BorderRightWidth borderRightWidth) { final StringBuilder cssValueBuilder = new StringBuilder(); if (borderRightWidth != null) { final String borderRightWidthCssValue = borderRightWidth.getCssValue(); if (BorderRightWidth.INITIAL.equals(borderRightWidthCssValue) || BorderRightWidth.INHERIT.equals(borderRightWidthCssValue)) { throw new InvalidValueException("borderRightWidth cannot have initial/inherit as its cssValue"); } cssValueBuilder.append(borderRightWidth.getCssValue()).append(' '); } if (borderRightStyle != null) { cssValueBuilder.append(borderRightStyle.getCssValue()).append(' '); } if (borderRightColor != null) { cssValueBuilder.append(borderRightColor.getCssValue()).append(' '); } final String trimmedCssValue = StringBuilderUtil.getTrimmedString(cssValueBuilder).toString(); cssValue = trimmedCssValue.isEmpty() ? INHERIT : trimmedCssValue; if (borderRightWidth != null && borderRightWidth.isAlreadyInUse() && !Objects.equals(this.borderRightWidth, borderRightWidth)) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning( "the given borderRightWidth is already used by another object so a new object or the previous object (if it exists) of BorderRightWidth will be used"); } return setCssValue(cssValue); } if (this.borderRightWidth != null) { this.borderRightWidth.setAlreadyInUse(false); } this.borderRightWidth = borderRightWidth; if (this.borderRightWidth != null) { this.borderRightWidth.setStateChangeInformer(this); this.borderRightWidth.setAlreadyInUse(true); } if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } return this; } public BorderRight setBorderRightStyle(final BorderRightStyle borderRightStyle) { final StringBuilder cssValueBuilder = new StringBuilder(); if (borderRightWidth != null) { cssValueBuilder.append(borderRightWidth.getCssValue()).append(' '); } if (borderRightStyle != null) { cssValueBuilder.append(borderRightStyle.getCssValue()).append(' '); } if (borderRightColor != null) { cssValueBuilder.append(borderRightColor.getCssValue()).append(' '); } final String trimmedCssValue = StringBuilderUtil.getTrimmedString(cssValueBuilder).toString(); cssValue = trimmedCssValue.isEmpty() ? INHERIT : trimmedCssValue; this.borderRightStyle = borderRightStyle; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } return this; } public BorderRight setBorderRightColor(final BorderRightColor borderRightColor) { final StringBuilder cssValueBuilder = new StringBuilder(); if (borderRightWidth != null) { cssValueBuilder.append(borderRightWidth.getCssValue()).append(' '); } if (borderRightStyle != null) { cssValueBuilder.append(borderRightStyle.getCssValue()).append(' '); } if (borderRightColor != null) { final String borderRightColorCssValue = borderRightColor.getCssValue(); if (BorderRightColor.INITIAL.equals(borderRightColorCssValue) || BorderRightColor.INHERIT.equals(borderRightColorCssValue)) { throw new InvalidValueException("borderRightColor cannot have initial/inherit as its cssValue"); } cssValueBuilder.append(borderRightColorCssValue); } final String trimmedCssValue = StringBuilderUtil.getTrimmedString(cssValueBuilder).toString(); cssValue = trimmedCssValue.isEmpty() ? INHERIT : trimmedCssValue; if (borderRightColor != null && borderRightColor.isAlreadyInUse() && this.borderRightColor != borderRightColor) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning( "the given borderRightColor is already used by another object so a new object or the previous object (if it exists) of BorderRightColor will be used"); } return setCssValue(cssValue); } if (this.borderRightColor != null) { this.borderRightColor.setAlreadyInUse(false); } this.borderRightColor = borderRightColor; if (this.borderRightColor != null) { this.borderRightColor.setStateChangeInformer(this); this.borderRightColor.setAlreadyInUse(true); } if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } return this; } @Override public void stateChanged(final CssProperty stateChangedObject) { if (stateChangedObject instanceof BorderRightColor) { final BorderRightColor borderRightColor = (BorderRightColor) stateChangedObject; final String cssValue = borderRightColor.getCssValue(); if (BorderRightColor.INITIAL.equals(cssValue) || BorderRightColor.INHERIT.equals(cssValue)) { throw new InvalidValueException("initial/inherit cannot be set as borderRightColor cssValue"); } setBorderRightColor(borderRightColor); } } /** * * @author WFF * @since 1.0.0 */ protected void addPredefinedConstant(final String constant) { PREDEFINED_CONSTANTS.add(constant); } }
package com.buabook.http.common; import java.io.IOException; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.buabook.http.common.auth.HttpBasicAuthenticationInitializer; import com.buabook.http.common.auth.HttpBearerAuthenticationInitializer; import com.buabook.http.common.exceptions.HttpClientRequestFailedException; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.EmptyContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.UrlEncodedContent; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.common.base.Stopwatch; import com.google.common.base.Strings; import com.google.common.net.MediaType; /** * <h3>HTTP Client Access Library</h3> * (c) 2015 Sport Trades Ltd * * @author Jas Rajasansir * @version 1.0.0 * @since 13 Oct 2015 */ public class HttpClient { private static final Logger log = LoggerFactory.getLogger(HttpClient.class); private final HttpRequestFactory requestFactory; public HttpClient() { this.requestFactory = new NetHttpTransport().createRequestFactory(); } protected HttpClient(HttpRequestFactory customRequestFactory) { this.requestFactory = customRequestFactory; } /** * HTTP client instantiation with Basic Authentication configured. See <a href="https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side"> * https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side</a>. * @see HttpBasicAuthenticationInitializer */ public HttpClient(String username, String password) { this.requestFactory = new NetHttpTransport().createRequestFactory(new HttpBasicAuthenticationInitializer(username, password)); } /** * HTTP client instantiation with OAuth 2.0 (<code>Bearer</code>) authentication. * @see HttpBearerAuthenticationInitializer */ public HttpClient(String bearerAuthToken) { this.requestFactory = new NetHttpTransport().createRequestFactory(new HttpBearerAuthenticationInitializer(bearerAuthToken)); } /** * <p>Standard HTTP GET request to the specified URL.</p> * <p><b>NOTE</b>: You must call {@link HttpResponse#disconnect()} after using the * response. {@link #getResponseAsString(HttpResponse)} and {@link #getResponseAsJson(HttpResponse)} will do this for you when * used.</p> * @param url The full URL to query. {@link HttpHelpers#appendUrlParameters(String, Map)} is useful to append query parameters to * the URL before passing into this function. * @throws HttpClientRequestFailedException If the GET returns any HTTP error code or the request fails due to an {@link IOException} * @see #getResponseAsString(HttpResponse) * @see #getResponseAsJson(HttpResponse) */ public HttpResponse doGet(String url) throws HttpClientRequestFailedException { if(Strings.isNullOrEmpty(url)) throw new IllegalArgumentException("No URL specified"); log.debug("Attempting HTTP GET [ URL: {} ]", url); GenericUrl target = new GenericUrl(url); HttpResponse response = null; Stopwatch timer = Stopwatch.createStarted(); try { HttpRequest request = requestFactory.buildGetRequest(target); response = request.execute(); } catch (HttpResponseException e) { log.error("HTTP client GET failed due to bad HTTP status code [ URL: {} ] [ Status Code: {} ] [ In Flight: {} ]", url, e.getStatusCode(), timer.stop()); throw new HttpClientRequestFailedException(e); } catch (IOException e) { log.error("HTTP client GET failed [ URL: {} ] [ In Flight: {} ]. Error - {}", url, timer.stop(), e.getMessage(), e); throw new HttpClientRequestFailedException(e); } log.debug("HTTP GET successful [ URL: {} ] [ In Flight: {} ]", url, timer.stop()); return response; } /** * <p>Standard HTTP POST equivalent to <code>&lt;form&gt;</code> or Content-Type <code>application/x-www-form-urlencoded</code>.</p> * <p><b>NOTE</b>: You must call {@link HttpResponse#disconnect()} after using the * response. {@link #getResponseAsString(HttpResponse)} and {@link #getResponseAsJson(HttpResponse)} will do this for you when * used.</p> * @param url * @param map * @return * @throws HttpClientRequestFailedException If the POST returns any HTTP error code or the request fails due to an {@link IOException} * @see #doPost(String, HttpContent, HttpHeaders) * @see #getResponseAsString(HttpResponse) * @see #getResponseAsJson(HttpResponse) */ public HttpResponse doPost(String url, Map<String, Object> map) throws HttpClientRequestFailedException { UrlEncodedContent content = new UrlEncodedContent(map); return doPost(url, content, null); } /** * <p><b>NOTE</b>: You must call {@link HttpResponse#disconnect()} after using the * response. {@link #getResponseAsString(HttpResponse)} and {@link #getResponseAsJson(HttpResponse)} will do this for you when * used.</p> * @param contentType A standard HTTP Content-Type (e.g. "application/json"). If this is <code>null</code> or empty string, * "text/plain" will be used * @param postContent The content to POST. Pass <code>null</code> or empty string to send no content * @param headers Any custom headers that need to be set. Pass <code>null</code> if not required * @throws HttpClientRequestFailedException If the GET returns any HTTP error code or the request fails due to an {@link IOException} * @see #doPost(String, HttpContent, HttpHeaders) * @see #getResponseAsString(HttpResponse) * @see #getResponseAsJson(HttpResponse) */ public HttpResponse doPost(String url, MediaType contentType, String postContent, HttpHeaders headers) throws HttpClientRequestFailedException { HttpContent content = null; if(contentType == null) contentType = MediaType.PLAIN_TEXT_UTF_8; if(Strings.isNullOrEmpty(postContent)) content = new EmptyContent(); else content = ByteArrayContent.fromString(contentType.toString(), postContent); return doPost(url, content, headers); } /** * <p>Performs a HTTP POST based on the specified content and URL. If you are unsure what content to pass, look at * the other <code>doPost</code> methods.</p> * <p><b>NOTE</b>: You must call {@link HttpResponse#disconnect()} after using the * response. {@link #getResponseAsString(HttpResponse)} and {@link #getResponseAsJson(HttpResponse)} will do this for you when * used.</p> * @return The response from the server * @throws IllegalArgumentException If either of the parameters are <code>null</code> * @throws HttpClientRequestFailedException If the request fails due to underlying network errors or a bad HTTP server status (e.g. 404, 500) * @see #getResponseAsString(HttpResponse) * @see #getResponseAsJson(HttpResponse) */ public HttpResponse doPost(String url, HttpContent content, HttpHeaders headers) throws IllegalArgumentException, HttpClientRequestFailedException { if(Strings.isNullOrEmpty(url)) throw new IllegalArgumentException("No URL specified"); if(content == null) throw new IllegalArgumentException("Content cannot be null"); log.debug("Attempting HTTP POST [ URL: {} ] [ Content-Type: {} ] [ Custom Headers: {} ]", url, content.getType(), (headers == null) ? 0 : headers.size()); GenericUrl target = new GenericUrl(url); HttpResponse response = null; Stopwatch timer = Stopwatch.createStarted(); try { HttpRequest request = requestFactory.buildPostRequest(target, content); if(headers != null) request.setHeaders(headers); response = request.execute(); } catch (HttpResponseException e) { log.error("HTTP client POST failed due to bad HTTP status code [ URL: {} ] [ Status Code: {} ] [ In Flight: {} ]", url, e.getStatusCode(), timer.stop()); throw new HttpClientRequestFailedException(e); } catch (IOException e) { log.error("HTTP client POST failed [ URL: {} ] [ In Flight: {} ]. Error - {}", url, timer.stop(), e.getMessage(), e); throw new HttpClientRequestFailedException(e); } log.debug("HTTP POST successful [ URL: {} ] [ In Flight: {} ]", url, timer.stop()); return response; } public HttpResponse doPut(String url, HttpContent content) throws IllegalArgumentException, HttpClientRequestFailedException { if(Strings.isNullOrEmpty(url)) throw new IllegalArgumentException("No URL specified"); if(content == null) throw new IllegalArgumentException("Content cannot be null"); log.debug("Attempting HTTP PUT [ URL: {} ] [ Content-Type: {} ]", url, content.getType()); GenericUrl target = new GenericUrl(url); HttpResponse response = null; Stopwatch timer = Stopwatch.createStarted(); try { HttpRequest request = requestFactory.buildPutRequest(target, content); response = request.execute(); } catch (HttpResponseException e) { log.error("HTTP client PUT failed due to bad HTTP status code [ URL: {} ] [ Status Code: {} ] [ In Flight: {} ]", url, e.getStatusCode(), timer.stop()); throw new HttpClientRequestFailedException(e); } catch (IOException e) { log.error("HTTP client PUT failed [ URL: {} ] [ In Flight: {} ]. Error - {}", url, timer.stop(), e); throw new HttpClientRequestFailedException(e); } log.debug("HTTP PUT successful [ URL: {} ] [ In Flight: {} ]", url, timer.stop()); return response; } /** * <b>NOTE</b>: After reading the response, {@link HttpResponse#disconnect()} will be called as required * by the documentation. * @param response * @return The body of the response as a string */ public static String getResponseAsString(HttpResponse response) { if(response == null) return ""; String responseString = ""; try { responseString = response.parseAsString(); } catch (IOException e) { log.error("Failed to convert HTTP response to string. Error - {}", e.getMessage(), e); } finally { try { response.disconnect(); } catch (IOException e) {} } return responseString; } /** * @param response * @return The body of the response as a JSON object * @throws JSONException If the string response does not parse into valid JSON * @see #getResponseAsString(HttpResponse) */ public static JSONObject getResponseAsJson(HttpResponse response) throws JSONException { return new JSONObject(getResponseAsString(response)); } }
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ /** * Do not modify this class. It was generated. * Instead modify LeafRegionEntry.cpp and then run * bin/generateRegionEntryClasses.sh from the directory * that contains your build.xml. */ package com.pivotal.gemfirexd.internal.engine.store.entry; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import com.gemstone.gemfire.internal.cache.Token; import com.gemstone.gemfire.internal.concurrent.AtomicUpdaterFactory; import com.gemstone.gemfire.internal.concurrent.CustomEntryConcurrentHashMap.HashEntry; import java.io.DataOutput; import java.io.IOException; import com.gemstone.gemfire.internal.cache.LocalRegion; import com.gemstone.gemfire.internal.cache.RegionEntry; import com.gemstone.gemfire.internal.cache.RegionEntryContext; import com.gemstone.gemfire.internal.cache.RegionEntryFactory; import com.gemstone.gemfire.internal.shared.Version; import com.gemstone.gemfire.internal.util.ArrayUtils; import com.pivotal.gemfirexd.internal.engine.sql.catalog.ExtraTableInfo; import com.pivotal.gemfirexd.internal.engine.store.CompactCompositeKey; import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer; import com.pivotal.gemfirexd.internal.engine.store.RegionEntryUtils; import com.pivotal.gemfirexd.internal.engine.store.RowFormatter; import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.services.cache.ClassSize; import com.pivotal.gemfirexd.internal.iapi.services.io.ArrayInputStream; import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow; import com.pivotal.gemfirexd.internal.iapi.types.BooleanDataValue; import com.pivotal.gemfirexd.internal.iapi.types.DataTypeDescriptor; import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor; import com.pivotal.gemfirexd.internal.iapi.types.DataValueFactory; import com.pivotal.gemfirexd.internal.iapi.types.RowLocation; import com.pivotal.gemfirexd.internal.shared.common.StoredFormatIds; public class VMLocalRowLocationThinRegionEntryHeap extends RowLocationThinRegionEntry { public VMLocalRowLocationThinRegionEntryHeap (RegionEntryContext context, Object key, Object value ) { super(context, value ); this.tableInfo = RegionEntryUtils.entryGetTableInfo(context, key, value); this.key = RegionEntryUtils.entryGetRegionKey(key, value); } protected int hash; private HashEntry<Object, Object> next; @SuppressWarnings("unused") private volatile long lastModified; private static final AtomicLongFieldUpdater<VMLocalRowLocationThinRegionEntryHeap> lastModifiedUpdater = AtomicUpdaterFactory.newLongFieldUpdater(VMLocalRowLocationThinRegionEntryHeap.class, "lastModified"); protected long getlastModifiedField() { return lastModifiedUpdater.get(this); } protected final boolean compareAndSetLastModifiedField(long expectedValue, long newValue) { return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue); } @Override public final int getEntryHash() { return this.hash; } @Override protected final void setEntryHash(int v) { this.hash = v; } @Override public final HashEntry<Object, Object> getNextEntry() { return this.next; } @Override public final void setNextEntry(final HashEntry<Object, Object> n) { this.next = n; } private Object key; @Override public final Object getRawKey() { return this.key; } @Override protected final void _setRawKey(Object key) { this.key = key; } private volatile Object value; @Override public final boolean isRemoved() { final Object o = this.value; return (o == Token.REMOVED_PHASE1) || (o == Token.REMOVED_PHASE2) || (o == Token.TOMBSTONE); } @Override public final boolean isDestroyedOrRemoved() { final Object o = this.value; return o == Token.DESTROYED || o == Token.REMOVED_PHASE1 || o == Token.REMOVED_PHASE2 || o == Token.TOMBSTONE; } @Override public final boolean isDestroyedOrRemovedButNotTombstone() { final Object o = this.value; return o == Token.DESTROYED || o == Token.REMOVED_PHASE1 || o == Token.REMOVED_PHASE2; } @Override protected final Object getValueField() { return this.value; } @Override protected final void setValueField(Object v) { this.value = v; } @Override public final Token getValueAsToken() { Object v = this.value; if (v == null) { return null; } else if (v instanceof Token) { return (Token)v; } else { return Token.NOT_A_TOKEN; } } @Override public final boolean isValueNull() { return this.value == null; } private transient ExtraTableInfo tableInfo; @Override public final ExtraTableInfo getTableInfo(GemFireContainer baseContainer) { return this.tableInfo; } @Override public final Object getContainerInfo() { return this.tableInfo; } @Override public final Object setContainerInfo(final LocalRegion owner, final Object val) { final GemFireContainer container; ExtraTableInfo tabInfo; if (owner == null) { final RowFormatter rf; if ((tabInfo = this.tableInfo) != null && (rf = tabInfo.getRowFormatter()) != null) { container = rf.container; } else { return null; } } else { container = (GemFireContainer)owner.getUserAttribute(); } if (container != null && container.isByteArrayStore()) { tabInfo = container.getExtraTableInfo(val); this.tableInfo = tabInfo; if (tabInfo != null && tabInfo.regionKeyPartOfValue()) { return tabInfo; } } return null; } @Override public final int estimateMemoryUsage() { return ClassSize.refSize; } @Override public final int getTypeFormatId() { return StoredFormatIds.ACCESS_MEM_HEAP_ROW_LOCATION_ID; } @Override public final Object cloneObject() { return this; } @Override public final RowLocation getClone() { return this; } @Override public final int compare(DataValueDescriptor other) { if (this == other) { return 0; } return this.hashCode() - other.hashCode(); } @Override public final DataValueDescriptor recycle() { return this; } @Override public final DataValueDescriptor getNewNull() { return DataValueFactory.DUMMY; } @Override public final boolean isNull() { return this == DataValueFactory.DUMMY; } @Override public final Object getObject() throws StandardException { return this; } @Override public DataValueDescriptor coalesce(DataValueDescriptor[] list, DataValueDescriptor returnValue) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public int compare(DataValueDescriptor other, boolean nullsOrderedLow) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public boolean compare(int op, DataValueDescriptor other, boolean orderedNulls, boolean unknownRV) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public boolean compare(int op, DataValueDescriptor other, boolean orderedNulls, boolean nullsOrderedLow, boolean unknownRV) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public int getLengthInBytes(DataTypeDescriptor dtd) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue in(DataValueDescriptor left, DataValueDescriptor[] inList, boolean orderedList) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue isNotNull() { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue isNullOp() { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public void normalize(DataTypeDescriptor dtd, DataValueDescriptor source) throws StandardException { } @Override public BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public void readExternalFromArray(ArrayInputStream ais) throws IOException, ClassNotFoundException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public void setValue(DataValueDescriptor theValue) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public int writeBytes(byte[] outBytes, int offset, DataTypeDescriptor dtd) { throw new UnsupportedOperationException("unexpected invocation"); } @Override public int computeHashCode(int maxWidth, int hash) { throw new UnsupportedOperationException("unexpected invocation for " + toString()); } @Override public final DataValueDescriptor getKeyColumn(int index) { throw new UnsupportedOperationException("unexpected invocation"); } @Override public final void getKeyColumns(DataValueDescriptor[] keys) { throw new UnsupportedOperationException("unexpected invocation"); } @Override public boolean compare(int op, ExecRow row, boolean byteArrayStore, int colIdx, boolean orderedNulls, boolean unknownRV) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public boolean compare(int op, CompactCompositeKey key, int colIdx, boolean orderedNulls, boolean unknownRV) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public int equals(RowFormatter rf, byte[] bytes, boolean isKeyBytes, int logicalPosition, int keyBytesPos, final DataValueDescriptor[] outDVD) throws StandardException { throw new UnsupportedOperationException("unexpected invocation"); } @Override public byte getTypeId() { throw new UnsupportedOperationException("Implement the method for DataType="+ this); } @Override public void writeNullDVD(DataOutput out) throws IOException{ throw new UnsupportedOperationException("Implement the method for DataType="+ this); } @Override public final Object getValueWithoutFaultInOrOffHeapEntry(LocalRegion owner) { final Object value = this.value; return value != null ? value : Token.NOT_AVAILABLE; } @Override public final Object getValueOrOffHeapEntry(LocalRegion owner) { return this.getValue(owner); } @Override public final Object getRawValue() { return this._getValue(); } @Override public final Version[] getSerializationVersions() { return null; } @Override public final Object getValue(GemFireContainer baseContainer) { return RegionEntryUtils.getValue(baseContainer.getRegion(), this); } @Override public final Object getValueWithoutFaultIn(GemFireContainer baseContainer) { return RegionEntryUtils.getValueWithoutFaultIn(baseContainer.getRegion(), this); } @Override public final ExecRow getRow(GemFireContainer baseContainer) { return RegionEntryUtils.getRow(baseContainer, baseContainer.getRegion(), this, this.tableInfo); } @Override public final ExecRow getRowWithoutFaultIn(GemFireContainer baseContainer) { return RegionEntryUtils.getRowWithoutFaultIn(baseContainer, baseContainer.getRegion(), this, this.tableInfo); } @Override public final int getBucketID() { return -1; } @Override protected StringBuilder appendFieldsToString(final StringBuilder sb) { sb.append("key="); final Object k = getRawKey(); final Object val = _getValue(); RegionEntryUtils.entryKeyString(k, val, getTableInfo(null), sb); sb.append("; rawValue="); ArrayUtils.objectStringNonRecursive(val, sb); sb.append("; lockState=0x").append(Integer.toHexString(getState())); return sb; } private static RegionEntryFactory factory = new RegionEntryFactory() { public final RegionEntry createEntry(RegionEntryContext context, Object key, Object value) { return new VMLocalRowLocationThinRegionEntryHeap(context, key, value); } public final Class<?> getEntryClass() { return VMLocalRowLocationThinRegionEntryHeap.class; } public RegionEntryFactory makeVersioned() { return VersionedLocalRowLocationThinRegionEntryHeap.getEntryFactory(); } @Override public RegionEntryFactory makeOnHeap() { return this; } }; public static RegionEntryFactory getEntryFactory() { return factory; } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.containerservice.v2019_02_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.Resource; import com.microsoft.azure.arm.resources.models.GroupableResourceCore; import com.microsoft.azure.arm.resources.models.HasResourceGroup; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.containerservice.v2019_02_01.implementation.ContainerServiceManager; import java.util.List; import com.microsoft.azure.management.containerservice.v2019_02_01.implementation.ContainerServiceInner; /** * Type representing ContainerService. */ public interface ContainerService extends HasInner<ContainerServiceInner>, Resource, GroupableResourceCore<ContainerServiceManager, ContainerServiceInner>, HasResourceGroup, Refreshable<ContainerService>, Updatable<ContainerService.Update>, HasManager<ContainerServiceManager> { /** * @return the agentPoolProfiles value. */ List<ContainerServiceAgentPoolProfile> agentPoolProfiles(); /** * @return the customProfile value. */ ContainerServiceCustomProfile customProfile(); /** * @return the diagnosticsProfile value. */ ContainerServiceDiagnosticsProfile diagnosticsProfile(); /** * @return the linuxProfile value. */ ContainerServiceLinuxProfile linuxProfile(); /** * @return the masterProfile value. */ ContainerServiceMasterProfile masterProfile(); /** * @return the orchestratorProfile value. */ ContainerServiceOrchestratorProfile orchestratorProfile(); /** * @return the provisioningState value. */ String provisioningState(); /** * @return the servicePrincipalProfile value. */ ContainerServiceServicePrincipalProfile servicePrincipalProfile(); /** * @return the windowsProfile value. */ ContainerServiceWindowsProfile windowsProfile(); /** * The entirety of the ContainerService definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithLinuxProfile, DefinitionStages.WithMasterProfile, DefinitionStages.WithOrchestratorProfile, DefinitionStages.WithCreate { } /** * Grouping of ContainerService definition stages. */ interface DefinitionStages { /** * The first stage of a ContainerService definition. */ interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> { } /** * The stage of the ContainerService definition allowing to specify the resource group. */ interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithLinuxProfile> { } /** * The stage of the containerservice definition allowing to specify LinuxProfile. */ interface WithLinuxProfile { /** * Specifies linuxProfile. * @param linuxProfile Profile for Linux VMs in the container service cluster * @return the next definition stage */ WithMasterProfile withLinuxProfile(ContainerServiceLinuxProfile linuxProfile); } /** * The stage of the containerservice definition allowing to specify MasterProfile. */ interface WithMasterProfile { /** * Specifies masterProfile. * @param masterProfile Profile for the container service master * @return the next definition stage */ WithOrchestratorProfile withMasterProfile(ContainerServiceMasterProfile masterProfile); } /** * The stage of the containerservice definition allowing to specify OrchestratorProfile. */ interface WithOrchestratorProfile { /** * Specifies orchestratorProfile. * @param orchestratorProfile Profile for the container service orchestrator * @return the next definition stage */ WithCreate withOrchestratorProfile(ContainerServiceOrchestratorProfile orchestratorProfile); } /** * The stage of the containerservice definition allowing to specify AgentPoolProfiles. */ interface WithAgentPoolProfiles { /** * Specifies agentPoolProfiles. * @param agentPoolProfiles Properties of the agent pool * @return the next definition stage */ WithCreate withAgentPoolProfiles(List<ContainerServiceAgentPoolProfile> agentPoolProfiles); } /** * The stage of the containerservice definition allowing to specify CustomProfile. */ interface WithCustomProfile { /** * Specifies customProfile. * @param customProfile Properties to configure a custom container service cluster * @return the next definition stage */ WithCreate withCustomProfile(ContainerServiceCustomProfile customProfile); } /** * The stage of the containerservice definition allowing to specify DiagnosticsProfile. */ interface WithDiagnosticsProfile { /** * Specifies diagnosticsProfile. * @param diagnosticsProfile Profile for diagnostics in the container service cluster * @return the next definition stage */ WithCreate withDiagnosticsProfile(ContainerServiceDiagnosticsProfile diagnosticsProfile); } /** * The stage of the containerservice definition allowing to specify ServicePrincipalProfile. */ interface WithServicePrincipalProfile { /** * Specifies servicePrincipalProfile. * @param servicePrincipalProfile Information about a service principal identity for the cluster to use for manipulating Azure APIs. Exact one of secret or keyVaultSecretRef need to be specified * @return the next definition stage */ WithCreate withServicePrincipalProfile(ContainerServiceServicePrincipalProfile servicePrincipalProfile); } /** * The stage of the containerservice definition allowing to specify WindowsProfile. */ interface WithWindowsProfile { /** * Specifies windowsProfile. * @param windowsProfile Profile for Windows VMs in the container service cluster * @return the next definition stage */ WithCreate withWindowsProfile(ContainerServiceWindowsProfile windowsProfile); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<ContainerService>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithAgentPoolProfiles, DefinitionStages.WithCustomProfile, DefinitionStages.WithDiagnosticsProfile, DefinitionStages.WithServicePrincipalProfile, DefinitionStages.WithWindowsProfile { } } /** * The template for a ContainerService update operation, containing all the settings that can be modified. */ interface Update extends Appliable<ContainerService>, Resource.UpdateWithTags<Update>, UpdateStages.WithAgentPoolProfiles, UpdateStages.WithCustomProfile, UpdateStages.WithDiagnosticsProfile, UpdateStages.WithServicePrincipalProfile, UpdateStages.WithWindowsProfile { } /** * Grouping of ContainerService update stages. */ interface UpdateStages { /** * The stage of the containerservice update allowing to specify AgentPoolProfiles. */ interface WithAgentPoolProfiles { /** * Specifies agentPoolProfiles. * @param agentPoolProfiles Properties of the agent pool * @return the next update stage */ Update withAgentPoolProfiles(List<ContainerServiceAgentPoolProfile> agentPoolProfiles); } /** * The stage of the containerservice update allowing to specify CustomProfile. */ interface WithCustomProfile { /** * Specifies customProfile. * @param customProfile Properties to configure a custom container service cluster * @return the next update stage */ Update withCustomProfile(ContainerServiceCustomProfile customProfile); } /** * The stage of the containerservice update allowing to specify DiagnosticsProfile. */ interface WithDiagnosticsProfile { /** * Specifies diagnosticsProfile. * @param diagnosticsProfile Profile for diagnostics in the container service cluster * @return the next update stage */ Update withDiagnosticsProfile(ContainerServiceDiagnosticsProfile diagnosticsProfile); } /** * The stage of the containerservice update allowing to specify ServicePrincipalProfile. */ interface WithServicePrincipalProfile { /** * Specifies servicePrincipalProfile. * @param servicePrincipalProfile Information about a service principal identity for the cluster to use for manipulating Azure APIs. Exact one of secret or keyVaultSecretRef need to be specified * @return the next update stage */ Update withServicePrincipalProfile(ContainerServiceServicePrincipalProfile servicePrincipalProfile); } /** * The stage of the containerservice update allowing to specify WindowsProfile. */ interface WithWindowsProfile { /** * Specifies windowsProfile. * @param windowsProfile Profile for Windows VMs in the container service cluster * @return the next update stage */ Update withWindowsProfile(ContainerServiceWindowsProfile windowsProfile); } } }
package org.eulerdb.kernel.storage; import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.Set; import org.apache.log4j.Logger; import org.eulerdb.kernel.commons.Common; import org.eulerdb.kernel.helper.ByteArrayHelper; import org.eulerdb.kernel.helper.FileHelper; import org.eulerdb.kernel.iterator.EdbPrimaryCursor; import org.eulerdb.kernel.iterator.EdbSecondaryCursor; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.Environment; import com.sleepycat.je.EnvironmentConfig; import com.sleepycat.je.SecondaryCursor; import com.sleepycat.je.Transaction; /** * @author Zekai Huang * */ public class EdbStorage { private Logger logger = Logger.getLogger(EdbStorage.class .getCanonicalName()); public enum storeType { VERTEX, EDGE, VERTEX_OUT, VERTEX_IN, NODEPROPERTY, EDGEPROPERTY }; public final ThreadLocal<Transaction> txs = new ThreadLocal<Transaction>() { protected Transaction initialValue() { return null; } }; private EdbKeyPairStore mNodePairs; private EdbKeyPairStore mEdgePairs; private EdbKeyPairStore mNodeOutPairs; private EdbKeyPairStore mNodeInPairs; private EdbKeyPairStore mNodePropertyPairs; private EdbKeyPairStore mEdgePropertyPairs; // private boolean mTransactional; private EdbPrimaryCursor mEdgeCursor; private EdbPrimaryCursor mNodeCursor; private EdbSecondaryCursor mEdgePropCursor; private EdbSecondaryCursor mNodePropCursor; private boolean mIsTransactional; private Environment mEnv; EdbStorage(String path, boolean transactional, boolean autoindex) { logger.debug("initStores in mode transactional: " + transactional + ", autoindex: " + autoindex + "at path:" + path); mIsTransactional = transactional; initStores(path, transactional, autoindex); } /* * public synchronized EdbStorage getInstance(String path,boolean * transactional,boolean autoindex) { if (instance == null) { instance = new * EdbStorage(path,transactional,autoindex); } return instance; } */ private void initEnv(String name, boolean isTransactional) { EnvironmentConfig envConf = new EnvironmentConfig(); // environment will be created if not exists File f = new File(FileHelper.appendFileName(EdbManager.getBase(), name)); if (!f.exists()) { f.mkdirs(); } if (!isTransactional) { envConf.setAllowCreate(true); } else { envConf.setAllowCreate(true); envConf.setTransactional(true); } mEnv = new Environment(f, envConf); } private void initStores(String name, boolean isTransactional, boolean autoIndex) { initEnv(name, isTransactional); DatabaseConfig dbConf = new DatabaseConfig(); dbConf.setAllowCreate(true); if (!isTransactional) { dbConf.setDeferredWrite(true); // dbConf.setSortedDuplicates(true); } else { dbConf.setTransactional(true); dbConf.setKeyPrefixing(true); } if (mNodePairs == null) { mNodePairs = new EdbKeyPairStore(mEnv, dbConf, Common.VERTEXSTORE, false); } if (mEdgePairs == null) { mEdgePairs = new EdbKeyPairStore(mEnv, dbConf, Common.EDGESTORE, false); } if (mNodeOutPairs == null) { mNodeOutPairs = new EdbKeyPairStore(mEnv, dbConf, Common.VERTEXOUTSTORE, false); } if (mNodeInPairs == null) { mNodeInPairs = new EdbKeyPairStore(mEnv, dbConf, Common.VERTEXINSTORE, false); } if (mNodePropertyPairs == null) { mNodePropertyPairs = new EdbKeyPairStore(mEnv, dbConf, Common.VERTEXPROPERTY, autoIndex); } if (mEdgePropertyPairs == null) { mEdgePropertyPairs = new EdbKeyPairStore(mEnv, dbConf, Common.EDGEPROPERTY, autoIndex); } } private EdbKeyPairStore getStore(storeType type) { switch (type) { case VERTEX: return mNodePairs; case EDGE: return mEdgePairs; case VERTEX_OUT: return mNodeOutPairs; case VERTEX_IN: return mNodeInPairs; case NODEPROPERTY: return mNodePropertyPairs; case EDGEPROPERTY: return mEdgePropertyPairs; default: throw new IllegalArgumentException("Type " + type + " is unknown."); } } public long getCount(storeType type) { return getStore(type).count(); } public void store(storeType type, Transaction tx, String id, Object n) { try { getStore(type).put(tx, ByteArrayHelper.serialize(id), ByteArrayHelper.serialize(n)); } catch (IOException e) { e.printStackTrace(); } } public Long getTransactionId(Transaction tx) { return tx == null ? 0 : tx.getId(); } public void delete(storeType type, Transaction tx, Object id) { try { getStore(type).delete(tx, ByteArrayHelper.serialize(id)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Object getObj(storeType type, Transaction tx, String id) { Object o = null; // mCache.get(id, tx.getId()); /* * switch(type){ case VERTEX: case EDGE: case VERTEX_OUT: case * VERTEX_IN: try { o = * ByteArrayHelper.deserialize(getStore(type).get(tx, * ByteArrayHelper.serialize(id))); } catch (IOException e) { // TODO * Auto-generated catch block e.printStackTrace(); } catch * (ClassNotFoundException e) { // TODO Auto-generated catch block * e.printStackTrace(); } break; case NODEPROPERTY: case EDGEPROPERTY: * DatabaseEntry theKey = null; try { theKey = new * DatabaseEntry(ByteArrayHelper.serialize(id)); } catch (IOException e) * { // TODO Auto-generated catch block e.printStackTrace(); } * DatabaseEntry theData = getStore(type).get(tx,theKey); * * PropertyBinding dataBinding = new PropertyBinding(); o = * dataBinding.entryToObject(theData); break; } */ try { o = ByteArrayHelper.deserialize(getStore(type).get(tx, ByteArrayHelper.serialize(id))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return o; } public EdbPrimaryCursor getCursor(storeType type, Transaction tx) { switch (type) { case EDGE: { if (mEdgeCursor != null) mEdgeCursor.close(); mEdgeCursor = new EdbPrimaryCursor(getStore(type).getCursor(tx)); return mEdgeCursor; } case VERTEX: { if (mNodeCursor != null) mNodeCursor.close(); mNodeCursor = new EdbPrimaryCursor(getStore(type).getCursor(tx)); return mNodeCursor; } default: return null; } } public EdbSecondaryCursor getSecondaryCursor(storeType type, Transaction tx, String pKey, Object pValue) { switch (type) { case EDGEPROPERTY: { if (mEdgePropCursor != null) mEdgePropCursor.close(); mEdgePropCursor = new EdbSecondaryCursor(getStore(type) .getSecondCursor(pKey, tx), pValue); return mEdgePropCursor; } case NODEPROPERTY: { if (mNodePropCursor != null) mNodePropCursor.close(); mNodePropCursor = new EdbSecondaryCursor(getStore(type) .getSecondCursor(pKey, tx), pValue); return mNodePropCursor; } default: return null; } } public boolean containsKey(storeType type, Transaction tx, String key) { try { if (getStore(type).get(tx, ByteArrayHelper.serialize(key)) != null) return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return false; } public synchronized void closeCursor() { if (mEdgeCursor != null) { mEdgeCursor.close(); mEdgeCursor = null; } if (mNodeCursor != null) { mNodeCursor.close(); mNodeCursor = null; } if (mEdgePropCursor != null) { mEdgePropCursor.close(); mEdgePropCursor = null; } if (mNodePropCursor != null) { mNodePropCursor.close(); mNodePropCursor = null; } } public synchronized void close() { closeCursor(); mNodePairs.close(); mEdgePairs.close(); mNodePairs = null; mEdgePairs = null; mNodeOutPairs.close(); mNodeOutPairs = null; mNodeInPairs.close(); mNodeInPairs = null; mNodePropertyPairs.close(); mNodePropertyPairs = null; mEdgePropertyPairs.close(); mEdgePropertyPairs = null; mEnv.close(); mEnv = null; } public void commit() { mNodeOutPairs.sync(); mNodeInPairs.sync(); mNodePropertyPairs.sync(); mEdgePropertyPairs.sync(); mNodePairs.sync(); mEdgePairs.sync(); } /* * public void openSecondary(String key, storeType type){ * getStore(type).openSecondary(key); } */ public Set<String> getKeys(storeType type) { return getStore(type).getKeys(); } public void deleteSecondary(storeType type, Transaction tx, String dbName) { getStore(type).deleteSecondary(tx, dbName); } public void createSecondaryIfNeed(storeType type, Transaction tx, String dbName) { getStore(type).createSecondaryIfNeeded(tx, dbName); } public boolean containsIndex(storeType type, String key) { return getStore(type).containsIndex(key); } public Transaction getTransaction() { if (!mIsTransactional) return null; Transaction t = txs.get(); if (t == null) { t = beginTransaction(); txs.set(t); } return txs.get(); } public void abortTransaction(){ txs.get().abort(); } public void commitTransaction(){ txs.get().commit(); } public void removeTransaction(){ txs.remove(); } public Transaction beginTransaction() { return mEnv.beginTransaction(null, null); } /* public void autoStartTransaction() { if (txs.get() == null) { txs.set(beginTransaction()); logger.info("creating new transaction"); } }*/ }
/** * * Copyright (c) Microsoft and contributors. 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. * */ // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. package com.microsoft.azure.management.trafficmanager; import com.microsoft.windowsazure.core.ServiceClient; import com.microsoft.windowsazure.credentials.SubscriptionCloudCredentials; import com.microsoft.windowsazure.management.configuration.ManagementConfiguration; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.ExecutorService; import javax.inject.Inject; import javax.inject.Named; import org.apache.http.impl.client.HttpClientBuilder; /** * Client for creating, updating, listing and deleting Azure Traffic Manager * profiles (see * http://azure.microsoft.com/en-gb/documentation/articles/traffic-manager-overview/ * for more information) */ public class TrafficManagerManagementClientImpl extends ServiceClient<TrafficManagerManagementClient> implements TrafficManagerManagementClient { private String apiVersion; /** * Gets the API version. * @return The ApiVersion value. */ public String getApiVersion() { return this.apiVersion; } private URI baseUri; /** * Gets the URI used as the base for all cloud service requests. * @return The BaseUri value. */ public URI getBaseUri() { return this.baseUri; } private SubscriptionCloudCredentials credentials; /** * Gets subscription credentials which uniquely identify Microsoft Azure * subscription. The subscription ID forms part of the URI for every * service call. * @return The Credentials value. */ public SubscriptionCloudCredentials getCredentials() { return this.credentials; } private int longRunningOperationInitialTimeout; /** * Gets or sets the initial timeout for Long Running Operations. * @return The LongRunningOperationInitialTimeout value. */ public int getLongRunningOperationInitialTimeout() { return this.longRunningOperationInitialTimeout; } /** * Gets or sets the initial timeout for Long Running Operations. * @param longRunningOperationInitialTimeoutValue The * LongRunningOperationInitialTimeout value. */ public void setLongRunningOperationInitialTimeout(final int longRunningOperationInitialTimeoutValue) { this.longRunningOperationInitialTimeout = longRunningOperationInitialTimeoutValue; } private int longRunningOperationRetryTimeout; /** * Gets or sets the retry timeout for Long Running Operations. * @return The LongRunningOperationRetryTimeout value. */ public int getLongRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Gets or sets the retry timeout for Long Running Operations. * @param longRunningOperationRetryTimeoutValue The * LongRunningOperationRetryTimeout value. */ public void setLongRunningOperationRetryTimeout(final int longRunningOperationRetryTimeoutValue) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeoutValue; } private EndpointOperations endpoints; /** * Operations for managing Traffic Manager endpoints. * @return The EndpointsOperations value. */ public EndpointOperations getEndpointsOperations() { return this.endpoints; } private ProfileOperations profiles; /** * Operations for managing Traffic Manager profiles. * @return The ProfilesOperations value. */ public ProfileOperations getProfilesOperations() { return this.profiles; } /** * Initializes a new instance of the TrafficManagerManagementClientImpl * class. * * @param httpBuilder The HTTP client builder. * @param executorService The executor service. */ public TrafficManagerManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService) { super(httpBuilder, executorService); this.endpoints = new EndpointOperationsImpl(this); this.profiles = new ProfileOperationsImpl(this); this.apiVersion = "2015-04-28-preview"; this.longRunningOperationInitialTimeout = -1; this.longRunningOperationRetryTimeout = -1; } /** * Initializes a new instance of the TrafficManagerManagementClientImpl * class. * * @param httpBuilder The HTTP client builder. * @param executorService The executor service. * @param credentials Required. Gets subscription credentials which uniquely * identify Microsoft Azure subscription. The subscription ID forms part of * the URI for every service call. * @param baseUri Optional. Gets the URI used as the base for all cloud * service requests. */ @Inject public TrafficManagerManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, @Named(ManagementConfiguration.SUBSCRIPTION_CLOUD_CREDENTIALS) SubscriptionCloudCredentials credentials, @Named(ManagementConfiguration.URI) URI baseUri) { this(httpBuilder, executorService); if (credentials == null) { throw new NullPointerException("credentials"); } else { this.credentials = credentials; } if (baseUri == null) { try { this.baseUri = new URI("https://management.azure.com"); } catch (URISyntaxException ex) { } } else { this.baseUri = baseUri; } } /** * Initializes a new instance of the TrafficManagerManagementClientImpl * class. * * @param httpBuilder The HTTP client builder. * @param executorService The executor service. * @param credentials Required. Gets subscription credentials which uniquely * identify Microsoft Azure subscription. The subscription ID forms part of * the URI for every service call. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. */ public TrafficManagerManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials) throws URISyntaxException { this(httpBuilder, executorService); if (credentials == null) { throw new NullPointerException("credentials"); } this.credentials = credentials; this.baseUri = new URI("https://management.azure.com"); } /** * Initializes a new instance of the TrafficManagerManagementClientImpl * class. * * @param httpBuilder The HTTP client builder. * @param executorService The executor service. * @param credentials Required. Gets subscription credentials which uniquely * identify Microsoft Azure subscription. The subscription ID forms part of * the URI for every service call. * @param baseUri Optional. Gets the URI used as the base for all cloud * service requests. * @param apiVersion Optional. Gets the API version. * @param longRunningOperationInitialTimeout Required. Gets or sets the * initial timeout for Long Running Operations. * @param longRunningOperationRetryTimeout Required. Gets or sets the retry * timeout for Long Running Operations. */ public TrafficManagerManagementClientImpl(HttpClientBuilder httpBuilder, ExecutorService executorService, SubscriptionCloudCredentials credentials, URI baseUri, String apiVersion, int longRunningOperationInitialTimeout, int longRunningOperationRetryTimeout) { this(httpBuilder, executorService); this.credentials = credentials; this.baseUri = baseUri; this.apiVersion = apiVersion; this.longRunningOperationInitialTimeout = longRunningOperationInitialTimeout; this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; } /** * Initializes a new instance of the TrafficManagerManagementClientImpl * class. * * @param httpBuilder The HTTP client builder. * @param executorService The executor service. */ protected TrafficManagerManagementClientImpl newInstance(HttpClientBuilder httpBuilder, ExecutorService executorService) { return new TrafficManagerManagementClientImpl(httpBuilder, executorService, this.getCredentials(), this.getBaseUri(), this.getApiVersion(), this.getLongRunningOperationInitialTimeout(), this.getLongRunningOperationRetryTimeout()); } }
package net.bytebuddy.dynamic.loading; import net.bytebuddy.ByteBuddy; import net.bytebuddy.agent.ByteBuddyAgent; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.implementation.FixedValue; import net.bytebuddy.test.utility.AgentAttachmentRule; import net.bytebuddy.test.utility.ClassFileExtraction; import net.bytebuddy.test.utility.JavaVersionRule; import net.bytebuddy.test.utility.ObjectPropertyAssertion; import net.bytebuddy.utility.RandomString; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.mockito.ArgumentCaptor; import java.lang.instrument.ClassDefinition; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; import java.util.Collections; import java.util.concurrent.Callable; import static junit.framework.TestCase.assertEquals; import static net.bytebuddy.matcher.ElementMatchers.named; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; public class ClassReloadingStrategyTest { private static final String FOO = "foo", BAR = "bar"; private static final String LAMBDA_SAMPLE_FACTORY = "net.bytebuddy.test.precompiled.LambdaSampleFactory"; @Rule public MethodRule agentAttachmentRule = new AgentAttachmentRule(); @Rule public MethodRule javaVersionRule = new JavaVersionRule(); @Test @AgentAttachmentRule.Enforce(redefinesClasses = true) public void testStrategyCreation() throws Exception { assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class)); assertThat(ClassReloadingStrategy.fromInstalledAgent(), notNullValue()); } @Test @AgentAttachmentRule.Enforce(redefinesClasses = true) public void testFromAgentClassReloadingStrategy() throws Exception { assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class)); Foo foo = new Foo(); assertThat(foo.foo(), is(FOO)); ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.fromInstalledAgent(); new ByteBuddy() .redefine(Foo.class) .method(named(FOO)) .intercept(FixedValue.value(BAR)) .make() .load(Foo.class.getClassLoader(), classReloadingStrategy); try { assertThat(foo.foo(), is(BAR)); } finally { classReloadingStrategy.reset(Foo.class); assertThat(foo.foo(), is(FOO)); } } @Test @AgentAttachmentRule.Enforce(redefinesClasses = true) public void testFromAgentClassWithAuxiliaryReloadingStrategy() throws Exception { assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class)); Foo foo = new Foo(); assertThat(foo.foo(), is(FOO)); ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.fromInstalledAgent(); String randomName = FOO + RandomString.make(); new ByteBuddy() .redefine(Foo.class) .method(named(FOO)) .intercept(FixedValue.value(BAR)) .make() .include(new ByteBuddy().subclass(Object.class).name(randomName).make()) .load(Foo.class.getClassLoader(), classReloadingStrategy); try { assertThat(foo.foo(), is(BAR)); } finally { classReloadingStrategy.reset(Foo.class); assertThat(foo.foo(), is(FOO)); } assertThat(Class.forName(randomName), notNullValue(Class.class)); } @Test @AgentAttachmentRule.Enforce(redefinesClasses = true) public void testClassRedefinitionRenamingWithStackMapFrames() throws Exception { assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class)); ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.fromInstalledAgent(); Bar bar = new Bar(); new ByteBuddy().redefine(Qux.class) .name(Bar.class.getName()) .make() .load(Bar.class.getClassLoader(), classReloadingStrategy); try { assertThat(bar.foo(), is(BAR)); } finally { classReloadingStrategy.reset(Bar.class); assertThat(bar.foo(), is(FOO)); } } @Test @AgentAttachmentRule.Enforce(redefinesClasses = true) public void testRedefinitionReloadingStrategy() throws Exception { assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class)); Foo foo = new Foo(); assertThat(foo.foo(), is(FOO)); ClassReloadingStrategy classReloadingStrategy = new ClassReloadingStrategy(ByteBuddyAgent.getInstrumentation(), ClassReloadingStrategy.Strategy.REDEFINITION); new ByteBuddy() .redefine(Foo.class) .method(named(FOO)) .intercept(FixedValue.value(BAR)) .make() .load(Foo.class.getClassLoader(), classReloadingStrategy); try { assertThat(foo.foo(), is(BAR)); } finally { classReloadingStrategy.reset(Foo.class); assertThat(foo.foo(), is(FOO)); } } @Test @AgentAttachmentRule.Enforce(retransformsClasses = true) public void testRetransformationReloadingStrategy() throws Exception { assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class)); Foo foo = new Foo(); assertThat(foo.foo(), is(FOO)); ClassReloadingStrategy classReloadingStrategy = new ClassReloadingStrategy(ByteBuddyAgent.getInstrumentation(), ClassReloadingStrategy.Strategy.RETRANSFORMATION); new ByteBuddy() .redefine(Foo.class) .method(named(FOO)) .intercept(FixedValue.value(BAR)) .make() .load(Foo.class.getClassLoader(), classReloadingStrategy); try { assertThat(foo.foo(), is(BAR)); } finally { classReloadingStrategy.reset(Foo.class); assertThat(foo.foo(), is(FOO)); } } @Test public void testPreregisteredType() throws Exception { Instrumentation instrumentation = mock(Instrumentation.class); ClassLoader classLoader = mock(ClassLoader.class); when(instrumentation.isRedefineClassesSupported()).thenReturn(true); when(instrumentation.getInitiatedClasses(classLoader)).thenReturn(new Class<?>[0]); ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.of(instrumentation).preregistered(Object.class); ArgumentCaptor<ClassDefinition> classDefinition = ArgumentCaptor.forClass(ClassDefinition.class); classReloadingStrategy.load(classLoader, Collections.singletonMap(TypeDescription.OBJECT, new byte[]{1, 2, 3})); verify(instrumentation).redefineClasses(classDefinition.capture()); assertEquals(Object.class, classDefinition.getValue().getDefinitionClass()); assertThat(classDefinition.getValue().getDefinitionClassFile(), is(new byte[]{1, 2, 3})); } @Test public void testRetransformationDiscovery() throws Exception { Instrumentation instrumentation = mock(Instrumentation.class); when(instrumentation.isRetransformClassesSupported()).thenReturn(true); assertThat(ClassReloadingStrategy.of(instrumentation), notNullValue(ClassReloadingStrategy.class)); } @Test(expected = IllegalArgumentException.class) public void testNonCompatible() throws Exception { ClassReloadingStrategy.of(mock(Instrumentation.class)); } @Test(expected = IllegalArgumentException.class) public void testNoRedefinition() throws Exception { new ClassReloadingStrategy(mock(Instrumentation.class), ClassReloadingStrategy.Strategy.REDEFINITION); } @Test(expected = IllegalArgumentException.class) public void testNoRetransformation() throws Exception { new ClassReloadingStrategy(mock(Instrumentation.class), ClassReloadingStrategy.Strategy.RETRANSFORMATION); } @Test public void testResetNotSupported() throws Exception { Instrumentation instrumentation = mock(Instrumentation.class); when(instrumentation.isRetransformClassesSupported()).thenReturn(true); new ClassReloadingStrategy(instrumentation, ClassReloadingStrategy.Strategy.RETRANSFORMATION).reset(); } @Test public void testEngineSelfReport() throws Exception { assertThat(ClassReloadingStrategy.Strategy.REDEFINITION.isRedefinition(), is(true)); assertThat(ClassReloadingStrategy.Strategy.RETRANSFORMATION.isRedefinition(), is(false)); } @Test @JavaVersionRule.Enforce(8) @AgentAttachmentRule.Enforce(retransformsClasses = true) public void testAnonymousType() throws Exception { ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileExtraction.of(Class.forName(LAMBDA_SAMPLE_FACTORY)), ByteArrayClassLoader.PersistenceHandler.MANIFEST); Instrumentation instrumentation = ByteBuddyAgent.install(); Class<?> factory = classLoader.loadClass(LAMBDA_SAMPLE_FACTORY); @SuppressWarnings("unchecked") Callable<String> instance = (Callable<String>) factory.getDeclaredMethod("nonCapturing").invoke(factory.getDeclaredConstructor().newInstance()); // Anonymous types can only be reset to their original format, if a retransformation is applied. ClassReloadingStrategy classReloadingStrategy = new ClassReloadingStrategy(instrumentation, ClassReloadingStrategy.Strategy.RETRANSFORMATION).preregistered(instance.getClass()); ClassFileLocator classFileLocator = ClassFileLocator.AgentBased.of(instrumentation, instance.getClass()); try { assertThat(instance.call(), is(FOO)); new ByteBuddy() .redefine(instance.getClass(), classFileLocator) .method(named("call")) .intercept(FixedValue.value(BAR)) .make() .load(instance.getClass().getClassLoader(), classReloadingStrategy); assertThat(instance.call(), is(BAR)); } finally { classReloadingStrategy.reset(classFileLocator, instance.getClass()); assertThat(instance.call(), is(FOO)); } } @Test public void testResetEmptyNoEffectImplicitLocator() throws Exception { Instrumentation instrumentation = mock(Instrumentation.class); when(instrumentation.isRedefineClassesSupported()).thenReturn(true); ClassReloadingStrategy.of(instrumentation).reset(); verify(instrumentation, times(2)).isRedefineClassesSupported(); verifyNoMoreInteractions(instrumentation); } @Test public void testResetEmptyNoEffect() throws Exception { Instrumentation instrumentation = mock(Instrumentation.class); ClassFileLocator classFileLocator = mock(ClassFileLocator.class); when(instrumentation.isRedefineClassesSupported()).thenReturn(true); ClassReloadingStrategy.of(instrumentation).reset(classFileLocator); verify(instrumentation, times(2)).isRedefineClassesSupported(); verifyNoMoreInteractions(instrumentation); verifyZeroInteractions(classFileLocator); } @Test public void testTransformerHandlesNullValue() throws Exception { assertThat(new ClassReloadingStrategy.Strategy.ClassRedefinitionTransformer(Collections.<Class<?>, ClassDefinition>emptyMap()).transform(mock(ClassLoader.class), FOO, Object.class, mock(ProtectionDomain.class), new byte[0]), nullValue(byte[].class)); } @Test public void testObjectProperties() throws Exception { ObjectPropertyAssertion.of(ClassReloadingStrategy.class).refine(new ObjectPropertyAssertion.Refinement<Instrumentation>() { @Override public void apply(Instrumentation mock) { when(mock.isRedefineClassesSupported()).thenReturn(true); when(mock.isRetransformClassesSupported()).thenReturn(true); } }).apply(); ObjectPropertyAssertion.of(ClassReloadingStrategy.BootstrapInjection.Enabled.class).apply(); ObjectPropertyAssertion.of(ClassReloadingStrategy.Strategy.class).apply(); ObjectPropertyAssertion.of(ClassReloadingStrategy.Strategy.ClassResettingTransformer.class).apply(); ObjectPropertyAssertion.of(ClassReloadingStrategy.BootstrapInjection.Enabled.class).apply(); ObjectPropertyAssertion.of(ClassReloadingStrategy.BootstrapInjection.Disabled.class).apply(); } @SuppressWarnings("unused") public static class Foo { /** * Padding to increase class file size. */ private long a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, b2, b3, b4, b5, b6, b7, b8, b9, b10, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10; public String foo() { return FOO; } } public static class Bar { @SuppressWarnings("unused") public String foo() { Bar bar = new Bar(); return Math.random() < 0 ? FOO : FOO; } } public static class Qux { @SuppressWarnings("unused") public String foo() { Qux qux = new Qux(); return Math.random() < 0 ? BAR : BAR; } } }
package com.yourname.flixelgame.examples.performance; import org.flixel.FlxG; import org.flixel.FlxState; import org.flixel.FlxText; import org.flixel.FlxU; import com.badlogic.gdx.math.MathUtils; public class PlayState extends FlxState { public static final int ITERATIONS = 10000; public static final float FLOAT1 = -2450.50f; public static final float FLOAT2 = -500f; public static final float FLOAT3 = 500f; public static final float FLOAT4 = -2450.50f; public static final int sInt = 90; public long start; public long elapsed; public FlxText output; @Override public void create() { output = new FlxText(0, 0, 200); add(output); log("ITERATIONS " + ITERATIONS); log("=================================="); testMathAbs(); testMathATan2(); testMathFloor(); testMathRound(); testMathPow(); testMathMax(); testMathMin(); testMathRandom(); } public void startTimer() { start = System.currentTimeMillis(); } public void stopTimer() { elapsed = System.currentTimeMillis() - start; log("elapsed time = " + elapsed + "ms"); log((elapsed * 1000.0) / 1000000 + " ms per execution"); log("----------------------------------"); } public void log(String string) { output.setText(output.getText() + string + "\n"); FlxG.log(string); } @SuppressWarnings("unused") public void testMathAbs() { //dry run to give everything time to start up float result; for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); result = Math.abs(FLOAT3); } log(" "); log("TestMathAbs"); log("Math.abs"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.abs(FLOAT2); result = Math.abs(FLOAT3); result = Math.abs(FLOAT2); result = Math.abs(FLOAT3); result = Math.abs(FLOAT2); result = Math.abs(FLOAT3); result = Math.abs(FLOAT2); result = Math.abs(FLOAT3); result = Math.abs(FLOAT2); result = Math.abs(FLOAT3); } stopTimer(); log("FlxU.abs"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxU.abs(FLOAT2); result = FlxU.abs(FLOAT3); result = FlxU.abs(FLOAT2); result = FlxU.abs(FLOAT3); result = FlxU.abs(FLOAT2); result = FlxU.abs(FLOAT3); result = FlxU.abs(FLOAT2); result = FlxU.abs(FLOAT3); result = FlxU.abs(FLOAT2); result = FlxU.abs(FLOAT3); } stopTimer(); } // TODO: math atan @SuppressWarnings("unused") public void testMathATan() { double result; for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); result = Math.atan(FLOAT1); } } @SuppressWarnings("unused") public void testMathATan2() { log(" "); log("TestMathATan2"); log("Math.atan2"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); result = Math.atan2(FLOAT1, FLOAT4); } stopTimer(); log("Gdx.atan2"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); result = MathUtils.atan2(FLOAT1, FLOAT4); } stopTimer(); } // TODO: math sqrt @SuppressWarnings("unused") public void testMathSqrt() { double result; for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); result = Math.sqrt(FLOAT1); } } @SuppressWarnings("unused") public void testMathCeil() { log(" "); log("TestMathCeil"); log("Math.ceil"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); result = Math.ceil(FLOAT1); } stopTimer(); log("FlxU.ceil"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); result = FlxU.ceil(FLOAT1); } stopTimer(); log("Gdx.ceil"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); result = MathUtils.ceil(FLOAT1); } stopTimer(); } @SuppressWarnings("unused") public void testMathRound() { log(" "); log("TestMathRound"); log("Math.round"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); result = Math.round(FLOAT1); } stopTimer(); log("FlxU.round"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); result = FlxU.round(FLOAT1); } stopTimer(); log("Gdx.round"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); result = MathUtils.round(FLOAT1); } stopTimer(); } @SuppressWarnings("unused") public void testMathFloor() { log(" "); log("TestMathFloor"); log("Math.floor"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); result = Math.floor(FLOAT1); } stopTimer(); log("FlxU.floor"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); result = FlxU.floor(FLOAT1); } stopTimer(); log("Gdx.floor"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); result = MathUtils.floor(FLOAT1); } stopTimer(); } @SuppressWarnings("unused") public void testMathPow() { log(" "); log("TestMathPow"); log("Math.pow"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); result = Math.pow(FLOAT1, FLOAT2); } stopTimer(); startTimer(); log("FlxU.pow"); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); result = FlxU.pow(FLOAT1, FLOAT2); } stopTimer(); } @SuppressWarnings("unused") public void testMathMax() { log(" "); log("TestMathMax"); log("Math.max"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); result = Math.max(FLOAT1, FLOAT2); } stopTimer(); log("FlxU.max"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); result = FlxU.max(FLOAT1, FLOAT2); } stopTimer(); } @SuppressWarnings("unused") public void testMathMin() { log(" "); log("TestMathMin"); log("Math.min"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); result = Math.min(FLOAT1, FLOAT2); } stopTimer(); log("FlxU.min"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); result = FlxU.min(FLOAT1, FLOAT2); } stopTimer(); } @SuppressWarnings("unused") public void testMathRandom() { log(" "); log("TestMathRandom"); log("Math.random"); double result; startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.random(); result = Math.random(); result = Math.random(); result = Math.random(); result = Math.random(); result = Math.random(); result = Math.random(); result = Math.random(); result = Math.random(); result = Math.random(); } stopTimer(); log("FlxG.random"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); result = FlxG.random(); } stopTimer(); log("Gdx.random"); startTimer(); for(int i = ITERATIONS - 1; i >= 0; i--) { result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); result = MathUtils.random(); } stopTimer(); } // TODO: Math IEEERemainder, not supported by GWT /*@SuppressWarnings("unused") public void testMathIEEERemainder() { double result; for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); result = Math.IEEEremainder(FLOAT1, FLOAT2); } }*/ // Not tested, but it's obvious that 180 / PI is faster. @SuppressWarnings("unused") public void testMathToDegrees() { double result; for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); result = Math.toDegrees(FLOAT1); } } // Not tested, but it's obviously that PI / 180 is faster. @SuppressWarnings("unused") public void testMathToRadians() { double result; for(int i = ITERATIONS - 1; i >= 0; i--) { result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); result = Math.toRadians(FLOAT1); } } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.adapter; import org.apache.commons.io.IOUtils; import org.jboss.arquillian.graphene.page.Page; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractAuthTest; import org.keycloak.testsuite.adapter.page.AppServerContextRoot; import org.keycloak.testsuite.arquillian.annotation.AppServerContainer; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * * @author tkyjovsk */ @AppServerContainer public abstract class AbstractAdapterTest extends AbstractAuthTest { @Page protected AppServerContextRoot appServerContextRootPage; public static final String JBOSS_DEPLOYMENT_STRUCTURE_XML = "jboss-deployment-structure.xml"; public static final URL jbossDeploymentStructure = AbstractServletsAdapterTest.class .getResource("/adapter-test/" + JBOSS_DEPLOYMENT_STRUCTURE_XML); public static final String TOMCAT_CONTEXT_XML = "context.xml"; public static final URL tomcatContext = AbstractServletsAdapterTest.class .getResource("/adapter-test/" + TOMCAT_CONTEXT_XML); @Override public void addTestRealms(List<RealmRepresentation> testRealms) { addAdapterTestRealms(testRealms); for (RealmRepresentation tr : testRealms) { log.info("Setting redirect-uris in test realm '" + tr.getRealm() + "' as " + (isRelative() ? "" : "non-") + "relative"); modifyClientRedirectUris(tr, "http://localhost:8080", ""); modifyClientUrls(tr, "http://localhost:8080", ""); if (isRelative()) { modifyClientRedirectUris(tr, appServerContextRootPage.toString(), ""); modifyClientUrls(tr, appServerContextRootPage.toString(), ""); modifyClientWebOrigins(tr, "8080", System.getProperty("auth.server.http.port", null)); modifySamlMasterURLs(tr, "/", "http://localhost:" + System.getProperty("auth.server.http.port", null) + "/"); modifySAMLClientsAttributes(tr, "8080", System.getProperty("auth.server.http.port", "8180")); } else { modifyClientRedirectUris(tr, "^(/.*/\\*)", appServerContextRootPage.toString() + "$1"); modifyClientUrls(tr, "^(/.*)", appServerContextRootPage.toString() + "$1"); modifySamlMasterURLs(tr, "8080", System.getProperty("auth.server.http.port", null)); modifySAMLClientsAttributes(tr, "8080", System.getProperty("app.server.http.port", "8280")); modifyClientJWKSUrl(tr, "^(/.*)", appServerContextRootPage.toString() + "$1"); } if ("true".equals(System.getProperty("auth.server.ssl.required"))) { tr.setSslRequired("all"); } } } private void modifyClientJWKSUrl(RealmRepresentation realm, String regex, String replacement) { if (realm.getClients() != null) { realm.getClients().stream().filter(client -> "client-jwt".equals(client.getClientAuthenticatorType())).forEach(client -> { Map<String, String> attr = client.getAttributes(); attr.put("jwks.url", attr.get("jwks.url").replaceFirst(regex, replacement)); client.setAttributes(attr); }); } } public abstract void addAdapterTestRealms(List<RealmRepresentation> testRealms); public boolean isRelative() { return testContext.isRelativeAdapterTest(); } protected void modifyClientRedirectUris(RealmRepresentation realm, String regex, String replacement) { if (realm.getClients() != null) { for (ClientRepresentation client : realm.getClients()) { List<String> redirectUris = client.getRedirectUris(); if (redirectUris != null) { List<String> newRedirectUris = new ArrayList<>(); for (String uri : redirectUris) { newRedirectUris.add(uri.replaceAll(regex, replacement)); } client.setRedirectUris(newRedirectUris); } } } } protected void modifyClientUrls(RealmRepresentation realm, String regex, String replacement) { if (realm.getClients() != null) { for (ClientRepresentation client : realm.getClients()) { String baseUrl = client.getBaseUrl(); if (baseUrl != null) { client.setBaseUrl(baseUrl.replaceAll(regex, replacement)); } String adminUrl = client.getAdminUrl(); if (adminUrl != null) { client.setAdminUrl(adminUrl.replaceAll(regex, replacement)); } } } } protected void modifyClientWebOrigins(RealmRepresentation realm, String regex, String replacement) { if (realm.getClients() != null) { for (ClientRepresentation client : realm.getClients()) { List<String> webOrigins = client.getWebOrigins(); if (webOrigins != null) { List<String> newWebOrigins = new ArrayList<>(); for (String uri : webOrigins) { newWebOrigins.add(uri.replaceAll(regex, replacement)); } client.setWebOrigins(newWebOrigins); } } } } protected void modifySAMLClientsAttributes(RealmRepresentation realm, String regex, String replacement) { if (realm.getClients() != null) { for (ClientRepresentation client : realm.getClients()) { if (client.getProtocol() != null && client.getProtocol().equals("saml")) { log.info("Modifying attributes of SAML client: " + client.getClientId()); for (Map.Entry<String, String> entry : client.getAttributes().entrySet()) { client.getAttributes().put(entry.getKey(), entry.getValue().replaceAll(regex, replacement)); } } } } } protected void modifySamlMasterURLs(RealmRepresentation realm, String regex, String replacement) { if (realm.getClients() != null) { for (ClientRepresentation client : realm.getClients()) { if (client.getProtocol() != null && client.getProtocol().equals("saml")) { log.info("Modifying master URL of SAML client: " + client.getClientId()); String masterUrl = client.getAdminUrl(); if (masterUrl == null) { masterUrl = client.getBaseUrl(); } masterUrl = masterUrl.replaceFirst(regex, replacement); client.setAdminUrl(masterUrl + ((!masterUrl.endsWith("/saml")) ? "/saml" : "")); } } } } /** * Modifies baseUrl, adminUrl and redirectUris for client based on real * deployment url of the app. * * @param realm * @param clientId * @param deploymentUrl */ protected void fixClientUrisUsingDeploymentUrl(RealmRepresentation realm, String clientId, String deploymentUrl) { for (ClientRepresentation client : realm.getClients()) { if (clientId.equals(client.getClientId())) { if (client.getBaseUrl() != null) { client.setBaseUrl(deploymentUrl); } if (client.getAdminUrl() != null) { client.setAdminUrl(deploymentUrl); } List<String> redirectUris = client.getRedirectUris(); if (redirectUris != null) { List<String> newRedirectUris = new ArrayList<>(); for (String uri : redirectUris) { newRedirectUris.add(deploymentUrl + "/*"); } client.setRedirectUris(newRedirectUris); } } } } public static void addContextXml(Archive archive, String contextPath) { try { String contextXmlContent = IOUtils.toString(tomcatContext.openStream()) .replace("%CONTEXT_PATH%", contextPath); archive.add(new StringAsset(contextXmlContent), "/META-INF/context.xml"); } catch (IOException ex) { throw new RuntimeException(ex); } } }
package core; import javax.swing.*; import javax.swing.Timer; import enemies.Enemy; import players.Direction; import players.Player; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.util.*; import java.util.List; public class Engine extends JPanel implements ActionListener, KeyListener { private final double fieldArea; // an array containing the colors to fill the polygons private Color[] colors; // the map saves the color of every polygon private Map<GeneralPath, Color> polygonColor; private Line2D startLine; private Line2D endLine; private Graphics2D g2d; private int startX; private int startY; private Timer timer; private boolean isPressed; private boolean isDrawn; private Player player; private Enemy enemy; // the temporary lines that are drawn be the player are going to be saved in this list private List<Line2D> currentLines; private GeneralPath polygon; // list with all the islands(polygons) that have been drawn by the player private List<GeneralPath> polygons; public Engine(Player player, Enemy enemy) { super(); setBackground(Color.WHITE); setPreferredSize(new Dimension(Mondrian.WIDTH, Mondrian.HEIGHT)); // making sure the Panel will stay with the given width and height setMaximumSize(new Dimension(Mondrian.WIDTH, Mondrian.HEIGHT)); setMinimumSize(new Dimension(Mondrian.WIDTH, Mondrian.HEIGHT)); setDoubleBuffered(true); // call step() 60 fps this.timer = new Timer(1000/60, this); this.timer.start(); this.player = player; this.enemy = enemy; this.polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD); this.fieldArea = (Mondrian.WIDTH * Mondrian.HEIGHT); // initialize the array colors with the possible colors this.colors = new Color[] {Color.RED, Color.YELLOW, Color.BLACK, Color.LIGHT_GRAY}; this.isPressed = false; this.isDrawn = false; this.currentLines = new ArrayList<Line2D>(); this.polygons = new LinkedList<GeneralPath>(); this.polygonColor = new HashMap<GeneralPath, Color>(); } @Override public void paintComponent(Graphics g) { this.g2d = (Graphics2D)g; super.paintComponent(this.g2d); this.drawCurrentLines(); this.drawFinalizedPolygon(); this.drawNewLine(); this.enemy.drawObject(this.g2d); this.drawPolygons(); this.player.drawObject(this.g2d); this.gameOver(); } // draws all the lines that were made by the player when the player has left a safe location for the last time public void drawCurrentLines() { // no polygon is being made this.isDrawn = false; // initialize the lines this.startLine = new Line2D.Double(0,0,0,0); this.endLine = new Line2D.Double(0,0,0,0); if ((!this.currentLines.isEmpty())) { // adds the last line to the list and draws it, when the player reaches the bounds if (this.player.isOnBounds()) { // create a new line which will be given the value of the last line from the list with the current lines Line2D lastLine = this.currentLines.get(this.currentLines.size() - 1); // if the coordinates of the last line in the list meet the requirements of the if statement // then the last line would be added to the list if ( (lastLine.getX2() == (Mondrian.WIDTH - this.player.getVelocity()) || lastLine.getX2() == (this.player.getVelocity())) || (lastLine.getY2() == (Mondrian.HEIGHT - this.player.getVelocity()) || lastLine.getY2() == (this.player.getVelocity()))) { // adds the last line to the list Line2D line = new Line2D.Double(this.startX, this.startY, this.player.getX(), this.player.getY()); this.currentLines.add(line); } } // get the first and the last line from the current lines this.startLine = this.currentLines.get(0); this.endLine = this.currentLines.get(this.currentLines.size() - 1); // checks if the player has finished an island or a is on safe position if ((!this.player.isOnBounds())) { // iterates through the lines that have been drawn by the player by far for (Line2D line : this.currentLines) { // setting the color to black before drawing a line this.g2d.setColor(Color.BLACK); // if the player is still moving around the field, a new line would be drawn this.g2d.draw(new Line2D.Double(line.getX1(), line.getY1(), line.getX2(), line.getY2())); } } } } // draws the new line that was made by the player public void drawNewLine() { // if the player is moving if(this.isPressed) { // check if the player is not on an island if ((!this.player.isOnBounds())) { // save the current line in a list with the current lines and all the lines Line2D line = new Line2D.Double(this.startX, this.startY, this.player.getX(), this.player.getY()); this.currentLines.add(line); if ((!this.currentLines.isEmpty())) { // get the first and the last line from the current lines this.startLine = this.currentLines.get(0); this.endLine = this.currentLines.get(this.currentLines.size() - 1); } if ((!this.isOnIsland())) { // draw a suitable line after the ball switch (this.player.getDirection()) { case UP: this.g2d.draw(new Line2D.Double(this.startX, this.startY, (this.player.getX()), (this.player.getY()) + (this.player.getLength() / 2))); break; case DOWN: this.g2d.draw(new Line2D.Double(this.startX, this.startY, this.player.getX(), (this.player.getY() - (this.player.getLength() / 2)))); break; case RIGHT: this.g2d.draw(new Line2D.Double(this.startX, this.startY, (this.player.getX() - (this.player.getLength() / 2)), this.player.getY())); break; case LEFT: this.g2d.draw(new Line2D.Double(this.startX, this.startY, (this.player.getX() + (this.player.getLength() / 2)), this.player.getY())); break; } } } } else { // the last coordinates of the player before he starts drawing this.startX = this.player.getX(); this.startY = this.player.getY(); } } // draws all the polygons that have been drawn by the player so far public void drawPolygons() { //Collections.reverse(this.polygons); for (GeneralPath polygon : this.polygons) { // every polygon has a random color if (this.polygonColor.containsKey(polygon)) { this.g2d.setColor(this.polygonColor.get(polygon)); } else { this.g2d.setColor(Color.YELLOW); } this.g2d.draw(polygon); this.g2d.fill(polygon); } //Collections.reverse(this.polygons); } public void drawFinalizedPolygon() { /** 1.creates a current polygon but not the whole one */ if (this.player.isOnBounds() && (!this.currentLines.isEmpty())) { for (Line2D line : this.currentLines) { // when the player is already on a safe position, a polygon is going to be created // the first line will be added to the polygon with moveTo if (line.equals(this.startLine)) { this.polygon.moveTo(line.getX1(), line.getY1()); this.polygon.lineTo(line.getX2(), line.getY2()); } // all other lines with lineTo else { this.polygon.lineTo(line.getX1(), line.getY1()); this.polygon.lineTo(line.getX2(), line.getY2()); } } // confirms that a current polygon has been created this.isDrawn = true; // clears the list of lines so that the new lines could be added this.currentLines = new ArrayList<Line2D>(); } /** 2.finalizes the a polygon the right way */ // checks if a current polygon is drawn and the player is located on a safe place (island) // and draws the polygon that does not include the enemy if (this.isDrawn && this.player.isOnBounds()) { // creates two polygons which will cover the whole area and check in which part is the enemy GeneralPath polygon1 = (GeneralPath) this.polygon.clone(); GeneralPath polygon2 = (GeneralPath) this.polygon.clone(); // when the starting point at coordinates x == 0 starts if (this.startLine.getX1() == 0) { if (this.endLine.getY2() == 0) { // makes the first area polygon1.lineTo(this.startLine.getX1(), this.endLine.getY2()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(Mondrian.WIDTH, this.endLine.getY2()); polygon2.lineTo(Mondrian.WIDTH, Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getY2() == Mondrian.HEIGHT) { // makes the first area polygon1.lineTo(this.startLine.getX1(), this.endLine.getY2()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(Mondrian.WIDTH, this.endLine.getY2()); polygon2.lineTo(Mondrian.WIDTH, 0); polygon2.lineTo(this.startLine.getX1(), 0); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == 0) { // makes the first area polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // checks in if the end point is over the start point if (this.startLine.getY1() > this.endLine.getY2()) { // makes the second area polygon2.lineTo(this.startLine.getX1(), 0); polygon2.lineTo(Mondrian.WIDTH, 0); polygon2.lineTo(Mondrian.WIDTH, Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } else { // makes the second area polygon2.lineTo(this.startLine.getX1(), Mondrian.HEIGHT); polygon2.lineTo(Mondrian.WIDTH, Mondrian.HEIGHT); polygon2.lineTo(Mondrian.WIDTH, 0); polygon2.lineTo(this.startLine.getX1(), 0); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == Mondrian.WIDTH) { // makes the startLine area polygon1.lineTo(this.endLine.getX2(), 0); polygon1.lineTo(this.startLine.getX1(), 0); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(this.endLine.getX2(), Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), Mondrian.HEIGHT); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } } else if (this.startLine.getX1() == Mondrian.WIDTH) { if (this.endLine.getY2() == 0) { // makes the first area polygon1.lineTo(this.startLine.getX1(), this.endLine.getY2()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(0, this.endLine.getY2()); polygon2.lineTo(0, Mondrian.HEIGHT); polygon2.lineTo(Mondrian.WIDTH, Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getY2() == Mondrian.HEIGHT) { // makes the first area polygon1.lineTo(this.startLine.getX1(), this.endLine.getY2()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(0, this.endLine.getY2()); polygon2.lineTo(0, 0); polygon2.lineTo(this.startLine.getX1(), 0); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == 0) { // makes the first area polygon1.lineTo(this.endLine.getX2(), 0); polygon1.lineTo(this.startLine.getX1(), 0); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(this.endLine.getX2(), Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), Mondrian.HEIGHT); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == Mondrian.WIDTH) { // makes the first area polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // checks in if the end point is over the start point if (this.startLine.getY1() > this.endLine.getY2()) { // makes the second area polygon2.lineTo(this.startLine.getX1(), 0); polygon2.lineTo(0, 0); polygon2.lineTo(0, Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), Mondrian.HEIGHT); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } else { // makes the second area polygon2.lineTo(this.startLine.getX1(), Mondrian.HEIGHT); polygon2.lineTo(0, Mondrian.HEIGHT); polygon2.lineTo(0, 0); polygon2.lineTo(this.startLine.getX1(), 0); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } this.polygonContainsEnemy(polygon1, polygon2); } } else if (this.startLine.getY1() == 0) { if (this.endLine.getY2() == 0) { // makes the startLine area polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // checks in if the end point is over the start point if (this.startLine.getX1() > this.endLine.getX2()) { // makes the second area polygon2.lineTo(0, this.startLine.getY1()); polygon2.lineTo(0, Mondrian.HEIGHT); polygon2.lineTo(Mondrian.WIDTH, Mondrian.HEIGHT); polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } else { // makes the second area polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon2.lineTo(Mondrian.WIDTH, Mondrian.HEIGHT); polygon2.lineTo(0, Mondrian.HEIGHT); polygon2.lineTo(0, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getY2() == Mondrian.HEIGHT) { // makes the first area polygon1.lineTo(0, this.endLine.getY2()); polygon1.lineTo(0, this.startLine.getY1()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(Mondrian.WIDTH, this.endLine.getY2()); polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == 0) { // makes the first area polygon1.lineTo(this.startLine.getY1(), this.endLine.getX2()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(this.endLine.getX2(), Mondrian.HEIGHT); polygon2.lineTo(Mondrian.WIDTH, Mondrian.HEIGHT); polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == Mondrian.WIDTH) { // makes the first area polygon1.lineTo(this.endLine.getX2(), this.startLine.getY1()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(this.endLine.getX2(), Mondrian.HEIGHT); polygon2.lineTo(0, Mondrian.HEIGHT); polygon2.lineTo(0, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } } else if (this.startLine.getY1() == Mondrian.HEIGHT) { if (this.endLine.getY2() == 0) { // makes the first area polygon1.lineTo(0, this.endLine.getY2()); polygon1.lineTo(0, this.startLine.getY1()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(Mondrian.WIDTH, this.endLine.getY2()); polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getY2() == Mondrian.HEIGHT) { // makes the first area polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // checks in if the end point is over the start point if (this.startLine.getX1() > this.endLine.getX2()) { // makes the second area polygon2.lineTo(0, this.startLine.getY1()); polygon2.lineTo(0, 0); polygon2.lineTo(Mondrian.WIDTH, 0); polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } else { // makes the second area polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon2.lineTo(Mondrian.WIDTH, 0); polygon2.lineTo(0, 0); polygon2.lineTo(0, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); } this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == 0) { // makes the first area polygon1.lineTo(this.endLine.getX2(), this.startLine.getY1()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(this.endLine.getX2(), 0); polygon2.lineTo(Mondrian.WIDTH, 0); polygon2.lineTo(Mondrian.WIDTH, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } else if (this.endLine.getX2() == Mondrian.WIDTH) { // makes the first area polygon1.lineTo(this.endLine.getX2(), this.startLine.getY1()); polygon1.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon1.closePath(); // makes the second area polygon2.lineTo(this.endLine.getX2(), 0); polygon2.lineTo(0, 0); polygon2.lineTo(0, this.startLine.getY1()); polygon2.lineTo(this.startLine.getX1(), this.startLine.getY1()); polygon2.closePath(); // checks in which polygon is not the enemy this.polygonContainsEnemy(polygon1, polygon2); } } // adding the current polygon to the list this.polygons.add(this.polygon); // puts a polygon in the map with a random-generated color this.polygonColor.put(this.polygon,this.randomColor()); // clear the current polygon this.polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD); } } // checks if a polygon contains the enemy (helper method to drawFinalizedPolygon()) public void polygonContainsEnemy(GeneralPath polygon1, GeneralPath polygon2) { if ((!polygon1.contains(this.enemy.getX(), this.enemy.getY()))) { this.polygon = (GeneralPath)polygon1.clone(); } else if ((!polygon2.contains(this.enemy.getX(), this.enemy.getY()))) { this.polygon = (GeneralPath)polygon2.clone(); } } // checks if the enemy touches a current line public boolean enemyIntersectsLine() { for (Line2D elem : this.currentLines) { if(elem.intersects(this.enemy.getBounds())) { return true; } } return false; } public void bounce() { // checks if the enemy is in contact with a polygon that has been drawn for (GeneralPath elem : this.polygons) { this.enemy.intersect(elem); } } public boolean isOnIsland() { for (GeneralPath polygon : this.polygons) { if (polygon.contains(this.player.getX(), this.player.getY())) { return true; } } return false; } public void gameOver() { if (this.isDead()) { this.drawEndOptions(Color.RED, "You Lose!"); } else if (this.youWon()) { this.drawEndOptions(Color.BLUE, "You Won!"); } } // helper method to gameOver() private void drawEndOptions(Color color, String message) { timer.stop(); this.g2d.setColor(color); this.g2d.setFont(new Font(Font.DIALOG, Font.BOLD, 18)); this.g2d.drawString(message, (Mondrian.WIDTH/3), (Mondrian.HEIGHT/2)); this.g2d.setFont(new Font(Font.DIALOG, Font.BOLD, 14)); this.g2d.drawString("Press esc to exit.", (Mondrian.WIDTH / 3), (Mondrian.HEIGHT - (Mondrian.HEIGHT / 3))); } public boolean isDead() { // if the player is not on a safe position and gets touched by the ball the game is over if ((!this.player.isOnBounds()) && (!this.isOnIsland())) { if (this.player.intersects(this.enemy.getBounds()) || this.enemyIntersectsLine()) { return true; } } return false; } // checks whether you have filled more than 80% of the filled public boolean youWon() { double surface = this.calculateFilledSurface(); return (surface > (this.fieldArea * (80.0/100.0))); } // helper method to youWon() private double calculateFilledSurface() { double result = 0; if ((!this.polygons.isEmpty())) { for (GeneralPath polygon : this.polygons) { result += (polygon.getBounds2D().getHeight() * polygon.getBounds2D().getWidth()); } } result *= (80.0/100.0); return result; } // makes sure all the needed actions are performed @Override public void actionPerformed(ActionEvent e){ this.update(); } // updates all the elements on the field public void update() { this.player.update(); this.enemy.update(); this.bounce(); // resets the position of the enemy, if it has stuck in a polygon this.resetEnemy(); this.repaint(); } @Override public void keyPressed(KeyEvent e) { // if a key is not pressed if ((!this.isPressed)) { int keyCode = e.getKeyCode(); // makes sure that two keys wont be pressed at the same time this.isPressed = true; // checks which key is pressed switch (keyCode) { case KeyEvent.VK_UP: this.player.setDirection(Direction.UP); break; case KeyEvent.VK_DOWN: this.player.setDirection(Direction.DOWN); break; case KeyEvent.VK_LEFT: this.player.setDirection(Direction.LEFT); break; case KeyEvent.VK_RIGHT: this.player.setDirection(Direction.RIGHT); break; case KeyEvent.VK_ESCAPE: System.exit(0); break; } } } @Override public void keyTyped(KeyEvent e) { // stays empty, because we do not need it } @Override public void keyReleased(KeyEvent e) { // makes sure that no key is pressed this.isPressed = false; int keyCode = e.getKeyCode(); // changes the direction of the enemy on a random base this.changeEnemyDirection(); // when a key is released the player stops moving switch (keyCode) { case KeyEvent.VK_UP: this.player.setDirection(null); break; case KeyEvent.VK_DOWN: this.player.setDirection(null); break; case KeyEvent.VK_LEFT: this.player.setDirection(null); break; case KeyEvent.VK_RIGHT: this.player.setDirection(null); break; case KeyEvent.VK_ESCAPE: System.exit(0); break; } } // changes the direction of the enemy on a random base public void changeEnemyDirection() { // not every time when a key is pressed, the enemy changes his direction Random randBool = new Random(); // the changing of the direction of the enemy would be randomly decided boolean changeDirection = randBool.nextBoolean(); // changes the direction of the enemy if (changeDirection) { this.enemy.changeDeltaX(-4, 4); this.enemy.changeDeltaY(-4, 4); } } // picks a random color from the array public Color randomColor() { int min = 0; int max = this.colors.length - 1; Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randNum = rand.nextInt((max - min) + 1) + min; return this.colors[randNum]; } // helper method for resetEnemy() private boolean EngineCenterFilled() { // checks if the player has already build a polygon that covers the center of the field for (GeneralPath polygon : this.polygons) { if (polygon.contains((Mondrian.WIDTH / 2), (Mondrian.HEIGHT / 2))) { return true; } } return false; } public void resetEnemy() { // if the enemy is on an island he would be transported to the center if it is not filled for (GeneralPath polygon : this.polygons) { if (polygon.contains(this.enemy.getX(),this.enemy.getY())) { if (!this.EngineCenterFilled()) { this.enemy.setX((Mondrian.WIDTH / 2)); this.enemy.setY((Mondrian.HEIGHT / 2)); break; } else { Random rand = new Random(); this.enemy.setX((int)(Mondrian.WIDTH * rand.nextDouble())); this.enemy.setY((int)(Mondrian.HEIGHT * rand.nextDouble())); break; } } } } }
package com.evature.evasdk.evaapis.crossplatform; import com.evature.evasdk.evaapis.crossplatform.flow.Flow; import com.evature.evasdk.util.DLog; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class EvaApiReply implements Serializable { private static final long serialVersionUID = 1L; public static boolean VERBOSE = true; private final String TAG = "EvaApiReply"; public String sayIt; public String sessionId; public String transactionId; public String transcribedText; public String originalInputText; public EvaChat chat; public EvaDialog dialog; public EvaLocation[] locations; public EvaLocation[] alt_locations; public Map<String, String> ean; public Sabre sabre; public RequestAttributes requestAttributes; public Map<String, Boolean> geoAttributes; public FlightAttributes flightAttributes; public HotelAttributes hotelAttributes; public ServiceAttributes serviceAttributes; public CruiseAttributes cruiseAttributes; public EvaTravelers travelers; public EvaMoney money; public PNRAttributes pnrAttributes; public Flow flow; // covers the top level understanding of what the user asks for, and what to do next public String errorMessage; // error code returned from Eva service public List<EvaWarning> evaWarnings = new ArrayList<EvaWarning>(); public List<String> parseErrors = new ArrayList<String>(); // errors identified during the parsing public ParsedText parsedText; public List<String> sessionText = new ArrayList<String>(); public transient JSONObject JSONReply; public EvaApiReply(String fullReply) { initFromJson(fullReply); } private void initFromJson(String fullReply) { parseErrors = new ArrayList<String>(); evaWarnings = new ArrayList<EvaWarning>(); try { this.JSONReply = new JSONObject(fullReply); JSONObject jFullReply = JSONReply; if (VERBOSE) { DLog.d(TAG, "Eva Reply:"); // Android log buffer truncates extra long text - so split to lines into chunks String replyStr = jFullReply.toString(2); int start = 0; int chunkSize = 512; int end = chunkSize; while (end < replyStr.length()) { DLog.d(TAG, replyStr.substring(start, end)); start = end; end += chunkSize; } DLog.d(TAG, replyStr.substring(start, replyStr.length())); // splitting by \n isn't good - slows down the device too much when connected by USB to LogCat // String[] splitLines = jFullReply.toString(2).split("\n"); // for (String line : splitLines) { // // don't go through the listeners and (File:Line) suffix of DLog // android.util.Log.d(TAG, line); // } } boolean status = jFullReply.optBoolean("status", false); if (!status) { errorMessage = jFullReply.optString("message", "Unknown Error"); } else { if (jFullReply.has("session_id")) { sessionId = jFullReply.getString("session_id"); } if (jFullReply.has("transaction_key")) { transactionId = jFullReply.getString("transaction_key"); } JSONObject jApiReply = jFullReply.getJSONObject("api_reply"); if (jApiReply.has("TranscribedText")) { transcribedText = jApiReply.getString("TranscribedText"); } if (jApiReply.has("original_input_text")) { originalInputText = jApiReply.getString("original_input_text"); } if (jApiReply.has("Warnings")) { JSONArray jWarn = jApiReply.getJSONArray("Warnings"); for (int i=0; i<jWarn.length(); i++) { try { EvaWarning warning = new EvaWarning(jWarn.getJSONArray(i)); evaWarnings.add(warning); } catch(JSONException e) { // warnings may contain some non-array that we can ignore } } } if (jApiReply.has("Last Utterance Parsed Text")) { parsedText = new ParsedText(jApiReply.getJSONObject("Last Utterance Parsed Text"), parseErrors); } if (jApiReply.has("Dialog")) { dialog = new EvaDialog(jApiReply.getJSONObject("Dialog"), parseErrors); } if (jApiReply.has("SayIt")) { sayIt = jApiReply.getString("SayIt"); } if (jApiReply.has("Locations")) { JSONArray jLocations = jApiReply.getJSONArray("Locations"); locations = new EvaLocation[jLocations.length()]; for (int index = 0; index < jLocations.length(); index++) { locations[index] = new EvaLocation(jLocations.getJSONObject(index), parseErrors); } } if (jApiReply.has("Alt Locations")) { JSONArray jLocations = jApiReply.getJSONArray("Alt Locations"); alt_locations = new EvaLocation[jLocations.length()]; for (int index = 0; index < jLocations.length(); index++) { alt_locations[index] = new EvaLocation(jLocations.getJSONObject(index), parseErrors); } } if (jApiReply.has("ean")) { JSONObject jEan = jApiReply.getJSONObject("ean"); @SuppressWarnings("unchecked") Iterator<String> nameItr = jEan.keys(); ean = new HashMap<String, String>(); while (nameItr.hasNext()) { String key = nameItr.next().toString(); String value = jEan.getString(key); ean.put(key, value); } } if (jApiReply.has("sabre")) { JSONObject jSabre = jApiReply.getJSONObject("sabre"); sabre = new Sabre(jSabre, parseErrors); } if (jApiReply.has("Geo Attributes")) { JSONObject jGeo = jApiReply.getJSONObject("Geo Attributes"); @SuppressWarnings("unchecked") Iterator<String> nameItr = jGeo.keys(); geoAttributes = new HashMap<String, Boolean>(); while (nameItr.hasNext()) { String key = nameItr.next().toString(); Boolean value = jGeo.getBoolean(key); geoAttributes.put(key, value); } } if (jApiReply.has("Travelers")) { travelers = new EvaTravelers(jApiReply.getJSONObject("Travelers"), parseErrors); } if (jApiReply.has("Money")) { money = new EvaMoney(jApiReply.getJSONObject("Money"), parseErrors); } if (jApiReply.has("Flight Attributes")) { flightAttributes = new FlightAttributes(jApiReply.getJSONObject("Flight Attributes"), parseErrors); } if (jApiReply.has("Hotel Attributes")) { hotelAttributes = new HotelAttributes(jApiReply.getJSONObject("Hotel Attributes"), parseErrors); } if (jApiReply.has("Service Attributes")) { serviceAttributes = new ServiceAttributes(jApiReply.getJSONObject("Service Attributes"), parseErrors); } if (jApiReply.has("Request Attributes")) { JSONObject requestAttr = jApiReply.getJSONObject("Request Attributes"); if (requestAttr.has("PNR")) { pnrAttributes = new PNRAttributes(requestAttr.getJSONObject("PNR"), parseErrors); } requestAttributes = new RequestAttributes(jApiReply.getJSONObject("Request Attributes"), parseErrors); } if (jApiReply.has("Cruise Attributes")) { cruiseAttributes = new CruiseAttributes(jApiReply.getJSONObject("Cruise Attributes"), parseErrors); } if (jApiReply.has("Flow")) { flow = new Flow(jApiReply.getJSONArray("Flow"), parseErrors, locations, jApiReply); } if (jApiReply.has("Chat")) { chat = new EvaChat(jApiReply.getJSONObject("Chat"), parseErrors); } if (jApiReply.has("SessionText")) { JSONArray jArray = jApiReply.getJSONArray("SessionText"); for (int i=0; i<jArray.length(); i++) { sessionText.add(jArray.getString(i)); } } } } catch (JSONException e) { DLog.e(TAG, "Bad EVA reply!", e); parseErrors.add("Exception during parsing: "+e.getMessage()); } if (parseErrors.size() > 0) { DLog.w(TAG, "reply is "+fullReply); } } private void writeObject(ObjectOutputStream oos) throws IOException { // write only the JSON - to save space and time oos.writeObject(JSONReply.toString()); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { initFromJson((String)ois.readObject()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.jini.test.spec.url.util; import java.util.logging.Level; // com.sun.jini.qa import com.sun.jini.qa.harness.QATest; import com.sun.jini.qa.harness.QAConfig; // com.sun.jini.qa.harness import com.sun.jini.qa.harness.QAConfig; // base class for QAConfig import com.sun.jini.qa.harness.TestException; // java.util import java.util.logging.Level; import java.util.Vector; // java.net import java.net.URL; /** * <pre> * This is an abstract class that is extended by the following tests: * - {@link com.sun.jini.test.spec.url.file.integrity.ProvidesIntegrity url.file.integrity.ProvidesIntegrity} * - {@link com.sun.jini.test.spec.url.httpmd.integrity.ProvidesIntegrity url.httpmd.integrity.ProvidesIntegrity} * - {@link com.sun.jini.test.spec.url.https.integrity.ProvidesIntegrity url.https.integrity.ProvidesIntegrity} * </pre> */ public abstract class AbstractProvidesIntegrity extends QATest { QAConfig config; /** * All Test Cases (each element describes a Test Case). */ protected Vector items = new Vector(); /** * This method performs all preparations. */ public void setup(QAConfig config) throws Exception { super.setup(config); this.config = (QAConfig) config; // or this.config = getConfig(); } /** * This method performs all actions mentioned in class description. */ public void run() throws Exception { boolean returnedVal = true; for (int i = 0; i < items.size(); i++) { boolean retVal = testCase((TestItem) items.get(i)); if (retVal != true) { // commented due to 'fast-fail' approach // returnedVal = retVal; break; } } if (returnedVal != true) { throw new TestException( "" + " test failed"); } return; } /** * Test Case actions. * * @param ti {@link AbstractProvidesIntegrity.TestItem} * object that descibes a Test Case * @return result of the Test Case (true (if the returned * value is equal to the expected one) or false) */ public boolean testCase(TestItem ti) { /* Test Case name */ String t_name = ti.getTestCaseName(); logger.log(Level.FINE, "\n=============== Test Case name: " + t_name); /* Testing */ boolean ret = checker(ti); if (ret != true) { logger.log(Level.FINE, t_name + " test case failed"); return false; } logger.log(Level.FINE, t_name + " test case passed"); return true; } /** * Checking test assertion. * * @param ti {@link AbstractProvidesIntegrity.TestItem} * object that descibes a Test Case * @return true (if the returned result is equal to * the expected one) or false otherwise */ public abstract boolean checker(TestItem ti); /** * Auxiliary class that describes a Test Case. */ protected class TestItem { /** * The Test Case name. */ protected String testCaseName; /** {@link java.net.URL URL} object */ protected URL testURL; /** * Expected boolean value. */ protected boolean expectedBoolean; /** * Expected Exception (Class object). */ protected Class expectedException; /** * Creating {@link AbstractProvidesIntegrity.TestItem} * object (Constructor). * * @param tcname Test Case name * @param url {@link java.net.URL URL} object * @param exp expected result * @throws Exception if any exception occured while * {@link AbstractProvidesIntegrity.TestItem} * object creation */ public TestItem(String tcname, String url, String exp) throws Exception { testCaseName = tcname; if (url == null) { testURL = null; } else { testURL = new URL(url); } if (exp.endsWith(".class")) { expectedException = Class.forName(exp.substring(0, exp.lastIndexOf(".class"))); } else { if (exp.compareTo("true") == 0) { expectedBoolean = true; } else if (exp.compareTo("false") == 0) { expectedBoolean = false; } else { throw new Exception(exp + ": Bad value for expected result"); } } } /** * Creating {@link AbstractProvidesIntegrity.TestItem} * object (Constructor). * * @param tcname Test Case name * @param proto protocol of {@link java.net.URL URL} object * @param host host of {@link java.net.URL URL} object * @param file file of {@link java.net.URL URL} object * @param exp expected result * @throws Exception if any exception occured while * {@link AbstractProvidesIntegrity.TestItem} * object creation */ public TestItem(String tcname, String proto, String host, String file, String exp) throws Exception { testCaseName = tcname; if (proto == null) { testURL = null; } else { testURL = new URL(proto, host, file); } if (exp.endsWith(".class")) { expectedException = Class.forName(exp.substring(0, exp.lastIndexOf(".class"))); } else { if (exp.compareTo("true") == 0) { expectedBoolean = true; } else if (exp.compareTo("false") == 0) { expectedBoolean = false; } else { throw new Exception(exp + ": Bad value for expected result"); } } } /** * Getting Test Case name of this * {@link AbstractProvidesIntegrity.TestItem} * object. * * @return Test Case name of this * {@link AbstractProvidesIntegrity.TestItem} * object */ public String getTestCaseName() { return testCaseName; } /** * This method returns {@link java.net.URL URL} object to be tested. * * @return url */ public URL getURL() { return testURL; } /** * Comparing 2 boolean values. * * @param test the result returned by method to be verified * @return result of comparison (true or false) */ public boolean compare(boolean test) { logger.log(Level.FINE, "Expected Result: " + expectedBoolean); logger.log(Level.FINE, "Returned Result: " + test); if (test == expectedBoolean) { return true; } return false; } /** * Comparing 2 Exceptions. * * @param test the Exception occurred while invoking method to be * verified * @return result of comparison (true or false) */ public boolean compare(Exception test) { logger.log(Level.FINE, "Expected Result: " + expectedException.getName()); logger.log(Level.FINE, "Returned Result: " + test); return expectedException.isInstance(test); } } }
/* * Copyright 2015 NAVER Corp. * * 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.navercorp.redis.cluster.spring; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * The Interface SessionOfHashSetOperations. * * @param <H> the generic type * @param <HK> the generic type * @param <HV> the generic type * @author jaehong.kim */ public interface SessionOfHashSetOperations<H, HK, HV> { /** * Gets the. * * @param key the key * @param field the field * @param name the name * @return the sets the */ Set<HV> get(H key, HK field, HK name); /** * Mulit get. * * @param key the key * @param field the field * @param names the names * @return the map */ Map<HK, Set<HV>> mulitGet(H key, HK field, Collection<HK> names); /** * Keys. * * @param key the key * @return the sets the */ Set<HK> keys(H key); /** * Keys. * * @param key the key * @param field the field * @return the sets the */ Set<HK> keys(H key, HK field); /** * Adds the. * * @param key the key * @param field the field * @param name the name * @param value the value * @return the long */ Long add(H key, HK field, HK name, HV value); /** * Adds the. * * @param key the key * @param field the field * @param name the name * @param value the value * @param timeout the timeout * @param unit the unit * @return the long */ Long add(H key, HK field, HK name, HV value, long timeout, TimeUnit unit); /** * Adds the at. * * @param key the key * @param field the field * @param name the name * @param value the value * @param millisecondsTimestamp the milliseconds timestamp * @return the long */ Long addAt(H key, HK field, HK name, HV value, long millisecondsTimestamp); /** * Multi add. * * @param key the key * @param field the field * @param name the name * @param values the values * @return the long */ Long multiAdd(H key, HK field, HK name, Collection<HV> values); /** * Multi add. * * @param key the key * @param field the field * @param name the name * @param values the values * @param timeout the timeout * @param unit the unit * @return the long */ Long multiAdd(H key, HK field, HK name, Collection<HV> values, long timeout, TimeUnit unit); /** * Multi add at. * * @param key the key * @param field the field * @param name the name * @param values the values * @param millisecondsTimestamp the milliseconds timestamp * @return the long */ Long multiAddAt(H key, HK field, HK name, Collection<HV> values, long millisecondsTimestamp); /** * Sets the. * * @param key the key * @param field the field * @param name the name * @param value the value * @return the long */ Long set(H key, HK field, HK name, HV value); /** * Sets the. * * @param key the key * @param field the field * @param name the name * @param value the value * @param timeout the timeout * @param unit the unit * @return the long */ Long set(H key, HK field, HK name, HV value, long timeout, TimeUnit unit); /** * Multi set. * * @param key the key * @param field the field * @param name the name * @param values the values * @return the long */ Long multiSet(H key, HK field, HK name, Collection<HV> values); /** * Multi set. * * @param key the key * @param field the field * @param name the name * @param values the values * @param timeout the timeout * @param unit the unit * @return the long */ Long multiSet(H key, HK field, HK name, Collection<HV> values, long timeout, TimeUnit unit); /** * Del. * * @param key the key * @return the long */ Long del(H key); /** * Del. * * @param key the key * @param field the field * @return the long */ Long del(H key, HK field); /** * Del. * * @param key the key * @param field the field * @param name the name * @return the long */ Long del(H key, HK field, HK name); /** * Del. * * @param key the key * @param field the field * @param name the name * @param value the value * @return the long */ Long del(H key, HK field, HK name, HV value); /** * Multi del. * * @param key the key * @param field the field * @param name the name * @param values the values * @return the long */ Long multiDel(H key, HK field, HK name, Collection<HV> values); /** * Count. * * @param key the key * @param field the field * @param name the name * @return the long */ Long count(H key, HK field, HK name); /** * Exists. * * @param key the key * @param field the field * @param name the name * @param value the value * @return the boolean */ Boolean exists(H key, HK field, HK name, HV value); /** * Expire. * * @param key the key * @param timeout the timeout * @param unit the unit * @return the long */ Long expire(H key, long timeout, TimeUnit unit); /** * Expire. * * @param key the key * @param field the field * @param timeout the timeout * @param unit the unit * @return the long */ Long expire(H key, HK field, long timeout, TimeUnit unit); /** * Expire. * * @param key the key * @param field the field * @param name the name * @param timeout the timeout * @param unit the unit * @return the long */ Long expire(H key, HK field, HK name, long timeout, TimeUnit unit); /** * Expire. * * @param key the key * @param field the field * @param name the name * @param value the value * @param timeout the timeout * @param unit the unit * @return the long */ Long expire(H key, HK field, HK name, HV value, long timeout, TimeUnit unit); /** * Ttl. * * @param key the key * @param field the field * @param name the name * @param value the value * @return the long */ Long ttl(H key, HK field, HK name, HV value); /** * Values. * * @param key the key * @param field the field * @return the list */ List<HV> values(H key, HK field); }
/** * Copyright 2011-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.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.asakusafw.vocabulary.flow.builder; import java.lang.reflect.Constructor; import java.text.MessageFormat; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.asakusafw.vocabulary.flow.FlowDescription; import com.asakusafw.vocabulary.flow.graph.FlowElementDescription; import com.asakusafw.vocabulary.flow.graph.FlowIn; import com.asakusafw.vocabulary.flow.graph.FlowOut; import com.asakusafw.vocabulary.flow.graph.FlowPartDescription; /** * Builds fragment graph node internally. * @since 0.9.0 */ public class FlowNodeBuilder extends FlowElementBuilder { private static final Object INVALID_ARGUMENT = new Object() { @Override public String toString() { return "INVALID"; //$NON-NLS-1$ } }; private final Constructor<? extends FlowDescription> constructor; /** * Creates a new instance for operator method. * @param flowClass flow class * @param parameterTypes flow-part constructor parameter types * @throws IllegalArgumentException if some parameters were {@code null} */ public FlowNodeBuilder(Class<? extends FlowDescription> flowClass, Class<?>... parameterTypes) { try { this.constructor = flowClass.getConstructor(parameterTypes); } catch (NoSuchMethodException e) { throw new IllegalStateException(MessageFormat.format( "Failed to detect flow description constructor (class={0}, parameters={1})", flowClass.getName(), Arrays.toString(parameterTypes)), e); } } /** * Returns the target constructor. * @return the constructor */ public Constructor<? extends FlowDescription> getConstructor() { return constructor; } @Override protected FlowElementDescription build( List<PortInfo> inputPorts, List<PortInfo> outputPorts, List<DataInfo> arguments, List<AttributeInfo> attributes) { FlowPartDescription.Builder builder = new FlowPartDescription.Builder(constructor.getDeclaringClass()); Map<String, FlowIn<?>> inputMap = new LinkedHashMap<>(); Map<String, FlowOut<?>> outputMap = new LinkedHashMap<>(); Map<String, Object> dataMap = new LinkedHashMap<>(); for (PortInfo info : inputPorts) { if (info.getKey() != null) { throw new IllegalArgumentException(MessageFormat.format( "flow-part cannot accept shuffle key: {0}({1})", constructor.getDeclaringClass().getName(), info.getName())); } if (info.getExtern() != null) { throw new IllegalArgumentException(MessageFormat.format( "flow-part cannot accept external input: {0}({1})", constructor.getDeclaringClass().getName(), info.getName())); } FlowIn<?> port = builder.addInput(info.getName(), info.getType()); inputMap.put(info.getName(), port); } for (PortInfo info : outputPorts) { if (info.getKey() != null) { throw new IllegalArgumentException(MessageFormat.format( "flow-part cannot accept shuffle key: {0}({1})", constructor.getDeclaringClass().getName(), info.getName())); } if (info.getExtern() != null) { throw new IllegalArgumentException(MessageFormat.format( "flow-part cannot accept external output: {0}({1})", constructor.getDeclaringClass().getName(), info.getName())); } FlowOut<?> port = builder.addOutput(info.getName(), info.getType()); outputMap.put(info.getName(), port); } for (DataInfo info : arguments) { Data data = info.getData(); Object value; switch (data.getKind()) { case CONSTANT: { Constant c = (Constant) data; value = c.getValue(); builder.addParameter(info.getName(), c.getType(), value); break; } default: throw new AssertionError(data); } dataMap.put(info.getName(), value); } if (attributes.isEmpty() == false) { throw new IllegalArgumentException(MessageFormat.format( "flow-part cannot accept attributes: {0}({1})", constructor.getDeclaringClass().getName(), attributes)); } Object[] constructorArguments = computeConstructoArguments( inputPorts, outputPorts, arguments, inputMap, outputMap, dataMap); try { FlowDescription instance = constructor.newInstance(constructorArguments); instance.start(); } catch (Exception e) { throw new IllegalStateException(MessageFormat.format( "error occurred while processing flow-part: {0}", constructor.getDeclaringClass().getName()), e); } return builder.toDescription(); } private Object[] computeConstructoArguments( List<PortInfo> inputPorts, List<PortInfo> outputPorts, List<DataInfo> arguments, Map<String, FlowIn<?>> inputMap, Map<String, FlowOut<?>> outputMap, Map<String, Object> dataMap) { Object[] results = new Object[constructor.getParameterTypes().length]; Arrays.fill(results, INVALID_ARGUMENT); for (PortInfo info : inputPorts) { put("input", results, info, inputMap); } for (PortInfo info : outputPorts) { put("output", results, info, outputMap); } for (DataInfo info : arguments) { put("data", results, info, dataMap); } for (int index = 0; index < results.length; index++) { if (results[index] == INVALID_ARGUMENT) { throw new IllegalStateException(MessageFormat.format( "flow-part constructor argument is not completed: {0}(@{1})", constructor.getDeclaringClass().getName(), index)); } } return results; } private void put(String label, Object[] results, EdgeInfo<?> info, Map<String, ?> valueMap) { Integer index = info.getParameterIndex(); if (index == null) { throw new IllegalArgumentException(MessageFormat.format( "flow-part {0} must have parameter index information: {1}({2})", label, constructor.getDeclaringClass().getName(), info.getName())); } if (results[index] != INVALID_ARGUMENT) { throw new IllegalStateException(MessageFormat.format( "flow-part constructor argument is duplicated: {0}(@{1}={2})", constructor.getDeclaringClass().getName(), index, info.getName())); } if (valueMap.containsKey(info.getName()) == false) { throw new IllegalStateException(MessageFormat.format( "flow-part constructor argument is unknown: {0}(@{1}={2})", constructor.getDeclaringClass().getName(), index, info.getName())); } Object value = valueMap.get(info.getName()); results[index] = value; } }
package ru.stqa.pft.addressbook.model; import com.google.gson.annotations.Expose; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamOmitField; import org.hibernate.annotations.ManyToAny; import org.hibernate.annotations.Type; import javax.persistence.*; import java.io.File; import java.util.HashSet; import java.util.Set; @XStreamAlias("contact") @Entity @Table(name = "addressbook") public class ContactData { @XStreamOmitField @Id @Column(name = "id") private int id = 0; @Expose @Column(name = "firstname") private String contactName; @Expose @Column(name = "middlename") private String contactMiddleName; @Expose @Column(name = "lastname") private String contactLastName; @Expose @Column(name = "nickname") private String contactNickname; @Expose @Column(name = "title") private String contactTitle; @Expose @Column(name = "company") private String contactCompany; @Expose @Column(name = "address") @Type(type = "text") private String contactCompanyAddress; @Expose @Column(name = "home") @Type(type = "text") private String contactHomePhone; @Expose @Column(name = "mobile") @Type(type = "text") private String contactMobilePhone; @Expose @Column(name = "work ") @Type(type = "text") private String contactWorkPhone; @Expose @Column(name = "fax ") @Type(type = "text") private String contactFax; @Expose @Column(name = "email") @Type(type = "text") private String contactEmail1; @Expose @Column(name = "email2") @Type(type = "text") private String contactEmail2; @Expose @Column(name = "email3") @Type(type = "text") private String contactEmail3; @Expose @Column(name = "homepage") @Type(type = "text") private String contactHomepage; @Transient private String allPhones; @Transient private String allEmails; @Transient private String fullName; @Transient private String contactSummary; @Transient @Column(name = "photo") @Type(type = "text") private String photo; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "address_in_groups", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "group_id")) private Set<GroupData> groups = new HashSet<GroupData>(); public File getPhoto() { return new File(photo); } public ContactData withPhoto(File photo) { this.photo = photo.getPath(); return this; } public Groups getGroups() { return new Groups(groups); } public ContactData inGroup(GroupData group) { groups.add(group); return this; } public int getId() { return id; } public String getContactName() { return contactName; } public String getContactMiddleName() { return contactMiddleName; } public String getContactLastName() { return contactLastName; } public String getContactNickname() { return contactNickname; } public String getContactTitle() { return contactTitle; } public String getContactCompany() { return contactCompany; } public String getContactCompanyAddress() { return contactCompanyAddress; } public String getContactHomePhone() { return contactHomePhone; } public String getContactMobilePhone() { return contactMobilePhone; } public String getContactWorkPhone() { return contactWorkPhone; } public String getContactFax() { return contactFax; } public String getContactEmail1() { return contactEmail1; } public String getContactHomepage() { return contactHomepage; } public String getFullName() { return fullName; } public String getContactSummary() { return contactSummary; } public ContactData withId(int id) { this.id = id; return this; } public String getAllPhones() { return allPhones; } public String getContactEmail2() { return contactEmail2; } public String getContactEmail3() { return contactEmail3; } public String getAllEmails() { return allEmails; } public ContactData withContactName(String contactName) { this.contactName = contactName; return this; } public ContactData withContactMiddleName(String contactMiddleName) { this.contactMiddleName = contactMiddleName; return this; } public ContactData withContactLastName(String contactLastName) { this.contactLastName = contactLastName; return this; } public ContactData withContactNickname(String contactNickname) { this.contactNickname = contactNickname; return this; } public ContactData withContactTitle(String contactTitle) { this.contactTitle = contactTitle; return this; } public ContactData withContactCompany(String contactCompany) { this.contactCompany = contactCompany; return this; } public ContactData withContactCompanyAddress(String contactCompanyAddress) { this.contactCompanyAddress = contactCompanyAddress; return this; } public ContactData withContactHomePhone(String contactHomePhone) { this.contactHomePhone = contactHomePhone; return this; } public ContactData withContactMobilePhone(String contactMobilePhone) { this.contactMobilePhone = contactMobilePhone; return this; } public ContactData withContactWorkPhone(String contactWorkPhone) { this.contactWorkPhone = contactWorkPhone; return this; } public ContactData withContactFax(String contactFax) { this.contactFax = contactFax; return this; } public ContactData withContactEmail1(String contactEmail) { this.contactEmail1 = contactEmail; return this; } public ContactData withContactEmail2(String contactEmail) { this.contactEmail2 = contactEmail; return this; } public ContactData withContactEmail3(String contactEmail) { this.contactEmail3 = contactEmail; return this; } public ContactData withContactHomepage(String contactHomepage) { this.contactHomepage = contactHomepage; return this; } public ContactData withAllPhones(String allPhones) { this.allPhones = allPhones; return this; } public ContactData withAllEmails(String allEmails){ this.allEmails = allEmails; return this; } public ContactData withContactSummary(String contactSummary) { this.contactSummary = contactSummary; return this; } public ContactData withContactFullName(String fullName) { this.fullName = fullName; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ContactData that = (ContactData) o; if (id != that.id) return false; if (contactName != null ? !contactName.equals(that.contactName) : that.contactName != null) return false; if (contactMiddleName != null ? !contactMiddleName.equals(that.contactMiddleName) : that.contactMiddleName != null) return false; if (contactLastName != null ? !contactLastName.equals(that.contactLastName) : that.contactLastName != null) return false; if (contactNickname != null ? !contactNickname.equals(that.contactNickname) : that.contactNickname != null) return false; if (contactTitle != null ? !contactTitle.equals(that.contactTitle) : that.contactTitle != null) return false; if (contactCompany != null ? !contactCompany.equals(that.contactCompany) : that.contactCompany != null) return false; if (contactCompanyAddress != null ? !contactCompanyAddress.equals(that.contactCompanyAddress) : that.contactCompanyAddress != null) return false; if (contactHomePhone != null ? !contactHomePhone.equals(that.contactHomePhone) : that.contactHomePhone != null) return false; if (contactMobilePhone != null ? !contactMobilePhone.equals(that.contactMobilePhone) : that.contactMobilePhone != null) return false; if (contactWorkPhone != null ? !contactWorkPhone.equals(that.contactWorkPhone) : that.contactWorkPhone != null) return false; if (contactFax != null ? !contactFax.equals(that.contactFax) : that.contactFax != null) return false; if (contactEmail1 != null ? !contactEmail1.equals(that.contactEmail1) : that.contactEmail1 != null) return false; if (contactEmail2 != null ? !contactEmail2.equals(that.contactEmail2) : that.contactEmail2 != null) return false; if (contactEmail3 != null ? !contactEmail3.equals(that.contactEmail3) : that.contactEmail3 != null) return false; if (contactHomepage != null ? !contactHomepage.equals(that.contactHomepage) : that.contactHomepage != null) return false; if (allPhones != null ? !allPhones.equals(that.allPhones) : that.allPhones != null) return false; if (allEmails != null ? !allEmails.equals(that.allEmails) : that.allEmails != null) return false; return photo != null ? photo.equals(that.photo) : that.photo == null; } @Override public int hashCode() { int result = id; result = 31 * result + (contactName != null ? contactName.hashCode() : 0); result = 31 * result + (contactMiddleName != null ? contactMiddleName.hashCode() : 0); result = 31 * result + (contactLastName != null ? contactLastName.hashCode() : 0); result = 31 * result + (contactNickname != null ? contactNickname.hashCode() : 0); result = 31 * result + (contactTitle != null ? contactTitle.hashCode() : 0); result = 31 * result + (contactCompany != null ? contactCompany.hashCode() : 0); result = 31 * result + (contactCompanyAddress != null ? contactCompanyAddress.hashCode() : 0); result = 31 * result + (contactHomePhone != null ? contactHomePhone.hashCode() : 0); result = 31 * result + (contactMobilePhone != null ? contactMobilePhone.hashCode() : 0); result = 31 * result + (contactWorkPhone != null ? contactWorkPhone.hashCode() : 0); result = 31 * result + (contactFax != null ? contactFax.hashCode() : 0); result = 31 * result + (contactEmail1 != null ? contactEmail1.hashCode() : 0); result = 31 * result + (contactEmail2 != null ? contactEmail2.hashCode() : 0); result = 31 * result + (contactEmail3 != null ? contactEmail3.hashCode() : 0); result = 31 * result + (contactHomepage != null ? contactHomepage.hashCode() : 0); result = 31 * result + (allPhones != null ? allPhones.hashCode() : 0); result = 31 * result + (allEmails != null ? allEmails.hashCode() : 0); result = 31 * result + (photo != null ? photo.hashCode() : 0); return result; } @Override public String toString() { return "ContactData{" + "id=" + id + ", contactName='" + contactName + '\'' + ", contactMiddleName='" + contactMiddleName + '\'' + // ", contactLastName='" + contactLastName + '\'' + // ", contactNickname='" + contactNickname + '\'' + // ", contactTitle='" + contactTitle + '\'' + // ", contactCompany='" + contactCompany + '\'' + // ", contactCompanyAddress='" + contactCompanyAddress + '\'' + // ", contactHomePhone='" + contactHomePhone + '\'' + // ", contactMobilePhone='" + contactMobilePhone + '\'' + // ", contactWorkPhone='" + contactWorkPhone + '\'' + // ", contactFax='" + contactFax + '\'' + // ", contactEmail1='" + contactEmail1 + '\'' + // ", contactEmail2='" + contactEmail2 + '\'' + // ", contactEmail3='" + contactEmail3 + '\'' + // ", contactHomepage='" + contactHomepage + '\'' + // ", contactSummary='" + contactSummary + '\'' + // ", photo='" + photo + '\'' + ", groups=" + groups + '}'; } }
package org.nd4j.linalg.api.ops.impl.layers.convolution; import lombok.Builder; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.imports.descriptors.properties.AttributeAdapter; import org.nd4j.imports.descriptors.properties.PropertyMapping; import org.nd4j.imports.descriptors.properties.adapters.IntArrayIntIndexAdpater; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.DynamicCustomOp; import org.nd4j.linalg.api.ops.impl.layers.convolution.config.FullConv3DConfig; import org.nd4j.linalg.util.ArrayUtil; import java.lang.reflect.Field; import java.util.*; /** * FullConv3D operation */ @Slf4j public class FullConv3D extends DynamicCustomOp { protected FullConv3DConfig config; @Builder(builderMethodName = "builder") public FullConv3D(SameDiff sameDiff, SDVariable[] inputFunctions, INDArray[] inputs, INDArray[] outputs, FullConv3DConfig config) { super(null,sameDiff, inputFunctions, false); this.config = config; if(inputs != null) { addInputArgument(inputs); } if(outputs != null) { addOutputArgument(outputs); } addArgs(); } public FullConv3D() {} @Override public Map<String, Object> propertiesForFunction() { return config.toProperties(); } @Override public void setValueFor(Field target, Object value) { config.setValueFor(target,value); } @Override public boolean isConfigProperties() { return true; } @Override public String configFieldName() { return "config"; } @Override public Map<String, Map<String, AttributeAdapter>> attributeAdaptersForFunction() { Map<String,Map<String,AttributeAdapter>> ret = new LinkedHashMap<>(); Map<String,AttributeAdapter> tfAdapters = new LinkedHashMap<>(); tfAdapters.put("dT", new IntArrayIntIndexAdpater(1)); tfAdapters.put("dW", new IntArrayIntIndexAdpater(2)); tfAdapters.put("dH",new IntArrayIntIndexAdpater(3)); tfAdapters.put("pT", new IntArrayIntIndexAdpater(1)); tfAdapters.put("pW", new IntArrayIntIndexAdpater(2)); tfAdapters.put("pH",new IntArrayIntIndexAdpater(3)); ret.put(tensorflowName(),tfAdapters); return ret; } @Override public Map<String, Map<String, PropertyMapping>> mappingsForFunction() { Map<String,Map<String,PropertyMapping>> ret = new HashMap<>(); Map<String,PropertyMapping> map = new HashMap<>(); val strideMapping = PropertyMapping.builder() .tfAttrName("strides") .onnxAttrName("strides") .propertyNames(new String[]{"dT","dW","dH"}) .build(); val dilationMapping = PropertyMapping.builder() .onnxAttrName("dilations") .propertyNames(new String[]{"dilationT","dilationH","dilationW"}) .tfAttrName("rates") .build(); val sameMode = PropertyMapping.builder() .onnxAttrName("auto_pad") .propertyNames(new String[]{"isSameMode"}) .tfAttrName("padding") .build(); val paddingWidthHeight = PropertyMapping.builder() .onnxAttrName("padding") .propertyNames(new String[]{"pT","pW","pH"}) .build(); val dataFormat = PropertyMapping.builder() .onnxAttrName("data_format") .tfAttrName("data_format") .propertyNames(new String[]{"dataFormat"}) .build(); val outputPadding = PropertyMapping.builder() .propertyNames(new String[]{"aT","aH","aW"}) .build(); val biasUsed = PropertyMapping.builder() .propertyNames(new String[]{"biasUsed"}) .build(); for(val propertyMapping : new PropertyMapping[] { strideMapping, dilationMapping, sameMode, paddingWidthHeight, dataFormat, outputPadding,biasUsed}) { for(val keys : propertyMapping.getPropertyNames()) map.put(keys,propertyMapping); } ret.put(onnxName(),map); ret.put(tensorflowName(),map); return ret; } private void addArgs() { addIArgument(new long[]{ config.getDT(), config.getDW(), config.getDH(), config.getPT(), config.getPW(), config.getPH(), config.getDilationT(), config.getDilationW(), config.getDilationH(), config.getAT(), config.getAW(), config.getAH(), ArrayUtil.fromBoolean(config.isBiasUsed())}); } @Override public String opName() { return "fullconv3d"; } @Override public List<SDVariable> doDiff(List<SDVariable> f1) { List<SDVariable> inputs = new ArrayList<>(); inputs.addAll(Arrays.asList(args())); inputs.addAll(f1); List<SDVariable> ret = new ArrayList<>(); FullConv3DDerivative fullConv3DDerivative = FullConv3DDerivative.derivativeBuilder() .conv3DConfig(config) .sameDiff(sameDiff) .inputFunctions(inputs.toArray(new SDVariable[inputs.size()])) .build(); ret.addAll(Arrays.asList(fullConv3DDerivative.outputVariables())); return ret; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.serde2.objectinspector.primitive; import java.sql.Date; import java.sql.Timestamp; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.common.type.HiveIntervalYearMonth; import org.apache.hadoop.hive.common.type.HiveIntervalDayTime; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.serde2.ByteStream; import org.apache.hadoop.hive.serde2.io.HiveCharWritable; import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable; import org.apache.hadoop.hive.serde2.lazy.LazyInteger; import org.apache.hadoop.hive.serde2.lazy.LazyLong; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; /** * PrimitiveObjectInspectorConverter. * */ public class PrimitiveObjectInspectorConverter { /** * A converter for the byte type. */ public static class BooleanConverter implements Converter { PrimitiveObjectInspector inputOI; SettableBooleanObjectInspector outputOI; Object r; public BooleanConverter(PrimitiveObjectInspector inputOI, SettableBooleanObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(false); } @Override public Object convert(Object input) { if (input == null) { return null; } try { return outputOI.set(r, PrimitiveObjectInspectorUtils.getBoolean(input, inputOI)); } catch (NumberFormatException e) { return null; } } } /** * A converter for the byte type. */ public static class ByteConverter implements Converter { PrimitiveObjectInspector inputOI; SettableByteObjectInspector outputOI; Object r; public ByteConverter(PrimitiveObjectInspector inputOI, SettableByteObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create((byte) 0); } @Override public Object convert(Object input) { if (input == null) { return null; } try { return outputOI.set(r, PrimitiveObjectInspectorUtils.getByte(input, inputOI)); } catch (NumberFormatException e) { return null; } } } /** * A converter for the short type. */ public static class ShortConverter implements Converter { PrimitiveObjectInspector inputOI; SettableShortObjectInspector outputOI; Object r; public ShortConverter(PrimitiveObjectInspector inputOI, SettableShortObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create((short) 0); } @Override public Object convert(Object input) { if (input == null) { return null; } try { return outputOI.set(r, PrimitiveObjectInspectorUtils.getShort(input, inputOI)); } catch (NumberFormatException e) { return null; } } } /** * A converter for the int type. */ public static class IntConverter implements Converter { PrimitiveObjectInspector inputOI; SettableIntObjectInspector outputOI; Object r; public IntConverter(PrimitiveObjectInspector inputOI, SettableIntObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(0); } @Override public Object convert(Object input) { if (input == null) { return null; } try { return outputOI.set(r, PrimitiveObjectInspectorUtils.getInt(input, inputOI)); } catch (NumberFormatException e) { return null; } } } /** * A converter for the long type. */ public static class LongConverter implements Converter { PrimitiveObjectInspector inputOI; SettableLongObjectInspector outputOI; Object r; public LongConverter(PrimitiveObjectInspector inputOI, SettableLongObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(0); } @Override public Object convert(Object input) { if (input == null) { return null; } try { return outputOI.set(r, PrimitiveObjectInspectorUtils.getLong(input, inputOI)); } catch (NumberFormatException e) { return null; } } } /** * A converter for the float type. */ public static class FloatConverter implements Converter { PrimitiveObjectInspector inputOI; SettableFloatObjectInspector outputOI; Object r; public FloatConverter(PrimitiveObjectInspector inputOI, SettableFloatObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(0); } @Override public Object convert(Object input) { if (input == null) { return null; } try { return outputOI.set(r, PrimitiveObjectInspectorUtils.getFloat(input, inputOI)); } catch (NumberFormatException e) { return null; } } } /** * A converter for the double type. */ public static class DoubleConverter implements Converter { PrimitiveObjectInspector inputOI; SettableDoubleObjectInspector outputOI; Object r; public DoubleConverter(PrimitiveObjectInspector inputOI, SettableDoubleObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(0); } @Override public Object convert(Object input) { if (input == null) { return null; } try { return outputOI.set(r, PrimitiveObjectInspectorUtils.getDouble(input, inputOI)); } catch (NumberFormatException e) { return null; } } } public static class DateConverter implements Converter { PrimitiveObjectInspector inputOI; SettableDateObjectInspector outputOI; Object r; public DateConverter(PrimitiveObjectInspector inputOI, SettableDateObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(new Date(0)); } public Object convert(Object input) { if (input == null) { return null; } return outputOI.set(r, PrimitiveObjectInspectorUtils.getDate(input, inputOI)); } } public static class TimestampConverter implements Converter { PrimitiveObjectInspector inputOI; SettableTimestampObjectInspector outputOI; boolean intToTimestampInSeconds = false; Object r; public TimestampConverter(PrimitiveObjectInspector inputOI, SettableTimestampObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(new Timestamp(0)); } public void setIntToTimestampInSeconds(boolean intToTimestampInSeconds) { this.intToTimestampInSeconds = intToTimestampInSeconds; } public Object convert(Object input) { if (input == null) { return null; } return outputOI.set(r, PrimitiveObjectInspectorUtils.getTimestamp(input, inputOI, intToTimestampInSeconds)); } } public static class HiveIntervalYearMonthConverter implements Converter { PrimitiveObjectInspector inputOI; SettableHiveIntervalYearMonthObjectInspector outputOI; Object r; public HiveIntervalYearMonthConverter(PrimitiveObjectInspector inputOI, SettableHiveIntervalYearMonthObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(new HiveIntervalYearMonth()); } public Object convert(Object input) { if (input == null) { return null; } return outputOI.set(r, PrimitiveObjectInspectorUtils.getHiveIntervalYearMonth(input, inputOI)); } } public static class HiveIntervalDayTimeConverter implements Converter { PrimitiveObjectInspector inputOI; SettableHiveIntervalDayTimeObjectInspector outputOI; Object r; public HiveIntervalDayTimeConverter(PrimitiveObjectInspector inputOI, SettableHiveIntervalDayTimeObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(new HiveIntervalDayTime()); } public Object convert(Object input) { if (input == null) { return null; } return outputOI.set(r, PrimitiveObjectInspectorUtils.getHiveIntervalDayTime(input, inputOI)); } } public static class HiveDecimalConverter implements Converter { PrimitiveObjectInspector inputOI; SettableHiveDecimalObjectInspector outputOI; Object r; public HiveDecimalConverter(PrimitiveObjectInspector inputOI, SettableHiveDecimalObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; this.r = outputOI.create(HiveDecimal.ZERO); } @Override public Object convert(Object input) { if (input == null) { return null; } return outputOI.set(r, PrimitiveObjectInspectorUtils.getHiveDecimal(input, inputOI)); } } public static class BinaryConverter implements Converter{ PrimitiveObjectInspector inputOI; SettableBinaryObjectInspector outputOI; Object r; public BinaryConverter(PrimitiveObjectInspector inputOI, SettableBinaryObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; r = outputOI.create(new byte[]{}); } @Override public Object convert(Object input) { if (input == null) { return null; } return outputOI.set(r, PrimitiveObjectInspectorUtils.getBinary(input, inputOI)); } } /** * A helper class to convert any primitive to Text. */ public static class TextConverter implements Converter { private final PrimitiveObjectInspector inputOI; private final Text t = new Text(); private final ByteStream.Output out = new ByteStream.Output(); private static byte[] trueBytes = {'T', 'R', 'U', 'E'}; private static byte[] falseBytes = {'F', 'A', 'L', 'S', 'E'}; public TextConverter(PrimitiveObjectInspector inputOI) { // The output ObjectInspector is writableStringObjectInspector. this.inputOI = inputOI; } public Text convert(Object input) { if (input == null) { return null; } switch (inputOI.getPrimitiveCategory()) { case VOID: return null; case BOOLEAN: t.set(((BooleanObjectInspector) inputOI).get(input) ? trueBytes : falseBytes); return t; case BYTE: out.reset(); LazyInteger.writeUTF8NoException(out, ((ByteObjectInspector) inputOI).get(input)); t.set(out.getData(), 0, out.getLength()); return t; case SHORT: out.reset(); LazyInteger.writeUTF8NoException(out, ((ShortObjectInspector) inputOI).get(input)); t.set(out.getData(), 0, out.getLength()); return t; case INT: out.reset(); LazyInteger.writeUTF8NoException(out, ((IntObjectInspector) inputOI).get(input)); t.set(out.getData(), 0, out.getLength()); return t; case LONG: out.reset(); LazyLong.writeUTF8NoException(out, ((LongObjectInspector) inputOI).get(input)); t.set(out.getData(), 0, out.getLength()); return t; case FLOAT: t.set(String.valueOf(((FloatObjectInspector) inputOI).get(input))); return t; case DOUBLE: t.set(String.valueOf(((DoubleObjectInspector) inputOI).get(input))); return t; case STRING: if (inputOI.preferWritable()) { t.set(((StringObjectInspector) inputOI).getPrimitiveWritableObject(input)); } else { t.set(((StringObjectInspector) inputOI).getPrimitiveJavaObject(input)); } return t; case CHAR: // when converting from char, the value should be stripped of any trailing spaces. if (inputOI.preferWritable()) { // char text value is already stripped of trailing space t.set(((HiveCharObjectInspector) inputOI).getPrimitiveWritableObject(input) .getStrippedValue()); } else { t.set(((HiveCharObjectInspector) inputOI).getPrimitiveJavaObject(input).getStrippedValue()); } return t; case VARCHAR: if (inputOI.preferWritable()) { t.set(((HiveVarcharObjectInspector) inputOI).getPrimitiveWritableObject(input) .toString()); } else { t.set(((HiveVarcharObjectInspector) inputOI).getPrimitiveJavaObject(input).toString()); } return t; case DATE: t.set(((DateObjectInspector) inputOI).getPrimitiveWritableObject(input).toString()); return t; case TIMESTAMP: t.set(((TimestampObjectInspector) inputOI) .getPrimitiveWritableObject(input).toString()); return t; case INTERVAL_YEAR_MONTH: t.set(((HiveIntervalYearMonthObjectInspector) inputOI) .getPrimitiveWritableObject(input).toString()); return t; case INTERVAL_DAY_TIME: t.set(((HiveIntervalDayTimeObjectInspector) inputOI) .getPrimitiveWritableObject(input).toString()); return t; case BINARY: BinaryObjectInspector binaryOI = (BinaryObjectInspector) inputOI; if (binaryOI.preferWritable()) { BytesWritable bytes = binaryOI.getPrimitiveWritableObject(input); t.set(bytes.getBytes(), 0, bytes.getLength()); } else { t.set(binaryOI.getPrimitiveJavaObject(input)); } return t; case DECIMAL: t.set(((HiveDecimalObjectInspector) inputOI).getPrimitiveWritableObject(input).toString()); return t; default: throw new RuntimeException("Hive 2 Internal error: type = " + inputOI.getTypeName()); } } } /** * A helper class to convert any primitive to String. */ public static class StringConverter implements Converter { PrimitiveObjectInspector inputOI; public StringConverter(PrimitiveObjectInspector inputOI) { // The output ObjectInspector is writableStringObjectInspector. this.inputOI = inputOI; } @Override public Object convert(Object input) { return PrimitiveObjectInspectorUtils.getString(input, inputOI); } } public static class HiveVarcharConverter implements Converter { PrimitiveObjectInspector inputOI; SettableHiveVarcharObjectInspector outputOI; Object hc; public HiveVarcharConverter(PrimitiveObjectInspector inputOI, SettableHiveVarcharObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; // unfortunately we seem to get instances of varchar object inspectors without params // when an old-style UDF has an evaluate() method with varchar arguments. // If we disallow varchar in old-style UDFs and only allow GenericUDFs to be defined // with varchar arguments, then we might be able to enforce this properly. //if (typeParams == null) { // throw new RuntimeException("varchar type used without type params"); //} hc = outputOI.create(new HiveVarchar("",-1)); } @Override public Object convert(Object input) { if (input == null) { return null; } switch (inputOI.getPrimitiveCategory()) { case BOOLEAN: return outputOI.set(hc, ((BooleanObjectInspector) inputOI).get(input) ? new HiveVarchar("TRUE", -1) : new HiveVarchar("FALSE", -1)); default: return outputOI.set(hc, PrimitiveObjectInspectorUtils.getHiveVarchar(input, inputOI)); } } } public static class HiveCharConverter implements Converter { PrimitiveObjectInspector inputOI; SettableHiveCharObjectInspector outputOI; Object hc; public HiveCharConverter(PrimitiveObjectInspector inputOI, SettableHiveCharObjectInspector outputOI) { this.inputOI = inputOI; this.outputOI = outputOI; hc = outputOI.create(new HiveChar("",-1)); } @Override public Object convert(Object input) { if (input == null) { return null; } switch (inputOI.getPrimitiveCategory()) { case BOOLEAN: return outputOI.set(hc, ((BooleanObjectInspector) inputOI).get(input) ? new HiveChar("TRUE", -1) : new HiveChar("FALSE", -1)); default: return outputOI.set(hc, PrimitiveObjectInspectorUtils.getHiveChar(input, inputOI)); } } } }
package com.clockwork.terrain.heightmap; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * AbstractHeightMap provides a base implementation of height * data for terrain rendering. The loading of the data is dependent on the * subclass. The abstract implementation provides a means to retrieve the height * data and to save it. * * It is the general contract that any subclass provide a means of editing * required attributes and calling load again to recreate a * heightfield with these new parameters. * * * @version $Id: AbstractHeightMap.java 4133 2009-03-19 20:40:11Z blaine.dev $ */ public abstract class AbstractHeightMap implements HeightMap { private static final Logger logger = Logger.getLogger(AbstractHeightMap.class.getName()); /** Height data information. */ protected float[] heightData = null; /** The size of the height map's width. */ protected int size = 0; /** Allows scaling the Y height of the map. */ protected float heightScale = 1.0f; /** The filter is used to erode the terrain. */ protected float filter = 0.5f; /** The range used to normalize terrain */ public static float NORMALIZE_RANGE = 255f; /** * unloadHeightMap clears the data of the height map. This * insures it is ready for reloading. */ public void unloadHeightMap() { heightData = null; } /** * setHeightScale sets the scale of the height values. * Typically, the height is a little too extreme and should be scaled to a * smaller value (i.e. 0.25), to produce cleaner slopes. * * @param scale * the scale to multiply height values by. */ public void setHeightScale(float scale) { heightScale = scale; } /** * setHeightAtPoint sets the height value for a given * coordinate. It is recommended that the height value be within the 0 - 255 * range. * * @param height * the new height for the coordinate. * @param x * the x (east/west) coordinate. * @param z * the z (north/south) coordinate. */ public void setHeightAtPoint(float height, int x, int z) { heightData[x + (z * size)] = height; } /** * setSize sets the size of the terrain where the area is * size x size. * * @param size * the new size of the terrain. * @throws Exception * * @throws CWException * if the size is less than or equal to zero. */ public void setSize(int size) throws Exception { if (size <= 0) { throw new Exception("size must be greater than zero."); } this.size = size; } /** * setFilter sets the erosion value for the filter. This * value must be between 0 and 1, where 0.2 - 0.4 produces arguably the best * results. * * @param filter * the erosion value. * @throws Exception * @throws CWException * if filter is less than 0 or greater than 1. */ public void setMagnificationFilter(float filter) throws Exception { if (filter < 0 || filter >= 1) { throw new Exception("filter must be between 0 and 1"); } this.filter = filter; } /** * getTrueHeightAtPoint returns the non-scaled value at the * point provided. * * @param x * the x (east/west) coordinate. * @param z * the z (north/south) coordinate. * @return the value at (x,z). */ public float getTrueHeightAtPoint(int x, int z) { //logger.fine( heightData[x + (z*size)]); return heightData[x + (z * size)]; } /** * getScaledHeightAtPoint returns the scaled value at the * point provided. * * @param x * the x (east/west) coordinate. * @param z * the z (north/south) coordinate. * @return the scaled value at (x, z). */ public float getScaledHeightAtPoint(int x, int z) { return ((heightData[x + (z * size)]) * heightScale); } /** * getInterpolatedHeight returns the height of a point that * does not fall directly on the height posts. * * @param x * the x coordinate of the point. * @param z * the y coordinate of the point. * @return the interpolated height at this point. */ public float getInterpolatedHeight(float x, float z) { float low, highX, highZ; float intX, intZ; float interpolation; low = getScaledHeightAtPoint((int) x, (int) z); if (x + 1 >= size) { return low; } highX = getScaledHeightAtPoint((int) x + 1, (int) z); interpolation = x - (int) x; intX = ((highX - low) * interpolation) + low; if (z + 1 >= size) { return low; } highZ = getScaledHeightAtPoint((int) x, (int) z + 1); interpolation = z - (int) z; intZ = ((highZ - low) * interpolation) + low; return ((intX + intZ) / 2); } /** * getHeightMap returns the entire grid of height data. * * @return the grid of height data. */ public float[] getHeightMap() { return heightData; } /** * Build a new array of height data with the scaled values. * @return */ public float[] getScaledHeightMap() { float[] hm = new float[heightData.length]; for (int i=0; i<heightData.length; i++) { hm[i] = heightScale * heightData[i]; } return hm; } /** * getSize returns the size of one side the height map. Where * the area of the height map is size x size. * * @return the size of a single side. */ public int getSize() { return size; } /** * save will save the heightmap data into a new RAW file * denoted by the supplied filename. * * @param filename * the file name to save the current data as. * @return true if the save was successful, false otherwise. * @throws Exception * * @throws CWException * if filename is null. */ public boolean save(String filename) throws Exception { if (null == filename) { throw new Exception("Filename must not be null"); } //open the streams and send the height data to the file. FileOutputStream fos = null; DataOutputStream dos = null; try { fos = new FileOutputStream(filename); dos = new DataOutputStream(fos); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { dos.write((int) heightData[j + (i * size)]); } } fos.close(); dos.close(); } catch (FileNotFoundException e) { logger.log(Level.WARNING, "Error opening file {0}", filename); return false; } catch (IOException e) { logger.log(Level.WARNING, "Error writing to file {0}", filename); return false; } finally { if (fos != null) { fos.close(); } if (dos != null) { dos.close(); } } logger.log(Level.FINE, "Saved terrain to {0}", filename); return true; } /** * normalizeTerrain takes the current terrain data and * converts it to values between 0 and value. * * @param value * the value to normalize to. */ public void normalizeTerrain(float value) { float currentMin, currentMax; float height; currentMin = heightData[0]; currentMax = heightData[0]; //find the min/max values of the height fTemptemptempBuffer for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (heightData[i + j * size] > currentMax) { currentMax = heightData[i + j * size]; } else if (heightData[i + j * size] < currentMin) { currentMin = heightData[i + j * size]; } } } //find the range of the altitude if (currentMax <= currentMin) { return; } height = currentMax - currentMin; //scale the values to a range of 0-255 for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { heightData[i + j * size] = ((heightData[i + j * size] - currentMin) / height) * value; } } } /** * Find the minimum and maximum height values. * @return a float array with two value: min height, max height */ public float[] findMinMaxHeights() { float[] minmax = new float[2]; float currentMin, currentMax; currentMin = heightData[0]; currentMax = heightData[0]; for (int i = 0; i < heightData.length; i++) { if (heightData[i] > currentMax) { currentMax = heightData[i]; } else if (heightData[i] < currentMin) { currentMin = heightData[i]; } } minmax[0] = currentMin; minmax[1] = currentMax; return minmax; } /** * erodeTerrain is a convenience method that applies the FIR * filter to a given height map. This simulates water errosion. * * see setFilter */ public void erodeTerrain() { //erode left to right float v; for (int i = 0; i < size; i++) { v = heightData[i]; for (int j = 1; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; } } //erode right to left for (int i = size - 1; i >= 0; i--) { v = heightData[i]; for (int j = 0; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; //erodeBand(tempBuffer[size * i + size - 1], -1); } } //erode top to bottom for (int i = 0; i < size; i++) { v = heightData[i]; for (int j = 0; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; } } //erode from bottom to top for (int i = size - 1; i >= 0; i--) { v = heightData[i]; for (int j = 0; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; } } } /** * Flattens out the valleys. The flatten algorithm makes the valleys more * prominent while keeping the hills mostly intact. This effect is based on * what happens when values below one are squared. The terrain will be * normalized between 0 and 1 for this function to work. * * @param flattening * the power of flattening applied, 1 means none */ public void flatten(byte flattening) { // If flattening is one we can skip the calculations // since it wouldn't change anything. (e.g. 2 power 1 = 2) if (flattening <= 1) { return; } float[] minmax = findMinMaxHeights(); normalizeTerrain(1f); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { float flat = 1.0f; float original = heightData[x + y * size]; // Flatten as many times as desired; for (int i = 0; i < flattening; i++) { flat *= original; } heightData[x + y * size] = flat; } } // re-normalize back to its oraginal height range float height = minmax[1] - minmax[0]; normalizeTerrain(height); } /** * Smooth the terrain. For each node, its 8 neighbors heights * are averaged and will participate in the node new height * by a factor np between 0 and 1 * * You must first load() the heightmap data before this will have any effect. * * @param np * The factor to what extend the neighbors average has an influence. * Value of 0 will ignore neighbors (no smoothing) * Value of 1 will ignore the node old height. */ public void smooth(float np) { smooth(np, 1); } /** * Smooth the terrain. For each node, its X(determined by radius) neighbors heights * are averaged and will participate in the node new height * by a factor np between 0 and 1 * * You must first load() the heightmap data before this will have any effect. * * @param np * The factor to what extend the neighbors average has an influence. * Value of 0 will ignore neighbors (no smoothing) * Value of 1 will ignore the node old height. */ public void smooth(float np, int radius) { if (np < 0 || np > 1) { return; } if (radius == 0) radius = 1; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { int neighNumber = 0; float neighAverage = 0; for (int rx = -radius; rx <= radius; rx++) { for (int ry = -radius; ry <= radius; ry++) { if (x+rx < 0 || x+rx >= size) { continue; } if (y+ry < 0 || y+ry >= size) { continue; } neighNumber++; neighAverage += heightData[(x+rx) + (y+ry) * size]; } } neighAverage /= neighNumber; float cp = 1 - np; heightData[x + y * size] = neighAverage * np + heightData[x + y * size] * cp; } } } }
/* * Copyright 2014-2016 CyberVision, 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 org.kaaproject.kaa.client.channel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.kaaproject.kaa.client.bootstrap.BootstrapManager; import org.kaaproject.kaa.client.channel.connectivity.ConnectivityChecker; import org.kaaproject.kaa.client.channel.failover.strategies.DefaultFailoverStrategy; import org.kaaproject.kaa.client.channel.failover.FailoverManager; import org.kaaproject.kaa.client.channel.failover.FailoverStatus; import org.kaaproject.kaa.client.channel.failover.strategies.FailoverStrategy; import org.kaaproject.kaa.client.channel.impl.ChannelRuntimeException; import org.kaaproject.kaa.client.channel.impl.DefaultChannelManager; import org.kaaproject.kaa.client.channel.failover.DefaultFailoverManager; import org.kaaproject.kaa.client.context.ExecutorContext; import org.kaaproject.kaa.common.TransportType; import org.kaaproject.kaa.common.endpoint.security.KeyUtil; import org.mockito.Mockito; public class DefaultChannelManagerTest { private static final ExecutorContext CONTEXT = Mockito.mock(ExecutorContext.class); private static final Map<TransportType, ChannelDirection> SUPPORTED_TYPES = new HashMap<TransportType, ChannelDirection>(); static { SUPPORTED_TYPES.put(TransportType.PROFILE, ChannelDirection.BIDIRECTIONAL); SUPPORTED_TYPES.put(TransportType.CONFIGURATION, ChannelDirection.UP); SUPPORTED_TYPES.put(TransportType.NOTIFICATION, ChannelDirection.BIDIRECTIONAL); SUPPORTED_TYPES.put(TransportType.USER, ChannelDirection.BIDIRECTIONAL); SUPPORTED_TYPES.put(TransportType.EVENT, ChannelDirection.DOWN); Mockito.when(CONTEXT.getScheduledExecutor()).thenReturn(Executors.newScheduledThreadPool(1)); } @Test(expected = ChannelRuntimeException.class) public void testNullBootstrapServer() { new DefaultChannelManager(Mockito.mock(BootstrapManager.class), null, null, null); } @Test(expected = ChannelRuntimeException.class) public void testEmptyBootstrapServer() { new DefaultChannelManager(Mockito.mock(BootstrapManager.class), new HashMap<TransportProtocolId, List<TransportConnectionInfo>>(), null, null); } @Test(expected = ChannelRuntimeException.class) public void testEmptyBootstrapManager() { new DefaultChannelManager(null, null, null, null); } @Test public void testAddHttpLpChannel() throws NoSuchAlgorithmException, InvalidKeySpecException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = new HashMap<>(); bootststrapServers.put(TransportProtocolIdConstants.HTTP_TRANSPORT_ID, Collections.singletonList(IPTransportInfoTest.createTestServerInfo( ServerType.BOOTSTRAP, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9889, KeyUtil.generateKeyPair().getPublic()))); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(SUPPORTED_TYPES); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.HTTP_TRANSPORT_ID); Mockito.when(channel.getServerType()).thenReturn(ServerType.OPERATIONS); Mockito.when(channel.getId()).thenReturn("mock_channel"); KaaInternalChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); FailoverManager failoverManager = Mockito.spy(new DefaultFailoverManager(channelManager, CONTEXT)); channelManager.setFailoverManager(failoverManager); channelManager.addChannel(channel); channelManager.addChannel(channel); TransportConnectionInfo server = IPTransportInfoTest.createTestServerInfo( ServerType.OPERATIONS, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9999, KeyUtil.generateKeyPair().getPublic()); channelManager.onTransportConnectionInfoUpdated(server); Mockito.verify(failoverManager, Mockito.times(1)).onServerChanged(Mockito.any(TransportConnectionInfo.class)); // assertEquals(channel, channelManager.getChannelByTransportType(TransportType.PROFILE)); assertEquals(channel, channelManager.getChannel("mock_channel")); assertEquals(channel, channelManager.getChannels().get(0)); channelManager.removeChannel(channel); // assertNull(channelManager.getChannelByTransportType(TransportType.PROFILE)); assertNull(channelManager.getChannel("mock_channel")); assertTrue(channelManager.getChannels().isEmpty()); channelManager.addChannel(channel); Mockito.verify(failoverManager, Mockito.times(2)).onServerChanged(Mockito.any(TransportConnectionInfo.class)); Mockito.verify(channel, Mockito.times(2)).setServer(server); channelManager.clearChannelList(); assertTrue(channelManager.getChannels().isEmpty()); } @Test public void testAddBootstrapChannel() throws NoSuchAlgorithmException, InvalidKeySpecException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = new HashMap<>(); TransportConnectionInfo server = IPTransportInfoTest.createTestServerInfo( ServerType.BOOTSTRAP, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9889, KeyUtil.generateKeyPair().getPublic()); bootststrapServers.put(TransportProtocolIdConstants.HTTP_TRANSPORT_ID, Collections.singletonList(server)); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(SUPPORTED_TYPES); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.HTTP_TRANSPORT_ID); Mockito.when(channel.getServerType()).thenReturn(ServerType.BOOTSTRAP); Mockito.when(channel.getId()).thenReturn("mock_channel"); KaaChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); FailoverManager failoverManager = Mockito.spy(new DefaultFailoverManager(channelManager, CONTEXT)); channelManager.setFailoverManager(failoverManager); channelManager.addChannel(channel); Mockito.verify(failoverManager, Mockito.times(1)).onServerChanged(Mockito.any(TransportConnectionInfo.class)); // assertEquals(channel, channelManager.getChannelByTransportType(TransportType.PROFILE)); assertEquals(channel, channelManager.getChannel("mock_channel")); assertEquals(channel, channelManager.getChannels().get(0)); channelManager.removeChannel(channel); // assertNull(channelManager.getChannelByTransportType(TransportType.PROFILE)); assertNull(channelManager.getChannel("mock_channel")); assertTrue(channelManager.getChannels().isEmpty()); channelManager.addChannel(channel); Mockito.verify(channel, Mockito.times(2)).setServer(server); } @Test public void testOperationServerFailed() throws NoSuchAlgorithmException, InvalidKeySpecException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(SUPPORTED_TYPES); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.HTTP_TRANSPORT_ID); Mockito.when(channel.getId()).thenReturn("mock_channel"); KaaInternalChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); channelManager.addChannel(channel); TransportConnectionInfo opServer = IPTransportInfoTest.createTestServerInfo( ServerType.OPERATIONS, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9999, KeyUtil.generateKeyPair().getPublic()); channelManager.onTransportConnectionInfoUpdated(opServer); channelManager.onServerFailed(opServer, FailoverStatus.NO_CONNECTIVITY); Mockito.verify(bootstrapManager, Mockito.times(1)) .useNextOperationsServer(TransportProtocolIdConstants.HTTP_TRANSPORT_ID, FailoverStatus.NO_CONNECTIVITY); } @Test public void testBootstrapServerFailed() throws NoSuchAlgorithmException, InvalidKeySpecException { final Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = new HashMap<>(); bootststrapServers.put(TransportProtocolIdConstants.HTTP_TRANSPORT_ID, Arrays.asList( IPTransportInfoTest.createTestServerInfo( ServerType.BOOTSTRAP, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9889, KeyUtil.generateKeyPair().getPublic()), IPTransportInfoTest.createTestServerInfo( ServerType.BOOTSTRAP, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost2", 9889, KeyUtil.generateKeyPair().getPublic()))); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); final KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(SUPPORTED_TYPES); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.HTTP_TRANSPORT_ID); Mockito.when(channel.getServerType()).thenReturn(ServerType.BOOTSTRAP); Mockito.when(channel.getId()).thenReturn("mock_channel"); ExecutorContext context = Mockito.mock(ExecutorContext.class); Mockito.when(context.getScheduledExecutor()).thenReturn(Executors.newScheduledThreadPool(1)); KaaChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, context, null); FailoverStrategy failoverStrategy = new DefaultFailoverStrategy(1, 1, 1, TimeUnit.MILLISECONDS); FailoverManager failoverManager = Mockito.spy(new DefaultFailoverManager(channelManager, CONTEXT, failoverStrategy, 1, TimeUnit.MILLISECONDS)); channelManager.setFailoverManager(failoverManager); channelManager.addChannel(channel); Mockito.verify(failoverManager, Mockito.times(1)).onServerChanged(Mockito.any(TransportConnectionInfo.class)); channelManager.onServerFailed(bootststrapServers.get(TransportProtocolIdConstants.HTTP_TRANSPORT_ID).get(0), FailoverStatus.CURRENT_BOOTSTRAP_SERVER_NA); new Thread(new Runnable() { @Override public void run() { Mockito.verify(channel, Mockito.timeout(100).times(1)).setServer(bootststrapServers.get(TransportProtocolIdConstants.HTTP_TRANSPORT_ID).get(1)); } }); Mockito.verify(failoverManager, Mockito.times(1)).onFailover(FailoverStatus.CURRENT_BOOTSTRAP_SERVER_NA); } @Test public void testSingleBootstrapServerFailed() throws NoSuchAlgorithmException, InvalidKeySpecException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = new HashMap<>(); bootststrapServers.put(TransportProtocolIdConstants.HTTP_TRANSPORT_ID, Arrays.asList( IPTransportInfoTest.createTestServerInfo( ServerType.BOOTSTRAP, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9889, KeyUtil.generateKeyPair().getPublic()))); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(SUPPORTED_TYPES); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.HTTP_TRANSPORT_ID); Mockito.when(channel.getServerType()).thenReturn(ServerType.BOOTSTRAP); Mockito.when(channel.getId()).thenReturn("mock_channel"); KaaChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, CONTEXT, null); FailoverManager failoverManager = Mockito.spy(new DefaultFailoverManager(channelManager, CONTEXT)); channelManager.setFailoverManager(failoverManager); channelManager.addChannel(channel); Mockito.verify(failoverManager, Mockito.times(1)).onServerChanged(Mockito.any(TransportConnectionInfo.class)); channelManager.onServerFailed(bootststrapServers.get(TransportProtocolIdConstants.HTTP_TRANSPORT_ID).get(0), FailoverStatus.CURRENT_BOOTSTRAP_SERVER_NA); } @Test public void testRemoveHttpLpChannel() throws NoSuchAlgorithmException, InvalidKeySpecException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); Map<TransportType, ChannelDirection> typesForChannel2 = new HashMap<>(SUPPORTED_TYPES); typesForChannel2.remove(TransportType.USER); KaaDataChannel channel1 = Mockito.mock(KaaDataChannel.class); Mockito.when(channel1.getSupportedTransportTypes()).thenReturn(typesForChannel2); Mockito.when(channel1.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.HTTP_TRANSPORT_ID); Mockito.when(channel1.getServerType()).thenReturn(ServerType.OPERATIONS); Mockito.when(channel1.getId()).thenReturn("mock_channel"); KaaDataChannel channel2 = Mockito.mock(KaaDataChannel.class); Mockito.when(channel2.getSupportedTransportTypes()).thenReturn(SUPPORTED_TYPES); Mockito.when(channel2.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.HTTP_TRANSPORT_ID); Mockito.when(channel2.getServerType()).thenReturn(ServerType.OPERATIONS); Mockito.when(channel2.getId()).thenReturn("mock_channel2"); KaaDataChannel channel3 = Mockito.mock(KaaDataChannel.class); Mockito.when(channel3.getSupportedTransportTypes()).thenReturn(typesForChannel2); Mockito.when(channel3.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel3.getServerType()).thenReturn(ServerType.OPERATIONS); Mockito.when(channel3.getId()).thenReturn("mock_tcp_channel3"); KaaInternalChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); FailoverManager failoverManager = Mockito.spy(new DefaultFailoverManager(channelManager, CONTEXT)); channelManager.setFailoverManager(failoverManager); channelManager.addChannel(channel1); channelManager.addChannel(channel2); TransportConnectionInfo opServer = IPTransportInfoTest.createTestServerInfo( ServerType.OPERATIONS, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9999, KeyUtil.generateKeyPair().getPublic()); channelManager.onTransportConnectionInfoUpdated(opServer); TransportConnectionInfo opServer2 = IPTransportInfoTest.createTestServerInfo( ServerType.OPERATIONS, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9889, KeyUtil.generateKeyPair().getPublic()); channelManager.onTransportConnectionInfoUpdated(opServer2); Mockito.verify(channel1, Mockito.times(1)).setServer(opServer); Mockito.verify(channel2, Mockito.times(1)).setServer(opServer2); // assertEquals(channel2, channelManager.getChannelByTransportType(TransportType.PROFILE)); channelManager.removeChannel(channel2); TransportConnectionInfo opServer3 = IPTransportInfoTest.createTestServerInfo( ServerType.OPERATIONS, TransportProtocolIdConstants.TCP_TRANSPORT_ID, "localhost", 9009, KeyUtil.generateKeyPair().getPublic()); channelManager.addChannel(channel3); channelManager.onTransportConnectionInfoUpdated(opServer3); Mockito.verify(channel3, Mockito.times(1)).setServer(opServer3); // assertEquals(channel3, channelManager.getChannelByTransportType(TransportType.PROFILE)); // assertNull(channelManager.getChannelByTransportType(TransportType.USER)); } @Test public void testConnectivityChecker() throws NoSuchAlgorithmException, InvalidKeySpecException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); TransportProtocolId type = TransportProtocolIdConstants.TCP_TRANSPORT_ID; KaaDataChannel channel1 = Mockito.mock(KaaDataChannel.class); Mockito.when(channel1.getTransportProtocolId()).thenReturn(type); Mockito.when(channel1.getId()).thenReturn("Channel1"); KaaDataChannel channel2 = Mockito.mock(KaaDataChannel.class); Mockito.when(channel2.getTransportProtocolId()).thenReturn(type); Mockito.when(channel2.getId()).thenReturn("Channel2"); channelManager.addChannel(channel1); channelManager.addChannel(channel2); ConnectivityChecker checker = Mockito.mock(ConnectivityChecker.class); channelManager.setConnectivityChecker(checker); Mockito.verify(channel1, Mockito.times(1)).setConnectivityChecker(checker); Mockito.verify(channel2, Mockito.times(1)).setConnectivityChecker(checker); KaaDataChannel channel3 = Mockito.mock(KaaDataChannel.class); Mockito.when(channel3.getTransportProtocolId()).thenReturn(type); Mockito.when(channel3.getId()).thenReturn("Channel3"); channelManager.addChannel(channel3); Mockito.verify(channel3, Mockito.times(1)).setConnectivityChecker(checker); } @Test public void testUpdateForSpecifiedTransport() throws NoSuchAlgorithmException, InvalidKeySpecException, KaaInvalidChannelException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); Map<TransportType, ChannelDirection> types = new HashMap<TransportType, ChannelDirection>(); types.put(TransportType.CONFIGURATION, ChannelDirection.BIDIRECTIONAL); types.put(TransportType.LOGGING, ChannelDirection.UP); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(types); Mockito.when(channel.getId()).thenReturn("channel1"); KaaDataChannel channel2 = Mockito.mock(KaaDataChannel.class); Mockito.when(channel2.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel2.getSupportedTransportTypes()).thenReturn(types); Mockito.when(channel2.getId()).thenReturn("channel2"); channelManager.addChannel(channel2); // assertEquals(channel2, channelManager.getChannelByTransportType(TransportType.LOGGING)); // assertEquals(channel2, channelManager.getChannelByTransportType(TransportType.CONFIGURATION)); channelManager.setChannel(TransportType.LOGGING, channel); channelManager.setChannel(TransportType.LOGGING, null); // assertEquals(channel, channelManager.getChannelByTransportType(TransportType.LOGGING)); // assertEquals(channel2, channelManager.getChannelByTransportType(TransportType.CONFIGURATION)); channelManager.removeChannel(channel2.getId()); // assertEquals(channel, channelManager.getChannelByTransportType(TransportType.CONFIGURATION)); } @Test(expected = KaaInvalidChannelException.class) public void testNegativeUpdateForSpecifiedTransport() throws NoSuchAlgorithmException, InvalidKeySpecException, KaaInvalidChannelException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); Map<TransportType, ChannelDirection> types = new HashMap<TransportType, ChannelDirection>(); types.put(TransportType.CONFIGURATION, ChannelDirection.DOWN); types.put(TransportType.LOGGING, ChannelDirection.UP); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(types); channelManager.setChannel(TransportType.CONFIGURATION, channel); } @Test public void testShutdown() throws NoSuchAlgorithmException, InvalidKeySpecException, KaaInvalidChannelException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); Map<TransportType, ChannelDirection> types = new HashMap<TransportType, ChannelDirection>(); types.put(TransportType.CONFIGURATION, ChannelDirection.BIDIRECTIONAL); types.put(TransportType.LOGGING, ChannelDirection.UP); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(types); Mockito.when(channel.getId()).thenReturn("channel1"); channelManager.addChannel(channel); channelManager.shutdown(); channelManager.onServerFailed(null, FailoverStatus.BOOTSTRAP_SERVERS_NA); channelManager.onTransportConnectionInfoUpdated(null); channelManager.addChannel(null); channelManager.setChannel(null, null); channelManager.setConnectivityChecker(null); Mockito.verify(channel, Mockito.times(1)).shutdown(); } @Test public void testPauseAfterAdd() throws NoSuchAlgorithmException, InvalidKeySpecException, KaaInvalidChannelException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); Map<TransportType, ChannelDirection> types = new HashMap<TransportType, ChannelDirection>(); types.put(TransportType.CONFIGURATION, ChannelDirection.BIDIRECTIONAL); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(types); Mockito.when(channel.getId()).thenReturn("channel1"); channelManager.addChannel(channel); channelManager.pause(); channelManager.pause(); Mockito.verify(channel, Mockito.times(1)).pause(); } @Test public void testPauseBeforeAdd() throws NoSuchAlgorithmException, InvalidKeySpecException, KaaInvalidChannelException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); Map<TransportType, ChannelDirection> types = new HashMap<TransportType, ChannelDirection>(); types.put(TransportType.CONFIGURATION, ChannelDirection.BIDIRECTIONAL); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(types); Mockito.when(channel.getId()).thenReturn("channel1"); channelManager.pause(); channelManager.addChannel(channel); Mockito.verify(channel, Mockito.times(1)).pause(); } @Test public void testPauseBeforeSet() throws NoSuchAlgorithmException, InvalidKeySpecException, KaaInvalidChannelException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); Map<TransportType, ChannelDirection> types = new HashMap<TransportType, ChannelDirection>(); types.put(TransportType.CONFIGURATION, ChannelDirection.BIDIRECTIONAL); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(types); Mockito.when(channel.getId()).thenReturn("channel1"); channelManager.pause(); channelManager.setChannel(TransportType.CONFIGURATION, channel); Mockito.verify(channel, Mockito.times(1)).pause(); } @Test public void testResume() throws NoSuchAlgorithmException, InvalidKeySpecException, KaaInvalidChannelException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = getDefaultBootstrapServers(); BootstrapManager bootstrapManager = Mockito.mock(BootstrapManager.class); DefaultChannelManager channelManager = new DefaultChannelManager(bootstrapManager, bootststrapServers, null, null); Map<TransportType, ChannelDirection> types = new HashMap<TransportType, ChannelDirection>(); types.put(TransportType.CONFIGURATION, ChannelDirection.BIDIRECTIONAL); KaaDataChannel channel = Mockito.mock(KaaDataChannel.class); Mockito.when(channel.getTransportProtocolId()).thenReturn(TransportProtocolIdConstants.TCP_TRANSPORT_ID); Mockito.when(channel.getSupportedTransportTypes()).thenReturn(types); Mockito.when(channel.getId()).thenReturn("channel1"); channelManager.pause(); channelManager.addChannel(channel); channelManager.resume(); Mockito.verify(channel, Mockito.times(1)).pause(); Mockito.verify(channel, Mockito.times(1)).resume(); } private Map<TransportProtocolId, List<TransportConnectionInfo>> getDefaultBootstrapServers() throws NoSuchAlgorithmException { Map<TransportProtocolId, List<TransportConnectionInfo>> bootststrapServers = new HashMap<>(); TransportConnectionInfo server = IPTransportInfoTest.createTestServerInfo( ServerType.BOOTSTRAP, TransportProtocolIdConstants.HTTP_TRANSPORT_ID, "localhost", 9889, KeyUtil.generateKeyPair().getPublic()); bootststrapServers.put(TransportProtocolIdConstants.HTTP_TRANSPORT_ID, Collections.singletonList(server)); return bootststrapServers; } }
/* * The MIT License * * Copyright (c) 2010, Brad Larson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.plugins.repo; import hudson.Util; import hudson.scm.SCMRevisionState; import java.io.PrintStream; import java.io.Serializable; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * A RevisionState records the state of the repository for a particular build. * It is used to see what changed from build to build. */ @SuppressWarnings("serial") class RevisionState extends SCMRevisionState implements Serializable { private final String manifest; private final Map<String, ProjectState> projects = new TreeMap<String, ProjectState>(); private final String url; private final String branch; private final String file; private static Logger debug = Logger.getLogger("hudson.plugins.repo.RevisionState"); /** * Creates a new RepoRevisionState. * * @param manifest * A string representation of the static manifest XML file * @param manifestRevision * Git hash of the manifest repo * @param url * The URL of the manifest * @param branch * The branch of the manifest project * @param file * The path to the manifest file * @param logger * A PrintStream for logging errors */ RevisionState(final String manifest, final String manifestRevision, final String url, final String branch, final String file, @Nullable final PrintStream logger) { this.manifest = manifest; this.url = url; this.branch = branch; this.file = file; try { final InputSource xmlSource = new InputSource(); xmlSource.setCharacterStream(new StringReader(manifest)); final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(xmlSource); if (!doc.getDocumentElement().getNodeName().equals("manifest")) { if (logger != null) { logger.println("Error - malformed manifest"); } return; } final NodeList projectNodes = doc.getElementsByTagName("project"); final int numProjects = projectNodes.getLength(); for (int i = 0; i < numProjects; i++) { final Element projectElement = (Element) projectNodes.item(i); String path = Util.fixEmptyAndTrim(projectElement .getAttribute("path")); final String serverPath = Util.fixEmptyAndTrim(projectElement .getAttribute("name")); final String revision = Util.fixEmptyAndTrim(projectElement .getAttribute("revision")); if (path == null) { // 'repo manifest -o' doesn't output a path if it is the // same as the server path, even if the path is specified. path = serverPath; } if (path != null && serverPath != null && revision != null) { projects.put(path, ProjectState.constructCachedInstance( path, serverPath, revision)); if (logger != null) { logger.println("Added a project: " + path + " at revision: " + revision); } } } final String manifestP = ".repo/manifests.git"; projects.put(manifestP, ProjectState.constructCachedInstance( manifestP, manifestP, manifestRevision)); if (logger != null) { logger.println("Manifest at revision: " + manifestRevision); } } catch (final Exception e) { if (logger != null) { logger.println(e); } } } @Override public boolean equals(final Object obj) { if (obj instanceof RevisionState) { final RevisionState other = (RevisionState) obj; if (branch == null) { if (other.branch != null) { return false; } return projects.equals(other.projects); } return branch.equals(other.branch) && projects.equals(other.projects); } return super.equals(obj); } @Override public int hashCode() { return (branch != null ? branch.hashCode() : 0) ^ (url != null ? url.hashCode() : 0) ^ (file != null ? file.hashCode() : 0) ^ (manifest != null ? manifest.hashCode() : 0) ^ projects.hashCode(); } /** * Returns the manifest repository's url when this state was * created. */ public String getUrl() { return url; } /** * Returns the manifest repository's branch name when this state was * created. */ public String getBranch() { return branch; } /** * Returns the path to the manifest file used when this state was created. */ public String getFile() { return file; } /** * Returns the static XML manifest for this repository state in String form. */ public String getManifest() { return manifest; } /** * Returns the revision for the repository at the specified path. * * @param path * The path to the repository in which we are interested. * @return the SHA1 revision of the repository. */ public String getRevision(final String path) { ProjectState project = projects.get(path); return project == null ? null : project.getRevision(); } /** * Calculate what has changed from a specified previous repository state. * * @param previousState * The previous repository state in which we are interested * @return A List of ProjectStates from the previous repo state which have * since been updated. */ List<ProjectState> whatChanged(@Nullable final RevisionState previousState) { final List<ProjectState> changes = new ArrayList<ProjectState>(); if (previousState == null) { // Everything is new. The change log would include every change, // which might be a little unwieldy (and take forever to // generate/parse). Instead, we will return null (no changes) debug.log(Level.FINE, "Everything is new"); return null; } //final Set<String> keys = projects.keySet(); HashMap<String, ProjectState> previousStateCopy = new HashMap<String, ProjectState>(previousState.projects); for (final Map.Entry<String, ProjectState> entry : projects.entrySet()) { final ProjectState status = previousStateCopy.get(entry.getKey()); if (status == null) { // This is a new project, just added to the manifest. final ProjectState newProject = entry.getValue(); debug.log(Level.FINE, "New project: {0}", entry.getKey()); changes.add(ProjectState.constructCachedInstance( newProject.getPath(), newProject.getServerPath(), null)); } else if (!status.equals(entry.getValue())) { changes.add(previousStateCopy.get(entry.getKey())); } previousStateCopy.remove(entry.getKey()); } changes.addAll(previousStateCopy.values()); return changes; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ftpserver.config.spring; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.ftpserver.DataConnectionConfiguration; import org.apache.ftpserver.DataConnectionConfigurationFactory; import org.apache.ftpserver.FtpServerConfigurationException; import org.apache.ftpserver.ipfilter.DefaultIpFilter; import org.apache.ftpserver.ipfilter.IpFilterType; import org.apache.ftpserver.listener.ListenerFactory; import org.apache.ftpserver.ssl.SslConfiguration; import org.apache.ftpserver.ssl.SslConfigurationFactory; import org.apache.mina.filter.firewall.Subnet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; import org.w3c.dom.Element; /** * Parses the FtpServer "nio-listener" element into a Spring bean graph * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class ListenerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { private final Logger LOG = LoggerFactory .getLogger(ListenerBeanDefinitionParser.class); /** * {@inheritDoc} */ @Override protected Class<?> getBeanClass(final Element element) { return null; } /** * {@inheritDoc} */ @Override protected void doParse(final Element element, final ParserContext parserContext, final BeanDefinitionBuilder builder) { BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(ListenerFactory.class); if (StringUtils.hasText(element.getAttribute("port"))) { factoryBuilder.addPropertyValue("port", Integer.parseInt(element .getAttribute("port"))); } SslConfiguration ssl = parseSsl(element); if (ssl != null) { factoryBuilder.addPropertyValue("sslConfiguration", ssl); } Element dataConElm = SpringUtil.getChildElement(element, FtpServerNamespaceHandler.FTPSERVER_NS, "data-connection"); DataConnectionConfiguration dc = parseDataConnection(dataConElm, ssl); factoryBuilder.addPropertyValue("dataConnectionConfiguration", dc); if (StringUtils.hasText(element.getAttribute("idle-timeout"))) { factoryBuilder.addPropertyValue("idleTimeout", SpringUtil.parseInt( element, "idle-timeout", 300)); } String localAddress = SpringUtil.parseStringFromInetAddress(element, "local-address"); if (localAddress != null) { factoryBuilder.addPropertyValue("serverAddress", localAddress); } factoryBuilder.addPropertyValue("implicitSsl", SpringUtil.parseBoolean( element, "implicit-ssl", false)); Element blacklistElm = SpringUtil.getChildElement(element, FtpServerNamespaceHandler.FTPSERVER_NS, "blacklist"); if (blacklistElm != null) { LOG.warn("Element 'blacklist' is deprecated, and may be removed in a future release. Please use 'ip-filter' instead. "); try { DefaultIpFilter ipFilter = new DefaultIpFilter(IpFilterType.DENY, blacklistElm.getTextContent()); factoryBuilder.addPropertyValue("ipFilter", ipFilter); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid IP address or subnet in the 'blacklist' element", e); } } Element ipFilterElement = SpringUtil.getChildElement(element, FtpServerNamespaceHandler.FTPSERVER_NS, "ip-filter"); if(ipFilterElement != null) { if(blacklistElm != null) { throw new FtpServerConfigurationException("Element 'ipFilter' may not be used when 'blacklist' element is specified. "); } String filterType = ipFilterElement.getAttribute("type"); try { DefaultIpFilter ipFilter = new DefaultIpFilter(IpFilterType.parse(filterType), ipFilterElement.getTextContent()); factoryBuilder.addPropertyValue("ipFilter", ipFilter); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid IP address or subnet in the 'ip-filter' element"); } } BeanDefinition factoryDefinition = factoryBuilder.getBeanDefinition(); String listenerFactoryName = parserContext.getReaderContext().generateBeanName(factoryDefinition); BeanDefinitionHolder factoryHolder = new BeanDefinitionHolder(factoryDefinition, listenerFactoryName); registerBeanDefinition(factoryHolder, parserContext.getRegistry()); // set the factory on the listener bean builder.getRawBeanDefinition().setFactoryBeanName(listenerFactoryName); builder.getRawBeanDefinition().setFactoryMethodName("createListener"); } private SslConfiguration parseSsl(final Element parent) { Element sslElm = SpringUtil.getChildElement(parent, FtpServerNamespaceHandler.FTPSERVER_NS, "ssl"); if (sslElm != null) { SslConfigurationFactory ssl = new SslConfigurationFactory(); Element keyStoreElm = SpringUtil.getChildElement(sslElm, FtpServerNamespaceHandler.FTPSERVER_NS, "keystore"); if (keyStoreElm != null) { ssl.setKeystoreFile(SpringUtil.parseFile(keyStoreElm, "file")); ssl.setKeystorePassword(SpringUtil.parseString(keyStoreElm, "password")); String type = SpringUtil.parseString(keyStoreElm, "type"); if (type != null) { ssl.setKeystoreType(type); } String keyAlias = SpringUtil.parseString(keyStoreElm, "key-alias"); if (keyAlias != null) { ssl.setKeyAlias(keyAlias); } String keyPassword = SpringUtil.parseString(keyStoreElm, "key-password"); if (keyPassword != null) { ssl.setKeyPassword(keyPassword); } String algorithm = SpringUtil.parseString(keyStoreElm, "algorithm"); if (algorithm != null) { ssl.setKeystoreAlgorithm(algorithm); } } Element trustStoreElm = SpringUtil.getChildElement(sslElm, FtpServerNamespaceHandler.FTPSERVER_NS, "truststore"); if (trustStoreElm != null) { ssl.setTruststoreFile(SpringUtil.parseFile(trustStoreElm, "file")); ssl.setTruststorePassword(SpringUtil.parseString(trustStoreElm, "password")); String type = SpringUtil.parseString(trustStoreElm, "type"); if (type != null) { ssl.setTruststoreType(type); } String algorithm = SpringUtil.parseString(trustStoreElm, "algorithm"); if (algorithm != null) { ssl.setTruststoreAlgorithm(algorithm); } } String clientAuthStr = SpringUtil.parseString(sslElm, "client-authentication"); if (clientAuthStr != null) { ssl.setClientAuthentication(clientAuthStr); } String enabledCiphersuites = SpringUtil.parseString(sslElm, "enabled-ciphersuites"); if (enabledCiphersuites != null) { ssl.setEnabledCipherSuites(enabledCiphersuites.split(" ")); } String protocol = SpringUtil.parseString(sslElm, "protocol"); if (protocol != null) { ssl.setSslProtocol(protocol); } return ssl.createSslConfiguration(); } else { return null; } } private DataConnectionConfiguration parseDataConnection( final Element element, final SslConfiguration listenerSslConfiguration) { DataConnectionConfigurationFactory dc = new DataConnectionConfigurationFactory(); if (element != null) { dc.setImplicitSsl(SpringUtil.parseBoolean(element, "implicit-ssl", false)); // data con config element available SslConfiguration ssl = parseSsl(element); if (ssl != null) { LOG.debug("SSL configuration found for the data connection"); dc.setSslConfiguration(ssl); } dc.setIdleTime(SpringUtil.parseInt(element, "idle-timeout", dc.getIdleTime())); Element activeElm = SpringUtil.getChildElement(element, FtpServerNamespaceHandler.FTPSERVER_NS, "active"); if (activeElm != null) { dc.setActiveEnabled(SpringUtil.parseBoolean(activeElm, "enabled", true)); dc.setActiveIpCheck(SpringUtil.parseBoolean(activeElm, "ip-check", false)); dc.setActiveLocalPort(SpringUtil.parseInt(activeElm, "local-port", 0)); String localAddress = SpringUtil.parseStringFromInetAddress( activeElm, "local-address"); if (localAddress != null) { dc.setActiveLocalAddress(localAddress); } } Element passiveElm = SpringUtil.getChildElement(element, FtpServerNamespaceHandler.FTPSERVER_NS, "passive"); if (passiveElm != null) { String address = SpringUtil.parseStringFromInetAddress(passiveElm, "address"); if (address != null) { dc.setPassiveAddress(address); } String externalAddress = SpringUtil.parseStringFromInetAddress( passiveElm, "external-address"); if (externalAddress != null) { dc.setPassiveExternalAddress(externalAddress); } String ports = SpringUtil.parseString(passiveElm, "ports"); if (ports != null) { dc.setPassivePorts(ports); } } } else { // no data conn config element, do we still have SSL config from the // parent? if (listenerSslConfiguration != null) { LOG .debug("SSL configuration found for the listener, falling back for that for the data connection"); dc.setSslConfiguration(listenerSslConfiguration); } } return dc.createDataConnectionConfiguration(); } }
package org.apache.lucene.codecs.blocktree; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.Collection; import java.util.Collections; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.ByteArrayDataInput; import org.apache.lucene.store.IndexInput; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.Accountables; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.RamUsageEstimator; import org.apache.lucene.util.automaton.CompiledAutomaton; import org.apache.lucene.util.fst.ByteSequenceOutputs; import org.apache.lucene.util.fst.FST; /** * BlockTree's implementation of {@link Terms}. * @deprecated Only for 4.x backcompat */ @Deprecated final class Lucene40FieldReader extends Terms implements Accountable { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(Lucene40FieldReader.class) + 3 * RamUsageEstimator.shallowSizeOfInstance(BytesRef.class); final long numTerms; final FieldInfo fieldInfo; final long sumTotalTermFreq; final long sumDocFreq; final int docCount; final long indexStartFP; final long rootBlockFP; final BytesRef rootCode; final BytesRef minTerm; final BytesRef maxTerm; final int longsSize; final Lucene40BlockTreeTermsReader parent; final FST<BytesRef> index; //private boolean DEBUG; Lucene40FieldReader(Lucene40BlockTreeTermsReader parent, FieldInfo fieldInfo, long numTerms, BytesRef rootCode, long sumTotalTermFreq, long sumDocFreq, int docCount, long indexStartFP, int longsSize, IndexInput indexIn, BytesRef minTerm, BytesRef maxTerm) throws IOException { assert numTerms > 0; this.fieldInfo = fieldInfo; //DEBUG = BlockTreeTermsReader.DEBUG && fieldInfo.name.equals("id"); this.parent = parent; this.numTerms = numTerms; this.sumTotalTermFreq = sumTotalTermFreq; this.sumDocFreq = sumDocFreq; this.docCount = docCount; this.indexStartFP = indexStartFP; this.rootCode = rootCode; this.longsSize = longsSize; this.minTerm = minTerm; this.maxTerm = maxTerm; // if (DEBUG) { // System.out.println("BTTR: seg=" + segment + " field=" + fieldInfo.name + " rootBlockCode=" + rootCode + " divisor=" + indexDivisor); // } rootBlockFP = (new ByteArrayDataInput(rootCode.bytes, rootCode.offset, rootCode.length)).readVLong() >>> Lucene40BlockTreeTermsReader.OUTPUT_FLAGS_NUM_BITS; if (indexIn != null) { final IndexInput clone = indexIn.clone(); //System.out.println("start=" + indexStartFP + " field=" + fieldInfo.name); clone.seek(indexStartFP); index = new FST<>(clone, ByteSequenceOutputs.getSingleton()); /* if (false) { final String dotFileName = segment + "_" + fieldInfo.name + ".dot"; Writer w = new OutputStreamWriter(new FileOutputStream(dotFileName)); Util.toDot(index, w, false, false); System.out.println("FST INDEX: SAVED to " + dotFileName); w.close(); } */ } else { index = null; } } @Override public BytesRef getMin() throws IOException { if (minTerm == null) { // Older index that didn't store min/maxTerm return super.getMin(); } else { return minTerm; } } @Override public BytesRef getMax() throws IOException { if (maxTerm == null) { // Older index that didn't store min/maxTerm return super.getMax(); } else { return maxTerm; } } /** For debugging -- used by CheckIndex too*/ @Override public Lucene40Stats getStats() throws IOException { return new Lucene40SegmentTermsEnum(this).computeBlockStats(); } @Override public boolean hasFreqs() { return fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0; } @Override public boolean hasOffsets() { return fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; } @Override public boolean hasPositions() { return fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; } @Override public boolean hasPayloads() { return fieldInfo.hasPayloads(); } @Override public TermsEnum iterator() throws IOException { return new Lucene40SegmentTermsEnum(this); } @Override public long size() { return numTerms; } @Override public long getSumTotalTermFreq() { return sumTotalTermFreq; } @Override public long getSumDocFreq() { return sumDocFreq; } @Override public int getDocCount() { return docCount; } @Override public TermsEnum intersect(CompiledAutomaton compiled, BytesRef startTerm) throws IOException { if (compiled.type != CompiledAutomaton.AUTOMATON_TYPE.NORMAL) { throw new IllegalArgumentException("please use CompiledAutomaton.getTermsEnum instead"); } return new Lucene40IntersectTermsEnum(this, compiled, startTerm); } @Override public long ramBytesUsed() { return BASE_RAM_BYTES_USED + ((index!=null)? index.ramBytesUsed() : 0); } @Override public Collection<Accountable> getChildResources() { if (index == null) { return Collections.emptyList(); } else { return Collections.singleton(Accountables.namedAccountable("term index", index)); } } @Override public String toString() { return "BlockTreeTerms(terms=" + numTerms + ",postings=" + sumDocFreq + ",positions=" + sumTotalTermFreq + ",docs=" + docCount + ")"; } }
package org.wso2.maven.car.artifact; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.wso2.developerstudio.eclipse.utils.file.FileUtils; import org.wso2.maven.capp.model.CAppArtifact; import org.wso2.maven.capp.model.CAppArtifactDependency; import org.wso2.maven.capp.utils.CAppMavenUtils; import org.wso2.maven.car.artifact.utils.FileManagementUtil; import org.wso2.maven.plugin.synapse.utils.SynapseArtifactBundleCreator; /** * Create a bpel artifact from Maven project * * @goal car * @phase package * @description build car artifact */ public class CARMojo extends AbstractMojo { /** * Location target folder * * @parameter expression="${project.build.directory}" */ private File target; /** * Location archiveLocation folder * * @parameter expression="${project.build.directory}" */ private File archiveLocation; /** * finalName to use for the generated capp project if the user wants to override the default name * * @parameter */ public String finalName; /** * @parameter default-value="${project}" */ private MavenProject project; /** * Maven ProjectHelper. * * @component */ private MavenProjectHelper projectHelper; /** * @component */ private ArtifactFactory artifactFactory; /** * @component */ private ArtifactResolver resolver; /** * @parameter default-value="${localRepository}" */ private ArtifactRepository localRepository; /** * @parameter default-value="${project.remoteArtifactRepositories}" */ private List<?> remoteRepositories; /** * Maven ProjectHelper. * * @parameter */ private List<artifact> artifacts; private void setupMavenRepoObjects(){ CAppMavenUtils.setArtifactFactory(artifactFactory); CAppMavenUtils.setResolver(resolver); CAppMavenUtils.setLocalRepository(localRepository); CAppMavenUtils.setRemoteRepositories(remoteRepositories); } private Map<String,CAppArtifactDependency> cAppArtifactDependencies=new HashMap<String, CAppArtifactDependency>(); public void execute() throws MojoExecutionException, MojoFailureException { setupMavenRepoObjects(); CAppArtifact cAppArtifact = new CAppArtifact(project,null); collectArtifacts(cAppArtifact, cAppArtifactDependencies); try { cAppArtifact.setRoot(true); cAppArtifact.toFile(new File(getArchiveDir(),"artifacts.xml")); for (CAppArtifactDependency cAppDependency : cAppArtifactDependencies.values()) { cAppArtifact.setRoot(false); createArtifactData(getArchiveDir(), cAppDependency); } FileManagementUtil.zipFolder(getArchiveDir().toString(), getArchiveFile().toString()); FileManagementUtil.deleteDirectories(getArchiveDir()); project.getArtifact().setFile(getArchiveFile()); } catch (Exception e) { throw new MojoExecutionException("",e); } } private void createArtifactData(File baseCARLocation, CAppArtifactDependency cAppArtifactDependency) throws IOException, MojoExecutionException{ getLog().info("Generating artifact descriptor for artifact: "+cAppArtifactDependency.getName()); File artifactLocation = new File(baseCARLocation,cAppArtifactDependency.getName()+"_"+cAppArtifactDependency.getVersion()); CAppArtifact cAppArtifact = cAppArtifactDependency.getcAppArtifact(); Dependency mavenArtifact = cAppArtifactDependency.getMavenDependency(); String artifactFinalName = null; if(artifacts != null){ for (artifact cappArtifact : artifacts) { if(mavenArtifact.getGroupId().equals(cappArtifact.getGroupId()) && mavenArtifact.getArtifactId().equals(cappArtifact.getArtifactId())){ artifactFinalName = cappArtifact.getFinalName(); break; } } } getLog().info("Copying artifact content to target location."); File[] cappArtifactFile = cAppArtifactDependency.getCappArtifactFile(); for (File file : cappArtifactFile) { if (file.isDirectory()){ FileUtils.copyDirectory(file, new File(artifactLocation,file.getName())); }else if(artifactFinalName == null){ FileUtils.copy(file, new File(artifactLocation,file.getName())); }else{ FileUtils.copy(file, new File(artifactLocation,artifactFinalName)); cAppArtifact.setFile(artifactFinalName); } } cAppArtifact.toFile(new File(artifactLocation,"artifact.xml")); } private void collectArtifacts(CAppArtifact cAppArtifact, Map<String,CAppArtifactDependency> cAppArtifacts) throws MojoExecutionException{ List<CAppArtifactDependency> dependencies = cAppArtifact.getDependencies(); cAppArtifact.getDependencies().clear(); for (CAppArtifactDependency artifactDependency : dependencies) { if (!cAppArtifacts.containsKey(artifactDependency.getDependencyId())){ List<CAppArtifactDependency> artifactsToAdd = processArtifactsToAdd(artifactDependency); boolean originalDependencyPresent=false; for (CAppArtifactDependency cAppArtifactDependency : artifactsToAdd) { cAppArtifact.addDependencies(cAppArtifactDependency); cAppArtifacts.put(cAppArtifactDependency.getDependencyId(), cAppArtifactDependency); collectArtifacts(cAppArtifactDependency.getcAppArtifact(), cAppArtifacts); originalDependencyPresent=originalDependencyPresent || (artifactDependency.getName().equals(cAppArtifactDependency.getName()) && artifactDependency.getVersion().equals(cAppArtifactDependency.getVersion())); } if (!originalDependencyPresent){ cAppArtifact.addIgnoreDependency(artifactDependency); } } } } private List<CAppArtifactDependency> processArtifactsToAdd( CAppArtifactDependency artifactDependency) throws MojoExecutionException{ List<CAppArtifactDependency> artifactsToAdd =new ArrayList<CAppArtifactDependency>(); try { if (artifactDependency.getcAppArtifact().getProject().getPackaging().equals("synapse/configuration")) { SynapseArtifactBundleCreator synapseArtifactBundleCreator = new SynapseArtifactBundleCreator(artifactDependency); artifactsToAdd = synapseArtifactBundleCreator.exportDependentArtifacts(artifactDependency.getCappArtifactFile()[0], artifactDependency); }else{ artifactsToAdd.add(artifactDependency); } } catch (Exception e) { throw new MojoExecutionException("Error occured while processing artifact", e); } return artifactsToAdd; } public MavenProjectHelper getProjectHelper() { return projectHelper; } public void setTarget(File target) { this.target = target; } public File getTarget() { return target; } private File getArchiveDir(){ File archiveDir = new File(getTarget(),"car"); if (!archiveDir.exists()){ archiveDir.mkdirs(); } return archiveDir; } private File getArchiveFile(){ File archiveFile = new File(getArchiveLocation(),project.getArtifactId()+"_"+project.getVersion()+".car"); if(finalName != null && !finalName.trim().equals("")){ archiveFile=new File(getArchiveLocation(), finalName+".car"); } return archiveFile; } public File getArchiveLocation() { return archiveLocation; } public void setArchiveLocation(File archiveLocation) { this.archiveLocation = archiveLocation; } }
package imj3.core; import static imj3.core.IMJCoreTools.cache; import static imj3.core.IMJCoreTools.quantize; import static java.lang.Math.min; import static multij.tools.Tools.ignore; import java.io.Serializable; /** * @author codistmonk (creation 2014-11-29) */ public abstract interface Image2D extends Image { public abstract int getWidth(); public abstract int getHeight(); @Override public default long getPixelCount() { return (long) this.getWidth() * this.getHeight(); } @Override public default long getPixelValue(final long pixel) { return this.getPixelValue(this.getX(pixel), this.getY(pixel)); } @Override public default Image2D setPixelValue(final long pixel, final long value) { return this.setPixelValue(this.getX(pixel), this.getY(pixel), value); } public default Image2D setPixelValue(final int x, final int y, double[] value) { return (Image2D) this.setPixelValue(this.getPixel(x, y), value); } public default double[] getPixelValue(final int x, final int y, double[] result) { return this.getPixelValue(this.getPixel(x, y), result); } public default long getPixelValue(final int x, final int y) { final Image2D tile = this.getTileContaining(x, y); return tile == this ? this.getPixelValue(this.getPixel(x, y)) : tile.getPixelValue(x % this.getOptimalTileWidth(), y % this.getOptimalTileHeight()); } public default long getPixelChannelValue(final int x, final int y, final int channelIndex) { final Image2D tile = this.getTileContaining(x, y); return tile == this ? this.getPixelChannelValue(this.getPixel(x, y), channelIndex) : tile.getPixelChannelValue( x % this.getOptimalTileWidth(), y % this.getOptimalTileHeight(), channelIndex); } public default Image2D setPixelValue(final int x, final int y, final long value) { final Image2D tile = this.getTileContaining(x, y); if (tile == this) { this.setPixelValue(this.getPixel(x, y), value); } else { tile.setPixelValue(x % this.getOptimalTileWidth(), y % this.getOptimalTileHeight(), value); } return this; } public default Image2D setPixelChannelValue(final int x, final int y, final int channelIndex, final long channelValue) { final Image2D tile = this.getTileContaining(x, y); if (tile == this) { this.setPixelChannelValue(this.getPixel(x, y), channelIndex, channelValue); } else { tile.setPixelChannelValue(x % this.getOptimalTileWidth(), y % this.getOptimalTileHeight(), channelIndex, channelValue); } return this; } public default long getPixel(final int x, final int y) { return y * this.getWidth() + x; } public default int getX(final long pixel) { return (int) (pixel % this.getWidth()); } public default int getY(final long pixel) { return (int) (pixel / this.getWidth()); } public default int getOptimalTileWidth() { return this.getWidth(); } public default int getOptimalTileHeight() { return this.getHeight(); } public default int getTileXContaining(final int x) { return quantize(x, this.getOptimalTileWidth()); } public default int getTileYContaining(final int y) { return quantize(y, this.getOptimalTileHeight()); } public default Image2D getTileContaining(final int x, final int y) { final int tileX = quantize(x, this.getOptimalTileWidth()); final int tileY = quantize(y, this.getOptimalTileHeight()); final TileHolder tileHolder = this.getTileHolder(); if (tileHolder == null) { return this.getTile(tileX, tileY); } if (tileX == tileHolder.getX() && tileY == tileHolder.getY()) { return tileHolder.getTile(); } final String tileKey = this.getTileKey(tileX, tileY); return tileHolder.setTile(tileX, tileY, cache(tileKey, () -> this.getTile(tileX, tileY))).getTile(); } public default String getTileKey(final int tileX, final int tileY) { return this.getId() + "_x" + tileX + "_y" + tileY; } public default Image2D getTile(final int tileX, final int tileY) { ignore(tileX); ignore(tileY); return this; } public default Image2D setTile(final int tileX, final int tileY, final Image2D tile) { ignore(tileX); ignore(tileY); ignore(tile); return this; } public default int getTileWidth(final int tileX) { return min(this.getOptimalTileWidth(), this.getWidth() - tileX); } public default int getTileHeight(final int tileY) { return min(this.getOptimalTileHeight(), this.getHeight() - tileY); } public default TileHolder getTileHolder() { return null; } public default Image2D forEachPixel(final Pixel2DProcessor process) { final int w = this.getWidth(); final int h = this.getHeight(); loop: for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { if (!process.pixel(x, y)) { break loop; } } } return this; } public default double getScale() { return 1.0; } public default Image2D getScaledImage(final double scale) { return this; } public default Object toAwt() { return null; } /** * @author codistmonk (creation 2014-12-03) */ public static abstract interface Pixel2DProcessor extends Serializable { public abstract boolean pixel(int x, int y); public default void endOfPatch() { // NOP } } /** * @author codistmonk (creation 2014-30-11) */ public static final class TileHolder implements Serializable { private int x = -1; private int y; private Image2D tile; public final int getX() { return this.x; } public final int getY() { return this.y; } public final Image2D getTile() { return this.tile; } public final TileHolder setTile(final int x, final int y, final Image2D tile) { this.x = x; this.y = y; this.tile = tile; return this; } /** * {@value}. */ private static final long serialVersionUID = 2483266583077586699L; } }
// Copyright (c) 2011, Mike Samuel // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the OWASP 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 HOLDER 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 org.owasp.html; import junit.framework.TestCase; import javax.annotation.Nullable; import org.junit.Test; public class HtmlSanitizerTest extends TestCase { @Test public static final void testEmpty() throws Exception { assertEquals("", sanitize("")); assertEquals("", sanitize(null)); } @Test public static final void testSimpleText() throws Exception { assertEquals("hello world", sanitize("hello world")); } @Test public static final void testEntities1() throws Exception { assertEquals("&lt;hello world&gt;", sanitize("&lt;hello world&gt;")); } @Test public static final void testEntities2() throws Exception { assertEquals("<b>hello <i>world</i></b>", sanitize("<b>hello <i>world</i></b>")); } @Test public static final void testUnknownTagsRemoved() throws Exception { assertEquals("<b>hello <i>world</i></b>", sanitize("<b>hello <bogus></bogus><i>world</i></b>")); } @Test public static final void testUnsafeTagsRemoved() throws Exception { assertEquals("<b>hello <i>world</i></b>", sanitize("<b>hello <i>world</i>" + "<script src=foo.js></script></b>")); } @Test public static final void testUnsafeAttributesRemoved() throws Exception { assertEquals( "<b>hello <i>world</i></b>", sanitize("<b>hello <i onclick=\"takeOverWorld(this)\">world</i></b>")); } @Test public static final void testCruftEscaped() throws Exception { assertEquals("<b>hello <i>world&lt;</i></b> &amp; tomorrow the universe", sanitize( "<b>hello <i>world<</i></b> & tomorrow the universe")); } @Test public static final void testTagCruftRemoved() throws Exception { assertEquals("<b id=\"p-foo\">hello <i>world&lt;</i></b>", sanitize("<b id=\"foo\" / -->hello <i>world<</i></b>")); } @Test public static final void testIdsAndClassesPrefixed() throws Exception { assertEquals( "<b id=\"p-foo\" class=\"p-boo p-bar p-baz\">" + "hello <i>world&lt;</i></b>", sanitize( "<b id=\"foo\" class=\"boo bar baz\">hello <i>world<</i></b>")); } @Test public static final void testSpecialCharsInAttributes() throws Exception { assertEquals( "<b title=\"a&lt;b &amp;&amp; c&gt;b\">bar</b>", sanitize("<b title=\"a<b && c>b\">bar</b>")); } @Test public static final void testUnclosedTags() throws Exception { assertEquals("<div id=\"p-foo\">Bar<br />Baz</div>", sanitize("<div id=\"foo\">Bar<br>Baz")); } @Test public static final void testUnopenedTags() throws Exception { assertEquals("Foo<b>Bar</b>Baz", sanitize("Foo<b></select>Bar</b></b>Baz</select>")); } @Test public static final void testUnsafeEndTags() throws Exception { assertEquals( "", sanitize( "</meta http-equiv=\"refesh\"" + " content=\"1;URL=http://evilgadget.com\">")); } @Test public static final void testEmptyEndTags() throws Exception { assertEquals("<input />", sanitize("<input></input>")); } @Test public static final void testOnLoadStripped() throws Exception { assertEquals( "<img />", sanitize("<img src=http://foo.com/bar ONLOAD=alert(1)>")); } @Test public static final void testClosingTagParameters() throws Exception { assertEquals( "<p>Hello world</p>", sanitize("<p>Hello world</b style=\"width:expression(alert(1))\">")); } @Test public static final void testOptionalEndTags() throws Exception { // Should not be // "<ol> <li>A</li> <li>B<li>C </li></li></ol>" // The difference is significant because in the first, the item contains no // space after 'A", but in the third, the item contains 'C' and a space. assertEquals( "<ol><li>A</li><li>B</li><li>C </li></ol>", sanitize("<ol> <li>A</li> <li>B<li>C </ol>")); } @Test public static final void testFoldingOfHtmlAndBodyTags() throws Exception { assertEquals( "<p>P 1</p>", sanitize("<html><head><title>Foo</title></head>" + "<body><p>P 1</p></body></html>")); assertEquals( "Hello", sanitize("<body bgcolor=\"blue\">Hello</body>")); assertEquals( "<p>Foo</p><p>One</p><p>Two</p>Three<p>Four</p>", sanitize( "<html>" + "<head>" + "<title>Blah</title>" + "<p>Foo</p>" + "</head>" + "<body>" + "<p>One" + "<p>Two</p>" + "Three" + "<p>Four</p>" + "</body>" + "</html>")); } @Test public static final void testEmptyAndValuelessAttributes() throws Exception { assertEquals( "<input checked=\"checked\" type=\"checkbox\" id=\"\" class=\"\" />", sanitize("<input checked type=checkbox id=\"\" class=>")); } @Test public static final void testSgmlShortTags() throws Exception { // We make no attempt to correctly handle SGML short tags since they are // not implemented consistently across browsers, and have been removed from // HTML 5. // // According to http://www.w3.org/QA/2007/10/shorttags.html // Shorttags - the odd side of HTML 4.01 // ... // It uses an ill-known feature of SGML called shorthand markup, which // was authorized in HTML up to HTML 4.01. But what used to be a "cool" // feature for SGML experts becomes a liability in HTML, where the // construct is more likely to appear as a typo than as a conscious // choice. // // All could be fine if this form typo-that-happens-to-be-legal was // properly implemented in contemporary HTML user-agents. It is not. assertEquals("<p></p>", sanitize("<p/b/")); // Short-tag discarded. assertEquals("<p></p>", sanitize("<p<b>")); // Discard <b attribute assertEquals( // This behavior for short tags is not ideal, but it is safe. "<p href=\"/\">first part of the text&lt;/&gt; second part</p>", sanitize("<p<a href=\"/\">first part of the text</> second part")); } @Test public static final void testNul() throws Exception { assertEquals( "<a title=" + "\"harmless SCRIPT&#61;javascript:alert(1) ignored&#61;ignored\">" + "</a>", sanitize( "<A TITLE=" + "\"harmless\0 SCRIPT=javascript:alert(1) ignored=ignored\">" )); } @Test public static final void testDigitsInAttrNames() throws Exception { // See bug 614 for details. assertEquals( "<div>Hello</div>", sanitize( "<div style1=\"expression(\'alert(1)\")\">Hello</div>" )); } @Test public static final void testSupplementaryCodepointEncoding() throws Exception { // &#xd87e;&#xdc1a; is not appropriate. // &#x2f81a; is appropriate as is the unencoded form. assertEquals( "&#x2f81a; | &#x2f81a; | &#x2f81a;", sanitize("&#x2F81A; | \ud87e\udc1a | &#xd87e;&#xdc1a;")); } @Test public static final void testDeeplyNestedTagsDoS() throws Exception { String sanitized = sanitize(stringRepeatedTimes("<div>", 20000)); int n = sanitized.length() / "<div></div>".length(); assertTrue("" + n, 50 <= n && n <= 1000); int middle = n * "<div>".length(); assertEquals(sanitized.substring(0, middle), stringRepeatedTimes("<div>", n)); assertEquals(sanitized.substring(middle), stringRepeatedTimes("</div>", n)); } @Test public static final void testInnerHTMLIE8() throws Exception { // Apparently, in quirks mode, IE8 does a poor job producing innerHTML // values. Given // <div attr="``foo=bar"> // we encode &#96; but if JavaScript does: // nodeA.innerHTML = nodeB.innerHTML; // and nodeB contains the DIV above, then IE8 will produce // <div attr=``foo=bar> // as the value of nodeB.innerHTML and assign it to nodeA. // IE8's HTML parser treats `` as a blank attribute value and foo=bar // becomes a separate attribute. // Adding a space at the end of the attribute prevents this by forcing // IE8 to put double quotes around the attribute when computing // nodeB.innerHTML. assertEquals( "<div title=\"&#96;&#96;onmouseover&#61;alert(1337) \"></div>", sanitize("<div title=\"``onmouseover=alert(1337)\">")); } @Test public static final void testNabobsOfNegativism() throws Exception { // Treating <noscript> as raw-text gains us nothing security-wise. assertEquals("<noscript></noscript>", sanitize("<noscript><evil></noscript>")); assertEquals("<noscript>I <b>&lt;3</b> Ponies</noscript>", sanitize("<noscript>I <b><3</b> Ponies</noscript>")); assertEquals("<noscript>I <b>&lt;3</b> Ponies</noscript>", sanitize("<NOSCRIPT>I <b><3</b> Ponies</noscript><evil>")); assertEquals("<noframes>I <b>&lt;3</b> Ponies</noframes>", sanitize("<noframes>I <b><3</b> Ponies</noframes><evil>")); assertEquals("<noembed>I <b>&lt;3</b> Ponies</noembed>", sanitize("<noembed>I <b><3</b> Ponies</noembed><evil>")); assertEquals("<noxss>I <b>&lt;3</b> Ponies</noxss>", sanitize("<noxss>I <b><3</b> Ponies</noxss><evil>")); assertEquals( "&lt;noscript&gt;I &lt;b&gt;&lt;3&lt;/b&gt; Ponies&lt;/noscript&gt;", sanitize("<xmp><noscript>I <b><3</b> Ponies</noscript></xmp>")); } @Test public static final void testNULs() throws Exception { assertEquals("<b>Hello, </b>", sanitize("<b>Hello, \u0000</b>")); assertEquals("<b>Hello, </b>", sanitize("<b>Hello, \u0000")); assertEquals("", sanitize("\u0000")); assertEquals("<b>Hello, </b>", sanitize("<b>Hello, &#0;</b>")); assertEquals("", sanitize("&#0;")); } @Test public static final void testQMarkMeta() throws Exception { assertEquals( "Hello, <b>World</b>!", sanitize( "" // An XML Prologue. // HTML5 treats it as ignorable content via the bogus comment state. + "<?xml version=\"1\" ?>" + "Hello, " // An XML Processing instruction. // HTML5 treats it as ignorable content via the bogus comment state. + "<?processing instruction?>" + "<b>World" // Appears in HTML copied from outlook. + "<?xml:namespace prefix = o ns = " + "\"urn:schemas-microsoft-com:office:office\" />" + "</b>!")); } @Test public static final void testScriptInIframe() throws Exception { assertEquals( "<iframe></iframe>", sanitize( "<iframe>\n" + " <script>alert(Hi)</script>\n" + "</iframe>")); } private static String sanitize(@Nullable String html) throws Exception { StringBuilder sb = new StringBuilder(); HtmlStreamRenderer renderer = HtmlStreamRenderer.create( sb, new Handler<String>() { public void handle(String errorMessage) { fail(errorMessage); } }); HtmlSanitizer.Policy policy = new HtmlPolicyBuilder() // Allow these tags. .allowElements( "a", "b", "br", "div", "i", "iframe", "img", "input", "li", "ol", "p", "span", "ul", "noscript", "noframes", "noembed", "noxss") // And these attributes. .allowAttributes( "dir", "checked", "class", "href", "id", "target", "title", "type") .globally() // Cleanup IDs and CLASSes and prefix them with p- to move to a separate // name-space. .allowAttributes("id", "class") .matching( new AttributePolicy() { public String apply( String elementName, String attributeName, String value) { return value.replaceAll("(?:^|\\s)([a-zA-Z])", " p-$1") .replaceAll("\\s+", " ") .trim(); } }) .globally() // Don't throw out useless <img> and <input> elements to ease debugging. .allowWithoutAttributes("img", "input") .build(renderer); HtmlSanitizer.sanitize(html, policy); return sb.toString(); } private static final String stringRepeatedTimes(String s, int n) { StringBuilder sb = new StringBuilder(s.length() * n); while (--n >= 0) { sb.append(s); } return sb.toString(); } }
package com.mopub.common.util; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.ResolveInfo; import android.os.Build; import com.mopub.common.MoPubBrowser; import com.mopub.mobileads.MoPubActivity; import com.mopub.mobileads.MraidActivity; import com.mopub.mobileads.MraidVideoPlayerActivity; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowToast; import java.util.List; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) public class ManifestUtilsTest { private Context context; private List<Class<? extends Activity>> requiredWebViewSdkActivities; private List<Class<? extends Activity>> requiredNativeSdkActivities; @Mock private ResolveInfo mockResolveInfo; @Before public void setUp() throws Exception { context = spy(Robolectric.buildActivity(Activity.class).create().get()); requiredWebViewSdkActivities = ManifestUtils.getRequiredWebViewSdkActivities(); requiredNativeSdkActivities = ManifestUtils.getRequiredNativeSdkActivities(); setDebugMode(false); } @After public void tearDown() throws Exception { setDebugMode(false); // This may have been set to a mock during testing. Reset this class back to normal ManifestUtils.setFlagCheckUtil(new ManifestUtils.FlagCheckUtil()); } @Test public void checkWebViewSdkActivitiesDeclared_shouldIncludeFourActivityDeclarations() throws Exception { ShadowLog.setupLogging(); ManifestUtils.checkWebViewActivitiesDeclared(context); assertLogIncludes( "com.mopub.mobileads.MoPubActivity", "com.mopub.mobileads.MraidActivity", "com.mopub.mobileads.MraidVideoPlayerActivity", "com.mopub.common.MoPubBrowser" ); } @Test public void checkNativeSdkActivitiesDeclared_shouldIncludeOneActivityDeclaration() throws Exception { ShadowLog.setupLogging(); ManifestUtils.checkNativeActivitiesDeclared(context); assertLogIncludes("com.mopub.common.MoPubBrowser"); assertLogDoesntInclude( "com.mopub.mobileads.MoPubActivity", "com.mopub.mobileads.MraidActivity", "com.mopub.mobileads.MraidVideoPlayerActivity" ); } @Test public void displayWarningForMissingActivities_withAllActivitiesDeclared_shouldNotShowLogOrToast() throws Exception { Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidVideoPlayerActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubBrowser.class), mockResolveInfo); ShadowLog.setupLogging(); setDebugMode(true); ManifestUtils.displayWarningForMissingActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNull(); assertThat(ShadowLog.getLogs()).isEmpty(); } @Test public void displayWarningForMissingActivities_withOneMissingActivity_shouldLogOnlyThatOne() throws Exception { Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidVideoPlayerActivity.class), mockResolveInfo); // Here, we leave out MoPubBrowser on purpose ShadowLog.setupLogging(); ManifestUtils.displayWarningForMissingActivities(context, requiredWebViewSdkActivities); assertLogIncludes("com.mopub.common.MoPubBrowser"); assertLogDoesntInclude( "com.mopub.mobileads.MoPubActivity", "com.mopub.mobileads.MraidActivity", "com.mopub.mobileads.MraidVideoPlayerActivity" ); } @Test public void displayWarningForMissingActivities_withAllMissingActivities_shouldLogMessage() throws Exception { setDebugMode(true); ShadowLog.setupLogging(); ManifestUtils.displayWarningForMissingActivities(context, requiredWebViewSdkActivities); final List<ShadowLog.LogItem> logs = ShadowLog.getLogs(); assertLogIncludes( "com.mopub.mobileads.MoPubActivity", "com.mopub.mobileads.MraidActivity", "com.mopub.mobileads.MraidVideoPlayerActivity", "com.mopub.common.MoPubBrowser" ); } @Test public void displayWarningForMissingActivities_withMissingActivities_withDebugTrue_shouldShowToast() throws Exception { setDebugMode(true); ManifestUtils.displayWarningForMissingActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNotNull(); final String toastText = ShadowToast.getTextOfLatestToast(); assertThat(toastText).isEqualTo("ERROR: YOUR MOPUB INTEGRATION IS INCOMPLETE.\nCheck logcat and update your AndroidManifest.xml with the correct activities and configuration."); } @Test public void displayWarningForMissingActivities_withMissingActivities_withDebugFalse_shouldNotShowToast() throws Exception { setDebugMode(false); ManifestUtils.displayWarningForMissingActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNull(); } @SuppressWarnings("unchecked") @TargetApi(13) @Test public void displayWarningForMisconfiguredActivities_withAllActivitiesConfigured_shouldNotLogOrShowToast() throws Exception { ManifestUtils.FlagCheckUtil mockActivitiyConfigCheck = mock(ManifestUtils.FlagCheckUtil.class); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_KEYBOARD_HIDDEN))).thenReturn(true); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_ORIENTATION))).thenReturn(true); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_SCREEN_SIZE))).thenReturn(true); ManifestUtils.setFlagCheckUtil(mockActivitiyConfigCheck); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidVideoPlayerActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubBrowser.class), mockResolveInfo); ShadowLog.setupLogging(); setDebugMode(true); ManifestUtils.displayWarningForMisconfiguredActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNull(); assertThat(ShadowLog.getLogs()).isEmpty(); } @SuppressWarnings("unchecked") @TargetApi(13) @Test public void displayWarningForMisconfiguredActivities_withOneMisconfiguredActivity_shouldLogOnlyThatOne() throws Exception { ManifestUtils.FlagCheckUtil mockActivitiyConfigCheck = mock(ManifestUtils.FlagCheckUtil.class); // Misconfigure the first activity; only return false if the activity is MoPubActivity doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); return MoPubActivity.class != args[0]; } }).when(mockActivitiyConfigCheck).hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_KEYBOARD_HIDDEN)); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_ORIENTATION))).thenReturn(true); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_SCREEN_SIZE))).thenReturn(true); ManifestUtils.setFlagCheckUtil(mockActivitiyConfigCheck); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MraidVideoPlayerActivity.class), mockResolveInfo); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubBrowser.class), mockResolveInfo); ShadowLog.setupLogging(); ManifestUtils.displayWarningForMisconfiguredActivities(context, requiredWebViewSdkActivities); assertLogIncludes("com.mopub.mobileads.MoPubActivity"); assertLogIncludes("The android:configChanges param for activity " + MoPubActivity.class.getName() + " must include keyboardHidden."); assertLogDoesntInclude( "com.mopub.mobileads.MraidActivity", "com.mopub.mobileads.MraidVideoPlayerActivity", "com.mopub.common.MoPubBrowser" ); assertLogDoesntInclude("The android:configChanges param for activity " + MoPubActivity.class.getName() + " must include orientation."); assertLogDoesntInclude("The android:configChanges param for activity " + MoPubActivity.class.getName() + " must include screenSize."); } @SuppressWarnings("unchecked") @TargetApi(13) @Test public void displayWarningForMisconfiguredActivities_withOneMisconfiguredActivity_withMissingAllConfigChangesValues_shouldLogAllConfigChangesValues() throws Exception { ManifestUtils.FlagCheckUtil mockActivitiyConfigCheck = mock(ManifestUtils.FlagCheckUtil.class); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_KEYBOARD_HIDDEN))).thenReturn(false); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_ORIENTATION))).thenReturn(false); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_SCREEN_SIZE))).thenReturn(false); ManifestUtils.setFlagCheckUtil(mockActivitiyConfigCheck); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); ShadowLog.setupLogging(); ManifestUtils.displayWarningForMisconfiguredActivities(context, requiredWebViewSdkActivities); assertLogIncludes("The android:configChanges param for activity " + MoPubActivity.class.getName() + " must include keyboardHidden."); assertLogIncludes("The android:configChanges param for activity " + MoPubActivity.class.getName() + " must include orientation."); assertLogIncludes("The android:configChanges param for activity " + MoPubActivity.class.getName() + " must include screenSize."); } @SuppressWarnings("unchecked") @Config(reportSdk = Build.VERSION_CODES.HONEYCOMB_MR1) @TargetApi(13) @Test public void displayWarningForMisconfiguredActivities_withMissingScreenSize_withApiLessThan13_shouldNotLogOrShowToast() throws Exception { ManifestUtils.FlagCheckUtil mockActivitiyConfigCheck = mock(ManifestUtils.FlagCheckUtil.class); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_KEYBOARD_HIDDEN))).thenReturn(true); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_ORIENTATION))).thenReturn(true); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_SCREEN_SIZE))).thenReturn(false); ManifestUtils.setFlagCheckUtil(mockActivitiyConfigCheck); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); ShadowLog.setupLogging(); setDebugMode(true); ManifestUtils.displayWarningForMisconfiguredActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNull(); assertThat(ShadowLog.getLogs()).isEmpty(); } @SuppressWarnings("unchecked") @TargetApi(13) @Test public void displayWarningForMisconfiguredActivities_withMissingScreenSize_withTargetApiLessThan13_shouldNotLogOrShowToast() throws Exception { // Set target API to < 13 ApplicationInfo applicationInfo = context.getApplicationInfo(); applicationInfo.targetSdkVersion = Build.VERSION_CODES.HONEYCOMB_MR1; when(context.getApplicationInfo()).thenReturn(applicationInfo); ManifestUtils.FlagCheckUtil mockActivitiyConfigCheck = mock(ManifestUtils.FlagCheckUtil.class); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_KEYBOARD_HIDDEN))).thenReturn(true); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_ORIENTATION))).thenReturn(true); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_SCREEN_SIZE))).thenReturn(false); ManifestUtils.setFlagCheckUtil(mockActivitiyConfigCheck); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); ShadowLog.setupLogging(); setDebugMode(true); ManifestUtils.displayWarningForMisconfiguredActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNull(); assertThat(ShadowLog.getLogs()).isEmpty(); } @SuppressWarnings("unchecked") @TargetApi(13) @Test public void displayWarningForMisconfiguredActivities_withMisconfiguredActivities_withDebugTrue_shouldShowToast() throws Exception { ManifestUtils.FlagCheckUtil mockActivitiyConfigCheck = mock(ManifestUtils.FlagCheckUtil.class); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_KEYBOARD_HIDDEN))).thenReturn(false); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_ORIENTATION))).thenReturn(false); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_SCREEN_SIZE))).thenReturn(false); ManifestUtils.setFlagCheckUtil(mockActivitiyConfigCheck); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); setDebugMode(true); ManifestUtils.displayWarningForMisconfiguredActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNotNull(); final String toastText = ShadowToast.getTextOfLatestToast(); assertThat(toastText).isEqualTo("ERROR: YOUR MOPUB INTEGRATION IS INCOMPLETE.\nCheck logcat and update your AndroidManifest.xml with the correct activities and configuration."); } @SuppressWarnings("unchecked") @TargetApi(13) @Test public void displayWarningForMisconfiguredActivities_withMisconfiguredActivities_withDebugFalse_shouldNotShowToast() throws Exception { ManifestUtils.FlagCheckUtil mockActivitiyConfigCheck = mock(ManifestUtils.FlagCheckUtil.class); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_KEYBOARD_HIDDEN))).thenReturn(false); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_ORIENTATION))).thenReturn(false); when(mockActivitiyConfigCheck.hasFlag(any(Class.class), anyInt(), eq(ActivityInfo.CONFIG_SCREEN_SIZE))).thenReturn(false); ManifestUtils.setFlagCheckUtil(mockActivitiyConfigCheck); Robolectric.packageManager.addResolveInfoForIntent(new Intent(context, MoPubActivity.class), mockResolveInfo); setDebugMode(false); ManifestUtils.displayWarningForMissingActivities(context, requiredWebViewSdkActivities); assertThat(ShadowToast.getLatestToast()).isNull(); } @Test public void isDebuggable_whenApplicationIsDebuggable_shouldReturnTrue() throws Exception { setDebugMode(true); assertThat(ManifestUtils.isDebuggable(context)).isTrue(); } @Test public void isDebuggable_whenApplicationIsNotDebuggable_shouldReturnFalse() throws Exception { setDebugMode(false); assertThat(ManifestUtils.isDebuggable(context)).isFalse(); } @SuppressWarnings("unchecked") @Test public void getRequiredWebViewSdkActivities_shouldIncludeRequiredActivities() throws Exception { assertThat(requiredWebViewSdkActivities).containsOnly( MoPubActivity.class, MraidActivity.class, MraidVideoPlayerActivity.class, MoPubBrowser.class ); } @SuppressWarnings("unchecked") @Test public void getRequiredNativeSdkActivities_shouldIncludeRequiredActivities() throws Exception { assertThat(requiredNativeSdkActivities).containsOnly( MoPubBrowser.class ); } private void setDebugMode(boolean enabled) { final ApplicationInfo applicationInfo = context.getApplicationInfo(); if (enabled) { applicationInfo.flags |= ApplicationInfo.FLAG_DEBUGGABLE; } else { applicationInfo.flags &= ~ApplicationInfo.FLAG_DEBUGGABLE; } when(context.getApplicationInfo()).thenReturn(applicationInfo); } private void assertLogIncludes(final String... messages) { final String logText = ShadowLog.getLogs().get(0).msg; for (final String message : messages) { assertThat(logText).containsOnlyOnce(message); } } private void assertLogDoesntInclude(final String... messages) { final String logText = ShadowLog.getLogs().get(0).msg; for (final String message : messages) { assertThat(logText).doesNotContain(message); } } }
package be.tarsos.dsp.wavelet.lift; /** * <p> * Polynomial wavelets * </p> * <p> * This wavelet transform uses a polynomial interpolation wavelet (e.g., the * function used to calculate the differences). A HaarWavelet scaling function * (the calculation of the average for the even points) is used. * </p> * <p> * This wavelet transform uses a two stage version of the lifting scheme. In the * "classic" two stage Lifting Scheme wavelet the predict stage preceeds the * update stage. Also, the algorithm is absolutely symetric, with only the * operators (usually addition and subtraction) interchanged. * </p> * <p> * The problem with the classic Lifting Scheme transform is that it can be * difficult to determine how to calculate the smoothing (scaling) function in * the update phase once the predict stage has altered the odd values. This * version of the wavelet transform calculates the update stage first and then * calculates the predict stage from the modified update values. In this case * the predict stage uses 4-point polynomial interpolation using even values * that result from the update stage. * </p> * * <p> * In this version of the wavelet transform the update stage is no longer * perfectly symetric, since the forward and inverse transform equations differ * by more than an addition or subtraction operator. However, this version of * the transform produces a better result than the HaarWavelet transform * extended with a polynomial interpolation stage. * </p> * * <p> * This algorithm was suggested to me from my reading of Wim Sweldens' tutorial * <i>Building Your Own Wavelets at Home</i>. * </p> * * </p> * * <pre> * <a href="http://www.bearcave.com/misl/misl_tech/wavelets/lifting/index.html"> * http://www.bearcave.com/misl/misl_tech/wavelets/lifting/index.html</a> * </pre> * * <h4> * Copyright and Use</h4> * * <p> * You may use this source code without limitation and without fee as long as * you include: * </p> * <blockquote> This software was written and is copyrighted by Ian Kaplan, Bear * Products International, www.bearcave.com, 2001. </blockquote> * <p> * This software is provided "as is", without any warrenty or claim as to its * usefulness. Anyone who uses this source code uses it at their own risk. Nor * is any support provided by Ian Kaplan and Bear Products International. * <p> * Please send any bug fixes or suggested source changes to: * * <pre> * iank@bearcave.com * </pre> * * @author Ian Kaplan */ public class PolynomialWavelets extends LiftingSchemeBaseWavelet { final static int numPts = 4; private PolynomialInterpolation fourPt; /** * PolynomialWavelets class constructor */ public PolynomialWavelets() { fourPt = new PolynomialInterpolation(); } /** * <p> * Copy four points or <i>N</i> (which ever is less) data points from * <i>vec</i> into <i>d</i> These points are the "known" points used in the * polynomial interpolation. * </p> * * @param vec * the input data set on which the wavelet is calculated * @param d * an array into which <i>N</i> data points, starting at * <i>start</i> are copied. * @param N * the number of polynomial interpolation points * @param start * the index in <i>vec</i> from which copying starts */ private void fill(float vec[], float d[], int N, int start) { int n = numPts; if (n > N) n = N; int end = start + n; int j = 0; for (int i = start; i < end; i++) { d[j] = vec[i]; j++; } } // fill /** * <p> * The update stage calculates the forward and inverse HaarWavelet scaling * functions. The forward HaarWavelet scaling function is simply the average * of the even and odd elements. The inverse function is found by simple * algebraic manipulation, solving for the even element given the average * and the odd element. * </p> * <p> * In this version of the wavelet transform the update stage preceeds the * predict stage in the forward transform. In the inverse transform the * predict stage preceeds the update stage, reversing the calculation on the * odd elements. * </p> */ protected void update(float[] vec, int N, int direction) { int half = N >> 1; for (int i = 0; i < half; i++) { int j = i + half; // double updateVal = vec[j] / 2.0; if (direction == forward) { vec[i] = (vec[i] + vec[j]) / 2; } else if (direction == inverse) { vec[i] = (2 * vec[i]) - vec[j]; } else { System.out.println("update: bad direction value"); } } } /** * <p> * Predict an odd point from the even points, using 4-point polynomial * interpolation. * </p> * <p> * The four points used in the polynomial interpolation are the even points. * We pretend that these four points are located at the x-coordinates * 0,1,2,3. The first odd point interpolated will be located between the * first and second even point, at 0.5. The next N-3 points are located at * 1.5 (in the middle of the four points). The last two points are located * at 2.5 and 3.5. For complete documentation see * </p> * * <pre> * <a href="http://www.bearcave.com/misl/misl_tech/wavelets/lifting/index.html"> * http://www.bearcave.com/misl/misl_tech/wavelets/lifting/index.html</a> * </pre> * * <p> * The difference between the predicted (interpolated) value and the actual * odd value replaces the odd value in the forward transform. * </p> * * <p> * As the recursive steps proceed, N will eventually be 4 and then 2. When N * = 4, linear interpolation is used. When N = 2, HaarWavelet interpolation * is used (the prediction for the odd value is that it is equal to the even * value). * </p> * * @param vec * the input data on which the forward or inverse transform is * calculated. * @param N * the area of vec over which the transform is calculated * @param direction * forward or inverse transform */ protected void predict(float[] vec, int N, int direction) { int half = N >> 1; float d[] = new float[numPts]; // int k = 42; for (int i = 0; i < half; i++) { float predictVal; if (i == 0) { if (half == 1) { // e.g., N == 2, and we use HaarWavelet interpolation predictVal = vec[0]; } else { fill(vec, d, N, 0); predictVal = fourPt.interpPoint(0.5f, half, d); } } else if (i == 1) { predictVal = fourPt.interpPoint(1.5f, half, d); } else if (i == half - 2) { predictVal = fourPt.interpPoint(2.5f, half, d); } else if (i == half - 1) { predictVal = fourPt.interpPoint(3.5f, half, d); } else { fill(vec, d, N, i - 1); predictVal = fourPt.interpPoint(1.5f, half, d); } int j = i + half; if (direction == forward) { vec[j] = vec[j] - predictVal; } else if (direction == inverse) { vec[j] = vec[j] + predictVal; } else { System.out .println("PolynomialWavelets::predict: bad direction value"); } } } // predict /** * <p> * Polynomial wavelet lifting scheme transform. * </p> * <p> * This version of the forwardTrans function overrides the function in the * LiftingSchemeBaseWavelet base class. This function introduces an extra * polynomial interpolation stage at the end of the transform. * </p> */ public void forwardTrans(float[] vec) { final int N = vec.length; for (int n = N; n > 1; n = n >> 1) { split(vec, n); update(vec, n, forward); predict(vec, n, forward); } // for } // forwardTrans /** * <p> * Polynomial wavelet lifting Scheme inverse transform. * </p> * <p> * This version of the inverseTrans function overrides the function in the * LiftingSchemeBaseWavelet base class. This function introduces an inverse * polynomial interpolation stage at the start of the inverse transform. * </p> */ public void inverseTrans(float[] vec) { final int N = vec.length; for (int n = 2; n <= N; n = n << 1) { predict(vec, n, inverse); update(vec, n, inverse); merge(vec, n); } } // inverseTrans } // PolynomialWavelets
package carbon.internal; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.content.res.Resources; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Checkable; import android.widget.PopupWindow; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import carbon.Carbon; import carbon.R; import carbon.recycler.ListAdapter; import carbon.recycler.ViewItemDecoration; import carbon.widget.DropDown; import carbon.widget.FrameLayout; import carbon.widget.RecyclerView; public class DropDownMenu extends PopupWindow { protected RecyclerView recycler; private View anchorView; private DropDown.PopupMode popupMode; private ListAdapter defaultAdapter; private DropDown.Mode mode; private List<Integer> selectedIndices = new ArrayList<>(); private RecyclerView.OnItemClickedListener<Serializable> onItemClickedListener; private Serializable customItem; public DropDownMenu(Context context) { super(View.inflate(context, R.layout.carbon_dropdown_menu, null)); getContentView().setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); recycler = getContentView().findViewById(R.id.recycler); recycler.setLayoutManager(new LinearLayoutManager(context)); recycler.setOnKeyListener((v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP && (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_BACK)) { dismiss(); return true; } return false; }); ViewItemDecoration dividerItemDecoration = new ViewItemDecoration(context, R.layout.carbon_menustrip_hseparator_item); dividerItemDecoration.setDrawAfter(position -> getAdapter().getItem(position) == customItem); recycler.addItemDecoration(dividerItemDecoration); ViewItemDecoration paddingItemDecoration = new ViewItemDecoration(context, R.layout.carbon_row_padding); paddingItemDecoration.setDrawBefore(position -> position == 0); paddingItemDecoration.setDrawAfter(position -> position == recycler.getAdapter().getItemCount() - 1); recycler.addItemDecoration(paddingItemDecoration); defaultAdapter = new DropDown.Adapter<>(); recycler.setAdapter(defaultAdapter); setBackgroundDrawable(new ColorDrawable(context.getResources().getColor(android.R.color.transparent))); setTouchable(true); setFocusable(true); setOutsideTouchable(true); setAnimationStyle(0); } public boolean show(View anchor) { anchorView = anchor; super.showAtLocation(anchor, Gravity.START | Gravity.TOP, 0, 0); update(); FrameLayout content = getContentView().findViewById(R.id.carbon_popupContainer); content.animateVisibility(View.VISIBLE); return true; } public boolean showImmediate(View anchor) { anchorView = anchor; super.showAtLocation(anchor, Gravity.START | Gravity.TOP, 0, 0); update(); FrameLayout content = getContentView().findViewById(R.id.carbon_popupContainer); content.setVisibility(View.VISIBLE); return true; } public void update() { if (anchorView == null) return; setClippingEnabled(popupMode == DropDown.PopupMode.Fit); final Resources res = getContentView().getContext().getResources(); int margin = (int) res.getDimension(R.dimen.carbon_margin); int itemHeight = (int) res.getDimension(R.dimen.carbon_dropdownMenuItemHeight); int marginHalf = (int) res.getDimension(R.dimen.carbon_paddingHalf); int selectedItem = 0; ListAdapter adapter = getAdapter(); if (anchorView instanceof android.widget.TextView) { TextView textView = (TextView) anchorView; String text = textView.getText().toString(); for (int i = 0; i < adapter.getItemCount(); i++) { if (adapter.getItem(i).toString().equals(text)) { selectedItem = i; break; } } } Rect windowRect = new Rect(); anchorView.getWindowVisibleDisplayFrame(windowRect); int hWindow = windowRect.bottom - windowRect.top; int wWindow = windowRect.right - windowRect.left; int[] location = new int[2]; anchorView.getLocationInWindow(location); if (popupMode == DropDown.PopupMode.Over) { int maxHeightAbove = location[1] - windowRect.top - marginHalf * 2; int maxItemsAbove = maxHeightAbove / itemHeight; int maxHeightBelow = hWindow - location[1] - marginHalf * 2; int maxItemsBelow = Math.max(1, maxHeightBelow / itemHeight); int itemsBelow = Math.min(adapter.getItemCount() - selectedItem, maxItemsBelow); int itemsAbove = Math.min(selectedItem, maxItemsAbove); int popupX = location[0] - margin - marginHalf; int popupY = location[1] - marginHalf * 2 - itemsAbove * itemHeight - (itemHeight - (anchorView.getHeight() - anchorView.getPaddingTop() - anchorView.getPaddingBottom())) / 2 + anchorView.getPaddingTop(); int popupWidth = anchorView.getWidth() + margin * 2 + marginHalf * 2 - anchorView.getPaddingLeft() - anchorView.getPaddingRight(); int popupHeight = marginHalf * 4 + Math.max(1, itemsAbove + itemsBelow) * itemHeight; popupWidth = Math.min(popupWidth, wWindow - marginHalf * 2); if (popupX < 0) { popupWidth -= Math.min(-popupX, margin); popupX = 0; } if (popupX + popupWidth > wWindow) { int diff = popupX + popupWidth - wWindow; diff = Math.min(margin, diff); popupWidth -= diff; popupX = wWindow - popupWidth; } popupY = MathUtils.constrain(popupY, 0, hWindow - popupHeight); LinearLayoutManager manager = (LinearLayoutManager) recycler.getLayoutManager(); manager.scrollToPositionWithOffset(selectedItem - itemsAbove, 0); update(popupX, popupY, popupWidth, popupHeight); } else { int maxItems = (hWindow - marginHalf * 2 - margin * 2) / itemHeight; int popupX = location[0] - margin - marginHalf; int popupY = location[1] - marginHalf * 2 - (itemHeight - (anchorView.getHeight() - anchorView.getPaddingTop() - anchorView.getPaddingBottom())) / 2 + anchorView.getPaddingTop(); int popupWidth = anchorView.getWidth() + margin * 2 + marginHalf * 2 - anchorView.getPaddingLeft() - anchorView.getPaddingRight(); int popupHeight = marginHalf * 4 + Math.min(recycler.getAdapter().getItemCount(), maxItems) * itemHeight; LinearLayoutManager manager = (LinearLayoutManager) recycler.getLayoutManager(); manager.scrollToPosition(selectedItem); update(popupX, popupY, popupWidth, popupHeight); } super.update(); } @Override public void dismiss() { FrameLayout content = getContentView().findViewById(R.id.carbon_popupContainer); content.animateVisibility(View.INVISIBLE).addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { DropDownMenu.super.dismiss(); } }); } public void dismissImmediate() { super.dismiss(); } /* private int measureContentWidth(android.support.v7.widget.RecyclerView.Adapter adapter) { // Menus don't tend to be long, so this is more sane than it looks. int width = 0; View itemView = null; int itemType = 0; final int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); final int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); final int count = adapter.getItemCount(); for (int i = 0; i < count; i++) { final int positionType = adapter.getItemViewType(i); if (positionType != itemType) { itemType = positionType; itemView = null; } if (mMeasureParent == null) { mMeasureParent = new FrameLayout(getContentView().getContext()); } itemView = adapter.getView(i, itemView, mMeasureParent); itemView.measure(widthMeasureSpec, heightMeasureSpec); width = Math.max(width, itemView.getMeasuredWidth()); } return width; }*/ public void setOnItemClickedListener(RecyclerView.OnItemClickedListener<Serializable> listener) { this.onItemClickedListener = listener; getAdapter().setOnItemClickedListener(listener); } public void setAdapter(RecyclerView.Adapter adapter) { if (adapter == null) { recycler.setAdapter(defaultAdapter); } else { recycler.setAdapter(adapter); } } public ListAdapter<?, Serializable> getAdapter() { return (ListAdapter<?, Serializable>) recycler.getAdapter(); } public void setSelectedIndex(int index) { selectedIndices.clear(); selectedIndices.add(index); } public void setSelectedIndices(int[] indices) { selectedIndices.clear(); for (int i : indices) selectedIndices.add(i); } public int getSelectedIndex() { return selectedIndices.isEmpty() ? Carbon.INVALID_INDEX : selectedIndices.get(0); } public int[] getSelectedIndices() { int[] result = new int[selectedIndices.size()]; for (int i = 0; i < selectedIndices.size(); i++) result[i] = selectedIndices.get(i); return result; } public <Type extends Serializable> void setSelectedItems(List<Type> items) { List<Serializable> adapterItems = getAdapter().getItems(); selectedIndices.clear(); for (Serializable item : items) { for (int i = 0; i < adapterItems.size(); i++) { if (adapterItems.get(i).equals(item)) { selectedIndices.add(i); break; } } } } public <Type extends Serializable> Type getSelectedItem() { return selectedIndices.isEmpty() ? null : (Type) getAdapter().getItem(selectedIndices.get(0)); } public <Type extends Serializable> List<Type> getSelectedItems() { List<Type> result = new ArrayList<>(); for (int i : selectedIndices) result.add((Type) getAdapter().getItem(i)); return result; } public String getSelectedText() { if (selectedIndices.isEmpty()) return ""; StringBuilder builder = new StringBuilder(); Collections.sort(selectedIndices); for (int i : selectedIndices) { builder.append(getAdapter().getItem(i).toString()); builder.append(", "); } return builder.substring(0, builder.length() - 2); } public void toggle(int position) { if (selectedIndices.contains(position)) { selectedIndices.remove(selectedIndices.indexOf(position)); } else { selectedIndices.add(position); } androidx.recyclerview.widget.RecyclerView.ViewHolder viewHolder = recycler.findViewHolderForAdapterPosition(position); if (viewHolder instanceof Checkable) ((Checkable) viewHolder).toggle(); } public DropDown.PopupMode getPopupMode() { return popupMode; } public void setPopupMode(DropDown.PopupMode popupMode) { this.popupMode = popupMode; } public DropDown.Mode getMode() { return mode; } public void setMode(@NonNull DropDown.Mode mode) { this.mode = mode; ListAdapter<?, Serializable> newAdapter; if (mode == DropDown.Mode.MultiSelect) { newAdapter = new DropDown.CheckableAdapter<>(selectedIndices); } else { newAdapter = new DropDown.Adapter<>(); } if (recycler.getAdapter() == defaultAdapter) recycler.setAdapter(newAdapter); defaultAdapter = newAdapter; newAdapter.setOnItemClickedListener(onItemClickedListener); } public <Type extends Serializable> void setCustomItem(Type item) { if (getAdapter().getItems().get(0) == customItem) { getAdapter().getItems().remove(0); getAdapter().notifyItemRemoved(0); } if (getAdapter().getItems().contains(item) || mode != DropDown.Mode.Editable) return; customItem = item; if (item != null) { getAdapter().getItems().add(0, customItem); getAdapter().notifyItemInserted(0); } } public <Type extends Serializable> void setItems(List<Type> items) { defaultAdapter.setItems(items); defaultAdapter.notifyDataSetChanged(); } /* @Override public boolean onSubMenuSelected(SubMenuBuilder subMenu) { if (subMenu.hasVisibleItems()) { PopupMenu subPopup = new PopupMenu(mContext, subMenu, false); subPopup.setCallback(mPresenterCallback); boolean preserveIconSpacing = false; final int count = subMenu.size(); for (int i = 0; i < count; i++) { MenuItem childItem = subMenu.getItem(i); if (childItem.isVisible() && childItem.getIcon() != null) { preserveIconSpacing = true; break; } } if (subPopup.show(anchorView)) { if (mPresenterCallback != null) { mPresenterCallback.onOpenSubMenu(subMenu); } return true; } } return false; }*/ }
package graph; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import edu.uci.ics.jung.graph.AbstractTypedGraph; import edu.uci.ics.jung.graph.DirectedGraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.graph.util.Pair; import graph.objects.Edge; import graph.objects.Vertex; /** * Implementacia directed grafu urcena pre corpus, velmy velky graf. * Tento graf vyuziva rozne predpoklady, ak nebudu splnena moze to * viest k nespravnemu spravaniu. Predpoklady vyuziva k rychlejsiemu * spracovaniu. * * @author Lukas Sekerak */ @SuppressWarnings("serial") public class DirectedCorpusGraph extends AbstractTypedGraph<Vertex, Integer> implements DirectedGraph<Vertex, Integer> { protected GraphHolder builder; /** * Vrati holder grafu. * * @return vrati holder grafu */ public GraphHolder getHolder() { return builder; } /** * Vytvor DirectedCorpusGraph z GraphHolder * @param build */ public DirectedCorpusGraph(GraphHolder build) { super(EdgeType.DIRECTED); builder = build; } /** * Najdi hranu medzi vrcholmy. */ @Override public Integer findEdge(Vertex v1, Vertex v2) { if (!containsVertex(v1) || !containsVertex(v2)) return null; if (v1.getOutcoming() != null && v2.getIncoming() != null) { return findEdgeHalf(v1, v2); } else if (v1.getIncoming() != null && v2.getOutcoming() != null) { return findEdgeHalf(v2, v1); } return null; } private Integer findEdgeHalf(Vertex v1, Vertex v2) { for (int hladamhranu : v1.getOutcoming()) { for (int moznahrana : v2.getIncoming()) { if (hladamhranu == moznahrana) { return new Integer(moznahrana); } } } return null; } /** * Vrat vsetky hrany medzi vrcholmy. */ @Override public Collection<Integer> findEdgeSet(Vertex v1, Vertex v2) { if (!containsVertex(v1) || !containsVertex(v2)) return null; ArrayList<Integer> edge_collection = new ArrayList<Integer>(1); Integer Integer = findEdge(v1, v2); if (Integer == null) return edge_collection; edge_collection.add(Integer); return edge_collection; } protected Collection<Integer> getIncoming_internal(Vertex vertex) { return vertex.getIncomingC(); } protected Collection<Integer> getOutgoing_internal(Vertex vertex) { return vertex.getOutcomingC(); } protected Collection<Vertex> getPreds_internal(Vertex vertex) { int[] hrany = vertex.getIncoming(); if (hrany == null) return new ArrayList<Vertex>(0); ArrayList<Vertex> vertexi = new ArrayList<Vertex>(hrany.length); Edge hrana = Edge.LoadSourceOnly(); for (int hranaindex : hrany) { builder.getEdges().get(hranaindex, hrana); try { vertexi.add(builder.getVertices().getSource(hrana)); } catch (Exception e) { e.printStackTrace(); } } return vertexi; } protected Collection<Vertex> getSuccs_internal(Vertex vertex) { int[] hrany = vertex.getOutcoming(); if (hrany == null) return new ArrayList<Vertex>(0); ArrayList<Vertex> vertexi = new ArrayList<Vertex>(hrany.length); Edge hrana = Edge.LoadTargetOnly(); for (int hranaindex : hrany) { builder.getEdges().get(hranaindex, hrana); try { vertexi.add(builder.getVertices().getTarget(hrana)); } catch (Exception e) { e.printStackTrace(); } } return vertexi; } /** * Ziskaj vsetky hrany ktore vstupuju do vrchola. */ public Collection<Integer> getInEdges(Vertex vertex) { if (!containsVertex(vertex)) return null; return Collections.unmodifiableCollection(getIncoming_internal(vertex)); } /** * Ziskaj vsetky hrany ktore vystupuju z vrchola. */ public Collection<Integer> getOutEdges(Vertex vertex) { if (!containsVertex(vertex)) return null; return Collections.unmodifiableCollection(getOutgoing_internal(vertex)); } /** * Ziskaj vsetkych predchodcov vrchola. */ public Collection<Vertex> getPredecessors(Vertex vertex) { if (!containsVertex(vertex)) return null; return Collections.unmodifiableCollection(getPreds_internal(vertex)); } /** * Ziskaj vsetkych nasledovnikov vrchola. */ public Collection<Vertex> getSuccessors(Vertex vertex) { if (!containsVertex(vertex)) return null; return Collections.unmodifiableCollection(getSuccs_internal(vertex)); } /** * Ziskaj vrcholy ako pair pre hranu. */ public Pair<Vertex> getEndpoints(Integer edge) { if (!containsEdge(edge)) return null; Edge hrana = new Edge(); builder.getEdges().get(edge, hrana); try { return new Pair<Vertex>(builder.getVertices().getSource(hrana), builder.getVertices().getTarget(hrana)); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Vrchol kde hrana zacina. */ public Vertex getSource(Integer directed_edge) { if (!containsEdge(directed_edge)) return null; Edge hrana = new Edge(); builder.getEdges().get(directed_edge, hrana); return builder.getVertices().getSource(hrana); } /** * Vrchol kde hrana konci. */ public Vertex getDest(Integer directed_edge) { if (!containsEdge(directed_edge)) return null; Edge hrana = new Edge(); builder.getEdges().get(directed_edge, hrana); return builder.getVertices().getTarget(hrana); } /** * Je vrchol ten kde dana hrana zacina. */ public boolean isSource(Vertex vertex, Integer edge) { if (!containsEdge(edge) || !containsVertex(vertex)) return false; return vertex.equals(this.getEndpoints(edge).getFirst()); } /** * Je vrchol ten kde dana hrana konci. */ public boolean isDest(Vertex vertex, Integer edge) { if (!containsEdge(edge) || !containsVertex(vertex)) return false; return vertex.equals(this.getEndpoints(edge).getSecond()); } /** * Vrat vsetky hrany. */ public Collection<Integer> getEdges() { return Collections.unmodifiableCollection(builder.getEdges()); } /** * Vrat vsetky vrcholy. */ public Collection<Vertex> getVertices() { return Collections.unmodifiableCollection(builder.getVertices()); } /** * Je tento vrchol medzi znamymi vrcholmy. */ public boolean containsVertex(Vertex vertex) { return builder.getVertices().contains(vertex); } /** * Existuje takato hrana ? */ public boolean containsEdge(Integer edge) { return builder.getEdges().contains(edge); } /** * Vrat pocet vsetkych hran. */ public int getEdgeCount() { return builder.getEdges().size(); } /** * Vrat pocet vsetkych vrcholov. */ public int getVertexCount() { return builder.getVertices().size(); } /** * Vrat vsetkych susedov vrchola. */ public Collection<Vertex> getNeighbors(Vertex vertex) { try { if (!containsVertex(vertex)) return null; Collection<Vertex> neighbors = new ArrayList<Vertex>(); neighbors.addAll(getPreds_internal(vertex)); neighbors.addAll(getSuccs_internal(vertex)); return Collections.unmodifiableCollection(neighbors); } catch (Exception e) { e.printStackTrace(); } return null; } private void getIncidentEdgesCopy(Collection<Integer> incident_edges, int[] hrany) { if (hrany != null) { for (int i = 0; i < hrany.length; i++) incident_edges.add(new Integer(hrany[i])); } } /** * Vrat vsetky susedne hrany. */ public Collection<Integer> getIncidentEdges(Vertex vertex) { if (!containsVertex(vertex)) return null; Collection<Integer> edges = new HashSet<Integer>(vertex.getSusednychHran()); getIncidentEdgesCopy(edges, vertex.getIncoming()); getIncidentEdgesCopy(edges, vertex.getOutcoming()); return Collections.unmodifiableCollection(edges); } /** * Vrat pocet susedov. */ public int degree(Vertex vertex) { if (!containsVertex(vertex)) throw new IllegalArgumentException(vertex + " is not a vertex in this graph"); return vertex.getSusednychHran(); } /** * Vrat pocet susedov. */ public int getNeighborCount(Vertex vertex) { if (!containsVertex(vertex)) throw new IllegalArgumentException(vertex + " is not a vertex in this graph"); return vertex.getSusednychHran(); } /** * Pridaj vrchol do grafu. * * @param key * @param value * @param priority */ public void addVertexFromFile(String key, String value, int priority) { builder.addVertexFromFile(key, value, priority); } /** * Vymaz vrchol z grafu. */ public boolean removeVertex(Vertex vertex) { if (!containsVertex(vertex)) return false; ArrayList<Integer> incident = new ArrayList<Integer>(getIncoming_internal(vertex)); incident.addAll(getOutgoing_internal(vertex)); for (Integer edge : incident) removeEdge(edge); builder.getVertices().remove(vertex); return true; } /** * Vymaz hranu z grafu. */ public boolean removeEdge(Integer edge) { if (!containsEdge(edge)) return false; // TODO: nemusi byt Pair<Vertex> endpoints = this.getEndpoints(edge); Vertex source = endpoints.getFirst(); Vertex dest = endpoints.getSecond(); // remove vertices from each others' adjacency maps source.removeTarget(edge); dest.removeSource(edge); builder.getEdges().remove(edge); return true; } /** * Posli spravu po spracovani suboru, je potrebne poslat spravu * aby graf sa preusporiadal a pod. */ public void ProcessOfReadingEnd() { builder.ProcessOfReadingEnd(); } /** * Pridaj hranu zo suboru. * * @param k1 * @param v1 * @param k2 * @param v2 * @param p */ public void addEdgeFromFile(String k1, String v1, String k2, String v2, int p) { builder.addEdgeFromFile(k1, v1, k2, v2, p); } /** * Nepodporovane. */ public boolean addVertex(Vertex vertex) { throw new UnsupportedOperationException(); } /** * Nepodporovane. */ @Override public boolean addEdge(Integer edge, Pair<? extends Vertex> endpoints, EdgeType edgeType) { throw new UnsupportedOperationException(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.resource; import java.io.BufferedInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.wicket.settings.IResourceSettings; import org.apache.wicket.util.io.IOUtils; import org.apache.wicket.util.listener.IChangeListener; import org.apache.wicket.util.resource.IResourceStream; import org.apache.wicket.util.resource.ResourceStreamNotFoundException; import org.apache.wicket.core.util.resource.locator.IResourceStreamLocator; import org.apache.wicket.util.value.ValueMap; import org.apache.wicket.util.watch.IModificationWatcher; import org.apache.wicket.util.watch.ModificationWatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation of {@link IPropertiesFactory} which uses the * {@link IResourceStreamLocator} as defined by {@link IResourceSettings#getResourceStreamLocator()} * to load the {@link Properties} objects. Depending on the settings, it will assign * {@link ModificationWatcher}s to the loaded resources to support reloading. * * @see org.apache.wicket.settings.IResourceSettings#getPropertiesFactory() * * @author Juergen Donnerstag */ public class PropertiesFactory implements IPropertiesFactory { /** Log. */ private static final Logger log = LoggerFactory.getLogger(PropertiesFactory.class); /** Listeners will be invoked after changes to property file have been detected */ private final List<IPropertiesChangeListener> afterReloadListeners = new ArrayList<IPropertiesChangeListener>(); /** Cache for all property files loaded */ private final Map<String, Properties> propertiesCache = newPropertiesCache(); /** Provides the environment for properties factory */ private final IPropertiesFactoryContext context; /** List of Properties Loader */ private final List<IPropertiesLoader> propertiesLoader; /** * Construct. * * @param context * context for properties factory */ public PropertiesFactory(final IPropertiesFactoryContext context) { this.context = context; this.propertiesLoader = new ArrayList<IPropertiesLoader>(); this.propertiesLoader.add(new IsoPropertiesFilePropertiesLoader("properties")); this.propertiesLoader.add(new UtfPropertiesFilePropertiesLoader("utf8.properties", "utf-8")); this.propertiesLoader.add(new XmlFilePropertiesLoader("properties.xml")); } /** * Gets the {@link List} of properties loader. You may add or remove properties loaders at your * will. * * @return the {@link List} of properties loader */ public List<IPropertiesLoader> getPropertiesLoaders() { return propertiesLoader; } /** * @return new Cache implementation */ protected Map<String, Properties> newPropertiesCache() { return new ConcurrentHashMap<String, Properties>(); } /** * @see org.apache.wicket.resource.IPropertiesFactory#addListener(org.apache.wicket.resource.IPropertiesChangeListener) */ @Override public void addListener(final IPropertiesChangeListener listener) { // Make sure listeners are added only once if (afterReloadListeners.contains(listener) == false) { afterReloadListeners.add(listener); } } /** * @see org.apache.wicket.resource.IPropertiesFactory#clearCache() */ @Override public final void clearCache() { if (propertiesCache != null) { propertiesCache.clear(); } // clear the localizer cache as well context.getLocalizer().clearCache(); } /** * * @see org.apache.wicket.resource.IPropertiesFactory#load(java.lang.Class, java.lang.String) */ @Override public Properties load(final Class<?> clazz, final String path) { // Check the cache Properties properties = null; if (propertiesCache != null) { properties = propertiesCache.get(path); } if (properties == null) { Iterator<IPropertiesLoader> iter = propertiesLoader.iterator(); while ((properties == null) && iter.hasNext()) { IPropertiesLoader loader = iter.next(); String fullPath = path + "." + loader.getFileExtension(); // If not in the cache than try to load properties IResourceStream resourceStream = context.getResourceStreamLocator() .locate(clazz, fullPath); if (resourceStream == null) { continue; } // Watch file modifications final IModificationWatcher watcher = context.getResourceWatcher(true); if (watcher != null) { addToWatcher(path, resourceStream, watcher); } ValueMap props = loadFromLoader(loader, resourceStream); if (props != null) { properties = new Properties(path, props); } } // Cache the lookup if (propertiesCache != null) { if (properties == null) { // Could not locate properties, store a placeholder propertiesCache.put(path, Properties.EMPTY_PROPERTIES); } else { propertiesCache.put(path, properties); } } } if (properties == Properties.EMPTY_PROPERTIES) { // Translate empty properties placeholder to null prior to returning properties = null; } return properties; } /** * * @param loader * @param resourceStream * @return properties */ private ValueMap loadFromLoader(final IPropertiesLoader loader, final IResourceStream resourceStream) { if (log.isInfoEnabled()) { log.info("Loading properties files from " + resourceStream + " with loader " + loader); } BufferedInputStream in = null; try { // Get the InputStream in = new BufferedInputStream(resourceStream.getInputStream()); ValueMap data = loader.loadWicketProperties(in); if (data == null) { java.util.Properties props = loader.loadJavaProperties(in); if (props != null) { // Copy the properties into the ValueMap data = new ValueMap(); Enumeration<?> enumeration = props.propertyNames(); while (enumeration.hasMoreElements()) { String property = (String)enumeration.nextElement(); data.put(property, props.getProperty(property)); } } } return data; } catch (ResourceStreamNotFoundException e) { log.warn("Unable to find resource " + resourceStream, e); } catch (IOException e) { log.warn("Unable to find resource " + resourceStream, e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(resourceStream); } return null; } /** * Add the resource stream to the file being watched * * @param path * @param resourceStream * @param watcher */ private void addToWatcher(final String path, final IResourceStream resourceStream, final IModificationWatcher watcher) { watcher.add(resourceStream, new IChangeListener() { @Override public void onChange() { log.info("A properties files has changed. Removing all entries " + "from the cache. Resource: " + resourceStream); // Clear the whole cache as associated localized files may // be affected and may need reloading as well. clearCache(); // Inform all listeners for (IPropertiesChangeListener listener : afterReloadListeners) { try { listener.propertiesChanged(path); } catch (Exception ex) { PropertiesFactory.log.error("PropertiesReloadListener has thrown an exception: " + ex.getMessage()); } } } }); } /** * For subclasses to get access to the cache * * @return Map */ protected final Map<String, Properties> getCache() { return propertiesCache; } }
package org.zstack.header.storage.primary; import org.zstack.header.configuration.PythonClassInventory; import org.zstack.header.query.*; import org.zstack.header.search.Inventory; import org.zstack.header.storage.snapshot.VolumeSnapshotInventory; import org.zstack.header.volume.VolumeInventory; import org.zstack.header.zone.ZoneInventory; import javax.persistence.JoinColumn; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @inventory * * inventory for primary storage * * @example * * { "inventory": { "uuid": "f4ac0a3119c94c6fae844c2298615d27", "zoneUuid": "f04caf351c014aa890126fc78193d063", "name": "SimulatorPrimaryStorage-0", "url": "nfs://simulator/primary/-0", "description": "Test Primary Storage", "totalCapacity": 10995116277760, "availableCapacity": 10995116277760, "type": "SimulatorPrimaryStorage", "state": "Enabled", "mountPath": "/primarystoragesimulator/f4ac0a3119c94c6fae844c2298615d27", "createDate": "May 1, 2014 2:42:51 PM", "lastOpDate": "May 1, 2014 2:42:51 PM", "attachedClusterUuids": [ "f23e402bc53b4b5abae87273b6004016", "4a1789235a86409a9a6db83f97bc582f", "fe755538d4e845d5b82073e4f80cb90b", "1f45d6d6c02b43bfb6196dcacb5b8a25" ] } } * * @since 0.1.0 */ @Inventory(mappingVOClass = PrimaryStorageVO.class) @PythonClassInventory @ExpandedQueries({ @ExpandedQuery(expandedField = "zone", inventoryClass = ZoneInventory.class, foreignKey = "zoneUuid", expandedInventoryKey = "uuid"), @ExpandedQuery(expandedField = "volume", inventoryClass = VolumeInventory.class, foreignKey = "uuid", expandedInventoryKey = "primaryStorageUuid"), @ExpandedQuery(expandedField = "volumeSnapshot", inventoryClass = VolumeSnapshotInventory.class, foreignKey = "uuid", expandedInventoryKey = "primaryStorageUuid"), @ExpandedQuery(expandedField = "clusterRef", inventoryClass = PrimaryStorageClusterRefInventory.class, foreignKey = "uuid", expandedInventoryKey = "primaryStorageUuid", hidden = true), }) @ExpandedQueryAliases({ @ExpandedQueryAlias(alias = "cluster", expandedField = "clusterRef.cluster") }) public class PrimaryStorageInventory implements Serializable{ /** * @desc primary storage uuid */ private String uuid; /** * @desc uuid of zone this primary storage is in */ private String zoneUuid; /** * @desc * max length of 255 characters */ private String name; /** * @desc * depending on primary storage type, url may have various formats. For example, * nfs primary storage uses url as *server_ip:/share_path* */ private String url; /** * @desc * * max length of 2048 characters * @nullable */ private String description; /** * @desc * total capacity in bytes */ @Queryable(mappingClass = PrimaryStorageCapacityInventory.class, joinColumn = @JoinColumn(name = "uuid", referencedColumnName = "totalCapacity")) private Long totalCapacity; /** * @desc * available capacity in bytes */ @Queryable(mappingClass = PrimaryStorageCapacityInventory.class, joinColumn = @JoinColumn(name = "uuid", referencedColumnName = "availableCapacity")) private Long availableCapacity; /** * @desc * primary storage type */ private String type; /** * @desc * - Enabled: volume can be created on this primary storage * - Disabled: volume can NOT be created on this primary storage * * @choices * - Enabled * - Disabled */ private String state; /** * @desc * - Connecting: connection is being established between zstack and primary storage, no volume can be created * - Connected: primary storage is functional * - Disconnected: primary storage is out of order, no volume can be created * * @choices * - Connecting * - Connected * - Disconnected */ private String status; /** * @desc * depending on primary storage type, mountPath can have various meanings. * For example, for nfs primary storage mountPath is hypervisor filesystem path where remote share * was mounted */ private String mountPath; /** * @desc the time this resource gets created */ private Timestamp createDate; /** * @desc last time this resource gets operated */ private Timestamp lastOpDate; /** * @desc a list of cluster uuid this primary storage has attached to */ @Queryable(mappingClass = PrimaryStorageClusterRefInventory.class, joinColumn = @JoinColumn(name = "primaryStorageUuid", referencedColumnName = "clusterUuid")) private List<String> attachedClusterUuids; public static PrimaryStorageInventory valueOf(PrimaryStorageVO vo) { PrimaryStorageInventory inv = new PrimaryStorageInventory(); inv.setZoneUuid(vo.getZoneUuid()); inv.setCreateDate(vo.getCreateDate()); inv.setDescription(vo.getDescription()); inv.setLastOpDate(vo.getLastOpDate()); inv.setName(vo.getName()); inv.setState(vo.getState().toString()); inv.setType(vo.getType()); inv.setUrl(vo.getUrl()); inv.setUuid(vo.getUuid()); inv.setMountPath(vo.getMountPath()); inv.setStatus(vo.getStatus().toString()); inv.attachedClusterUuids = new ArrayList<String>(vo.getAttachedClusterRefs().size()); for (PrimaryStorageClusterRefVO ref : vo.getAttachedClusterRefs()) { inv.attachedClusterUuids.add(ref.getClusterUuid()); } if (vo.getCapacity() != null) { inv.setTotalCapacity(vo.getCapacity().getTotalCapacity()); inv.setAvailableCapacity(vo.getCapacity().getAvailableCapacity()); } return inv; } public static List<PrimaryStorageInventory> valueOf(Collection<PrimaryStorageVO> vos) { List<PrimaryStorageInventory> invs = new ArrayList<PrimaryStorageInventory>(vos.size()); for (PrimaryStorageVO vo : vos) { invs.add(PrimaryStorageInventory.valueOf(vo)); } return invs; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public long getAvailableCapacity() { return availableCapacity; } public void setAvailableCapacity(long availableCapacity) { this.availableCapacity = availableCapacity; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public long getTotalCapacity() { return totalCapacity; } public void setTotalCapacity(long totalCapacity) { this.totalCapacity = totalCapacity; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public Timestamp getLastOpDate() { return lastOpDate; } public void setLastOpDate(Timestamp lastOpDate) { this.lastOpDate = lastOpDate; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getState() { return state; } public void setState(String state) { this.state = state; } public List<String> getAttachedClusterUuids() { return attachedClusterUuids; } public void setAttachedClusterUuids(List<String> attachedClusterUuids) { this.attachedClusterUuids = attachedClusterUuids; } public String getMountPath() { return mountPath; } public void setMountPath(String mountPath) { this.mountPath = mountPath; } public String getZoneUuid() { return zoneUuid; } public void setZoneUuid(String zoneUuid) { this.zoneUuid = zoneUuid; } }
/* ** Copyright (C) 2015 Aldebaran Robotics ** See COPYING for the license */ package com.aldebaran.qi; import java.lang.reflect.Type; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ExecutionException; import com.aldebaran.qi.serialization.QiSerializer; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class ObjectTest { public AnyObject proxy = null; public AnyObject proxyts = null; public AnyObject obj = null; public AnyObject objts = null; public Session s = null; public Session client = null; public ServiceDirectory sd = null; public DynamicObjectBuilder ob = null; @Before public void setUp() throws Exception { sd = new ServiceDirectory(); s = new Session(); client = new Session(); // Get Service directory listening url. String url = sd.listenUrl(); // Create new QiMessaging generic object ob = new DynamicObjectBuilder(); // Get instance of ReplyService QiService reply = new ReplyService(); // Register event 'Fire' ob.advertiseSignal("fire::(i)"); ob.advertiseMethod("reply::s(s)", reply, "Concatenate given argument with 'bim !'"); ob.advertiseMethod("answer::s()", reply, "Return given argument"); ob.advertiseMethod("add::i(iii)", reply, "Return sum of arguments"); ob.advertiseMethod("info::(sib)(sib)", reply, "Return a tuple containing given arguments"); ob.advertiseMethod("answer::i(i)", reply, "Return given parameter plus 1"); ob.advertiseMethod("answerFloat::f(f)", reply, "Return given parameter plus 1"); ob.advertiseMethod("answerBool::b(b)", reply, "Flip given parameter and return it"); ob.advertiseMethod("abacus::{ib}({ib})", reply, "Flip all booleans in map"); ob.advertiseMethod("echoFloatList::[m]([f])", reply, "Return the exact same list"); ob.advertiseMethod("createObject::o()", reply, "Return a test object"); ob.advertiseMethod("createNullObject::o()", reply, "Return a null object"); ob.advertiseMethod("setStored::v(i)", reply, "Set stored value"); ob.advertiseMethod("waitAndAddToStored::i(ii)", reply, "Wait given time, and return stored + val"); ob.advertiseMethod("genTuple::(is)()", reply, "Return a tuple"); ob.advertiseMethod("genTuples::[(is)]()", reply, "Return a tuple list"); ob.advertiseMethod("getFirstFieldValue::i((is))", reply, "Return the first field value as int"); ob.advertiseMethods(QiSerializer.getDefault(), TestInterface.class, new TestClass()); QiService replyts = new ReplyService(); DynamicObjectBuilder obts = new DynamicObjectBuilder(); obts.advertiseMethod("setStored::v(i)", replyts, "Set stored value"); obts.advertiseMethod("waitAndAddToStored::i(ii)", replyts, "Wait given time, and return stored + val"); obts.advertiseMethod("throwUp::v()", replyts, "Throws"); obts.setThreadingModel(DynamicObjectBuilder.ObjectThreadingModel.MultiThread); // Connect session to Service Directory s.connect(url).sync(); // Register service as serviceTest obj = ob.object(); objts = obts.object(); assertTrue("Service must be registered", s.registerService("serviceTest", obj) > 0); assertTrue("Service must be registered", s.registerService("serviceTestTs", objts) > 0); // Connect client session to service directory client.connect(url).sync(); // Get a proxy to serviceTest proxy = client.service("serviceTest").get(); proxyts = client.service("serviceTestTs").get(); assertNotNull(proxy); assertNotNull(proxyts); } @After public void tearDown() { obj = null; proxy = null; s.close(); client.close(); sd.close(); s = null; client = null; sd = null; } @Test public void singleThread() throws Exception { Future<Integer> v0; v0 = proxy.<Integer>call("waitAndAddToStored", 500, 0); Thread.sleep(10); Future<Void> v1 = proxy.<Void>call("setStored", 42); assertEquals(v0.get(), new Integer(0)); } @Test public void multiThread() throws Exception { Future<Integer> v0 = proxyts.<Integer>call("waitAndAddToStored", 500, 0); Thread.sleep(10); Future<Void> v1 = proxyts.<Void>call("setStored", 42); assertEquals(v0.get(), new Integer(42)); } @Test public void callThrow() throws Exception { Future<Integer> v0 = proxyts.<Integer>call("throwUp"); assertTrue(v0.hasError()); assertEquals(v0.getErrorMessage(), "I has faild"); } @Test public void getErrorOnSuccess() throws Exception { Future<Void> v0 = proxyts.<Void>call("setStored", 18); assertNull(v0.getError()); assertFalse(v0.hasError()); } @Test public void getObject() { boolean ok; AnyObject anyObject = null; try { anyObject = proxy.<AnyObject>call("createObject").get(); } catch (Exception e) { fail("Call must not fail: " + e.getMessage()); } assertNotNull(anyObject); try { assertEquals("foo", anyObject.<String>property("name").get()); } catch (Exception e1) { fail("Property must not fail"); } Map<Object, Object> settings = new HashMap<Object, Object>(); settings.put("foo", true); settings.put("bar", "This is bar"); try { anyObject.setProperty("settings", settings).get(); } catch (Exception e) { fail("Call must succeed: " + e.getMessage()); } Map<Object, Object> readSettings = null; try { readSettings = anyObject.<Map<Object, Object>>property("settings").get(); } catch (ExecutionException e) { fail("Execution must not fail: " + e.getMessage()); } assertEquals(true, readSettings.get("foo")); assertEquals("This is bar", readSettings.get("bar")); String ret = null; try { ret = anyObject.<String>call("answer").get(); } catch (Exception e) { fail("Call must succeed : " + e.getMessage()); } assertEquals("42 !", ret); ok = false; try { ret = anyObject.<String>call("add", 42).get(); } catch (Exception e) { ok = true; System.out.println(e.getMessage()); assertTrue(e.getMessage().startsWith("Could not find suitable " + "method")); } assertTrue(ok); ok = false; try { ret = anyObject.<String>call("add", "42", 42, 42).get(); } catch (ExecutionException e) { ok = true; String prefix = "Could not find suitable method"; System.out.println(e.getMessage()); assertTrue(e.getMessage().startsWith(prefix)); } assertTrue(ok); ok = false; try { ret = anyObject.<String>call("addFoo").get(); } catch (Exception e) { ok = true; String expected = "Can't find method: addFoo\n"; System.out.println(e.getMessage()); System.out.println(expected); assertTrue(e.getMessage().startsWith("Could not find suitable " + "method")); } assertTrue(ok); } @QiStruct static class Item { @QiField(0) int i; @QiField(1) String s; Item() { } Item(int i, String s) { this.i = i; this.s = s; } } @Test public void testCallReturnStructConversion() throws ExecutionException { Tuple tuple = proxy.<Tuple>call("genTuple").get(); assertEquals(42, tuple.get(0)); assertEquals("forty-two", tuple.get(1)); Item item = proxy.call(Item.class, "genTuple").get(); assertEquals(42, item.i); assertEquals("forty-two", item.s); Type listOfItemsType = new TypeToken<List<Item>>() { }.getType(); List<Item> items = proxy.<List<Item>>call(listOfItemsType, "genTuples").get(); item = items.get(0); assertEquals(42, item.i); assertEquals("forty-two", item.s); } @Test public void testCallParameterStructConversion() throws ExecutionException { Item item = new Item(42, "forty-two"); int value = proxy.<Integer>call(int.class, "getFirstFieldValue", item).get(); assertEquals(42, value); } @Test public void callsCanReturnNullAkaInvalidObject() { try { AnyObject anyObject = proxy.<AnyObject>call("createNullObject").get(); assertNull(anyObject); } catch (Exception e) { fail("Call to 'createNullObject' failed: " + e.getMessage()); } } /** * Utility structures for `advertiseMethodsWithComplexSignatureCanBeCalledWithSameType` test * consisting of an interface and a class with a method with a "complex" signature (List of String). */ interface TestInterface { Integer stringListMethod(List<String> values); byte[] byteArrayMethod(byte[] buffer); ByteBuffer byteBufferMethod(ByteBuffer buffer); } static class TestClass implements TestInterface { public Integer stringListMethod(List<String> values) { return values.hashCode(); } public byte[] byteArrayMethod(byte[] buffer) { return buffer; } public ByteBuffer byteBufferMethod(ByteBuffer buffer) { return buffer; } } /** * The purpose of this test is to verify that generic types don't lose type parameter * information when advertised. * In this test case, the method waits for a `List<String>` so the test checks that * it advertised as such and it can be called accordingly. * See issue #41933. */ @Test public void advertiseMethodsWithComplexSignatureCanBeCalledWithSameType() { try { ArrayList<String> l = new ArrayList<String>(); l.add("Test"); // Tries to call complexMethod with coinciding parameters. Future<Integer> f = ob.object().<Integer>call("stringListMethod", l); assertEquals(f.get().intValue(), l.hashCode()); } catch (ExecutionException e) { fail("Call to 'stringListMethod' failed: " + e.getMessage()); } } @Test public void advertiseMethodWithByteArray() { try { byte[] bytes = "Coucou les amis".getBytes(); Future<byte[]> f = ob.object().call("byteArrayMethod", bytes); assertArrayEquals(f.<byte[]>get(), bytes); } catch (ExecutionException e) { fail("Call to 'byteArrayMethod' failed: " + e.getMessage()); } } @Test public void advertiseMethodWithEmptyByteArray() { try { byte[] bytes = new byte[0]; Future<byte[]> f = ob.object().call("byteArrayMethod", bytes); assertArrayEquals(f.<byte[]>get(), bytes); } catch (ExecutionException e) { fail("Call to 'byteArrayMethod' failed: " + e.getMessage()); } } @Test public void advertiseMethodWithEmptyByteBuffer() { try { ByteBuffer buffer = ByteBuffer.allocate(0); Future<ByteBuffer> f = ob.object().call(ByteBuffer.class, "byteBufferMethod", buffer); assertEquals(buffer, f.<ByteBuffer>get()); } catch (ExecutionException e) { fail("Call to 'byteBufferMethod' failed: " + e.getMessage()); } } @Test public void advertiseMethodWithDirectByteBuffer() { try { ByteBuffer originalBuffer = ByteBuffer.allocateDirect(10); // Need to duplicate the buffer in order to compare remaining elements. ByteBuffer consumedBuffer = originalBuffer.duplicate(); Future<ByteBuffer> f = ob.object().call(ByteBuffer.class, "byteBufferMethod", consumedBuffer); ByteBuffer result = f.get(); assertEquals(originalBuffer, result); } catch (ExecutionException e) { fail("Call to 'byteBufferMethod' failed: " + e.getMessage()); } } @Test public void advertiseMethodWithValuesInByteBuffer() { try { // TODO: Replace the following capacity expression when switching to java 8 by // `Byte.BYTES + Character.BYTES + Integer.BYTES + Double.BYTES`. ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + 4 + 8); byte v1 = 24; char v2 = 'x'; int v3 = 42; double v4 = 3.14; buffer.put(v1); buffer.putChar(v2); buffer.putInt(v3); buffer.putDouble(v4); buffer.rewind(); Future<ByteBuffer> f = ob.object().call(ByteBuffer.class, "byteBufferMethod", buffer); ByteBuffer result = f.get(); assertEquals(v1, result.get()); assertEquals(v2, result.getChar()); assertEquals(v3, result.getInt()); assertEquals(v4, result.getDouble(), 0.1); } catch (ExecutionException e) { fail("Call to 'byteBufferMethod' failed: " + e.getMessage()); } } @Test public void advertiseMethodWithByteBuffer() { try { byte[] array = "Coucou les amis".getBytes(); ByteBuffer originalBuffer = ByteBuffer.wrap(array); // Need to duplicate the buffer in order to compare remaining elements. ByteBuffer consumedBuffer = originalBuffer.duplicate(); Future<ByteBuffer> f = ob.object().call(ByteBuffer.class, "byteBufferMethod", consumedBuffer); ByteBuffer result = f.get(); assertEquals(originalBuffer, result); // None of the two buffers should be sliced. Underling array can be compared. assertArrayEquals(originalBuffer.array(), result.array()); } catch (ExecutionException e) { fail("Call to 'byteBufferMethod' failed: " + e.getMessage()); } } @Test public void advertiseMethodWithSlicedByteBuffer() { try { ByteBuffer originalBuffer = ByteBuffer.wrap("Coucou les amis".getBytes(), 2, 5); // Need to duplicate the buffer in order to compare remaining elements. ByteBuffer consumedBuffer = originalBuffer.duplicate(); Future<ByteBuffer> f = ob.object().call(ByteBuffer.class, "byteBufferMethod", consumedBuffer); assertEquals(originalBuffer, f.<ByteBuffer>get()); } catch (ExecutionException e) { fail("Call to 'byteBufferMethod' failed: " + e.getMessage()); } } static class BigObject extends QiService { public void returnBigNames(List<Object> input) { }; } @Test public void advertiseMethodWithBigList() { DynamicObjectBuilder ob = new DynamicObjectBuilder(); try { List<String> names = new ArrayList<String>(); for(int i = 0; i < 1000; i++) { names.add("name" + i); } List<Tuple> itemList = new ArrayList<Tuple>(); for(int i = 0; i < names.size(); ++i) { itemList.add(Tuple.of(names)); } BigObject bigO = new BigObject(); ob.advertiseMethod("returnBigNames::v(m)", bigO, "calling big boy"); Future<Void> fut = ob.object().call("returnBigNames", itemList); fut.get(); } catch (Exception e) { fail("cannot advertise methods: " + e.getMessage()); } } }
package net.powermatcher.fpai.agents; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.measure.Measure; import javax.measure.quantity.Temperature; import javax.measure.unit.NonSI; import javax.measure.unit.SI; import junit.framework.Assert; import junit.framework.TestCase; import net.powermatcher.api.data.Bid; import net.powermatcher.api.data.MarketBasis; import net.powermatcher.api.data.Price; import net.powermatcher.api.messages.BidUpdate; import net.powermatcher.api.messages.PriceUpdate; import net.powermatcher.fpai.test.BidAnalyzer; import net.powermatcher.fpai.test.MockAgentSender; import net.powermatcher.fpai.test.MockSession; import org.flexiblepower.efi.buffer.Actuator; import org.flexiblepower.efi.buffer.ActuatorBehaviour; import org.flexiblepower.efi.buffer.ActuatorUpdate; import org.flexiblepower.efi.buffer.BufferAllocation; import org.flexiblepower.efi.buffer.BufferRegistration; import org.flexiblepower.efi.buffer.BufferStateUpdate; import org.flexiblepower.efi.buffer.BufferSystemDescription; import org.flexiblepower.efi.buffer.BufferTargetProfileUpdate; import org.flexiblepower.efi.buffer.LeakageRate; import org.flexiblepower.efi.buffer.RunningModeBehaviour; import org.flexiblepower.efi.util.FillLevelFunction; import org.flexiblepower.efi.util.RunningMode; import org.flexiblepower.efi.util.Timer; import org.flexiblepower.efi.util.TimerUpdate; import org.flexiblepower.efi.util.Transition; import org.flexiblepower.ral.values.CommodityMeasurables; import org.flexiblepower.ral.values.CommoditySet; import org.flexiblepower.ral.values.Constraint; import org.flexiblepower.ral.values.ConstraintProfile; /** * Test suite for BufferAgent * * TODO: Currently it only tests a single actuator, should be more! * */ public class BufferAgentTest extends TestCase { private static final double NOMINAL_POWER_ON = 1000d; private static final double ONE_HUNDREDTH = 0.01; private static final double FILL_RATE_ONE_OVER_SIXTY_CELSIUS = .001666667; private final static String RESOURCE_ID = "resourceId"; private static final double NOMINAL_POWER_OFF = 0; private final MarketBasis marketBasis = new MarketBasis("electricity", "EUR", 100, 0, 99); private final MockSession session = new MockSession(marketBasis); private final MockContext context = new MockContext(System.currentTimeMillis()); private BufferRegistration<Temperature> singleActuatorRegistration() { Actuator actuator = new Actuator(0, "HeatPump", CommoditySet.onlyElectricity); return new BufferRegistration<Temperature>(RESOURCE_ID, context.currentTime(), Measure.zero(SI.SECOND), "Temerature", SI.CELSIUS, Collections.singletonList(actuator)); } private BufferSystemDescription systemDescription(BufferRegistration<Temperature> registration) { Timer minOnTimer = new Timer(0, "minOnTimer", Measure.valueOf(10, SI.SECOND)); Timer minOffTimer = new Timer(1, "minOffTimer", Measure.valueOf(10, SI.SECOND)); FillLevelFunction<RunningModeBehaviour> offFF = FillLevelFunction.<RunningModeBehaviour> create(20) .add(120, new RunningModeBehaviour(0, CommodityMeasurables.electricity(Measure.valueOf(NOMINAL_POWER_OFF, SI.WATT)), Measure.valueOf(0, NonSI.EUR_PER_HOUR))) .build(); RunningMode<FillLevelFunction<RunningModeBehaviour>> off = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(0, "off", offFF, Collections.singleton(Transition.create(1) .starts(minOnTimer) .isBlockedBy(minOffTimer) .build())); FillLevelFunction<RunningModeBehaviour> onFF = FillLevelFunction.<RunningModeBehaviour> create(20) .add(120, new RunningModeBehaviour(FILL_RATE_ONE_OVER_SIXTY_CELSIUS, CommodityMeasurables.electricity(Measure.valueOf(NOMINAL_POWER_ON, SI.WATT)), Measure.valueOf(0, NonSI.EUR_PER_HOUR))) .build(); RunningMode<FillLevelFunction<RunningModeBehaviour>> on = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(1, "on", onFF, Collections.singleton(Transition.create(0) .starts(minOffTimer) .isBlockedBy(minOnTimer) .build())); Collection<RunningMode<FillLevelFunction<RunningModeBehaviour>>> runningModes = new ArrayList<RunningMode<FillLevelFunction<RunningModeBehaviour>>>(); runningModes.add(on); runningModes.add(off); ActuatorBehaviour ab = new ActuatorBehaviour(0, runningModes); FillLevelFunction<LeakageRate> bufferLeakage = FillLevelFunction.<LeakageRate> create(20) .add(120, new LeakageRate(0.01)) .build(); BufferSystemDescription bsd = new BufferSystemDescription(registration, context.currentTime(), context.currentTime(), Collections.singleton(ab), bufferLeakage); return bsd; } private BufferSystemDescription producingBufferSystemDescription(BufferRegistration<Temperature> registration) { Timer minConsumeTimer = new Timer(0, "minConsumeTimer", Measure.valueOf(10, SI.SECOND)); Timer minOffTimer = new Timer(1, "minOffTimer", Measure.valueOf(10, SI.SECOND)); Timer minProduceTimer = new Timer(2, "minConsumeTimer", Measure.valueOf(10, SI.SECOND)); Set<Transition> transitionsFromOff = new HashSet<Transition>(); transitionsFromOff.add(Transition.create(2) .starts(minProduceTimer) .isBlockedBy(minOffTimer) .isBlockedBy(minConsumeTimer) .build()); transitionsFromOff.add(Transition.create(1) .starts(minConsumeTimer) .isBlockedBy(minOffTimer) .isBlockedBy(minProduceTimer) .build()); RunningMode<FillLevelFunction<RunningModeBehaviour>> off = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(0, "off", FillLevelFunction.<RunningModeBehaviour> create(-20) .add(120, new RunningModeBehaviour(0, CommodityMeasurables.electricity(Measure.valueOf(NOMINAL_POWER_OFF, SI.WATT)), Measure.valueOf(0, NonSI.EUR_PER_HOUR))) .build(), transitionsFromOff); RunningMode<FillLevelFunction<RunningModeBehaviour>> consume = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(1, "consume", FillLevelFunction.<RunningModeBehaviour> create(20) .add(120, new RunningModeBehaviour(1, CommodityMeasurables.electricity(Measure.valueOf(NOMINAL_POWER_ON, SI.WATT)), Measure.valueOf(0, NonSI.EUR_PER_HOUR))) .build(), Collections.singleton(Transition.create(0) .starts(minOffTimer) .isBlockedBy(minConsumeTimer) .isBlockedBy(minProduceTimer) .build())); RunningMode<FillLevelFunction<RunningModeBehaviour>> produce = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(2, "produce", FillLevelFunction.<RunningModeBehaviour> create(20) .add(120, new RunningModeBehaviour(-1, CommodityMeasurables.electricity(Measure.valueOf(-1000, SI.WATT)), Measure.valueOf(0, NonSI.EUR_PER_HOUR))) .build(), Collections.singleton(Transition.create(0) .starts(minOffTimer) .isBlockedBy(minConsumeTimer) .build())); Collection<RunningMode<FillLevelFunction<RunningModeBehaviour>>> runningModes = new ArrayList<RunningMode<FillLevelFunction<RunningModeBehaviour>>>(); runningModes.add(consume); runningModes.add(off); runningModes.add(produce); return new BufferSystemDescription(registration, context.currentTime(), context.currentTime(), Collections.singleton(new ActuatorBehaviour(0, runningModes)), FillLevelFunction.<LeakageRate> create(-20) .add(120, new LeakageRate(ONE_HUNDREDTH)) .build()); } @SuppressWarnings("rawtypes") private MockAgentSender<BufferAgent> agentSender; private BufferAgent<Temperature> agent; @Override @SuppressWarnings("unchecked") protected void setUp() throws Exception { agentSender = MockAgentSender.create(BufferAgent.class, "agent-1", "matcher"); agent = agentSender.getAgent(); agent.setContext(context); agent.connectToMatcher(session); } /** * Test: Agent has not received message but does receive price update * * Expected behavior: Agent does nothing and doesn't break */ public void testNoRegistration() throws Exception { agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 0)); assertNull(agentSender.getLastMessage()); } /** * Test: Agent has not received a BufferSystemDescirption but does receive price update * * Expected behavior: Agent does nothing and doesn't break */ public void testNoSystemDescription() throws Exception { agent.handleControlSpaceRegistration(singleActuatorRegistration()); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 0)); assertNull(agentSender.getLastMessage()); } /** * Test: Agent has two runningmodes, but the other is currently blocked by a timer * * Expected behavior: Agent creates a bid without flexibility */ @SuppressWarnings({ "unchecked" }) public void testTimerBlocking() throws Exception { BufferAgent<Temperature> agent = agentSender.getAgent(); BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); BufferSystemDescription bsd = systemDescription(registration); agentSender.handleMessage(bsd); TimerUpdate minOnTimer = new TimerUpdate(0, new Date(context.currentTimeMillis() + 5000)); // blocking ActuatorUpdate au = new ActuatorUpdate(0, 1, Collections.singleton(minOnTimer)); // current running mode is on BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(60, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 0)); // Bid should not have flexibility Bid bid = session.getLastBid().getBid(); BidAnalyzer.assertFlatBidWithValue(bid, Measure.valueOf(NOMINAL_POWER_ON, SI.WATT)); } /** * Test: Agent has two running modes, but they are not connected through a transition * * Expected behavior: Agent creates a bid without flexibility */ public void testNoTransition() throws Exception { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); // Create system description. FillLevelFunction<RunningModeBehaviour> offFF = FillLevelFunction.<RunningModeBehaviour> create(20) .add(120, new RunningModeBehaviour(1, CommodityMeasurables.electricity(Measure.valueOf(0, SI.WATT)), Measure.valueOf(0, NonSI.EUR_PER_HOUR))) .build(); RunningMode<FillLevelFunction<RunningModeBehaviour>> off = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(0, "off", offFF, Collections.<Transition> emptySet()); FillLevelFunction<RunningModeBehaviour> onFF = FillLevelFunction.<RunningModeBehaviour> create(20) .add(120, new RunningModeBehaviour(1, CommodityMeasurables.electricity(Measure.valueOf(NOMINAL_POWER_ON, SI.WATT)), Measure.valueOf(0, NonSI.EUR_PER_HOUR))) .build(); // There is no way to leave this mode. RunningMode<FillLevelFunction<RunningModeBehaviour>> on = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(1, "on", onFF, Collections.<Transition> emptySet()); Collection<RunningMode<FillLevelFunction<RunningModeBehaviour>>> runningModes = new ArrayList<RunningMode<FillLevelFunction<RunningModeBehaviour>>>(); runningModes.add(on); runningModes.add(off); ActuatorBehaviour ab = new ActuatorBehaviour(0, runningModes); FillLevelFunction<LeakageRate> bufferLeakage = FillLevelFunction.<LeakageRate> create(20) .add(120, new LeakageRate(ONE_HUNDREDTH)) .build(); BufferSystemDescription bsd = new BufferSystemDescription(registration, context.currentTime(), context.currentTime(), Collections.singleton(ab), bufferLeakage); agentSender.handleMessage(bsd); // Create BufferStateUpdate ActuatorUpdate au = new ActuatorUpdate(0, 1, null); // current running mode // is on BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(60, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 0)); // Bid should not have flexibility Bid bid = session.getLastBid().getBid(); BidAnalyzer.assertFlatBidWithValue(bid, Measure.valueOf(NOMINAL_POWER_ON, SI.WATT)); } /** * Test: Agent has a blocking timer but it is not set. * * Expected behavior: Agent produces a flexible bid. */ public void testBlockingTimerNotSet() throws Exception { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); // Actuator is on, but there are no timer updates. agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(35, SI.CELSIUS), Collections.<ActuatorUpdate> singleton(new ActuatorUpdate(0, 1, Collections.<TimerUpdate> emptySet())))); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 0)); // Bid should have flexibility Bid bid2 = session.getLastBid().getBid(); System.out.println("bid with no sys update" + bid2); BidAnalyzer.assertStepBid(bid2); } /** * Test: The timer has just finished. * * The agents should produce a step bid. */ public void testBlockingTimerFinished() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); BufferSystemDescription bsd = systemDescription(registration); agentSender.handleMessage(bsd); // The timer just finished. TimerUpdate minOnTimer = new TimerUpdate(0, new Date(context.currentTimeMillis() - 1)); ActuatorUpdate au = new ActuatorUpdate(0, 1, Collections.singleton(minOnTimer)); BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(60, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 0)); // Bid should not have flexibility Bid bid = session.getLastBid().getBid(); BidAnalyzer.assertStepBid(bid); } /** * Test: Must-run forces agent to allocate the same running mode regardless of price. */ public void testBidResponseMustRun() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); TimerUpdate minOnTimer = new TimerUpdate(0, new Date(context.currentTimeMillis() + 5000)); // blocking ActuatorUpdate au = new ActuatorUpdate(0, 1, Collections.singleton(minOnTimer)); // current running mode is on // This is a must-on situation. BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(60, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 1)); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), 1)); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMaximumPrice()), 1)); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); } /** * Test: Must-run forces agent to allocate the same running mode regardless of price. */ public void testBidResponseFlexible() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); // Attention: The minimum on timer is running, but the current running mode is off, so it should not be bothered // by it. TimerUpdate minOnTimer = new TimerUpdate(0, new Date(context.currentTimeMillis() + 1000)); ActuatorUpdate au = new ActuatorUpdate(0, 0, Collections.singleton(minOnTimer)); // current running mode is off BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(60, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); // Price around halfway means we should do what exactly? // agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 0)); // Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() // .iterator() // .next().getRunningModeId())); // Minimum price means go on! agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), 1)); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); // Maximum price means go off! agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMaximumPrice()), 1)); Assert.assertEquals(0, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); } /** * Test: Buffer is exactly full. * * Should produce a bid that will go off for all prices (effectively, though it may technically be a step function, * where the 'on part' has zero length). */ public void testBufferFull() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); TimerUpdate minOnTimer = new TimerUpdate(0, new Date(context.currentTimeMillis() - 1)); ActuatorUpdate au = new ActuatorUpdate(0, 0, Collections.singleton(minOnTimer)); // current running mode is off BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(120, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), 1)); System.out.println(agentSender.getLastMessage()); Assert.assertEquals(0, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMaximumPrice()), 1)); Assert.assertEquals(0, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), 1)); Assert.assertEquals(0, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); } /** * Test: This test sees what happens when the fill level is over full and how the agent responds. * * Agents should go off for all prices. */ public void testBufferOverFull() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); // No blocking timers. TimerUpdate minOnTimer = new TimerUpdate(0, new Date(context.currentTimeMillis() - 1)); ActuatorUpdate au = new ActuatorUpdate(0, 0, Collections.singleton(minOnTimer)); // Current running mode is off. BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(140, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), 0)); agentSender.handleMessage(bsu); BidUpdate newBid = session.getLastBid(); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMaximumPrice()), newBid.getBidNumber())); BidUpdate newerBid = session.getLastBid(); BidAnalyzer.assertFlatBidWithValue(newBid.getBid(), Measure.valueOf(NOMINAL_POWER_OFF, SI.WATT)); BidAnalyzer.assertFlatBidWithValue(newerBid.getBid(), Measure.valueOf(NOMINAL_POWER_OFF, SI.WATT)); } /** * Test: Buffer is empty. * * It should go on at any price! */ public void testBufferEmpty() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); // No blocking timers. TimerUpdate minOnTimer = new TimerUpdate(1, new Date(context.currentTimeMillis() - 1)); ActuatorUpdate au = new ActuatorUpdate(0, 0, Collections.singleton(minOnTimer)); // Current running mode is off. BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(20, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), 1)); System.out.println(agentSender.getLastMessage()); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMaximumPrice()), 1)); System.out.println("faler:" + agentSender.getLastMessage()); // Bid should not have flexibility BidUpdate bid = session.getLastBid(); System.out.println("faler:" + bid); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), bid.getBidNumber())); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); } /** * A producing buffer should produce bids that have production and consumption in them. */ public void testProducingBuffer() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(producingBufferSystemDescription(registration)); ActuatorUpdate au = new ActuatorUpdate(0, 0, null); // current running mode is Off. Buffer is half full. BufferStateUpdate<Temperature> bsu = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(70, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu); // Price is low. BidUpdate bid = session.getLastBid(); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), bid.getBidNumber())); Assert.assertEquals(NOMINAL_POWER_ON, bid.getBid().getMaximumDemand()); Assert.assertEquals(-1000d, bid.getBid().getMinimumDemand()); Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); // Current running mode is Off. Buffer is empty. BufferStateUpdate<Temperature> bsu2 = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(-20, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu2); // Price is at maximum. BidUpdate bid2 = session.getLastBid(); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMaximumPrice()), bid2.getBidNumber())); System.out.println("overempty: " + bid2); // TODO: Fix these checks, what should happen in overempty? // Assert.assertEquals(NOMINAL_POWER_ON, bid2.getBid().getMaximumDemand()); // Assert.assertEquals(NOMINAL_POWER_ON, bid2.getBid().getMinimumDemand()); // Should consume when at maximum price. // Assert.assertEquals(1, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() // .iterator() // .next().getRunningModeId())); // Current running mode is Off. Buffer is full. BufferStateUpdate<Temperature> bsu3 = new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(120, SI.CELSIUS), Collections.singleton(au)); agentSender.handleMessage(bsu3); // Price is middle. BidUpdate bid3 = session.getLastBid(); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, 50), bid3.getBidNumber())); System.out.println("overfull: " + bid3); Assert.assertEquals(-1000d, bid3.getBid().getMaximumDemand()); Assert.assertEquals(-1000d, bid3.getBid().getMinimumDemand()); // Should discharge (empty buffer) when buffer is full. Assert.assertEquals(2, (((BufferAllocation) (agentSender.getLastMessage())).getActuatorAllocations() .iterator() .next().getRunningModeId())); } /** * Test: A new system description is received with widely differing FillLevelFunctions. A price update now triggers * a bid update. * * The previous state update is not used for making the bid. Rather, a good default is chosen until the first * StateUpdate message arrives. */ public void testNewSystemDescription() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(producingBufferSystemDescription(registration)); ActuatorUpdate au = new ActuatorUpdate(0, 0, null); // current running mode is Off. Buffer is half full. agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(70, SI.CELSIUS), Collections.singleton(au))); Bid oldBid = session.getLastBid().getBid(); FillLevelFunction<RunningModeBehaviour> offFF = FillLevelFunction.<RunningModeBehaviour> create(200) .add(520, new RunningModeBehaviour(0d, CommodityMeasurables.electricity(Measure.valueOf(1d, SI.WATT)), Measure.valueOf(0.02, NonSI.EUR_PER_HOUR))) .build(); RunningMode<FillLevelFunction<RunningModeBehaviour>> off = new RunningMode<FillLevelFunction<RunningModeBehaviour>>(1, "off", offFF, Collections.<Transition> emptySet()); agentSender.handleMessage(new BufferSystemDescription(registration, context.currentTime(), context.currentTime(), Collections.<ActuatorBehaviour> singleton(new ActuatorBehaviour(0, Collections.<RunningMode<FillLevelFunction<RunningModeBehaviour>>> singleton(off))), FillLevelFunction.<LeakageRate> create(200) .add(520, new LeakageRate(ONE_HUNDREDTH)) .build())); // The new system description leads to an invalid fill level, so the agent should not send out a new bid. Assert.assertEquals(oldBid, session.getLastBid().getBid()); } /** * Test: What happens when the buffer is under or overfull. */ public void testOverfullUnderfull() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); // No blocking timers. TimerUpdate minOnTimer = new TimerUpdate(1, new Date(context.currentTimeMillis() - 1)); ActuatorUpdate au = new ActuatorUpdate(0, 0, Collections.singleton(minOnTimer)); // Current running mode is off. Buffer is underfilled. agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(19, SI.CELSIUS), Collections.singleton(au))); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), 1)); // TODO: fix the underful situation // The agent should send a must run bid and an allocation for ON when the fill level is too low. // BidAnalyzer.assertFlatBidWithValue(session.getLastBid().getBid(), Measure.valueOf(NOMINAL_POWER_ON, // SI.WATT)); BufferAllocation allocation = (BufferAllocation) agentSender.getLastMessage(); Assert.assertEquals(0, allocation.getActuatorAllocations().iterator().next().getActuatorId()); // Assert.assertEquals(1, allocation.getActuatorAllocations().iterator().next().getRunningModeId()); agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(1900, SI.CELSIUS), Collections.singleton(au))); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMinimumPrice()), 1)); // The agent should not send out an allocation when the fill level is too high. BidAnalyzer.assertFlatBidWithValue(session.getLastBid().getBid(), Measure.valueOf(NOMINAL_POWER_OFF, SI.WATT)); BufferAllocation allocationNewer = (BufferAllocation) agentSender.getLastMessage(); Assert.assertEquals(0, allocationNewer.getActuatorAllocations().iterator().next().getActuatorId()); Assert.assertEquals(0, allocationNewer.getActuatorAllocations().iterator().next().getRunningModeId()); } /** * Test: The target profile is set to one hour ahead and requires the fill level to be minimum 80% then. * * The bid should continue to be more willing to pay as time goes by, until the latest start time when a must run * bid should be given. */ public void testTargetProfile() { BufferRegistration<Temperature> registration = singleActuatorRegistration(); agentSender.handleMessage(registration); agentSender.handleMessage(systemDescription(registration)); // No blocking timers. TimerUpdate minOnTimer = new TimerUpdate(1, new Date(context.currentTimeMillis() - 1)); ActuatorUpdate au = new ActuatorUpdate(0, 0, Collections.singleton(minOnTimer)); // Current running mode is off. Buffer is half full. agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(70, SI.CELSIUS), Collections.singleton(au))); BidUpdate bidT0 = session.getLastBid(); agent.handlePriceUpdate(new PriceUpdate(new Price(marketBasis, marketBasis.getMaximumPrice()), bidT0.getBidNumber())); // This is valid from one hour from now. Date validFrom = new Date(context.currentTimeMillis() + 1000 * 60 * 60); // Creates a single constraint profile one hour from now with minimum 100 and maximum 120 degrees. ConstraintProfile<Temperature> constraintProfile = ConstraintProfile.<Temperature> create() .duration(Measure.valueOf(60 * 15, SI.SECOND)) .add(new Constraint<Temperature>(Measure.valueOf(100, SI.CELSIUS), Measure.valueOf(120, SI.CELSIUS))) .build(); agentSender.handleMessage(new BufferTargetProfileUpdate<Temperature>(registration, context.currentTime(), validFrom, constraintProfile)); // This target profile update should trigger a bid update. BidUpdate bidT1 = session.getLastBid(); // Jump ahead to 30 minutes before the deadline. context.jump(30 * 60 * 1000); agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(70, SI.CELSIUS), Collections.singleton(au))); BidUpdate bidT1b = session.getLastBid(); // Jump ahead to the profile deadline. context.jump(30 * 60 * 1000); agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(70, SI.CELSIUS), Collections.singleton(au))); BidUpdate bidT2 = session.getLastBid(); // Jump ahead 10 minutes (within the profile). context.jump(10 * 60 * 1000); agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(70, SI.CELSIUS), Collections.singleton(au))); BidUpdate bidT3 = session.getLastBid(); // Jump ahead 10 minutes (the profile has expired now, so it should be flexible again). context.jump(10 * 60 * 1000); agentSender.handleMessage(new BufferStateUpdate<Temperature>(registration, context.currentTime(), context.currentTime(), Measure.valueOf(70, SI.CELSIUS), Collections.singleton(au))); BidUpdate bidT4 = session.getLastBid(); // In this scenario the buffer is always half full, except at T1b (where the buffer is halfway between the // target // profile constraints). // Bid T0 is before the target profile is set. // Bid T1 is when the target profile is just set and an hour away. // Bid T1b is when the target profile is just set and an hour away. // Bid T2 is exactly at the start of the profile. // Bid T3 is is during the target profile period. // Bid T4 is when the profile has ended. BidAnalyzer.assertStepBid(bidT0.getBid()); // Bid T0 should be equal to T4. BidAnalyzer.assertBidsEqual(bidT0.getBid(), bidT4.getBid()); // Bid T1 should be a step bid more eager than T0. BidAnalyzer.assertDemandSumGreaterThan(bidT1.getBid(), bidT0.getBid()); // Bid T1b should be a step bid more eager than T1. BidAnalyzer.assertDemandSumGreaterThan(bidT1b.getBid(), bidT1.getBid()); // Bid T2 at the deadline should effectively be a must run bid. BidAnalyzer.assertDemandAtLeast(bidT2.getBid(), Measure.valueOf(NOMINAL_POWER_ON, SI.WATT)); // Bid T3 should be equal to T0, because at T3 the fill level is halfway between the target profile bounds. BidAnalyzer.assertBidsEqual(bidT0.getBid(), bidT3.getBid()); // Bid T4 is when the target profile has expired, so like T0. Already asserted above. } }
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2017 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.client.editor.simple.components; import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.SimpleComponentDatabase; import com.google.appinventor.client.ComponentsTranslation; import com.google.appinventor.client.Images; import com.google.appinventor.client.Ode; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.simple.components.utils.PropertiesUtil; import com.google.appinventor.client.editor.youngandroid.YaBlocksEditor; import com.google.appinventor.client.editor.youngandroid.YaFormEditor; import com.google.appinventor.client.explorer.SourceStructureExplorerItem; import com.google.appinventor.client.explorer.project.Project; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.client.widgets.ClonedWidget; import com.google.appinventor.client.widgets.LabeledTextBox; import com.google.appinventor.client.widgets.dnd.DragSource; import com.google.appinventor.client.widgets.dnd.DragSourceSupport; import com.google.appinventor.client.widgets.dnd.DropTarget; import com.google.appinventor.client.widgets.properties.EditableProperties; import com.google.appinventor.client.widgets.properties.EditableProperty; import com.google.appinventor.client.widgets.properties.PropertyChangeListener; import com.google.appinventor.client.widgets.properties.PropertyEditor; import com.google.appinventor.client.widgets.properties.TextPropertyEditor; import com.google.appinventor.client.youngandroid.TextValidators; import com.google.appinventor.shared.rpc.project.HasAssetsFolder; import com.google.appinventor.shared.rpc.project.ProjectNode; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidAssetsFolder; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode; import com.google.appinventor.shared.storage.StorageUtil; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.HasAllTouchHandlers; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.dom.client.TouchCancelHandler; import com.google.gwt.event.dom.client.TouchEndHandler; import com.google.gwt.event.dom.client.TouchMoveHandler; import com.google.gwt.event.dom.client.TouchStartHandler; import com.google.gwt.event.dom.client.TouchCancelEvent; import com.google.gwt.event.dom.client.TouchEndEvent; import com.google.gwt.event.dom.client.TouchMoveEvent; import com.google.gwt.event.dom.client.TouchStartEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Random; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.Focusable; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.MouseListener; import com.google.gwt.user.client.ui.MouseListenerCollection; import com.google.gwt.user.client.ui.SourcesMouseEvents; import com.google.gwt.user.client.ui.TreeItem; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.appinventor.shared.simple.ComponentDatabaseInterface.ComponentDefinition; import com.google.appinventor.shared.simple.ComponentDatabaseInterface.PropertyDefinition; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Abstract superclass for all components in the visual designer. * * <p>Since the actual component implementation are for a target platform * that is different from the platform used to implement the development * environment, we need to mock them. * * @author lizlooney@google.com (Liz Looney) */ public abstract class MockComponent extends Composite implements PropertyChangeListener, SourcesMouseEvents, DragSource, HasAllTouchHandlers { // Common property names (not all components support all properties). public static final String PROPERTY_NAME_NAME = "Name"; public static final String PROPERTY_NAME_UUID = "Uuid"; private static final int ICON_IMAGE_WIDTH = 16; private static final int ICON_IMAGE_HEIGHT = 16; public static final int BORDER_SIZE = 2 + 2; // see ode-SimpleMockComponent in Ya.css /** * This class defines the dialog box for renaming a component. */ private class RenameDialog extends DialogBox { // UI elements private final LabeledTextBox newNameTextBox; RenameDialog(String oldName) { super(false, true); setStylePrimaryName("ode-DialogBox"); setText(MESSAGES.renameTitle()); VerticalPanel contentPanel = new VerticalPanel(); LabeledTextBox oldNameTextBox = new LabeledTextBox(MESSAGES.oldNameLabel()); oldNameTextBox.setText(getName()); oldNameTextBox.setEnabled(false); contentPanel.add(oldNameTextBox); newNameTextBox = new LabeledTextBox(MESSAGES.newNameLabel()); newNameTextBox.setText(oldName); newNameTextBox.getTextBox().addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { int keyCode = event.getNativeKeyCode(); if (keyCode == KeyCodes.KEY_ENTER) { handleOkClick(); } else if (keyCode == KeyCodes.KEY_ESCAPE) { hide(); } } }); contentPanel.add(newNameTextBox); Button cancelButton = new Button(MESSAGES.cancelButton()); cancelButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }); Button okButton = new Button(MESSAGES.okButton()); okButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { handleOkClick(); } }); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.add(cancelButton); buttonPanel.add(okButton); buttonPanel.setSize("100%", "24px"); contentPanel.add(buttonPanel); contentPanel.setSize("320px", "100%"); add(contentPanel); } private void handleOkClick() { String newName = newNameTextBox.getText(); // Remove leading and trailing whitespace // Replace nonempty sequences of internal spaces by underscores newName = newName.trim().replaceAll("[\\s\\xa0]+", "_"); if (newName.equals(getName())) { hide(); } else if (validate(newName)) { hide(); String oldName = getName(); changeProperty(PROPERTY_NAME_NAME, newName); getForm().fireComponentRenamed(MockComponent.this, oldName); } else { newNameTextBox.setFocus(true); newNameTextBox.selectAll(); } } private boolean validate(String newName) { // Check that it meets the formatting requirements. if (!TextValidators.isValidComponentIdentifier(newName)) { Window.alert(MESSAGES.malformedComponentNameError()); return false; } // Check that it's unique. final List<String> names = editor.getComponentNames(); if (names.contains(newName)) { Window.alert(MESSAGES.duplicateComponentNameError()); return false; } // Check that it is a variable name used in the Yail code if (TextValidators.isReservedName(newName)) { Window.alert(MESSAGES.reservedNameError()); return false; } //Check that it is not a Component type name, as this is bad for generics SimpleComponentDatabase COMPONENT_DATABASE = SimpleComponentDatabase.getInstance(); if (COMPONENT_DATABASE.isComponent(newName)) { Window.alert(MESSAGES.sameAsComponentTypeNameError()); return false; } return true; } @Override public void show() { super.show(); DeferredCommand.addCommand(new Command() { @Override public void execute() { newNameTextBox.setFocus(true); newNameTextBox.selectAll(); } }); } } /** * This class defines the dialog box for deleting a component. */ private class DeleteDialog extends DialogBox { DeleteDialog() { super(false, true); setStylePrimaryName("ode-DialogBox"); setText(MESSAGES.deleteComponentButton()); VerticalPanel contentPanel = new VerticalPanel(); contentPanel.add(new HTML(MESSAGES.reallyDeleteComponent())); Button cancelButton = new Button(MESSAGES.cancelButton()); cancelButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }); Button deleteButton = new Button(MESSAGES.deleteButton()); deleteButton.addStyleName("destructive-action"); deleteButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); MockComponent.this.delete(); } }); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.add(cancelButton); buttonPanel.add(deleteButton); buttonPanel.setSize("100%", "24px"); contentPanel.add(buttonPanel); contentPanel.setSize("320px", "100%"); add(contentPanel); } @Override protected void onPreviewNativeEvent(NativePreviewEvent event) { super.onPreviewNativeEvent(event); switch (event.getTypeInt()) { case Event.ONKEYDOWN: if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) { hide(); } else if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) { hide(); MockComponent.this.delete(); } break; } } } // Component database: information about components (including their properties and events) private final SimpleComponentDatabase COMPONENT_DATABASE; // Image bundle protected static final Images images = Ode.getImageBundle(); // Empty component children array so that we don't have to special case and test for null in // case of no children private static final List<MockComponent> NO_CHILDREN = Collections.emptyList(); // Editor of Simple form source file the component belongs to protected final SimpleEditor editor; private final String type; private ComponentDefinition componentDefinition; private Image iconImage; private final SourceStructureExplorerItem sourceStructureExplorerItem; /** * The state of the branch in the components tree corresponding to this component. */ protected boolean expanded; // Properties of the component // Expose these to individual component subclasses, which might need to // check properties fpr UI manipulation. One example is MockHorizontalArrangement protected final EditableProperties properties; private DragSourceSupport dragSourceSupport; // Component container the component belongs to (this will be null for the root component aka the // form) private MockContainer container; private MouseListenerCollection mouseListeners = new MouseListenerCollection(); private HandlerManager handlers; /** * Creates a new instance of the component. * * @param editor editor of source file the component belongs to */ MockComponent(SimpleEditor editor, String type, Image iconImage) { this.editor = editor; this.type = type; this.iconImage = iconImage; this.handlers = new HandlerManager(this); COMPONENT_DATABASE = SimpleComponentDatabase.getInstance(editor.getProjectId()); componentDefinition = COMPONENT_DATABASE.getComponentDefinition(type); sourceStructureExplorerItem = new SourceStructureExplorerItem() { @Override public void onSelected(NativeEvent source) { // are we showing the blocks editor? if so, toggle the component drawer if (Ode.getInstance().getCurrentFileEditor() instanceof YaBlocksEditor) { YaBlocksEditor blocksEditor = (YaBlocksEditor) Ode.getInstance().getCurrentFileEditor(); OdeLog.log("Showing item " + getName()); blocksEditor.showComponentBlocks(getName()); } else { select(source); } } @Override public void onStateChange(boolean open) { // The user has expanded or collapsed the branch in the components tree corresponding to // this component. Remember that by setting the expanded field so that when we re-build // the tree, we will keep the branch in the same state. expanded = open; } @Override public boolean canRename() { return !isForm(); } @Override public void rename() { if (!isForm()) { new RenameDialog(getName()).center(); } } @Override public boolean canDelete() { return !isForm(); } @Override public void delete() { if (!isForm()) { new DeleteDialog().center(); } } }; expanded = true; // Create a default property set for the component properties = new EditableProperties(true); // Add the mock component itself as a property change listener so that it can update its // visual aspects according to changes of its properties properties.addPropertyChangeListener(this); // Allow dragging this component in a drag-and-drop action if this is not the root form if (!isForm()) { dragSourceSupport = new DragSourceSupport(this); addMouseListener(dragSourceSupport); addTouchStartHandler(dragSourceSupport); addTouchMoveHandler(dragSourceSupport); addTouchEndHandler(dragSourceSupport); addTouchCancelHandler(dragSourceSupport); } } /** * Sets the components widget representation and initializes its properties. * * <p>To be called from implementing constructor. * * @param widget components visual representation in designer */ void initComponent(Widget widget) { // Widget needs to be initialized before the component itself so that the component properties // can be reflected by the widget initWidget(widget); // Capture mouse and click events in onBrowserEvent(Event) sinkEvents(Event.MOUSEEVENTS | Event.ONCLICK | Event.TOUCHEVENTS); // Add the special name property and set the tooltip String name = componentName(); setTitle(name); addProperty(PROPERTY_NAME_NAME, name, null, new TextPropertyEditor()); // TODO(user): Ensure this value is unique within the project using a list of // already used UUIDs // Set the component's UUID // The default value here can be anything except 0, because YoungAndroidProjectServce // creates forms with an initial Uuid of 0, and Properties.java doesn't encode // default values when it generates JSON for a component. addProperty(PROPERTY_NAME_UUID, "-1", null, new TextPropertyEditor()); changeProperty(PROPERTY_NAME_UUID, "" + Random.nextInt()); editor.getComponentPalettePanel().configureComponent(this); } public boolean isPropertyPersisted(String propertyName) { if (propertyName.equals(PROPERTY_NAME_NAME)) { return false; } return true; } protected boolean isPropertyVisible(String propertyName) { if (propertyName.equals(PROPERTY_NAME_NAME) || propertyName.equals(PROPERTY_NAME_UUID)) { return false; } return true; } protected boolean isPropertyforYail(String propertyName) { // By default we use the same criterion as persistance // This method can then be overriden by the invididual // component Mocks return isPropertyPersisted(propertyName); } /** * Invoked after a component is created from the palette. * * <p>Some subclasses may wish to override this method to initialize * properties of the newly created component. For example, a component with a * caption may want to initialize the caption to match the component's name. */ public void onCreateFromPalette() { } /** * Returns a unique default component name. */ private String componentName() { String compType = ComponentsTranslation.getComponentName(getType()); compType = compType.replace(" ", "_").replace("'", "_"); // Make sure it doesn't have any spaces in it return compType + getNextComponentIndex(); } /** * All components have default names for new component instantiations, * usually consisting of the type name and an index. This method * returns the next available component index for this component's type. * * We lower case the typeName and cName so we don't wind up with * components of the names 'fooComponent1' and 'FooComponent1' where * the only difference is the case of the first (or other) * letters. Ultimately the case does matter but when gensyming new * component names components whose only difference is in case will * still result in an incremented index. So if 'fooComponent1' exist * the new component will be 'FooComponent2' instead of * 'FooComponent1'. Hopefully this will be less confusing. * */ private int getNextComponentIndex() { int highIndex = 0; if (editor != null) { final String typeName = ComponentsTranslation.getComponentName(getType()) .toLowerCase() .replace(" ", "_") .replace("'", "_"); final int nameLength = typeName.length(); for (String cName : editor.getComponentNames()) { cName = cName.toLowerCase(); try { if (cName.startsWith(typeName)) { highIndex = Math.max(highIndex, Integer.parseInt(cName.substring(nameLength))); } } catch (NumberFormatException e) { continue; } } } return highIndex + 1; } /** * Adds a new property for the component. * * @param name property name * @param defaultValue default value of property * @param caption property's caption for use in the ui * @param editor property editor */ public final void addProperty(String name, String defaultValue, String caption, PropertyEditor editor) { int type = EditableProperty.TYPE_NORMAL; if (!isPropertyPersisted(name)) { type |= EditableProperty.TYPE_NONPERSISTED; } if (!isPropertyVisible(name)) { type |= EditableProperty.TYPE_INVISIBLE; } if (isPropertyforYail(name)) { type |= EditableProperty.TYPE_DOYAIL; } properties.addProperty(name, defaultValue, caption, editor, type, "", null); } /** * Adds a new property for the component. * * @param name property name * @param defaultValue default value of property * @param caption property's caption for use in the ui * @param editorType editor type for the property * @param editorArgs additional editor arguments * @param editor property editor */ public final void addProperty(String name, String defaultValue, String caption, String editorType, String[] editorArgs, PropertyEditor editor) { int type = EditableProperty.TYPE_NORMAL; if (!isPropertyPersisted(name)) { type |= EditableProperty.TYPE_NONPERSISTED; } if (!isPropertyVisible(name)) { type |= EditableProperty.TYPE_INVISIBLE; } if (isPropertyforYail(name)) { type |= EditableProperty.TYPE_DOYAIL; } properties.addProperty(name, defaultValue, caption, editor, type, editorType, editorArgs); } /** * Returns the component name. * <p> * This should not be called prior to {@link #initComponent(Widget)}. * * @return component name */ public String getName() { return properties.getPropertyValue(PROPERTY_NAME_NAME); } /** * Returns true if there is a property with the given name. * * @param name property name * @return true if the property exists */ public boolean hasProperty(String name) { return properties.getProperty(name) != null; } /** * Returns the property's value. * * @param name property name * @return property value */ public String getPropertyValue(String name) { return properties.getPropertyValue(name); } /** * Changes the value of a component property. * * @param name property name * @param value new property value */ public void changeProperty(String name, String value) { properties.changePropertyValue(name, value); } /** * Renames the component to {@code newName}. * @param newName The new name for the component. */ public void rename(String newName) { String oldName = getPropertyValue(PROPERTY_NAME_NAME); properties.changePropertyValue(PROPERTY_NAME_NAME, newName); getForm().fireComponentRenamed(this, oldName); } /** * Returns the properties set for the component. * * @return properties */ public EditableProperties getProperties() { return properties; } /** * Returns the children of this component. Note that the return value will * never be {@code null} but rather an empty array for components without * children. * <p> * The returned list should not be modified. * * @return children of the component */ public List<MockComponent> getChildren() { return NO_CHILDREN; } /** * Returns the visible children of this component that should be showing. * <p> * The returned list should not be modified. */ public final List<MockComponent> getShowingVisibleChildren() { List<MockComponent> allChildren = getChildren(); if (allChildren.size() == 0) { return NO_CHILDREN; } List<MockComponent> showingVisibleChildren = new ArrayList<MockComponent>(); for (MockComponent child : allChildren) { if (child.isVisibleComponent() && child.showComponentInDesigner()) { showingVisibleChildren.add(child); } } return showingVisibleChildren; } /** * Returns the visible children of this component that should be hidden. * <p> * The returned list should not be modified. */ public final List<MockComponent> getHiddenVisibleChildren() { List<MockComponent> allChildren = getChildren(); if (allChildren.size() == 0) { return NO_CHILDREN; } List<MockComponent> hiddenVisibleChildren = new ArrayList<MockComponent>(); for (MockComponent child : allChildren) { if (child.isVisibleComponent() && !child.showComponentInDesigner()) { hiddenVisibleChildren.add(child); } } return hiddenVisibleChildren; } /** * Returns the form containing this component. * * @return containing form */ public MockForm getForm() { return getContainer().getForm(); } public boolean isForm() { return false; } /** * Indicates whether a component has a visible representation. * <p> * The return value of this method will not change upon successive invocations. * * @return {@code true} if there is a visible representation for the * component, otherwise {@code false} */ public abstract boolean isVisibleComponent(); /** * Selects this component in the visual editor. */ public final void select(NativeEvent event) { getForm().setSelectedComponent(this, event); } /** * Invoked when the selection state of this component changes. * <p> * Implementations may override this method to perform additional * alterations to their appearance based on their new selection state. * Overriders must call {@code super.onSelectedChange(selected)} * before performing their own alterations. */ protected void onSelectedChange(boolean selected) { if (selected) { addStyleDependentName("selected"); } else { removeStyleDependentName("selected"); } getForm().fireComponentSelectionChange(this, selected); } /** * Returns whether this component is selected. */ public boolean isSelected() { return (getForm().getSelectedComponents() == this); } /** * Returns the type of the component. * The return value must not change between invocations. * <p> * This is used in the serialization format of the component. * * @return component type */ public final String getType() { return type; } /** * Returns the user-visible type name of the component. * By default this is the internal type string. * * @return component type name */ public String getVisibleTypeName() { return getType(); } /** * Returns the icon's image for the component (e.g. to be used on the component palette). * The return value must not change between invocations. * * @return icon for the component */ public final Image getIconImage() { return iconImage; } /** * Returns the unique id for the component * * @return uuid for the component */ public final String getUuid() { return getPropertyValue(PROPERTY_NAME_UUID); } /** * Sets the component container to which the component belongs. * * @param container owning component container for this component */ protected final void setContainer(MockContainer container) { this.container = container; } /** * Returns the component container to which the component belongs. * * @return owning component container for this component */ public final MockContainer getContainer() { return container; } private final Focusable nullFocusable = new Focusable() { @Override public int getTabIndex() { return 0; } @Override public void setAccessKey(char key) { } @Override public void setFocus(boolean focused) { } @Override public void setTabIndex(int index) { } }; /** * Constructs a tree item for the component which will be displayed in the * source structure explorer. * * @return tree item for this component */ protected TreeItem buildTree() { // Instantiate new tree item for this component // Note: We create a ClippedImagePrototype because we need something that can be // used to get HTML for the iconImage. AbstractImagePrototype requires // an ImageResource, which we don't necessarily have. TreeItem itemNode = new TreeItem( new HTML("<span>" + iconImage.getElement().getString() + SafeHtmlUtils.htmlEscapeAllowEntities(getName()) + "</span>")) { @Override protected Focusable getFocusable() { return nullFocusable; } }; itemNode.setUserObject(sourceStructureExplorerItem); return itemNode; } /** * If this component isn't a Form, and this component's type isn't already in typesAndIcons, * adds this component's type name as a key to typesAndIcons, mapped to the HTML string used * to display the component type's icon. Subclasses that contain components should override * this to add their own info as well as that for their contained components. * @param typesAndIcons */ public void collectTypesAndIcons(Map<String, String> typesAndIcons) { String name = getVisibleTypeName(); if (!isForm() && !typesAndIcons.containsKey(name)) { typesAndIcons.put(name, iconImage.getElement().getString()); } } /** * Returns the source structure explorer item for this component. */ public final SourceStructureExplorerItem getSourceStructureExplorerItem() { return sourceStructureExplorerItem; } /** * Returns the asset node with the given name. * * @param name asset name * @return asset node found or {@code null} */ protected ProjectNode getAssetNode(String name) { Project project = Ode.getInstance().getProjectManager().getProject(editor.getProjectId()); if (project != null) { HasAssetsFolder<YoungAndroidAssetsFolder> hasAssetsFolder = (YoungAndroidProjectNode) project.getRootNode(); for (ProjectNode asset : hasAssetsFolder.getAssetsFolder().getChildren()) { if (asset.getName().equals(name)) { return asset; } } } return null; } /** * Converts the given image property value to an image url. * Returns null if the image property value is blank or not recognized as an * asset. */ protected String convertImagePropertyValueToUrl(String text) { if (text.length() > 0) { ProjectNode asset = getAssetNode(text); if (asset != null) { return StorageUtil.getFileUrl(asset.getProjectId(), asset.getFileId()); } } return null; } // For debugging purposes only private String describeElement(com.google.gwt.dom.client.Element element) { if (element == null) { return "null"; } if (element == getElement()) { return "this"; } try { return element.getTagName(); } catch (com.google.gwt.core.client.JavaScriptException e) { // Can get here if the browser throws a permission denied error return "????"; } } /** * Invoked by GWT whenever a browser event is dispatched to this component. */ @Override public void onBrowserEvent(Event event) { if (!shouldCancel(event)) return; switch (event.getTypeInt()) { case Event.ONTOUCHSTART: case Event.ONTOUCHEND: if (isForm()) { select(event); } case Event.ONTOUCHMOVE: case Event.ONTOUCHCANCEL: cancelBrowserEvent(event); DomEvent.fireNativeEvent(event, handlers); break; case Event.ONMOUSEDOWN: case Event.ONMOUSEUP: case Event.ONMOUSEMOVE: case Event.ONMOUSEOVER: case Event.ONMOUSEOUT: cancelBrowserEvent(event); mouseListeners.fireMouseEvent(this, event); break; case Event.ONCLICK: cancelBrowserEvent(event); select(event); break; default: // Ignore unexpected events break; } } /* * Prevent browser from doing its own event handling and consume event */ private static void cancelBrowserEvent(Event event) { DOM.eventPreventDefault(event); DOM.eventCancelBubble(event, true); } // SourcesMouseEvents implementation /** * Adds the specified mouse-listener to this component's widget. * The listener will be notified of mouse events. */ @Override public final void addMouseListener(MouseListener listener) { mouseListeners.add(listener); } /** * Removes the specified mouse-listener from this component's widget. */ @Override public final void removeMouseListener(MouseListener listener) { mouseListeners.remove(listener); } @Override public final HandlerRegistration addTouchStartHandler(TouchStartHandler handler) { return handlers.addHandler(TouchStartEvent.getType(), handler); } @Override public final HandlerRegistration addTouchMoveHandler(TouchMoveHandler handler) { return handlers.addHandler(TouchMoveEvent.getType(), handler); } @Override public final HandlerRegistration addTouchEndHandler(TouchEndHandler handler) { return handlers.addHandler(TouchEndEvent.getType(), handler); } @Override public final HandlerRegistration addTouchCancelHandler(TouchCancelHandler handler) { return handlers.addHandler(TouchCancelEvent.getType(), handler); } // DragSource implementation @Override public final void onDragStart() { // no action until createDragWidget() is called } @Override public final Widget createDragWidget(int x, int y) { // TODO(user): Make sure the cloned widget does NOT appear in the // selected state, even if the original widget is in // the selected state. Widget w = new ClonedWidget(this); DragSourceSupport.configureDragWidgetToAppearWithCursorAt(w, x, y); // Hide this element, but keep taking up space in the UI. // This must be done after the drag-widget is created so that // the drag widget itself isn't hidden. setVisible(false); return w; } @Override public Widget getDragWidget() { return dragSourceSupport.getDragWidget(); } @Override public DropTarget[] getDropTargets() { final List<DropTarget> targetsWithinForm = getForm().getDropTargetsWithin(); return targetsWithinForm.toArray(new DropTarget[targetsWithinForm.size()]); } @Override public final void onDragEnd() { // Reshow this element setVisible(true); } /** * Returns the preferred width of the component if there was no layout restriction, * including the CSS border. * <p> * Callers should be aware that most components cannot calculate their * preferred size correctly until they are attached to the UI; see {@link #isAttached()}. * Unattached components are liable to return {@code 0} for any query about their preferred size. * * @return preferred width */ // TODO(user): see getPreferredHeight()! public int getPreferredWidth() { return MockComponentsUtil.getPreferredWidth(this); } /** * Returns the preferred height of the component if there was no layout restriction, * including the CSS border. * <p> * Callers should be aware that most components cannot calculate their * preferred size correctly until they are attached to the UI; see {@link #isAttached()}. * Unattached components are liable to return {@code 0} for any query about their preferred size. * * @return preferred height */ // TODO(user): The concept of preferred height/width is implemented completely wrong. // Currently we are taking the default size of GWT components. This should be // implemented to match the behavior of the Android components being mocked. public int getPreferredHeight() { return MockComponentsUtil.getPreferredHeight(this); } /* * Returns true if this component should be shown in the designer. */ private boolean showComponentInDesigner() { if (hasProperty(MockVisibleComponent.PROPERTY_NAME_VISIBLE)) { boolean visible = Boolean.parseBoolean(getPropertyValue( MockVisibleComponent.PROPERTY_NAME_VISIBLE)); // If this component's visible property is false, we need to check whether to show hidden // components. if (!visible) { YaFormEditor formEditor = (YaFormEditor) editor; return formEditor.shouldDisplayHiddenComponents(); } } return true; } int getWidthHint() { return Integer.parseInt(getPropertyValue(MockVisibleComponent.PROPERTY_NAME_WIDTH)); } int getHeightHint() { return Integer.parseInt(getPropertyValue(MockVisibleComponent.PROPERTY_NAME_HEIGHT)); } /** * Refreshes the form. * * <p>This method should be called whenever a property that affects the size * of the component is changed. It calls refreshForm(false) which permits * throttling. */ final void refreshForm() { refreshForm(false); } /* * Refresh the current form. If force is true, we bypass the * throttling code. This is needed by MockImageBase because it * *must* refresh the form before resizing loaded images. * */ final void refreshForm(boolean force) { if (isAttached()) { if (getContainer() != null || isForm()) { if (force) { getForm().doRefresh(); } else { getForm().refresh(); } } } } // PropertyChangeListener implementation @Override public void onPropertyChange(String propertyName, String newValue) { if (propertyName.equals(PROPERTY_NAME_NAME)) { setTitle(newValue); } else if (getContainer() != null || isForm()) { /* If we've already placed the component onto a Form (and therefore * into a container) then call fireComponentPropertyChanged(). * It's not really an instantiated component until its been added to * a container. If we don't make this test then we end up calling * fireComponentPropertyChanged when we start dragging the component from * the palette. We need to explicitly trigger on Form here, because forms * are not in containers. */ getForm().fireComponentPropertyChanged(this, propertyName, newValue); } } public void onRemoved() { } public void delete() { this.editor.getProjectEditor().clearLocation(getName()); getForm().select(null); // Pass true to indicate that the component is being permanently deleted. getContainer().removeComponent(this, true); // tell the component its been removed, so it can remove children's blocks onRemoved(); properties.removePropertyChangeListener(this); properties.clear(); } // Layout LayoutInfo createLayoutInfo(Map<MockComponent, LayoutInfo> layoutInfoMap) { return new LayoutInfo(layoutInfoMap, this) { @Override int calculateAutomaticWidth() { return getPreferredWidth(); } @Override int calculateAutomaticHeight() { return getPreferredHeight(); } }; } /** Upgrading MockComponent * * When extensions are upgraded, the MockComponents might need to undergo changes. * These changes can be produced inside this function. * All subclasses overriding this method must call super.upgrade()! */ public void upgrade() { //Upgrade Icon //We copy all compatible properties values List<PropertyDefinition> newProperties = COMPONENT_DATABASE.getPropertyDefinitions(this.type); List<PropertyDefinition> oldProperties = componentDefinition.getProperties(); EditableProperties currentProperties = getProperties(); //Operations List<String> toBeRemoved = new ArrayList<String>(); List<String> toBeAdded = new ArrayList<String>(); //Plan operations for (EditableProperty property : currentProperties) { boolean presentInNewProperties = false; boolean presentInOldProperties = false; String oldType = ""; String newType = ""; for (PropertyDefinition prop : newProperties) { if (prop.getName().equals(property.getName())) { presentInNewProperties = true; newType = prop.getEditorType(); } } for (PropertyDefinition prop : oldProperties) { if (prop.getName().equals(property.getName())) { presentInOldProperties = true; oldType = prop.getEditorType(); } } // deprecated property if (!presentInNewProperties && presentInOldProperties) { toBeRemoved.add(property.getName()); } // new property, less likely to happen here else if (presentInNewProperties && !presentInOldProperties) { toBeAdded.add(property.getName()); } // existing property else if (presentInNewProperties && presentInOldProperties) { if (newType != oldType) { // type change detected toBeRemoved.add(property.getName()); toBeAdded.add(property.getName()); } } } //New property for (PropertyDefinition property : newProperties) { if (!toBeAdded.contains(property.getName()) && !currentProperties.hasProperty(property.getName())) { toBeAdded.add(property.getName()); } } //Execute operations for (String prop : toBeRemoved) { currentProperties.removeProperty(prop); } for (PropertyDefinition property : newProperties) { if (toBeAdded.contains(property.getName())) { PropertyEditor propertyEditor = PropertiesUtil.createPropertyEditor(property.getEditorType(), property.getDefaultValue(), (YaFormEditor) editor, property.getEditorArgs()); addProperty(property.getName(), property.getDefaultValue(), property.getCaption(), property.getEditorType(), property.getEditorArgs(), propertyEditor); } } } /** * upgradeComplete() * Mark a MockComponent upgrade complete. * This MUST be called manually after calling upgrade()! * All subclasses overriding this method must call super.upgradeComplete()! */ public void upgradeComplete() { this.componentDefinition = COMPONENT_DATABASE.getComponentDefinition(this.type); //Update ComponentDefinition } public native void setShouldCancel(Event event, boolean cancelable)/*-{ event.shouldNotCancel = !cancelable; }-*/; public native boolean shouldCancel(Event event)/*-{ return !event.shouldNotCancel; }-*/; }
package LSB; import LittleEndian.Utils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.math3.util.Precision; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; /** * Created by bozhao on 08/02/2017. */ public class ParseLSB { private static final int headerSize = 512; private static final int subHeaderSize = 32; private static final int logSize = 64; private static int fileLength; private static int xDataStartPosition, xDataEndPosition; private static int subFileStartPosition, subFileEndPosition; private static int dataFormatCode; private static ArrayList xDataList; private static ArrayList<SubFile> subFiles; private static Header header; private static FlagBits flagBits; private static int year, month, day, hour, minute; public static void toTSV(byte[] bytes, String outputPath, int numberOfDecimals, boolean enablePeakGroup, double peakRangeStart, double peakRangeEnd) { fileLength = bytes.length; System.out.println("Input file array size: " + fileLength); header = new Header(bytes); System.out.println("Header process completed."); flagBits = new FlagBits(bytes); System.out.println("Flagbits process completed."); subFileStartPosition = headerSize; dataFormatCode = flagBits.getDataFormat(); getDataX(bytes, flagBits, numberOfDecimals); System.out.println("Global X axis process completed."); getSubFiles(bytes, header, flagBits, numberOfDecimals, enablePeakGroup, peakRangeStart, peakRangeEnd); System.out.println("Sub files process completed."); generateTSV(subFiles, header, outputPath, numberOfDecimals, enablePeakGroup); System.out.println("File export process completed."); } private static void getDataX(byte[] bytes, FlagBits flagBits, int numberOfDecimals) { switch (flagBits.getDataFormat()) { case 1: // has individual x data //System.out.println("Will be using individual x data."); break; case 2: // has global x data xDataStartPosition = headerSize; xDataEndPosition = headerSize + 4 * header.getFnpts(); //System.out.println("X data start from: " + xDataStartPosition + " and end at: " + xDataEndPosition); xDataList = new ArrayList(); int readPosition = xDataStartPosition; while (readPosition < xDataEndPosition) { //System.out.println(readPosition); xDataList.add(Precision.round(Utils.getFloat(bytes, readPosition, 4), numberOfDecimals)); readPosition += 4; } subFileStartPosition = xDataEndPosition; break; case 3: // no global or individual x data, generate one xDataList = new ArrayList(); //System.out.println("--------------------"); //System.out.println("Generating x data:"); //System.out.println("X data start from: " + header.getFfirst() + " and end at: " + header.getFlast()); for (double i = header.getFfirst(); i < header.getFlast(); i = i + (header.getFlast() - header.getFfirst()) / (header.getFnpts() - 1)) { //System.out.println(Precision.round(i, 2)); xDataList.add(Precision.round(i, numberOfDecimals)); } break; } } private static SubFile getSubFile(byte[] bytes, Header header, FlagBits flagBits, int numberOfDecimals, boolean enablePeakGroup, double peakRangeStart, double peakRangeEnd) { SubFile subFile = new SubFile(); SubFileHeader subFileHeader = new SubFileHeader(bytes); subFile.setHeader(subFileHeader); int subnpts; int subexp; int xDataStartPosition; int yDataStartPosition = 32; if (flagBits.isTxyxys()) { subnpts = subFileHeader.getSubnpts(); } else { subnpts = header.getFnpts(); } if (flagBits.isTmulti()) { subexp = subFileHeader.getSubexp(); } else { subexp = header.getFexp(); } // TODO may not need this if (subexp > 127 || subexp < -128) { subexp = 0; } if (flagBits.isTxyxys()) { // has x data in subfile, get x data xDataStartPosition = yDataStartPosition; int xDataEndPosition = xDataStartPosition + 4 * subnpts; xDataList = new ArrayList(); int readPosition = xDataStartPosition; while (readPosition < xDataEndPosition) { int xDataPoint = Utils.getInt(bytes, readPosition, 4); double xData = Math.pow(2, subexp - 32) * xDataPoint; xDataList.add(Precision.round(xData, numberOfDecimals)); readPosition += 4; } subFile.setX(xDataList); yDataStartPosition = xDataEndPosition; } ArrayList yDataList = new ArrayList(); // FloatY = (2^Exponent)*IntegerY/(2^32) -if 32-bit values // FloatY = (2^Exponent)*IntegerY/(2^16) -if 16-bit values if (subexp == -128 || !flagBits.isTsprec()) { // 32bit int yDataEndPosition = yDataStartPosition + 4 * subnpts; int readPosition = yDataStartPosition; while (readPosition < yDataEndPosition) { int yDataPoint = Utils.getInt(bytes, readPosition, 4); int yData = (int) (Math.pow(2, subexp - 32) * yDataPoint); yDataList.add(Precision.round(yData, numberOfDecimals)); readPosition += 4; } subFile.setY(yDataList); if (enablePeakGroup) { subFile.setPeakY(groupPeak(yDataList, header, peakRangeStart, peakRangeEnd)); } } else { // 16bit //System.out.println("16bit mode"); int yDataEndPosition = yDataStartPosition + 2 * subnpts; int readPosition = yDataStartPosition; while (readPosition < yDataEndPosition) { int yDataPoint = Utils.getInt(bytes, readPosition, 2); double yData = Math.pow(2, subexp - 16) * yDataPoint; yDataList.add(Precision.round(yData, numberOfDecimals)); readPosition += 2; } subFile.setY(yDataList); if (enablePeakGroup) { subFile.setPeakY(groupPeak(yDataList, header, peakRangeStart, peakRangeEnd)); } } return subFile; } private static void getSubFiles(byte[] bytes, Header header, FlagBits flagBits, int numberOfDecimals, boolean enablePeakGroup, double peakRangeStart, double peakRangeEnd) { int fnpts = header.getFnpts(); int fnsub = header.getFnsub(); subFiles = new ArrayList<SubFile>(); if (flagBits.getDataFormat() == 1 && fnpts > 0) { for (int i = 0; i < fnpts; i++) { int ssfposn = Utils.getInt(bytes, fnpts + i * 12, 4); int ssfsize = Utils.getInt(bytes, fnpts + i * 12 + 4, 4); float ssftime = Utils.getFloat(bytes, fnpts + i * 12 + 8, 4); byte[] subBytes = Arrays.copyOfRange(bytes, ssfposn, ssfposn + ssfsize); SubFile subFile = getSubFile(subBytes, header, flagBits, numberOfDecimals, enablePeakGroup, peakRangeStart, peakRangeEnd); subFiles.add(subFile); } } else { byte[] subBytes = Arrays.copyOfRange(bytes, subFileStartPosition, fileLength); int subnpts; int subfsize; for (int i = 0; i < fnsub; i++) { if (flagBits.isTxyxys()) { SubFileHeader subFileHeader = new SubFileHeader(subBytes); subnpts = subFileHeader.getSubnpts(); subfsize = 8 * subnpts + 32; } else { subnpts = fnpts; subfsize = 4 * subnpts + 32; } subFileEndPosition = subFileStartPosition + subfsize; byte[] subFileBytes = Arrays.copyOfRange(bytes, subFileStartPosition, subFileEndPosition); SubFile subFile = getSubFile(subFileBytes, header, flagBits, numberOfDecimals, enablePeakGroup, peakRangeStart, peakRangeEnd); subFiles.add(subFile); subFileStartPosition = subFileEndPosition; } } } private static void generateTSV(ArrayList<SubFile> subFiles, Header header, String outputPath, int numberOfDecimals, boolean enablePeakGroup) { ArrayList csvHeader = new ArrayList(); if (enablePeakGroup) { for (double i = header.getFfirst(); i <= header.getFlast(); i++) { csvHeader.add(Precision.round(i, numberOfDecimals)); } } else { for (double i = header.getFfirst(); i <= header.getFlast(); ) { csvHeader.add(Precision.round(i, numberOfDecimals)); i = Precision.round(i + ((header.getFlast() - header.getFfirst()) / (header.getFnpts() - 1)), numberOfDecimals); } } StringBuilder stringBuilder = new StringBuilder(); //stringBuilder.append("Comment section.").append("\n").append("\n"); stringBuilder.append(StringUtils.join(csvHeader, "\t")); stringBuilder.append("\n"); for (SubFile subFile : subFiles) { if (enablePeakGroup) { stringBuilder.append(StringUtils.join(subFile.getPeakY(), "\t")); } else { stringBuilder.append(StringUtils.join(subFile.getY(), "\t")); } stringBuilder.append("\n"); } try { System.out.println("Preparing output to: " + outputPath); PrintWriter printWriter = new PrintWriter(new FileWriter(outputPath)); printWriter.print(stringBuilder); printWriter.close(); } catch (Exception e) { e.printStackTrace(); } } private static ArrayList<Integer> groupPeak(ArrayList<Float> input, Header header, double peakRangeStart, double peakRangeEnd) { ArrayList<Integer> peak = new ArrayList(); int fnpts = header.getFnpts(); double rangeStart = header.getFfirst(); double rangeEnd = header.getFlast(); double resolution = (rangeEnd - rangeStart) / (fnpts - 1); int peakGap = (int) (1 / resolution); int dataPointsBeforePeak = (int) Math.round(peakRangeStart / resolution); int dataPointsAfterPeak = (int) Math.round(peakRangeEnd / resolution); int i = 0; while (i <= rangeEnd) { int peakCount = 0; if (i == 0) { int peakPosition = 0; for (int m = peakPosition; m <= peakPosition + rangeEnd; m++) { float yDataPoint = input.get(m); peakCount += yDataPoint; } peak.add(peakCount); } else if (i == rangeEnd) { int peakPosition = i * peakGap; for (int m = peakPosition - dataPointsBeforePeak; m <= peakPosition; m++) { float yDataPoint = input.get(m); peakCount += yDataPoint; } peak.add(peakCount); } else { int peakPosition = i * peakGap; for (int m = peakPosition - dataPointsBeforePeak; m <= peakPosition + dataPointsAfterPeak; m++) { float yDataPoint = input.get(m); peakCount += yDataPoint; } peak.add(peakCount); } i++; } return peak; } } class Header { private int ftflg; private int fversn; private int fexper; private int fexp; private int fnpts; private double ffirst; private double flast; private int fnsub; private int fxtype; private int fytype; private int fztype; private int fpost; private int fdate; private String fres; private String fsource; private int fpeakpt; private String fspare; private String fcmnt; private String fcatxt; private int flogoff; private int fmods; private int fprocs; private int flevel; private int fsampin; private float ffactor; private String fmethod; private float fzinc; private int fwplanes; private float fwinc; private int fwtype; private String freserv; public Header() { } public Header(byte[] bytes) { this.ftflg = Utils.getInt(bytes[0]); //ftflg, flagbits this.fversn = Utils.getInt(bytes[1]); // fversn, file format this.fexper = Utils.getInt(bytes[2]); //fexper, instrument technical code this.fexp = Utils.getInt(bytes[3]); // fexp, fraction scaling exponent integer, range -128 ~ 127 this.fnpts = Utils.getInt(bytes, 4, 4); // fnpts, interger number of points, or txyxys directory position this.ffirst = Utils.getDouble(bytes, 8, 8); // ffirst, floating x coordinate of first point this.flast = Utils.getDouble(bytes, 16, 8); // flast, floating x coordinate of last point this.fnsub = Utils.getInt(bytes, 24, 4); // fnsub, integer number of subfiles, set to 1 if not tmulti this.fxtype = Utils.getInt(bytes, 28, 1); // fxtype, type of X axis units, range 0 ~ 255 this.fytype = Utils.getInt(bytes, 29, 1); // fytype, type of Y axis units, range 0 ~ 255 this.fztype = Utils.getInt(bytes, 30, 1); // fztype, type of Z axis units, range 0 ~ 255 this.fpost = Utils.getInt(bytes, 31, 1); // fpost, posting disposition this.fdate = Utils.getInt(bytes, 32, 4); // fdate, date/time this.fres = Utils.getString(bytes, 36, 9); // fres, resolution description text this.fsource = Utils.getString(bytes, 45, 9); // fsource, source instrument description this.fpeakpt = Utils.getInt(bytes, 54, 2); // fpeakpt, peak point number for interferograms, 0=unknown this.fspare = Utils.getString(bytes, 56, 32); // fspare, used for array basic storage this.fcmnt = Utils.getString(bytes, 88, 130); // fcmnt, ASCII comment string this.fcatxt = Utils.getString(bytes, 218, 30); // fcatxt, axis labels for x, y, z if talabs is true in flagbits this.flogoff = Utils.getInt(bytes, 248, 4); // flogoff, offset to log block if not 0 this.fmods = Utils.getInt(bytes, 252, 4); // fmods, spectral modification flags this.fprocs = Utils.getInt(bytes[256]); // fprocs, processing code this.flevel = Utils.getInt(bytes[257]); // flevel, calibration level plus 1 this.fsampin = Utils.getInt(bytes, 258, 2); // fsampin, sub-method sample injection number, 1 = first or only this.ffactor = Utils.getFloat(bytes, 260, 4); // ffactor, floating data multiplier concentration factor, IEEE-32 this.fmethod = Utils.getString(bytes, 264, 48); // fmethod, method/program/data filename with extension comma list this.fzinc = Utils.getFloat(bytes, 312, 4); // fzinc, Z subfile increment, 0 = use 1st subnext - subfirst this.fwplanes = Utils.getInt(bytes, 316, 4); // fwplanes, number of planes for 4D with W dimension, 0 = normal this.fwinc = Utils.getFloat(bytes, 320, 4); // fwinc, W plane increment, only if fwplanes not zero this.fwtype = Utils.getInt(bytes, 324, 1); // fwtype, type of W axis units, range 0 ~ 255 this.freserv = Utils.getString(bytes, 325, 187); // freserv, reserved space, must be set to 0 } public Header(int ftflg, int fversn, int fexper, int fexp, int fnpts, double ffirst, double flast, int fnsub, int fxtype, int fytype, int fztype, int fpost, int fdate, String fres, String fsource, int fpeakpt, String fspare, String fcmnt, String fcatxt, int flogoff, int fmods, int fprocs, int flevel, int fsampin, float ffactor, String fmethod, float fzinc, int fwplanes, float fwinc, int fwtype, String freserv) { this.ftflg = ftflg; this.fversn = fversn; this.fexper = fexper; this.fexp = fexp; this.fnpts = fnpts; this.ffirst = ffirst; this.flast = flast; this.fnsub = fnsub; this.fxtype = fxtype; this.fytype = fytype; this.fztype = fztype; this.fpost = fpost; this.fdate = fdate; this.fres = fres; this.fsource = fsource; this.fpeakpt = fpeakpt; this.fspare = fspare; this.fcmnt = fcmnt; this.fcatxt = fcatxt; this.flogoff = flogoff; this.fmods = fmods; this.fprocs = fprocs; this.flevel = flevel; this.fsampin = fsampin; this.ffactor = ffactor; this.fmethod = fmethod; this.fzinc = fzinc; this.fwplanes = fwplanes; this.fwinc = fwinc; this.fwtype = fwtype; this.freserv = freserv; } public int getFtflg() { return ftflg; } public void setFtflg(int ftflg) { this.ftflg = ftflg; } public int getFversn() { return fversn; } public void setFversn(int fversn) { this.fversn = fversn; } public int getFexper() { return fexper; } public void setFexper(int fexper) { this.fexper = fexper; } public int getFexp() { return fexp; } public void setFexp(int fexp) { this.fexp = fexp; } public int getFnpts() { return fnpts; } public void setFnpts(int fnpts) { this.fnpts = fnpts; } public double getFfirst() { return ffirst; } public void setFfirst(double ffirst) { this.ffirst = ffirst; } public double getFlast() { return flast; } public void setFlast(double flast) { this.flast = flast; } public int getFnsub() { return fnsub; } public void setFnsub(int fnsub) { this.fnsub = fnsub; } public int getFxtype() { return fxtype; } public void setFxtype(int fxtype) { this.fxtype = fxtype; } public int getFytype() { return fytype; } public void setFytype(int fytype) { this.fytype = fytype; } public int getFztype() { return fztype; } public void setFztype(int fztype) { this.fztype = fztype; } public int getFpost() { return fpost; } public void setFpost(int fpost) { this.fpost = fpost; } public int getFdate() { return fdate; } public void setFdate(int fdate) { this.fdate = fdate; } public String getFres() { return fres; } public void setFres(String fres) { this.fres = fres; } public String getFsource() { return fsource; } public void setFsource(String fsource) { this.fsource = fsource; } public int getFpeakpt() { return fpeakpt; } public void setFpeakpt(int fpeakpt) { this.fpeakpt = fpeakpt; } public String getFspare() { return fspare; } public void setFspare(String fspare) { this.fspare = fspare; } public String getFcmnt() { return fcmnt; } public void setFcmnt(String fcmnt) { this.fcmnt = fcmnt; } public String getFcatxt() { return fcatxt; } public void setFcatxt(String fcatxt) { this.fcatxt = fcatxt; } public int getFlogoff() { return flogoff; } public void setFlogoff(int flogoff) { this.flogoff = flogoff; } public int getFmods() { return fmods; } public void setFmods(int fmods) { this.fmods = fmods; } public int getFprocs() { return fprocs; } public void setFprocs(int fprocs) { this.fprocs = fprocs; } public int getFlevel() { return flevel; } public void setFlevel(int flevel) { this.flevel = flevel; } public int getFsampin() { return fsampin; } public void setFsampin(int fsampin) { this.fsampin = fsampin; } public float getFfactor() { return ffactor; } public void setFfactor(float ffactor) { this.ffactor = ffactor; } public String getFmethod() { return fmethod; } public void setFmethod(String fmethod) { this.fmethod = fmethod; } public float getFzinc() { return fzinc; } public void setFzinc(float fzinc) { this.fzinc = fzinc; } public int getFwplanes() { return fwplanes; } public void setFwplanes(int fwplanes) { this.fwplanes = fwplanes; } public float getFwinc() { return fwinc; } public void setFwinc(float fwinc) { this.fwinc = fwinc; } public int getFwtype() { return fwtype; } public void setFwtype(int fwtype) { this.fwtype = fwtype; } public String getFreserv() { return freserv; } public void setFreserv(String freserv) { this.freserv = freserv; } } class FlagBits { private boolean tsprec; // true for single precision 16bit Y data, false for 32 bit private boolean tcgram; // enable fexper in older software, CGM if false private boolean tmulti; // true for more than one subfiles private boolean trandm; // if tmulti && trandm both true, then arbitrary time Z values private boolean tordrd; // if tmulti && tordrd both true, then ordered but uneven subtimes private boolean talabs; // true to use fcatxt axis lables instead of fxtype, fytype, fztype private boolean txyxys; // if tmulti && txyxys, then each subfile has own X data private boolean txvals; // true for floating x value array preceeds Y's public FlagBits() { } public FlagBits(byte[] bytes) { boolean[] flags = Utils.getFlagBits(bytes); this.tsprec = flags[0]; this.tcgram = flags[1]; this.tmulti = flags[2]; this.trandm = flags[3]; this.tordrd = flags[4]; this.talabs = flags[5]; this.txyxys = flags[6]; this.txvals = flags[7]; } public FlagBits(boolean tsprec, boolean tcgram, boolean tmulti, boolean trandm, boolean tordrd, boolean talabs, boolean txyxys, boolean txvals) { this.tsprec = tsprec; this.tcgram = tcgram; this.tmulti = tmulti; this.trandm = trandm; this.tordrd = tordrd; this.talabs = talabs; this.txyxys = txyxys; this.txvals = txvals; } public int getDataFormat() { if (this.txyxys) { return 1; // each subfile has its own x data } else if (this.txvals) { return 2; // has global x data in one subfile } else { return 3; // no x data found } } public boolean isTsprec() { return tsprec; } public void setTsprec(boolean tsprec) { this.tsprec = tsprec; } public boolean isTcgram() { return tcgram; } public void setTcgram(boolean tcgram) { this.tcgram = tcgram; } public boolean isTmulti() { return tmulti; } public void setTmulti(boolean tmulti) { this.tmulti = tmulti; } public boolean isTrandm() { return trandm; } public void setTrandm(boolean trandm) { this.trandm = trandm; } public boolean isTordrd() { return tordrd; } public void setTordrd(boolean tordrd) { this.tordrd = tordrd; } public boolean isTalabs() { return talabs; } public void setTalabs(boolean talabs) { this.talabs = talabs; } public boolean isTxyxys() { return txyxys; } public void setTxyxys(boolean txyxys) { this.txyxys = txyxys; } public boolean isTxvals() { return txvals; } public void setTxvals(boolean txvals) { this.txvals = txvals; } } class SubFile { private SubFileHeader header; private ArrayList x; private ArrayList y; private ArrayList peakX; private ArrayList peakY; public ArrayList getPeakX() { return peakX; } public void setPeakX(ArrayList peakX) { this.peakX = peakX; } public ArrayList getPeakY() { return peakY; } public void setPeakY(ArrayList peakY) { this.peakY = peakY; } public void printHeader() { header.printHeader(); } public void printX() { //System.out.println("------------------------------"); //System.out.println("Subfile X Data:"); //System.out.println(x); } public void printY() { //System.out.println("------------------------------"); //System.out.println("Subfile Y Data:"); //System.out.println(y); } public void printPeakY() { //System.out.println("------------------------------"); //System.out.println("Subfile Peak Y Data:"); //System.out.println(peakY); } public SubFileHeader getHeader() { return header; } public void setHeader(SubFileHeader header) { this.header = header; } public ArrayList getX() { return x; } public void setX(ArrayList x) { this.x = x; } public ArrayList getY() { return y; } public void setY(ArrayList y) { this.y = y; } } class SubFileHeader { private int subflgs; // subfile flagbits private int subexp; // exponent for sub file Y values private int subindx; // Integer index number of trace subfile (0=first) private float subtime; // Floating time for trace (Z axis corrdinate) private float subnext; // Floating time for next trace (May be same as beg) private float subnois; // Floating peak pick noise level if high byte nonzero private int subnpts; // Integer number of subfile points for TXYXYS type private int subscan; // Integer number of co-added scans or 0 (for collect) private float subwlevel; // Floating W axis value (if fwplanes non-zero) private String subresv; // Reserved area (must be set to zero) public SubFileHeader() { } public SubFileHeader(byte[] bytes) { this.subflgs = bytes[0]; this.subexp = bytes[1]; this.subindx = Utils.getInt(bytes, 2, 2); this.subtime = Utils.getFloat(bytes, 4, 4); this.subnext = Utils.getFloat(bytes, 8, 4); this.subnois = Utils.getFloat(bytes, 12, 4); this.subnpts = Utils.getInt(bytes, 16, 4); this.subscan = Utils.getInt(bytes, 20, 4); this.subwlevel = Utils.getInt(bytes, 24, 4); this.subresv = Utils.getString(bytes, 28, 4); } public SubFileHeader(int subflgs, int subexp, int subindx, float subtime, float subnext, float subnois, int subnpts, int subscan, float subwlevel, String subresv) { this.subflgs = subflgs; this.subexp = subexp; this.subindx = subindx; this.subtime = subtime; this.subnext = subnext; this.subnois = subnois; this.subnpts = subnpts; this.subscan = subscan; this.subwlevel = subwlevel; this.subresv = subresv; } public void printHeader() { //System.out.println("------------------------------"); //System.out.println("Subfile Header Information:"); //System.out.println("subflgs: " + subflgs); //System.out.println("subexp: " + subexp); //System.out.println("subindx: " + subexp); //System.out.println("subtime: " + subtime); //System.out.println("subnext: " + subnext); //System.out.println("subnois: " + subnois); //System.out.println("subnpts: " + subnpts); //System.out.println("subscan: " + subscan); //System.out.println("subwlevel: " + subwlevel); //System.out.println("subresv: " + subresv); } public int getSubflgs() { return subflgs; } public void setSubflgs(int subflgs) { this.subflgs = subflgs; } public int getSubexp() { return subexp; } public void setSubexp(int subexp) { this.subexp = subexp; } public int getSubindx() { return subindx; } public void setSubindx(int subindx) { this.subindx = subindx; } public float getSubtime() { return subtime; } public void setSubtime(float subtime) { this.subtime = subtime; } public float getSubnext() { return subnext; } public void setSubnext(float subnext) { this.subnext = subnext; } public float getSubnois() { return subnois; } public void setSubnois(float subnois) { this.subnois = subnois; } public int getSubnpts() { return subnpts; } public void setSubnpts(int subnpts) { this.subnpts = subnpts; } public int getSubscan() { return subscan; } public void setSubscan(int subscan) { this.subscan = subscan; } public float getSubwlevel() { return subwlevel; } public void setSubwlevel(float subwlevel) { this.subwlevel = subwlevel; } public String getSubresv() { return subresv; } public void setSubresv(String subresv) { this.subresv = subresv; } } class SubFileFlagBits { private boolean subchgd; // true if subfile changed private boolean subnopt; // true is peak table file should not be used private boolean submodf; // true if subfile modified by arithmetic public SubFileFlagBits() { } public SubFileFlagBits(byte[] bytes) { boolean[] flags = Utils.getFlagBits(bytes); this.subchgd = flags[0]; this.subnopt = flags[3]; this.submodf = flags[7]; } public SubFileFlagBits(boolean subchgd, boolean subnopt, boolean submodf) { this.subchgd = subchgd; this.subnopt = subnopt; this.submodf = submodf; } public boolean isSubchgd() { return subchgd; } public void setSubchgd(boolean subchgd) { this.subchgd = subchgd; } public boolean isSubnopt() { return subnopt; } public void setSubnopt(boolean subnopt) { this.subnopt = subnopt; } public boolean isSubmodf() { return submodf; } public void setSubmodf(boolean submodf) { this.submodf = submodf; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.rest.protocols.tcp; import org.apache.ignite.*; import org.apache.ignite.internal.client.marshaller.*; import org.apache.ignite.internal.processors.rest.client.message.*; import org.apache.ignite.internal.util.*; import org.apache.ignite.internal.util.nio.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.marshaller.*; import org.apache.ignite.marshaller.jdk.*; import org.jetbrains.annotations.*; import java.io.*; import java.nio.*; import java.nio.charset.*; import java.util.*; import static org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage.*; import static org.apache.ignite.internal.util.nio.GridNioSessionMetaKey.*; /** * Parser for extended memcache protocol. Handles parsing and encoding activity. */ public class GridTcpRestParser implements GridNioParser { /** UTF-8 charset. */ private static final Charset UTF_8 = Charset.forName("UTF-8"); /** JDK marshaller. */ private final Marshaller jdkMarshaller = new JdkMarshaller(); /** Router client flag. */ private final boolean routerClient; /** * @param routerClient Router client flag. */ public GridTcpRestParser(boolean routerClient) { this.routerClient = routerClient; } /** {@inheritDoc} */ @Nullable @Override public GridClientMessage decode(GridNioSession ses, ByteBuffer buf) throws IOException, IgniteCheckedException { ParserState state = ses.removeMeta(PARSER_STATE.ordinal()); if (state == null) state = new ParserState(); GridClientPacketType type = state.packetType(); if (type == null) { byte hdr = buf.get(buf.position()); switch (hdr) { case MEMCACHE_REQ_FLAG: state.packet(new GridMemcachedMessage()); state.packetType(GridClientPacketType.MEMCACHE); break; case IGNITE_REQ_FLAG: // Skip header. buf.get(); state.packetType(GridClientPacketType.IGNITE); break; case IGNITE_HANDSHAKE_FLAG: // Skip header. buf.get(); state.packetType(GridClientPacketType.IGNITE_HANDSHAKE); break; case IGNITE_HANDSHAKE_RES_FLAG: buf.get(); state.packetType(GridClientPacketType.IGNITE_HANDSHAKE_RES); break; default: throw new IOException("Failed to parse incoming packet (invalid packet start) [ses=" + ses + ", b=" + Integer.toHexString(hdr & 0xFF) + ']'); } } GridClientMessage res = null; switch (state.packetType()) { case MEMCACHE: res = parseMemcachePacket(ses, buf, state); break; case IGNITE_HANDSHAKE: res = parseHandshake(buf, state); break; case IGNITE_HANDSHAKE_RES: if (buf.hasRemaining()) res = new GridClientHandshakeResponse(buf.get()); break; case IGNITE: res = parseCustomPacket(ses, buf, state); break; } if (res == null) // Packet was not fully parsed yet. ses.addMeta(PARSER_STATE.ordinal(), state); return res; } /** {@inheritDoc} */ @Override public ByteBuffer encode(GridNioSession ses, Object msg0) throws IOException, IgniteCheckedException { assert msg0 != null; GridClientMessage msg = (GridClientMessage)msg0; if (msg instanceof GridMemcachedMessage) return encodeMemcache((GridMemcachedMessage)msg); else if (msg instanceof GridClientPingPacket) return ByteBuffer.wrap(GridClientPingPacket.PING_PACKET); else if (msg instanceof GridClientHandshakeRequest) { byte[] bytes = ((GridClientHandshakeRequest)msg).rawBytes(); ByteBuffer buf = ByteBuffer.allocate(bytes.length + 1); buf.put(IGNITE_HANDSHAKE_FLAG); buf.put(bytes); buf.flip(); return buf; } else if (msg instanceof GridClientHandshakeResponse) return ByteBuffer.wrap(new byte[] { IGNITE_HANDSHAKE_RES_FLAG, ((GridClientHandshakeResponse)msg).resultCode() }); else if (msg instanceof GridRouterRequest) { byte[] body = ((GridRouterRequest)msg).body(); ByteBuffer buf = ByteBuffer.allocate(45 + body.length); buf.put(IGNITE_REQ_FLAG); buf.putInt(40 + body.length); buf.putLong(msg.requestId()); buf.put(U.uuidToBytes(msg.clientId())); buf.put(U.uuidToBytes(msg.destinationId())); buf.put(body); buf.flip(); return buf; } else { GridClientMarshaller marsh = marshaller(ses); ByteBuffer res = marsh.marshal(msg, 45); ByteBuffer slice = res.slice(); slice.put(IGNITE_REQ_FLAG); slice.putInt(res.remaining() - 5); slice.putLong(msg.requestId()); slice.put(U.uuidToBytes(msg.clientId())); slice.put(U.uuidToBytes(msg.destinationId())); return res; } } /** * Parses memcache protocol message. * * @param ses Session. * @param buf Buffer containing not parsed bytes. * @param state Current parser state. * @return Parsed packet.s * @throws IOException If packet cannot be parsed. * @throws IgniteCheckedException If deserialization error occurred. */ @Nullable private GridClientMessage parseMemcachePacket(GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException, IgniteCheckedException { assert state.packetType() == GridClientPacketType.MEMCACHE; assert state.packet() != null; assert state.packet() instanceof GridMemcachedMessage; GridMemcachedMessage req = (GridMemcachedMessage)state.packet(); ByteArrayOutputStream tmp = state.buffer(); int i = state.index(); while (buf.remaining() > 0) { byte b = buf.get(); if (i == 0) req.requestFlag(b); else if (i == 1) req.operationCode(b); else if (i == 2 || i == 3) { tmp.write(b); if (i == 3) { req.keyLength(U.bytesToShort(tmp.toByteArray(), 0)); tmp.reset(); } } else if (i == 4) req.extrasLength(b); else if (i >= 8 && i <= 11) { tmp.write(b); if (i == 11) { req.totalLength(U.bytesToInt(tmp.toByteArray(), 0)); tmp.reset(); } } else if (i >= 12 && i <= 15) { tmp.write(b); if (i == 15) { req.opaque(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN && i < HDR_LEN + req.extrasLength()) { tmp.write(b); if (i == HDR_LEN + req.extrasLength() - 1) { req.extras(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN + req.extrasLength() && i < HDR_LEN + req.extrasLength() + req.keyLength()) { tmp.write(b); if (i == HDR_LEN + req.extrasLength() + req.keyLength() - 1) { req.key(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN + req.extrasLength() + req.keyLength() && i < HDR_LEN + req.totalLength()) { tmp.write(b); if (i == HDR_LEN + req.totalLength() - 1) { req.value(tmp.toByteArray()); tmp.reset(); } } if (i == HDR_LEN + req.totalLength() - 1) // Assembled the packet. return assemble(ses, req); i++; } state.index(i); return null; } /** * Parses a client handshake, checking a client version and * reading the marshaller protocol ID. * * @param buf Message bytes. * @param state Parser state. * @return True if a hint was parsed, false if still need more bytes to parse. */ @Nullable private GridClientMessage parseHandshake(ByteBuffer buf, ParserState state) { assert state.packetType() == GridClientPacketType.IGNITE_HANDSHAKE; int idx = state.index(); GridClientHandshakeRequest packet = (GridClientHandshakeRequest)state.packet(); if (packet == null) { packet = new GridClientHandshakeRequest(); state.packet(packet); } int rem = buf.remaining(); if (rem > 0) { byte[] bbuf = new byte[5]; // Buffer to read data to. int nRead = Math.min(rem, bbuf.length); // Number of bytes to read. buf.get(bbuf, 0, nRead); // Batch read from buffer. int nAvailable = nRead; // Number of available bytes. if (idx < 4) { // Need to read version bytes. int len = Math.min(nRead, 4 - idx); // Number of version bytes available in buffer. packet.putBytes(bbuf, idx, len); idx += len; state.index(idx); nAvailable -= len; } assert idx <= 4 : "Wrong idx: " + idx; assert nAvailable == 0 || nAvailable == 1 : "Wrong nav: " + nAvailable; if (idx == 4 && nAvailable > 0) return packet; } return null; // Wait for more data. } /** * Parses custom packet serialized by Ignite marshaller. * * @param ses Session. * @param buf Buffer containing not parsed bytes. * @param state Parser state. * @return Parsed message. * @throws IOException If packet parsing or deserialization failed. * @throws IgniteCheckedException If failed. */ @Nullable private GridClientMessage parseCustomPacket(GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException, IgniteCheckedException { assert state.packetType() == GridClientPacketType.IGNITE; assert state.packet() == null; ByteArrayOutputStream tmp = state.buffer(); int len = state.index(); if (buf.remaining() > 0) { if (len == 0) { // Don't know the size yet. byte[] lenBytes = statefulRead(buf, tmp, 4); if (lenBytes != null) { len = U.bytesToInt(lenBytes, 0); if (len == 0) return GridClientPingPacket.PING_MESSAGE; else if (len < 0) throw new IOException("Failed to parse incoming packet (invalid packet length) [ses=" + ses + ", len=" + len + ']'); state.index(len); } } if (len > 0 && state.header() == null) { byte[] hdrBytes = statefulRead(buf, tmp, 40); if (hdrBytes != null) { long reqId = GridClientByteUtils.bytesToLong(hdrBytes, 0); UUID clientId = GridClientByteUtils.bytesToUuid(hdrBytes, 8); UUID destId = GridClientByteUtils.bytesToUuid(hdrBytes, 24); state.header(new HeaderData(reqId, clientId, destId)); } } if (len > 0 && state.header() != null) { final int packetSize = len - 40; if (tmp.size() + buf.remaining() >= packetSize) { if (buf.remaining() > 0) { byte[] bodyBytes = new byte[packetSize - tmp.size()]; buf.get(bodyBytes); tmp.write(bodyBytes); } return parseClientMessage(ses, state); } else copyRemaining(buf, tmp); } } return null; } /** * Tries to read the specified amount of bytes using intermediate buffer. Stores * the bytes to intermediate buffer, if size requirement is not met. * * @param buf Byte buffer to read from. * @param intBuf Intermediate buffer to read bytes from and to save remaining bytes to. * @param size Number of bytes to read. * @return Resulting byte array or {@code null}, if both buffers contain less bytes * than required. In case of non-null result, the intermediate buffer is empty. * In case of {@code null} result, the input buffer is empty (read fully). * @throws IOException If IO error occurs. */ @Nullable private byte[] statefulRead(ByteBuffer buf, ByteArrayOutputStream intBuf, int size) throws IOException { if (intBuf.size() + buf.remaining() >= size) { int off = 0; byte[] bytes = new byte[size]; if (intBuf.size() > 0) { assert intBuf.size() < size; byte[] tmpBytes = intBuf.toByteArray(); System.arraycopy(tmpBytes, 0, bytes, 0, tmpBytes.length); off = intBuf.size(); intBuf.reset(); } buf.get(bytes, off, size - off); return bytes; } else { copyRemaining(buf, intBuf); return null; } } /** * Copies remaining bytes from byte buffer to output stream. * * @param src Source buffer. * @param dest Destination stream. * @throws IOException If IO error occurs. */ private void copyRemaining(ByteBuffer src, OutputStream dest) throws IOException { byte[] b = new byte[src.remaining()]; src.get(b); dest.write(b); } /** * Parses {@link GridClientMessage} from raw bytes. * * @param ses Session. * @param state Parser state. * @return A parsed client message. * @throws IOException On marshaller error. * @throws IgniteCheckedException If no marshaller was defined for the session. */ protected GridClientMessage parseClientMessage(GridNioSession ses, ParserState state) throws IOException, IgniteCheckedException { GridClientMessage msg; if (routerClient) { msg = new GridRouterResponse( state.buffer().toByteArray(), state.header().reqId(), state.header().clientId(), state.header().destinationId()); } else { GridClientMarshaller marsh = marshaller(ses); msg = marsh.unmarshal(state.buffer().toByteArray()); msg.requestId(state.header().reqId()); msg.clientId(state.header().clientId()); msg.destinationId(state.header().destinationId()); } return msg; } /** * Encodes memcache message to a raw byte array. * * @param msg Message being serialized. * @return Serialized message. * @throws IgniteCheckedException If serialization failed. */ private ByteBuffer encodeMemcache(GridMemcachedMessage msg) throws IgniteCheckedException { GridByteArrayList res = new GridByteArrayList(HDR_LEN); int keyLen = 0; int keyFlags = 0; if (msg.key() != null) { ByteArrayOutputStream rawKey = new ByteArrayOutputStream(); keyFlags = encodeObj(msg.key(), rawKey); msg.key(rawKey.toByteArray()); keyLen = rawKey.size(); } int dataLen = 0; int valFlags = 0; if (msg.value() != null) { ByteArrayOutputStream rawVal = new ByteArrayOutputStream(); valFlags = encodeObj(msg.value(), rawVal); msg.value(rawVal.toByteArray()); dataLen = rawVal.size(); } int flagsLen = 0; if (msg.addFlags())// || keyFlags > 0 || valFlags > 0) flagsLen = FLAGS_LENGTH; res.add(MEMCACHE_RES_FLAG); res.add(msg.operationCode()); // Cast is required due to packet layout. res.add((short)keyLen); // Cast is required due to packet layout. res.add((byte)flagsLen); // Data type is always 0x00. res.add((byte)0x00); res.add((short)msg.status()); res.add(keyLen + flagsLen + dataLen); res.add(msg.opaque(), 0, msg.opaque().length); // CAS, unused. res.add(0L); assert res.size() == HDR_LEN; if (flagsLen > 0) { res.add((short) keyFlags); res.add((short) valFlags); } assert msg.key() == null || msg.key() instanceof byte[]; assert msg.value() == null || msg.value() instanceof byte[]; if (keyLen > 0) res.add((byte[])msg.key(), 0, ((byte[])msg.key()).length); if (dataLen > 0) res.add((byte[])msg.value(), 0, ((byte[])msg.value()).length); return ByteBuffer.wrap(res.entireArray()); } /** * Validates incoming packet and deserializes all fields that need to be deserialized. * * @param ses Session on which packet is being parsed. * @param req Raw packet. * @return Same packet with fields deserialized. * @throws IOException If parsing failed. * @throws IgniteCheckedException If deserialization failed. */ private GridClientMessage assemble(GridNioSession ses, GridMemcachedMessage req) throws IOException, IgniteCheckedException { byte[] extras = req.extras(); // First, decode key and value, if any if (req.key() != null || req.value() != null) { short keyFlags = 0; short valFlags = 0; if (req.hasFlags()) { if (extras == null || extras.length < FLAGS_LENGTH) throw new IOException("Failed to parse incoming packet (flags required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); keyFlags = U.bytesToShort(extras, 0); valFlags = U.bytesToShort(extras, 2); } if (req.key() != null) { assert req.key() instanceof byte[]; byte[] rawKey = (byte[])req.key(); // Only values can be hessian-encoded. req.key(decodeObj(keyFlags, rawKey)); } if (req.value() != null) { assert req.value() instanceof byte[]; byte[] rawVal = (byte[])req.value(); req.value(decodeObj(valFlags, rawVal)); } } if (req.hasExpiration()) { if (extras == null || extras.length < 8) throw new IOException("Failed to parse incoming packet (expiration value required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); req.expiration(U.bytesToInt(extras, 4) & 0xFFFFFFFFL); } if (req.hasInitial()) { if (extras == null || extras.length < 16) throw new IOException("Failed to parse incoming packet (initial value required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); req.initial(U.bytesToLong(extras, 8)); } if (req.hasDelta()) { if (extras == null || extras.length < 8) throw new IOException("Failed to parse incoming packet (delta value required for command) [ses=" + ses + ", opCode=" + Integer.toHexString(req.operationCode() & 0xFF) + ']'); req.delta(U.bytesToLong(extras, 0)); } if (extras != null) { // Clients that include cache name must always include flags. int len = 4; if (req.hasExpiration()) len += 4; if (req.hasDelta()) len += 8; if (req.hasInitial()) len += 8; if (extras.length - len > 0) { byte[] cacheName = new byte[extras.length - len]; U.arrayCopy(extras, len, cacheName, 0, extras.length - len); req.cacheName(new String(cacheName, UTF_8)); } } return req; } /** * Decodes value from a given byte array to the object according to the flags given. * * @param flags Flags. * @param bytes Byte array to decode. * @return Decoded value. * @throws IgniteCheckedException If deserialization failed. */ private Object decodeObj(short flags, byte[] bytes) throws IgniteCheckedException { assert bytes != null; if ((flags & SERIALIZED_FLAG) != 0) return jdkMarshaller.unmarshal(bytes, null); int masked = flags & 0xff00; switch (masked) { case BOOLEAN_FLAG: return bytes[0] == '1'; case INT_FLAG: return U.bytesToInt(bytes, 0); case LONG_FLAG: return U.bytesToLong(bytes, 0); case DATE_FLAG: return new Date(U.bytesToLong(bytes, 0)); case BYTE_FLAG: return bytes[0]; case FLOAT_FLAG: return Float.intBitsToFloat(U.bytesToInt(bytes, 0)); case DOUBLE_FLAG: return Double.longBitsToDouble(U.bytesToLong(bytes, 0)); case BYTE_ARR_FLAG: return bytes; default: return new String(bytes, UTF_8); } } /** * Encodes given object to a byte array and returns flags that describe the type of serialized object. * * @param obj Object to serialize. * @param out Output stream to which object should be written. * @return Serialization flags. * @throws IgniteCheckedException If JDK serialization failed. */ private int encodeObj(Object obj, ByteArrayOutputStream out) throws IgniteCheckedException { int flags = 0; byte[] data = null; if (obj instanceof String) data = ((String)obj).getBytes(UTF_8); else if (obj instanceof Boolean) { data = new byte[] {(byte)((Boolean)obj ? '1' : '0')}; flags |= BOOLEAN_FLAG; } else if (obj instanceof Integer) { data = U.intToBytes((Integer) obj); flags |= INT_FLAG; } else if (obj instanceof Long) { data = U.longToBytes((Long) obj); flags |= LONG_FLAG; } else if (obj instanceof Date) { data = U.longToBytes(((Date) obj).getTime()); flags |= DATE_FLAG; } else if (obj instanceof Byte) { data = new byte[] {(Byte)obj}; flags |= BYTE_FLAG; } else if (obj instanceof Float) { data = U.intToBytes(Float.floatToIntBits((Float) obj)); flags |= FLOAT_FLAG; } else if (obj instanceof Double) { data = U.longToBytes(Double.doubleToLongBits((Double) obj)); flags |= DOUBLE_FLAG; } else if (obj instanceof byte[]) { data = (byte[])obj; flags |= BYTE_ARR_FLAG; } else { jdkMarshaller.marshal(obj, out); flags |= SERIALIZED_FLAG; } if (data != null) out.write(data, 0, data.length); return flags; } /** * Returns marshaller. * * @return Marshaller. */ protected GridClientMarshaller marshaller(GridNioSession ses) { GridClientMarshaller marsh = ses.meta(MARSHALLER.ordinal()); assert marsh != null; return marsh; } /** {@inheritDoc} */ public String toString() { return S.toString(GridTcpRestParser.class, this); } /** * Holder for parser state and temporary buffer. */ protected static class ParserState { /** Parser index. */ private int idx; /** Temporary data buffer. */ private ByteArrayOutputStream buf = new ByteArrayOutputStream(); /** Packet being assembled. */ private GridClientMessage packet; /** Packet type. */ private GridClientPacketType packetType; /** Header data. */ private HeaderData hdr; /** * @return Stored parser index. */ public int index() { return idx; } /** * @param idx Index to store. */ public void index(int idx) { this.idx = idx; } /** * @return Temporary data buffer. */ public ByteArrayOutputStream buffer() { return buf; } /** * @return Pending packet. */ @Nullable public GridClientMessage packet() { return packet; } /** * @param packet Pending packet. */ public void packet(GridClientMessage packet) { assert this.packet == null; this.packet = packet; } /** * @return Pending packet type. */ public GridClientPacketType packetType() { return packetType; } /** * @param packetType Pending packet type. */ public void packetType(GridClientPacketType packetType) { this.packetType = packetType; } /** * @return Header. */ public HeaderData header() { return hdr; } /** * @param hdr Header. */ public void header(HeaderData hdr) { this.hdr = hdr; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(ParserState.class, this); } } /** * Header. */ protected static class HeaderData { /** Request Id. */ private final long reqId; /** Request Id. */ private final UUID clientId; /** Request Id. */ private final UUID destId; /** * @param reqId Request Id. * @param clientId Client Id. * @param destId Destination Id. */ private HeaderData(long reqId, UUID clientId, UUID destId) { this.reqId = reqId; this.clientId = clientId; this.destId = destId; } /** * @return Request Id. */ public long reqId() { return reqId; } /** * @return Client Id. */ public UUID clientId() { return clientId; } /** * @return Destination Id. */ public UUID destinationId() { return destId; } } }
/* * Copyright (c) 2018. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad.user; import android.app.Activity; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.databinding.DataBindingUtil; import android.os.Build; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.design.widget.AppBarLayout.OnOffsetChangedListener; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.animation.AlphaAnimation; import android.widget.TextView; import com.freshdigitable.udonroad.AppViewModelProviderFactory; import com.freshdigitable.udonroad.FabViewModel; import com.freshdigitable.udonroad.OnSpanClickListener; import com.freshdigitable.udonroad.R; import com.freshdigitable.udonroad.TimelineContainerSwitcher; import com.freshdigitable.udonroad.TimelineContainerSwitcher.ContentType; import com.freshdigitable.udonroad.ToolbarTweetInputToggle; import com.freshdigitable.udonroad.Utils; import com.freshdigitable.udonroad.databinding.ActivityUserInfoBinding; import com.freshdigitable.udonroad.datastore.TypedCache; import com.freshdigitable.udonroad.ffab.IndicatableFFAB; import com.freshdigitable.udonroad.input.TweetInputModel; import com.freshdigitable.udonroad.input.TweetInputViewModel; import com.freshdigitable.udonroad.listitem.OnUserIconClickedListener; import com.freshdigitable.udonroad.timeline.TimelineFragment; import javax.inject.Inject; import dagger.android.AndroidInjection; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.support.HasSupportFragmentInjector; import io.reactivex.disposables.Disposable; import timber.log.Timber; import twitter4j.User; import static com.freshdigitable.udonroad.FabViewModel.Type.FAB; import static com.freshdigitable.udonroad.FabViewModel.Type.HIDE; import static com.freshdigitable.udonroad.FabViewModel.Type.TOOLBAR; import static com.freshdigitable.udonroad.input.TweetInputFragment.TYPE_QUOTE; import static com.freshdigitable.udonroad.input.TweetInputFragment.TYPE_REPLY; import static com.freshdigitable.udonroad.input.TweetInputFragment.TweetType; /** * UserInfoActivity shows information and tweets of specified user. * * Created by akihit on 2016/01/30. */ public class UserInfoActivity extends AppCompatActivity implements OnUserIconClickedListener, OnSpanClickListener, TimelineFragment.OnItemClickedListener, HasSupportFragmentInjector { public static final String TAG = UserInfoActivity.class.getSimpleName(); private UserInfoPagerFragment viewPager; private ActivityUserInfoBinding binding; @Inject TypedCache<User> userCache; private UserInfoFragment userInfoAppbarFragment; private TimelineContainerSwitcher timelineContainerSwitcher; private FabViewModel fabViewModel; private Disposable tweetUploadSubs; @Override protected void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); super.onCreate(savedInstanceState); if (savedInstanceState == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); } final View v = findViewById(R.id.userInfo_appbar_container); if (v == null) { binding = DataBindingUtil.setContentView(this, R.layout.activity_user_info); } else { binding = DataBindingUtil.findBinding(v); } setUpAppbar(); setupInfoAppbarFragment(getUserId()); fabViewModel = ViewModelProviders.of(this).get(FabViewModel.class); fabViewModel.getFabState().observe(this, type -> { if (type == FAB) { binding.ffab.transToFAB(timelineContainerSwitcher.isItemSelected() ? View.VISIBLE : View.INVISIBLE); } else if (type == TOOLBAR) { binding.ffab.transToToolbar(); } else if (type == HIDE) { if (viewPager.getSelectedItemId() > 0) { return; } binding.ffab.hide(); } else { binding.ffab.show(); } }); fabViewModel.getMenuState().observe(this, FabViewModel.createMenuStateObserver(binding.ffab)); } private void setupInfoAppbarFragment(long userId) { userInfoAppbarFragment = UserInfoFragment.create(userId); getSupportFragmentManager().beginTransaction() .replace(R.id.userInfo_appbar_container, userInfoAppbarFragment) .commit(); } private void setUpAppbar() { binding.userInfoToolbar.setTitle(""); final TextView toolbarTitle = binding.userInfoToolbarTitle; binding.userInfoAppbarLayout.addOnOffsetChangedListener(new OnOffsetChangedListener() { private boolean isTitleVisible = toolbarTitle.getVisibility() == View.VISIBLE; @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { final int totalScrollRange = appBarLayout.getTotalScrollRange(); final float percent = (float) Math.abs(verticalOffset) / (float) totalScrollRange; if (percent > 0.9) { if (!isTitleVisible) { startAnimation(toolbarTitle, View.VISIBLE); isTitleVisible = true; } } else { if (isTitleVisible) { startAnimation(toolbarTitle, View.INVISIBLE); isTitleVisible = false; } } } private void startAnimation(View v, int visibility) { AlphaAnimation animation = (visibility == View.VISIBLE) ? new AlphaAnimation(0f, 1f) : new AlphaAnimation(1f, 0f); animation.setDuration(200); animation.setFillAfter(true); v.startAnimation(animation); } }); } @Override protected void onStart() { super.onStart(); userCache.open(); final User user = userCache.find(getUserId()); UserInfoActivity.bindUserScreenName(binding.userInfoToolbarTitle, user); setSupportActionBar(binding.userInfoToolbar); setupActionMap(); } @Override protected void onResume() { super.onResume(); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1 || getWindow().getSharedElementEnterTransition() == null) { onEnterAnimationComplete(); } } @Override protected void onStop() { super.onStop(); timelineContainerSwitcher.setOnContentChangedListener(null); binding.ffab.setOnIffabItemSelectedListener(null); binding.userInfoToolbarTitle.setText(""); binding.userInfoCollapsingToolbar.setTitleEnabled(false); userCache.close(); } @Override protected void onDestroy() { super.onDestroy(); Utils.maybeDispose(tweetUploadSubs); } @Override public void onEnterAnimationComplete() { userInfoAppbarFragment.onEnterAnimationComplete(); setupTimeline(); final User user = userCache.find(getUserId()); timelineContainerSwitcher.setOnContentChangedListener((type, title) -> { if (type == ContentType.MAIN) { UserInfoActivity.bindUserScreenName(binding.userInfoToolbarTitle, user); binding.userInfoTabs.setVisibility(View.VISIBLE); } else { binding.userInfoToolbarTitle.setText(title); binding.userInfoTabs.setVisibility(View.GONE); } }); timelineContainerSwitcher.syncState(); } private void setupTimeline() { final Fragment mainFragment = getSupportFragmentManager().findFragmentByTag(TimelineContainerSwitcher.MAIN_FRAGMENT_TAG); if (mainFragment == null) { viewPager = UserInfoPagerFragment.create(getUserId()); viewPager.setTabLayout(binding.userInfoTabs); getSupportFragmentManager().beginTransaction() .replace(R.id.userInfo_timeline_container, viewPager, TimelineContainerSwitcher.MAIN_FRAGMENT_TAG) .commitNow(); } else { viewPager = (UserInfoPagerFragment) mainFragment; viewPager.setTabLayout(binding.userInfoTabs); } timelineContainerSwitcher = new TimelineContainerSwitcher(binding.userInfoTimelineContainer, viewPager, binding.ffab, factory); } public static Intent createIntent(Context context, User user) { return createIntent(context, user.getId()); } public static Intent createIntent(Context context, long userId) { Intent intent = new Intent(context, UserInfoActivity.class); intent.putExtra("user", userId); return intent; } public static void start(Context context, long userId) { final Intent intent = createIntent(context, userId); context.startActivity(intent); } public static void start(Activity activity, User user, View userIcon) { Timber.tag(TAG).d("start: "); final Intent intent = createIntent(activity.getApplicationContext(), user.getId()); final String transitionName = getUserIconTransitionName(user.getId()); ViewCompat.setTransitionName(userIcon, transitionName); ActivityCompat.startActivity(activity, intent, ActivityOptionsCompat.makeSceneTransitionAnimation(activity, userIcon, transitionName).toBundle()); } static String getUserIconTransitionName(long id) { return "user_icon_" + id; } private long getUserId() { return getIntent().getLongExtra("user", -1L); } public static void bindUserScreenName(TextView textView, User user) { final Resources resources = textView.getContext().getResources(); textView.setText( String.format(resources.getString(R.string.tweet_screenName), user.getScreenName())); } @Override public void onBackPressed() { if (toolbarTweetInputToggle != null && toolbarTweetInputToggle.isOpened()) { toolbarTweetInputToggle.cancelInput(); onTweetInputClosed(); tearDownTweetInputView(); return; } if (timelineContainerSwitcher.clearSelectedCursorIfNeeded()) { return; } if (binding.ffab.getFabMode() == IndicatableFFAB.MODE_SHEET) { binding.ffab.transToFAB(); return; } if (timelineContainerSwitcher.popBackStackTimelineContainer()) { return; } super.onBackPressed(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (toolbarTweetInputToggle != null && toolbarTweetInputToggle.onOptionMenuSelected(item)) { final int itemId = item.getItemId(); if (itemId == R.id.action_sendTweet) { onTweetInputClosed(); } else if (itemId == R.id.action_resumeTweet) { onTweetInputOpened(); } else if (itemId == android.R.id.home) { onTweetInputClosed(); tearDownTweetInputView(); } } return super.onOptionsItemSelected(item); } private int titleVisibility; private ToolbarTweetInputToggle toolbarTweetInputToggle; private void showTwitterInputView(@TweetType int type, long statusId) { if (toolbarTweetInputToggle != null) { return; } toolbarTweetInputToggle = new ToolbarTweetInputToggle(binding.userInfoToolbar); getSupportFragmentManager().beginTransaction() .hide(userInfoAppbarFragment) .add(R.id.userInfo_appbar_container, toolbarTweetInputToggle.getFragment()) .commitNow(); toolbarTweetInputToggle.expandTweetInputView(type, statusId); onTweetInputOpened(); } @Inject AppViewModelProviderFactory factory; public void onTweetInputOpened() { binding.userInfoAppbarContainer.setPadding(0, binding.userInfoToolbar.getHeight(), 0, 0); if (userInfoAppbarFragment.isVisible()) { getSupportFragmentManager().beginTransaction() .hide(userInfoAppbarFragment) .commitNow(); } titleVisibility = binding.userInfoToolbarTitle.getVisibility(); binding.userInfoToolbarTitle.setVisibility(View.GONE); binding.userInfoAppbarLayout.setExpanded(true); final TweetInputViewModel tweetInputViewModel = ViewModelProviders.of(this, factory).get(TweetInputViewModel.class); tweetUploadSubs = tweetInputViewModel.observeModel() .map(TweetInputModel::getState) .filter(state -> state == TweetInputModel.State.SENT) .subscribe(s -> tearDownTweetInputView()); } public void onTweetInputClosed() { if (toolbarTweetInputToggle == null) { return; } binding.userInfoAppbarContainer.setPadding(0, 0, 0, 0); binding.userInfoAppbarLayout.setExpanded(titleVisibility != View.VISIBLE); binding.userInfoToolbarTitle.setVisibility(titleVisibility); getSupportFragmentManager().beginTransaction() .show(userInfoAppbarFragment) .commit(); } private void tearDownTweetInputView() { getSupportFragmentManager().beginTransaction() .remove(toolbarTweetInputToggle.getFragment()) .commit(); toolbarTweetInputToggle = null; } private void setupActionMap() { binding.ffab.setOnIffabItemSelectedListener(item -> { final int itemId = item.getItemId(); final long selectedTweetId = timelineContainerSwitcher.getSelectedTweetId(); if (itemId == R.id.iffabMenu_main_reply) { showTwitterInputView(TYPE_REPLY, selectedTweetId); } else if (itemId == R.id.iffabMenu_main_quote) { showTwitterInputView(TYPE_QUOTE, selectedTweetId); } else if (itemId == R.id.iffabMenu_main_detail) { timelineContainerSwitcher.showStatusDetail(selectedTweetId); } else if (itemId == R.id.iffabMenu_main_conv) { timelineContainerSwitcher.showConversation(selectedTweetId); } fabViewModel.onMenuItemSelected(item); }); } @Override public void onUserIconClicked(View view, User user) { if (user.getId() == getUserId()) { return; } start(this, user, view); } @Override public void onSpanClicked(View v, SpanItem item) { if (item.getType() == SpanItem.TYPE_HASHTAG) { timelineContainerSwitcher.showSearchResult(item.getQuery()); } } @Override public void onItemClicked(ContentType type, long id, String query) { if (type == ContentType.LISTS) { timelineContainerSwitcher.showListTimeline(id, query); } } @Inject DispatchingAndroidInjector<Fragment> androidInjector; @Override public AndroidInjector<Fragment> supportFragmentInjector() { return androidInjector; } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.action.admin.cluster.health; import org.elasticsearch.Version; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.master.MasterNodeReadRequest; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.Priority; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.core.TimeValue; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; public class ClusterHealthRequest extends MasterNodeReadRequest<ClusterHealthRequest> implements IndicesRequest.Replaceable { private String[] indices; private IndicesOptions indicesOptions = IndicesOptions.lenientExpandHidden(); private TimeValue timeout = new TimeValue(30, TimeUnit.SECONDS); private ClusterHealthStatus waitForStatus; private boolean waitForNoRelocatingShards = false; private boolean waitForNoInitializingShards = false; private ActiveShardCount waitForActiveShards = ActiveShardCount.NONE; private String waitForNodes = ""; private Priority waitForEvents = null; /** * Only used by the high-level REST Client. Controls the details level of the health information returned. * The default value is 'cluster'. */ private Level level = Level.CLUSTER; public ClusterHealthRequest() { } public ClusterHealthRequest(String... indices) { this.indices = indices; } public ClusterHealthRequest(StreamInput in) throws IOException { super(in); indices = in.readStringArray(); timeout = in.readTimeValue(); if (in.readBoolean()) { waitForStatus = ClusterHealthStatus.readFrom(in); } waitForNoRelocatingShards = in.readBoolean(); waitForActiveShards = ActiveShardCount.readFrom(in); waitForNodes = in.readString(); if (in.readBoolean()) { waitForEvents = Priority.readFrom(in); } waitForNoInitializingShards = in.readBoolean(); if (in.getVersion().onOrAfter(Version.V_7_2_0)) { indicesOptions = IndicesOptions.readIndicesOptions(in); } else { indicesOptions = IndicesOptions.lenientExpandOpen(); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); if (indices == null) { out.writeVInt(0); } else { out.writeStringArray(indices); } out.writeTimeValue(timeout); if (waitForStatus == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeByte(waitForStatus.value()); } out.writeBoolean(waitForNoRelocatingShards); waitForActiveShards.writeTo(out); out.writeString(waitForNodes); if (waitForEvents == null) { out.writeBoolean(false); } else { out.writeBoolean(true); Priority.writeTo(waitForEvents, out); } out.writeBoolean(waitForNoInitializingShards); if (out.getVersion().onOrAfter(Version.V_7_2_0)) { indicesOptions.writeIndicesOptions(out); } } @Override public String[] indices() { return indices; } @Override public ClusterHealthRequest indices(String... indices) { this.indices = indices; return this; } @Override public IndicesOptions indicesOptions() { return indicesOptions; } public ClusterHealthRequest indicesOptions(final IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } @Override public boolean includeDataStreams() { return true; } public TimeValue timeout() { return timeout; } public ClusterHealthRequest timeout(TimeValue timeout) { this.timeout = timeout; if (masterNodeTimeout == DEFAULT_MASTER_NODE_TIMEOUT) { masterNodeTimeout = timeout; } return this; } public ClusterHealthRequest timeout(String timeout) { return this.timeout(TimeValue.parseTimeValue(timeout, null, getClass().getSimpleName() + ".timeout")); } public ClusterHealthStatus waitForStatus() { return waitForStatus; } public ClusterHealthRequest waitForStatus(ClusterHealthStatus waitForStatus) { this.waitForStatus = waitForStatus; return this; } public ClusterHealthRequest waitForGreenStatus() { return waitForStatus(ClusterHealthStatus.GREEN); } public ClusterHealthRequest waitForYellowStatus() { return waitForStatus(ClusterHealthStatus.YELLOW); } public boolean waitForNoRelocatingShards() { return waitForNoRelocatingShards; } /** * Sets whether the request should wait for there to be no relocating shards before * retrieving the cluster health status. Defaults to {@code false}, meaning the * operation does not wait on there being no more relocating shards. Set to <code>true</code> * to wait until the number of relocating shards in the cluster is 0. */ public ClusterHealthRequest waitForNoRelocatingShards(boolean waitForNoRelocatingShards) { this.waitForNoRelocatingShards = waitForNoRelocatingShards; return this; } public boolean waitForNoInitializingShards() { return waitForNoInitializingShards; } /** * Sets whether the request should wait for there to be no initializing shards before * retrieving the cluster health status. Defaults to {@code false}, meaning the * operation does not wait on there being no more initializing shards. Set to <code>true</code> * to wait until the number of initializing shards in the cluster is 0. */ public ClusterHealthRequest waitForNoInitializingShards(boolean waitForNoInitializingShards) { this.waitForNoInitializingShards = waitForNoInitializingShards; return this; } public ActiveShardCount waitForActiveShards() { return waitForActiveShards; } /** * Sets the number of shard copies that must be active across all indices before getting the * health status. Defaults to {@link ActiveShardCount#NONE}, meaning we don't wait on any active shards. * Set this value to {@link ActiveShardCount#ALL} to wait for all shards (primary and * all replicas) to be active across all indices in the cluster. Otherwise, use * {@link ActiveShardCount#from(int)} to set this value to any non-negative integer, up to the * total number of shard copies to wait for. */ public ClusterHealthRequest waitForActiveShards(ActiveShardCount waitForActiveShards) { if (waitForActiveShards.equals(ActiveShardCount.DEFAULT)) { // the default for cluster health request is 0, not 1 this.waitForActiveShards = ActiveShardCount.NONE; } else { this.waitForActiveShards = waitForActiveShards; } return this; } /** * A shortcut for {@link #waitForActiveShards(ActiveShardCount)} where the numerical * shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)} * to get the ActiveShardCount. */ public ClusterHealthRequest waitForActiveShards(final int waitForActiveShards) { return waitForActiveShards(ActiveShardCount.from(waitForActiveShards)); } public String waitForNodes() { return waitForNodes; } /** * Waits for N number of nodes. Use "12" for exact mapping, "&gt;12" and "&lt;12" for range. */ public ClusterHealthRequest waitForNodes(String waitForNodes) { this.waitForNodes = waitForNodes; return this; } public ClusterHealthRequest waitForEvents(Priority waitForEvents) { this.waitForEvents = waitForEvents; return this; } public Priority waitForEvents() { return this.waitForEvents; } /** * Set the level of detail for the health information to be returned. * Only used by the high-level REST Client. */ public void level(Level level) { this.level = Objects.requireNonNull(level, "level must not be null"); } /** * Get the level of detail for the health information to be returned. * Only used by the high-level REST Client. */ public Level level() { return level; } @Override public ActionRequestValidationException validate() { return null; } public enum Level { CLUSTER, INDICES, SHARDS } }
package it.unibz.krdb.obda.owlrefplatform.questdb; /* * #%L * ontop-quest-db * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * 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 it.unibz.krdb.obda.exception.InvalidMappingException; import it.unibz.krdb.obda.io.ModelIOManager; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.OBDADataSource; import it.unibz.krdb.obda.model.OBDAException; import it.unibz.krdb.obda.model.OBDAModel; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.obda.model.impl.RDBMSourceParameterConstants; import it.unibz.krdb.obda.ontology.Ontology; import it.unibz.krdb.obda.ontology.impl.OntologyFactoryImpl; import it.unibz.krdb.obda.owlapi3.OWLAPI3TranslatorUtility; import it.unibz.krdb.obda.owlapi3.directmapping.DirectMappingEngine; import it.unibz.krdb.obda.owlrefplatform.core.Quest; import it.unibz.krdb.obda.owlrefplatform.core.QuestConnection; import it.unibz.krdb.obda.owlrefplatform.core.QuestConstants; import it.unibz.krdb.obda.owlrefplatform.core.QuestPreferences; import it.unibz.krdb.obda.owlrefplatform.core.abox.RDBMSSIRepositoryManager; import it.unibz.krdb.obda.r2rml.R2RMLReader; import it.unibz.krdb.sql.DBMetadata; import it.unibz.krdb.sql.ImplicitDBConstraints; import org.openrdf.model.Model; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyIRIMapper; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.util.AutoIRIMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Properties; import java.util.Set; /*** * A bean that holds all the data about a store, generates a store folder and * maintains this data. */ public class QuestDBVirtualStore extends QuestDBAbstractStore { private static final long serialVersionUID = 2495624993519521937L; private static Logger log = LoggerFactory.getLogger(QuestDBVirtualStore.class); private static OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); protected transient OWLOntologyManager man = OWLManager.createOWLOntologyManager(); private QuestConnection questConn; private Quest questInstance; private boolean isinitalized = false; public QuestDBVirtualStore(String name, URI obdaURI) throws Exception { this(name, null, obdaURI, null); } public QuestDBVirtualStore(String name, URI obdaURI, QuestPreferences config) throws Exception { this(name, null, obdaURI, config); } public QuestDBVirtualStore(String name, URI tboxFile, URI obdaURI) throws Exception { this(name, tboxFile, obdaURI, null); } public QuestDBVirtualStore(String name, QuestPreferences pref) throws Exception { // direct mapping : no tbox, no obda file, repo in-mem h2 this(name, (URI)null, null, pref); } public QuestDBVirtualStore(String name, URI tboxFile, URI obdaUri, QuestPreferences config) throws Exception { this(name, tboxFile, obdaUri, config, null); } /** * The method generates the OBDAModel from an * obda or ttl (r2rml) file * @param obdaURI - the file URI * @return the generated OBDAModel * @throws IOException * @throws InvalidMappingException */ public OBDAModel getObdaModel(URI obdaURI) throws IOException, InvalidMappingException { //create empty model OBDAModel obdaModel = fac.getOBDAModel(); // System.out.println(obdaURI.toString()); if (obdaURI.toString().endsWith(".obda")) { //read obda file ModelIOManager modelIO = new ModelIOManager(obdaModel); modelIO.load(new File(obdaURI)); } else if (obdaURI.toString().endsWith(".ttl")) { //read R2RML file R2RMLReader reader = null; try { reader = new R2RMLReader(new File(obdaURI)); obdaModel = reader.readModel(obdaURI); } catch (Exception e) { e.printStackTrace(); } } return obdaModel; } /** * The constructor to setup Quest virtual store given * an owl file URI and an obda or R2rml mapping file URI * @param name - the name of the triple store * @param tboxFile - the owl file URI * @param obdaUri - the obda or ttl file URI * @param config - QuestPreferences * @param userConstraints - User-supplied database constraints (or null) * @throws Exception */ public QuestDBVirtualStore(String name, URI tboxFile, URI obdaUri, QuestPreferences config, ImplicitDBConstraints userConstraints) throws Exception { super(name); //obtain the model OBDAModel obdaModel; if (obdaUri == null) { log.debug("No mappings where given, mappings will be automatically generated."); //obtain model from direct mapping RDB2RDF method obdaModel = getOBDAModelDM(); } else { //obtain model from file obdaModel = getObdaModel(obdaUri); } //set config preferences values if (config == null) { config = new QuestPreferences(); } //we are working in virtual mode config.setProperty(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL); //obtain the ontology Ontology tbox; if (tboxFile != null) { //read owl file OWLOntology owlontology = getOntologyFromFile(tboxFile); //get transformation from owlontology into ontology tbox = getOntologyFromOWLOntology(owlontology); } else { // create empty ontology //owlontology = man.createOntology(); tbox = OntologyFactoryImpl.getInstance().createOntology(); if (obdaModel.getSources().size() == 0) obdaModel.addSource(getMemOBDADataSource("MemH2")); } obdaModel.declareAll(tbox.getVocabulary()); // OBDAModelSynchronizer.declarePredicates(owlontology, obdaModel); //set up Quest setupQuest(tbox, obdaModel, null, config); } /** * Constructor to start Quest given an OWL ontology and an RDF Graph * representing R2RML mappings * @param name - the name of the triple store * @param tbox - the OWLOntology * @param mappings - the RDF Graph (Sesame API) * @param pref - QuestPreferences * @throws Exception */ public QuestDBVirtualStore(String name, OWLOntology tbox, Model mappings, DBMetadata metadata, QuestPreferences config) throws Exception { //call super constructor -> QuestDBAbstractStore super(name); //obtain ontology Ontology ontology = getOntologyFromOWLOntology(tbox); //obtain datasource OBDADataSource source = getDataSourceFromConfig(config); //obtain obdaModel R2RMLReader reader = new R2RMLReader(mappings); OBDAModel obdaModel = reader.readModel(source.getSourceID()); //add data source to model obdaModel.addSource(source); //OBDAModelSynchronizer.declarePredicates(tbox, obdaModel); obdaModel.declareAll(ontology.getVocabulary()); //setup Quest setupQuest(ontology, obdaModel, metadata, config); } private OBDADataSource getDataSourceFromConfig(QuestPreferences config) { String id = config.get(QuestPreferences.DBNAME).toString(); String url = config.get(QuestPreferences.JDBC_URL).toString(); String username = config.get(QuestPreferences.DBUSER).toString(); String password = config.get(QuestPreferences.DBPASSWORD).toString(); String driver = config.get(QuestPreferences.JDBC_DRIVER).toString(); OBDADataSource source = OBDADataFactoryImpl.getInstance().getDataSource(URI.create(id)); source.setParameter(RDBMSourceParameterConstants.DATABASE_URL, url); source.setParameter(RDBMSourceParameterConstants.DATABASE_USERNAME, username); source.setParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD, password); source.setParameter(RDBMSourceParameterConstants.DATABASE_DRIVER, driver); return source; } /** * Given a URI of an owl file returns the * translated OWLOntology object * @param tboxFile - the URI of the file * @return the translated OWLOntology * @throws Exception */ private OWLOntology getOntologyFromFile(URI tboxFile) throws Exception{ //get owl ontology from file OWLOntologyIRIMapper iriMapper = new AutoIRIMapper(new File(tboxFile).getParentFile(), false); man.addIRIMapper(iriMapper); OWLOntology owlontology = man.loadOntologyFromOntologyDocument(new File(tboxFile)); return owlontology; } /** * Given an OWL ontology returns the translated Ontology * of its closure * @param owlontology * @return the translated Ontology * @throws Exception */ private Ontology getOntologyFromOWLOntology(OWLOntology owlontology) throws Exception{ //compute closure first (owlontology might contain include other source declarations) Set<OWLOntology> clousure = owlontology.getOWLOntologyManager().getImportsClosure(owlontology); return OWLAPI3TranslatorUtility.mergeTranslateOntologies(clousure); } private void setupQuest(Ontology tbox, OBDAModel obdaModel, DBMetadata metadata, QuestPreferences pref) throws Exception { //start Quest with the given ontology and model and preferences if (metadata == null) { //start up quest by obtaining metadata from given data source questInstance = new Quest(tbox, obdaModel, pref); } else { //start up quest with given metadata questInstance = new Quest(tbox, obdaModel, metadata, pref); } } /** * Sets the implicit db constraints, i.e. primary and foreign keys not in the database * Must be called before the call to initialize * * @param userConstraints */ public void setImplicitDBConstraints(ImplicitDBConstraints userConstraints){ if(userConstraints == null) throw new NullPointerException(); if(this.isinitalized) throw new Error("Implicit DB Constraints must be given before the call to initialize to have effect. See https://github.com/ontop/ontop/wiki/Implicit-database-constraints and https://github.com/ontop/ontop/wiki/API-change-in-SesameVirtualRepo-and-QuestDBVirtualStore"); questInstance.setImplicitDBConstraints(userConstraints); } /** * Create an in-memory H2 database data source * @param name - the datasource name * @return the created OBDADataSource */ private static OBDADataSource getMemOBDADataSource(String name) { OBDADataSource obdaSource = OBDADataFactoryImpl.getInstance().getDataSource(URI.create(name)); String driver = "org.h2.Driver"; String url = "jdbc:h2:mem:questrepository"; String username = "sa"; String password = ""; obdaSource = fac.getDataSource(URI.create("http://www.obda.org/ABOXDUMP" + System.currentTimeMillis())); obdaSource.setParameter(RDBMSourceParameterConstants.DATABASE_DRIVER, driver); obdaSource.setParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD, password); obdaSource.setParameter(RDBMSourceParameterConstants.DATABASE_URL, url); obdaSource.setParameter(RDBMSourceParameterConstants.DATABASE_USERNAME, username); obdaSource.setParameter(RDBMSourceParameterConstants.IS_IN_MEMORY, "true"); obdaSource.setParameter(RDBMSourceParameterConstants.USE_DATASOURCE_FOR_ABOXDUMP, "true"); return (obdaSource); } /** * Generate an OBDAModel from Direct Mapping (Bootstrapping) * @return the OBDAModel */ private OBDAModel getOBDAModelDM() { DirectMappingEngine dm = new DirectMappingEngine("http://example.org/base", 0); try { OBDAModel model = dm.extractMappings(getMemOBDADataSource("H2m")); return model; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Must be called once after the constructor call and before any queries are run, that is, * before the call to getQuestConnection. * * Calls {@link Quest.setupRepository()} * @throws Exception */ public void initialize() throws Exception { if(this.isinitalized){ log.warn("Double initialization of QuestDBVirtualStore"); } else { this.isinitalized = true; questInstance.setupRepository(); } } /** * Get a Quest connection from the Quest instance * @return the QuestConnection */ public QuestConnection getQuestConnection() { if(!this.isinitalized) throw new Error("The QuestDBVirtualStore must be initialized before getQuestConnection can be run. See https://github.com/ontop/ontop/wiki/API-change-in-SesameVirtualRepo-and-QuestDBVirtualStore"); try { // System.out.println("getquestconn.."); questConn = questInstance.getConnection(); } catch (OBDAException e) { e.printStackTrace(); } return questConn; } /** * Shut down Quest and its connections. */ public void close() { questInstance.close(); } @Override public Properties getPreferences() { return questInstance.getPreferences(); } @Override public RDBMSSIRepositoryManager getSemanticIndexRepository() { return questInstance.getSemanticIndexRepository(); } }
package com.ociweb.iot.grove.oled.oled2; import com.ociweb.gl.api.transducer.ShutdownListenerTransducer; import com.ociweb.gl.api.transducer.StartupListenerTransducer; import com.ociweb.iot.grove.oled.BinaryOLED; import com.ociweb.iot.maker.FogCommandChannel; import com.ociweb.iot.maker.IODeviceTransducer; import com.ociweb.iot.maker.image.*; import com.ociweb.pronghorn.iot.schema.I2CCommandSchema; import com.ociweb.pronghorn.pipe.DataOutputBlobWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OLED96x96Transducer implements IODeviceTransducer, StartupListenerTransducer, ShutdownListenerTransducer, FogBmpDisplayable { private Logger logger = LoggerFactory.getLogger((BinaryOLED.class)); private final FogCommandChannel ch; private final int i2cCommandBatchLimit = 64; // Max commands before we must call flush (batch is i2c bus atomic, and must fit entirely on channel) private final int i2cCommandMaxSize = 64; // Max single i2C command size in bytes (i.e. address, register, payload) // TODO another constant for data payload chunks. This effects i2cCommandMaxSize. private static final int DISPLAY_OFF = 0xAE; private static final int REMAP_SGMT = 0xA0; private static final int SET_EXT_VPP = 0xAD; // Initialization public OLED96x96Transducer(FogCommandChannel ch) { this.ch = ch; // TODO: commandCountCapacity cannot be just i2cCommandBatchLimit, why? this.ch.ensureI2CWriting(i2cCommandMaxSize, i2cCommandMaxSize); } @Override public void startup() { if (!init()) { logger.error("Failed to init."); } if (!setOrientation(OLEDOrientation.horizontal)) { logger.error("Failed to set horizontal."); } if (!turnScreenOn()) { logger.error("Failed to turn screen on."); } } private boolean init() { if (tryBeginI2CBatch(1)) { final int SET_D_CLOCK = 0xD5; final int SET_ROW_ADDRESS = 0x20; final int SET_CONTRAST = 0x81; final int NORMAL_DISPLAY = 0xA6; final int SET_COMMON_SCAN_DIR = 0xC0; final int SET_PHASE_LENGTH = 0xD9; final int SET_VCOMH_VOLTAGE = 0xDB; final int ENTIRE_DISPLAY_ON = 0xA4; DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, DISPLAY_OFF); queueInstruction(writer, SET_D_CLOCK); queueInstruction(writer, 0x50); queueInstruction(writer, SET_ROW_ADDRESS); queueInstruction(writer, SET_CONTRAST); queueInstruction(writer, 0x70); queueInstruction(writer, REMAP_SGMT); queueInstruction(writer, ENTIRE_DISPLAY_ON); queueInstruction(writer, NORMAL_DISPLAY); queueInstruction(writer, SET_EXT_VPP); queueInstruction(writer, 0x80); queueInstruction(writer, SET_COMMON_SCAN_DIR); queueInstruction(writer, SET_PHASE_LENGTH); queueInstruction(writer, 0x1F); queueInstruction(writer, SET_VCOMH_VOLTAGE); queueInstruction(writer, 0x20); endI2CCommand(writer); endI2CBatch(); return true; } return false; } private boolean turnScreenOn() { final int DISPLAY_ON = 0xAF; if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, DISPLAY_ON); endI2CCommand(writer); endI2CBatch(); return true; } return false; } @Override public boolean acceptShutdown() { if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, DISPLAY_OFF); queueInstruction(writer, SET_EXT_VPP); queueInstruction(writer, 0x00); endI2CCommand(writer); endI2CBatch(); } return true; } // Public API public boolean setContrast(int contrast) { final int SET_CONTRAST = 0x81; if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, SET_CONTRAST); queueInstruction(writer, contrast); endI2CCommand(writer); endI2CBatch(); return true; } return false; } // Does not rotate - just flips one axis public boolean setOrientation(OLEDOrientation orientation) { if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, REMAP_SGMT); queueInstruction(writer, orientation.COMMAND); endI2CCommand(writer); endI2CBatch(); return true; } return false; } public boolean setScrollActivated(boolean activated) { final int SET_ACTIVATED = activated ? 0x2F : 0x2E; if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, SET_ACTIVATED); endI2CCommand(writer); endI2CBatch(); return true; } return false; } public boolean setHorizontalScrollProperties(OLEDScrollDirection direction, int startRow, int endRow, int startColumn, int endColumn, OLEDScrollSpeed speed) { if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, direction.COMMAND); queueInstruction(writer, 0x00); queueInstruction(writer, startRow); queueInstruction(writer, speed.COMMAND); queueInstruction(writer, endRow); queueInstruction(writer, startColumn+8); queueInstruction(writer, endColumn+8); queueInstruction(writer, 0x00); endI2CCommand(writer); endI2CBatch(); return true; } return false; } public boolean setPresentation(OLEDScreenPresentation presentation) { if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, presentation.COMMAND); endI2CCommand(writer); endI2CBatch(); return true; } return false; } public boolean clearDisplay() { setOrientation(OLEDOrientation.horizontal); //if (tryBeginI2CBatch(1)) { //DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); for (int i = 0; i < 16; i++) { //16 Pages writeElement(0xb0 + i, true); writeElement(0x00, true); writeElement(0x10, true); //queueInstruction(writer, 0xb0 + i); //queueInstruction(writer, 0x00); //queueInstruction(writer, 0x10); for (int j = 0; j < 128; j++) { //128 Columns //queueData(writer, 0x00); writeElement(0x00, false); } } //endI2CCommand(writer); //endI2CBatch(); //} //else { // return false; //} return true; } // FogBitmap @Override public FogBitmapLayout newBmpLayout() { FogBitmapLayout bmpLayout = new FogBitmapLayout(FogColorSpace.gray); bmpLayout.setComponentDepth((byte) 4); bmpLayout.setWidth(96); bmpLayout.setHeight(96); return bmpLayout; } @Override public FogBitmap newEmptyBmp() { return new FogBitmap(newBmpLayout()); } @Override public boolean display(FogBitmap bmp) { return clearDisplay(); } // Commands private boolean writeElement(int data, boolean isInstruction) { if (tryBeginI2CBatch(1)) { DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); if (isInstruction) { queueInstruction(writer, data); } else { queueData(writer, data); } endI2CCommand(writer); endI2CBatch(); } return true; } private boolean tryBeginI2CBatch(int commandCount) { if (!ch.i2cIsReady(commandCount)) { logger.trace("I2C is not ready for batch of {} commands.", commandCount); return false; } return true; } private DataOutputBlobWriter<I2CCommandSchema> beginI2CCommand() { final int i2cAddress = 0x3c; return ch.i2cCommandOpen(i2cAddress); } private void queueInstruction(DataOutputBlobWriter<I2CCommandSchema> writer, int data) { writer.write(OLEDMode.instruction.COMMAND); writer.write(data & 0xFF); } private void queueData(DataOutputBlobWriter<I2CCommandSchema> writer, int data) { writer.write(OLEDMode.data.COMMAND); writer.write(data & 0xFF); } private void endI2CCommand(DataOutputBlobWriter<I2CCommandSchema> writer) { int bytesWritten = ch.i2cCommandClose(writer); if (bytesWritten > i2cCommandMaxSize) { throw new UnsupportedOperationException("Write too large i2C command. i2cCommandMaxSize is too small or too much was written."); } //logger.warn("Batch Size: {}<={}", bytesWritten, i2cCommandMaxSize); } private void endI2CBatch() { ch.i2cFlushBatch(); } // Test private boolean testScreen2() { System.out.print("testScreen1\n"); setOrientation(OLEDOrientation.horizontal); final int SET_ROW_BASE_BYTE = 0xB0; int i = 0; for (int x = 0; x < 96; x++) { for (int y = 0; y < 96; y++) { if (((i + i2cCommandBatchLimit) % i2cCommandBatchLimit) == 0) { if (!tryBeginI2CBatch(i2cCommandBatchLimit)) { return false; } } int tmp = 0x00; DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); //queueInstruction(writer, SET_ROW_BASE_BYTE + Row); //queueInstruction(writer, column_l); //queueInstruction(writer, column_h); queueData(writer, tmp); endI2CCommand(writer); if (((i + i2cCommandBatchLimit) % i2cCommandBatchLimit) == i2cCommandBatchLimit - 1) { endI2CBatch(); } i++; } } endI2CBatch(); return true; } private boolean testScreen() { System.out.print("testScreen2\n"); setOrientation(OLEDOrientation.horizontal); final int SET_ROW_BASE_BYTE = 0xB0; int Row = 0; int column_l = 0x00; int column_h = 0x11; // 17 for(int i=0;i<(96*96/8);i++) //1152 { if (((i + i2cCommandBatchLimit) % i2cCommandBatchLimit) == 0) { if (!tryBeginI2CBatch(i2cCommandBatchLimit)) { return false; } } int tmp = 0x00; for(int b = 0; b < 8; b++) { int bits = SeeedLogo[i]; tmp |= ( ( bits >> ( 7 - b ) ) & 0x01 ) << b; } //tmp = 0x0F; //tmp = 0xF0; //tmp = 0x00; //tmp = 0xFF; //tmp = 0x88; DataOutputBlobWriter<I2CCommandSchema> writer = beginI2CCommand(); queueInstruction(writer, SET_ROW_BASE_BYTE + Row); queueInstruction(writer, column_l); queueInstruction(writer, column_h); queueData(writer, tmp); endI2CCommand(writer); Row++; if(Row >= 12){ Row = 0; column_l++; //logger.info("End Row {}", column_l); if(column_l >= 16){ column_l = 0x00; column_h += 0x01; //logger.info("End Col {}", column_h); } } if (((i + i2cCommandBatchLimit) % i2cCommandBatchLimit) == i2cCommandBatchLimit - 1) { endI2CBatch(); } } endI2CBatch(); return true; } final int[] SeeedLogo = new int[] { // 72 is the number of rows // 96 - 72 = 24, 24 / 2 = 12 - means Row@12 is the image vert centering // measurement on device backs this up 20mm/2.5mm == 96/12 // 1152 is the number of bytes in image // 16 * 72 == 1152 // 96 * 96 / 8 == 1152 // // Image is square on display (15mm*15mm) // But with 1 pixel = 1 bit then we are 128 pixels wide! // Array 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xC0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xC0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x80, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x80, 0x01, 0xC0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x07, 0x80, 0x01, 0xE0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x0F, 0x80, 0x01, 0xE0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x0F, 0x00, 0x01, 0xE0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x0F, 0x00, 0x01, 0xE0, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x0F, 0x80, 0x01, 0xE0, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x0F, 0x80, 0x01, 0xE0, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x0F, 0x80, 0x03, 0xE0, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x07, 0x80, 0x03, 0xE0, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x07, 0x80, 0x03, 0xE0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x07, 0x80, 0x03, 0xC1, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x87, 0xC0, 0x07, 0xC1, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x83, 0xC0, 0x07, 0x83, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xC3, 0xC0, 0x07, 0x87, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE1, 0xE0, 0x07, 0x0F, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xF0, 0xE0, 0x0F, 0x0F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xF8, 0xF0, 0x0E, 0x1F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xF8, 0x70, 0x1C, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x30, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x18, 0x30, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x88, 0x21, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xC4, 0x47, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE0, 0x0F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x60, 0x00, 0x7E, 0x3F, 0x0F, 0xC3, 0xF0, 0xFA, 0x0F, 0xDF, 0xE1, 0x9F, 0xEC, 0x7E, 0xE6, 0x73, 0x9C, 0xE7, 0x39, 0xCE, 0x1C, 0xDF, 0xE1, 0xB9, 0xEC, 0xE7, 0xE0, 0x61, 0xD8, 0x66, 0x1B, 0x86, 0x1C, 0x06, 0x61, 0xB0, 0x6D, 0xC3, 0x7C, 0x7F, 0xFF, 0xFF, 0xFF, 0x06, 0x0F, 0x86, 0x61, 0xB0, 0x6D, 0x83, 0x3E, 0x7F, 0xFF, 0xFF, 0xFF, 0x06, 0x07, 0xC6, 0x61, 0xB0, 0x6D, 0x83, 0xC3, 0x61, 0x18, 0x46, 0x03, 0x86, 0x18, 0x66, 0x61, 0xB0, 0x6D, 0xC3, 0xFE, 0x7F, 0x9F, 0xE7, 0xF9, 0xFE, 0x1F, 0xE6, 0x3F, 0x9F, 0xEC, 0xFE, 0x7E, 0x3F, 0x0F, 0xC3, 0xF0, 0xFA, 0x0F, 0xC6, 0x3F, 0x9F, 0xEC, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x20, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x20, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0xF3, 0xCF, 0x70, 0x9E, 0x79, 0xE7, 0x80, 0x00, 0x00, 0x00, 0x00, 0x7D, 0x9E, 0x68, 0x20, 0xB2, 0xC8, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x9E, 0x6F, 0x20, 0xB2, 0xF9, 0xE7, 0x80, 0x00, 0x00, 0x00, 0x00, 0x46, 0x9A, 0x61, 0x20, 0xB2, 0xCB, 0x60, 0x80, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xF3, 0xCF, 0x30, 0x9E, 0x79, 0xE7, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x02, 0x00, 0x00, 0x82, 0x60, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x40, 0x40, 0x02, 0x00, 0x00, 0x83, 0x60, 0x00, 0x00, 0x8C, 0x00, 0x00, 0x40, 0x60, 0xB7, 0x79, 0xE7, 0x81, 0xC7, 0x92, 0x70, 0x89, 0xE7, 0x9E, 0x78, 0x7C, 0xE2, 0xC9, 0x2C, 0x81, 0xCC, 0xD2, 0x40, 0xFB, 0x21, 0xB2, 0x48, 0x40, 0x62, 0xF9, 0x2C, 0x80, 0x8C, 0xD2, 0x40, 0x8B, 0xE7, 0xB0, 0x48, 0x40, 0xE2, 0xC9, 0x2C, 0x80, 0x84, 0xD2, 0x40, 0x8B, 0x2D, 0x92, 0x48, 0x7D, 0xB3, 0x79, 0x27, 0x80, 0x87, 0x9E, 0x40, 0x8D, 0xE7, 0x9E, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; }