gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/** * Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com> */ package com.crashnote.external.config.impl; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import com.crashnote.external.config.Config; import com.crashnote.external.config.ConfigException; import com.crashnote.external.config.ConfigIncluder; import com.crashnote.external.config.ConfigObject; import com.crashnote.external.config.ConfigOrigin; import com.crashnote.external.config.ConfigParseOptions; import com.crashnote.external.config.ConfigParseable; import com.crashnote.external.config.ConfigValue; import com.crashnote.external.config.impl.SimpleIncluder.NameSource; /** This is public but is only supposed to be used by the "config" package */ public class ConfigImpl { private static class LoaderCache { private Config currentSystemProperties; private ClassLoader currentLoader; private Map<String, Config> cache; LoaderCache() { this.currentSystemProperties = null; this.currentLoader = null; this.cache = new HashMap<String, Config>(); } // for now, caching as long as the loader remains the same, // drop entire cache if it changes. synchronized Config getOrElseUpdate(ClassLoader loader, String key, Callable<Config> updater) { if (loader != currentLoader) { // reset the cache if we start using a different loader cache.clear(); currentLoader = loader; } Config systemProperties = systemPropertiesAsConfig(); if (systemProperties != currentSystemProperties) { cache.clear(); currentSystemProperties = systemProperties; } Config config = cache.get(key); if (config == null) { try { config = updater.call(); } catch (RuntimeException e) { throw e; // this will include ConfigException } catch (Exception e) { throw new ConfigException.Generic(e.getMessage(), e); } if (config == null) throw new ConfigException.BugOrBroken("null config from cache updater"); cache.put(key, config); } return config; } } private static class LoaderCacheHolder { static final LoaderCache cache = new LoaderCache(); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static Config computeCachedConfig(ClassLoader loader, String key, Callable<Config> updater) { LoaderCache cache; try { cache = LoaderCacheHolder.cache; } catch (ExceptionInInitializerError e) { throw ConfigImplUtil.extractInitializerError(e); } return cache.getOrElseUpdate(loader, key, updater); } static class FileNameSource implements SimpleIncluder.NameSource { @Override public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) { return Parseable.newFile(new File(name), parseOptions); } }; static class ClasspathNameSource implements SimpleIncluder.NameSource { @Override public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) { return Parseable.newResources(name, parseOptions); } }; static class ClasspathNameSourceWithClass implements SimpleIncluder.NameSource { final private Class<?> klass; public ClasspathNameSourceWithClass(Class<?> klass) { this.klass = klass; } @Override public ConfigParseable nameToParseable(String name, ConfigParseOptions parseOptions) { return Parseable.newResources(klass, name, parseOptions); } }; /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static ConfigObject parseResourcesAnySyntax(Class<?> klass, String resourceBasename, ConfigParseOptions baseOptions) { NameSource source = new ClasspathNameSourceWithClass(klass); return SimpleIncluder.fromBasename(source, resourceBasename, baseOptions); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static ConfigObject parseResourcesAnySyntax(String resourceBasename, ConfigParseOptions baseOptions) { NameSource source = new ClasspathNameSource(); return SimpleIncluder.fromBasename(source, resourceBasename, baseOptions); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static ConfigObject parseFileAnySyntax(File basename, ConfigParseOptions baseOptions) { NameSource source = new FileNameSource(); return SimpleIncluder.fromBasename(source, basename.getPath(), baseOptions); } static AbstractConfigObject emptyObject(String originDescription) { ConfigOrigin origin = originDescription != null ? SimpleConfigOrigin .newSimple(originDescription) : null; return emptyObject(origin); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static Config emptyConfig(String originDescription) { return emptyObject(originDescription).toConfig(); } static AbstractConfigObject empty(ConfigOrigin origin) { return emptyObject(origin); } // default origin for values created with fromAnyRef and no origin specified final private static ConfigOrigin defaultValueOrigin = SimpleConfigOrigin .newSimple("hardcoded value"); final private static ConfigBoolean defaultTrueValue = new ConfigBoolean( defaultValueOrigin, true); final private static ConfigBoolean defaultFalseValue = new ConfigBoolean( defaultValueOrigin, false); final private static ConfigNull defaultNullValue = new ConfigNull( defaultValueOrigin); final private static SimpleConfigList defaultEmptyList = new SimpleConfigList( defaultValueOrigin, Collections.<AbstractConfigValue> emptyList()); final private static SimpleConfigObject defaultEmptyObject = SimpleConfigObject .empty(defaultValueOrigin); private static SimpleConfigList emptyList(ConfigOrigin origin) { if (origin == null || origin == defaultValueOrigin) return defaultEmptyList; else return new SimpleConfigList(origin, Collections.<AbstractConfigValue> emptyList()); } private static AbstractConfigObject emptyObject(ConfigOrigin origin) { // we want null origin to go to SimpleConfigObject.empty() to get the // origin "empty config" rather than "hardcoded value" if (origin == defaultValueOrigin) return defaultEmptyObject; else return SimpleConfigObject.empty(origin); } private static ConfigOrigin valueOrigin(String originDescription) { if (originDescription == null) return defaultValueOrigin; else return SimpleConfigOrigin.newSimple(originDescription); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static ConfigValue fromAnyRef(Object object, String originDescription) { ConfigOrigin origin = valueOrigin(originDescription); return fromAnyRef(object, origin, FromMapMode.KEYS_ARE_KEYS); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static ConfigObject fromPathMap( Map<String, ? extends Object> pathMap, String originDescription) { ConfigOrigin origin = valueOrigin(originDescription); return (ConfigObject) fromAnyRef(pathMap, origin, FromMapMode.KEYS_ARE_PATHS); } static AbstractConfigValue fromAnyRef(Object object, ConfigOrigin origin, FromMapMode mapMode) { if (origin == null) throw new ConfigException.BugOrBroken( "origin not supposed to be null"); if (object == null) { if (origin != defaultValueOrigin) return new ConfigNull(origin); else return defaultNullValue; } else if (object instanceof Boolean) { if (origin != defaultValueOrigin) { return new ConfigBoolean(origin, (Boolean) object); } else if ((Boolean) object) { return defaultTrueValue; } else { return defaultFalseValue; } } else if (object instanceof String) { return new ConfigString(origin, (String) object); } else if (object instanceof Number) { // here we always keep the same type that was passed to us, // rather than figuring out if a Long would fit in an Int // or a Double has no fractional part. i.e. deliberately // not using ConfigNumber.newNumber() when we have a // Double, Integer, or Long. if (object instanceof Double) { return new ConfigDouble(origin, (Double) object, null); } else if (object instanceof Integer) { return new ConfigInt(origin, (Integer) object, null); } else if (object instanceof Long) { return new ConfigLong(origin, (Long) object, null); } else { return ConfigNumber.newNumber(origin, ((Number) object).doubleValue(), null); } } else if (object instanceof Map) { if (((Map<?, ?>) object).isEmpty()) return emptyObject(origin); if (mapMode == FromMapMode.KEYS_ARE_KEYS) { Map<String, AbstractConfigValue> values = new HashMap<String, AbstractConfigValue>(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) { Object key = entry.getKey(); if (!(key instanceof String)) throw new ConfigException.BugOrBroken( "bug in method caller: not valid to create ConfigObject from map with non-String key: " + key); AbstractConfigValue value = fromAnyRef(entry.getValue(), origin, mapMode); values.put((String) key, value); } return new SimpleConfigObject(origin, values); } else { return PropertiesParser.fromPathMap(origin, (Map<?, ?>) object); } } else if (object instanceof Iterable) { Iterator<?> i = ((Iterable<?>) object).iterator(); if (!i.hasNext()) return emptyList(origin); List<AbstractConfigValue> values = new ArrayList<AbstractConfigValue>(); while (i.hasNext()) { AbstractConfigValue v = fromAnyRef(i.next(), origin, mapMode); values.add(v); } return new SimpleConfigList(origin, values); } else { throw new ConfigException.BugOrBroken( "bug in method caller: not valid to create ConfigValue from: " + object); } } private static class DefaultIncluderHolder { static final ConfigIncluder defaultIncluder = new SimpleIncluder(null); } static ConfigIncluder defaultIncluder() { try { return DefaultIncluderHolder.defaultIncluder; } catch (ExceptionInInitializerError e) { throw ConfigImplUtil.extractInitializerError(e); } } private static Properties getSystemProperties() { // Avoid ConcurrentModificationException due to parallel setting of system properties by copying properties final Properties systemProperties = System.getProperties(); final Properties systemPropertiesCopy = new Properties(); synchronized (systemProperties) { systemPropertiesCopy.putAll(systemProperties); } return systemPropertiesCopy; } private static AbstractConfigObject loadSystemProperties() { return (AbstractConfigObject) Parseable.newProperties(getSystemProperties(), ConfigParseOptions.defaults().setOriginDescription("system properties")).parse(); } private static class SystemPropertiesHolder { // this isn't final due to the reloadSystemPropertiesConfig() hack below static volatile AbstractConfigObject systemProperties = loadSystemProperties(); } static AbstractConfigObject systemPropertiesAsConfigObject() { try { return SystemPropertiesHolder.systemProperties; } catch (ExceptionInInitializerError e) { throw ConfigImplUtil.extractInitializerError(e); } } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static Config systemPropertiesAsConfig() { return systemPropertiesAsConfigObject().toConfig(); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static void reloadSystemPropertiesConfig() { // ConfigFactory.invalidateCaches() relies on this having the side // effect that it drops all caches SystemPropertiesHolder.systemProperties = loadSystemProperties(); } private static AbstractConfigObject loadEnvVariables() { Map<String, String> env = System.getenv(); Map<String, AbstractConfigValue> m = new HashMap<String, AbstractConfigValue>(); for (Map.Entry<String, String> entry : env.entrySet()) { String key = entry.getKey(); m.put(key, new ConfigString(SimpleConfigOrigin.newSimple("env var " + key), entry .getValue())); } return new SimpleConfigObject(SimpleConfigOrigin.newSimple("env variables"), m, ResolveStatus.RESOLVED, false /* ignoresFallbacks */); } private static class EnvVariablesHolder { static final AbstractConfigObject envVariables = loadEnvVariables(); } static AbstractConfigObject envVariablesAsConfigObject() { try { return EnvVariablesHolder.envVariables; } catch (ExceptionInInitializerError e) { throw ConfigImplUtil.extractInitializerError(e); } } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static Config envVariablesAsConfig() { return envVariablesAsConfigObject().toConfig(); } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static Config defaultReference(final ClassLoader loader) { return computeCachedConfig(loader, "defaultReference", new Callable<Config>() { @Override public Config call() { Config unresolvedResources = Parseable .newResources("reference.conf", ConfigParseOptions.defaults().setClassLoader(loader)) .parse().toConfig(); return systemPropertiesAsConfig().withFallback(unresolvedResources).resolve(); } }); } private static class DebugHolder { private static String LOADS = "loads"; private static Map<String, Boolean> loadDiagnostics() { Map<String, Boolean> result = new HashMap<String, Boolean>(); result.put(LOADS, false); // People do -Dconfig.trace=foo,bar to enable tracing of different things String s = System.getProperty("config.trace"); if (s == null) { return result; } else { String[] keys = s.split(","); for (String k : keys) { if (k.equals(LOADS)) { result.put(LOADS, true); } else { System.err.println("config.trace property contains unknown trace topic '" + k + "'"); } } return result; } } private static final Map<String, Boolean> diagnostics = loadDiagnostics(); private static final boolean traceLoadsEnabled = diagnostics.get(LOADS); static boolean traceLoadsEnabled() { return traceLoadsEnabled; } } /** For use ONLY by library internals, DO NOT TOUCH not guaranteed ABI */ public static boolean traceLoadsEnabled() { try { return DebugHolder.traceLoadsEnabled(); } catch (ExceptionInInitializerError e) { throw ConfigImplUtil.extractInitializerError(e); } } public static void trace(String message) { System.err.println(message); } // the basic idea here is to add the "what" and have a canonical // toplevel error message. the "original" exception may however have extra // detail about what happened. call this if you have a better "what" than // further down on the stack. static ConfigException.NotResolved improveNotResolved(Path what, ConfigException.NotResolved original) { String newMessage = what.render() + " has not been resolved, you need to call Config#resolve()," + " see API docs for Config#resolve()"; if (newMessage.equals(original.getMessage())) return original; else return new ConfigException.NotResolved(newMessage, original); } }
// NERD - The Named Entity Recognition and Disambiguation framework. // It processes textual resources for extracting named entities // linked to Web resources. // // Copyright 2013 EURECOM // Authors: // Jose Luis Redondo Garcia <[email protected]> // // Licensed under both the CeCILL-B and 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.cecill.info/licences/Licence_CeCILL-B_V1-en.html // 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 fr.eurecom.nerd.core.proxy; import java.lang.reflect.Type; import java.util.LinkedList; import java.util.List; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import fr.eurecom.nerd.core.db.table.DocumentType; import fr.eurecom.nerd.core.db.table.TDocument; import fr.eurecom.nerd.core.db.table.TEntity; import fr.eurecom.nerd.core.exceptions.ClientException; import fr.eurecom.nerd.core.logging.LogFactory; import fr.eurecom.nerd.core.ontology.OntoFactory; import fr.eurecom.nerd.core.ontology.OntologyType; import fr.eurecom.nerd.core.srt.SRTMapper; public class THDClient implements IClient { private static String SOURCE = Extractor.getName(ExtractorType.THD); //OLD API URL //private static String ENDPOINT = "http://ner.vse.cz/thd/api/v1/extraction"; //API 2.0 private static String ENDPOINT = "https://entityclassifier.eu/thd/api/v2/extraction"; public List<TEntity> extract( TDocument document, String key, OntologyType otype) throws ClientException { LogFactory.logger.info(SOURCE + " is going to extract entities from a document"); String json = post(key, document.getText(), document.getLanguage()); List<TEntity> result = parse (json, document.getText(), otype); //if the document is a TIMEDTEXTTYPE then it map the corresponding time interval if(document.getType().equals(DocumentType.TIMEDTEXTTYPE)) { SRTMapper srt = new SRTMapper(); result = srt.run(document, result); } LogFactory.logger.info(SOURCE + " has found #entities=" + result.size()); return result; } private List<TEntity> parse(String json, String text, OntologyType otype) { List<TEntity> result = new LinkedList<TEntity>(); Gson gson = new Gson(); try { JSONArray arrayEntities = new JSONArray(json); //JSONObject response = o.getJSONObject("response"); //String entityjson = response.getJSONArray("entities").toString(); //System.out.println(entityjson); //Type listType = new TypeToken<LinkedList<TextRazorEntity>>() {}.getType(); //List<TextRazorEntity> entities = gson.fromJson(THDEntity, listType); for(int i = 0; i < arrayEntities.length(); i++) { JSONObject entityJSON = (JSONObject) arrayEntities.get(i); Type entityType = new TypeToken<THDEntity>() {}.getType(); THDEntity e = gson.fromJson(entityJSON.toString(), entityType); Integer startChar = e.getStartOffset(); Integer endChar = e.getEndOffset(); //LABEL String label = text.substring(startChar, endChar); // we relax a bit this constraint //if( ! label.equalsIgnoreCase(e.getMatchedText()) ) // continue; //URL (The most specific one by the moment) May be prioritize those from DBPedia? String uri = null; if (e.getTypes() != null){ if (e.getTypes().size()>0){ uri = e.getTypes().get(e.getTypes().size()-1).entityURI; } } //EXTRACTOR TYPE (the most specific one) String extractorType = "null"; if (e.getTypes() != null){ if (e.getTypes().size()>0){ extractorType = e.getTypes().get(e.getTypes().size()-1).typeURI; } } //FIXME //String nerdType (STARTING TO LOOK FOR THE MOST GENERAL ONE, the first one in hierarchy) String nerdTypeThing = "http://nerd.eurecom.fr/ontology#Thing"; String nerdType = nerdTypeThing; if (e.getTypes() != null){ int cont = 0; while (cont < e.getTypes().size() && nerdType.equals(nerdTypeThing)) { String currentType = e.getTypes().get(cont).typeURI; if (currentType == null) currentType = e.getTypes().get(cont).entityURI; if (currentType != null){ //Remove namespace / baseURI currentType = currentType.split("/")[currentType.split("/").length-1]; nerdType = OntoFactory.mapper.getNerdType(otype, label, SOURCE, currentType).toString(); } cont ++; } } //The one from the more specific one. Double confidence = 0.0; if (e.getTypes() != null){ if (e.getTypes().size()>0){ if (e.getTypes().get(e.getTypes().size()-1).getConfidence() != null){ confidence = e.getTypes().get(e.getTypes().size()-1).getConfidence().getValue(); } } } TEntity entity = new TEntity( label, extractorType, uri, nerdType, startChar, endChar, confidence, SOURCE ); //System.out.println(entity.toString()); result.add(entity); } } catch (JSONException e) { e.printStackTrace(); } return result; } private String post(String key, String text, String language) throws ClientException { //curl -v "http://ner.vse.cz/thd/api/v1/extraction?apikey=a515172367fc402fa38685d0a3482a7d&format=json&provenance=thd&priority_entity_linking=true&entity_type=all" -d "The Charles Bridge is a famous historic bridge that crosses the Vltava river in Prague, Czech Republic." -H "Accept: application/xml" Client client = ClientBuilder.newClient(); //client.addFilter(new LoggingFilter(System.out)); WebTarget target = client.target(ENDPOINT); target = target.queryParam("apikey", key); target = target.queryParam("format", "json"); target = target.queryParam("provenance", "thd,dbpedia"); target = target.queryParam("knowledge_base", "linkedHypernymsDataset"); target = target.queryParam("lang", language); target = target.queryParam("priority_entity_linking", "true"); target = target.queryParam("entity_type", "ne"); target = target.queryParam("types_filter", "dbo"); Response response = target.request(MediaType.APPLICATION_JSON) .post(Entity.entity( text, MediaType.APPLICATION_XML_TYPE) ); if( response.getStatus() != 200 ) throw new ClientException("Extractor: " + SOURCE + " is temporary not available."); String json = response.readEntity(String.class); return json; } class THDEntity { private Integer startOffset; private Integer endOffset; private String underlyingString; private String entityType; private List<THDType> types; public Integer getStartOffset() { return startOffset; } public void setStartOffset(Integer startOffset) { this.startOffset = startOffset; } public Integer getEndOffset() { return endOffset; } public void setEndOffset(Integer endOffset) { this.endOffset = endOffset; } public String getUnderlyingString() { return underlyingString; } public void setUnderlyingString(String underlyingString) { this.underlyingString = underlyingString; } public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public List<THDType> getTypes() { return types; } public void setTypes(List<THDType> types) { this.types = types; } } class THDType { private String entityURI; private String typeURI; private String entityLabel; private String provenance; private THDConfidence confidence; public String getEntityURI() { return entityURI; } public void setEntityURI(String entityURI) { this.entityURI = entityURI; } public String getTypeURI() { return typeURI; } public void setTypeURI(String typeURI) { this.typeURI = typeURI; } public String getEntityLabel() { return entityLabel; } public void setEntityLabel(String entityLabel) { this.entityLabel = entityLabel; } public String getProvenance() { return provenance; } public void setProvenance(String provenance) { this.provenance = provenance; } public THDConfidence getConfidence() { return confidence; } public void setConfidence(THDConfidence confidence) { this.confidence = confidence; } } class THDConfidence { private String type; private String bounds; private Double value; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getBounds() { return bounds; } public void setBounds(String bounds) { this.bounds = bounds; } public Double getValue() { return value; } public void setValue(Double value) { this.value = value; } } }
// 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.cloud.storage.template; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Date; import org.apache.log4j.Logger; public class FtpTemplateUploader implements TemplateUploader { public static final Logger s_logger = Logger.getLogger(FtpTemplateUploader.class.getName()); public TemplateUploader.Status status = TemplateUploader.Status.NOT_STARTED; public String errorString = ""; public long totalBytes = 0; public long entitySizeinBytes; private String sourcePath; private String ftpUrl; private UploadCompleteCallback completionCallback; private boolean resume; private BufferedInputStream inputStream = null; private BufferedOutputStream outputStream = null; private static final int CHUNK_SIZE = 1024*1024; //1M public FtpTemplateUploader(String sourcePath, String url, UploadCompleteCallback callback, long entitySizeinBytes){ this.sourcePath = sourcePath; this.ftpUrl = url; this.completionCallback = callback; this.entitySizeinBytes = entitySizeinBytes; } public long upload(UploadCompleteCallback callback ) { switch (status) { case ABORTED: case UNRECOVERABLE_ERROR: case UPLOAD_FINISHED: return 0; default: } Date start = new Date(); StringBuffer sb = new StringBuffer(ftpUrl); // check for authentication else assume its anonymous access. /* if (user != null && password != null) { sb.append( user ); sb.append( ':' ); sb.append( password ); sb.append( '@' ); }*/ /* * type ==> a=ASCII mode, i=image (binary) mode, d= file directory * listing */ sb.append( ";type=i" ); try { URL url = new URL( sb.toString() ); URLConnection urlc = url.openConnection(); File sourceFile = new File(sourcePath); entitySizeinBytes = sourceFile.length(); outputStream = new BufferedOutputStream( urlc.getOutputStream() ); inputStream = new BufferedInputStream( new FileInputStream(sourceFile) ); status = TemplateUploader.Status.IN_PROGRESS; int bytes = 0; byte[] block = new byte[CHUNK_SIZE]; boolean done=false; while (!done && status != Status.ABORTED ) { if ( (bytes = inputStream.read(block, 0, CHUNK_SIZE)) > -1) { outputStream.write(block,0, bytes); totalBytes += bytes; } else { done = true; } } status = TemplateUploader.Status.UPLOAD_FINISHED; return totalBytes; } catch (MalformedURLException e) { status = TemplateUploader.Status.UNRECOVERABLE_ERROR; errorString = e.getMessage(); s_logger.error(errorString); } catch (IOException e) { status = TemplateUploader.Status.UNRECOVERABLE_ERROR; errorString = e.getMessage(); s_logger.error(errorString); } finally { try { if (inputStream != null){ inputStream.close(); } if (outputStream != null){ outputStream.close(); } }catch (IOException ioe){ s_logger.error(" Caught exception while closing the resources" ); } if (callback != null) { callback.uploadComplete(status); } } return 0; } @Override public void run() { try { upload(completionCallback); } catch (Throwable t) { s_logger.warn("Caught exception during upload "+ t.getMessage(), t); errorString = "Failed to install: " + t.getMessage(); status = TemplateUploader.Status.UNRECOVERABLE_ERROR; } } @Override public Status getStatus() { return status; } @Override public String getUploadError() { return errorString; } @Override public String getUploadLocalPath() { return sourcePath; } @Override public int getUploadPercent() { if (entitySizeinBytes == 0) { return 0; } return (int)(100.0*totalBytes/entitySizeinBytes); } @Override public long getUploadTime() { // TODO return 0; } @Override public long getUploadedBytes() { return totalBytes; } @Override public void setResume(boolean resume) { this.resume = resume; } @Override public void setStatus(Status status) { this.status = status; } @Override public void setUploadError(String string) { errorString = string; } @Override public boolean stopUpload() { switch (getStatus()) { case IN_PROGRESS: try { if(outputStream != null) { outputStream.close(); } if (inputStream != null){ inputStream.close(); } } catch (IOException e) { s_logger.error(" Caught exception while closing the resources" ); } status = TemplateUploader.Status.ABORTED; return true; case UNKNOWN: case NOT_STARTED: case RECOVERABLE_ERROR: case UNRECOVERABLE_ERROR: case ABORTED: status = TemplateUploader.Status.ABORTED; case UPLOAD_FINISHED: return true; default: return true; } } }
/******************************************************************************* * * Copyright 2012 Impetus Infotech. * * * * 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.impetus.client.crud.compositeType; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import junit.framework.Assert; import org.apache.cassandra.thrift.Compression; import org.apache.cassandra.thrift.ConsistencyLevel; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.impetus.client.cassandra.CassandraClientBase; import com.impetus.client.cassandra.common.CassandraConstants; import com.impetus.client.crud.compositeType.CassandraPrimeUser.NickName; import com.impetus.kundera.client.Client; import com.impetus.kundera.client.cassandra.persistence.CassandraCli; import com.impetus.kundera.query.QueryHandlerException; /** * Junit test case for Compound/Composite key. * * @author vivek.mishra * */ public class CassandraCompositeTypeTest { /** The Constant PERSISTENCE_UNIT. */ private static final String PERSISTENCE_UNIT = "composite_pu"; /** The emf. */ private EntityManagerFactory emf; /** The Constant logger. */ private static final Logger logger = LoggerFactory.getLogger(CassandraCompositeTypeTest.class); /** The current date. */ private Date currentDate = new Date(); /** * Sets the up. * * @throws Exception * the exception */ @Before public void setUp() throws Exception { CassandraCli.cassandraSetUp(); CassandraCli.initClient(); } /** * On add column. * * @throws Exception * the exception */ @Test public void onAddColumn() throws Exception { // cql script is not adding "tweetBody", kundera.ddl.auto.update will // add it. String cql_Query = "create columnfamily \"CompositeUser\" (\"userId\" text, \"tweetId\" int, \"timeLineId\" uuid, " + " \"tweetDate\" timestamp, PRIMARY KEY(\"userId\",\"tweetId\",\"timeLineId\"))"; executeScript(cql_Query); emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); EntityManager em = emf.createEntityManager(); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); onCRUD(em, key); em = emf.createEntityManager(); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key); Assert.assertNotNull(result); Assert.assertNull(result.getKey().getFullName()); Assert.assertEquals("After merge", result.getTweetBody()); // assertion // of newly // added // tweet body em.remove(result); em.flush(); em.close(); em = emf.createEntityManager(); clients = (Map<String, Client>) em.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); result = em.find(CassandraPrimeUser.class, key); Assert.assertNull(result); em.close(); } // @Test /** * On alter column type. * * @throws Exception * the exception */ public void onAlterColumnType() throws Exception { // Here tweetDate is of type "int". On update will be changed to // timestamp. String cql_Query = "create columnfamily \"CompositeUser\" (\"userId\" text, \"tweetId\" int, \"timeLineId\" uuid, " + " \"tweetDate\" int, PRIMARY KEY(\"userId\",\"tweetId\",\"timeLineId\"))"; executeScript(cql_Query); emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); EntityManager em = emf.createEntityManager(); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); onCRUD(em, key); em = emf.createEntityManager(); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key); Assert.assertNotNull(result); Assert.assertNull(result.getKey().getFullName()); Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime()); // assertion // of // changed // tweetDate. em.remove(result); em.flush(); em.close(); em = emf.createEntityManager(); clients = (Map<String, Client>) em.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); result = em.find(CassandraPrimeUser.class, key); Assert.assertNull(result); em.close(); } /** * On query. */ @Test public void onQuery() { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); EntityManager em = emf.createEntityManager(); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); CassandraPrimeUser user = new CassandraPrimeUser(key); user.setTweetBody("my first tweet"); user.setTweetDate(currentDate); em.persist(user); em.flush(); // optional,just to clear persistence cache. em.clear(); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); final String noClause = "Select u from CassandraPrimeUser u"; final String withFirstCompositeColClause = "Select u from CassandraPrimeUser u where u.key.userId = :userId"; final String withSecondCompositeColClause = "Select u from CassandraPrimeUser u where u.key.tweetId = :tweetId"; final String withBothCompositeColClause = "Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId"; final String withAllCompositeColClause = "Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId"; final String withLastCompositeColGTClause = "Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId"; final String withSelectiveCompositeColClause = "Select u.key from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId"; final String withSelectCompositeKeyColumnClause = "Select u.key.userId,u.key.timeLineId, u.tweetDate from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId"; // query over 1 composite and 1 non-column // query with no clause. Query q = em.createQuery(noClause); List<CassandraPrimeUser> results = q.getResultList(); Assert.assertEquals(1, results.size()); // Query with composite key clause. q = em.createQuery(withFirstCompositeColClause); q.setParameter("userId", "mevivs"); results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // Query with composite key clause. q = em.createQuery(withSecondCompositeColClause); q.setParameter("tweetId", 1); results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // Query with composite key clause. q = em.createQuery(withBothCompositeColClause); q.setParameter("userId", "mevivs"); q.setParameter("tweetId", 1); results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // Query with composite key clause. q = em.createQuery(withAllCompositeColClause); q.setParameter("userId", "mevivs"); q.setParameter("tweetId", 1); q.setParameter("timeLineId", timeLineId); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals(1, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // Query with composite key clause. q = em.createQuery(withLastCompositeColGTClause); q.setParameter("userId", "mevivs"); q.setParameter("tweetId", 1); q.setParameter("timeLineId", timeLineId); results = q.getResultList(); Assert.assertNull(results.get(0).getKey().getFullName()); Assert.assertEquals(1, results.size()); // Query with composite key with selective clause. q = em.createQuery(withSelectiveCompositeColClause); q.setParameter("userId", "mevivs"); q.setParameter("tweetId", 1); q.setParameter("timeLineId", timeLineId); results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertNull(results.get(0).getTweetBody()); Assert.assertNull(results.get(0).getKey().getFullName()); // Query for selecting a column of composite key. q = em.createQuery(withSelectCompositeKeyColumnClause); q.setParameter("userId", "mevivs"); q.setParameter("tweetId", 1); q.setParameter("timeLineId", timeLineId); results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertNotNull(results.get(0)); Assert.assertNotNull(results.get(0).getKey()); Assert.assertNotNull(results.get(0).getKey().getUserId()); Assert.assertNull(results.get(0).getKey().getFullName()); Assert.assertNotNull(results.get(0).getKey().getTimeLineId()); Assert.assertEquals(0, results.get(0).getKey().getTweetId()); Assert.assertEquals(currentDate, results.get(0).getTweetDate()); Assert.assertNull(results.get(0).getTweetBody()); Assert.assertNull(results.get(0).getKey().getFullName()); final String selectiveColumnTweetBodyWithAllCompositeColClause = "Select u.tweetBody from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId"; // Query for selective column tweetBody with composite key clause. q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause); q.setParameter("userId", "mevivs"); q.setParameter("tweetId", 1); q.setParameter("timeLineId", timeLineId); results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertEquals("my first tweet", results.get(0).getTweetBody()); Assert.assertNull(results.get(0).getTweetDate()); final String selectiveColumnTweetDateWithAllCompositeColClause = "Select u.tweetDate from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId"; // Query for selective column tweetDate with composite key clause. q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause); q.setParameter("userId", "mevivs"); q.setParameter("tweetId", 1); q.setParameter("timeLineId", timeLineId); results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime()); Assert.assertNull(results.get(0).getTweetBody()); final String withCompositeKeyClause = "Select u from CassandraPrimeUser u where u.key = :key"; // Query with composite key clause. q = em.createQuery(withCompositeKeyClause); q.setParameter("key", key); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals(1, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); Assert.assertNull(results.get(0).getKey().getFullName()); final String withSemiColonAtEnd = "Select u from CassandraPrimeUser u where u.key.userId = :userId;"; // Query with semi colon at end. try { q = em.createQuery(withSemiColonAtEnd); q.setParameter("userId", "mevivs"); } catch (QueryHandlerException qhe) { Assert.assertEquals( "unexpected char: ';' in query [ Select u from CassandraPrimeUser u where u.key.userId = :userId; ]", qhe.getMessage().trim()); } em.remove(user); em.clear();// optional,just to clear persistence cache. } /** * On named query test. */ @Test public void onNamedQueryTest() { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); updateNamed(); deleteNamed(); } /** * On named query batch test. */ @Test public void onNamedQueryBatchTest() { Map propertyMap = new HashMap(); propertyMap.put("kundera.batch.size", "5"); emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, propertyMap); insertUpdateBatch(); deleteBatch(); } /** * On limit. */ @Test public void onLimit() { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); EntityManager em = emf.createEntityManager(); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser user1 = new CassandraPrimeUser(key); user1.setTweetBody("my first tweet"); user1.setTweetDate(currentDate); em.persist(user1); key = new CassandraCompoundKey("mevivs", 2, timeLineId); CassandraPrimeUser user2 = new CassandraPrimeUser(key); user2.setTweetBody("my first tweet"); user2.setTweetDate(currentDate); em.persist(user2); key = new CassandraCompoundKey("mevivs", 3, timeLineId); CassandraPrimeUser user3 = new CassandraPrimeUser(key); user3.setTweetBody("my first tweet"); user3.setTweetDate(currentDate); em.persist(user3); em.flush(); // em.clear(); // optional,just to clear persistence cache. // em = emf.createEntityManager(); em.clear(); final String noClause = "Select u from CassandraPrimeUser u"; Query q = em.createQuery(noClause); List<CassandraPrimeUser> results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals(3, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // With limit q = em.createQuery(noClause); q.setMaxResults(2); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals(2, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); } /** * On order by clause. */ @Test public void onOrderBYClause() { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); EntityManager em = emf.createEntityManager(); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser user1 = new CassandraPrimeUser(key); user1.setTweetBody("my first tweet"); user1.setTweetDate(currentDate); em.persist(user1); key = new CassandraCompoundKey("mevivs", 2, timeLineId); CassandraPrimeUser user2 = new CassandraPrimeUser(key); user2.setTweetBody("my second tweet"); user2.setTweetDate(currentDate); em.persist(user2); key = new CassandraCompoundKey("mevivs", 3, timeLineId); CassandraPrimeUser user3 = new CassandraPrimeUser(key); user3.setTweetBody("my third tweet"); user3.setTweetDate(currentDate); em.persist(user3); em.flush(); // em.clear(); // optional,just to clear persistence cache. // em = emf.createEntityManager(); em.clear(); String orderClause = "Select u from CassandraPrimeUser u where u.key.userId = :userId ORDER BY u.key.tweetId ASC"; Query q = em.createQuery(orderClause); q.setParameter("userId", "mevivs"); List<CassandraPrimeUser> results = q.getResultList(); Assert.assertNotNull(results); Assert.assertFalse(results.isEmpty()); Assert.assertEquals(3, results.size()); Assert.assertEquals("my first tweet", results.get(0).getTweetBody()); Assert.assertEquals("my second tweet", results.get(1).getTweetBody()); Assert.assertEquals("my third tweet", results.get(2).getTweetBody()); Assert.assertNull(results.get(0).getKey().getFullName()); orderClause = "Select u from CassandraPrimeUser u where u.key.userId = :userId ORDER BY u.key.tweetId DESC"; q = em.createQuery(orderClause); q.setParameter("userId", "mevivs"); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals("my first tweet", results.get(2).getTweetBody()); Assert.assertEquals("my second tweet", results.get(1).getTweetBody()); Assert.assertEquals("my third tweet", results.get(0).getTweetBody()); Assert.assertEquals(3, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // With limit q = em.createQuery(orderClause); q.setParameter("userId", "mevivs"); q.setMaxResults(2); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals(2, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); try { orderClause = "Select u from CassandraPrimeUser u where u.key.userId = :userId ORDER BY u.key.userId DESC"; q = em.createQuery(orderClause); q.setParameter("userId", "mevivs"); results = q.getResultList(); Assert.fail(); } catch (Exception e) { Assert.assertEquals( "javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: InvalidRequestException(why:Order by is currently only supported on the clustered columns of the PRIMARY KEY, got userId)", e.getMessage()); } } /** * On in clause. */ @Test public void onInClause() { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); EntityManager em = emf.createEntityManager(); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser user1 = new CassandraPrimeUser(key); user1.setTweetBody("my first tweet"); user1.setTweetDate(currentDate); em.persist(user1); key = new CassandraCompoundKey("cgangwals", 2, timeLineId); CassandraPrimeUser user2 = new CassandraPrimeUser(key); user2.setTweetBody("my second tweet"); user2.setTweetDate(currentDate); em.persist(user2); key = new CassandraCompoundKey("kmishra", 3, timeLineId); CassandraPrimeUser user3 = new CassandraPrimeUser(key); user3.setTweetBody("my third tweet"); user3.setTweetDate(currentDate); em.persist(user3); em.flush(); em.clear(); String inClause = "Select u from CassandraPrimeUser u where u.key.userId IN ('mevivs','kmishra') ORDER BY u.key.tweetId ASC"; Query q = em.createQuery(inClause); List<CassandraPrimeUser> results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals(2, results.size()); Assert.assertNotNull(results.get(0)); Assert.assertNotNull(results.get(1)); Assert.assertEquals("my first tweet", results.get(0).getTweetBody()); Assert.assertEquals("my third tweet", results.get(1).getTweetBody()); Assert.assertNull(results.get(0).getKey().getFullName()); inClause = "Select u from CassandraPrimeUser u where u.key.userId IN ('\"mevivs\"','\"kmishra\"') ORDER BY u.key.tweetId ASC"; q = em.createQuery(inClause); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertTrue(results.isEmpty()); inClause = "Select u from CassandraPrimeUser u where u.key.userId IN ('mevivs') ORDER BY u.key.tweetId ASC"; q = em.createQuery(inClause); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertEquals("my first tweet", results.get(0).getTweetBody()); Assert.assertEquals(1, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); try { inClause = "Select u from CassandraPrimeUser u where u.key.tweetId IN (1,2,3) ORDER BY u.key.tweetId DESC"; q = em.createQuery(inClause); results = q.getResultList(); Assert.fail(); } catch (Exception e) { Assert.assertEquals( "javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: InvalidRequestException(why:Clustering column \"tweetId\" cannot be restricted by an IN relation)", e.getMessage()); } // In Query. inClause = "Select u from CassandraPrimeUser u where u.key.userId IN ('mevivs','kmishra') ORDER BY u.key.tweetId ASC"; q = em.createQuery(inClause); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertTrue(!results.isEmpty()); Assert.assertEquals(2, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // In Query set Paramater. inClause = "Select u from CassandraPrimeUser u where u.key.userId IN :userIdList ORDER BY u.key.tweetId ASC"; q = em.createQuery(inClause); List<String> userIdList = new ArrayList<String>(); userIdList.add("mevivs"); userIdList.add("kmishra"); userIdList.add("cgangwals"); q = em.createQuery(inClause); q.setParameter("userIdList", userIdList); results = q.getResultList(); Assert.assertNotNull(results); Assert.assertTrue(!results.isEmpty()); Assert.assertEquals(3, results.size()); Assert.assertNull(results.get(0).getKey().getFullName()); // In Query set Paramater with and clause. inClause = "Select u from CassandraPrimeUser u where u.key.userId IN :userIdList and u.name = 'kuldeep' ORDER BY u.key.tweetId ASC"; q = em.createQuery(inClause); q.setParameter("userIdList", userIdList); try { results = q.getResultList(); Assert.fail(); } catch (Exception e) { Assert.assertEquals( "javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: InvalidRequestException(why:Select on indexed columns and with IN clause for the PRIMARY KEY are not supported)", e.getMessage()); } // In Query set Paramater with gt clause. inClause = "Select u from CassandraPrimeUser u where u.key IN :keyList"; q = em.createQuery(inClause); List<CassandraCompoundKey> keyList = new ArrayList<CassandraCompoundKey>(); UUID timeLineId1 = UUID.randomUUID(); keyList.add(new CassandraCompoundKey("mevivs", 1, timeLineId1)); keyList.add(new CassandraCompoundKey("kmishra", 3, timeLineId1)); keyList.add(new CassandraCompoundKey("cgangwals", 2, timeLineId1)); q.setParameter("keyList", keyList); try { results = q.getResultList(); Assert.fail(); } catch (Exception e) { Assert.assertEquals( "javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: InvalidRequestException(why:Clustering column \"tweetId\" cannot be restricted by an IN relation)", e.getMessage()); } } /** * On batch insert. */ @Test public void onBatchInsert() { emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); EntityManager em = emf.createEntityManager(); UUID timeLineId = UUID.randomUUID(); for (int i = 0; i < 500; i++) { CassandraCompoundKey key = new CassandraCompoundKey("mevivs", i, timeLineId); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser user = new CassandraPrimeUser(key); user.setTweetBody("my first tweet"); user.setTweetDate(currentDate); em.persist(user); } em.clear(); CassandraPrimeUser u = em.find(CassandraPrimeUser.class, new CassandraCompoundKey("mevivs", 499, timeLineId)); Assert.assertNotNull(u); } /** * CompositeUserDataType. * * @throws Exception * the exception */ @After public void tearDown() throws Exception { emf.close(); CassandraCli.client.execute_cql3_query(ByteBuffer.wrap("use \"CompositeCassandra\"".getBytes()), Compression.NONE, ConsistencyLevel.ONE); CassandraCli.client.execute_cql3_query(ByteBuffer.wrap("truncate \"CompositeUser\"".getBytes()), Compression.NONE, ConsistencyLevel.ONE); CassandraCli.dropKeySpace("CompositeCassandra"); } // DO NOT DELETE IT!! though it is automated with schema creation option. /** * create column family script for compound key. * * @param cql * the cql */ private void executeScript(final String cql) { CassandraCli.createKeySpace("CompositeCassandra"); CassandraCli.executeCqlQuery(cql, "CompositeCassandra"); } /** * CRUD over Compound primary Key. * * @param em * the em * @param key * the key */ private void onCRUD(final EntityManager em, CassandraCompoundKey key) { Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser user = new CassandraPrimeUser(key); user.setTweetBody("my first tweet"); user.setTweetDate(currentDate); user.setNickName(NickName.KK); em.persist(user); em.flush(); // em.clear(); // optional,just to clear persistence cache. // em = emf.createEntityManager(); em.clear(); clients = (Map<String, Client>) em.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key); Assert.assertNotNull(result); Assert.assertEquals("my first tweet", result.getTweetBody()); // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId()); Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime()); Assert.assertEquals(NickName.KK, result.getNickName()); Assert.assertEquals(NickName.KK.name(), result.getNickName().name()); em.clear();// optional,just to clear persistence cache. user.setTweetBody("After merge"); em.merge(user); em.close();// optional,just to clear persistence cache. EntityManager em1 = emf.createEntityManager(); // em = emf.createEntityManager(); clients = (Map<String, Client>) em1.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); result = em1.find(CassandraPrimeUser.class, key); Assert.assertNotNull(result); Assert.assertEquals("After merge", result.getTweetBody()); // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId()); Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime()); // deleting composite em1.clear(); // optional,just to clear persistence cache. // em.close();// optional,just to clear persistence cache. } /** * Update by Named Query. */ private void updateNamed() { EntityManager em = emf.createEntityManager(); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); CassandraPrimeUser user = new CassandraPrimeUser(key); user.setTweetBody("my first tweet"); user.setTweetDate(currentDate); em.persist(user); em.close(); em = emf.createEntityManager(); clients = (Map<String, Client>) em.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); String updateQuery = "Update CassandraPrimeUser u SET u.tweetBody='after merge' where u.key= :beforeUpdate"; Query q = em.createQuery(updateQuery); q.setParameter("beforeUpdate", key); q.executeUpdate(); em.close(); // optional,just to clear persistence cache. em = emf.createEntityManager(); clients = (Map<String, Client>) em.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key); Assert.assertNotNull(result); Assert.assertEquals("after merge", result.getTweetBody()); Assert.assertEquals(timeLineId, result.getKey().getTimeLineId()); Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime()); em.close(); } /** * delete by Named Query. */ private void deleteNamed() { UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); String deleteQuery = "Delete From CassandraPrimeUser u where u.key= :key"; EntityManager em = emf.createEntityManager(); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); Query q = em.createQuery(deleteQuery); q.setParameter("key", key); q.executeUpdate(); CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key); Assert.assertNull(result); em.close(); } /** * Insert update batch. */ private void insertUpdateBatch() { EntityManager em = emf.createEntityManager(); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); CassandraPrimeUser user = new CassandraPrimeUser(key); user.setTweetBody("my first tweet"); user.setTweetDate(currentDate); em.persist(user); CassandraCompoundKey key1 = new CassandraCompoundKey("mevivs", 2, timeLineId); CassandraPrimeUser user1 = new CassandraPrimeUser(key1); user1.setTweetBody("my first tweet"); user1.setTweetDate(currentDate); em.persist(user1); CassandraCompoundKey key2 = new CassandraCompoundKey("mevivs", 3, timeLineId); CassandraPrimeUser user2 = new CassandraPrimeUser(key2); user2.setTweetBody("my first tweet"); user2.setTweetDate(currentDate); em.persist(user2); em.close(); em = emf.createEntityManager(); clients = (Map<String, Client>) em.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); String updateQuery = "Update CassandraPrimeUser u SET u.tweetBody='after merge' where u.key= :beforeUpdate"; Query q = em.createQuery(updateQuery); q.setParameter("beforeUpdate", key); q.executeUpdate(); em.close(); // optional,just to clear persistence cache. em = emf.createEntityManager(); clients = (Map<String, Client>) em.getDelegate(); client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0); CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key); Assert.assertNotNull(result); Assert.assertEquals("after merge", result.getTweetBody()); Assert.assertEquals(timeLineId, result.getKey().getTimeLineId()); Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime()); em.close(); } /** * Delete batch. */ private void deleteBatch() { UUID timeLineId = UUID.randomUUID(); CassandraCompoundKey key = new CassandraCompoundKey("mevivs", 1, timeLineId); String deleteQuery = "Delete From CassandraPrimeUser u where u.key.userId= :userId"; EntityManager em = emf.createEntityManager(); Map<String, Client> clients = (Map<String, Client>) em.getDelegate(); Client client = clients.get(PERSISTENCE_UNIT); ((CassandraClientBase) client).setCqlVersion("3.0.0"); Query q = em.createQuery(deleteQuery); q.setParameter("userId", "mevivs"); q.executeUpdate(); CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key); Assert.assertNull(result); em.close(); } }
/** * 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.recoveryservices.backup.v2016_06_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.implementation.ProtectionPolicyResourceInner; import com.microsoft.azure.arm.model.Indexable; 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.recoveryservices.backup.v2016_06_01.implementation.RecoveryServicesManager; import java.util.Map; import com.microsoft.azure.management.recoveryservices.backup.v2016_06_01.implementation.ProtectionPolicyInner; /** * Type representing VaultProtectionPolicyResource. */ public interface VaultProtectionPolicyResource extends HasInner<ProtectionPolicyResourceInner>, Indexable, Refreshable<VaultProtectionPolicyResource>, Updatable<VaultProtectionPolicyResource.Update>, HasManager<RecoveryServicesManager> { /** * @return the eTag value. */ String eTag(); /** * @return the id value. */ String id(); /** * @return the location value. */ String location(); /** * @return the name value. */ String name(); /** * @return the properties value. */ ProtectionPolicyInner properties(); /** * @return the tags value. */ Map<String, String> tags(); /** * @return the type value. */ String type(); /** * The entirety of the VaultProtectionPolicyResource definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithVault, DefinitionStages.WithCreate { } /** * Grouping of VaultProtectionPolicyResource definition stages. */ interface DefinitionStages { /** * The first stage of a VaultProtectionPolicyResource definition. */ interface Blank extends WithVault { } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify Vault. */ interface WithVault { /** * Specifies vaultName, resourceGroupName. */ WithCreate withExistingVault(String vaultName, String resourceGroupName); } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify ETag. */ interface WithETag { /** * Specifies eTag. */ WithCreate withETag(String eTag); } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify Id. */ interface WithId { /** * Specifies id. */ WithCreate withId(String id); } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify Location. */ interface WithLocation { /** * Specifies location. */ WithCreate withLocation(String location); } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify Name. */ interface WithName { /** * Specifies name. */ WithCreate withName(String name); } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify Properties. */ interface WithProperties { /** * Specifies properties. */ WithCreate withProperties(ProtectionPolicyInner properties); } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify Tags. */ interface WithTags { /** * Specifies tags. */ WithCreate withTags(Map<String, String> tags); } /** * The stage of the vaultprotectionpolicyresource definition allowing to specify Type. */ interface WithType { /** * Specifies type. */ WithCreate withType(String type); } /** * 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<VaultProtectionPolicyResource>, DefinitionStages.WithETag, DefinitionStages.WithId, DefinitionStages.WithLocation, DefinitionStages.WithName, DefinitionStages.WithProperties, DefinitionStages.WithTags, DefinitionStages.WithType { } } /** * The template for a VaultProtectionPolicyResource update operation, containing all the settings that can be modified. */ interface Update extends Appliable<VaultProtectionPolicyResource>, UpdateStages.WithETag, UpdateStages.WithId, UpdateStages.WithLocation, UpdateStages.WithName, UpdateStages.WithProperties, UpdateStages.WithTags, UpdateStages.WithType { } /** * Grouping of VaultProtectionPolicyResource update stages. */ interface UpdateStages { /** * The stage of the vaultprotectionpolicyresource update allowing to specify ETag. */ interface WithETag { /** * Specifies eTag. */ Update withETag(String eTag); } /** * The stage of the vaultprotectionpolicyresource update allowing to specify Id. */ interface WithId { /** * Specifies id. */ Update withId(String id); } /** * The stage of the vaultprotectionpolicyresource update allowing to specify Location. */ interface WithLocation { /** * Specifies location. */ Update withLocation(String location); } /** * The stage of the vaultprotectionpolicyresource update allowing to specify Name. */ interface WithName { /** * Specifies name. */ Update withName(String name); } /** * The stage of the vaultprotectionpolicyresource update allowing to specify Properties. */ interface WithProperties { /** * Specifies properties. */ Update withProperties(ProtectionPolicyInner properties); } /** * The stage of the vaultprotectionpolicyresource update allowing to specify Tags. */ interface WithTags { /** * Specifies tags. */ Update withTags(Map<String, String> tags); } /** * The stage of the vaultprotectionpolicyresource update allowing to specify Type. */ interface WithType { /** * Specifies type. */ Update withType(String type); } } }
/* * 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.geode.internal.cache.ha; import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.AttributesFactory; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheException; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.CacheListener; import org.apache.geode.cache.DataPolicy; import org.apache.geode.cache.EntryEvent; import org.apache.geode.cache.InterestResultPolicy; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.Scope; import org.apache.geode.cache.util.CacheListenerAdapter; import org.apache.geode.cache30.CacheSerializableRunnable; import org.apache.geode.cache30.ClientServerTestCase; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.internal.AvailablePort; import org.apache.geode.internal.cache.CacheServerImpl; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.IgnoredException; import org.apache.geode.test.dunit.NetworkUtils; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase; import org.apache.geode.test.junit.categories.ClientSubscriptionTest; /** * This is the Dunit test to verify the duplicates after the fail over The test perorms following * operations 1. Create 2 servers and 1 client 2. Perform put operations for knows set of keys * directy from the server1. 3. Stop the server1 so that fail over happens 4. Validate the * duplicates received by the client1 */ @Category({ClientSubscriptionTest.class}) public class HADuplicateDUnitTest extends JUnit4DistributedTestCase { VM server1 = null; VM server2 = null; VM client1 = null; VM client2 = null; private static final String REGION_NAME = "HADuplicateDUnitTest_Region"; protected static Cache cache = null; static boolean isEventDuplicate = true; static CacheServerImpl server = null; static final int NO_OF_PUTS = 100; public static final Object dummyObj = "dummyObject"; static boolean waitFlag = true; static int put_counter = 0; static Map storeEvents = new HashMap(); @Override public final void postSetUp() throws Exception { final Host host = Host.getHost(0); server1 = host.getVM(0); server2 = host.getVM(1); client1 = host.getVM(2); client2 = host.getVM(3); } @Override public final void preTearDown() throws Exception { client1.invoke(() -> HADuplicateDUnitTest.closeCache()); // close server server1.invoke(() -> HADuplicateDUnitTest.reSetQRMslow()); server1.invoke(() -> HADuplicateDUnitTest.closeCache()); server2.invoke(() -> HADuplicateDUnitTest.closeCache()); } @Ignore("TODO") @Test public void testDuplicate() throws Exception { createClientServerConfiguration(); server1.invoke(putForKnownKeys()); server1.invoke(stopServer()); // wait till all the duplicates are received by client client1.invoke(new CacheSerializableRunnable("waitForPutToComplete") { @Override public void run2() throws CacheException { synchronized (dummyObj) { while (waitFlag) { try { dummyObj.wait(); } catch (InterruptedException e) { fail("interrupted"); } } } if (waitFlag) fail("test failed"); } }); // validate the duplicates received by client client1.invoke(new CacheSerializableRunnable("validateDuplicates") { @Override public void run2() throws CacheException { if (!isEventDuplicate) fail(" Not all duplicates received"); } }); server1.invoke(() -> HADuplicateDUnitTest.reSetQRMslow()); } @Test public void testSample() throws Exception { IgnoredException.addIgnoredException("IOException"); IgnoredException.addIgnoredException("Connection reset"); createClientServerConfiguration(); server1.invoke(new CacheSerializableRunnable("putKey") { @Override public void run2() throws CacheException { Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); region.put("key1", "value1"); } }); } // function to perform put operations for the known set of keys. private CacheSerializableRunnable putForKnownKeys() { CacheSerializableRunnable putforknownkeys = new CacheSerializableRunnable("putforknownkeys") { @Override public void run2() throws CacheException { Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); for (int i = 0; i < NO_OF_PUTS; i++) { region.put("key" + i, "value" + i); } } }; return putforknownkeys; } // function to stop server so that the fail over happens private CacheSerializableRunnable stopServer() { CacheSerializableRunnable stopserver = new CacheSerializableRunnable("stopServer") { @Override public void run2() throws CacheException { server.stop(); } }; return stopserver; } // function to create 2servers and 1 clients private void createClientServerConfiguration() { int PORT1 = ((Integer) server1.invoke(() -> HADuplicateDUnitTest.createServerCache())).intValue(); server1.invoke(() -> HADuplicateDUnitTest.setQRMslow()); int PORT2 = ((Integer) server2.invoke(() -> HADuplicateDUnitTest.createServerCache())).intValue(); String hostname = NetworkUtils.getServerHostName(Host.getHost(0)); client1.invoke(() -> HADuplicateDUnitTest.createClientCache(hostname, new Integer(PORT1), new Integer(PORT2))); } // function to set QRM slow public static void setQRMslow() { System.setProperty("QueueRemovalThreadWaitTime", "100000"); } public static void reSetQRMslow() { System.setProperty("QueueRemovalThreadWaitTime", "1000"); } public static Integer createServerCache() throws Exception { new HADuplicateDUnitTest().createCache(new Properties()); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.DISTRIBUTED_ACK); factory.setDataPolicy(DataPolicy.REPLICATE); RegionAttributes attrs = factory.create(); cache.createRegion(REGION_NAME, attrs); server = (CacheServerImpl) cache.addCacheServer(); assertNotNull(server); int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET); server.setPort(port); server.setNotifyBySubscription(true); server.start(); return new Integer(server.getPort()); } private void createCache(Properties props) throws Exception { DistributedSystem ds = getSystem(props); assertNotNull(ds); ds.disconnect(); ds = getSystem(props); cache = CacheFactory.create(ds); assertNotNull(cache); } public static void createClientCache(String hostName, Integer port1, Integer port2) throws Exception { int PORT1 = port1.intValue(); int PORT2 = port2.intValue(); Properties props = new Properties(); props.setProperty(MCAST_PORT, "0"); props.setProperty(LOCATORS, ""); new HADuplicateDUnitTest().createCache(props); AttributesFactory factory = new AttributesFactory(); ClientServerTestCase.configureConnectionPool(factory, hostName, new int[] {PORT1, PORT2}, true, -1, 2, null); factory.setScope(Scope.DISTRIBUTED_ACK); CacheListener clientListener = new HAValidateDuplicateListener(); factory.setCacheListener(clientListener); RegionAttributes attrs = factory.create(); cache.createRegion(REGION_NAME, attrs); Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); region.registerInterest("ALL_KEYS", InterestResultPolicy.NONE); } public static void closeCache() { if (cache != null && !cache.isClosed()) { cache.close(); cache.getDistributedSystem().disconnect(); } } // Listener class for the validation purpose private static class HAValidateDuplicateListener extends CacheListenerAdapter { @Override public void afterCreate(EntryEvent event) { System.out.println("After Create"); storeEvents.put(event.getKey(), event.getNewValue()); } @Override public void afterUpdate(EntryEvent event) { Object value = storeEvents.get(event.getKey()); if (value == null) isEventDuplicate = false; synchronized (dummyObj) { try { put_counter++; if (put_counter == NO_OF_PUTS) { waitFlag = false; dummyObj.notifyAll(); } } catch (Exception e) { e.printStackTrace(); } } } } }
/* 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 java.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Array; public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> implements Map<K, V>, Serializable, Cloneable { private static final long serialVersionUID = 458661240069192865L; private Class<K> keyType; transient Enum[] keys; transient Object[] values; transient boolean[] hasMapping; private transient int mappingsCount; transient int enumSize; private transient EnumMapEntrySet<K, V> entrySet = null; private static class Entry<KT extends Enum<KT>, VT> extends MapEntry<KT, VT> { private final EnumMap<KT, VT> enumMap; private final int ordinal; Entry(KT theKey, VT theValue, EnumMap<KT, VT> em) { super(theKey, theValue); enumMap = em; ordinal = ((Enum) theKey).ordinal(); } @Override public boolean equals(Object object) { if (!enumMap.hasMapping[ordinal]) { return false; } boolean isEqual = false; if (object instanceof Map.Entry) { Map.Entry<KT, VT> entry = (Map.Entry<KT, VT>) object; Object enumKey = entry.getKey(); if (key.equals(enumKey)) { Object theValue = entry.getValue(); isEqual = enumMap.values[ordinal] == null ? null == theValue : enumMap.values[ordinal].equals(theValue); } } return isEqual; } @Override public int hashCode() { return (enumMap.keys[ordinal] == null ? 0 : enumMap.keys[ordinal] .hashCode()) ^ (enumMap.values[ordinal] == null ? 0 : enumMap.values[ordinal].hashCode()); } @Override public KT getKey() { checkEntryStatus(); return (KT) enumMap.keys[ordinal]; } @Override public VT getValue() { checkEntryStatus(); return (VT) enumMap.values[ordinal]; } @Override public VT setValue(VT value) { checkEntryStatus(); return enumMap.put((KT) enumMap.keys[ordinal], value); } @Override public String toString() { StringBuilder result = new StringBuilder(enumMap.keys[ordinal] .toString()); result.append("="); //$NON-NLS-1$ result.append(enumMap.values[ordinal].toString()); return result.toString(); } private void checkEntryStatus() { if (!enumMap.hasMapping[ordinal]) { throw new IllegalStateException(); } } } private static class EnumMapIterator<E, KT extends Enum<KT>, VT> implements Iterator<E> { int position = 0; int prePosition = -1; final EnumMap<KT, VT> enumMap; final MapEntry.Type<E, KT, VT> type; EnumMapIterator(MapEntry.Type<E, KT, VT> value, EnumMap<KT, VT> em) { enumMap = em; type = value; } public boolean hasNext() { int length = enumMap.enumSize; for (; position < length; position++) { if (enumMap.hasMapping[position]) { break; } } return position != length; } @SuppressWarnings("unchecked") public E next() { if (!hasNext()) { throw new NoSuchElementException(); } prePosition = position++; return type.get(new MapEntry(enumMap.keys[prePosition], enumMap.values[prePosition])); } public void remove() { checkStatus(); if (enumMap.hasMapping[prePosition]) { enumMap.remove(enumMap.keys[prePosition]); } prePosition = -1; } @Override @SuppressWarnings("unchecked") public String toString() { if (-1 == prePosition) { return super.toString(); } return type.get( new MapEntry(enumMap.keys[prePosition], enumMap.values[prePosition])).toString(); } private void checkStatus() { if (-1 == prePosition) { throw new IllegalStateException(); } } } private static class EnumMapKeySet<KT extends Enum<KT>, VT> extends AbstractSet<KT> { private final EnumMap<KT, VT> enumMap; EnumMapKeySet(EnumMap<KT, VT> em) { enumMap = em; } @Override public void clear() { enumMap.clear(); } @Override public boolean contains(Object object) { return enumMap.containsKey(object); } @Override @SuppressWarnings("unchecked") public Iterator iterator() { return new EnumMapIterator<KT, KT, VT>( new MapEntry.Type<KT, KT, VT>() { public KT get(MapEntry<KT, VT> entry) { return entry.key; } }, enumMap); } @Override @SuppressWarnings("unchecked") public boolean remove(Object object) { if (contains(object)) { enumMap.remove(object); return true; } return false; } @Override public int size() { return enumMap.size(); } } private static class EnumMapValueCollection<KT extends Enum<KT>, VT> extends AbstractCollection<VT> { private final EnumMap<KT, VT> enumMap; EnumMapValueCollection(EnumMap<KT, VT> em) { enumMap = em; } @Override public void clear() { enumMap.clear(); } @Override public boolean contains(Object object) { return enumMap.containsValue(object); } @SuppressWarnings("unchecked") @Override public Iterator iterator() { return new EnumMapIterator<VT, KT, VT>( new MapEntry.Type<VT, KT, VT>() { public VT get(MapEntry<KT, VT> entry) { return entry.value; } }, enumMap); } @Override public boolean remove(Object object) { if (null == object) { for (int i = 0; i < enumMap.enumSize; i++) { if (enumMap.hasMapping[i] && null == enumMap.values[i]) { enumMap.remove(enumMap.keys[i]); return true; } } } else { for (int i = 0; i < enumMap.enumSize; i++) { if (enumMap.hasMapping[i] && object.equals(enumMap.values[i])) { enumMap.remove(enumMap.keys[i]); return true; } } } return false; } @Override public int size() { return enumMap.size(); } } private static class EnumMapEntryIterator<E, KT extends Enum<KT>, VT> extends EnumMapIterator<E, KT, VT> { EnumMapEntryIterator(MapEntry.Type<E, KT, VT> value, EnumMap<KT, VT> em) { super(value, em); } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } prePosition = position++; return type.get(new Entry<KT, VT>((KT) enumMap.keys[prePosition], (VT) enumMap.values[prePosition], enumMap)); } } private static class EnumMapEntrySet<KT extends Enum<KT>, VT> extends AbstractSet<Map.Entry<KT, VT>> { private final EnumMap<KT, VT> enumMap; EnumMapEntrySet(EnumMap<KT, VT> em) { enumMap = em; } @Override public void clear() { enumMap.clear(); } @Override public boolean contains(Object object) { boolean isEqual = false; if (object instanceof Map.Entry) { Object enumKey = ((Map.Entry) object).getKey(); Object enumValue = ((Map.Entry) object).getValue(); if (enumMap.containsKey(enumKey)) { VT value = enumMap.get(enumKey); isEqual = (value == null ? null == enumValue : value .equals(enumValue)); } } return isEqual; } @Override public Iterator<Map.Entry<KT, VT>> iterator() { return new EnumMapEntryIterator<Map.Entry<KT, VT>, KT, VT>( new MapEntry.Type<Map.Entry<KT, VT>, KT, VT>() { public Map.Entry<KT, VT> get(MapEntry<KT, VT> entry) { return entry; } }, enumMap); } @Override public boolean remove(Object object) { if (contains(object)) { enumMap.remove(((Map.Entry) object).getKey()); return true; } return false; } @Override public int size() { return enumMap.size(); } @Override public Object[] toArray() { Object[] entryArray = new Object[enumMap.size()]; return toArray(entryArray); } @Override public Object[] toArray(Object[] array) { int size = enumMap.size(); int index = 0; Object[] entryArray = array; if (size > array.length) { Class<?> clazz = array.getClass().getComponentType(); entryArray = (Object[]) Array.newInstance(clazz, size); } Iterator<Map.Entry<KT, VT>> iter = iterator(); for (; index < size; index++) { Map.Entry<KT, VT> entry = iter.next(); entryArray[index] = new MapEntry<KT, VT>(entry.getKey(), entry .getValue()); } if (index < array.length) { entryArray[index] = null; } return entryArray; } } /** * Constructs an empty enum map using the given key type. * * @param keyType * the class object of the key type used by this enum map * @throws NullPointerException * if the keyType is null */ public EnumMap(Class<K> keyType) { initialization(keyType); } /** * Constructs an enum map using the same key type as the given enum map and * initially containing the same mappings. * * @param map * the enum map from which this enum map is initialized * @throws NullPointerException * if the map is null */ public EnumMap(EnumMap<K, ? extends V> map) { initialization(map); } /** * Constructs an enum map initialized from the given map. If the given map * is an EnumMap instance, this constructor behaves in the exactly the same * way as {@link EnumMap#EnumMap(EnumMap)}}. Otherwise, the given map at * least should contain one mapping. * * @param map * the map from which this enum map is initialized * @throws IllegalArgumentException * if the map is not an enum map instance and does not contain * any mappings * @throws NullPointerException * if the map is null */ public EnumMap(Map<K, ? extends V> map) { if (map instanceof EnumMap) { initialization((EnumMap<K, V>) map); } else { if (0 == map.size()) { throw new IllegalArgumentException(); } Iterator<K> iter = map.keySet().iterator(); K enumKey = iter.next(); Class clazz = enumKey.getClass(); if (clazz.isEnum()) { initialization(clazz); } else { initialization(clazz.getSuperclass()); } putAllImpl(map); } } /** * Removes all mappings in this map. */ @Override public void clear() { Arrays.fill(values, null); Arrays.fill(hasMapping, false); mappingsCount = 0; } /** * Answers a shallow copy of this map. * * @return a shallow copy of this map */ @Override public EnumMap<K, V> clone() { try { EnumMap<K, V> enumMap = (EnumMap<K, V>) super.clone(); enumMap.initialization(this); return enumMap; } catch (CloneNotSupportedException e) { return null; } } /** * Answers true if this map has a mapping for the given key. * * @param key * the key whose presence in this map is to be tested * @return true if this map has a mapping for the given key. */ @Override public boolean containsKey(Object key) { if (isValidKeyType(key)) { int keyOrdinal = ((Enum) key).ordinal(); return hasMapping[keyOrdinal]; } return false; } /** * Answers true if this map has one or more keys mapped to the given value. * * @param value * the value whose presence in this map is to be tested * @return true if this map has one or more keys mapped to the given value. */ @Override public boolean containsValue(Object value) { if (null == value) { for (int i = 0; i < enumSize; i++) { if (hasMapping[i] && null == values[i]) { return true; } } } else { for (int i = 0; i < enumSize; i++) { if (hasMapping[i] && value.equals(values[i])) { return true; } } } return false; } /** * Answers a {@link Set}} view of the mappings contained in this map. The * returned set complies with the general rule specified in * {@link Map#entrySet()}}. The set's iterator will return the mappings in * the their keys' natural order(the enum constants are declared in this * order) * * @return a set view of the mappings contained in this map. */ @Override public Set<Map.Entry<K, V>> entrySet() { if (null == entrySet) { entrySet = new EnumMapEntrySet<K, V>(this); } return entrySet; } /** * Compares the given object with this map. Answers true if the given object * is equal to this map. * * @param object * the object to be compared with this map * @return true if the given object is equal to this map. */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof EnumMap)) { return super.equals(object); } EnumMap<K, V> enumMap = (EnumMap<K, V>) object; if (keyType != enumMap.keyType || size() != enumMap.size()) { return false; } return Arrays.equals(hasMapping, enumMap.hasMapping) && Arrays.equals(values, enumMap.values); } /** * Answers the value which is mapped to the given key in this map, or null * if this map has no mapping for the given key. * * @param key * the key whose associated value is to be returned * @return the value to which this map maps the given key, or null if this * map has no mapping for the given key. */ @Override @SuppressWarnings("unchecked") public V get(Object key) { if (!isValidKeyType(key)) { return null; } int keyOrdinal = ((Enum) key).ordinal(); return (V) values[keyOrdinal]; } /** * Answers a {@link Set}} view of the keys contained in this map. The * returned set complies with the general rule specified in * {@link Map#keySet()}}. The set's iterator will return the keys in the * their natural order(the enum constants are declared in this order) * * @return a set view of the keys contained in this map. */ @Override public Set<K> keySet() { if (null == keySet) { keySet = new EnumMapKeySet<K, V>(this); } return keySet; } /** * Associates the given value with the given key in this map. If the map * previously had a mapping for this key, the old value is replaced. * * @param key * the key with which the given value is to be associated value * @param value * the value to be associated with the given key * @return the value to which this map maps the given key, or null if this * map has no mapping for the given key. * @throws NullPointerException * if the given key is null */ @Override @SuppressWarnings("unchecked") public V put(K key, V value) { return putImpl(key, value); } /** * Copies all the mappings in the given map to this map. These mappings will * replace all mappings that this map had for all of the keys currently in * the given map. * * @param map * the key whose presence in this map is to be tested * @throws NullPointerException * if the given map is null, or if one or more keys in the given * map are null */ @Override @SuppressWarnings("unchecked") public void putAll(Map<? extends K, ? extends V> map) { putAllImpl(map); } /** * Removes the mapping for this key from this map if it is present. * * @param key * the key whose mapping is to be removed from this map * @return the previous value associated with the given key, or null if this * map has no mapping for this key. */ @Override @SuppressWarnings("unchecked") public V remove(Object key) { if (!isValidKeyType(key)) { return null; } int keyOrdinal = ((Enum) key).ordinal(); if (hasMapping[keyOrdinal]) { hasMapping[keyOrdinal] = false; mappingsCount--; } V oldValue = (V) values[keyOrdinal]; values[keyOrdinal] = null; return oldValue; } /** * Answers the number of the mappings in this map. * * @return the number of the mappings in this map */ @Override public int size() { return mappingsCount; } /** * Answers a {@link Collection}} view of the values contained in this map. * The returned collection complys with the general rule specified in * {@link Map#values()}}. The collection's iterator will return the values * in the their corresponding keys' natural order(the enum constants are * declared in this order) * * @return a collection view of the mappings contained in this map. */ @Override public Collection<V> values() { if (null == valuesCollection) { valuesCollection = new EnumMapValueCollection<K, V>(this); } return valuesCollection; } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); initialization(keyType); int elementCount = stream.readInt(); Enum<K> enumKey; Object value; for (int i = elementCount; i > 0; i--) { enumKey = (Enum<K>) stream.readObject(); value = stream.readObject(); putImpl((K) enumKey, (V) value); } } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(mappingsCount); Iterator<Map.Entry<K, V>> iterator = entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<K, V> entry = iterator.next(); stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } private boolean isValidKeyType(Object key) { if (null != key && keyType.isInstance(key)) { return true; } return false; } @SuppressWarnings("unchecked") private void initialization(EnumMap enumMap) { keyType = enumMap.keyType; keys = enumMap.keys; enumSize = enumMap.enumSize; values = enumMap.values.clone(); hasMapping = enumMap.hasMapping.clone(); mappingsCount = enumMap.mappingsCount; } private void initialization(Class<K> type) { keyType = type; keys = keyType.getEnumConstants(); enumSize = keys.length; values = new Object[enumSize]; hasMapping = new boolean[enumSize]; } @SuppressWarnings("unchecked") private void putAllImpl(Map map) { Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); putImpl((K) entry.getKey(), (V) entry.getValue()); } } @SuppressWarnings("unchecked") private V putImpl(K key, V value) { if (null == key) { throw new NullPointerException(); } if (!isValidKeyType(key)) { throw new ClassCastException(); } int keyOrdinal = key.ordinal(); if (!hasMapping[keyOrdinal]) { hasMapping[keyOrdinal] = true; mappingsCount++; } V oldValue = (V) values[keyOrdinal]; values[keyOrdinal] = value; return oldValue; } }
package org.testobject.kernel.imgproc.segmentation; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.testobject.commons.util.image.Image; /* * - TODO may use 256 color images instead of real color (creating indexed images seems to be quite expensive) * - TODO transitive thresholds: may merge pixels with diffs > 0 * - TODO check if all screenshots could be handled with default settings (0.6,10000,20) * */ public class Segmentation { private static int[] segment_image(BufferedImage im, float sigma, double c, int min_size) throws IOException { int width = im.getWidth(); int height = im.getHeight(); float[][] r_im = new float[height][width]; float[][] g_im = new float[height][width]; float[][] b_im = new float[height][width]; // smooth each color channel for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgb = im.getRGB(x, y); r_im[y][x] = ((rgb >> 16) & 0xff); g_im[y][x] = ((rgb >> 8) & 0xff); b_im[y][x] = ((rgb >> 0) & 0xff); } } long startSmoothing = System.currentTimeMillis(); Filter.smooth(r_im, width, height, sigma); Filter.smooth(g_im, width, height, sigma); Filter.smooth(b_im, width, height, sigma); System.out.println("Smoothing: " + (System.currentTimeMillis() - startSmoothing)); int[] a = new int[width * height * 4]; int[] b = new int[width * height * 4]; double[] w = new double[width * height * 4]; int _a; int _b; double _w; int num = 0; int numEnd = (width * height * 4) - 1; for (int y = 0; y < height; y++) { float[] r_row_0 = y > 0 ? r_im[y - 1] : null; float[] g_row_0 = y > 0 ? g_im[y - 1] : null; float[] b_row_0 = y > 0 ? b_im[y - 1] : null; float[] r_row_1 = r_im[y]; float[] g_row_1 = g_im[y]; float[] b_row_1 = b_im[y]; float[] r_row_2 = y < height - 1 ? r_im[y + 1] : null; float[] g_row_2 = y < height - 1 ? g_im[y + 1] : null; float[] b_row_2 = y < height - 1 ? b_im[y + 1] : null; for (int x = 0; x < width; x++) { float r0 = r_row_1[x]; float g0 = g_row_1[x]; float b0 = b_row_1[x]; if (x < width - 1) { _a = y * width + x; _b = y * width + (x + 1); _w = diff(r0, r_row_1[x + 1], g0, g_row_1[x + 1], b0, b_row_1[x + 1]); if (_w != 0) { a[num] = _a; b[num] = _b; w[num] = _w; num++; } else { a[numEnd] = _a; b[numEnd] = _b; w[numEnd] = _w; numEnd--; } } if (y < height - 1) { _a = y * width + x; _b = (y + 1) * width + x; _w = diff(r0, r_row_2[x], g0, g_row_2[x], b0, b_row_2[x]); if (_w != 0) { a[num] = _a; b[num] = _b; w[num] = _w; num++; } else { a[numEnd] = _a; b[numEnd] = _b; w[numEnd] = _w; numEnd--; } } if ((x < width - 1) && (y < height - 1)) { _a = y * width + x; _b = (y + 1) * width + (x + 1); _w = diff(r0, r_row_2[x + 1], g0, g_row_2[x + 1], b0, b_row_2[x + 1]); if (_w != 0) { a[num] = _a; b[num] = _b; w[num] = _w; num++; } else { a[numEnd] = _a; b[numEnd] = _b; w[numEnd] = _w; numEnd--; } } if ((x < width - 1) && (y > 0)) { _a = y * width + x; _b = (y - 1) * width + (x + 1); _w = diff(r0, r_row_0[x + 1], g0, g_row_0[x + 1], b0, b_row_0[x + 1]); if (_w != 0) { a[num] = _a; b[num] = _b; w[num] = _w; num++; } else { a[numEnd] = _a; b[numEnd] = _b; w[numEnd] = _w; numEnd--; } } } } IntroSort.sort(a, b, w, 0, num - 1); // init thresholds double[] threshold = new double[height * width]; Arrays.fill(threshold, c); // segment // make a disjoint-set forest int[] p = new int[height * width]; int[] rank = new int[height * width]; int[] size = new int[height * width]; for (int i = 0; i < p.length; i++) { p[i] = i; size[i] = 1; } for (int i = (width * height * 4) - 1; i >= numEnd; i--) { int a_tmp = find(p, a[i]); int b_tmp = find(p, b[i]); double w_tmp = w[i]; if (a_tmp != b_tmp) { join(rank, size, p, a_tmp, b_tmp); a_tmp = find(p, a_tmp); threshold[a_tmp] = w_tmp + threshold(size[a_tmp], c); } } // for each edge, in non-decreasing weight order... for (int i = 0; i < num; i++) { // components conected by this edge int a_tmp = find(p, a[i]); int b_tmp = find(p, b[i]); double w_tmp = w[i]; if (a_tmp != b_tmp) { if ((w_tmp <= threshold[a_tmp]) && (w_tmp <= threshold[b_tmp])) { join(rank, size, p, a_tmp, b_tmp); a_tmp = find(p, a_tmp); threshold[a_tmp] = w_tmp + threshold(size[a_tmp], c); } } } // post process small components for (int i = 0; i < num; i++) { int a_tmp = find(p, a[i]); int b_tmp = find(p, b[i]); if ((a_tmp != b_tmp) && ((size[a_tmp] < min_size) || (size[b_tmp] < min_size))) { join(rank, size, p, a_tmp, b_tmp); } } return p; } // random color public static Image.Int visualizeSegmentation(BufferedImage input) throws IOException { float sigma = 0.6f; double k = 10000.0f; int min_size = 20; int[] p = segment_image(input, sigma, k, min_size); int height = input.getHeight(); int width = input.getWidth(); Image.Int output = new Image.Int(width, height); // pick random colors for each component int[] colors = new int[width * height]; for (int i = 0; i < width * height; i++) { colors[i] = random_rgb(); } for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int comp = find(p, y * width + x); output.pixels[y * width + x] = colors[comp]; } } return output; } private static int random_rgb() { Random random = new Random(); int r = random.nextInt(256); int g = random.nextInt(256); int b = random.nextInt(256); return ((255 & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0); } public static double threshold(int size, double c) { return c / size; } private static final double diff(double r0, double r1, double g0, double g1, double b0, double b1) { return Math.sqrt((r0 - r1) * (r0 - r1) + (g0 - g1) * (g0 - g1) + (b0 - b1) * (b0 - b1)); } private static final void join(int[] rank, int[] size, int[] p, int x, int y) { if (rank[x] > rank[y]) { mergeYintoX(size, p, x, y); } else { mergeXintoY(rank, size, p, x, y); } } private static final void mergeYintoX(int[] size, int[] p, int x, int y) { p[y] = x; size[x] += size[y]; } private static final void mergeXintoY(int[] rank, int[] size, int[] p, int x, int y) { p[x] = y; size[y] += size[x]; if (rank[x] == rank[y]) { rank[y]++; } } private static final int find(int[] p, int x) { int y = x; while (y != p[y]) { y = p[y]; } p[x] = y; return y; } }
/** * Copyright (C) FuseSource, Inc. * http://fusesource.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 io.fabric8.internal; import io.fabric8.api.BootstrapComplete; import io.fabric8.api.Container; import io.fabric8.api.CreateEnsembleOptions; import io.fabric8.api.DataStoreRegistrationHandler; import io.fabric8.api.FabricException; import io.fabric8.api.FabricService; import io.fabric8.api.ServiceLocator; import io.fabric8.api.ZooKeeperClusterBootstrap; import io.fabric8.api.jcip.ThreadSafe; import io.fabric8.api.scr.AbstractComponent; import io.fabric8.api.scr.Configurer; import io.fabric8.api.scr.ValidatingReference; import io.fabric8.utils.BundleUtils; import io.fabric8.zookeeper.bootstrap.BootstrapConfiguration; import io.fabric8.zookeeper.bootstrap.DataStoreBootstrapTemplate; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.component.ComponentContext; /** * ZooKeeperClusterBootstrap * |_ ConfigurationAdmin * |_ DataStoreRegistrationHandler (@see DataStoreManager) * |_ BootstrapConfiguration (@see BootstrapConfiguration) */ @ThreadSafe @Component(name = "io.fabric8.zookeeper.cluster.bootstrap", label = "Fabric8 ZooKeeper Cluster Bootstrap", immediate = true, metatype = false) @Service(ZooKeeperClusterBootstrap.class) public final class ZooKeeperClusterBootstrapImpl extends AbstractComponent implements ZooKeeperClusterBootstrap { @Reference private Configurer configurer; @Reference(referenceInterface = ConfigurationAdmin.class) private final ValidatingReference<ConfigurationAdmin> configAdmin = new ValidatingReference<ConfigurationAdmin>(); @Reference(referenceInterface = DataStoreRegistrationHandler.class) private final ValidatingReference<DataStoreRegistrationHandler> registrationHandler = new ValidatingReference<DataStoreRegistrationHandler>(); @Reference(referenceInterface = BootstrapConfiguration.class) private final ValidatingReference<BootstrapConfiguration> bootstrapConfiguration = new ValidatingReference<BootstrapConfiguration>(); @Property(name = "name", label = "Container Name", description = "The name of the container", value = "${karaf.name}") private String name; @Property(name = "home", label = "Container Home", description = "The home directory of the container", value = "${karaf.home}") private String home; @Property(name = "data", label = "Container Data", description = "The data directory of the container", value = "${karaf.data}") private String data; private BundleContext bundleContext; @Activate void activate(BundleContext bundleContext, Map<String, ?> configuration) throws Exception { this.bundleContext = bundleContext; this.configurer.configure(configuration, this); BootstrapConfiguration bootConfig = bootstrapConfiguration.get(); CreateEnsembleOptions options = bootConfig.getBootstrapOptions(); if (options.isEnsembleStart()) { startBundles(options); } activateComponent(); } @Deactivate void deactivate() { deactivateComponent(); } @Override public void create(CreateEnsembleOptions options) { assertValid(); try { // Wait for bootstrap to be complete ServiceLocator.awaitService(bundleContext, BootstrapComplete.class); stopBundles(); DataStoreRegistrationHandler regHandler = registrationHandler.get(); BootstrapConfiguration bootConfig = bootstrapConfiguration.get(); BundleContext syscontext = bundleContext.getBundle(0).getBundleContext(); if (options.isClean()) { bootConfig = cleanInternal(syscontext, bootConfig, regHandler); } BootstrapCreateHandler createHandler = new BootstrapCreateHandler(bootConfig, regHandler); createHandler.bootstrapFabric(name, home, options); startBundles(options); long startTime = System.currentTimeMillis(); createHandler.waitForContainerAlive(name, syscontext, options.getBootstrapTimeout()); if (options.isWaitForProvision() && options.isAgentEnabled()) { long currentTime = System.currentTimeMillis(); createHandler.waitForSuccessfulDeploymentOf(name, syscontext, options.getBootstrapTimeout() - (currentTime - startTime)); } } catch (RuntimeException rte) { throw rte; } catch (Exception ex) { throw new FabricException("Unable to create zookeeper server configuration", ex); } } private BootstrapConfiguration cleanInternal(final BundleContext syscontext, BootstrapConfiguration bootConfig, DataStoreRegistrationHandler registrationHandler) throws TimeoutException { try { Configuration[] configs = configAdmin.get().listConfigurations("(|(service.factoryPid=io.fabric8.zookeeper.server)(service.pid=io.fabric8.zookeeper))"); File karafData = new File(data); // Setup the listener for unregistration of {@link BootstrapConfiguration} final CountDownLatch unregisterLatch = new CountDownLatch(1); ServiceListener listener = new ServiceListener() { @Override public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.UNREGISTERING) { syscontext.removeServiceListener(this); unregisterLatch.countDown(); } } }; syscontext.addServiceListener(listener, "(objectClass=" + BootstrapConfiguration.class.getName() + ")"); // Disable the BootstrapConfiguration component ComponentContext componentContext = bootConfig.getComponentContext(); componentContext.disableComponent(BootstrapConfiguration.COMPONENT_NAME); if (!unregisterLatch.await(30, TimeUnit.SECONDS)) throw new TimeoutException("Timeout for unregistering BootstrapConfiguration service"); // Do the cleanup registrationHandler.removeRegistrationCallback(); cleanConfigurations(configs); cleanZookeeperDirectory(karafData); cleanGitDirectory(karafData); // Setup the registration listener for the new {@link BootstrapConfiguration} final CountDownLatch registerLatch = new CountDownLatch(1); final AtomicReference<ServiceReference<?>> sref = new AtomicReference<ServiceReference<?>>(); listener = new ServiceListener() { @Override public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.REGISTERED) { syscontext.removeServiceListener(this); sref.set(event.getServiceReference()); registerLatch.countDown(); } } }; syscontext.addServiceListener(listener, "(objectClass=" + BootstrapConfiguration.class.getName() + ")"); // Enable the {@link BootstrapConfiguration} component and await the registration of the respective service componentContext.enableComponent(BootstrapConfiguration.COMPONENT_NAME); if (!registerLatch.await(30, TimeUnit.SECONDS)) throw new TimeoutException("Timeout for registering BootstrapConfiguration service"); return (BootstrapConfiguration) syscontext.getService(sref.get()); } catch (RuntimeException rte) { throw rte; } catch (TimeoutException toe) { throw toe; } catch (Exception ex) { throw new FabricException("Unable to delete zookeeper configuration", ex); } } private void cleanConfigurations(Configuration[] configs) throws IOException, InvalidSyntaxException { if (configs != null && configs.length > 0) { for (Configuration config : configs) { config.delete(); } } } private void cleanZookeeperDirectory(File karafData) throws IOException { File zkdir = new File(karafData, "zookeeper"); if (zkdir.isDirectory()) { File renamed = new File(karafData, "zookeeper." + System.currentTimeMillis()); if (!zkdir.renameTo(renamed)) { throw new IOException("Cannot rename zookeeper data dir for removal: " + zkdir); } delete(renamed); } } private void cleanGitDirectory(File karafData) throws IOException { File gitdir = new File(karafData, "git"); if (gitdir.isDirectory()) { File renamed = new File(karafData, "git." + System.currentTimeMillis()); if (!gitdir.renameTo(renamed)) { throw new IOException("Cannot rename git data dir for removal: " + gitdir); } delete(renamed); } } private void stopBundles() throws BundleException { BundleUtils bundleUtils = new BundleUtils(bundleContext); bundleUtils.findAndStopBundle("io.fabric8.fabric-agent"); } private void startBundles(CreateEnsembleOptions options) throws BundleException { BundleUtils bundleUtils = new BundleUtils(bundleContext); Bundle agentBundle = bundleUtils.findBundle("io.fabric8.fabric-agent"); if (agentBundle != null && options.isAgentEnabled()) { agentBundle.start(); } } private static void delete(File dir) { if (dir.isDirectory()) { for (File child : dir.listFiles()) { delete(child); } } if (dir.exists()) { dir.delete(); } } void bindConfigAdmin(ConfigurationAdmin service) { this.configAdmin.bind(service); } void unbindConfigAdmin(ConfigurationAdmin service) { this.configAdmin.unbind(service); } void bindBootstrapConfiguration(BootstrapConfiguration service) { this.bootstrapConfiguration.bind(service); } void unbindBootstrapConfiguration(BootstrapConfiguration service) { this.bootstrapConfiguration.unbind(service); } void bindRegistrationHandler(DataStoreRegistrationHandler service) { this.registrationHandler.bind(service); } void unbindRegistrationHandler(DataStoreRegistrationHandler service) { this.registrationHandler.unbind(service); } /** * This static bootstrap create handler does not have access to the {@link ZooKeeperClusterBootstrap} state. * It operates on the state that it is given, which is unrelated to this component. */ static class BootstrapCreateHandler { private final BootstrapConfiguration bootConfig; private final DataStoreRegistrationHandler registrationHandler; BootstrapCreateHandler(BootstrapConfiguration bootConfig, DataStoreRegistrationHandler registrationHandler) { this.bootConfig = bootConfig; this.registrationHandler = registrationHandler; } void bootstrapFabric(String karafName, String karafHome, CreateEnsembleOptions options) throws IOException { String connectionUrl = bootConfig.getConnectionUrl(options); registrationHandler.setRegistrationCallback(new DataStoreBootstrapTemplate(karafName, karafHome, connectionUrl, options)); bootConfig.createOrUpdateDataStoreConfig(options); bootConfig.createZooKeeeperServerConfig(options); bootConfig.createZooKeeeperClientConfig(connectionUrl, options); } private void waitForContainerAlive(String containerName, BundleContext syscontext, long timeout) throws TimeoutException { System.out.println(String.format("Waiting for container: %s", containerName)); Exception lastException = null; long startedAt = System.currentTimeMillis(); while (!Thread.interrupted() && System.currentTimeMillis() < startedAt + timeout) { ServiceReference<FabricService> sref = syscontext.getServiceReference(FabricService.class); FabricService fabricService = sref != null ? syscontext.getService(sref) : null; try { Container container = fabricService != null ? fabricService.getContainer(containerName) : null; if (container != null && container.isAlive()) { return; } else { Thread.sleep(500); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); lastException = ex; } catch (Exception ex) { lastException = ex; } } TimeoutException toex = new TimeoutException("Cannot create container in time"); if (lastException != null) { toex.initCause(lastException); } throw toex; } private void waitForSuccessfulDeploymentOf(String containerName, BundleContext syscontext, long timeout) throws TimeoutException { System.out.println(String.format("Waiting for container %s to provision.", containerName)); Exception lastException = null; long startedAt = System.currentTimeMillis(); while (!Thread.interrupted() && System.currentTimeMillis() < startedAt + timeout) { ServiceReference<FabricService> sref = syscontext.getServiceReference(FabricService.class); FabricService fabricService = sref != null ? syscontext.getService(sref) : null; try { Container container = fabricService != null ? fabricService.getContainer(containerName) : null; if (container != null && container.isAlive() && "success".equals(container.getProvisionStatus())) { return; } else { Thread.sleep(500); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); lastException = ex; } catch (Exception ex) { lastException = ex; } } TimeoutException toex = new TimeoutException("Cannot provision container in time"); if (lastException != null) { toex.initCause(lastException); } throw toex; } } }
/* * * 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.util.*; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.KSMetaData; import org.apache.cassandra.config.Schema; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.locator.SimpleStrategy; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.db.composites.*; import org.apache.cassandra.db.filter.ColumnSlice; import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.utils.SearchIterator; public class ArrayBackedSortedColumnsTest { private static final String KEYSPACE1 = "ArrayBackedSortedColumnsTest"; private static final String CF_STANDARD1 = "Standard1"; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE1, SimpleStrategy.class, KSMetaData.optsWithRF(1), SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD1)); } @Test public void testAdd() { testAddInternal(false); testAddInternal(true); } private CFMetaData metadata() { return Schema.instance.getCFMetaData(KEYSPACE1, CF_STANDARD1); } private void testAddInternal(boolean reversed) { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily map = ArrayBackedSortedColumns.factory.create(metadata(), reversed); int[] values = new int[]{ 1, 2, 2, 3 }; for (int i = 0; i < values.length; ++i) map.addColumn(new BufferCell(type.makeCellName(values[reversed ? values.length - 1 - i : i]))); Iterator<Cell> iter = map.iterator(); assertEquals("1st column", 1, iter.next().name().toByteBuffer().getInt(0)); assertEquals("2nd column", 2, iter.next().name().toByteBuffer().getInt(0)); assertEquals("3rd column", 3, iter.next().name().toByteBuffer().getInt(0)); } @Test public void testOutOfOrder() { testAddOutOfOrder(false); testAddOutOfOrder(false); } private void testAddOutOfOrder(boolean reversed) { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily cells = ArrayBackedSortedColumns.factory.create(metadata(), reversed); int[] values = new int[]{ 1, 2, 1, 3, 4, 4, 5, 5, 1, 2, 6, 6, 6, 1, 2, 3 }; for (int i = 0; i < values.length; ++i) cells.addColumn(new BufferCell(type.makeCellName(values[reversed ? values.length - 1 - i : i]))); assertEquals(6, cells.getColumnCount()); Iterator<Cell> iter = cells.iterator(); assertEquals(1, iter.next().name().toByteBuffer().getInt(0)); assertEquals(2, iter.next().name().toByteBuffer().getInt(0)); assertEquals(3, iter.next().name().toByteBuffer().getInt(0)); assertEquals(4, iter.next().name().toByteBuffer().getInt(0)); assertEquals(5, iter.next().name().toByteBuffer().getInt(0)); assertEquals(6, iter.next().name().toByteBuffer().getInt(0)); // Add more values values = new int[]{ 11, 15, 12, 12, 12, 16, 10, 8, 8, 7, 4, 4, 5 }; for (int i = 0; i < values.length; ++i) cells.addColumn(new BufferCell(type.makeCellName(values[reversed ? values.length - 1 - i : i]))); assertEquals(13, cells.getColumnCount()); iter = cells.reverseIterator(); assertEquals(16, iter.next().name().toByteBuffer().getInt(0)); assertEquals(15, iter.next().name().toByteBuffer().getInt(0)); assertEquals(12, iter.next().name().toByteBuffer().getInt(0)); assertEquals(11, iter.next().name().toByteBuffer().getInt(0)); assertEquals(10, iter.next().name().toByteBuffer().getInt(0)); assertEquals(8, iter.next().name().toByteBuffer().getInt(0)); assertEquals(7, iter.next().name().toByteBuffer().getInt(0)); assertEquals(6, iter.next().name().toByteBuffer().getInt(0)); assertEquals(5, iter.next().name().toByteBuffer().getInt(0)); assertEquals(4, iter.next().name().toByteBuffer().getInt(0)); assertEquals(3, iter.next().name().toByteBuffer().getInt(0)); assertEquals(2, iter.next().name().toByteBuffer().getInt(0)); assertEquals(1, iter.next().name().toByteBuffer().getInt(0)); } @Test public void testGetColumn() { testGetColumnInternal(true); testGetColumnInternal(false); } private void testGetColumnInternal(boolean reversed) { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily cells = ArrayBackedSortedColumns.factory.create(metadata(), reversed); int[] values = new int[]{ -1, 20, 44, 55, 27, 27, 17, 1, 9, 89, 33, 44, 0, 9 }; for (int i = 0; i < values.length; ++i) cells.addColumn(new BufferCell(type.makeCellName(values[reversed ? values.length - 1 - i : i]))); for (int i : values) assertEquals(i, cells.getColumn(type.makeCellName(i)).name().toByteBuffer().getInt(0)); } @Test public void testAddAll() { testAddAllInternal(false); testAddAllInternal(true); } private void testAddAllInternal(boolean reversed) { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily map = ArrayBackedSortedColumns.factory.create(metadata(), reversed); ColumnFamily map2 = ArrayBackedSortedColumns.factory.create(metadata(), reversed); int[] values1 = new int[]{ 1, 3, 5, 6 }; int[] values2 = new int[]{ 2, 4, 5, 6 }; for (int i = 0; i < values1.length; ++i) map.addColumn(new BufferCell(type.makeCellName(values1[reversed ? values1.length - 1 - i : i]))); for (int i = 0; i < values2.length; ++i) map2.addColumn(new BufferCell(type.makeCellName(values2[reversed ? values2.length - 1 - i : i]))); map2.addAll(map); Iterator<Cell> iter = map2.iterator(); assertEquals("1st column", 1, iter.next().name().toByteBuffer().getInt(0)); assertEquals("2nd column", 2, iter.next().name().toByteBuffer().getInt(0)); assertEquals("3rd column", 3, iter.next().name().toByteBuffer().getInt(0)); assertEquals("4st column", 4, iter.next().name().toByteBuffer().getInt(0)); assertEquals("5st column", 5, iter.next().name().toByteBuffer().getInt(0)); assertEquals("6st column", 6, iter.next().name().toByteBuffer().getInt(0)); } @Test public void testGetCollection() { testGetCollectionInternal(false); testGetCollectionInternal(true); } private void testGetCollectionInternal(boolean reversed) { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily map = ArrayBackedSortedColumns.factory.create(metadata(), reversed); int[] values = new int[]{ 1, 2, 3, 5, 9 }; List<Cell> sorted = new ArrayList<>(); for (int v : values) sorted.add(new BufferCell(type.makeCellName(v))); List<Cell> reverseSorted = new ArrayList<>(sorted); Collections.reverse(reverseSorted); for (int i = 0; i < values.length; ++i) map.addColumn(new BufferCell(type.makeCellName(values[reversed ? values.length - 1 - i : i]))); assertSame(sorted, map.getSortedColumns()); assertSame(reverseSorted, map.getReverseSortedColumns()); } @Test public void testIterator() { testIteratorInternal(false); //testIteratorInternal(true); } private void testIteratorInternal(boolean reversed) { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily map = ArrayBackedSortedColumns.factory.create(metadata(), reversed); int[] values = new int[]{ 1, 2, 3, 5, 9 }; for (int i = 0; i < values.length; ++i) map.addColumn(new BufferCell(type.makeCellName(values[reversed ? values.length - 1 - i : i]))); assertSame(new int[]{ 3, 2, 1 }, map.reverseIterator(new ColumnSlice[]{ new ColumnSlice(type.make(3), Composites.EMPTY) })); assertSame(new int[]{ 3, 2, 1 }, map.reverseIterator(new ColumnSlice[]{ new ColumnSlice(type.make(4), Composites.EMPTY) })); assertSame(map.iterator(), map.iterator(ColumnSlice.ALL_COLUMNS_ARRAY)); } @Test public void testSearchIterator() { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily map = ArrayBackedSortedColumns.factory.create(metadata(), false); int[] values = new int[]{ 1, 2, 3, 5, 9, 15, 21, 22 }; for (int i = 0; i < values.length; ++i) map.addColumn(new BufferCell(type.makeCellName(values[i]))); SearchIterator<CellName, Cell> iter = map.searchIterator(); for (int i = 0 ; i < values.length ; i++) assertSame(values[i], iter.next(type.makeCellName(values[i]))); iter = map.searchIterator(); for (int i = 0 ; i < values.length ; i+=2) assertSame(values[i], iter.next(type.makeCellName(values[i]))); iter = map.searchIterator(); for (int i = 0 ; i < values.length ; i+=4) assertSame(values[i], iter.next(type.makeCellName(values[i]))); iter = map.searchIterator(); for (int i = 0 ; i < values.length ; i+=1) { if (i % 2 == 0) { Cell cell = iter.next(type.makeCellName(values[i] - 1)); if (i > 0 && values[i - 1] == values[i] - 1) assertSame(values[i - 1], cell); else assertNull(cell); } } } private <T> void assertSame(Iterable<T> c1, Iterable<T> c2) { assertSame(c1.iterator(), c2.iterator()); } private <T> void assertSame(Iterator<T> iter1, Iterator<T> iter2) { while (iter1.hasNext() && iter2.hasNext()) assertEquals(iter1.next(), iter2.next()); if (iter1.hasNext() || iter2.hasNext()) fail("The collection don't have the same size"); } private void assertSame(int name, Cell cell) { int value = ByteBufferUtil.toInt(cell.name().toByteBuffer()); assert name == value : "Expected " + name + " but got " + value; } private void assertSame(int[] names, Iterator<Cell> iter) { for (int name : names) { assert iter.hasNext() : "Expected " + name + " but no more result"; int value = ByteBufferUtil.toInt(iter.next().name().toByteBuffer()); assert name == value : "Expected " + name + " but got " + value; } } @Test public void testRemove() { testRemoveInternal(false); testRemoveInternal(true); } private void testRemoveInternal(boolean reversed) { CellNameType type = new SimpleDenseCellNameType(Int32Type.instance); ColumnFamily map = ArrayBackedSortedColumns.factory.create(metadata(), reversed); int[] values = new int[]{ 1, 2, 2, 3 }; for (int i = 0; i < values.length; ++i) map.addColumn(new BufferCell(type.makeCellName(values[reversed ? values.length - 1 - i : i]))); Iterator<Cell> iter = map.getReverseSortedColumns().iterator(); assertTrue(iter.hasNext()); iter.next(); iter.remove(); assertTrue(iter.hasNext()); iter.next(); iter.remove(); assertTrue(iter.hasNext()); iter.next(); iter.remove(); assertTrue(!iter.hasNext()); } }
package org.apereo.cas.support.oauth.web.endpoints; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URIBuilder; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.PrincipalException; import org.apereo.cas.authentication.principal.PrincipalFactory; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.authentication.principal.ServiceFactory; import org.apereo.cas.authentication.principal.WebApplicationService; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.services.RegisteredServiceAccessStrategyUtils; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.services.UnauthorizedServiceException; import org.apereo.cas.support.oauth.OAuth20Constants; import org.apereo.cas.support.oauth.OAuth20ResponseTypes; import org.apereo.cas.support.oauth.authenticator.OAuth20CasAuthenticationBuilder; import org.apereo.cas.support.oauth.profile.OAuth20ProfileScopeToAttributesFilter; import org.apereo.cas.support.oauth.services.OAuthRegisteredService; import org.apereo.cas.support.oauth.util.OAuth20Utils; import org.apereo.cas.support.oauth.validator.OAuth20Validator; import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenRequestDataHolder; import org.apereo.cas.support.oauth.web.views.ConsentApprovalViewResolver; import org.apereo.cas.ticket.TicketGrantingTicket; import org.apereo.cas.ticket.accesstoken.AccessToken; import org.apereo.cas.ticket.accesstoken.AccessTokenFactory; import org.apereo.cas.ticket.code.OAuthCode; import org.apereo.cas.ticket.code.OAuthCodeFactory; import org.apereo.cas.ticket.registry.TicketRegistry; import org.apereo.cas.util.EncodingUtils; import org.apereo.cas.web.support.CookieRetrievingCookieGenerator; import org.apereo.cas.web.support.CookieUtils; import org.apereo.cas.web.support.WebUtils; import org.pac4j.core.context.J2EContext; import org.pac4j.core.profile.CommonProfile; import org.pac4j.core.profile.ProfileManager; import org.pac4j.core.profile.UserProfile; import org.pac4j.core.util.CommonHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Stream; /** * This controller is in charge of responding to the authorize call in OAuth v2 protocol. * This url is protected by a CAS authentication. It returns an OAuth code or directly an access token. * * @author Jerome Leleu * @since 3.5.0 */ public class OAuth20AuthorizeEndpointController extends BaseOAuth20Controller { private static final Logger LOGGER = LoggerFactory.getLogger(OAuth20AuthorizeEndpointController.class); /** * The code factory instance. */ protected OAuthCodeFactory oAuthCodeFactory; /** * The Consent approval view resolver. */ protected final ConsentApprovalViewResolver consentApprovalViewResolver; /** * The Authentication builder. */ protected final OAuth20CasAuthenticationBuilder authenticationBuilder; public OAuth20AuthorizeEndpointController(final ServicesManager servicesManager, final TicketRegistry ticketRegistry, final OAuth20Validator validator, final AccessTokenFactory accessTokenFactory, final PrincipalFactory principalFactory, final ServiceFactory<WebApplicationService> webApplicationServiceServiceFactory, final OAuthCodeFactory oAuthCodeFactory, final ConsentApprovalViewResolver consentApprovalViewResolver, final OAuth20ProfileScopeToAttributesFilter scopeToAttributesFilter, final CasConfigurationProperties casProperties, final CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator, final OAuth20CasAuthenticationBuilder authenticationBuilder) { super(servicesManager, ticketRegistry, validator, accessTokenFactory, principalFactory, webApplicationServiceServiceFactory, scopeToAttributesFilter, casProperties, ticketGrantingTicketCookieGenerator); this.oAuthCodeFactory = oAuthCodeFactory; this.consentApprovalViewResolver = consentApprovalViewResolver; this.authenticationBuilder = authenticationBuilder; } /** * Handle request internal model and view. * * @param request the request * @param response the response * @return the model and view * @throws Exception the exception */ @GetMapping(path = OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.AUTHORIZE_URL) public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final J2EContext context = WebUtils.getPac4jJ2EContext(request, response); final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response); if (!verifyAuthorizeRequest(request) || !isRequestAuthenticated(manager, context)) { LOGGER.error("Authorize request verification failed"); return OAuth20Utils.produceUnauthorizedErrorView(); } final String clientId = context.getRequestParameter(OAuth20Constants.CLIENT_ID); final OAuthRegisteredService registeredService = getRegisteredServiceByClientId(clientId); try { RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(clientId, registeredService); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); return OAuth20Utils.produceUnauthorizedErrorView(); } final ModelAndView mv = this.consentApprovalViewResolver.resolve(context, registeredService); if (!mv.isEmpty() && mv.hasView()) { return mv; } return redirectToCallbackRedirectUrl(manager, registeredService, context, clientId); } /** * Gets registered service by client id. * * @param clientId the client id * @return the registered service by client id */ protected OAuthRegisteredService getRegisteredServiceByClientId(final String clientId) { return OAuth20Utils.getRegisteredOAuthService(this.servicesManager, clientId); } private static boolean isRequestAuthenticated(final ProfileManager manager, final J2EContext context) { final Optional<CommonProfile> opt = manager.get(true); return opt.isPresent(); } /** * Redirect to callback redirect url model and view. * * @param manager the manager * @param registeredService the registered service * @param context the context * @param clientId the client id * @return the model and view * @throws Exception the exception */ protected ModelAndView redirectToCallbackRedirectUrl(final ProfileManager manager, final OAuthRegisteredService registeredService, final J2EContext context, final String clientId) throws Exception { final Optional<UserProfile> profile = manager.get(true); if (profile == null || !profile.isPresent()) { LOGGER.error("Unexpected null profile from profile manager. Request is not fully authenticated."); return OAuth20Utils.produceUnauthorizedErrorView(); } final Service service = this.authenticationBuilder.buildService(registeredService, context, false); LOGGER.debug("Created service [{}] based on registered service [{}]", service, registeredService); final Authentication authentication = this.authenticationBuilder.build(profile.get(), registeredService, context, service); LOGGER.debug("Created OAuth authentication [{}] for service [{}]", service, authentication); try { RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService(service, registeredService, authentication); } catch (final UnauthorizedServiceException | PrincipalException e) { LOGGER.error(e.getMessage(), e); return OAuth20Utils.produceUnauthorizedErrorView(); } final String redirectUri = context.getRequestParameter(OAuth20Constants.REDIRECT_URI); LOGGER.debug("Authorize request verification successful for client [{}] with redirect uri [{}]", clientId, redirectUri); final String responseType = context.getRequestParameter(OAuth20Constants.RESPONSE_TYPE); final TicketGrantingTicket ticketGrantingTicket = CookieUtils.getTicketGrantingTicketFromRequest( ticketGrantingTicketCookieGenerator, this.ticketRegistry, context.getRequest()); final String callbackUrl; if (OAuth20Utils.isResponseType(responseType, OAuth20ResponseTypes.CODE)) { callbackUrl = buildCallbackUrlForAuthorizationCodeResponseType(authentication, service, redirectUri, ticketGrantingTicket); } else if (OAuth20Utils.isResponseType(responseType, OAuth20ResponseTypes.TOKEN)) { final AccessTokenRequestDataHolder holder = new AccessTokenRequestDataHolder(service, authentication, registeredService, ticketGrantingTicket); callbackUrl = buildCallbackUrlForImplicitTokenResponseType(holder, redirectUri); } else { callbackUrl = buildCallbackUrlForTokenResponseType(context, authentication, service, redirectUri, responseType, clientId); } LOGGER.debug("Callback URL to redirect: [{}]", callbackUrl); if (StringUtils.isBlank(callbackUrl)) { return OAuth20Utils.produceUnauthorizedErrorView(); } return OAuth20Utils.redirectTo(callbackUrl); } /** * Build callback url for token response type string. * * @param context the context * @param authentication the authentication * @param service the service * @param redirectUri the redirect uri * @param responseType the response type * @param clientId the client id * @return the callback url */ protected String buildCallbackUrlForTokenResponseType(final J2EContext context, final Authentication authentication, final Service service, final String redirectUri, final String responseType, final String clientId) { return null; } private String buildCallbackUrlForImplicitTokenResponseType(final AccessTokenRequestDataHolder holder, final String redirectUri) throws Exception { final AccessToken accessToken = generateAccessToken(holder); LOGGER.debug("Generated OAuth access token: [{}]", accessToken); return buildCallbackUrlResponseType(holder.getAuthentication(), holder.getService(), redirectUri, accessToken, Collections.emptyList()); } /** * Build callback url response type string. * * @param authentication the authentication * @param service the service * @param redirectUri the redirect uri * @param accessToken the access token * @param params the params * @return the string * @throws Exception the exception */ protected String buildCallbackUrlResponseType(final Authentication authentication, final Service service, final String redirectUri, final AccessToken accessToken, final List<NameValuePair> params) throws Exception { final String state = authentication.getAttributes().get(OAuth20Constants.STATE).toString(); final String nonce = authentication.getAttributes().get(OAuth20Constants.NONCE).toString(); final URIBuilder builder = new URIBuilder(redirectUri); final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(OAuth20Constants.ACCESS_TOKEN) .append('=') .append(accessToken.getId()) .append('&') .append(OAuth20Constants.TOKEN_TYPE) .append('=') .append(OAuth20Constants.TOKEN_TYPE_BEARER) .append('&') .append(OAuth20Constants.EXPIRES_IN) .append('=') .append(casProperties.getTicket().getTgt().getTimeToKillInSeconds()); params.forEach(p -> stringBuilder.append('&') .append(p.getName()) .append('=') .append(p.getValue())); if (StringUtils.isNotBlank(state)) { stringBuilder.append('&') .append(OAuth20Constants.STATE) .append('=') .append(EncodingUtils.urlEncode(state)); } if (StringUtils.isNotBlank(nonce)) { stringBuilder.append('&') .append(OAuth20Constants.NONCE) .append('=') .append(EncodingUtils.urlEncode(nonce)); } builder.setFragment(stringBuilder.toString()); final String url = builder.toString(); return url; } private String buildCallbackUrlForAuthorizationCodeResponseType(final Authentication authentication, final Service service, final String redirectUri, final TicketGrantingTicket ticketGrantingTicket) { final OAuthCode code = this.oAuthCodeFactory.create(service, authentication, ticketGrantingTicket); LOGGER.debug("Generated OAuth code: [{}]", code); this.ticketRegistry.addTicket(code); final String state = authentication.getAttributes().get(OAuth20Constants.STATE).toString(); final String nonce = authentication.getAttributes().get(OAuth20Constants.NONCE).toString(); String callbackUrl = redirectUri; callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.CODE, code.getId()); if (StringUtils.isNotBlank(state)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.STATE, state); } if (StringUtils.isNotBlank(nonce)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.NONCE, nonce); } return callbackUrl; } /** * Verify the authorize request. * * @param request the HTTP request * @return whether the authorize request is valid */ private boolean verifyAuthorizeRequest(final HttpServletRequest request) { final boolean checkParameterExist = this.validator.checkParameterExist(request, OAuth20Constants.CLIENT_ID) && this.validator.checkParameterExist(request, OAuth20Constants.REDIRECT_URI) && this.validator.checkParameterExist(request, OAuth20Constants.RESPONSE_TYPE); final String responseType = request.getParameter(OAuth20Constants.RESPONSE_TYPE); final String clientId = request.getParameter(OAuth20Constants.CLIENT_ID); final String redirectUri = request.getParameter(OAuth20Constants.REDIRECT_URI); final OAuthRegisteredService registeredService = getRegisteredServiceByClientId(clientId); return checkParameterExist && checkResponseTypes(responseType, OAuth20ResponseTypes.values()) && this.validator.checkServiceValid(registeredService) && this.validator.checkCallbackValid(registeredService, redirectUri); } /** * Check the response type against expected response types. * * @param type the current response type * @param expectedTypes the expected response types * @return whether the response type is supported */ private boolean checkResponseTypes(final String type, final OAuth20ResponseTypes... expectedTypes) { LOGGER.debug("Response type: [{}]", type); final boolean checked = Stream.of(expectedTypes).anyMatch(t -> OAuth20Utils.isResponseType(type, t)); if (!checked) { LOGGER.error("Unsupported response type: [{}]", type); } return checked; } }
/* * Copyright (C) 2011 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.flightmap.parsing.faa.nfd.tools; import java.util.LinkedHashMap; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; /** * Analyzes ARINC 424-18 file and prints record statistics. * */ public class NfdAnalyzer { // Command line options private final static Options OPTIONS = new Options(); private final static String HELP_OPTION = "help"; private final static String NFD_OPTION = "nfd"; // IATA to ICAO pattern regex private final static Pattern volRecordPattern = Pattern.compile("VOL.{129}"); private final static Pattern hdrRecordPattern = Pattern.compile("(?:HDR|EOF)(\\d).{128}"); private final static Pattern dataRecordPattern = Pattern.compile("(S|T)(.{3})(\\S).{127}"); static { // Command Line options definitions OPTIONS.addOption("h", "help", false, "Print this message."); OPTIONS.addOption(OptionBuilder.withLongOpt(NFD_OPTION) .withDescription("FAA National Flight Database.") .hasArg() .isRequired() .withArgName("nfd.dat") .create()); } private final File nfd; /** * @param nfd Source database in ARINC 424-18 format (eg NFD) */ public NfdAnalyzer(final File nfd) { this.nfd = nfd; } public static void main(String args[]) { CommandLine line = null; try { final CommandLineParser parser = new PosixParser(); line = parser.parse(OPTIONS, args); } catch (ParseException pEx) { System.err.println(pEx.getMessage()); printHelp(line); System.exit(1); } if (line.hasOption(HELP_OPTION)) { printHelp(line); System.exit(0); } final String nfdPath = line.getOptionValue(NFD_OPTION); final File nfd = new File(nfdPath); try { (new NfdAnalyzer(nfd)).execute(); } catch (IOException ioEx) { ioEx.printStackTrace(); System.exit(2); } } private static void printHelp(final CommandLine line) { final HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp("NfdParser", OPTIONS, true); } private void execute() throws IOException { final BufferedReader in = new BufferedReader(new FileReader(nfd)); NfdFileStats stats = new NfdFileStats(); String line; Matcher m; try { while ((line = in.readLine()) != null) { ++stats.totalLines; // Handle generic data record m = dataRecordPattern.matcher(line); if (m.matches()) { processDataRecord(m, stats); continue; } // Handle header record m = hdrRecordPattern.matcher(line); if (m.matches()) { processHdrRecord(m, stats); continue; } // Handle volume header record m = volRecordPattern.matcher(line); if (m.matches()) { processVolRecord(m, stats); continue; } // Else, handle unknown record processUnknownRecord(line, stats); } // Display results of analysis printStats(stats); } finally { in.close(); } } /** * Updates {@code stats} with unknown record corresponding to read {@code line}. */ private void processUnknownRecord(final String line, final NfdFileStats s) { s.unknownRecords.put(s.totalLines, line); } /** * Updates {@code stats} with volume header record matched by {@link #volRecordPattern}. */ private void processVolRecord(final Matcher m, final NfdFileStats s) { ++s.totalRecords; ++s.volRecords; } /** * Updates {@code stats} with header record matched by {@link #hdrRecordPattern}. */ private void processHdrRecord(final Matcher m, final NfdFileStats s) { ++s.totalRecords; ++s.hdrRecords; } /** * Updates {@code stats} with data record matched by {@link #dataRecordPattern}. */ private void processDataRecord(final Matcher m, final NfdFileStats s) { ++s.totalRecords; final String type = m.group(1); final String area = m.group(2); final String secCode = m.group(3); // Increment area count Integer count = s.recordsPerArea.get(area); if (count == null) count = 0; count = count + 1; s.recordsPerArea.put(area, count); // Increment section count Character subCode = m.group(0).charAt(5); if (subCode.equals(' ') && (secCode.equals("P") || secCode.equals("H"))) { subCode = m.group(0).charAt(12); } if (!NfdFileStats.isValidCategory(secCode, subCode)) { processUnknownRecord(m.group(0), s); return; } Map<Character, Integer> recordsPerSubsection = s.recordsPerSection.get(secCode); if (recordsPerSubsection == null) { recordsPerSubsection = new TreeMap<Character, Integer>(); s.recordsPerSection.put(secCode, recordsPerSubsection); count = 0; } else { count = recordsPerSubsection.get(subCode); if (count == null) count = 0; } count = count + 1; recordsPerSubsection.put(subCode, count); ++s.dataRecords; } /** * Prints results from {@code s} in a nice format. */ private void printStats(final NfdFileStats s) { System.out.println("Lines read: " + s.totalLines); System.out.println("Records"); System.out.println(" Vol: " + s.volRecords); System.out.println(" Hdr: " + s.hdrRecords); System.out.println(" Data: " + s.dataRecords); System.out.println(" Unknown: " + s.unknownRecords.size()); for (Map.Entry<Integer, String> unknownEntry: s.unknownRecords.entrySet()) { final Integer lineCount = unknownEntry.getKey(); final String line = unknownEntry.getValue(); System.out.println(" l." + lineCount + ": " + line); } System.out.println("Areas"); for (Map.Entry<String, Integer> areaEntry: s.recordsPerArea.entrySet()) { final String area = areaEntry.getKey(); final Integer count = areaEntry.getValue(); System.out.println(" " + area + ": " + count); } System.out.println("Categories"); for (Map.Entry<String, Map<Character, Integer>> secEntry: s.recordsPerSection.entrySet()) { final String sec = secEntry.getKey(); final String secLabel = NfdFileStats.getLabel(sec, null); System.out.println(" " + sec + " (" + secLabel + ")"); for (Map.Entry<Character, Integer> subEntry: secEntry.getValue().entrySet()) { final Character sub = subEntry.getKey(); final String subLabel = NfdFileStats.getLabel(sec, sub); final Integer count = subEntry.getValue(); System.out.println(" " + sub + " (" + subLabel + "): " + count); } } } /** * Data holder class for NFD file stats. */ private static final class NfdFileStats { /** * Maps section codes to their label. */ final static Map<String, String> SEC_LABELS; /** * Maps section codes to subsection codes to their label. */ final static Map<String, Map<Character, String>> SUB_LABELS; static { SEC_LABELS = new LinkedHashMap<String, String>(); SEC_LABELS.put("A", "MORA"); SEC_LABELS.put("D", "Navaid"); SEC_LABELS.put("E", "Enroute"); SEC_LABELS.put("H", "Heliport"); SEC_LABELS.put("P", "Airport"); SEC_LABELS.put("R", "Company Routes"); SEC_LABELS.put("T", "Tables"); SEC_LABELS.put("U", "Airspace"); SUB_LABELS = new LinkedHashMap<String, Map<Character, String>>(); final Map<Character, String> moraSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("A", moraSubLabels); moraSubLabels.put('S', "Grid MORA"); final Map<Character, String> navaidSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("D", navaidSubLabels); navaidSubLabels.put(' ', "VHF Navaid"); navaidSubLabels.put('B', "NDB Navaid"); final Map<Character, String> enrouteSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("E", enrouteSubLabels); enrouteSubLabels.put('A', "Waypoints"); enrouteSubLabels.put('M', "Airway Markers"); enrouteSubLabels.put('P', "Holding Patterns"); enrouteSubLabels.put('R', "Airways and Routes"); enrouteSubLabels.put('T', "Preferred Routes"); enrouteSubLabels.put('U', "Airway Restrictions"); enrouteSubLabels.put('V', "Communications"); final Map<Character, String> heliportSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("H", heliportSubLabels); heliportSubLabels.put('A', "Pads"); heliportSubLabels.put('C', "Terminal Waypoints"); heliportSubLabels.put('D', "SIDs"); heliportSubLabels.put('E', "STARs"); heliportSubLabels.put('F', "Approach Procedures"); heliportSubLabels.put('K', "TAA"); heliportSubLabels.put('S', "MSA"); heliportSubLabels.put('V', "Communications"); final Map<Character, String> airportSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("P", airportSubLabels); airportSubLabels.put('A', "Reference Points"); airportSubLabels.put('B', "Gates"); airportSubLabels.put('C', "Terminal Waypoints"); airportSubLabels.put('D', "SIDs"); airportSubLabels.put('E', "STARs"); airportSubLabels.put('F', "Approach Procedures"); airportSubLabels.put('G', "Runways"); airportSubLabels.put('I', "Localizer/Glide Slope"); airportSubLabels.put('K', "TAA"); airportSubLabels.put('L', "MLS"); airportSubLabels.put('M', "Localizer Marker"); airportSubLabels.put('N', "Terminal NDB"); airportSubLabels.put('P', "Path Point"); airportSubLabels.put('R', "Flt Planning ARR/DEP"); airportSubLabels.put('S', "MSA"); airportSubLabels.put('T', "GLS Station"); airportSubLabels.put('V', "Communications"); final Map<Character, String> companyRoutesSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("R", companyRoutesSubLabels); companyRoutesSubLabels.put(' ', "Company Routes"); companyRoutesSubLabels.put('A', "Alternate Records"); final Map<Character, String> tablesSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("T", tablesSubLabels); tablesSubLabels.put('C', "Cruising Tables"); tablesSubLabels.put('G', "Geographical Reference"); tablesSubLabels.put('N', "RNAV Name Table"); final Map<Character, String> airspaceSubLabels = new LinkedHashMap<Character, String>(); SUB_LABELS.put("U", airspaceSubLabels); airspaceSubLabels.put('C', "Controlled Airspace"); airspaceSubLabels.put('F', "FIR/UIR"); airspaceSubLabels.put('R', "Restrictive Airspace"); } /** * Number of lines read in file. */ int totalLines; /** * Number of records read in file. */ int totalRecords; /** * Number of volume header records found in file. */ int volRecords; /** * Number of header records found in file. */ int hdrRecords; /** * Number of data records found in file. */ int dataRecords; /** * Maps section code and subsection code to the number of corresponding records found. */ Map<String, Map<Character, Integer>> recordsPerSection; // Sec code -> Sub code -> Count /** * Maps area/customer codes to the number of corresponding records found. */ Map<String, Integer> recordsPerArea; /** * Maps line numbers to their text for lines that corresponded to unknown records. */ SortedMap<Integer, String> unknownRecords; NfdFileStats() { recordsPerSection = new TreeMap<String, Map<Character, Integer>>(); recordsPerArea = new TreeMap<String, Integer>(); unknownRecords = new TreeMap<Integer, String>(); } /** * Returns label for section {@code sec} and (optionaly) subsection {@code sub}. * * @param sec Section code, MUST NOT be {@code null}. * @param sub Subsection code, MAY be {@code null}. * @return If {@code sub} is {@code null}, the label corresponding to section {@code sec}. * Otherwise, the label of subsection {@code sub} in section {@code sec}. */ static String getLabel(final String sec, final Character sub) { if (sub == null) { return SEC_LABELS.get(sec); } return SUB_LABELS.get(sec).get(sub); } /** * Checks if the given section and (optionaly) subsection codes are valid. * @param sec Section code * @param sub Subsection code * @return If {@code sub} is {@code null}: {@code true} if section {@code sec} is valid. If * {@code sub} is not {@code null}: {@code true} is the corresponding section and subsection are * valid. Otherwise, {@code false}. */ static boolean isValidCategory(final String sec, final Character sub) { try { final String label = getLabel(sec, sub); return label != null; } catch (Exception ex) { return false; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: com/google/protobuf/outer_class_name_test.proto package protobuf_unittest; public final class OuterClassNameTestOuterClass { private OuterClassNameTestOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface OuterClassNameTestOrBuilder extends // @@protoc_insertion_point(interface_extends:protobuf_unittest.OuterClassNameTest) com.google.protobuf.MessageOrBuilder { } /** * Protobuf type {@code protobuf_unittest.OuterClassNameTest} * * <pre> * This message's name is the same with the default outer class name of this * proto file. It's used to test if the compiler can avoid this conflict * correctly. * </pre> */ public static final class OuterClassNameTest extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:protobuf_unittest.OuterClassNameTest) OuterClassNameTestOrBuilder { // Use OuterClassNameTest.newBuilder() to construct. private OuterClassNameTest(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private OuterClassNameTest(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final OuterClassNameTest defaultInstance; public static OuterClassNameTest getDefaultInstance() { return defaultInstance; } public OuterClassNameTest getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private OuterClassNameTest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return protobuf_unittest.OuterClassNameTestOuterClass.internal_static_protobuf_unittest_OuterClassNameTest_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return protobuf_unittest.OuterClassNameTestOuterClass.internal_static_protobuf_unittest_OuterClassNameTest_fieldAccessorTable .ensureFieldAccessorsInitialized( protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest.class, protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest.Builder.class); } public static com.google.protobuf.Parser<OuterClassNameTest> PARSER = new com.google.protobuf.AbstractParser<OuterClassNameTest>() { public OuterClassNameTest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new OuterClassNameTest(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<OuterClassNameTest> getParserForType() { return PARSER; } private void initFields() { } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code protobuf_unittest.OuterClassNameTest} * * <pre> * This message's name is the same with the default outer class name of this * proto file. It's used to test if the compiler can avoid this conflict * correctly. * </pre> */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:protobuf_unittest.OuterClassNameTest) protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return protobuf_unittest.OuterClassNameTestOuterClass.internal_static_protobuf_unittest_OuterClassNameTest_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return protobuf_unittest.OuterClassNameTestOuterClass.internal_static_protobuf_unittest_OuterClassNameTest_fieldAccessorTable .ensureFieldAccessorsInitialized( protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest.class, protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest.Builder.class); } // Construct using protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return protobuf_unittest.OuterClassNameTestOuterClass.internal_static_protobuf_unittest_OuterClassNameTest_descriptor; } public protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest getDefaultInstanceForType() { return protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest.getDefaultInstance(); } public protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest build() { protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest buildPartial() { protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest result = new protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest(this); onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest) { return mergeFrom((protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest other) { if (other == protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest.getDefaultInstance()) return this; this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (protobuf_unittest.OuterClassNameTestOuterClass.OuterClassNameTest) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } // @@protoc_insertion_point(builder_scope:protobuf_unittest.OuterClassNameTest) } static { defaultInstance = new OuterClassNameTest(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:protobuf_unittest.OuterClassNameTest) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_protobuf_unittest_OuterClassNameTest_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_protobuf_unittest_OuterClassNameTest_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n/com/google/protobuf/outer_class_name_t" + "est.proto\022\021protobuf_unittest\"\024\n\022OuterCla" + "ssNameTest" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_protobuf_unittest_OuterClassNameTest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_protobuf_unittest_OuterClassNameTest_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_protobuf_unittest_OuterClassNameTest_descriptor, new java.lang.String[] { }); } // @@protoc_insertion_point(outer_class_scope) }
/* * Copyright (C) 2011 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.cache; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.cache.LocalCache.Strength; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; /** * Helper class for creating {@link CacheBuilder} instances with all combinations of several sets of * parameters. * * @author mike nonemacher */ class CacheBuilderFactory { // Default values contain only 'null', which means don't call the CacheBuilder method (just give // the CacheBuilder default). private Set<Integer> concurrencyLevels = Sets.newHashSet((Integer) null); private Set<Integer> initialCapacities = Sets.newHashSet((Integer) null); private Set<Integer> maximumSizes = Sets.newHashSet((Integer) null); private Set<DurationSpec> expireAfterWrites = Sets.newHashSet((DurationSpec) null); private Set<DurationSpec> expireAfterAccesses = Sets.newHashSet((DurationSpec) null); private Set<DurationSpec> refreshes = Sets.newHashSet((DurationSpec) null); private Set<Strength> keyStrengths = Sets.newHashSet((Strength) null); private Set<Strength> valueStrengths = Sets.newHashSet((Strength) null); CacheBuilderFactory withConcurrencyLevels(Set<Integer> concurrencyLevels) { this.concurrencyLevels = Sets.newLinkedHashSet(concurrencyLevels); return this; } CacheBuilderFactory withInitialCapacities(Set<Integer> initialCapacities) { this.initialCapacities = Sets.newLinkedHashSet(initialCapacities); return this; } CacheBuilderFactory withMaximumSizes(Set<Integer> maximumSizes) { this.maximumSizes = Sets.newLinkedHashSet(maximumSizes); return this; } CacheBuilderFactory withExpireAfterWrites(Set<DurationSpec> durations) { this.expireAfterWrites = Sets.newLinkedHashSet(durations); return this; } CacheBuilderFactory withExpireAfterAccesses(Set<DurationSpec> durations) { this.expireAfterAccesses = Sets.newLinkedHashSet(durations); return this; } CacheBuilderFactory withRefreshes(Set<DurationSpec> durations) { this.refreshes = Sets.newLinkedHashSet(durations); return this; } CacheBuilderFactory withKeyStrengths(Set<Strength> keyStrengths) { this.keyStrengths = Sets.newLinkedHashSet(keyStrengths); Preconditions.checkArgument(!this.keyStrengths.contains(Strength.SOFT)); return this; } CacheBuilderFactory withValueStrengths(Set<Strength> valueStrengths) { this.valueStrengths = Sets.newLinkedHashSet(valueStrengths); return this; } Iterable<CacheBuilder<Object, Object>> buildAllPermutations() { @SuppressWarnings("unchecked") Iterable<List<Object>> combinations = buildCartesianProduct( concurrencyLevels, initialCapacities, maximumSizes, expireAfterWrites, expireAfterAccesses, refreshes, keyStrengths, valueStrengths); return Iterables.transform( combinations, new Function<List<Object>, CacheBuilder<Object, Object>>() { @Override public CacheBuilder<Object, Object> apply(List<Object> combination) { return createCacheBuilder( (Integer) combination.get(0), (Integer) combination.get(1), (Integer) combination.get(2), (DurationSpec) combination.get(3), (DurationSpec) combination.get(4), (DurationSpec) combination.get(5), (Strength) combination.get(6), (Strength) combination.get(7)); } }); } private static final Function<Object, Optional<?>> NULLABLE_TO_OPTIONAL = new Function<Object, Optional<?>>() { @Override public Optional<?> apply(@CheckForNull Object obj) { return Optional.fromNullable(obj); } }; private static final Function<Optional<?>, Object> OPTIONAL_TO_NULLABLE = new Function<Optional<?>, Object>() { @Override public Object apply(Optional<?> optional) { return optional.orNull(); } }; /** * Sets.cartesianProduct doesn't allow sets that contain null, but we want null to mean "don't * call the associated CacheBuilder method" - that is, get the default CacheBuilder behavior. This * method wraps the elements in the input sets (which may contain null) as Optionals, calls * Sets.cartesianProduct with those, then transforms the result to unwrap the Optionals. */ private Iterable<List<Object>> buildCartesianProduct(Set<?>... sets) { List<Set<Optional<?>>> optionalSets = Lists.newArrayListWithExpectedSize(sets.length); for (Set<?> set : sets) { Set<Optional<?>> optionalSet = Sets.newLinkedHashSet(Iterables.transform(set, NULLABLE_TO_OPTIONAL)); optionalSets.add(optionalSet); } Set<List<Optional<?>>> cartesianProduct = Sets.cartesianProduct(optionalSets); return Iterables.transform( cartesianProduct, new Function<List<Optional<?>>, List<Object>>() { @Override public List<Object> apply(List<Optional<?>> objs) { return Lists.transform(objs, OPTIONAL_TO_NULLABLE); } }); } private CacheBuilder<Object, Object> createCacheBuilder( Integer concurrencyLevel, Integer initialCapacity, Integer maximumSize, DurationSpec expireAfterWrite, DurationSpec expireAfterAccess, DurationSpec refresh, Strength keyStrength, Strength valueStrength) { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); if (concurrencyLevel != null) { builder.concurrencyLevel(concurrencyLevel); } if (initialCapacity != null) { builder.initialCapacity(initialCapacity); } if (maximumSize != null) { builder.maximumSize(maximumSize); } if (expireAfterWrite != null) { builder.expireAfterWrite(expireAfterWrite.duration, expireAfterWrite.unit); } if (expireAfterAccess != null) { builder.expireAfterAccess(expireAfterAccess.duration, expireAfterAccess.unit); } if (refresh != null) { builder.refreshAfterWrite(refresh.duration, refresh.unit); } if (keyStrength != null) { builder.setKeyStrength(keyStrength); } if (valueStrength != null) { builder.setValueStrength(valueStrength); } return builder; } static class DurationSpec { private final long duration; private final TimeUnit unit; private DurationSpec(long duration, TimeUnit unit) { this.duration = duration; this.unit = unit; } public static DurationSpec of(long duration, TimeUnit unit) { return new DurationSpec(duration, unit); } @Override public int hashCode() { return Objects.hashCode(duration, unit); } @Override public boolean equals(Object o) { if (o instanceof DurationSpec) { DurationSpec that = (DurationSpec) o; return unit.toNanos(duration) == that.unit.toNanos(that.duration); } return false; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("duration", duration) .add("unit", unit) .toString(); } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.mongodb; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.trino.plugin.mongodb.MongoIndex.MongodbIndexKey; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ColumnMetadata; import io.trino.spi.connector.ConnectorInsertTableHandle; import io.trino.spi.connector.ConnectorMetadata; import io.trino.spi.connector.ConnectorNewTableLayout; import io.trino.spi.connector.ConnectorOutputMetadata; import io.trino.spi.connector.ConnectorOutputTableHandle; import io.trino.spi.connector.ConnectorSession; import io.trino.spi.connector.ConnectorTableHandle; import io.trino.spi.connector.ConnectorTableMetadata; import io.trino.spi.connector.ConnectorTableProperties; import io.trino.spi.connector.Constraint; import io.trino.spi.connector.ConstraintApplicationResult; import io.trino.spi.connector.LimitApplicationResult; import io.trino.spi.connector.LocalProperty; import io.trino.spi.connector.NotFoundException; import io.trino.spi.connector.SchemaTableName; import io.trino.spi.connector.SchemaTablePrefix; import io.trino.spi.connector.SortingProperty; import io.trino.spi.connector.TableNotFoundException; import io.trino.spi.predicate.TupleDomain; import io.trino.spi.statistics.ComputedStatistics; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import static com.google.common.base.Preconditions.checkState; import static java.lang.Math.toIntExact; import static java.util.Locale.ENGLISH; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; public class MongoMetadata implements ConnectorMetadata { private static final Logger log = Logger.get(MongoMetadata.class); private final MongoSession mongoSession; private final AtomicReference<Runnable> rollbackAction = new AtomicReference<>(); public MongoMetadata(MongoSession mongoSession) { this.mongoSession = requireNonNull(mongoSession, "mongoSession is null"); } @Override public List<String> listSchemaNames(ConnectorSession session) { return mongoSession.getAllSchemas(); } @Override public MongoTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName) { requireNonNull(tableName, "tableName is null"); try { return mongoSession.getTable(tableName).getTableHandle(); } catch (TableNotFoundException e) { log.debug(e, "Table(%s) not found", tableName); return null; } } @Override public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle tableHandle) { requireNonNull(tableHandle, "tableHandle is null"); SchemaTableName tableName = getTableName(tableHandle); return getTableMetadata(session, tableName); } @Override public List<SchemaTableName> listTables(ConnectorSession session, Optional<String> optionalSchemaName) { List<String> schemaNames = optionalSchemaName.map(ImmutableList::of) .orElseGet(() -> (ImmutableList<String>) listSchemaNames(session)); ImmutableList.Builder<SchemaTableName> tableNames = ImmutableList.builder(); for (String schemaName : schemaNames) { for (String tableName : mongoSession.getAllTables(schemaName)) { tableNames.add(new SchemaTableName(schemaName, tableName.toLowerCase(ENGLISH))); } } return tableNames.build(); } @Override public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) { MongoTableHandle table = (MongoTableHandle) tableHandle; List<MongoColumnHandle> columns = mongoSession.getTable(table.getSchemaTableName()).getColumns(); ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder(); for (MongoColumnHandle columnHandle : columns) { columnHandles.put(columnHandle.getName(), columnHandle); } return columnHandles.build(); } @Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { requireNonNull(prefix, "prefix is null"); ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder(); for (SchemaTableName tableName : listTables(session, prefix)) { try { columns.put(tableName, getTableMetadata(session, tableName).getColumns()); } catch (NotFoundException e) { // table disappeared during listing operation } } return columns.build(); } private List<SchemaTableName> listTables(ConnectorSession session, SchemaTablePrefix prefix) { if (prefix.getTable().isEmpty()) { return listTables(session, prefix.getSchema()); } return ImmutableList.of(prefix.toSchemaTableName()); } @Override public ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle) { return ((MongoColumnHandle) columnHandle).toColumnMetadata(); } @Override public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { mongoSession.createTable(tableMetadata.getTable(), buildColumnHandles(tableMetadata)); } @Override public void dropTable(ConnectorSession session, ConnectorTableHandle tableHandle) { MongoTableHandle table = (MongoTableHandle) tableHandle; mongoSession.dropTable(table.getSchemaTableName()); } @Override public void addColumn(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnMetadata column) { mongoSession.addColumn(((MongoTableHandle) tableHandle).getSchemaTableName(), column); } @Override public void dropColumn(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle column) { mongoSession.dropColumn(((MongoTableHandle) tableHandle).getSchemaTableName(), ((MongoColumnHandle) column).getName()); } @Override public ConnectorOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout) { List<MongoColumnHandle> columns = buildColumnHandles(tableMetadata); mongoSession.createTable(tableMetadata.getTable(), columns); setRollback(() -> mongoSession.dropTable(tableMetadata.getTable())); return new MongoOutputTableHandle( tableMetadata.getTable(), columns.stream().filter(c -> !c.isHidden()).collect(toList())); } @Override public Optional<ConnectorOutputMetadata> finishCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle, Collection<Slice> fragments, Collection<ComputedStatistics> computedStatistics) { clearRollback(); return Optional.empty(); } @Override public ConnectorInsertTableHandle beginInsert(ConnectorSession session, ConnectorTableHandle tableHandle) { MongoTableHandle table = (MongoTableHandle) tableHandle; List<MongoColumnHandle> columns = mongoSession.getTable(table.getSchemaTableName()).getColumns(); return new MongoInsertTableHandle( table.getSchemaTableName(), columns.stream().filter(c -> !c.isHidden()).collect(toList())); } @Override public Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments, Collection<ComputedStatistics> computedStatistics) { return Optional.empty(); } @Override public boolean usesLegacyTableLayouts() { return false; } @Override public ConnectorTableProperties getTableProperties(ConnectorSession session, ConnectorTableHandle table) { MongoTableHandle tableHandle = (MongoTableHandle) table; Optional<Set<ColumnHandle>> partitioningColumns = Optional.empty(); //TODO: sharding key ImmutableList.Builder<LocalProperty<ColumnHandle>> localProperties = ImmutableList.builder(); MongoTable tableInfo = mongoSession.getTable(tableHandle.getSchemaTableName()); Map<String, ColumnHandle> columns = getColumnHandles(session, tableHandle); for (MongoIndex index : tableInfo.getIndexes()) { for (MongodbIndexKey key : index.getKeys()) { if (key.getSortOrder().isEmpty()) { continue; } if (columns.get(key.getName()) != null) { localProperties.add(new SortingProperty<>(columns.get(key.getName()), key.getSortOrder().get())); } } } return new ConnectorTableProperties( TupleDomain.all(), Optional.empty(), partitioningColumns, Optional.empty(), localProperties.build()); } @Override public Optional<LimitApplicationResult<ConnectorTableHandle>> applyLimit(ConnectorSession session, ConnectorTableHandle table, long limit) { MongoTableHandle handle = (MongoTableHandle) table; // MongoDB cursor.limit(0) is equivalent to setting no limit if (limit == 0) { return Optional.empty(); } // MongoDB doesn't support limit number greater than integer max if (limit > Integer.MAX_VALUE) { return Optional.empty(); } if (handle.getLimit().isPresent() && handle.getLimit().getAsInt() <= limit) { return Optional.empty(); } return Optional.of(new LimitApplicationResult<>( new MongoTableHandle(handle.getSchemaTableName(), handle.getConstraint(), OptionalInt.of(toIntExact(limit))), true)); } @Override public Optional<ConstraintApplicationResult<ConnectorTableHandle>> applyFilter(ConnectorSession session, ConnectorTableHandle table, Constraint constraint) { MongoTableHandle handle = (MongoTableHandle) table; TupleDomain<ColumnHandle> oldDomain = handle.getConstraint(); TupleDomain<ColumnHandle> newDomain = oldDomain.intersect(constraint.getSummary()); if (oldDomain.equals(newDomain)) { return Optional.empty(); } handle = new MongoTableHandle( handle.getSchemaTableName(), newDomain, handle.getLimit()); return Optional.of(new ConstraintApplicationResult<>(handle, constraint.getSummary())); } private void setRollback(Runnable action) { checkState(rollbackAction.compareAndSet(null, action), "rollback action is already set"); } private void clearRollback() { rollbackAction.set(null); } public void rollback() { Optional.ofNullable(rollbackAction.getAndSet(null)).ifPresent(Runnable::run); } private static SchemaTableName getTableName(ConnectorTableHandle tableHandle) { return ((MongoTableHandle) tableHandle).getSchemaTableName(); } private ConnectorTableMetadata getTableMetadata(ConnectorSession session, SchemaTableName tableName) { MongoTableHandle tableHandle = mongoSession.getTable(tableName).getTableHandle(); List<ColumnMetadata> columns = ImmutableList.copyOf( getColumnHandles(session, tableHandle).values().stream() .map(MongoColumnHandle.class::cast) .map(MongoColumnHandle::toColumnMetadata) .collect(toList())); return new ConnectorTableMetadata(tableName, columns); } private static List<MongoColumnHandle> buildColumnHandles(ConnectorTableMetadata tableMetadata) { return tableMetadata.getColumns().stream() .map(m -> new MongoColumnHandle(m.getName(), m.getType(), m.isHidden())) .collect(toList()); } }
package com.example.administrator.boomtimer.Adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.administrator.boomtimer.R; import com.example.administrator.boomtimer.model.SelectIconItem; import com.tonicartos.superslim.GridSLM; import com.tonicartos.superslim.LinearSLM; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/9/12. */ public class IconListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final static int VIEW_TYPE_HEADER = 0; private final static int VIEW_TYPE_CONTENT = 1; private static final int LINEAR = 0; private List<SelectIconItem> mItems; private Context mContext; @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view; if (viewType == VIEW_TYPE_HEADER) { view = inflater.inflate(R.layout.item_icon_header, parent, false); return new TextViewHolder(view); } else { view = inflater.inflate(R.layout.item_icon, parent, false); return new ImageViewHolder(view); } } public IconListAdapter(Context mContext) { initDatas(); this.mContext = mContext; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final SelectIconItem item = mItems.get(position); // A content binding implementation. if (holder instanceof TextViewHolder) { ((TextViewHolder) holder).tv.setText(item.getItem()); final GridSLM.LayoutParams params = GridSLM.LayoutParams.from(((TextViewHolder) holder).tv.getLayoutParams()); params.setSlm(LinearSLM.ID); params.width = ViewGroup.LayoutParams.MATCH_PARENT; // Position of the first item in the section. This doesn't have to // be a header. However, if an item is a header, it must then be the // first item in a section. params.setSlm(item.sectionManager == LINEAR ? LinearSLM.ID : GridSLM.ID); params.setColumnWidth(mContext.getResources().getDimensionPixelSize(R.dimen.grid_column_width)); params.setFirstPosition(item.sectionFirstPosition); // holder.bindItem(item.getItem()); } else if (holder instanceof ImageViewHolder){ ((ImageViewHolder) holder).icon.setBackgroundResource(getResId(item.getItem(), R.drawable.class)); final GridSLM.LayoutParams params = GridSLM.LayoutParams.from(((ImageViewHolder) holder).icon.getLayoutParams()); params.setSlm(LinearSLM.ID); if (item.getType() == VIEW_TYPE_HEADER) { params.width = ViewGroup.LayoutParams.MATCH_PARENT; } // Position of the first item in the section. This doesn't have to // be a header. However, if an item is a header, it must then be the // first item in a section. params.setSlm(item.sectionManager == LINEAR ? LinearSLM.ID : GridSLM.ID); params.setColumnWidth(mContext.getResources().getDimensionPixelSize(R.dimen.grid_column_width)); params.setFirstPosition(item.sectionFirstPosition); ((ImageViewHolder) holder).icon.setLayoutParams(params); } } @Override public int getItemCount() { return mItems.size(); } @Override public int getItemViewType(int position) { return mItems.get(position).getType(); } class ImageViewHolder extends RecyclerView.ViewHolder{ ImageView icon; public ImageViewHolder(View view) { super(view); icon = (ImageView) view.findViewById(R.id.select_item_icon); } } class TextViewHolder extends RecyclerView.ViewHolder{ TextView tv; public TextViewHolder(View view) { super(view); tv = (TextView) view.findViewById(R.id.select_icon_text); } } private String one2three(int i) { if (i < 10) { return "00" + i; } else if (i < 100) { return "0" + i; } else { return "" + i; } } public static int getResId(String variableName, Class<?> c) { try { Field idField = c.getDeclaredField(variableName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } } private void initDatas() { int sectionManager = -1; int itemCount = 0; int sectionFirstPosition = 0; mItems = new ArrayList<>(); String[] strings = {"Default", "Eat and Cook", "Family", "Finance and Shopping", "Home and Personal Care", "Music", "Relax and Party", "Sport", "Study", "Transport and Travel"}; SelectIconItem item; SelectIconItem header; for (int i = 0; i < strings.length; i++) { sectionManager = (sectionManager + 1) % 2; switch (i) { case 0: for (int j = 1; j <= 228; j++) { item = new SelectIconItem("cat_" + j, VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 1: for (int j = 1; j <= 74; j++) { item = new SelectIconItem("ec_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 2: for (int j = 1; j <= 56; j++) { item = new SelectIconItem("fam_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 3: for (int j = 1; j <= 43; j++) { item = new SelectIconItem("fs_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 4: for (int j = 1; j <= 108; j++) { item = new SelectIconItem("hpcd_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 5: for (int j = 1; j <= 48; j++) { item = new SelectIconItem("mi_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 6: for (int j = 1; j <= 53; j++) { item = new SelectIconItem("rph_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 7: for (int j = 1; j <= 96; j++) { item = new SelectIconItem("sp_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 8: for (int j = 1; j <= 67; j++) { item = new SelectIconItem("st_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; case 9: for (int j = 1; j <= 59; j++) { item = new SelectIconItem("tt_" + one2three(j), VIEW_TYPE_CONTENT, sectionManager, sectionFirstPosition); mItems.add(item); itemCount++; } break; } sectionFirstPosition = i + itemCount; header = new SelectIconItem(strings[i], VIEW_TYPE_HEADER, sectionManager, sectionFirstPosition); mItems.add(header); } } }
package org.vaadin.elements.impl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Proxy; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.vaadin.elements.Element; import org.vaadin.elements.Elements; import org.vaadin.elements.EventParam; import org.vaadin.elements.Node; import com.vaadin.server.JsonCodec; import com.vaadin.shared.communication.ServerRpc; import com.vaadin.ui.JavaScriptFunction; import elemental.json.JsonArray; public class ElementImpl extends NodeImpl implements Element { public ElementImpl(org.jsoup.nodes.Element node) { super(node); } @Override public void appendChild(Node child) { NodeImpl nodeImpl = (NodeImpl) child; appendSoupNode(nodeImpl); context.adoptAll(nodeImpl); } @Override public void appendHtml(String html) { org.jsoup.nodes.Element element = getElement(); int oldChildCount = element.childNodeSize(); element.append(html); int newChildCount = element.childNodeSize(); for (int i = oldChildCount; i < newChildCount; i++) { org.jsoup.nodes.Element soupChild = element.child(i); NodeImpl node = ElementReflectHelper.wrap(soupChild); context.adopt(node); context.wrapChildren(node); } } void appendSoupNode(NodeImpl child) { getElement().appendChild(child.node); } private org.jsoup.nodes.Element getElement() { return (org.jsoup.nodes.Element) node; } @Override public String getTag() { return getElement().tagName(); } // TODO create a wrapper class instead of using two lists private List<String> evalQueue = new ArrayList<>(); private List<Object[]> evalParamQueue = new ArrayList<>(); private Map<Integer, JavaScriptFunction> callbacks = new HashMap<>(); // Maps event name -> set of attributes private Map<String, Set<String>> boundAttributeQueue = new HashMap<>(); @Override public void setAttribute(String name, String value) { org.jsoup.nodes.Element element = getElement(); if (Objects.equals(value, getAttribute(name))) { return; } if (value == null) { element.removeAttr(name); } else { element.attr(name, value); } RootImpl document = getRoot(); if (document != null) { document.setAttributeChange(this, name); } } @Override public Collection<String> getAttributeNames() { List<String> list = new ArrayList<>(); getElement().attributes().forEach(a -> list.add(a.getKey())); return list; } @Override public String getAttribute(String name) { if (!getElement().hasAttr(name)) { return null; } return getElement().attr(name); } @Override public void setInnerText(String text) { removeAllChildren(); appendChild(Elements.createText(text)); } @Override public void setAttribute(String name, boolean value) { if (value) { setAttribute(name, ""); } else { removeAttribute(name); } } @Override public boolean hasAttribute(String name) { return getElement().hasAttr(name); } @Override public void removeAttribute(String name) { setAttribute(name, null); } @Override public void eval(String script, Object... arguments) { RootImpl document = getRoot(); if (document != null) { document.eval(this, script, arguments); } else { evalQueue.add(script); evalParamQueue.add(arguments); } } void flushCommandQueues() { RootImpl document = getRoot(); assert document != null; if (!evalQueue.isEmpty()) { for (int i = 0; i < evalQueue.size(); i++) { eval(evalQueue.get(i), evalParamQueue.get(i)); } evalQueue.clear(); evalParamQueue.clear(); } if (!boundAttributeQueue.isEmpty()) { boundAttributeQueue.forEach((event, attributes) -> { attributes.forEach(attribute -> document.setAttributeBound(this, attribute, event)); }); boundAttributeQueue.clear(); } } void setCallback(int cid, JavaScriptFunction callback) { callbacks.put(Integer.valueOf(cid), callback); } JavaScriptFunction getCallback(int cid) { return callbacks.get(Integer.valueOf(cid)); } @Override public void bindAttribute(String attributeName, String eventName) { RootImpl document = getRoot(); if (document != null) { document.setAttributeBound(this, attributeName, eventName); } else { Set<String> attributes = boundAttributeQueue.get(eventName); if (attributes == null) { attributes = new HashSet<String>(); boundAttributeQueue.put(eventName, attributes); } attributes.add(attributeName); } } @Override public void addEventListener(String eventName, JavaScriptFunction listener, String... arguments) { String argumentBuilder = String.join(",", arguments); eval("e.addEventListener('" + eventName + "', function (event) { $0(" + argumentBuilder + ") })", listener); } @Override public void addEventListener(EventListener listener) { List<Method> listenerMethods = findInterfaceMethods( listener.getClass()); for (Method method : listenerMethods) { if (method.getDeclaringClass() == Object.class) { // Ignore continue; } String name = method.getName(); if (!name.startsWith("on")) { throw new RuntimeException(method.toString()); } name = name.substring(2).toLowerCase(); if (method.getParameterCount() != 1) { throw new RuntimeException(); } if (method.getReturnType() != void.class) { throw new RuntimeException(); } Map<String, Integer> methodOrder = new HashMap<>(); Class<?> eventType = method.getParameterTypes()[0]; Method[] eventGetters = eventType.getDeclaredMethods(); String[] argumentBuilders = new String[eventGetters.length]; for (int i = 0; i < eventGetters.length; i++) { Method getter = eventGetters[i]; if (getter.getParameterCount() != 0) { throw new RuntimeException(getter.toString()); } String paramName = ElementReflectHelper .getPropertyName(getter.getName()); methodOrder.put(getter.getName(), Integer.valueOf(i)); argumentBuilders[i] = "event." + paramName; } addEventListener(name, new JavaScriptFunction() { @Override public void call(final JsonArray arguments) { InvocationHandler invocationHandler = (proxy, calledMethod, args) -> { if (calledMethod.getDeclaringClass() == Object.class) { // Standard object methods return calledMethod.invoke(proxy, args); } else { String methodName = calledMethod.getName(); int indexOf = methodOrder.get(methodName) .intValue(); return JsonCodec.decodeInternalOrCustomType( calledMethod.getGenericReturnType(), arguments.get(indexOf), null); } }; Object event = Proxy.newProxyInstance( eventType.getClassLoader(), new Class[] { eventType }, invocationHandler); try { method.invoke(listener, event); } catch (Exception e) { throw new RuntimeException(e); } } }, argumentBuilders); } } private List<Method> findInterfaceMethods(Class<?> type) { return Arrays.asList(type.getInterfaces()).stream() .flatMap(iface -> Arrays.asList(iface.getMethods()).stream()) .collect(Collectors.toList()); } @Override public void addEventListener(ServerRpc rpc) { List<Method> interfaceMethods = findInterfaceMethods(rpc.getClass()); for (Method method : interfaceMethods) { String eventName = method.getName().toLowerCase(); String[] arguments = new String[method.getParameterCount()]; Parameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { EventParam eventParam = parameters[i] .getAnnotation(EventParam.class); arguments[i] = "event." + eventParam.value(); } addEventListener(eventName, new JavaScriptFunction() { @Override public void call(JsonArray arguments) { Object[] args = new Object[parameters.length]; for (int i = 0; i < args.length; i++) { // TODO handle null for primitive return types args[i] = JsonCodec.decodeInternalOrCustomType( parameters[i].getParameterizedType(), arguments.get(i), null); } try { method.invoke(rpc, args); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } }, arguments); } } @Override public void setInnerHtml(String html) { removeAllChildren(); getElement().html(html); context.wrapChildren(this); } @Override public Optional<Element> querySelector(String query) { org.jsoup.nodes.Element element = getElement().select(query).first(); if (element == null) { return Optional.empty(); } else { return Optional.of((Element) context.resolve(element)); } } @Override public List<Element> querySelectorAll(String query) { org.jsoup.select.Elements elements = getElement().select(query); return new AbstractList<Element>() { @Override public Element get(int index) { return (Element) context.resolve(elements.get(index)); } @Override public int size() { return elements.size(); } }; } void resetChildren(ArrayList<NodeImpl> newChildren) { HashSet<NodeImpl> oldChildren = new HashSet<>(getChildren()); oldChildren.removeAll(newChildren); oldChildren.forEach(child -> child.node.remove()); getElement().children().remove(); for (NodeImpl child : newChildren) { appendSoupNode(child); } } @Override public void setDisabled(boolean disabled) { setAttribute("disabled", disabled); } @Override public boolean isDisabled() { return hasAttribute("disabled"); } }
package com.jusfoun.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class RoleExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public RoleExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andRoleIdIsNull() { addCriterion("roleId is null"); return (Criteria) this; } public Criteria andRoleIdIsNotNull() { addCriterion("roleId is not null"); return (Criteria) this; } public Criteria andRoleIdEqualTo(Integer value) { addCriterion("roleId =", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotEqualTo(Integer value) { addCriterion("roleId <>", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThan(Integer value) { addCriterion("roleId >", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdGreaterThanOrEqualTo(Integer value) { addCriterion("roleId >=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThan(Integer value) { addCriterion("roleId <", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdLessThanOrEqualTo(Integer value) { addCriterion("roleId <=", value, "roleId"); return (Criteria) this; } public Criteria andRoleIdIn(List<Integer> values) { addCriterion("roleId in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotIn(List<Integer> values) { addCriterion("roleId not in", values, "roleId"); return (Criteria) this; } public Criteria andRoleIdBetween(Integer value1, Integer value2) { addCriterion("roleId between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotBetween(Integer value1, Integer value2) { addCriterion("roleId not between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andRoleNameIsNull() { addCriterion("roleName is null"); return (Criteria) this; } public Criteria andRoleNameIsNotNull() { addCriterion("roleName is not null"); return (Criteria) this; } public Criteria andRoleNameEqualTo(String value) { addCriterion("roleName =", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotEqualTo(String value) { addCriterion("roleName <>", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameGreaterThan(String value) { addCriterion("roleName >", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameGreaterThanOrEqualTo(String value) { addCriterion("roleName >=", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameLessThan(String value) { addCriterion("roleName <", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameLessThanOrEqualTo(String value) { addCriterion("roleName <=", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameLike(String value) { addCriterion("roleName like", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotLike(String value) { addCriterion("roleName not like", value, "roleName"); return (Criteria) this; } public Criteria andRoleNameIn(List<String> values) { addCriterion("roleName in", values, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotIn(List<String> values) { addCriterion("roleName not in", values, "roleName"); return (Criteria) this; } public Criteria andRoleNameBetween(String value1, String value2) { addCriterion("roleName between", value1, value2, "roleName"); return (Criteria) this; } public Criteria andRoleNameNotBetween(String value1, String value2) { addCriterion("roleName not between", value1, value2, "roleName"); return (Criteria) this; } public Criteria andRoleDescIsNull() { addCriterion("roleDesc is null"); return (Criteria) this; } public Criteria andRoleDescIsNotNull() { addCriterion("roleDesc is not null"); return (Criteria) this; } public Criteria andRoleDescEqualTo(String value) { addCriterion("roleDesc =", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescNotEqualTo(String value) { addCriterion("roleDesc <>", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescGreaterThan(String value) { addCriterion("roleDesc >", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescGreaterThanOrEqualTo(String value) { addCriterion("roleDesc >=", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescLessThan(String value) { addCriterion("roleDesc <", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescLessThanOrEqualTo(String value) { addCriterion("roleDesc <=", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescLike(String value) { addCriterion("roleDesc like", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescNotLike(String value) { addCriterion("roleDesc not like", value, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescIn(List<String> values) { addCriterion("roleDesc in", values, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescNotIn(List<String> values) { addCriterion("roleDesc not in", values, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescBetween(String value1, String value2) { addCriterion("roleDesc between", value1, value2, "roleDesc"); return (Criteria) this; } public Criteria andRoleDescNotBetween(String value1, String value2) { addCriterion("roleDesc not between", value1, value2, "roleDesc"); return (Criteria) this; } public Criteria andRoleParentIdIsNull() { addCriterion("roleParentId is null"); return (Criteria) this; } public Criteria andRoleParentIdIsNotNull() { addCriterion("roleParentId is not null"); return (Criteria) this; } public Criteria andRoleParentIdEqualTo(Integer value) { addCriterion("roleParentId =", value, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdNotEqualTo(Integer value) { addCriterion("roleParentId <>", value, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdGreaterThan(Integer value) { addCriterion("roleParentId >", value, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdGreaterThanOrEqualTo(Integer value) { addCriterion("roleParentId >=", value, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdLessThan(Integer value) { addCriterion("roleParentId <", value, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdLessThanOrEqualTo(Integer value) { addCriterion("roleParentId <=", value, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdIn(List<Integer> values) { addCriterion("roleParentId in", values, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdNotIn(List<Integer> values) { addCriterion("roleParentId not in", values, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdBetween(Integer value1, Integer value2) { addCriterion("roleParentId between", value1, value2, "roleParentId"); return (Criteria) this; } public Criteria andRoleParentIdNotBetween(Integer value1, Integer value2) { addCriterion("roleParentId not between", value1, value2, "roleParentId"); return (Criteria) this; } public Criteria andPermissionNameIsNull() { addCriterion("permissionName is null"); return (Criteria) this; } public Criteria andPermissionNameIsNotNull() { addCriterion("permissionName is not null"); return (Criteria) this; } public Criteria andPermissionNameEqualTo(String value) { addCriterion("permissionName =", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameNotEqualTo(String value) { addCriterion("permissionName <>", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameGreaterThan(String value) { addCriterion("permissionName >", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameGreaterThanOrEqualTo(String value) { addCriterion("permissionName >=", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameLessThan(String value) { addCriterion("permissionName <", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameLessThanOrEqualTo(String value) { addCriterion("permissionName <=", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameLike(String value) { addCriterion("permissionName like", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameNotLike(String value) { addCriterion("permissionName not like", value, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameIn(List<String> values) { addCriterion("permissionName in", values, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameNotIn(List<String> values) { addCriterion("permissionName not in", values, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameBetween(String value1, String value2) { addCriterion("permissionName between", value1, value2, "permissionName"); return (Criteria) this; } public Criteria andPermissionNameNotBetween(String value1, String value2) { addCriterion("permissionName not between", value1, value2, "permissionName"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("`status` is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("`status` is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Byte value) { addCriterion("`status` =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Byte value) { addCriterion("`status` <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Byte value) { addCriterion("`status` >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Byte value) { addCriterion("`status` >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Byte value) { addCriterion("`status` <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Byte value) { addCriterion("`status` <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Byte> values) { addCriterion("`status` in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Byte> values) { addCriterion("`status` not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Byte value1, Byte value2) { addCriterion("`status` between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Byte value1, Byte value2) { addCriterion("`status` not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("createTime is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("createTime is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("createTime =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("createTime <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("createTime >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("createTime >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("createTime <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("createTime <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("createTime in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("createTime not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("createTime between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("createTime not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("updateTime is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("updateTime is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("updateTime =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("updateTime <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("updateTime >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("updateTime >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("updateTime <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("updateTime <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("updateTime in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("updateTime not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("updateTime between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("updateTime not between", value1, value2, "updateTime"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table role * * @mbggenerated do_not_delete_during_merge Wed May 24 10:47:32 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table role * * @mbggenerated Wed May 24 10:47:32 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
/* * 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 java.util; /*-[ #import "IOSClass.h" #import "java/lang/NullPointerException.h" ]-*/ /** * Class {@code AbstractCollection} is an abstract implementation of the {@code * Collection} interface. A subclass must implement the abstract methods {@code * iterator()} and {@code size()} to create an immutable collection. To create a * modifiable collection it's necessary to override the {@code add()} method that * currently throws an {@code UnsupportedOperationException}. * * @since 1.2 */ public abstract class AbstractCollection<E> implements Collection<E> { /** * Constructs a new instance of this AbstractCollection. */ protected AbstractCollection() { super(); } public boolean add(E object) { throw new UnsupportedOperationException(); } /** * Attempts to add all of the objects contained in {@code collection} * to the contents of this {@code Collection} (optional). This implementation * iterates over the given {@code Collection} and calls {@code add} for each * element. If any of these calls return {@code true}, then {@code true} is * returned as result of this method call, {@code false} otherwise. If this * {@code Collection} does not support adding elements, an {@code * UnsupportedOperationException} is thrown. * <p> * If the passed {@code Collection} is changed during the process of adding elements * to this {@code Collection}, the behavior depends on the behavior of the passed * {@code Collection}. * * @param collection * the collection of objects. * @return {@code true} if this {@code Collection} is modified, {@code false} * otherwise. * @throws UnsupportedOperationException * if adding to this {@code Collection} is not supported. * @throws ClassCastException * if the class of an object is inappropriate for this * {@code Collection}. * @throws IllegalArgumentException * if an object cannot be added to this {@code Collection}. * @throws NullPointerException * if {@code collection} is {@code null}, or if it contains * {@code null} elements and this {@code Collection} does not support * such elements. */ public boolean addAll(Collection<? extends E> collection) { boolean result = false; Iterator<? extends E> it = collection.iterator(); while (it.hasNext()) { if (add(it.next())) { result = true; } } return result; } /** * Removes all elements from this {@code Collection}, leaving it empty (optional). * This implementation iterates over this {@code Collection} and calls the {@code * remove} method on each element. If the iterator does not support removal * of elements, an {@code UnsupportedOperationException} is thrown. * <p> * Concrete implementations usually can clear a {@code Collection} more efficiently * and should therefore overwrite this method. * * @throws UnsupportedOperationException * it the iterator does not support removing elements from * this {@code Collection} * @see #iterator * @see #isEmpty * @see #size */ public void clear() { Iterator<E> it = iterator(); while (it.hasNext()) { it.next(); it.remove(); } } /** * Tests whether this {@code Collection} contains the specified object. This * implementation iterates over this {@code Collection} and tests, whether any * element is equal to the given object. If {@code object != null} then * {@code object.equals(e)} is called for each element {@code e} returned by * the iterator until the element is found. If {@code object == null} then * each element {@code e} returned by the iterator is compared with the test * {@code e == null}. * * @param object * the object to search for. * @return {@code true} if object is an element of this {@code Collection}, {@code * false} otherwise. * @throws ClassCastException * if the object to look for isn't of the correct type. * @throws NullPointerException * if the object to look for is {@code null} and this * {@code Collection} doesn't support {@code null} elements. */ public boolean contains(Object object) { Iterator<E> it = iterator(); if (object != null) { while (it.hasNext()) { if (object.equals(it.next())) { return true; } } } else { while (it.hasNext()) { if (it.next() == null) { return true; } } } return false; } /** * Tests whether this {@code Collection} contains all objects contained in the * specified {@code Collection}. This implementation iterates over the specified * {@code Collection}. If one element returned by the iterator is not contained in * this {@code Collection}, then {@code false} is returned; {@code true} otherwise. * * @param collection * the collection of objects. * @return {@code true} if all objects in the specified {@code Collection} are * elements of this {@code Collection}, {@code false} otherwise. * @throws ClassCastException * if one or more elements of {@code collection} isn't of the * correct type. * @throws NullPointerException * if {@code collection} contains at least one {@code null} * element and this {@code Collection} doesn't support {@code null} * elements. * @throws NullPointerException * if {@code collection} is {@code null}. */ public boolean containsAll(Collection<?> collection) { Iterator<?> it = collection.iterator(); while (it.hasNext()) { if (!contains(it.next())) { return false; } } return true; } /** * Returns if this {@code Collection} contains no elements. This implementation * tests, whether {@code size} returns 0. * * @return {@code true} if this {@code Collection} has no elements, {@code false} * otherwise. * * @see #size */ public boolean isEmpty() { return size() == 0; } /** * Returns an instance of {@link Iterator} that may be used to access the * objects contained by this {@code Collection}. The order in which the elements are * returned by the {@link Iterator} is not defined unless the instance of the * {@code Collection} has a defined order. In that case, the elements are returned in that order. * <p> * In this class this method is declared abstract and has to be implemented * by concrete {@code Collection} implementations. * * @return an iterator for accessing the {@code Collection} contents. */ public abstract Iterator<E> iterator(); /** * Removes one instance of the specified object from this {@code Collection} if one * is contained (optional). This implementation iterates over this * {@code Collection} and tests for each element {@code e} returned by the iterator, * whether {@code e} is equal to the given object. If {@code object != null} * then this test is performed using {@code object.equals(e)}, otherwise * using {@code object == null}. If an element equal to the given object is * found, then the {@code remove} method is called on the iterator and * {@code true} is returned, {@code false} otherwise. If the iterator does * not support removing elements, an {@code UnsupportedOperationException} * is thrown. * * @param object * the object to remove. * @return {@code true} if this {@code Collection} is modified, {@code false} * otherwise. * @throws UnsupportedOperationException * if removing from this {@code Collection} is not supported. * @throws ClassCastException * if the object passed is not of the correct type. * @throws NullPointerException * if {@code object} is {@code null} and this {@code Collection} * doesn't support {@code null} elements. */ public boolean remove(Object object) { Iterator<?> it = iterator(); if (object != null) { while (it.hasNext()) { if (object.equals(it.next())) { it.remove(); return true; } } } else { while (it.hasNext()) { if (it.next() == null) { it.remove(); return true; } } } return false; } /** * Removes all occurrences in this {@code Collection} of each object in the * specified {@code Collection} (optional). After this method returns none of the * elements in the passed {@code Collection} can be found in this {@code Collection} * anymore. * <p> * This implementation iterates over this {@code Collection} and tests for each * element {@code e} returned by the iterator, whether it is contained in * the specified {@code Collection}. If this test is positive, then the {@code * remove} method is called on the iterator. If the iterator does not * support removing elements, an {@code UnsupportedOperationException} is * thrown. * * @param collection * the collection of objects to remove. * @return {@code true} if this {@code Collection} is modified, {@code false} * otherwise. * @throws UnsupportedOperationException * if removing from this {@code Collection} is not supported. * @throws ClassCastException * if one or more elements of {@code collection} isn't of the * correct type. * @throws NullPointerException * if {@code collection} contains at least one {@code null} * element and this {@code Collection} doesn't support {@code null} * elements. * @throws NullPointerException * if {@code collection} is {@code null}. */ public boolean removeAll(Collection<?> collection) { boolean result = false; Iterator<?> it = iterator(); while (it.hasNext()) { if (collection.contains(it.next())) { it.remove(); result = true; } } return result; } /** * Removes all objects from this {@code Collection} that are not also found in the * {@code Collection} passed (optional). After this method returns this {@code Collection} * will only contain elements that also can be found in the {@code Collection} * passed to this method. * <p> * This implementation iterates over this {@code Collection} and tests for each * element {@code e} returned by the iterator, whether it is contained in * the specified {@code Collection}. If this test is negative, then the {@code * remove} method is called on the iterator. If the iterator does not * support removing elements, an {@code UnsupportedOperationException} is * thrown. * * @param collection * the collection of objects to retain. * @return {@code true} if this {@code Collection} is modified, {@code false} * otherwise. * @throws UnsupportedOperationException * if removing from this {@code Collection} is not supported. * @throws ClassCastException * if one or more elements of {@code collection} * isn't of the correct type. * @throws NullPointerException * if {@code collection} contains at least one * {@code null} element and this {@code Collection} doesn't support * {@code null} elements. * @throws NullPointerException * if {@code collection} is {@code null}. */ public boolean retainAll(Collection<?> collection) { boolean result = false; Iterator<?> it = iterator(); while (it.hasNext()) { if (!collection.contains(it.next())) { it.remove(); result = true; } } return result; } /** * Returns a count of how many objects this {@code Collection} contains. * <p> * In this class this method is declared abstract and has to be implemented * by concrete {@code Collection} implementations. * * @return how many objects this {@code Collection} contains, or {@code Integer.MAX_VALUE} * if there are more than {@code Integer.MAX_VALUE} elements in this * {@code Collection}. */ public abstract int size(); @Override public native Object[] toArray() /*-[ IOSObjectArray *result = [[IOSObjectArray alloc] initWithLength:[self size] type:[IOSClass classWithClass:[NSObject class]]]; #if ! __has_feature(objc_arc) [result autorelease]; #endif return [self toArrayWithNSObjectArray:result]; ]-*/; @Override public native <T> T[] toArray(T[] contents) /*-[ if (!contents) { id exception = [[JavaLangNullPointerException alloc] init]; #if ! __has_feature(objc_arc) [exception autorelease]; #endif @throw exception; return nil; } if ([contents count] < [self size]) { contents = [[IOSObjectArray alloc] initWithLength:[self size] type:[[contents getClass] getComponentType]]; #if ! __has_feature(objc_arc) [contents autorelease]; #endif } NSUInteger i = 0; id<JavaUtilIterator> it = [self iterator]; while ([it hasNext]) { [contents replaceObjectAtIndex:i++ withObject:[it next]]; } return contents; ]-*/; /** * Returns the string representation of this {@code Collection}. The presentation * has a specific format. It is enclosed by square brackets ("[]"). Elements * are separated by ', ' (comma and space). * * @return the string representation of this {@code Collection}. */ @Override public String toString() { if (isEmpty()) { return "[]"; //$NON-NLS-1$ } StringBuilder buffer = new StringBuilder(size() * 16); buffer.append('['); Iterator<?> it = iterator(); while (it.hasNext()) { Object next = it.next(); if (next != this) { buffer.append(next); } else { buffer.append("(this Collection)"); //$NON-NLS-1$ } if (it.hasNext()) { buffer.append(", "); //$NON-NLS-1$ } } buffer.append(']'); return buffer.toString(); } }
/* * 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.geode.internal.cache.execute; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.Logger; import org.apache.geode.cache.Region; import org.apache.geode.cache.client.internal.ProxyCache; import org.apache.geode.cache.client.internal.ServerRegionProxy; import org.apache.geode.cache.client.internal.UserAttributes; import org.apache.geode.cache.execute.Execution; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.internal.cache.TXStateProxyImpl; import org.apache.geode.internal.cache.execute.metrics.FunctionStats; import org.apache.geode.internal.cache.execute.metrics.FunctionStatsManager; import org.apache.geode.internal.cache.execute.util.SynchronizedResultCollector; import org.apache.geode.logging.internal.log4j.api.LogService; /** * Executes Function with FunctionService#onRegion(Region region) in client server mode. * * @see FunctionService#onRegion(Region) * * @since GemFire 5.8 LA */ public class ServerRegionFunctionExecutor extends AbstractExecution { private static final Logger logger = LogService.getLogger(); private final LocalRegion region; private boolean executeOnBucketSet = false; ServerRegionFunctionExecutor(Region r, ProxyCache proxyCache) { if (r == null) { throw new IllegalArgumentException( String.format("The input %s for the execute function request is null", "Region")); } region = (LocalRegion) r; this.proxyCache = proxyCache; } private ServerRegionFunctionExecutor(ServerRegionFunctionExecutor serverRegionFunctionExecutor, Object args) { super(serverRegionFunctionExecutor); region = serverRegionFunctionExecutor.region; filter.clear(); filter.addAll(serverRegionFunctionExecutor.filter); this.args = args; executeOnBucketSet = serverRegionFunctionExecutor.executeOnBucketSet; } private ServerRegionFunctionExecutor(ServerRegionFunctionExecutor serverRegionFunctionExecutor, MemberMappedArgument memberMapargs) { super(serverRegionFunctionExecutor); region = serverRegionFunctionExecutor.region; filter.clear(); filter.addAll(serverRegionFunctionExecutor.filter); memberMappedArg = memberMapargs; executeOnBucketSet = serverRegionFunctionExecutor.executeOnBucketSet; } private ServerRegionFunctionExecutor(ServerRegionFunctionExecutor serverRegionFunctionExecutor, ResultCollector rc) { super(serverRegionFunctionExecutor); region = serverRegionFunctionExecutor.region; filter.clear(); filter.addAll(serverRegionFunctionExecutor.filter); this.rc = rc != null ? new SynchronizedResultCollector(rc) : null; executeOnBucketSet = serverRegionFunctionExecutor.executeOnBucketSet; } private ServerRegionFunctionExecutor(ServerRegionFunctionExecutor serverRegionFunctionExecutor, Set filter2) { super(serverRegionFunctionExecutor); region = serverRegionFunctionExecutor.region; filter.clear(); filter.addAll(filter2); executeOnBucketSet = serverRegionFunctionExecutor.executeOnBucketSet; } private ServerRegionFunctionExecutor(ServerRegionFunctionExecutor serverRegionFunctionExecutor, Set<Integer> bucketsAsFilter, boolean executeOnBucketSet) { super(serverRegionFunctionExecutor); region = serverRegionFunctionExecutor.region; filter.clear(); filter.addAll(bucketsAsFilter); this.executeOnBucketSet = executeOnBucketSet; } @Override public Execution withFilter(Set fltr) { if (fltr == null) { throw new FunctionException( String.format("The input %s for the execute function request is null", "filter")); } executeOnBucketSet = false; return new ServerRegionFunctionExecutor(this, fltr); } @Override public InternalExecution withBucketFilter(Set<Integer> bucketIDs) { if (bucketIDs == null) { throw new FunctionException( String.format("The input %s for the execute function request is null", "buckets as filter")); } return new ServerRegionFunctionExecutor(this, bucketIDs, true /* execute on bucketset */); } @Override protected ResultCollector executeFunction(final Function function, long timeout, TimeUnit unit) { byte hasResult = 0; try { if (proxyCache != null) { if (proxyCache.isClosed()) { throw proxyCache.getCacheClosedException("Cache is closed for this user."); } UserAttributes.userAttributes.set(proxyCache.getUserAttributes()); } if (function.hasResult()) { // have Results final int timeoutMs = TimeoutHelper.toMillis(timeout, unit); hasResult = 1; if (rc == null) { // Default Result Collector ResultCollector defaultCollector = new DefaultResultCollector(); return executeOnServer(function, defaultCollector, hasResult, timeoutMs); } else { // Custome Result COllector return executeOnServer(function, rc, hasResult, timeoutMs); } } else { // No results executeOnServerNoAck(function, hasResult); return new NoResult(); } } finally { UserAttributes.userAttributes.set(null); } } protected ResultCollector executeFunction(final String functionId, boolean resultReq, boolean isHA, boolean optimizeForWrite, long timeout, TimeUnit unit) { try { if (proxyCache != null) { if (proxyCache.isClosed()) { throw proxyCache.getCacheClosedException("Cache is closed for this user."); } UserAttributes.userAttributes.set(proxyCache.getUserAttributes()); } byte hasResult = 0; if (resultReq) { // have Results hasResult = 1; final int timeoutMs = TimeoutHelper.toMillis(timeout, unit); if (rc == null) { // Default Result Collector ResultCollector defaultCollector = new DefaultResultCollector(); return executeOnServer(functionId, defaultCollector, hasResult, isHA, optimizeForWrite, timeoutMs); } else { // Custome Result COllector return executeOnServer(functionId, rc, hasResult, isHA, optimizeForWrite, timeoutMs); } } else { // No results executeOnServerNoAck(functionId, hasResult, isHA, optimizeForWrite); return new NoResult(); } } finally { UserAttributes.userAttributes.set(null); } } private ResultCollector executeOnServer(Function function, ResultCollector collector, byte hasResult, int timeoutMs) throws FunctionException { ServerRegionProxy srp = getServerRegionProxy(); FunctionStats stats = FunctionStatsManager.getFunctionStats(function.getId(), region.getSystem()); long start = stats.startFunctionExecution(true); try { validateExecution(function, null); srp.executeFunction(function, this, collector, hasResult, timeoutMs); stats.endFunctionExecution(start, true); return collector; } catch (FunctionException functionException) { stats.endFunctionExecutionWithException(start, true); throw functionException; } catch (Exception exception) { stats.endFunctionExecutionWithException(start, true); throw new FunctionException(exception); } } private ResultCollector executeOnServer(String functionId, ResultCollector collector, byte hasResult, boolean isHA, boolean optimizeForWrite, int timeoutMs) throws FunctionException { ServerRegionProxy srp = getServerRegionProxy(); FunctionStats stats = FunctionStatsManager.getFunctionStats(functionId, region.getSystem()); long start = stats.startFunctionExecution(true); try { validateExecution(null, null); srp.executeFunction(functionId, this, collector, hasResult, isHA, optimizeForWrite, timeoutMs); stats.endFunctionExecution(start, true); return collector; } catch (FunctionException functionException) { stats.endFunctionExecutionWithException(start, true); throw functionException; } catch (Exception exception) { stats.endFunctionExecutionWithException(start, true); throw new FunctionException(exception); } } private void executeOnServerNoAck(Function function, byte hasResult) throws FunctionException { ServerRegionProxy srp = getServerRegionProxy(); FunctionStats stats = FunctionStatsManager.getFunctionStats(function.getId(), region.getSystem()); long start = stats.startFunctionExecution(false); try { validateExecution(function, null); srp.executeFunctionNoAck(region.getFullPath(), function, this, hasResult); stats.endFunctionExecution(start, false); } catch (FunctionException functionException) { stats.endFunctionExecutionWithException(start, false); throw functionException; } catch (Exception exception) { stats.endFunctionExecutionWithException(start, false); throw new FunctionException(exception); } } private void executeOnServerNoAck(String functionId, byte hasResult, boolean isHA, boolean optimizeForWrite) throws FunctionException { ServerRegionProxy srp = getServerRegionProxy(); FunctionStats stats = FunctionStatsManager.getFunctionStats(functionId, region.getSystem()); long start = stats.startFunctionExecution(false); try { validateExecution(null, null); srp.executeFunctionNoAck(region.getFullPath(), functionId, this, hasResult, isHA, optimizeForWrite); stats.endFunctionExecution(start, false); } catch (FunctionException functionException) { stats.endFunctionExecutionWithException(start, false); throw functionException; } catch (Exception exception) { stats.endFunctionExecutionWithException(start, false); throw new FunctionException(exception); } } private ServerRegionProxy getServerRegionProxy() throws FunctionException { ServerRegionProxy srp = region.getServerProxy(); if (srp != null) { if (logger.isDebugEnabled()) { logger.debug("Found server region proxy on region. RegionName: {}", region.getName()); } return srp; } else { String message = srp + ": " + "No available connection was found. Server Region Proxy is not available for this region " + region.getName(); throw new FunctionException(message); } } public LocalRegion getRegion() { return region; } @Override public String toString() { return "[ ServerRegionExecutor: args=" + args + " ;filter=" + filter + " ;region=" + region.getName() + "]"; } @Override public Execution setArguments(Object args) { if (args == null) { throw new FunctionException( String.format("The input %s for the execute function request is null", "args")); } return new ServerRegionFunctionExecutor(this, args); } @Override public Execution withArgs(Object args) { return setArguments(args); } @Override public Execution withCollector(ResultCollector rs) { if (rs == null) { throw new FunctionException( String.format("The input %s for the execute function request is null", "Result Collector")); } return new ServerRegionFunctionExecutor(this, rs); } @Override public InternalExecution withMemberMappedArgument(MemberMappedArgument argument) { if (argument == null) { throw new FunctionException( String.format("The input %s for the execute function request is null", "MemberMappedArgument")); } return new ServerRegionFunctionExecutor(this, argument); } @Override public void validateExecution(Function function, Set targetMembers) { InternalCache cache = GemFireCacheImpl.getInstance(); if (cache != null && cache.getTxManager().getTXState() != null) { TXStateProxyImpl tx = (TXStateProxyImpl) cache.getTxManager().getTXState(); tx.getRealDeal(null, region); tx.incOperationCount(); } } @Override public ResultCollector execute(final String functionName) { return execute(functionName, getTimeoutMs(), TimeUnit.MILLISECONDS); } @Override public ResultCollector execute(final String functionName, long timeout, TimeUnit unit) { if (functionName == null) { throw new FunctionException( "The input function for the execute function request is null"); } int timeoutInMs = (int) TimeUnit.MILLISECONDS.convert(timeout, unit); isFnSerializationReqd = false; Function functionObject = FunctionService.getFunction(functionName); if (functionObject == null) { byte[] functionAttributes = getFunctionAttributes(functionName); if (functionAttributes == null) { // GEODE-5618: Set authentication properties before executing the internal function. try { if (proxyCache != null) { if (proxyCache.isClosed()) { throw proxyCache.getCacheClosedException("Cache is closed for this user."); } UserAttributes.userAttributes.set(proxyCache.getUserAttributes()); } ServerRegionProxy srp = getServerRegionProxy(); Object obj = srp.getFunctionAttributes(functionName); functionAttributes = (byte[]) obj; addFunctionAttributes(functionName, functionAttributes); } finally { UserAttributes.userAttributes.set(null); } } boolean isHA = functionAttributes[1] == 1; boolean hasResult = functionAttributes[0] == 1; boolean optimizeForWrite = functionAttributes[2] == 1; return executeFunction(functionName, hasResult, isHA, optimizeForWrite, timeout, unit); } else { return executeFunction(functionObject, timeout, unit); } } public boolean getExecuteOnBucketSetFlag() { return executeOnBucketSet; } }
/* * Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.internal.monitor.impl; import com.hazelcast.internal.json.JsonObject; import com.hazelcast.internal.metrics.Probe; import com.hazelcast.internal.util.Clock; import com.hazelcast.json.internal.JsonSerializable; import com.hazelcast.query.LocalIndexStats; import com.hazelcast.replicatedmap.LocalReplicatedMapStats; import java.util.Map; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_CREATION_TIME; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_MAX_GET_LATENCY; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_MAX_PUT_LATENCY; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_MAX_REMOVE_LATENCY; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_GET_COUNT; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_HITS; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_LAST_ACCESS_TIME; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_LAST_UPDATE_TIME; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_NUMBER_OF_EVENTS; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_NUMBER_OF_OTHER_OPERATIONS; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_PUT_COUNT; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_REMOVE_COUNT; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_TOTAL_GET_LATENCIES; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_TOTAL_PUT_LATENCIES; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_METRIC_TOTAL_REMOVE_LATENCIES; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_OWNED_ENTRY_COUNT; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_OWNED_ENTRY_MEMORY_COST; import static com.hazelcast.internal.metrics.MetricDescriptorConstants.REPLICATED_MAP_TOTAL; import static com.hazelcast.internal.metrics.ProbeUnit.BYTES; import static com.hazelcast.internal.metrics.ProbeUnit.MS; import static com.hazelcast.internal.util.ConcurrencyUtil.setMax; import static com.hazelcast.internal.util.JsonUtil.getLong; import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater; /** * This class collects statistics about the replication map usage for management center and is * able to transform those between wire format and instance view. */ @SuppressWarnings("checkstyle:methodcount") public class LocalReplicatedMapStatsImpl implements LocalReplicatedMapStats, JsonSerializable { private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> LAST_ACCESS_TIME = newUpdater(LocalReplicatedMapStatsImpl.class, "lastAccessTime"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> LAST_UPDATE_TIME = newUpdater(LocalReplicatedMapStatsImpl.class, "lastUpdateTime"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> HITS = newUpdater(LocalReplicatedMapStatsImpl.class, "hits"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> NUMBER_OF_OTHER_OPERATIONS = newUpdater(LocalReplicatedMapStatsImpl.class, "numberOfOtherOperations"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> NUMBER_OF_EVENTS = newUpdater(LocalReplicatedMapStatsImpl.class, "numberOfEvents"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> GET_COUNT = newUpdater(LocalReplicatedMapStatsImpl.class, "getCount"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> PUT_COUNT = newUpdater(LocalReplicatedMapStatsImpl.class, "putCount"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> REMOVE_COUNT = newUpdater(LocalReplicatedMapStatsImpl.class, "removeCount"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> TOTAL_GET_LATENCIES = newUpdater(LocalReplicatedMapStatsImpl.class, "totalGetLatencies"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> TOTAL_PUT_LATENCIES = newUpdater(LocalReplicatedMapStatsImpl.class, "totalPutLatencies"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> TOTAL_REMOVE_LATENCIES = newUpdater(LocalReplicatedMapStatsImpl.class, "totalRemoveLatencies"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> MAX_GET_LATENCY = newUpdater(LocalReplicatedMapStatsImpl.class, "maxGetLatency"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> MAX_PUT_LATENCY = newUpdater(LocalReplicatedMapStatsImpl.class, "maxPutLatency"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> MAX_REMOVE_LATENCY = newUpdater(LocalReplicatedMapStatsImpl.class, "maxRemoveLatency"); private static final AtomicLongFieldUpdater<LocalReplicatedMapStatsImpl> OWNED_ENTRY_MEMORY_COST = newUpdater(LocalReplicatedMapStatsImpl.class, "ownedEntryMemoryCost"); // these fields are only accessed through the updaters @Probe(name = REPLICATED_MAP_METRIC_LAST_ACCESS_TIME, unit = MS) private volatile long lastAccessTime; @Probe(name = REPLICATED_MAP_METRIC_LAST_UPDATE_TIME, unit = MS) private volatile long lastUpdateTime; @Probe(name = REPLICATED_MAP_METRIC_HITS) private volatile long hits; @Probe(name = REPLICATED_MAP_METRIC_NUMBER_OF_OTHER_OPERATIONS) private volatile long numberOfOtherOperations; @Probe(name = REPLICATED_MAP_METRIC_NUMBER_OF_EVENTS) private volatile long numberOfEvents; @Probe(name = REPLICATED_MAP_METRIC_GET_COUNT) private volatile long getCount; @Probe(name = REPLICATED_MAP_METRIC_PUT_COUNT) private volatile long putCount; @Probe(name = REPLICATED_MAP_METRIC_REMOVE_COUNT) private volatile long removeCount; @Probe(name = REPLICATED_MAP_METRIC_TOTAL_GET_LATENCIES, unit = MS) private volatile long totalGetLatencies; @Probe(name = REPLICATED_MAP_METRIC_TOTAL_PUT_LATENCIES, unit = MS) private volatile long totalPutLatencies; @Probe(name = REPLICATED_MAP_METRIC_TOTAL_REMOVE_LATENCIES, unit = MS) private volatile long totalRemoveLatencies; @Probe(name = REPLICATED_MAP_MAX_GET_LATENCY, unit = MS) private volatile long maxGetLatency; @Probe(name = REPLICATED_MAP_MAX_PUT_LATENCY, unit = MS) private volatile long maxPutLatency; @Probe(name = REPLICATED_MAP_MAX_REMOVE_LATENCY, unit = MS) private volatile long maxRemoveLatency; @Probe(name = REPLICATED_MAP_CREATION_TIME, unit = MS) private volatile long creationTime; @Probe(name = REPLICATED_MAP_OWNED_ENTRY_COUNT) private volatile long ownedEntryCount; @Probe(name = REPLICATED_MAP_OWNED_ENTRY_MEMORY_COST, unit = BYTES) private volatile long ownedEntryMemoryCost; public LocalReplicatedMapStatsImpl() { creationTime = Clock.currentTimeMillis(); } @Override public long getOwnedEntryCount() { return ownedEntryCount; } public void setOwnedEntryCount(long ownedEntryCount) { this.ownedEntryCount = ownedEntryCount; } @Override public long getBackupEntryCount() { return 0; } // TODO: unused public void setBackupEntryCount(long backupEntryCount) { } @Override public int getBackupCount() { return 0; } // TODO: unused public void setBackupCount(int backupCount) { } @Override public long getOwnedEntryMemoryCost() { return ownedEntryMemoryCost; } public void setOwnedEntryMemoryCost(long ownedEntryMemoryCost) { OWNED_ENTRY_MEMORY_COST.set(this, ownedEntryMemoryCost); } @Override public long getBackupEntryMemoryCost() { return 0; } // TODO: unused public void setBackupEntryMemoryCost(long backupEntryMemoryCost) { } @Override public long getCreationTime() { return creationTime; } @Override public long getLastAccessTime() { return lastAccessTime; } public void setLastAccessTime(long lastAccessTime) { setMax(this, LAST_ACCESS_TIME, lastAccessTime); } @Override public long getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(long lastUpdateTime) { setMax(this, LAST_UPDATE_TIME, lastUpdateTime); } @Override public long getHits() { return hits; } public void setHits(long hits) { HITS.set(this, hits); } @Override public long getLockedEntryCount() { return 0; } // TODO: unused public void setLockedEntryCount(long lockedEntryCount) { } @Override public long getDirtyEntryCount() { return 0; } // TODO: unused public void setDirtyEntryCount(long dirtyEntryCount) { } @Probe(name = REPLICATED_MAP_TOTAL) @Override public long total() { return putCount + getCount + removeCount + numberOfOtherOperations; } @Override public long getPutOperationCount() { return putCount; } public void incrementPuts(long latency) { PUT_COUNT.incrementAndGet(this); TOTAL_PUT_LATENCIES.addAndGet(this, latency); setMax(this, MAX_PUT_LATENCY, latency); } @Override public long getGetOperationCount() { return getCount; } public void incrementGets(long latency) { GET_COUNT.incrementAndGet(this); TOTAL_GET_LATENCIES.addAndGet(this, latency); setMax(this, MAX_GET_LATENCY, latency); } @Override public long getRemoveOperationCount() { return removeCount; } public void incrementRemoves(long latency) { REMOVE_COUNT.incrementAndGet(this); TOTAL_REMOVE_LATENCIES.addAndGet(this, latency); setMax(this, MAX_REMOVE_LATENCY, latency); } @Override public long getTotalPutLatency() { return totalPutLatencies; } @Override public long getTotalGetLatency() { return totalGetLatencies; } @Override public long getTotalRemoveLatency() { return totalRemoveLatencies; } @Override public long getMaxPutLatency() { return maxPutLatency; } @Override public long getMaxGetLatency() { return maxGetLatency; } @Override public long getMaxRemoveLatency() { return maxRemoveLatency; } @Override public long getOtherOperationCount() { return numberOfOtherOperations; } public void incrementOtherOperations() { NUMBER_OF_OTHER_OPERATIONS.incrementAndGet(this); } @Override public long getEventOperationCount() { return numberOfEvents; } public void incrementReceivedEvents() { NUMBER_OF_EVENTS.incrementAndGet(this); } @Override public long getHeapCost() { return 0; } // TODO: unused public void setHeapCost(long heapCost) { } @Override public long getMerkleTreesCost() { return 0; } // TODO: unused public void setMerkleTreesCost(long merkleTreesCost) { } @Override public NearCacheStatsImpl getNearCacheStats() { throw new UnsupportedOperationException("Replicated map has no Near Cache!"); } @Override public long getQueryCount() { throw new UnsupportedOperationException("Queries on replicated maps are not supported."); } @Override public long getIndexedQueryCount() { throw new UnsupportedOperationException("Queries on replicated maps are not supported."); } @Override public Map<String, LocalIndexStats> getIndexStats() { throw new UnsupportedOperationException("Queries on replicated maps are not supported."); } @Override public long getSetOperationCount() { throw new UnsupportedOperationException("Set operation on replicated maps is not supported."); } @Override public long getTotalSetLatency() { throw new UnsupportedOperationException("Set operation on replicated maps is not supported."); } @Override public long getMaxSetLatency() { throw new UnsupportedOperationException("Set operation on replicated maps is not supported."); } @Override public JsonObject toJson() { JsonObject root = new JsonObject(); root.add("getCount", getCount); root.add("putCount", putCount); root.add("removeCount", removeCount); root.add("numberOfOtherOperations", numberOfOtherOperations); root.add("numberOfEvents", numberOfEvents); root.add("lastAccessTime", lastAccessTime); root.add("lastUpdateTime", lastUpdateTime); root.add("hits", hits); root.add("ownedEntryCount", ownedEntryCount); root.add("ownedEntryMemoryCost", ownedEntryMemoryCost); root.add("creationTime", creationTime); root.add("totalGetLatencies", totalGetLatencies); root.add("totalPutLatencies", totalPutLatencies); root.add("totalRemoveLatencies", totalRemoveLatencies); root.add("maxGetLatency", maxGetLatency); root.add("maxPutLatency", maxPutLatency); root.add("maxRemoveLatency", maxRemoveLatency); return root; } @Override public void fromJson(JsonObject json) { getCount = getLong(json, "getCount", -1L); putCount = getLong(json, "putCount", -1L); removeCount = getLong(json, "removeCount", -1L); numberOfOtherOperations = getLong(json, "numberOfOtherOperations", -1L); numberOfEvents = getLong(json, "numberOfEvents", -1L); lastAccessTime = getLong(json, "lastAccessTime", -1L); lastUpdateTime = getLong(json, "lastUpdateTime", -1L); hits = getLong(json, "hits", -1L); ownedEntryCount = getLong(json, "ownedEntryCount", -1L); ownedEntryMemoryCost = getLong(json, "ownedEntryMemoryCost", -1L); creationTime = getLong(json, "creationTime", -1L); totalGetLatencies = getLong(json, "totalGetLatencies", -1L); totalPutLatencies = getLong(json, "totalPutLatencies", -1L); totalRemoveLatencies = getLong(json, "totalRemoveLatencies", -1L); maxGetLatency = getLong(json, "maxGetLatency", -1L); maxPutLatency = getLong(json, "maxPutLatency", -1L); maxRemoveLatency = getLong(json, "maxRemoveLatency", -1L); } @Override public String toString() { return "LocalReplicatedMapStatsImpl{" + "lastAccessTime=" + lastAccessTime + ", lastUpdateTime=" + lastUpdateTime + ", hits=" + hits + ", numberOfOtherOperations=" + numberOfOtherOperations + ", numberOfEvents=" + numberOfEvents + ", getCount=" + getCount + ", putCount=" + putCount + ", removeCount=" + removeCount + ", totalGetLatencies=" + totalGetLatencies + ", totalPutLatencies=" + totalPutLatencies + ", totalRemoveLatencies=" + totalRemoveLatencies + ", ownedEntryCount=" + ownedEntryCount + ", ownedEntryMemoryCost=" + ownedEntryMemoryCost + ", creationTime=" + creationTime + '}'; } }
// Copyright 2015 The Bazel Authors. 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.devtools.build.lib.skyframe; import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.build.skyframe.EvaluationResultSubjectFactory.assertThatEvaluationResult; import static com.google.devtools.build.skyframe.WalkableGraphUtils.exists; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.analysis.util.BuildViewTestCase; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.RepositoryName; import com.google.devtools.build.lib.pkgcache.FilteringPolicies; import com.google.devtools.build.lib.pkgcache.FilteringPolicy; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.vfs.Root; import com.google.devtools.build.lib.vfs.RootedPath; import com.google.devtools.build.skyframe.EvaluationContext; import com.google.devtools.build.skyframe.EvaluationResult; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.WalkableGraph; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link PrepareDepsOfTargetsUnderDirectoryFunction}. Insert excuses here. */ @RunWith(JUnit4.class) public class PrepareDepsOfTargetsUnderDirectoryFunctionTest extends BuildViewTestCase { private static SkyKey createCollectPackagesKey( Path root, PathFragment rootRelativePath, ImmutableSet<PathFragment> excludedPaths) { RootedPath rootedPath = RootedPath.toRootedPath(Root.fromPath(root), rootRelativePath); return CollectPackagesUnderDirectoryValue.key( RepositoryName.MAIN, rootedPath, excludedPaths); } private static SkyKey createPrepDepsKey(Path root, PathFragment rootRelativePath) { return createPrepDepsKey(root, rootRelativePath, ImmutableSet.of()); } private static SkyKey createPrepDepsKey( Path root, PathFragment rootRelativePath, ImmutableSet<PathFragment> excludedPaths) { RootedPath rootedPath = RootedPath.toRootedPath(Root.fromPath(root), rootRelativePath); return PrepareDepsOfTargetsUnderDirectoryValue.key( RepositoryName.MAIN, rootedPath, excludedPaths); } private static SkyKey createPrepDepsKey( Path root, PathFragment rootRelativePath, ImmutableSet<PathFragment> excludedPaths, FilteringPolicy filteringPolicy) { RootedPath rootedPath = RootedPath.toRootedPath(Root.fromPath(root), rootRelativePath); return PrepareDepsOfTargetsUnderDirectoryValue.key( RepositoryName.MAIN, rootedPath, excludedPaths, filteringPolicy); } private EvaluationResult<?> getEvaluationResult(SkyKey... keys) throws InterruptedException { EvaluationContext evaluationContext = EvaluationContext.newBuilder() .setKeepGoing(false) .setNumThreads(SequencedSkyframeExecutor.DEFAULT_THREAD_COUNT) .setEventHandler(reporter) .build(); EvaluationResult<PrepareDepsOfTargetsUnderDirectoryValue> evaluationResult = skyframeExecutor.getEvaluator().evaluate(ImmutableList.copyOf(keys), evaluationContext); assertThatEvaluationResult(evaluationResult).hasNoError(); return evaluationResult; } @Test public void testTransitiveLoading() throws Exception { // Given a package "a" with a genrule "a" that depends on a target in package "b", createPackages(); // When package "a" is evaluated, SkyKey key = createPrepDepsKey(rootDirectory, PathFragment.create("a")); EvaluationResult<?> evaluationResult = getEvaluationResult(key); WalkableGraph graph = Preconditions.checkNotNull(evaluationResult.getWalkableGraph()); // Then the TransitiveTraversalValue for "@//a:a" is evaluated, SkyKey aaKey = TransitiveTraversalValue.key(Label.create("@//a", "a")); assertThat(exists(aaKey, graph)).isTrue(); // And that TransitiveTraversalValue depends on "@//b:b.txt". Iterable<SkyKey> depsOfAa = Iterables.getOnlyElement(graph.getDirectDeps(ImmutableList.of(aaKey)).values()); SkyKey bTxtKey = TransitiveTraversalValue.key(Label.create("@//b", "b.txt")); assertThat(depsOfAa).contains(bTxtKey); // And the TransitiveTraversalValue for "b:b.txt" is evaluated. assertThat(exists(bTxtKey, graph)).isTrue(); } @Test public void testTargetFilterSensitivity() throws Exception { // Given a package "a" with a genrule "a" that depends on a target in package "b", and a test // rule "aTest", createPackages(); // When package "a" is evaluated under a test-only filtering policy, SkyKey key = createPrepDepsKey( rootDirectory, PathFragment.create("a"), ImmutableSet.of(), FilteringPolicies.FILTER_TESTS); EvaluationResult<?> evaluationResult = getEvaluationResult(key); WalkableGraph graph = Preconditions.checkNotNull(evaluationResult.getWalkableGraph()); // Then the TransitiveTraversalValue for "@//a:a" is not evaluated, SkyKey aaKey = TransitiveTraversalValue.key(Label.create("@//a", "a")); assertThat(exists(aaKey, graph)).isFalse(); // But the TransitiveTraversalValue for "@//a:aTest" is. SkyKey aaTestKey = TransitiveTraversalValue.key(Label.create("@//a", "aTest")); assertThat(exists(aaTestKey, graph)).isTrue(); } /** * Creates a package "a" with a genrule "a" that depends on a target in a created package "b", * and a test rule "aTest". */ private void createPackages() throws IOException { scratch.file("a/BUILD", "genrule(name='a', cmd='', srcs=['//b:b.txt'], outs=['a.out'])", "sh_test(name='aTest', size='small', srcs=['aTest.sh'])"); scratch.file("b/BUILD", "exports_files(['b.txt'])"); } @Test public void testSubdirectoryExclusion() throws Exception { // Given a package "a" with two packages below it, "a/b" and "a/c", scratch.file("a/BUILD"); scratch.file("a/b/BUILD"); scratch.file("a/c/BUILD"); // When the top package is evaluated via PrepareDepsOfTargetsUnderDirectoryValue with "a/b" // excluded, PathFragment excludedPathFragment = PathFragment.create("a/b"); SkyKey key = createPrepDepsKey(rootDirectory, PathFragment.create("a"), ImmutableSet.of(excludedPathFragment)); SkyKey collectkey = createCollectPackagesKey( rootDirectory, PathFragment.create("a"), ImmutableSet.of(excludedPathFragment)); EvaluationResult<?> evaluationResult = getEvaluationResult(key, collectkey); CollectPackagesUnderDirectoryValue value = (CollectPackagesUnderDirectoryValue) evaluationResult .getWalkableGraph() .getValue( createCollectPackagesKey( rootDirectory, PathFragment.create("a"), ImmutableSet.of(excludedPathFragment))); // Then the value reports that "a" is a package, assertThat(value.isDirectoryPackage()).isTrue(); // And only the subdirectory corresponding to "a/c" is present in the result, RootedPath onlySubdir = Iterables.getOnlyElement( value.getSubdirectoryTransitivelyContainsPackagesOrErrors().keySet()); assertThat(onlySubdir.getRootRelativePath()).isEqualTo(PathFragment.create("a/c")); // And the "a/c" subdirectory reports a package under it. assertThat(value.getSubdirectoryTransitivelyContainsPackagesOrErrors().get(onlySubdir)) .isTrue(); // Also, the computation graph does not contain a cached value for "a/b". WalkableGraph graph = Preconditions.checkNotNull(evaluationResult.getWalkableGraph()); assertThat( exists( createPrepDepsKey(rootDirectory, excludedPathFragment, ImmutableSet.of()), graph)) .isFalse(); // And the computation graph does contain a cached value for "a/c" with the empty set excluded, // because that key was evaluated. assertThat( exists( createPrepDepsKey(rootDirectory, PathFragment.create("a/c"), ImmutableSet.of()), graph)) .isTrue(); } @Test public void testExcludedSubdirectoryGettingPassedDown() throws Exception { // Given a package "a", and a package below it in "a/b/c", and a non-BUILD file below it in // "a/b/d", scratch.file("a/BUILD"); scratch.file("a/b/c/BUILD"); scratch.file("a/b/d/helloworld"); // When the top package is evaluated for recursive package values, and "a/b/c" is excluded, ImmutableSet<PathFragment> excludedPaths = ImmutableSet.of(PathFragment.create("a/b/c")); SkyKey key = createPrepDepsKey(rootDirectory, PathFragment.create("a"), excludedPaths); SkyKey collectKey = createCollectPackagesKey(rootDirectory, PathFragment.create("a"), excludedPaths); EvaluationResult<?> evaluationResult = getEvaluationResult(key, collectKey); CollectPackagesUnderDirectoryValue value = (CollectPackagesUnderDirectoryValue) evaluationResult .getWalkableGraph() .getValue( createCollectPackagesKey( rootDirectory, PathFragment.create("a"), excludedPaths)); // Then the value reports that "a" is a package, assertThat(value.isDirectoryPackage()).isTrue(); // And the subdirectory corresponding to "a/b" is present in the result, RootedPath onlySubdir = Iterables.getOnlyElement( value.getSubdirectoryTransitivelyContainsPackagesOrErrors().keySet()); assertThat(onlySubdir.getRootRelativePath()).isEqualTo(PathFragment.create("a/b")); // And the "a/b" subdirectory does not report a package under it (because it got excluded). assertThat(value.getSubdirectoryTransitivelyContainsPackagesOrErrors().get(onlySubdir)) .isFalse(); // Also, the computation graph contains a cached value for "a/b" with "a/b/c" excluded, because // "a/b/c" does live underneath "a/b". WalkableGraph graph = Preconditions.checkNotNull(evaluationResult.getWalkableGraph()); SkyKey abKey = createCollectPackagesKey( rootDirectory, PathFragment.create("a/b"), excludedPaths); assertThat(exists(abKey, graph)).isTrue(); CollectPackagesUnderDirectoryValue abValue = (CollectPackagesUnderDirectoryValue) Preconditions.checkNotNull(graph.getValue(abKey)); // And that value says that "a/b" is not a package, assertThat(abValue.isDirectoryPackage()).isFalse(); // And only the subdirectory "a/b/d" is present in that value, RootedPath abd = Iterables.getOnlyElement( abValue.getSubdirectoryTransitivelyContainsPackagesOrErrors().keySet()); assertThat(abd.getRootRelativePath()).isEqualTo(PathFragment.create("a/b/d")); // And no package is under "a/b/d". assertThat(abValue.getSubdirectoryTransitivelyContainsPackagesOrErrors().get(abd)).isFalse(); } }
package uk.co.thefishlive.meteor.group; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import uk.co.thefishlive.auth.assessments.Assessment; import uk.co.thefishlive.auth.assessments.assignments.Assignment; import uk.co.thefishlive.auth.assessments.assignments.AssignmentResult; import uk.co.thefishlive.auth.group.Group; import uk.co.thefishlive.auth.group.GroupProfile; import uk.co.thefishlive.auth.group.member.GroupMemberProfile; import uk.co.thefishlive.auth.permission.Permission; import uk.co.thefishlive.auth.settings.Setting; import uk.co.thefishlive.auth.user.UserProfile; import uk.co.thefishlive.http.HttpClient; import uk.co.thefishlive.http.HttpHeader; import uk.co.thefishlive.http.HttpRequest; import uk.co.thefishlive.http.HttpResponse; import uk.co.thefishlive.http.RequestType; import uk.co.thefishlive.http.meteor.BasicHttpHeader; import uk.co.thefishlive.http.meteor.MeteorHttpClient; import uk.co.thefishlive.http.meteor.MeteorHttpRequest; import uk.co.thefishlive.meteor.MeteorAuthHandler; import uk.co.thefishlive.meteor.assessments.MeteorAssessmentManager; import uk.co.thefishlive.meteor.assessments.assignments.MeteorAssignment; import uk.co.thefishlive.meteor.json.annotations.Internal; import uk.co.thefishlive.meteor.settings.StringSetting; import uk.co.thefishlive.meteor.utils.SerialisationUtils; import uk.co.thefishlive.meteor.utils.WebUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MeteorGroup implements Group { private static final Gson GSON = SerialisationUtils.getGsonInstance(); @Internal private final MeteorAuthHandler authHandler; private GroupProfile profile; private List<GroupMemberProfile> groups; public MeteorGroup(MeteorAuthHandler authHandler, GroupProfile profile) { this.authHandler = authHandler; this.profile = profile; } @Override public List<GroupMemberProfile> getUsers() { if (groups == null) { groups = new ArrayList<>(); try { HttpClient client = MeteorHttpClient.getInstance(); List<HttpHeader> headers = new ArrayList<>(); headers.add(new BasicHttpHeader("X-Client", this.authHandler.getClientId().toString())); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.GET, headers); HttpResponse response = client.sendRequest(WebUtils.GROUP_USERS_ENDPOINT(getProfile()), request); JsonObject payload = response.getResponseBody(); for (JsonElement element : payload.getAsJsonArray("users")) { this.groups.add(GSON.fromJson(element, UserProfile.class)); } } catch (IOException e) { Throwables.propagate(e); } } return ImmutableList.copyOf(groups); } @Override public GroupProfile getProfile() { return profile; } @Override public GroupProfile updateProfile(GroupProfile update) { try { HttpClient client = MeteorHttpClient.getInstance(); JsonObject payload = new JsonObject(); if (update.hasDisplayName()) { payload.addProperty("display-name", update.getDisplayName()); } if (update.hasName()) { payload.addProperty("group-name", update.getName()); } List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.POST, payload, headers); HttpResponse response = client.sendRequest(WebUtils.GROUP_LOOKUP_ENDPOINT(getProfile()), request); return GSON.fromJson(response.getResponseBody().get("profile"), GroupProfile.class); } catch (IOException e) { Throwables.propagate(e); return null; } } @Override public boolean hasPermission(Permission permission) throws IOException { HttpClient client = MeteorHttpClient.getInstance(); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.GET, headers); HttpResponse response = client.sendRequest(WebUtils.GROUP_PERMISSION_CHECK_ENDPOINT(getProfile(), permission), request); JsonObject payload = response.getResponseBody(); return payload.get("present").getAsBoolean(); } @Override public void addPermission(Permission permission) throws IOException { HttpClient client = MeteorHttpClient.getInstance(); JsonObject payload = new JsonObject(); payload.addProperty("permission", permission.getKey()); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.POST, payload, headers); client.sendRequest(WebUtils.GROUP_PERMISSION_EDIT_ENDPOINT(getProfile()), request); } @Override public void removePermission(Permission permission) throws IOException { HttpClient client = MeteorHttpClient.getInstance(); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.DELETE, headers); client.sendRequest(WebUtils.GROUP_PERMISSION_CHECK_ENDPOINT(getProfile(), permission), request); } @Override public List<Permission> getPermissions() { return null; } @Override public Setting<String, String> getSetting(String key) throws IOException { HttpClient client = MeteorHttpClient.getInstance(); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.GET, headers); HttpResponse response = client.sendRequest(WebUtils.GROUP_SETTING_LOOKUP_ENDPOINT(getProfile(), key), request); JsonObject payload = response.getResponseBody(); return GSON.fromJson(payload.get("setting"), StringSetting.class); } @Override public void setSetting(Setting<String, ?> setting) throws IOException { HttpClient client = MeteorHttpClient.getInstance(); JsonObject payload = new JsonObject(); payload.add("setting", GSON.toJsonTree(setting)); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.POST, payload, headers); client.sendRequest(WebUtils.GROUP_SETTING_EDIT_ENDPOINT(getProfile()), request); } @Override public void deleteSetting(String key) throws IOException { HttpClient client = MeteorHttpClient.getInstance(); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.DELETE, headers); client.sendRequest(WebUtils.GROUP_SETTING_LOOKUP_ENDPOINT(getProfile(), key), request); } @Override public List<Assignment> getOutstandingAssignments() { throw new UnsupportedOperationException(); } @Override public List<Assignment> getAllAssignments() { throw new UnsupportedOperationException(); } @Override public List<Assignment> getCompletedAssignments() { List<Assignment> assignments = Lists.newArrayList(); try { HttpClient client = MeteorHttpClient.getInstance(); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); HttpRequest request = new MeteorHttpRequest(RequestType.GET, headers); HttpResponse response = client.sendRequest(WebUtils.GROUP_ASSIGNMENT_LOOKUP_COMPLETED(getProfile()), request); JsonObject payload = response.getResponseBody(); for (JsonElement element : payload.getAsJsonArray("assignments")) { Assignment assignment = GSON.fromJson(element, Assignment.class); ((MeteorAssignment) assignment).setHandler((MeteorAssessmentManager) authHandler.getAssessmentManager()); assignments.add(assignment); } } catch (IOException e) { Throwables.propagate(e); } return assignments; } @Override public void assignAssessment(Assignment assignment) { try { HttpClient client = MeteorHttpClient.getInstance(); List<HttpHeader> headers = new ArrayList<>(); headers.addAll(this.authHandler.getAuthHeaders()); JsonObject payload = new JsonObject(); payload.addProperty("assignment", assignment.getAssignmentId().toString()); HttpRequest request = new MeteorHttpRequest(RequestType.POST, payload, headers); client.sendRequest(WebUtils.GROUP_ASSIGNMENT_ADD(getProfile()), request); } catch (IOException e) { Throwables.propagate(e); } } @Override public AssignmentResult submitAssessment(Assignment assignment, Assessment assessment) { throw new UnsupportedOperationException(); } }
/******************************************************************************* * Copyright 2017 * Language Technology Lab * University of Duisburg-Essen * * 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 de.unidue.ltl.flextag.core; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.collection.CollectionReaderDescription; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.resource.ResourceInitializationException; import org.dkpro.lab.Lab; import org.dkpro.lab.reporting.Report; import org.dkpro.lab.task.Dimension; import org.dkpro.lab.task.ParameterSpace; import org.dkpro.tc.api.features.TcFeature; import org.dkpro.tc.api.features.TcFeatureSet; import org.dkpro.tc.core.Constants; import org.dkpro.tc.core.ml.TCMachineLearningAdapter; import org.dkpro.tc.ml.Experiment_ImplBase; import org.dkpro.tc.ml.crfsuite.CRFSuiteAdapter; import org.dkpro.tc.ml.liblinear.LiblinearAdapter; import org.dkpro.tc.ml.libsvm.LibsvmAdapter; import org.dkpro.tc.ml.svmhmm.SVMHMMAdapter; import org.dkpro.tc.ml.weka.WekaClassificationAdapter; import de.unidue.ltl.flextag.core.uima.TcPosTaggingWrapper; public abstract class FlexTagSetUp implements Constants { protected String experimentName = "FlexTag"; protected TcFeatureSet features; protected Experiment_ImplBase batch; protected CollectionReaderDescription reader; protected AnalysisEngineDescription[] userPreprocessing; protected Classifier classifier; protected Dimension<?> dimClassificationArgs; protected List<Class<? extends Report>> reports; boolean useCoarse = false; boolean didWire = false; public FlexTagSetUp(CollectionReaderDescription reader) { this.reader = reader; this.classifier = Classifier.CRFSUITE; this.dimClassificationArgs = setDefaultCrfConfiguration(); } @SuppressWarnings("unchecked") private Dimension<?> setDefaultCrfConfiguration() { return Dimension.create(DIM_CLASSIFICATION_ARGS, asList(new String[] { CRFSuiteAdapter.ALGORITHM_ADAPTIVE_REGULARIZATION_OF_WEIGHT_VECTOR })); } public List<Class<? extends Report>> getReports() { return reports; } /** * Sets a new feature set * * @param featureSet * a feature set */ public void setFeatures(TcFeatureSet featureSet) { this.features = featureSet; } /** * Removes all reports */ public void removeReports() { this.reports = new ArrayList<>(); } /** * Sets a new feature set * * @param features * an array of features which are added to the current features. If no features have * been set yet the feature set is initialized. */ public void setFeatures(TcFeature... features) { if (this.features == null) { this.features = new TcFeatureSet(features); } else { for (TcFeature f : features) { this.features.add(f); } } } /** * Sets an own experiment name which will make it easier to locate the result folders in the * DKPRO_HOME folder * * @param experimentName * the name of the experiment */ public void setExperimentName(String experimentName) { this.experimentName = experimentName; } public String getExperimentName() { return this.experimentName; } public void setDKProHomeFolder(String home) { System.setProperty("DKPRO_HOME", home); } protected Dimension<TcFeatureSet> wrapFeatures() { return Dimension.create(DIM_FEATURE_SET, features); } protected ParameterSpace assembleParameterSpace(Map<String, Object> dimReaders, Dimension<TcFeatureSet> dimFeatureSets) { return new ParameterSpace(Dimension.createBundle("readers", dimReaders), Dimension.create(DIM_LEARNING_MODE, Constants.LM_SINGLE_LABEL), Dimension.create(DIM_FEATURE_MODE, Constants.FM_SEQUENCE), dimFeatureSets, dimClassificationArgs); } public Class<? extends TCMachineLearningAdapter> getClassifier() { switch (classifier) { case CRFSUITE: return CRFSuiteAdapter.class; case SVMHMM: return SVMHMMAdapter.class; case WEKA: return WekaClassificationAdapter.class; case LIBLINEAR: return LiblinearAdapter.class; case LIBSVM: return LibsvmAdapter.class; default: throw new IllegalArgumentException( "Classifier [" + classifier.toString() + "] is unknown"); } } public TcFeatureSet getFeatures() { return this.features; } @SuppressWarnings("unchecked") public void setClassifier(Classifier classifier, List<Object> dimClassificationArgs) { this.classifier = classifier; this.dimClassificationArgs = Dimension.create(DIM_CLASSIFICATION_ARGS, dimClassificationArgs); } /** * Gets the current pre-processing set up * @return Pre-processing pipeline * @throws ResourceInitializationException * for erroneous configurations */ public AnalysisEngineDescription getPreprocessing() throws ResourceInitializationException { List<AnalysisEngineDescription> preprocessing = new ArrayList<>(); if (userPreprocessing != null) { preprocessing.addAll(Arrays.asList(userPreprocessing)); } preprocessing.add(AnalysisEngineFactory.createEngineDescription(TcPosTaggingWrapper.class, TcPosTaggingWrapper.PARAM_USE_COARSE_GRAINED, useCoarse)); return AnalysisEngineFactory .createEngineDescription(preprocessing.toArray(new AnalysisEngineDescription[0])); } public void setPreprocessing(AnalysisEngineDescription... createEngineDescription) { userPreprocessing = createEngineDescription; } public void useCoarse(boolean useCoarse) { this.useCoarse = useCoarse; } public void addReport(Class<? extends Report> report) { reports.add(report); } public void addReports(List<Class<? extends Report>> r) { for (Class<? extends Report> c : r) { reports.add(c); } } protected void checkFeatureSpace() { if (features == null || features.isEmpty()) { throw new IllegalStateException("The feature space contains no feature extractors"); } } public abstract void wire() throws Exception; Experiment_ImplBase getLabTask(){ return batch; } public void execute() throws Exception{ if(!didWire){ wire(); } Lab.getInstance().run(batch); } }
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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.dartlang.vm.service.element; // This is a generated file. import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * An {@link Instance} represents an instance of the Dart language class {@link Obj}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Instance extends Obj { public Instance(JsonObject json) { super(json); } /** * The stack trace associated with the allocation of a ReceivePort. * * Provided for instance kinds: * - ReceivePort * * Can return <code>null</code>. */ public InstanceRef getAllocationLocation() { JsonObject obj = (JsonObject) json.get("allocationLocation"); if (obj == null) return null; return new InstanceRef(obj); } /** * The elements of a Map instance. * * Provided for instance kinds: * - Map * * Can return <code>null</code>. */ public ElementList<MapAssociation> getAssociations() { if (json.get("associations") == null) return null; return new ElementList<MapAssociation>(json.get("associations").getAsJsonArray()) { @Override protected MapAssociation basicGet(JsonArray array, int index) { return new MapAssociation(array.get(index).getAsJsonObject()); } }; } /** * The bound of a TypeParameter or BoundedType. * * The value will always be of one of the kinds: Type, TypeRef, TypeParameter, BoundedType. * * Provided for instance kinds: * - BoundedType * - TypeParameter * * Can return <code>null</code>. */ public InstanceRef getBound() { JsonObject obj = (JsonObject) json.get("bound"); if (obj == null) return null; return new InstanceRef(obj); } /** * The bytes of a TypedData instance. * * The data is provided as a Base64 encoded string. * * Provided for instance kinds: * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * * Can return <code>null</code>. */ public String getBytes() { return getAsString("bytes"); } /** * Instance references always include their class. */ @Override public ClassRef getClassRef() { return new ClassRef((JsonObject) json.get("class")); } /** * The context associated with a Closure instance. * * Provided for instance kinds: * - Closure * * Can return <code>null</code>. */ public ContextRef getClosureContext() { JsonObject obj = (JsonObject) json.get("closureContext"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ContextRef(obj); } /** * The function associated with a Closure instance. * * Provided for instance kinds: * - Closure * * Can return <code>null</code>. */ public FuncRef getClosureFunction() { JsonObject obj = (JsonObject) json.get("closureFunction"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new FuncRef(obj); } /** * The number of elements or associations or codeunits returned. This is only provided when it is * less than length. * * Provided for instance kinds: * - String * - List * - Map * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * * Can return <code>null</code>. */ public int getCount() { return getAsInt("count"); } /** * A name associated with a ReceivePort used for debugging purposes. * * Provided for instance kinds: * - ReceivePort * * Can return <code>null</code>. */ public String getDebugName() { return getAsString("debugName"); } /** * The elements of a List instance. * * Provided for instance kinds: * - List * * @return one of <code>ElementList<InstanceRef></code> or <code>ElementList<Sentinel></code> * * Can return <code>null</code>. */ public ElementList<InstanceRef> getElements() { if (json.get("elements") == null) return null; return new ElementList<InstanceRef>(json.get("elements").getAsJsonArray()) { @Override protected InstanceRef basicGet(JsonArray array, int index) { return new InstanceRef(array.get(index).getAsJsonObject()); } }; } /** * The fields of this Instance. * * Can return <code>null</code>. */ public ElementList<BoundField> getFields() { if (json.get("fields") == null) return null; return new ElementList<BoundField>(json.get("fields").getAsJsonArray()) { @Override protected BoundField basicGet(JsonArray array, int index) { return new BoundField(array.get(index).getAsJsonObject()); } }; } /** * The identityHashCode assigned to the allocated object. This hash code is the same as the hash * code provided in HeapSnapshot and CpuSample's returned by getAllocationTraces(). */ public int getIdentityHashCode() { return getAsInt("identityHashCode"); } /** * Whether this regular expression is case sensitive. * * Provided for instance kinds: * - RegExp * * Can return <code>null</code>. */ public boolean getIsCaseSensitive() { return getAsBoolean("isCaseSensitive"); } /** * Whether this regular expression matches multiple lines. * * Provided for instance kinds: * - RegExp * * Can return <code>null</code>. */ public boolean getIsMultiLine() { return getAsBoolean("isMultiLine"); } /** * What kind of instance is this? */ public InstanceKind getKind() { final JsonElement value = json.get("kind"); try { return value == null ? InstanceKind.Unknown : InstanceKind.valueOf(value.getAsString()); } catch (IllegalArgumentException e) { return InstanceKind.Unknown; } } /** * The length of a List or the number of associations in a Map or the number of codeunits in a * String. * * Provided for instance kinds: * - String * - List * - Map * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * * Can return <code>null</code>. */ public int getLength() { return getAsInt("length"); } /** * The referent of a MirrorReference instance. * * Provided for instance kinds: * - MirrorReference * * Can return <code>null</code>. */ public InstanceRef getMirrorReferent() { JsonObject obj = (JsonObject) json.get("mirrorReferent"); if (obj == null) return null; return new InstanceRef(obj); } /** * The name of a Type instance. * * Provided for instance kinds: * - Type * * Can return <code>null</code>. */ public String getName() { return getAsString("name"); } /** * The index of the first element or association or codeunit returned. This is only provided when * it is non-zero. * * Provided for instance kinds: * - String * - List * - Map * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * * Can return <code>null</code>. */ public int getOffset() { return getAsInt("offset"); } /** * The index of a TypeParameter instance. * * Provided for instance kinds: * - TypeParameter * * Can return <code>null</code>. */ public int getParameterIndex() { return getAsInt("parameterIndex"); } /** * The parameterized class of a type parameter: * * Provided for instance kinds: * - TypeParameter * * Can return <code>null</code>. */ public ClassRef getParameterizedClass() { JsonObject obj = (JsonObject) json.get("parameterizedClass"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ClassRef(obj); } /** * The pattern of a RegExp instance. * * Provided for instance kinds: * - RegExp * * Can return <code>null</code>. */ public InstanceRef getPattern() { JsonObject obj = (JsonObject) json.get("pattern"); if (obj == null) return null; return new InstanceRef(obj); } /** * The port ID for a ReceivePort. * * Provided for instance kinds: * - ReceivePort * * Can return <code>null</code>. */ public int getPortId() { return getAsInt("portId"); } /** * The key for a WeakProperty instance. * * Provided for instance kinds: * - WeakProperty * * Can return <code>null</code>. */ public InstanceRef getPropertyKey() { JsonObject obj = (JsonObject) json.get("propertyKey"); if (obj == null) return null; return new InstanceRef(obj); } /** * The key for a WeakProperty instance. * * Provided for instance kinds: * - WeakProperty * * Can return <code>null</code>. */ public InstanceRef getPropertyValue() { JsonObject obj = (JsonObject) json.get("propertyValue"); if (obj == null) return null; return new InstanceRef(obj); } /** * The type bounded by a BoundedType instance - or - the referent of a TypeRef instance. * * The value will always be of one of the kinds: Type, TypeRef, TypeParameter, BoundedType. * * Provided for instance kinds: * - BoundedType * - TypeRef * * Can return <code>null</code>. */ public InstanceRef getTargetType() { JsonObject obj = (JsonObject) json.get("targetType"); if (obj == null) return null; return new InstanceRef(obj); } /** * The type arguments for this type. * * Provided for instance kinds: * - Type * * Can return <code>null</code>. */ public TypeArgumentsRef getTypeArguments() { JsonObject obj = (JsonObject) json.get("typeArguments"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new TypeArgumentsRef(obj); } /** * The corresponding Class if this Type is canonical. * * Provided for instance kinds: * - Type * * Can return <code>null</code>. */ public ClassRef getTypeClass() { JsonObject obj = (JsonObject) json.get("typeClass"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ClassRef(obj); } /** * The value of this instance as a string. * * Provided for the instance kinds: * - Bool (true or false) * - Double (suitable for passing to Double.parse()) * - Int (suitable for passing to int.parse()) * - String (value may be truncated) * - StackTrace * * Can return <code>null</code>. */ public String getValueAsString() { return getAsString("valueAsString"); } /** * The valueAsString for String references may be truncated. If so, this property is added with * the value 'true'. * * New code should use 'length' and 'count' instead. * * Can return <code>null</code>. */ public boolean getValueAsStringIsTruncated() { final JsonElement elem = json.get("valueAsStringIsTruncated"); return elem != null ? elem.getAsBoolean() : false; } /** * Returns whether this instance represents null. */ public boolean isNull() { return getKind() == InstanceKind.Null; } }
/* * 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.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Configs when Samza is used with a ClusterManager like Yarn or Mesos. Some of these configs were originally defined * in the yarn namespace. These will be moved to the "cluster-manager" namespace. For now, both configs will be honored * with the cluster-manager.* configs taking precedence. There will be a deprecated config warning when old configs are used. * Later, we'll enforce the new configs. */ public class ClusterManagerConfig extends MapConfig { private static final Logger log = LoggerFactory.getLogger(ClusterManagerConfig.class); private static final String CLUSTER_MANAGER_FACTORY = "samza.cluster-manager.factory"; private static final String CLUSTER_MANAGER_FACTORY_DEFAULT = "org.apache.samza.job.yarn.YarnResourceManagerFactory"; /** * Sleep interval for the allocator thread in milliseconds */ private static final String ALLOCATOR_SLEEP_MS = "cluster-manager.allocator.sleep.ms"; public static final String YARN_ALLOCATOR_SLEEP_MS = "yarn.allocator.sleep.ms"; private static final int DEFAULT_ALLOCATOR_SLEEP_MS = 3600; /** * Number of milliseconds before a container request is considered to have to expired */ public static final String CONTAINER_REQUEST_TIMEOUT_MS = "yarn.container.request.timeout.ms"; public static final String CLUSTER_MANAGER_REQUEST_TIMEOUT_MS = "cluster-manager.container.request.timeout.ms"; private static final int DEFAULT_CONTAINER_REQUEST_TIMEOUT_MS = 5000; /** * Flag to indicate if host-affinity is enabled for the job or not */ public static final String HOST_AFFINITY_ENABLED = "yarn.samza.host-affinity.enabled"; public static final String CLUSTER_MANAGER_HOST_AFFINITY_ENABLED = "job.host-affinity.enabled"; private static final boolean DEFAULT_HOST_AFFINITY_ENABLED = false; /** * Number of CPU cores to request from the cluster manager per container */ public static final String CONTAINER_MAX_CPU_CORES = "yarn.container.cpu.cores"; public static final String CLUSTER_MANAGER_MAX_CORES = "cluster-manager.container.cpu.cores"; private static final int DEFAULT_CPU_CORES = 1; /** * Memory, in megabytes, to request from the cluster manager per container */ public static final String CONTAINER_MAX_MEMORY_MB = "yarn.container.memory.mb"; public static final String CLUSTER_MANAGER_MEMORY_MB = "cluster-manager.container.memory.mb"; private static final int DEFAULT_CONTAINER_MEM = 1024; /** * Determines how frequently a container is allowed to fail before we give up and fail the job */ public static final String CONTAINER_RETRY_WINDOW_MS = "yarn.container.retry.window.ms"; public static final String CLUSTER_MANAGER_RETRY_WINDOW_MS = "cluster-manager.container.retry.window.ms"; private static final int DEFAULT_CONTAINER_RETRY_WINDOW_MS = 300000; /** * Maximum number of times Samza tries to restart a failed container */ public static final String CONTAINER_RETRY_COUNT = "yarn.container.retry.count"; public static final String CLUSTER_MANAGER_CONTAINER_RETRY_COUNT = "cluster-manager.container.retry.count"; private static final int DEFAULT_CONTAINER_RETRY_COUNT = 8; /** * Determines whether a JMX server should be started on the job coordinator * Default: true */ public static final String AM_JMX_ENABLED = "yarn.am.jmx.enabled"; public static final String CLUSTER_MANAGER_JMX_ENABLED = "cluster-manager.jobcoordinator.jmx.enabled"; /** * The cluster managed job coordinator sleeps for a configurable time before checking again for termination. * The sleep interval of the cluster managed job coordinator. */ public static final String CLUSTER_MANAGER_SLEEP_MS = "cluster-manager.jobcoordinator.sleep.interval.ms"; private static final int DEFAULT_CLUSTER_MANAGER_SLEEP_MS = 1000; public ClusterManagerConfig(Config config) { super(config); } public int getAllocatorSleepTime() { if (containsKey(ALLOCATOR_SLEEP_MS)) { return getInt(ALLOCATOR_SLEEP_MS); } else if (containsKey(YARN_ALLOCATOR_SLEEP_MS)) { log.info("Configuration {} is deprecated. Please use {}", YARN_ALLOCATOR_SLEEP_MS, ALLOCATOR_SLEEP_MS); return getInt(YARN_ALLOCATOR_SLEEP_MS); } else { return DEFAULT_ALLOCATOR_SLEEP_MS; } } public int getNumCores() { if (containsKey(CLUSTER_MANAGER_MAX_CORES)) { return getInt(CLUSTER_MANAGER_MAX_CORES); } else if (containsKey(CONTAINER_MAX_CPU_CORES)) { log.info("Configuration {} is deprecated. Please use {}", CONTAINER_MAX_CPU_CORES, CLUSTER_MANAGER_MAX_CORES); return getInt(CONTAINER_MAX_CPU_CORES); } else { return DEFAULT_CPU_CORES; } } public int getContainerMemoryMb() { if (containsKey(CLUSTER_MANAGER_MEMORY_MB)) { return getInt(CLUSTER_MANAGER_MEMORY_MB); } else if (containsKey(CONTAINER_MAX_MEMORY_MB)) { log.info("Configuration {} is deprecated. Please use {}", CONTAINER_MAX_MEMORY_MB, CLUSTER_MANAGER_MEMORY_MB); return getInt(CONTAINER_MAX_MEMORY_MB); } else { return DEFAULT_CONTAINER_MEM; } } public boolean getHostAffinityEnabled() { if (containsKey(CLUSTER_MANAGER_HOST_AFFINITY_ENABLED)) { return getBoolean(CLUSTER_MANAGER_HOST_AFFINITY_ENABLED); } else if (containsKey(HOST_AFFINITY_ENABLED)) { log.info("Configuration {} is deprecated. Please use {}", HOST_AFFINITY_ENABLED, CLUSTER_MANAGER_HOST_AFFINITY_ENABLED); return getBoolean(HOST_AFFINITY_ENABLED); } else { return false; } } public int getContainerRequestTimeout() { if (containsKey(CLUSTER_MANAGER_REQUEST_TIMEOUT_MS)) { return getInt(CLUSTER_MANAGER_REQUEST_TIMEOUT_MS); } else if (containsKey(CONTAINER_REQUEST_TIMEOUT_MS)) { log.info("Configuration {} is deprecated. Please use {}", CONTAINER_REQUEST_TIMEOUT_MS, CLUSTER_MANAGER_REQUEST_TIMEOUT_MS); return getInt(CONTAINER_REQUEST_TIMEOUT_MS); } else { return DEFAULT_CONTAINER_REQUEST_TIMEOUT_MS; } } public int getContainerRetryCount() { if (containsKey(CLUSTER_MANAGER_CONTAINER_RETRY_COUNT)) return getInt(CLUSTER_MANAGER_CONTAINER_RETRY_COUNT); else if (containsKey(CONTAINER_RETRY_COUNT)) { log.info("Configuration {} is deprecated. Please use {}", CONTAINER_RETRY_COUNT, CLUSTER_MANAGER_CONTAINER_RETRY_COUNT); return getInt(CONTAINER_RETRY_COUNT); } else { return DEFAULT_CONTAINER_RETRY_COUNT; } } public int getContainerRetryWindowMs() { if (containsKey(CLUSTER_MANAGER_RETRY_WINDOW_MS)) { return getInt(CLUSTER_MANAGER_RETRY_WINDOW_MS); } else if (containsKey(CONTAINER_RETRY_WINDOW_MS)) { log.info("Configuration {} is deprecated. Please use {}", CONTAINER_RETRY_WINDOW_MS, CLUSTER_MANAGER_RETRY_WINDOW_MS); return getInt(CONTAINER_RETRY_WINDOW_MS); } else { return DEFAULT_CONTAINER_RETRY_WINDOW_MS; } } public int getJobCoordinatorSleepInterval() { return getInt(CLUSTER_MANAGER_SLEEP_MS, DEFAULT_CLUSTER_MANAGER_SLEEP_MS); } public String getContainerManagerClass() { return get(CLUSTER_MANAGER_FACTORY, CLUSTER_MANAGER_FACTORY_DEFAULT); } public boolean getJmxEnabled() { if (containsKey(CLUSTER_MANAGER_JMX_ENABLED)) { return getBoolean(CLUSTER_MANAGER_JMX_ENABLED); } else if (containsKey(AM_JMX_ENABLED)) { log.info("Configuration {} is deprecated. Please use {}", AM_JMX_ENABLED, CLUSTER_MANAGER_JMX_ENABLED); return getBoolean(AM_JMX_ENABLED); } else { return true; } } }
/* * Licensed to ElasticSearch and Shay Banon 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.test.integration.indexlifecycle; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.internal.InternalNode; import org.elasticsearch.test.integration.AbstractNodesTests; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.elasticsearch.client.Requests.*; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.cluster.routing.ShardRoutingState.STARTED; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /** * */ public class IndexLifecycleActionTests extends AbstractNodesTests { private final ESLogger logger = Loggers.getLogger(IndexLifecycleActionTests.class); @AfterMethod public void closeNodes() { closeAllNodes(); } @Test public void testIndexLifecycleActionsWith11Shards1Backup() throws Exception { Settings settings = settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, 11) .put(SETTING_NUMBER_OF_REPLICAS, 1) .put("cluster.routing.schedule", "20ms") // reroute every 20ms so we identify new nodes fast .build(); // start one server logger.info("Starting sever1"); startNode("server1", settings); ClusterService clusterService1 = ((InternalNode) node("server1")).injector().getInstance(ClusterService.class); logger.info("Creating index [test]"); CreateIndexResponse createIndexResponse = client("server1").admin().indices().create(createIndexRequest("test")).actionGet(); assertThat(createIndexResponse.acknowledged(), equalTo(true)); logger.info("Running Cluster Health"); ClusterHealthResponse clusterHealth = client("server1").admin().cluster().prepareHealth().setWaitForYellowStatus().execute().actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.YELLOW)); // sleep till the cluster state gets published, since we check the master Thread.sleep(200); ClusterState clusterState1 = clusterService1.state(); RoutingNode routingNodeEntry1 = clusterState1.readOnlyRoutingNodes().nodesToShards().get(clusterState1.nodes().localNodeId()); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), equalTo(11)); clusterState1 = client("server1").admin().cluster().state(clusterStateRequest()).actionGet().state(); routingNodeEntry1 = clusterState1.readOnlyRoutingNodes().nodesToShards().get(clusterState1.nodes().localNodeId()); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), equalTo(11)); logger.info("Starting server2"); // start another server startNode("server2", settings); ClusterService clusterService2 = ((InternalNode) node("server2")).injector().getInstance(ClusterService.class); logger.info("Running Cluster Health"); clusterHealth = client("server1").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); // sleep till the cluster state gets published, since we check the master Thread.sleep(200); clusterState1 = clusterService1.state(); routingNodeEntry1 = clusterState1.readOnlyRoutingNodes().nodesToShards().get(clusterState1.nodes().localNodeId()); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), equalTo(11)); ClusterState clusterState2 = clusterService2.state(); RoutingNode routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), equalTo(11)); logger.info("Starting server3"); // start another server startNode("server3", settings); Thread.sleep(200); ClusterService clusterService3 = ((InternalNode) node("server3")).injector().getInstance(ClusterService.class); logger.info("Running Cluster Health"); clusterHealth = client("server1").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("3").waitForRelocatingShards(0)).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.relocatingShards(), equalTo(0)); assertThat(clusterHealth.activeShards(), equalTo(22)); assertThat(clusterHealth.activePrimaryShards(), equalTo(11)); // sleep till the cluster state gets published, since we check the master Thread.sleep(200); clusterState1 = clusterService1.state(); routingNodeEntry1 = clusterState1.readOnlyRoutingNodes().nodesToShards().get(clusterState1.nodes().localNodeId()); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), anyOf(equalTo(7), equalTo(8))); clusterState2 = clusterService2.state(); routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(7), equalTo(8))); ClusterState clusterState3 = clusterService3.state(); RoutingNode routingNodeEntry3 = clusterState3.readOnlyRoutingNodes().nodesToShards().get(clusterState3.nodes().localNodeId()); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(7)); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED) + routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(22)); logger.info("Closing server1"); // kill the first server closeNode("server1"); // verify health logger.info("Running Cluster Health"); clusterHealth = client("server2").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.relocatingShards(), equalTo(0)); assertThat(clusterHealth.activeShards(), equalTo(22)); assertThat(clusterHealth.activePrimaryShards(), equalTo(11)); // sleep till the cluster state gets published, since we check the master Thread.sleep(200); clusterState2 = clusterService2.state(); routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), equalTo(11)); clusterState3 = clusterService3.state(); routingNodeEntry3 = clusterState3.readOnlyRoutingNodes().nodesToShards().get(clusterState3.nodes().localNodeId()); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(11)); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(22)); logger.info("Deleting index [test]"); // last, lets delete the index DeleteIndexResponse deleteIndexResponse = client("server2").admin().indices().prepareDelete("test").execute().actionGet(); assertThat(deleteIndexResponse.acknowledged(), equalTo(true)); Thread.sleep(500); // wait till the cluster state gets published clusterState2 = clusterService2.state(); routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2, nullValue()); clusterState3 = clusterService3.state(); routingNodeEntry3 = clusterState3.readOnlyRoutingNodes().nodesToShards().get(clusterState3.nodes().localNodeId()); assertThat(routingNodeEntry3, nullValue()); } @Test public void testIndexLifecycleActionsWith11Shards0Backup() throws Exception { Settings settings = settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, 11) .put(SETTING_NUMBER_OF_REPLICAS, 0) .put("cluster.routing.schedule", "20ms") // reroute every 20ms so we identify new nodes fast .build(); // start one server logger.info("Starting server1"); startNode("server1", settings); ClusterService clusterService1 = ((InternalNode) node("server1")).injector().getInstance(ClusterService.class); logger.info("Creating index [test]"); CreateIndexResponse createIndexResponse = client("server1").admin().indices().create(createIndexRequest("test")).actionGet(); assertThat(createIndexResponse.acknowledged(), equalTo(true)); logger.info("Running Cluster Health"); ClusterHealthResponse clusterHealth = client("server1").admin().cluster().health(clusterHealthRequest().waitForGreenStatus()).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.relocatingShards(), equalTo(0)); assertThat(clusterHealth.activeShards(), equalTo(11)); assertThat(clusterHealth.activePrimaryShards(), equalTo(11)); ClusterState clusterState1 = clusterService1.state(); RoutingNode routingNodeEntry1 = clusterState1.readOnlyRoutingNodes().nodesToShards().get(clusterState1.nodes().localNodeId()); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), equalTo(11)); // start another server logger.info("Starting server2"); startNode("server2", settings); Thread.sleep(200); logger.info("Running Cluster Health"); clusterHealth = client("server1").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("2")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.relocatingShards(), equalTo(0)); assertThat(clusterHealth.activeShards(), equalTo(11)); assertThat(clusterHealth.activePrimaryShards(), equalTo(11)); // sleep till the cluster state gets published, since we check the master Thread.sleep(200); ClusterService clusterService2 = ((InternalNode) node("server2")).injector().getInstance(ClusterService.class); clusterState1 = clusterService1.state(); routingNodeEntry1 = clusterState1.readOnlyRoutingNodes().nodesToShards().get(clusterState1.nodes().localNodeId()); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), anyOf(equalTo(6), equalTo(5))); ClusterState clusterState2 = clusterService2.state(); RoutingNode routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(6))); // start another server logger.info("Starting server3"); startNode("server3"); Thread.sleep(200); ClusterService clusterService3 = ((InternalNode) node("server3")).injector().getInstance(ClusterService.class); logger.info("Running Cluster Health"); clusterHealth = client("server1").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForRelocatingShards(0).waitForNodes("3")).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.relocatingShards(), equalTo(0)); assertThat(clusterHealth.activeShards(), equalTo(11)); assertThat(clusterHealth.activePrimaryShards(), equalTo(11)); // sleep till the cluster state gets published, since we check the master Thread.sleep(200); clusterState1 = clusterService1.state(); routingNodeEntry1 = clusterState1.readOnlyRoutingNodes().nodesToShards().get(clusterState1.nodes().localNodeId()); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(4), equalTo(3))); clusterState2 = clusterService2.state(); routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(4), equalTo(3))); ClusterState clusterState3 = clusterService3.state(); RoutingNode routingNodeEntry3 = clusterState3.readOnlyRoutingNodes().nodesToShards().get(clusterState3.nodes().localNodeId()); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(3)); assertThat(routingNodeEntry1.numberOfShardsWithState(STARTED) + routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(11)); logger.info("Closing server1"); // kill the first server closeNode("server1"); logger.info("Running Cluster Health"); clusterHealth = client("server3").admin().cluster().health(clusterHealthRequest().waitForGreenStatus().waitForNodes("2").waitForRelocatingShards(0)).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.status()); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); assertThat(clusterHealth.relocatingShards(), equalTo(0)); assertThat(clusterHealth.activeShards(), equalTo(11)); assertThat(clusterHealth.activePrimaryShards(), equalTo(11)); // sleep till the cluster state gets published, since we check the master Thread.sleep(200); clusterState2 = clusterService2.state(); routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(6))); clusterState3 = clusterService3.state(); routingNodeEntry3 = clusterState3.readOnlyRoutingNodes().nodesToShards().get(clusterState3.nodes().localNodeId()); assertThat(routingNodeEntry3.numberOfShardsWithState(STARTED), anyOf(equalTo(5), equalTo(6))); assertThat(routingNodeEntry2.numberOfShardsWithState(STARTED) + routingNodeEntry3.numberOfShardsWithState(STARTED), equalTo(11)); logger.info("Deleting index [test]"); // last, lets delete the index DeleteIndexResponse deleteIndexResponse = client("server2").admin().indices().delete(deleteIndexRequest("test")).actionGet(); assertThat(deleteIndexResponse.acknowledged(), equalTo(true)); Thread.sleep(500); // wait till the cluster state gets published clusterState2 = clusterService2.state(); routingNodeEntry2 = clusterState2.readOnlyRoutingNodes().nodesToShards().get(clusterState2.nodes().localNodeId()); assertThat(routingNodeEntry2, nullValue()); clusterState3 = clusterService3.state(); routingNodeEntry3 = clusterState3.readOnlyRoutingNodes().nodesToShards().get(clusterState3.nodes().localNodeId()); assertThat(routingNodeEntry3, nullValue()); } @Test public void testTwoIndicesCreation() throws Exception { Settings settings = settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, 11) .put(SETTING_NUMBER_OF_REPLICAS, 0) .put("cluster.routing.schedule", "20ms") // reroute every 20ms so we identify new nodes fast .build(); // start one server startNode("server1", settings); client("server1").admin().indices().create(createIndexRequest("test1")).actionGet(); client("server1").admin().indices().create(createIndexRequest("test2")).actionGet(); } }
/* * #%L * SparkCommerce Common Libraries * %% * Copyright (C) 2015 Spark Commerce * %% */ package org.sparkcommerce.common.site.service; import org.sparkcommerce.common.site.dao.SiteDao; import org.sparkcommerce.common.site.domain.Catalog; import org.sparkcommerce.common.site.domain.Site; import org.sparkcommerce.common.util.StreamCapableTransactionalOperationAdapter; import org.sparkcommerce.common.util.StreamingTransactionCapableUtil; import org.sparkcommerce.common.util.TransactionUtils; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; @Service("blSiteService") public class SiteServiceImpl implements SiteService { @Resource(name="blStreamingTransactionCapableUtil") protected StreamingTransactionCapableUtil transUtil; @Resource(name = "blSiteDao") protected SiteDao siteDao; @Resource(name = "blSiteServiceExtensionManager") protected SiteServiceExtensionManager extensionManager; @Override public Site createSite() { return siteDao.create(); } @Override @Deprecated public Site retrieveSiteById(final Long id) { return retrieveNonPersistentSiteById(id); } @Override public Site retrieveNonPersistentSiteById(final Long id) { return retrieveSiteById(id, false); } @Override public Site retrievePersistentSiteById(final Long id) { return retrieveSiteById(id, true); } protected Site retrieveSiteById(final Long id, final boolean persistentResult) { //Since the methods on this class are frequently called during regular page requests and transactions are expensive, //only run the operation under a transaction if there is not already an entity manager in the view final Site[] response = new Site[1]; transUtil.runOptionalTransactionalOperation(new StreamCapableTransactionalOperationAdapter() { @Override public void execute() throws Throwable { Site site = siteDao.retrieve(id); if (persistentResult) { response[0] = site; } else { response[0] = getNonPersistentSite(site); } } }, RuntimeException.class, !TransactionSynchronizationManager.hasResource(((JpaTransactionManager) transUtil.getTransactionManager()).getEntityManagerFactory())); return response[0]; } @Override @Deprecated public Site retrieveSiteByDomainName(final String domainName) { return retrieveNonPersistentSiteByDomainName(domainName); } @Override public Site retrieveNonPersistentSiteByDomainName(final String domainName) { return retrieveSiteByDomainName(domainName, false); } @Override public Site retrievePersistentSiteByDomainName(final String domainName) { return retrieveSiteByDomainName(domainName, true); } public Site retrieveSiteByDomainName(final String domainName, final boolean persistentResult) { //Since the methods on this class are frequently called during regular page requests and transactions are expensive, //only run the operation under a transaction if there is not already an entity manager in the view final Site[] response = new Site[1]; transUtil.runOptionalTransactionalOperation(new StreamCapableTransactionalOperationAdapter() { @Override public void execute() throws Throwable { String domainPrefix = null; if (domainName != null) { int pos = domainName.indexOf('.'); if (pos >= 0) { domainPrefix = domainName.substring(0, pos); } else { domainPrefix = domainName; } } Site site = siteDao.retrieveSiteByDomainOrDomainPrefix(domainName, domainPrefix); if (persistentResult) { response[0] = site; } else { response[0] = getNonPersistentSite(site); } } }, RuntimeException.class, !TransactionSynchronizationManager.hasResource(((JpaTransactionManager) transUtil.getTransactionManager()).getEntityManagerFactory())); return response[0]; } @Override @Deprecated @Transactional("blTransactionManager") public Site save(Site site) { return saveAndReturnNonPersisted(site); } @Override @Transactional("blTransactionManager") public Site saveAndReturnNonPersisted(Site site) { return getNonPersistentSite(saveAndReturnPersisted(site)); } @Override @Transactional("blTransactionManager") public Site saveAndReturnPersisted(Site site) { return siteDao.save(site); } @Override public Catalog findCatalogById(Long id) { return siteDao.retrieveCatalog(id); } @Override @Deprecated public Site retrieveDefaultSite() { return retrieveNonPersistentDefaultSite(); } @Override public Site retrieveNonPersistentDefaultSite() { return getNonPersistentSite(retrievePersistentDefaultSite()); } @Override public Site retrievePersistentDefaultSite() { return retrieveDefaultSite(true); } protected Site retrieveDefaultSite(final boolean persistentResult) { //Since the methods on this class are frequently called during regular page requests and transactions are expensive, //only run the operation under a transaction if there is not already an entity manager in the view final Site[] response = new Site[1]; transUtil.runOptionalTransactionalOperation(new StreamCapableTransactionalOperationAdapter() { @Override public void execute() throws Throwable { Site defaultSite = siteDao.retrieveDefaultSite(); if (persistentResult) { response[0] = defaultSite; } else { response[0] = getNonPersistentSite(defaultSite); } } }, RuntimeException.class, !TransactionSynchronizationManager.hasResource(((JpaTransactionManager) transUtil.getTransactionManager()).getEntityManagerFactory())); return response[0]; } @Override @Deprecated public List<Site> findAllActiveSites() { return findAllNonPersistentActiveSites(); } @Override public List<Site> findAllNonPersistentActiveSites() { return findAllSites(false); } @Override public List<Site> findAllPersistentActiveSites() { return findAllSites(true); } protected List<Site> findAllSites(final boolean persistentResult) { //Since the methods on this class are frequently called during regular page requests and transactions are expensive, //only run the operation under a transaction if there is not already an entity manager in the view final List<Site> response = new ArrayList<Site>(); transUtil.runOptionalTransactionalOperation(new StreamCapableTransactionalOperationAdapter() { @Override public void execute() throws Throwable { List<Site> sites = siteDao.readAllActiveSites(); for (Site site : sites) { if (persistentResult) { response.add(site); } else { response.add(getNonPersistentSite(site)); } } } }, RuntimeException.class, !TransactionSynchronizationManager.hasResource(((JpaTransactionManager) transUtil.getTransactionManager()).getEntityManagerFactory())); return response; } protected Site getNonPersistentSite(Site persistentSite) { if (persistentSite == null) { return null; } Site clone = persistentSite.clone(); extensionManager.getProxy().contributeNonPersitentSiteProperties(persistentSite, clone); return clone; } @Override @Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER) public Catalog save(Catalog catalog) { return siteDao.save(catalog); } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.firstrun; import android.accounts.Account; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.os.Bundle; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.CommandLine; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.ChromeSwitches; import org.chromium.chrome.browser.ChromeVersionInfo; import org.chromium.chrome.browser.ChromiumApplication; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager; import org.chromium.chrome.browser.services.AndroidEduAndChildAccountHelper; import org.chromium.chrome.browser.signin.SigninManager; import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.sync.signin.AccountManagerHelper; import org.chromium.sync.signin.ChromeSigninController; /** * A helper to determine what should be the sequence of First Run Experience screens. * Usage: * new FirstRunFlowSequencer(activity, launcherProvidedProperties) { * override onFlowIsKnown * }.start(); */ public abstract class FirstRunFlowSequencer { private final Activity mActivity; private final Bundle mLaunchProperties; private boolean mIsAndroidEduDevice; private boolean mHasChildAccount; /** * Callback that is called once the flow is determined. * If the properties is null, the First Run experience needs to finish and * restart the original intent if necessary. * @param activity An activity. * @param freProperties Properties to be used in the First Run activity, or null. */ public abstract void onFlowIsKnown(Activity activity, Bundle freProperties); public FirstRunFlowSequencer(Activity activity, Bundle launcherProvidedProperties) { mActivity = activity; mLaunchProperties = launcherProvidedProperties; } /** * Starts determining parameters for the First Run. * Once finished, calls onFlowIsKnown(). */ public void start() { if (CommandLine.getInstance().hasSwitch(ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE)) { onFlowIsKnown(mActivity, null); return; } if (!mLaunchProperties.getBoolean(FirstRunActivity.USE_FRE_FLOW_SEQUENCER)) { onFlowIsKnown(mActivity, mLaunchProperties); return; } new AndroidEduAndChildAccountHelper() { @Override public void onParametersReady() { mIsAndroidEduDevice = isAndroidEduDevice(); mHasChildAccount = hasChildAccount(); processFreEnvironment(); } }.start(mActivity); } /** * @return Whether the sync could be turned on. */ @VisibleForTesting boolean isSyncAllowed() { return FeatureUtilities.canAllowSync(mActivity) && !SigninManager.get(mActivity.getApplicationContext()).isSigninDisabledByPolicy(); } /** * @return Whether Terms of Service could be assumed to be accepted. */ @VisibleForTesting boolean didAcceptToS() { return ToSAckedReceiver.checkAnyUserHasSeenToS(mActivity) || PrefServiceBridge.getInstance().isFirstRunEulaAccepted(); } /** * @return Whether Chrome was installed as a part of the system image. */ @VisibleForTesting boolean isSystemInstall() { return ((mActivity.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) != 0); } private void processFreEnvironment() { final Context context = mActivity.getApplicationContext(); if (FirstRunStatus.getFirstRunFlowComplete(mActivity)) { assert PrefServiceBridge.getInstance().isFirstRunEulaAccepted(); // We do not need any interactive FRE. onFlowIsKnown(mActivity, null); return; } Bundle freProperties = new Bundle(); freProperties.putAll(mLaunchProperties); freProperties.remove(FirstRunActivity.USE_FRE_FLOW_SEQUENCER); final Account[] googleAccounts = AccountManagerHelper.get(context).getGoogleAccounts(); final boolean onlyOneAccount = googleAccounts.length == 1; // EDU devices should always have exactly 1 google account, which will be automatically // signed-in. All FRE screens are skipped in this case. final boolean forceEduSignIn = mIsAndroidEduDevice && onlyOneAccount && !ChromeSigninController.get(context).isSignedIn(); final boolean shouldSkipFirstUseHints = ApiCompatibilityUtils.shouldSkipFirstUseHints(context.getContentResolver()); if (!FirstRunStatus.getFirstRunFlowComplete(context)) { // In the full FRE we always show the Welcome page, except on EDU devices. final boolean showWelcomePage = !forceEduSignIn; freProperties.putBoolean(FirstRunActivity.SHOW_WELCOME_PAGE, showWelcomePage); // Enable reporting by default on non-Stable releases. // The user can turn it off on the Welcome page. // This is controlled by the administrator via a policy on EDU devices. if (!ChromeVersionInfo.isStableBuild()) { PrivacyPreferencesManager.getInstance(mActivity).initCrashUploadPreference(true); } // We show the sign-in page if sync is allowed, and this is not an EDU device, and // - no "skip the first use hints" is set, or // - "skip the first use hints" is set, but there is at least one account. final boolean syncOk = isSyncAllowed(); final boolean offerSignInOk = syncOk && !forceEduSignIn && (!shouldSkipFirstUseHints || googleAccounts.length > 0); freProperties.putBoolean(FirstRunActivity.SHOW_SIGNIN_PAGE, offerSignInOk); if (offerSignInOk || forceEduSignIn) { // If the user has accepted the ToS in the Setup Wizard and there is exactly // one account, or if the device has a child account, or if the device is an // Android EDU device and there is exactly one account, preselect the sign-in // account and force the selection if necessary. if ((ToSAckedReceiver.checkAnyUserHasSeenToS(mActivity) && onlyOneAccount) || mHasChildAccount || forceEduSignIn) { freProperties.putString(AccountFirstRunFragment.FORCE_SIGNIN_ACCOUNT_TO, googleAccounts[0].name); freProperties.putBoolean(AccountFirstRunFragment.PRESELECT_BUT_ALLOW_TO_CHANGE, !forceEduSignIn && !mHasChildAccount); } } } else { // If the full FRE has already been shown, don't show Welcome or Sign-In pages. freProperties.putBoolean(FirstRunActivity.SHOW_WELCOME_PAGE, false); freProperties.putBoolean(FirstRunActivity.SHOW_SIGNIN_PAGE, false); } freProperties.putBoolean(AccountFirstRunFragment.IS_CHILD_ACCOUNT, mHasChildAccount); onFlowIsKnown(mActivity, freProperties); } /** * Marks a given flow as completed. * @param activity An activity. * @param data Resulting FRE properties bundle. */ public static void markFlowAsCompleted(Activity activity, Bundle data) { // When the user accepts ToS in the Setup Wizard (see ToSAckedReceiver), we do not // show the ToS page to the user because the user has already accepted one outside FRE. if (!PrefServiceBridge.getInstance().isFirstRunEulaAccepted()) { PrefServiceBridge.getInstance().setEulaAccepted(); } // Mark the FRE flow as complete and set the sign-in flow preferences if necessary. FirstRunSignInProcessor.finalizeFirstRunFlowState(activity, data); } /** * Checks if the First Run needs to be launched. * @return The intent to launch the First Run Experience if necessary, or null. * @param activity The context * @param originalIntent An original intent * @param fromChromeIcon Whether Chrome is opened via the Chrome icon */ public static Intent checkIfFirstRunIsNecessary(Activity activity, Intent originalIntent, boolean fromChromeIcon) { // If FRE is disabled (e.g. in tests), proceed directly to the intent handling. if (CommandLine.getInstance().hasSwitch(ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE)) { return null; } // If Chrome isn't opened via the Chrome icon, and the user accepted the ToS // in the Setup Wizard, skip any First Run Experience screens and proceed directly // to the intent handling. if (!fromChromeIcon && ToSAckedReceiver.checkAnyUserHasSeenToS(activity)) return null; // If the user hasn't been through the First Run Activity -- it must be shown. final boolean baseFreComplete = FirstRunStatus.getFirstRunFlowComplete(activity); if (!baseFreComplete) { return createGenericFirstRunIntent(activity, originalIntent, fromChromeIcon); } // If Chrome isn't opened via the Chrome icon proceed directly to the intent handling. if (!fromChromeIcon) return null; return createGenericFirstRunIntent(activity, originalIntent, fromChromeIcon); } /** * @return A generic intent to show the First Run Activity. * @param activity The context * @param originalIntent An original intent * @param fromChromeIcon Whether Chrome is opened via the Chrome icon */ public static Intent createGenericFirstRunIntent( Activity activity, Intent originalIntent, boolean fromChromeIcon) { ChromiumApplication application = (ChromiumApplication) activity.getApplication(); String activityName = application.getFirstRunActivityName(); Intent intent = new Intent(); intent.setClassName(activity, activityName); intent.putExtra(FirstRunActivity.COMING_FROM_CHROME_ICON, fromChromeIcon); intent.putExtra(FirstRunActivity.USE_FRE_FLOW_SEQUENCER, true); return intent; } }
/* * Copyright 2012-2014 eBay Software Foundation and selendroid committers. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.selendroid.server.model; import static io.selendroid.server.model.DeviceStoreFixture.anDevice; import static io.selendroid.server.model.DeviceStoreFixture.anDeviceManager; import static io.selendroid.server.model.DeviceStoreFixture.anEmulator; import static io.selendroid.server.model.DeviceStoreFixture.withDefaultCapabilities; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import io.selendroid.SelendroidCapabilities; import io.selendroid.android.AndroidDevice; import io.selendroid.android.AndroidEmulator; import io.selendroid.android.impl.DefaultAndroidEmulator; import io.selendroid.android.impl.DefaultHardwareDevice; import io.selendroid.device.DeviceTargetPlatform; import io.selendroid.exceptions.AndroidDeviceException; import io.selendroid.exceptions.DeviceStoreException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.Dimension; /** * @author ddary */ public class DeviceStoreTest { public static final String ANY_STRING = "ANY"; private static final Integer EMULATOR_PORT = 5560; @Test public void shouldAddStartedEmulator() throws Exception { AndroidEmulator emulator = anEmulator("de", DeviceTargetPlatform.ANDROID10, false); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Collections.singletonList(emulator)); Assert.assertEquals(deviceStore.getDevicesInUse().size(), 0); Assert.assertEquals(deviceStore.getDevicesList().size(), 1); Assert.assertTrue(deviceStore.getDevicesList().containsKey(DeviceTargetPlatform.ANDROID10)); Assert.assertTrue(deviceStore.getDevicesList().get(DeviceTargetPlatform.ANDROID10) .contains(emulator)); } @Test public void shouldIncrementEmulatorPortsByTwo() throws Exception { DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); Assert.assertEquals(5560, deviceStore.nextEmulatorPort().intValue()); Assert.assertEquals(5562, deviceStore.nextEmulatorPort().intValue()); Assert.assertEquals(5564, deviceStore.nextEmulatorPort().intValue()); } @Test public void shouldReleaseActiveEmulators() throws Exception { AndroidEmulator deEmulator = anEmulator("de", DeviceTargetPlatform.ANDROID16, false); when(deEmulator.getPort()).thenReturn(5554); EmulatorPortFinder finder = mock(EmulatorPortFinder.class); when(finder.next()).thenReturn(5554); DeviceStore deviceStore = new DeviceStore(finder, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator})); Assert.assertEquals(deviceStore.getDevicesInUse().size(), 0); AndroidDevice foundDevice = deviceStore.findAndroidDevice(withDefaultCapabilities()); Assert.assertEquals(deEmulator, foundDevice); Assert.assertEquals(deviceStore.getDevicesInUse().size(), 1); deviceStore.release(foundDevice, null); // make sure the emulator has been stopped verify(deEmulator, times(1)).stop(); verify(finder, times(1)).release(5554); // Make sure the device has been removed from devices in use Assert.assertEquals(deviceStore.getDevicesInUse().size(), 0); } @Test public void shouldRegisterMultipleNotStatedEmulators() throws Exception { AndroidEmulator deEmulator10 = anEmulator("de", DeviceTargetPlatform.ANDROID10, false); AndroidEmulator enEmulator10 = anEmulator("en", DeviceTargetPlatform.ANDROID10, false); AndroidEmulator deEmulator16 = anEmulator("de", DeviceTargetPlatform.ANDROID16, false); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator10, enEmulator10, deEmulator16})); Assert.assertEquals(deviceStore.getDevicesInUse().size(), 0); // Expecting two entries for two android target platforms Assert.assertEquals(deviceStore.getDevicesList().size(), 2); Assert.assertTrue(deviceStore.getDevicesList().containsKey(DeviceTargetPlatform.ANDROID10)); Assert.assertTrue(deviceStore.getDevicesList().get(DeviceTargetPlatform.ANDROID10) .contains(deEmulator10)); Assert.assertTrue(deviceStore.getDevicesList().get(DeviceTargetPlatform.ANDROID10) .contains(enEmulator10)); Assert.assertTrue(deviceStore.getDevicesList().get(DeviceTargetPlatform.ANDROID16) .contains(deEmulator16)); } @Test public void shouldRegisterStartedAndStoppedEmulators() throws Exception { AndroidEmulator deEmulator10 = anEmulator("de", DeviceTargetPlatform.ANDROID10, false); AndroidEmulator enEmulator10 = anEmulator("en", DeviceTargetPlatform.ANDROID10, true); AndroidEmulator deEmulator16 = anEmulator("de", DeviceTargetPlatform.ANDROID16, true); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator10, enEmulator10, deEmulator16})); Assert.assertEquals(deviceStore.getDevicesInUse().size(), 0); Assert.assertTrue("Should have an entry for target version 10.", deviceStore.getDevicesList() .containsKey(DeviceTargetPlatform.ANDROID10)); List<AndroidDevice> devicesApi10 = deviceStore.getDevicesList().get(DeviceTargetPlatform.ANDROID10); Assert.assertTrue("Entry of target version 10 should contain de emulator.", devicesApi10.contains(deEmulator10)); Assert.assertTrue("Entry of target version 10 should contain en emulator.", devicesApi10.contains(enEmulator10)); Assert.assertTrue("Should have an entry for target version 16.", deviceStore.getDevicesList() .containsKey(DeviceTargetPlatform.ANDROID16)); Assert.assertTrue("Entry of target version 16 should contain the emulator.", deviceStore .getDevicesList().get(DeviceTargetPlatform.ANDROID16).contains(deEmulator16)); } @Test public void shouldNotIgnoreRunningEmulators() throws Exception { AndroidEmulator enEmulator10 = anEmulator("en", DeviceTargetPlatform.ANDROID10, true); AndroidEmulator deEmulator16 = anEmulator("de", DeviceTargetPlatform.ANDROID16, true); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {enEmulator10, deEmulator16})); // Nothing has been added. Assert.assertEquals(deviceStore.getDevicesList().size(), 2); } @Test public void storeShouldDoNothingIfInitializedWithEmptyList() throws AndroidDeviceException { DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addEmulators(new ArrayList<AndroidEmulator>()); Assert.assertEquals(store.getDevicesList().size(), 0); } @Test public void storeShouldDoNothingIfInitializedWithNull() throws AndroidDeviceException { DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addEmulators(null); Assert.assertEquals(store.getDevicesList().size(), 0); } @Test public void shouldFindSwitchedOffEmulator() throws Exception { // prepare device store DefaultAndroidEmulator deEmulator16 = anEmulator("de", DeviceTargetPlatform.ANDROID16, false); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator16})); // find by Capabilities AndroidDevice device = deviceStore.findAndroidDevice(withDefaultCapabilities()); // The right device is found assertThat(device, equalTo((AndroidDevice) deEmulator16)); // the device is in use when found assertThat(deviceStore.getDevicesInUse(), contains((AndroidDevice) deEmulator16)); } @Test public void shouldThrowAnExceptionIfTargetPlatformIsMissingInCapabilities() throws Exception { // prepare device store DefaultAndroidEmulator deEmulator16 = anEmulator("de", DeviceTargetPlatform.ANDROID16, false); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator16})); SelendroidCapabilities capa = new SelendroidCapabilities(); try { deviceStore.findAndroidDevice(capa); Assert.fail(); } catch (DeviceStoreException e) { Assert .assertEquals( "No devices are found. This can happen if the devices are in use or no device screen matches the required capabilities.", e.getMessage()); } } @Test public void shouldNotFindDeviceIfTargetPlatformIsNotSuported() throws Exception { // prepare device store DefaultAndroidEmulator deEmulator10 = anEmulator("de", DeviceTargetPlatform.ANDROID10, false); AndroidEmulator enEmulator10 = anEmulator("en", DeviceTargetPlatform.ANDROID10, false); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator10, enEmulator10})); // find by Capabilities try { deviceStore.findAndroidDevice(withDefaultCapabilities()); Assert.fail(); } catch (DeviceStoreException e) { assertThat( e.getMessage(), equalTo("No devices are found. This can happen if the devices are in use or no device screen matches the required capabilities.")); } assertThat(deviceStore.getDevicesInUse(), hasSize(0)); } @Test public void shouldNotFindDeviceIfScreenSizeIsNotSupported() throws Exception { // prepare device store DefaultAndroidEmulator deEmulator10 = anEmulator("de", DeviceTargetPlatform.ANDROID16, false); AndroidEmulator enEmulator10 = anEmulator("en", DeviceTargetPlatform.ANDROID10, false); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator10, enEmulator10})); // find by Capabilities SelendroidCapabilities capa = withDefaultCapabilities(); capa.setScreenSize("768x1024"); try { deviceStore.findAndroidDevice(capa); Assert.fail(); } catch (DeviceStoreException e) { assertThat(e.getMessage(), containsString("No devices are found.")); } assertThat(deviceStore.getDevicesInUse(), hasSize(0)); assertThat(deviceStore.getDevicesList().values(), hasSize(2)); } @Test public void testShouldBeAbleToAddDevices() throws Exception { AndroidDevice device = mock(AndroidDevice.class); when(device.getTargetPlatform()).thenReturn(DeviceTargetPlatform.ANDROID16); when(device.isDeviceReady()).thenReturn(Boolean.TRUE); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addDevice(device); assertThat(store.getDevicesList().values(), hasSize(1)); assertThat(store.getDevicesInUse(), hasSize(0)); assertThat(store.getDevicesList().values().iterator().next(), contains(device)); } @Test public void testShouldBeAbleToUpdateDevices() throws Exception { AndroidEmulator emulator = anEmulator("de", DeviceTargetPlatform.ANDROID10, false); Map<String,String> prop = new HashMap(); // used for phone properties AndroidDevice device = anDevice("01234ABC", prop); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addEmulators(Arrays.asList(new AndroidEmulator[] {emulator})); // Emulating ddmlib behavior. // Add device with empty property because HardwareDeviceListener#onDeviceConnected is called // before phone properties are available store.addDevice(device); assertThat(store.getDevicesList().get(null), hasSize(1)); assertThat(store.getDevicesList().get(null), contains(device)); // After phone properties are available, HardwareDeviceListener#onDeviceChanged is called prop.put("ro.build.version.sdk", "16"); prop.put("ro.product.model", "en"); store.updateDevice(device); assertThat(store.getDevicesList().get(null), hasSize(0)); assertThat(store.getDevicesList().get(DeviceTargetPlatform.ANDROID16), hasSize(1)); assertThat(store.getDevicesList().get(DeviceTargetPlatform.ANDROID16), contains(device)); } @Test public void testShouldBeAbleToRemoveDevices() throws Exception { DefaultAndroidEmulator emulator = anEmulator("de", DeviceTargetPlatform.ANDROID10, false); AndroidDevice device = anDevice("en", DeviceTargetPlatform.ANDROID16); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addEmulators(Arrays.asList(new AndroidEmulator[] {emulator})); store.addDevice(device); store.removeAndroidDevice(device); assertThat(store.getDevicesList().values(), hasSize(1)); assertThat(store.getDevicesList().values().iterator().next(), contains((AndroidDevice) emulator)); } @Test public void shouldIgnoreNotReadyDevices() throws Exception { AndroidDevice device = mock(AndroidDevice.class); when(device.getTargetPlatform()).thenReturn(DeviceTargetPlatform.ANDROID16); when(device.isDeviceReady()).thenReturn(Boolean.FALSE); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addDevice(device); assertThat(store.getDevicesList().values(), hasSize(0)); assertThat(store.getDevicesInUse(), hasSize(0)); } @Test public void shouldFindRealDeviceForCapabilities() throws Exception { AndroidDevice device = mock(DefaultHardwareDevice.class); when(device.getTargetPlatform()).thenReturn(DeviceTargetPlatform.ANDROID16); when(device.isDeviceReady()).thenReturn(Boolean.TRUE); when(device.getScreenSize()).thenReturn(new Dimension(320, 480)); when(device.screenSizeMatches("320x480")).thenReturn(Boolean.TRUE); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addDevice(device); assertThat(store.getDevicesList().values(), hasSize(1)); assertThat(store.getDevicesInUse(), hasSize(0)); SelendroidCapabilities capa = withDefaultCapabilities(); capa.setEmulator(false); AndroidDevice foundDevice = store.findAndroidDevice(capa); assertThat(foundDevice, equalTo(device)); assertThat(store.getDevicesInUse(), hasSize(1)); } @Test public void shouldNotFindRealDeviceForCapabilities() throws Exception { AndroidDevice device = mock(AndroidDevice.class); when(device.getTargetPlatform()).thenReturn(DeviceTargetPlatform.ANDROID16); when(device.isDeviceReady()).thenReturn(Boolean.TRUE); when(device.getScreenSize()).thenReturn(new Dimension(320, 500)); when(device.screenSizeMatches("320x500")).thenReturn(Boolean.FALSE); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addDevice(device); assertThat(store.getDevicesList().values(), hasSize(1)); assertThat(store.getDevicesInUse(), hasSize(0)); try { store.findAndroidDevice(withDefaultCapabilities()); Assert.fail(); } catch (DeviceStoreException e) { // expected } assertThat(store.getDevicesInUse(), hasSize(0)); } @Test public void shouldFindRealDeviceBySerial() throws Exception { AndroidDevice device1 = mock(DefaultHardwareDevice.class); String device1Serial = "device1Serial"; AndroidDevice device2 = mock(DefaultHardwareDevice.class); String device2Serial = "device2Serial"; for (AndroidDevice device : Lists.newArrayList(device1, device2)) { when(device.getTargetPlatform()).thenReturn(DeviceTargetPlatform.ANDROID16); when(device.isDeviceReady()).thenReturn(Boolean.TRUE); when(device.getScreenSize()).thenReturn(new Dimension(320, 480)); when(device.screenSizeMatches("320x480")).thenReturn(Boolean.TRUE); } when(device1.getSerial()).thenReturn(device1Serial); when(device2.getSerial()).thenReturn(device2Serial); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addDevice(device1); store.addDevice(device2); assertThat(store.getDevicesList().values(), hasSize(1)); assertThat(store.getDevicesList().get(DeviceTargetPlatform.ANDROID16), hasSize(2)); assertThat(store.getDevicesInUse(), hasSize(0)); SelendroidCapabilities capa = withDefaultCapabilities(); capa.setEmulator(false); capa.setSerial(device2Serial); AndroidDevice foundDevice = store.findAndroidDevice(capa); assertThat(foundDevice, equalTo(device2)); assertThat(Iterables.getOnlyElement(store.getDevicesInUse()), is(device2)); } @Test(expected = DeviceStoreException.class) public void willNotReturnADeviceInUse() throws Exception { AndroidDevice device = mock(DefaultHardwareDevice.class); String serial = "device1Serial"; when(device.getTargetPlatform()).thenReturn(DeviceTargetPlatform.ANDROID16); when(device.isDeviceReady()).thenReturn(Boolean.TRUE); when(device.getScreenSize()).thenReturn(new Dimension(320, 480)); when(device.screenSizeMatches("320x480")).thenReturn(Boolean.TRUE); when(device.getSerial()).thenReturn(serial); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addDevice(device); store.getDevicesInUse().add(device); SelendroidCapabilities capa = withDefaultCapabilities(); capa.setEmulator(false); capa.setSerial(serial); store.findAndroidDevice(withDefaultCapabilities()); } @Test(expected = IllegalArgumentException.class) public void findAndroidDeviceThrowsIllegalArgumentExceptionIfCapabilitiesNull() throws Exception { DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.findAndroidDevice(null); } @Test(expected = DeviceStoreException.class) public void findAndroidDeviceThrowsDeviceStoreExceptionIfNoDevices() throws Exception { DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.getDevices().clear(); store.findAndroidDevice(withDefaultCapabilities()); } @Test public void shouldRemoveHardwareDevice() throws Exception { DefaultHardwareDevice device = anDevice("de", DeviceTargetPlatform.ANDROID16); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addDevice(device); assertThat(store.getDevicesList().values(), hasSize(1)); store.removeAndroidDevice(device); assertThat(store.getDevicesList().values(), hasSize(0)); } @Test public void shouldNotRemoveAnEmulator() throws Exception { DefaultAndroidEmulator deEmulator10 = anEmulator("de", DeviceTargetPlatform.ANDROID16, false); DeviceStore store = new DeviceStore(EMULATOR_PORT, anDeviceManager()); store.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator10})); assertThat(store.getDevicesList().values(), hasSize(1)); try { store.removeAndroidDevice(deEmulator10); Assert.fail("Only hardware devices should be able to be removed."); } catch (DeviceStoreException e) { // expected } } @Test public void shouldFindStartedEmulator() throws Exception { // prepare device store DefaultAndroidEmulator deEmulator16 = anEmulator("de", DeviceTargetPlatform.ANDROID16, true); DeviceStore deviceStore = new DeviceStore(EMULATOR_PORT, anDeviceManager()); deviceStore.addEmulators(Arrays.asList(new AndroidEmulator[] {deEmulator16})); // find by Capabilities AndroidDevice device = deviceStore.findAndroidDevice(withDefaultCapabilities()); // The right device is found assertThat(device, equalTo((AndroidDevice) deEmulator16)); // the device is in use when found assertThat(deviceStore.getDevicesInUse(), contains((AndroidDevice) deEmulator16)); } }
/******************************************************************************* * Copyright 2008 Amazon Technologies, 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://aws.amazon.com/apache2.0 * 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * Amazon FPS Java Library * API Version: 2008-09-17 * Generated: Tue Sep 29 03:25:00 PDT 2009 * */ package com.amazonaws.fps; import com.amazonaws.utils.PropertyBundle; import com.amazonaws.utils.PropertyKeys; /** * Configuration for accessing Amazon FPS service */ public class AmazonFPSConfig { private String serviceVersion = "2008-09-17"; private String serviceURL = PropertyBundle.getProperty(PropertyKeys.AWS_SERVICE_END_POINT); private String userAgent = "Amazon FPS Java Library"; private String signatureVersion = "2"; private String signatureMethod = "HmacSHA256"; private String proxyHost = null; private int proxyPort = Integer.parseInt(PropertyBundle.getProperty(PropertyKeys.PROXY_PORT)); private String proxyUsername = PropertyBundle.getProperty(PropertyKeys.PROXY_USER_NAME); private String proxyPassword = PropertyBundle.getProperty(PropertyKeys.PROXY_PASSWORD); private int maxErrorRetry = Integer.parseInt(PropertyBundle.getProperty(PropertyKeys.MAX_ERROR_RETRY)); private int maxConnections = Integer.parseInt(PropertyBundle.getProperty(PropertyKeys.MAX_CONNECTIONS)); /** * Gets Version of the API * * @return Version of the Service */ public String getServiceVersion() { return serviceVersion; } /** * Gets SignatureVersion property * * @return Signature Version for signing requests */ public String getSignatureVersion() { return signatureVersion; } /** * Sets SignatureVersion property * * @param signatureVersion Signature Version for signing requests */ public void setSignatureVersion(String signatureVersion) { this.signatureVersion = signatureVersion; } /** * Sets SignatureVersion property and returns current AmazonFPSConfig * * @param signatureVersion Signature Version for signing requests * * @return AmazonFPSConfig */ public AmazonFPSConfig withSignatureVersion(String signatureVersion) { setSignatureVersion(signatureVersion); return this; } /** * Checks if SignatureVersion property is set * * @return true if SignatureVersion property is set */ public boolean isSetSignatureVersion() { return true; } /** * Gets SignatureMethod property * * @return Signature Method for signing requests */ public String getSignatureMethod() { return signatureMethod; } /** * Sets SignatureMethod property * * @param signatureMethod Signature Method for signing requests */ public void setSignatureMethod(String signatureMethod) { this.signatureMethod = signatureMethod; } /** * Sets SignatureMethod property and returns current AmazonFPSConfig * * @param signatureMethod Signature Method for signing requests * * @return AmazonFPSConfig */ public AmazonFPSConfig withSignatureMethod(String signatureMethod) { setSignatureMethod(signatureMethod); return this; } /** * Checks if SignatureMethod property is set * * @return true if SignatureMethod property is set */ public boolean isSetSignatureMethod() { return true; } /** * Gets UserAgent property * * @return User Agent String to use when sending request */ public String getUserAgent() { return userAgent; } /** * Sets UserAgent property * * @param userAgent User Agent String to use when sending request * */ public void setUserAgent(String userAgent) { this.userAgent = userAgent; } /** * Sets UserAgent property and returns current AmazonFPSConfig * * @param userAgent User Agent String to use when sending request * * @return AmazonFPSConfig */ public AmazonFPSConfig withUserAgent(String userAgent) { setUserAgent(userAgent); return this; } /** * Checks if UserAgent property is set * * @return true if UserAgent property is set */ public boolean isSetUserAgent() { return this.userAgent != null; } /** * Gets ServiceURL property * * @return Service Endpoint URL */ public String getServiceURL() { return serviceURL; } /** * Sets ServiceURL property * * @param serviceURL Service Endpoint URL * */ public void setServiceURL(String serviceURL) { this.serviceURL = serviceURL; } /** * Sets ServiceURL property and returns current AmazonFPSConfig * * @param serviceURL Service Endpoint URL * * @return AmazonFPSConfig */ public AmazonFPSConfig withServiceURL(String serviceURL) { setServiceURL(serviceURL); return this; } /** * Checks if ServiceURL property is set * * @return true if ServiceURL property is set */ public boolean isSetServiceURL() { return this.serviceURL != null; } /** * Gets ProxyHost property * * @return Proxy Host for connection */ public String getProxyHost() { return proxyHost; } /** * Sets ProxyHost property * * @param proxyHost Proxy Host for connection * */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } /** * Sets ProxyHost property and returns current AmazonFPSConfig * * @param proxyHost Proxy Host for connection * * @return AmazonFPSConfig */ public AmazonFPSConfig withProxyHost(String proxyHost) { setProxyHost(proxyHost); return this; } /** * Checks if ProxyHost property is set * * @return true if ProxyHost property is set */ public boolean isSetProxyHost() { return this.proxyHost != null; } /** * Gets ProxyPort property * * @return Proxy Port for connection */ public int getProxyPort() { return proxyPort; } /** * Sets ProxyPort property * * @param proxyPort Proxy Port for connection * */ public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } /** * Sets ProxyPort property and returns current AmazonFPSConfig * * @param proxyPort Proxy Port for connection * * @return AmazonFPSConfig */ public AmazonFPSConfig withProxyPort(int proxyPort) { setProxyPort(proxyPort); return this; } /** * Checks if ProxyPort property is set * * @return true if ProxyPort property is set */ public boolean isSetProxyPort() { return this.proxyPort != -1; } /** * Gets ProxyUsername property * * @return Proxy Username */ public String getProxyUsername() { return proxyUsername; } /** * Sets ProxyUsername property * * @param proxyUsername Proxy Username for connection * */ public void setProxyUsername(String proxyUsername) { this.proxyUsername = proxyUsername; } /** * Sets ProxyUsername property and returns current AmazonFPSConfig * * @param proxyUsername Proxy Username for connection * * @return AmazonFPSConfig */ public AmazonFPSConfig withProxyUsername(String proxyUsername) { setProxyUsername(proxyUsername); return this; } /** * Checks if ProxyUsername property is set * * @return true if ProxyUsername property is set */ public boolean isSetProxyUsername() { return this.proxyUsername != null; } /** * Gets ProxyPassword property * * @return Proxy Password */ public String getProxyPassword() { return proxyPassword; } /** * Sets ProxyPassword property * * @param proxyPassword Proxy Password for connection * */ public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } /** * Sets ProxyPassword property and returns current AmazonFPSConfig * * @param proxyPassword Proxy Password for connection * * @return AmazonFPSConfig */ public AmazonFPSConfig withProxyPassword(String proxyPassword) { setProxyPassword(proxyPassword); return this; } /** * Checks if ProxyPassword property is set * * @return true if ProxyPassword property is set */ public boolean isSetProxyPassword() { return this.proxyPassword != null; } /** * Gets MaxErrorRetry property * * @return Max number of retries on 500th errors */ public int getMaxErrorRetry() { return maxErrorRetry; } /** * Sets MaxErrorRetry property * * @param maxErrorRetry Max number of retries on 500th errors * */ public void setMaxErrorRetry(int maxErrorRetry) { this.maxErrorRetry = maxErrorRetry; } /** * Sets MaxErrorRetry property and returns current AmazonFPSConfig * * @param maxErrorRetry Max number of retries on 500th errors * * @return AmazonFPSConfig */ public AmazonFPSConfig withMaxErrorRetry(int maxErrorRetry) { setMaxErrorRetry(maxErrorRetry); return this; } /** * Checks if MaxErrorRetry property is set * * @return true if MaxErrorRetry property is set */ public boolean isSetMaxErrorRetry() { return this.maxErrorRetry > 0; } /** * Gets MaxConnections property * * @return Max number of http connections */ public int getMaxConnections() { return maxConnections; } /** * Sets MaxConnections property * * @param maxConnections Max number of http connections * */ public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } /** * Sets MaxConnections property and returns current AmazonFPSConfig * * on your particular environment. Experiment. * * @return AmazonFPSConfig */ public AmazonFPSConfig withMaxConnections(int maxConnections) { setMaxConnections(maxConnections); return this; } /** * Checks if MaxConnections property is set * * @return true if MaxConnections property is set */ public boolean isSetMaxConnections() { return this.maxConnections > 0; } }
/******************************************************************************* * Copyright (c) 2015 IBM 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.ibm.ws.massive.esa; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Locale; import java.util.StringTokenizer; import java.util.zip.ZipException; import com.ibm.ws.massive.esa.internal.EsaManifest; import com.ibm.ws.massive.upload.RepositoryArchiveEntryNotFoundException; import com.ibm.ws.massive.upload.RepositoryArchiveIOException; import com.ibm.ws.massive.upload.RepositoryArchiveInvalidEntryException; import com.ibm.ws.massive.upload.RepositoryUploader; import com.ibm.ws.massive.upload.internal.MassiveUploader; import com.ibm.ws.repository.common.enums.AttachmentType; import com.ibm.ws.repository.common.enums.DisplayPolicy; import com.ibm.ws.repository.common.enums.InstallPolicy; import com.ibm.ws.repository.common.enums.LicenseType; import com.ibm.ws.repository.common.enums.Visibility; import com.ibm.ws.repository.connections.RepositoryConnection; import com.ibm.ws.repository.exceptions.RepositoryException; import com.ibm.ws.repository.exceptions.RepositoryResourceCreationException; import com.ibm.ws.repository.exceptions.RepositoryResourceUpdateException; import com.ibm.ws.repository.resources.EsaResource; import com.ibm.ws.repository.resources.internal.AppliesToProcessor; import com.ibm.ws.repository.resources.writeable.AttachmentResourceWritable; import com.ibm.ws.repository.resources.writeable.EsaResourceWritable; import com.ibm.ws.repository.resources.writeable.WritableResourceFactory; import com.ibm.ws.repository.strategies.writeable.UploadStrategy; /** * <p> * This class contains methods for working with ESAs inside MaaSive. * </p> */ public class MassiveEsa extends MassiveUploader implements RepositoryUploader<EsaResourceWritable> { /** * Construct a new instance and load all of the existing features inside MaaSive. * * @param userId The userId to use to connect to Massive * @param password The password to use to connect to Massive * @param apiKey The API key to use to connect to Massive * @throws RepositoryException */ public MassiveEsa(RepositoryConnection repoConnection) throws RepositoryException { super(repoConnection); } /** * This method will add a collection of ESAs into MaaSive * * @param esas The ESAs to add * @return the new {@link EsaResource}s added to massive (will not included any resources that * were modified as a result of this operation) * @throws ZipException * @throws RepositoryResourceCreationException * @throws RepositoryResourceUpdateException */ public Collection<EsaResource> addEsasToMassive(Collection<File> esas, UploadStrategy strategy) throws RepositoryException { Collection<EsaResource> resources = new HashSet<EsaResource>(); for (File esa : esas) { EsaResource resource = uploadFile(esa, strategy, null); resources.add(resource); } return resources; } /* * (non-Javadoc) * * @see com.ibm.ws.massive.upload.RepositoryUploader#canUploadFile(java.io.File) */ @Override public boolean canUploadFile(File assetFile) { return assetFile.getName().endsWith(".esa"); } /* * (non-Javadoc) * * @see com.ibm.ws.massive.upload.RepositoryUploader#uploadFile(java.io.File, * com.ibm.ws.massive.resources.UploadStrategy) */ @Override public EsaResourceWritable uploadFile(File esa, UploadStrategy strategy, String contentUrl) throws RepositoryException { ArtifactMetadata artifactMetadata = explodeArtifact(esa); // Read the meta data from the esa EsaManifest feature; try { feature = EsaManifest .constructInstance(esa); } catch (IOException e) { throw new RepositoryArchiveIOException(e.getMessage(), esa, e); } /* * First see if we already have this feature in MaaSive, note this means we can only have * one version of the asset in MaaSive at a time */ EsaResourceWritable resource = WritableResourceFactory.createEsa(repoConnection); String symbolicName = feature.getSymbolicName(); String version = feature.getVersion().toString(); // Massive assets are always English, find the best name String subsystemName = feature.getHeader("Subsystem-Name", Locale.ENGLISH); String shortName = feature.getIbmShortName(); String metadataName = artifactMetadata != null ? artifactMetadata.getName() : null; final String name; /* * We want to be able to override the name in the built ESA with a value supplied in the * metadata so use this in preference of what is in the ESA so that we can correct any typos * post-GM */ if (metadataName != null && !metadataName.isEmpty()) { name = metadataName; } else if (subsystemName != null && !subsystemName.isEmpty()) { name = subsystemName; } else if (shortName != null && !shortName.isEmpty()) { name = shortName; } else { // symbolic name is always set name = symbolicName; } resource.setName(name); String shortDescription = null; if (artifactMetadata != null) { shortDescription = artifactMetadata.getShortDescription(); resource.setDescription(artifactMetadata.getLongDescription()); } if (shortDescription == null) { shortDescription = feature.getHeader("Subsystem-Description", Locale.ENGLISH); } resource.setShortDescription(shortDescription); resource.setVersion(version); //Add icon files processIcons(esa, feature, resource); String provider = feature.getHeader("Subsystem-Vendor"); if (provider != null && !provider.isEmpty()) { resource.setProviderName(provider); } // Add custom attributes for WLP resource.setProvideFeature(symbolicName); resource.setAppliesTo(feature.getHeader("IBM-AppliesTo")); Visibility visibility = feature.getVisibility(); resource.setVisibility(visibility); /* * Two things affect the display policy - the visibility and the install policy. If a * private auto feature is set to manual install we need to make it visible so people know * that it exists and can be installed */ DisplayPolicy displayPolicy; DisplayPolicy webDisplayPolicy; if (visibility == Visibility.PUBLIC) { displayPolicy = DisplayPolicy.VISIBLE; webDisplayPolicy = DisplayPolicy.VISIBLE; } else { displayPolicy = DisplayPolicy.HIDDEN; webDisplayPolicy = DisplayPolicy.HIDDEN; } if (feature.isAutoFeature()) { resource.setProvisionCapability(feature.getHeader("IBM-Provision-Capability")); String IBMInstallPolicy = feature.getHeader("IBM-Install-Policy"); // Default InstallPolicy is set to MANUAL InstallPolicy installPolicy; if (IBMInstallPolicy != null && ("when-satisfied".equals(IBMInstallPolicy))) { installPolicy = InstallPolicy.WHEN_SATISFIED; } else { installPolicy = InstallPolicy.MANUAL; // As discussed above set the display policy to visible for any manual auto features displayPolicy = DisplayPolicy.VISIBLE; webDisplayPolicy = DisplayPolicy.VISIBLE; } resource.setInstallPolicy(installPolicy); } // if we are dealing with a beta feature hide it otherwise apply the // display policies from above if (isBeta(resource.getAppliesTo())) { resource.setWebDisplayPolicy(DisplayPolicy.HIDDEN); } else { resource.setWebDisplayPolicy(webDisplayPolicy); } // Always set displayPolicy resource.setDisplayPolicy(displayPolicy); // handle required iFixes String requiredFixes = feature.getHeader("IBM-Require-Fix"); if (requiredFixes != null && !requiredFixes.isEmpty()) { String[] fixes = requiredFixes.split(","); for (String fix : fixes) { fix = fix.trim(); if (!fix.isEmpty()) { resource.addRequireFix(fix); } } } resource.setShortName(shortName); // Calculate which features this relies on for (String requiredFeature : feature.getRequiredFeatures()) { resource.addRequireFeature(requiredFeature); } // feature.supersededBy is a comma-separated list of shortNames. Add // each of the elements to either supersededBy or supersededByOptional. String supersededBy = feature.getSupersededBy(); if (supersededBy != null && !supersededBy.trim().isEmpty()) { String[] supersededByArray = supersededBy.split(","); for (String f : supersededByArray) { // If one of the elements is surrounded by [square brackets] then we // strip the brackets off and treat it as optional if (f.startsWith("[")) { f = f.substring(1, f.length() - 1); resource.addSupersededByOptional(f); } else { resource.addSupersededBy(f); } } } String attachmentName = symbolicName + ".esa"; addContent(resource, esa, attachmentName, artifactMetadata, contentUrl); // Set the license type if we're using the feature terms agreement String subsystemLicense = feature.getHeader("Subsystem-License"); if (subsystemLicense != null && subsystemLicense.equals("http://www.ibm.com/licenses/wlp-featureterms-v1")) { resource.setLicenseType(LicenseType.UNSPECIFIED); } if (artifactMetadata != null) { attachLicenseData(artifactMetadata, resource); } // Now look for LI, LA files inside the .esa try { processLAandLI(esa, resource, feature); } catch (IOException e) { throw new RepositoryArchiveIOException(e.getMessage(), esa, e); } resource.setLicenseId(feature.getHeader("Subsystem-License")); // Publish to massive try { resource.uploadToMassive(strategy); } catch (RepositoryException re) { throw re; } return resource; } protected static boolean isBeta(String appliesTo) { // Use the appliesTo string to determine whether a feature is a Beta or a regular feature. // Beta features are of the format: // "com.ibm.websphere.appserver; productVersion=2014.8.0.0; productInstallType=Archive", if (appliesTo == null) { return false; } else { String regex = ".*productVersion=" + AppliesToProcessor.BETA_REGEX; boolean matches = appliesTo.matches(regex); return matches; } } private void processIcons(File esa, EsaManifest feature, EsaResourceWritable resource) throws RepositoryException { //checking icon file int size = 0; String current = ""; String sizeString = ""; String iconName = ""; String subsystemIcon = feature.getHeader("Subsystem-Icon"); if (subsystemIcon != null) { subsystemIcon = subsystemIcon.replaceAll("\\s", ""); StringTokenizer s = new StringTokenizer(subsystemIcon, ","); while (s.hasMoreTokens()) { current = s.nextToken(); if (current.contains(";")) { //if the icon has an associated size StringTokenizer t = new StringTokenizer(current, ";"); while (t.hasMoreTokens()) { sizeString = t.nextToken(); if (sizeString.contains("size=")) { String sizes[] = sizeString.split("size="); size = Integer.parseInt(sizes[sizes.length - 1]); } else { iconName = sizeString; } } } else { iconName = current; } File icon = this.extractFileFromArchive(esa.getAbsolutePath(), iconName).getExtractedFile(); if (icon.exists()) { AttachmentResourceWritable at = resource.addAttachment(icon, AttachmentType.THUMBNAIL); if (size != 0) { at.setImageDimensions(size, size); } } else { throw new RepositoryArchiveEntryNotFoundException("Icon does not exist", esa, iconName); } } } } @Override protected void checkRequiredProperties(ArtifactMetadata artifact) throws RepositoryArchiveInvalidEntryException { checkPropertySet(PROP_DESCRIPTION, artifact); } }
package scc.regalloc; import java.util.*; import scc.*; import scc.frames.*; import scc.imcode.*; import scc.asmcode.*; import scc.tmpan.*; public class RegAlloc { private boolean dump; private int registers; private TmpAn tmpan; private LinkedList<TmpNode> stack; public RegAlloc(boolean dump) { this.dump = dump; // remove // na voljo imamo 5 registrov, ampak moramo nekam shraniti se SP in FP. FP bi bilo zelo dobro imeti v registrih, // ker se veliko uporablja, SP pa lahko pustimo v pomnilniku this.registers = 5; tmpan = new TmpAn(false); stack = null; } public void allocate(LinkedList<ImcChunk> chunks) { for(ImcChunk chunk : chunks) { if(chunk instanceof ImcCodeChunk == true) { ImcCodeChunk codeChunk = (ImcCodeChunk)chunk; do { build(codeChunk); stack = new LinkedList<>(); do { simplify(codeChunk); } while (spill(codeChunk)); } while (select(codeChunk)); codeChunk.registers = new HashMap<>(); codeChunk.registers.put(codeChunk.frame.FP, "X"); codeChunk.registers.put(codeChunk.frame.SP, "SP"); for(TmpNode node : codeChunk.graph) { codeChunk.registers.put(node.temp, "" + node.register); } LinkedHashMap<FrmTemp, TmpNode> graph = tmpan.analyze(codeChunk); for(int i = 0; i < codeChunk.asmcode.size(); i++) { AsmInstr instr = codeChunk.asmcode.get(i); if(instr.mnemonic.equals("JSUB") == true) { AsmInstr next = codeChunk.asmcode.get(i + 1); LinkedList<TmpNode> edges = graph.get(instr.defs.getFirst()).edges; int maxRegister = 0; for(TmpNode edge : edges) { int register = Integer.parseInt(codeChunk.registers.get(edge.temp)); if(register > maxRegister) { maxRegister = register; } } // toString codeChunk.registers.put(instr.defs.getFirst(), "" + (edges.size() == 0 ? 0 : maxRegister + 1)); if(next.mnemonic.equals("SET") == true && codeChunk.registers.get(next.defs.getFirst()).equals(codeChunk.registers.get(next.uses.getFirst())) == true) { codeChunk.asmcode.remove(i + 1); } } } } } } private void build(ImcCodeChunk chunk) { tmpan.analyze(chunk); } private void simplify(ImcCodeChunk chunk) { boolean done = false; while(done == false) { done = true; Iterator<TmpNode> iterator = chunk.graph.iterator(); while(iterator.hasNext() == true) { TmpNode node = iterator.next(); if(node.edges.size() < registers) { done = false; stack.push(node); for(TmpNode edge : chunk.graph) { edge.edges.remove(node); } iterator.remove(); } } } } private boolean spill(ImcCodeChunk chunk) { if(chunk.graph.size() == 0) { return false; } TmpNode spill = null; int length = 0; for(TmpNode node : chunk.graph) { int def = 0; while(chunk.asmcode.get(def).defs.contains(node.temp) == false) { def++; } int use = chunk.asmcode.size() - 1; while(chunk.asmcode.get(use).uses.contains(node.temp) == false) { use--; } if(use - def > length) { spill = node; length = use - def; } } chunk.graph.remove(spill); spill.spill = TmpNode.POTENTIAL_SPILL; stack.push(spill); for(TmpNode edge : spill.edges) { edge.edges.remove(spill); } return true; } private boolean select(ImcCodeChunk chunk) { boolean repeat = false; while(stack.size() > 0) { TmpNode node = stack.pop(); chunk.graph.add(node); int regs[] = new int[registers + 1]; boolean ok = false; for(TmpNode edge : node.edges) { regs[edge.register] = 1; } for(int i = 0; i < registers; i++) { if(regs[i] == 0) { node.register = i; ok = true; break; } } for(AsmInstr instr : chunk.asmcode) { if(instr.mnemonic.equals("JSUB") == true && instr.defs.contains(node.temp) == true) { node.register = registers; ok = true; break; } } if(ok == false) { if(node.spill == TmpNode.POTENTIAL_SPILL) { node.spill = TmpNode.ACTUAL_SPILL; repeat = true; break; } else { Report.error("Unable to allocate a register to " + node.temp.name() + "."); } } } if(repeat == true) { startOver(chunk); } return repeat; } private void startOver(ImcCodeChunk chunk) { for(TmpNode node : chunk.graph) { if(node.spill != TmpNode.ACTUAL_SPILL) { continue; } long offset = chunk.frame.sizeArgs + chunk.frame.sizeTmps; chunk.frame.sizeTmps += 8; int def = 0; while(chunk.asmcode.get(def++).defs.contains(node.temp) == false) {} // TODO chunk.asmcode.add(def, new AsmOPER("STO", "`s0,`s1," + offset, null, new LinkedList<FrmTemp>(Arrays.asList(node.temp, chunk.frame.SP)))); for(int i = chunk.asmcode.size() - 1; i > def; i--) { if(chunk.asmcode.get(i).uses.contains(node.temp) == true) { chunk.asmcode.add(i, new AsmOPER("LDO", "`d0,`s0," + offset, new LinkedList<FrmTemp>(Arrays.asList(node.temp)), new LinkedList<FrmTemp>(Arrays.asList(chunk.frame.SP)))); } } } } public void dump(LinkedList<ImcChunk> chunks) { if(dump == false) return; if(Report.dumpFile() == null) return; int i = 0; for(ImcChunk chunk : chunks) { if(chunk instanceof ImcCodeChunk == true) { if(i++ > 0) { Report.dump(0, ""); } ImcCodeChunk codeChunk = (ImcCodeChunk)chunk; for(AsmInstr instr : codeChunk.asmcode) { Report.dump(0, instr.format(codeChunk.registers)); } } } } }
package com.p1.mobile.p1android.ui.fragment; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.p1.mobile.p1android.P1Application; import com.p1.mobile.p1android.R; import com.p1.mobile.p1android.content.Content; import com.p1.mobile.p1android.content.ContentHandler; import com.p1.mobile.p1android.content.IContentRequester; import com.p1.mobile.p1android.content.Profile; import com.p1.mobile.p1android.content.Profile.BloodType; import com.p1.mobile.p1android.content.Profile.MaritalStatus; import com.p1.mobile.p1android.content.Profile.ProfileIOSession; import com.p1.mobile.p1android.content.Profile.Zodiac; import com.p1.mobile.p1android.content.User; import com.p1.mobile.p1android.content.User.UserIOSession; import com.p1.mobile.p1android.content.logic.ReadProfile; import com.p1.mobile.p1android.content.logic.ReadUser; import com.p1.mobile.p1android.ui.widget.P1ActionBar; import com.p1.mobile.p1android.ui.widget.P1ActionBar.ListenerAction; import com.p1.mobile.p1android.ui.widget.P1ActionBar.OnActionListener; import com.p1.mobile.p1android.ui.widget.P1TextView; import com.squareup.picasso.Picasso; /** * * @author Cui pengpeng * */ public class ProfileDetailsFragment extends Fragment implements IContentRequester, OnActionListener { private static final String TAG = ProfileDetailsFragment.class .getSimpleName(); private static String USER_ID = "userid"; private P1TextView mActionBarTitle; private P1ActionBar mActionBar; private ImageView mCoverImage; private ImageView mThumbImage; private P1TextView mName; private P1TextView mCareerTextView; private P1TextView mRelationshipTextView; private P1TextView mZodiacTextView; private P1TextView mBloodTypeTextView; private P1TextView mSchoolTextView; private P1TextView mPositionTextView; private P1TextView mCompanyTextView; private P1TextView mLocationTextView; private P1TextView mDescriptionTextView; private LinearLayout mDescriptionLinearLayout; private LinearLayout mProfessionalLinearLayout; private LinearLayout mSchoolLinearLayout; private LinearLayout mPositionLinearLayout; private LinearLayout mCompanyLinearLayout; private RelativeLayout mLocationRelativeLayout; private ProfileRequester mProfileRequester; private String mUserId; private User mUser; private Profile mProfile; public static Fragment newInstance(String userId) { ProfileDetailsFragment fragment = new ProfileDetailsFragment(); if (userId != null) { Bundle args = new Bundle(); args.putString(USER_ID, userId); fragment.setArguments(args); } return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mUserId = getArguments().getString(USER_ID); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.profile_details_fragment, container, false); mCoverImage = (ImageView) view .findViewById(R.id.profile_details_cover_image); mThumbImage = (ImageView) view .findViewById(R.id.profile_details_thumb_image); mName = (P1TextView) view.findViewById(R.id.tv_profile_detail_username); mCareerTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_career); mRelationshipTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_relationship); mZodiacTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_zodiac); mBloodTypeTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_blood_type); mSchoolTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_school); mPositionTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_position); mCompanyTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_company); mLocationTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_location); mDescriptionTextView = (P1TextView) view .findViewById(R.id.tv_profile_detail_desc); mDescriptionLinearLayout = (LinearLayout) view .findViewById(R.id.ll_profile_detail_desc); mProfessionalLinearLayout = (LinearLayout) view .findViewById(R.id.ll_profile_detail_professional); mSchoolLinearLayout = (LinearLayout) view .findViewById(R.id.ll_profile_deatil_school); mPositionLinearLayout = (LinearLayout) view .findViewById(R.id.ll_profile_deatil_position); mCompanyLinearLayout = (LinearLayout) view .findViewById(R.id.ll_profile_deatil_company); mLocationRelativeLayout = (RelativeLayout) view .findViewById(R.id.rl_profile_deatil_location); initActionBar(inflater, view); return view; } private void initActionBar(LayoutInflater inflater, View containerView) { mActionBar = (P1ActionBar) containerView .findViewById(R.id.user_profile_action_bar); mActionBarTitle = new P1TextView(getActivity()); mActionBarTitle.setTextAppearance(getActivity(), R.style.P1LargerTextLight); mActionBarTitle.setGravity(Gravity.CENTER); mActionBar.setCenterView(mActionBarTitle); mActionBar.setLeftAction(new ListenerAction( R.drawable.back_arrow_button, this)); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mUser = ReadUser.requestUser(mUserId, this); contentChanged(mUser); mProfileRequester = new ProfileRequester(); mProfile = ReadProfile.requestProfile(mUserId, mProfileRequester); mProfileRequester.contentChanged(mProfile); } @Override public void onDestroyView() { ContentHandler.getInstance().removeRequester(this); ContentHandler.getInstance().removeRequester(mProfileRequester); super.onDestroyView(); } @Override public void onAction() { FragmentManager fm= getActivity().getSupportFragmentManager(); FragmentTransaction ft =fm.beginTransaction(); fm.popBackStack(); ft.commit(); } class ProfileRequester implements IContentRequester { @Override public void contentChanged(Content content) { if (content != null) { Profile profile = (Profile) content; ProfileIOSession io = profile.getIOSession(); try { mDescriptionTextView.setText(io.getDescription()); if (StringUtils.isEmpty(io.getDescription())) { mDescriptionLinearLayout.setVisibility(View.GONE); } else { mDescriptionLinearLayout.setVisibility(View.VISIBLE); } if (io.getMarital() != null) { if (io.getMarital().equals( MaritalStatus.IN_RELATIONSHIP)) { mRelationshipTextView .setText(getResources().getString(R.string.relationship_ship_in_relationship)); } else if (io.getMarital().equals( MaritalStatus.COMPLICATED)) { mRelationshipTextView .setText(getResources().getString(R.string.relationship_ship_complicated)); } else if (io.getMarital().equals(MaritalStatus.OTHER)) { mRelationshipTextView .setText(getResources().getString(R.string.relationship_ship_private)); } else { mRelationshipTextView .setText(makeFirstLetterUpper(io .getMarital() + "")); } } if (io.getBloodtype() != null) { if (io.getBloodtype().equals(BloodType.UNKNOWN)) { mBloodTypeTextView .setText(getResources().getString( R.string.blood_type_unknown)); } else { mBloodTypeTextView.setText(io.getBloodtype() + ""); } } //set zodiac if (io.getZodiac() != null) { if(io.getZodiac().equals(Zodiac.AQUARIUS)) { mZodiacTextView.setText(getResources().getString(R.string.zodiac_aquarius)); }else if(io.getZodiac().equals(Zodiac.ARIES)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_aries)); }else if(io.getZodiac().equals(Zodiac.CANCER)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_cancer)); }else if(io.getZodiac().equals(Zodiac.CAPRICORNUS)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_capricornus)); }else if(io.getZodiac().equals(Zodiac.GEMINI)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_gemini)); }else if(io.getZodiac().equals(Zodiac.LEO)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_leo)); }else if(io.getZodiac().equals(Zodiac.LIBRA)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_libra)); }else if(io.getZodiac().equals(Zodiac.PISCES)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_pisces)); }else if(io.getZodiac().equals(Zodiac.SAGITTARUS)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_sagittarus)); }else if(io.getZodiac().equals(Zodiac.SCORPIO)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_scorpio)); }else if(io.getZodiac().equals(Zodiac.TAURUS)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_taurus)); }else if(io.getZodiac().equals(Zodiac.VIRGO)){ mZodiacTextView.setText(getResources().getString(R.string.zodiac_virgo)); } } } finally { io.close(); } } } } private String makeFirstLetterUpper(String s) { StringBuilder sb = new StringBuilder(); sb.append(Character.toUpperCase(s.charAt(0))).append( s.substring(1).toLowerCase(Locale.CHINA)); return sb.toString(); } @Override public void contentChanged(Content content) { if (content != null) { User user = (User) content; UserIOSession io = user.getIOSession(); try { mActionBarTitle.setText(getResources().getString( R.string.profile_details_title)); P1Application.picasso.load(Uri.parse(io.getCoverUrl())) .placeholder(null).into(mCoverImage); P1Application.picasso .load(Uri.parse(io.getProfileThumb100Url())).noFade() .placeholder(null).into(mThumbImage); mName.setText(io.getPreferredFullName()); String positionStr = io.getCareerPosition(); String companyStr = io.getCareerCompany(); String link = " at "; if (StringUtils.isEmpty(positionStr)) { positionStr = ""; link = ""; } if (StringUtils.isEmpty(companyStr)) { companyStr = ""; link = ""; } mCareerTextView.setText(positionStr + link + companyStr); mSchoolTextView.setText(io.getEducation()); mPositionTextView.setText(io.getCareerPosition()); mCompanyTextView.setText(io.getCareerCompany()); mLocationTextView.setText(io.getCity()); if (StringUtils.isEmpty(io.getCareerCompany())) { mCompanyLinearLayout.setVisibility(View.GONE); } else { mCompanyLinearLayout.setVisibility(View.VISIBLE); } if (StringUtils.isEmpty(io.getCareerPosition())) { mSchoolLinearLayout.setVisibility(View.GONE); } else { mSchoolLinearLayout.setVisibility(View.VISIBLE); } if (StringUtils.isEmpty(io.getCareerPosition())) { mPositionLinearLayout.setVisibility(View.GONE); } else { mPositionLinearLayout.setVisibility(View.VISIBLE); } if (StringUtils.isEmpty(io.getCity())) { mLocationRelativeLayout.setVisibility(View.GONE); } else { mLocationRelativeLayout.setVisibility(View.VISIBLE); } if (StringUtils.isEmpty(io.getCity()) && StringUtils.isEmpty(io.getEducation()) && StringUtils.isEmpty(io.getCareerPosition()) && StringUtils.isEmpty(io.getCareerCompany())) { mProfessionalLinearLayout.setVisibility(View.GONE); } else { mProfessionalLinearLayout.setVisibility(View.VISIBLE); } } finally { io.close(); } } } }
/* * 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.servicecatalog.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The parameter key-value pair used to update a provisioned product. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateProvisioningParameter" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateProvisioningParameter implements Serializable, Cloneable, StructuredPojo { /** * <p> * The parameter key. * </p> */ private String key; /** * <p> * The parameter value. * </p> */ private String value; /** * <p> * If set to true, <code>Value</code> is ignored and the previous parameter value is kept. * </p> */ private Boolean usePreviousValue; /** * <p> * The parameter key. * </p> * * @param key * The parameter key. */ public void setKey(String key) { this.key = key; } /** * <p> * The parameter key. * </p> * * @return The parameter key. */ public String getKey() { return this.key; } /** * <p> * The parameter key. * </p> * * @param key * The parameter key. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateProvisioningParameter withKey(String key) { setKey(key); return this; } /** * <p> * The parameter value. * </p> * * @param value * The parameter value. */ public void setValue(String value) { this.value = value; } /** * <p> * The parameter value. * </p> * * @return The parameter value. */ public String getValue() { return this.value; } /** * <p> * The parameter value. * </p> * * @param value * The parameter value. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateProvisioningParameter withValue(String value) { setValue(value); return this; } /** * <p> * If set to true, <code>Value</code> is ignored and the previous parameter value is kept. * </p> * * @param usePreviousValue * If set to true, <code>Value</code> is ignored and the previous parameter value is kept. */ public void setUsePreviousValue(Boolean usePreviousValue) { this.usePreviousValue = usePreviousValue; } /** * <p> * If set to true, <code>Value</code> is ignored and the previous parameter value is kept. * </p> * * @return If set to true, <code>Value</code> is ignored and the previous parameter value is kept. */ public Boolean getUsePreviousValue() { return this.usePreviousValue; } /** * <p> * If set to true, <code>Value</code> is ignored and the previous parameter value is kept. * </p> * * @param usePreviousValue * If set to true, <code>Value</code> is ignored and the previous parameter value is kept. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateProvisioningParameter withUsePreviousValue(Boolean usePreviousValue) { setUsePreviousValue(usePreviousValue); return this; } /** * <p> * If set to true, <code>Value</code> is ignored and the previous parameter value is kept. * </p> * * @return If set to true, <code>Value</code> is ignored and the previous parameter value is kept. */ public Boolean isUsePreviousValue() { return this.usePreviousValue; } /** * 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 (getKey() != null) sb.append("Key: ").append(getKey()).append(","); if (getValue() != null) sb.append("Value: ").append(getValue()).append(","); if (getUsePreviousValue() != null) sb.append("UsePreviousValue: ").append(getUsePreviousValue()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateProvisioningParameter == false) return false; UpdateProvisioningParameter other = (UpdateProvisioningParameter) obj; if (other.getKey() == null ^ this.getKey() == null) return false; if (other.getKey() != null && other.getKey().equals(this.getKey()) == false) return false; if (other.getValue() == null ^ this.getValue() == null) return false; if (other.getValue() != null && other.getValue().equals(this.getValue()) == false) return false; if (other.getUsePreviousValue() == null ^ this.getUsePreviousValue() == null) return false; if (other.getUsePreviousValue() != null && other.getUsePreviousValue().equals(this.getUsePreviousValue()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKey() == null) ? 0 : getKey().hashCode()); hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode()); hashCode = prime * hashCode + ((getUsePreviousValue() == null) ? 0 : getUsePreviousValue().hashCode()); return hashCode; } @Override public UpdateProvisioningParameter clone() { try { return (UpdateProvisioningParameter) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.servicecatalog.model.transform.UpdateProvisioningParameterMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package com.apollographql.apollo.internal.cache.normalized; import com.apollographql.apollo.CustomTypeAdapter; import com.apollographql.apollo.api.Operation; import com.apollographql.apollo.api.ResponseField; import com.apollographql.apollo.api.ResponseFieldMarshaller; import com.apollographql.apollo.api.ResponseWriter; import com.apollographql.apollo.api.ScalarType; import com.apollographql.apollo.api.internal.Optional; import com.apollographql.apollo.cache.normalized.Record; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; final class CacheResponseWriter implements ResponseWriter { private final Operation.Variables operationVariables; private final Map<ScalarType, CustomTypeAdapter> customTypeAdapters; final Map<String, FieldDescriptor> fieldDescriptors = new LinkedHashMap<>(); final Map<String, Object> fieldValues = new LinkedHashMap<>(); CacheResponseWriter(Operation.Variables operationVariables, Map<ScalarType, CustomTypeAdapter> customTypeAdapters) { this.operationVariables = operationVariables; this.customTypeAdapters = customTypeAdapters; } @Override public void writeString(ResponseField field, String value) { writeScalarFieldValue(field, value); } @Override public void writeInt(ResponseField field, Integer value) { writeScalarFieldValue(field, value != null ? BigDecimal.valueOf(value) : null); } @Override public void writeLong(ResponseField field, Long value) { writeScalarFieldValue(field, value != null ? BigDecimal.valueOf(value) : null); } @Override public void writeDouble(ResponseField field, Double value) { writeScalarFieldValue(field, value != null ? BigDecimal.valueOf(value) : null); } @Override public void writeBoolean(ResponseField field, Boolean value) { writeScalarFieldValue(field, value); } @Override public void writeCustom(ResponseField.CustomTypeField field, Object value) { CustomTypeAdapter typeAdapter = customTypeAdapters.get(field.scalarType()); if (typeAdapter == null) { writeScalarFieldValue(field, value); } else { writeScalarFieldValue(field, value != null ? typeAdapter.encode(value) : null); } } @Override public void writeObject(ResponseField field, ResponseFieldMarshaller marshaller) { checkFieldValue(field, marshaller); if (marshaller == null) { fieldDescriptors.put(field.responseName(), new ObjectFieldDescriptor(field, Collections.<String, FieldDescriptor>emptyMap())); return; } CacheResponseWriter nestedResponseWriter = new CacheResponseWriter(operationVariables, customTypeAdapters); marshaller.marshal(nestedResponseWriter); fieldDescriptors.put(field.responseName(), new ObjectFieldDescriptor(field, nestedResponseWriter.fieldDescriptors)); fieldValues.put(field.responseName(), nestedResponseWriter.fieldValues); } @Override public void writeList(ResponseField field, ListWriter listWriter) { checkFieldValue(field, listWriter); if (listWriter == null) { fieldDescriptors.put(field.responseName(), new ListFieldDescriptor(field, Collections.<Map<String, FieldDescriptor>>emptyList())); return; } ListItemWriter listItemWriter = new ListItemWriter(operationVariables, customTypeAdapters); listWriter.write(listItemWriter); fieldDescriptors.put(field.responseName(), new ListFieldDescriptor(field, listItemWriter.fieldDescriptors)); fieldValues.put(field.responseName(), listItemWriter.fieldValues); } public Collection<Record> normalize(ResponseNormalizer<Map<String, Object>> responseNormalizer) { normalize(operationVariables, responseNormalizer, fieldDescriptors, fieldValues); return responseNormalizer.records(); } private void writeScalarFieldValue(ResponseField field, Object value) { checkFieldValue(field, value); fieldDescriptors.put(field.responseName(), new FieldDescriptor(field)); if (value != null) { fieldValues.put(field.responseName(), value); } } @SuppressWarnings("unchecked") private void normalize(Operation.Variables operationVariables, ResponseNormalizer<Map<String, Object>> responseNormalizer, Map<String, FieldDescriptor> fieldDescriptors, Map<String, Object> fieldValues) { for (String fieldResponseName : fieldDescriptors.keySet()) { FieldDescriptor fieldDescriptor = fieldDescriptors.get(fieldResponseName); Object fieldValue = fieldValues.get(fieldResponseName); responseNormalizer.willResolve(fieldDescriptor.field, operationVariables); switch (fieldDescriptor.field.type()) { case OBJECT: { ObjectFieldDescriptor objectFieldDescriptor = (ObjectFieldDescriptor) fieldDescriptor; Map<String, Object> objectFieldValues = (Map<String, Object>) fieldValue; normalizeObjectField(objectFieldDescriptor, objectFieldValues, responseNormalizer); break; } case OBJECT_LIST: { ListFieldDescriptor listFieldDescriptor = (ListFieldDescriptor) fieldDescriptor; List<Map<String, Object>> listFieldValues = (List<Map<String, Object>>) fieldValue; normalizeObjectListField(listFieldDescriptor, listFieldValues, responseNormalizer); break; } case CUSTOM_LIST: case SCALAR_LIST: { normalizeScalarList((List) fieldValue, responseNormalizer); break; } default: { if (fieldValue == null) { responseNormalizer.didResolveNull(); } else { responseNormalizer.didResolveScalar(fieldValue); } break; } } responseNormalizer.didResolve(fieldDescriptor.field, operationVariables); } } private void normalizeObjectField(ObjectFieldDescriptor objectFieldDescriptor, Map<String, Object> objectFieldValues, ResponseNormalizer<Map<String, Object>> responseNormalizer) { responseNormalizer.willResolveObject(objectFieldDescriptor.field, Optional.fromNullable(objectFieldValues)); if (objectFieldValues == null) { responseNormalizer.didResolveNull(); } else { normalize(operationVariables, responseNormalizer, objectFieldDescriptor.childFields, objectFieldValues); } responseNormalizer.didResolveObject(objectFieldDescriptor.field, Optional.fromNullable(objectFieldValues)); } private void normalizeObjectListField(ListFieldDescriptor listFieldDescriptor, List<Map<String, Object>> listFieldValues, ResponseNormalizer<Map<String, Object>> responseNormalizer) { if (listFieldValues == null) { responseNormalizer.didResolveNull(); } else { for (int i = 0; i < listFieldDescriptor.items.size(); i++) { responseNormalizer.willResolveElement(i); responseNormalizer.willResolveObject(listFieldDescriptor.field, Optional.fromNullable(listFieldValues.get(i))); normalize(operationVariables, responseNormalizer, listFieldDescriptor.items.get(i), listFieldValues.get(i)); responseNormalizer.didResolveObject(listFieldDescriptor.field, Optional.fromNullable(listFieldValues.get(i))); responseNormalizer.didResolveElement(i); } responseNormalizer.didResolveList(listFieldValues); } } private void normalizeScalarList(List listFieldValues, ResponseNormalizer<Map<String, Object>> responseNormalizer) { if (listFieldValues == null) { responseNormalizer.didResolveNull(); } else { for (int i = 0; i < listFieldValues.size(); i++) { responseNormalizer.willResolveElement(i); responseNormalizer.didResolveScalar(listFieldValues.get(i)); responseNormalizer.didResolveElement(i); } responseNormalizer.didResolveList(listFieldValues); } } private static void checkFieldValue(ResponseField field, Object value) { if (!field.optional() && value == null) { throw new NullPointerException(String.format("Mandatory response field `%s` resolved with null value", field.responseName())); } } @SuppressWarnings("unchecked") private static final class ListItemWriter implements ResponseWriter.ListItemWriter { final Operation.Variables operationVariables; final Map<ScalarType, CustomTypeAdapter> customTypeAdapters; final List<Map<String, FieldDescriptor>> fieldDescriptors = new ArrayList(); final List fieldValues = new ArrayList(); ListItemWriter(Operation.Variables operationVariables, Map<ScalarType, CustomTypeAdapter> customTypeAdapters) { this.operationVariables = operationVariables; this.customTypeAdapters = customTypeAdapters; } @Override public void writeString(String value) { fieldValues.add(value); } @Override public void writeInt(Integer value) { fieldValues.add(value); } @Override public void writeLong(Long value) { fieldValues.add(value); } @Override public void writeDouble(Double value) { fieldValues.add(value); } @Override public void writeBoolean(Boolean value) { fieldValues.add(value); } @Override public void writeCustom(ScalarType scalarType, Object value) { CustomTypeAdapter typeAdapter = customTypeAdapters.get(scalarType); if (typeAdapter == null) { fieldValues.add(value); } else { fieldValues.add(typeAdapter.encode(value)); } } @Override public void writeObject(ResponseFieldMarshaller marshaller) { CacheResponseWriter nestedResponseWriter = new CacheResponseWriter(operationVariables, customTypeAdapters); marshaller.marshal(nestedResponseWriter); fieldDescriptors.add(nestedResponseWriter.fieldDescriptors); fieldValues.add(nestedResponseWriter.fieldValues); } } private static class FieldDescriptor { final ResponseField field; FieldDescriptor(ResponseField field) { this.field = field; } } private static final class ObjectFieldDescriptor extends FieldDescriptor { final Map<String, FieldDescriptor> childFields; ObjectFieldDescriptor(ResponseField field, Map<String, FieldDescriptor> childFields) { super(field); this.childFields = childFields; } } private static final class ListFieldDescriptor extends FieldDescriptor { final List<Map<String, FieldDescriptor>> items; ListFieldDescriptor(ResponseField field, List<Map<String, FieldDescriptor>> items) { super(field); this.items = items; } } }
package com.google.api.ads.dfp.jaxws.v201502; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * * A {@code Creative} that is created by a Rich Media Studio. * * * <p>Java class for BaseRichMediaStudioCreative complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="BaseRichMediaStudioCreative"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201502}Creative"> * &lt;sequence> * &lt;element name="studioCreativeId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="creativeFormat" type="{https://www.google.com/apis/ads/publisher/v201502}RichMediaStudioCreativeFormat" minOccurs="0"/> * &lt;element name="artworkType" type="{https://www.google.com/apis/ads/publisher/v201502}RichMediaStudioCreativeArtworkType" minOccurs="0"/> * &lt;element name="totalFileSize" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="adTagKeys" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="customKeyValues" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="surveyUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="allImpressionsUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="richMediaImpressionsUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="backupImageImpressionsUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="overrideCss" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="requiredFlashPluginVersion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="duration" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="billingAttribute" type="{https://www.google.com/apis/ads/publisher/v201502}RichMediaStudioCreativeBillingAttribute" minOccurs="0"/> * &lt;element name="richMediaStudioChildAssetProperties" type="{https://www.google.com/apis/ads/publisher/v201502}RichMediaStudioChildAssetProperty" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="sslScanResult" type="{https://www.google.com/apis/ads/publisher/v201502}SslScanResult" minOccurs="0"/> * &lt;element name="sslManualOverride" type="{https://www.google.com/apis/ads/publisher/v201502}SslManualOverride" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BaseRichMediaStudioCreative", propOrder = { "studioCreativeId", "creativeFormat", "artworkType", "totalFileSize", "adTagKeys", "customKeyValues", "surveyUrl", "allImpressionsUrl", "richMediaImpressionsUrl", "backupImageImpressionsUrl", "overrideCss", "requiredFlashPluginVersion", "duration", "billingAttribute", "richMediaStudioChildAssetProperties", "sslScanResult", "sslManualOverride" }) @XmlSeeAlso({ RichMediaStudioCreative.class }) public abstract class BaseRichMediaStudioCreative extends Creative { protected Long studioCreativeId; @XmlSchemaType(name = "string") protected RichMediaStudioCreativeFormat creativeFormat; @XmlSchemaType(name = "string") protected RichMediaStudioCreativeArtworkType artworkType; protected Long totalFileSize; protected List<String> adTagKeys; protected List<String> customKeyValues; protected String surveyUrl; protected String allImpressionsUrl; protected String richMediaImpressionsUrl; protected String backupImageImpressionsUrl; protected String overrideCss; protected String requiredFlashPluginVersion; protected Integer duration; @XmlSchemaType(name = "string") protected RichMediaStudioCreativeBillingAttribute billingAttribute; protected List<RichMediaStudioChildAssetProperty> richMediaStudioChildAssetProperties; @XmlSchemaType(name = "string") protected SslScanResult sslScanResult; @XmlSchemaType(name = "string") protected SslManualOverride sslManualOverride; /** * Gets the value of the studioCreativeId property. * * @return * possible object is * {@link Long } * */ public Long getStudioCreativeId() { return studioCreativeId; } /** * Sets the value of the studioCreativeId property. * * @param value * allowed object is * {@link Long } * */ public void setStudioCreativeId(Long value) { this.studioCreativeId = value; } /** * Gets the value of the creativeFormat property. * * @return * possible object is * {@link RichMediaStudioCreativeFormat } * */ public RichMediaStudioCreativeFormat getCreativeFormat() { return creativeFormat; } /** * Sets the value of the creativeFormat property. * * @param value * allowed object is * {@link RichMediaStudioCreativeFormat } * */ public void setCreativeFormat(RichMediaStudioCreativeFormat value) { this.creativeFormat = value; } /** * Gets the value of the artworkType property. * * @return * possible object is * {@link RichMediaStudioCreativeArtworkType } * */ public RichMediaStudioCreativeArtworkType getArtworkType() { return artworkType; } /** * Sets the value of the artworkType property. * * @param value * allowed object is * {@link RichMediaStudioCreativeArtworkType } * */ public void setArtworkType(RichMediaStudioCreativeArtworkType value) { this.artworkType = value; } /** * Gets the value of the totalFileSize property. * * @return * possible object is * {@link Long } * */ public Long getTotalFileSize() { return totalFileSize; } /** * Sets the value of the totalFileSize property. * * @param value * allowed object is * {@link Long } * */ public void setTotalFileSize(Long value) { this.totalFileSize = value; } /** * Gets the value of the adTagKeys property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the adTagKeys property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdTagKeys().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAdTagKeys() { if (adTagKeys == null) { adTagKeys = new ArrayList<String>(); } return this.adTagKeys; } /** * Gets the value of the customKeyValues property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the customKeyValues property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCustomKeyValues().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getCustomKeyValues() { if (customKeyValues == null) { customKeyValues = new ArrayList<String>(); } return this.customKeyValues; } /** * Gets the value of the surveyUrl property. * * @return * possible object is * {@link String } * */ public String getSurveyUrl() { return surveyUrl; } /** * Sets the value of the surveyUrl property. * * @param value * allowed object is * {@link String } * */ public void setSurveyUrl(String value) { this.surveyUrl = value; } /** * Gets the value of the allImpressionsUrl property. * * @return * possible object is * {@link String } * */ public String getAllImpressionsUrl() { return allImpressionsUrl; } /** * Sets the value of the allImpressionsUrl property. * * @param value * allowed object is * {@link String } * */ public void setAllImpressionsUrl(String value) { this.allImpressionsUrl = value; } /** * Gets the value of the richMediaImpressionsUrl property. * * @return * possible object is * {@link String } * */ public String getRichMediaImpressionsUrl() { return richMediaImpressionsUrl; } /** * Sets the value of the richMediaImpressionsUrl property. * * @param value * allowed object is * {@link String } * */ public void setRichMediaImpressionsUrl(String value) { this.richMediaImpressionsUrl = value; } /** * Gets the value of the backupImageImpressionsUrl property. * * @return * possible object is * {@link String } * */ public String getBackupImageImpressionsUrl() { return backupImageImpressionsUrl; } /** * Sets the value of the backupImageImpressionsUrl property. * * @param value * allowed object is * {@link String } * */ public void setBackupImageImpressionsUrl(String value) { this.backupImageImpressionsUrl = value; } /** * Gets the value of the overrideCss property. * * @return * possible object is * {@link String } * */ public String getOverrideCss() { return overrideCss; } /** * Sets the value of the overrideCss property. * * @param value * allowed object is * {@link String } * */ public void setOverrideCss(String value) { this.overrideCss = value; } /** * Gets the value of the requiredFlashPluginVersion property. * * @return * possible object is * {@link String } * */ public String getRequiredFlashPluginVersion() { return requiredFlashPluginVersion; } /** * Sets the value of the requiredFlashPluginVersion property. * * @param value * allowed object is * {@link String } * */ public void setRequiredFlashPluginVersion(String value) { this.requiredFlashPluginVersion = value; } /** * Gets the value of the duration property. * * @return * possible object is * {@link Integer } * */ public Integer getDuration() { return duration; } /** * Sets the value of the duration property. * * @param value * allowed object is * {@link Integer } * */ public void setDuration(Integer value) { this.duration = value; } /** * Gets the value of the billingAttribute property. * * @return * possible object is * {@link RichMediaStudioCreativeBillingAttribute } * */ public RichMediaStudioCreativeBillingAttribute getBillingAttribute() { return billingAttribute; } /** * Sets the value of the billingAttribute property. * * @param value * allowed object is * {@link RichMediaStudioCreativeBillingAttribute } * */ public void setBillingAttribute(RichMediaStudioCreativeBillingAttribute value) { this.billingAttribute = value; } /** * Gets the value of the richMediaStudioChildAssetProperties property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the richMediaStudioChildAssetProperties property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRichMediaStudioChildAssetProperties().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link RichMediaStudioChildAssetProperty } * * */ public List<RichMediaStudioChildAssetProperty> getRichMediaStudioChildAssetProperties() { if (richMediaStudioChildAssetProperties == null) { richMediaStudioChildAssetProperties = new ArrayList<RichMediaStudioChildAssetProperty>(); } return this.richMediaStudioChildAssetProperties; } /** * Gets the value of the sslScanResult property. * * @return * possible object is * {@link SslScanResult } * */ public SslScanResult getSslScanResult() { return sslScanResult; } /** * Sets the value of the sslScanResult property. * * @param value * allowed object is * {@link SslScanResult } * */ public void setSslScanResult(SslScanResult value) { this.sslScanResult = value; } /** * Gets the value of the sslManualOverride property. * * @return * possible object is * {@link SslManualOverride } * */ public SslManualOverride getSslManualOverride() { return sslManualOverride; } /** * Sets the value of the sslManualOverride property. * * @param value * allowed object is * {@link SslManualOverride } * */ public void setSslManualOverride(SslManualOverride value) { this.sslManualOverride = value; } }
/* * 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.ode.dao.jpa; import org.apache.ode.bpel.dao.CorrelationSetDAO; import org.apache.ode.bpel.dao.PartnerLinkDAO; import org.apache.ode.bpel.dao.ProcessInstanceDAO; import org.apache.ode.bpel.dao.ScopeDAO; import org.apache.ode.bpel.dao.ScopeStateEnum; import org.apache.ode.bpel.dao.XmlDataDAO; import org.apache.ode.bpel.evt.BpelEvent; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Query; import javax.persistence.Table; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Entity @Table(name = "ODE_SCOPE") @NamedQueries({ @NamedQuery(name = "ScopeEvents", query = "SELECT se FROM EventDAOImpl as se WHERE se._scopeId = :sid"), @NamedQuery(name = ScopeDAOImpl.SELECT_SCOPE_IDS_BY_PROCESS, query = "select s._scopeInstanceId from ScopeDAOImpl as s where s._processInstance._process = :process"), @NamedQuery(name = ScopeDAOImpl.SELECT_SCOPE_IDS_BY_INSTANCE, query = "select s._scopeInstanceId from ScopeDAOImpl as s where s._processInstance = :instance"), @NamedQuery(name = ScopeDAOImpl.DELETE_SCOPES_BY_SCOPE_IDS, query = "delete from ScopeDAOImpl as s where s._scopeInstanceId in(:ids)") }) public class ScopeDAOImpl extends OpenJPADAO implements ScopeDAO { public final static String SELECT_SCOPE_IDS_BY_PROCESS = "SELECT_SCOPE_IDS_BY_PROCESS"; public final static String SELECT_SCOPE_IDS_BY_INSTANCE = "SELECT_SCOPE_IDS_BY_INSTANCE"; public final static String DELETE_SCOPES_BY_SCOPE_IDS = "DELETE_SCOPES_BY_SCOPE_IDS"; @Id @Column(name = "SCOPE_ID") @GeneratedValue(strategy = GenerationType.AUTO) private Long _scopeInstanceId; @Basic @Column(name = "MODEL_ID") private int _modelId; @Basic @Column(name = "SCOPE_NAME") private String _name; @Basic @Column(name = "SCOPE_STATE") private String _scopeState; @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) @Column(name = "PARENT_SCOPE_ID") private ScopeDAOImpl _parentScope; @OneToMany(targetEntity = ScopeDAOImpl.class, mappedBy = "_parentScope", fetch = FetchType.LAZY, cascade = { CascadeType.ALL }) private Collection<ScopeDAO> _childScopes = new ArrayList<ScopeDAO>(); @OneToMany(targetEntity = CorrelationSetDAOImpl.class, mappedBy = "_scope", fetch = FetchType.LAZY, cascade = { CascadeType.ALL }) private Collection<CorrelationSetDAO> _correlationSets = new ArrayList<CorrelationSetDAO>(); @OneToMany(targetEntity = PartnerLinkDAOImpl.class, mappedBy = "_scope", fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST }) private Collection<PartnerLinkDAO> _partnerLinks = new ArrayList<PartnerLinkDAO>(); @OneToMany(targetEntity = XmlDataDAOImpl.class, mappedBy = "_scope", fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST }) private Collection<XmlDataDAO> _variables = new ArrayList<XmlDataDAO>(); @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) @Column(name = "PROCESS_INSTANCE_ID") private ProcessInstanceDAOImpl _processInstance; public ScopeDAOImpl() { } public ScopeDAOImpl(ScopeDAOImpl parentScope, String name, int scopeModelId, ProcessInstanceDAOImpl pi) { _parentScope = parentScope; _name = name; _modelId = scopeModelId; _processInstance = pi; } public PartnerLinkDAO createPartnerLink(int plinkModelId, String pLinkName, String myRole, String partnerRole) { PartnerLinkDAOImpl pl = new PartnerLinkDAOImpl(plinkModelId, pLinkName, myRole, partnerRole); pl.setScope(this); _partnerLinks.add(pl); return pl; } public Collection<ScopeDAO> getChildScopes() { return _childScopes; } public CorrelationSetDAO getCorrelationSet(String corrSetName) { CorrelationSetDAO ret = null; for (CorrelationSetDAO csElement : _correlationSets) { if (csElement.getName().equals(corrSetName)) ret = csElement; } if (ret == null) { // Apparently the caller knows there should be a correlation set // in here. Create a new set if one does not exist. // Not sure I understand this implied object creation and why // an explicit create pattern isn't used ( i.e. similar to // PartnerLink creation ) ret = new CorrelationSetDAOImpl(this, corrSetName); // Persist the new correlation set to generate an ID getEM().persist(ret); _correlationSets.add(ret); } return ret; } public Collection<CorrelationSetDAO> getCorrelationSets() { return _correlationSets; } public int getModelId() { return _modelId; } public String getName() { return _name; } public ScopeDAO getParentScope() { return _parentScope; } public PartnerLinkDAO getPartnerLink(int plinkModelId) { for (PartnerLinkDAO pLink : getPartnerLinks()) { if (pLink.getPartnerLinkModelId() == plinkModelId) { return pLink; } } return null; } public Collection<PartnerLinkDAO> getPartnerLinks() { return _partnerLinks; } public ProcessInstanceDAO getProcessInstance() { return _processInstance; } public Long getScopeInstanceId() { return _scopeInstanceId; } public ScopeStateEnum getState() { return ScopeStateEnum.valueOf(_scopeState); } public XmlDataDAO getVariable(String varName) { XmlDataDAO ret = null; for (XmlDataDAO xmlElement : _variables) { if (xmlElement.getName().equals(varName)) return xmlElement; } ret = new XmlDataDAOImpl(this, varName); _variables.add(ret); return ret; } public Collection<XmlDataDAO> getVariables() { return _variables; } public List<BpelEvent> listEvents() { List<BpelEvent> result = new ArrayList<BpelEvent>(); Query qry = getEM().createNamedQuery("ScopeEvents"); qry.setParameter("sid", _scopeInstanceId); for (Object eventDao : qry.getResultList()) { result.add(((EventDAOImpl) eventDao).getEvent()); } return result; } public void setState(ScopeStateEnum state) { _scopeState = state.toString(); } }
package org.drip.analytics.holset; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * GENERATED on Fri Jan 11 19:54:07 EST 2013 ---- DO NOT DELETE */ /*! * Copyright (C) 2013 Lakshmi Krishnamurthy * Copyright (C) 2012 Lakshmi Krishnamurthy * Copyright (C) 2011 Lakshmi Krishnamurthy * * This file is part of CreditAnalytics, a free-software/open-source library for * fixed income analysts and developers - http://www.credit-trader.org * * CreditAnalytics is a free, full featured, fixed income credit analytics library, developed with a special focus * towards the needs of the bonds and credit products community. * * 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. */ public class ESPHoliday implements org.drip.analytics.holset.LocationHoliday { public ESPHoliday() { } public java.lang.String getHolidayLoc() { return "ESP"; } public org.drip.analytics.holiday.Locale getHolidaySet() { org.drip.analytics.holiday.Locale lh = new org.drip.analytics.holiday.Locale(); lh.addStaticHoliday ("01-JAN-1998", "New Years Day"); lh.addStaticHoliday ("06-JAN-1998", "Epiphany"); lh.addStaticHoliday ("19-MAR-1998", "St. Josephs Day"); lh.addStaticHoliday ("09-APR-1998", "Holy Thursday"); lh.addStaticHoliday ("10-APR-1998", "Good Friday"); lh.addStaticHoliday ("01-MAY-1998", "Labour Day"); lh.addStaticHoliday ("15-MAY-1998", "San Isidro"); lh.addStaticHoliday ("12-OCT-1998", "National Holiday"); lh.addStaticHoliday ("02-NOV-1998", "All Saints Day Observed"); lh.addStaticHoliday ("09-NOV-1998", "Our Lady of Almudena"); lh.addStaticHoliday ("08-DEC-1998", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-1998", "Christmas Day"); lh.addStaticHoliday ("01-JAN-1999", "New Years Day"); lh.addStaticHoliday ("06-JAN-1999", "Epiphany"); lh.addStaticHoliday ("19-MAR-1999", "St. Josephs Day"); lh.addStaticHoliday ("01-APR-1999", "Holy Thursday"); lh.addStaticHoliday ("02-APR-1999", "Good Friday"); lh.addStaticHoliday ("03-JUN-1999", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-1999", "National Holiday"); lh.addStaticHoliday ("01-NOV-1999", "All Saints Day"); lh.addStaticHoliday ("09-NOV-1999", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-1999", "Constitution Day"); lh.addStaticHoliday ("08-DEC-1999", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2000", "Epiphany"); lh.addStaticHoliday ("20-APR-2000", "Holy Thursday"); lh.addStaticHoliday ("21-APR-2000", "Good Friday"); lh.addStaticHoliday ("01-MAY-2000", "Labour Day"); lh.addStaticHoliday ("02-MAY-2000", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2000", "San Isidro"); lh.addStaticHoliday ("22-JUN-2000", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2000", "St. James Day"); lh.addStaticHoliday ("15-AUG-2000", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2000", "National Holiday"); lh.addStaticHoliday ("01-NOV-2000", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2000", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2000", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2000", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2000", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2001", "New Years Day"); lh.addStaticHoliday ("19-MAR-2001", "St. Josephs Day"); lh.addStaticHoliday ("12-APR-2001", "Holy Thursday"); lh.addStaticHoliday ("13-APR-2001", "Good Friday"); lh.addStaticHoliday ("16-APR-2001", "Easter Monday"); lh.addStaticHoliday ("01-MAY-2001", "Labour Day"); lh.addStaticHoliday ("02-MAY-2001", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2001", "San Isidro"); lh.addStaticHoliday ("14-JUN-2001", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2001", "St. James Day"); lh.addStaticHoliday ("15-AUG-2001", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2001", "National Holiday"); lh.addStaticHoliday ("01-NOV-2001", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2001", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2001", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2001", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2002", "New Years Day"); lh.addStaticHoliday ("19-MAR-2002", "St. Josephs Day"); lh.addStaticHoliday ("28-MAR-2002", "Holy Thursday"); lh.addStaticHoliday ("29-MAR-2002", "Good Friday"); lh.addStaticHoliday ("01-MAY-2002", "Labour Day"); lh.addStaticHoliday ("02-MAY-2002", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2002", "San Isidro"); lh.addStaticHoliday ("30-MAY-2002", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2002", "St. James Day"); lh.addStaticHoliday ("15-AUG-2002", "Assumption Day"); lh.addStaticHoliday ("01-NOV-2002", "All Saints Day"); lh.addStaticHoliday ("06-DEC-2002", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2002", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2003", "New Years Day"); lh.addStaticHoliday ("06-JAN-2003", "Epiphany"); lh.addStaticHoliday ("19-MAR-2003", "St. Josephs Day"); lh.addStaticHoliday ("17-APR-2003", "Holy Thursday"); lh.addStaticHoliday ("18-APR-2003", "Good Friday"); lh.addStaticHoliday ("01-MAY-2003", "Labour Day"); lh.addStaticHoliday ("02-MAY-2003", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2003", "San Isidro"); lh.addStaticHoliday ("19-JUN-2003", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2003", "St. James Day"); lh.addStaticHoliday ("15-AUG-2003", "Assumption Day"); lh.addStaticHoliday ("08-DEC-2003", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2003", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2004", "New Years Day"); lh.addStaticHoliday ("06-JAN-2004", "Epiphany"); lh.addStaticHoliday ("19-MAR-2004", "St. Josephs Day"); lh.addStaticHoliday ("08-APR-2004", "Holy Thursday"); lh.addStaticHoliday ("09-APR-2004", "Good Friday"); lh.addStaticHoliday ("10-JUN-2004", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2004", "National Holiday"); lh.addStaticHoliday ("01-NOV-2004", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2004", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2004", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2004", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2005", "Epiphany"); lh.addStaticHoliday ("24-MAR-2005", "Holy Thursday"); lh.addStaticHoliday ("25-MAR-2005", "Good Friday"); lh.addStaticHoliday ("02-MAY-2005", "Madrid Day"); lh.addStaticHoliday ("26-MAY-2005", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2005", "St. James Day"); lh.addStaticHoliday ("15-AUG-2005", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2005", "National Holiday"); lh.addStaticHoliday ("01-NOV-2005", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2005", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2005", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2005", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2006", "Epiphany"); lh.addStaticHoliday ("13-APR-2006", "Holy Thursday"); lh.addStaticHoliday ("14-APR-2006", "Good Friday"); lh.addStaticHoliday ("01-MAY-2006", "Labour Day"); lh.addStaticHoliday ("02-MAY-2006", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2006", "San Isidro"); lh.addStaticHoliday ("15-JUN-2006", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2006", "St. James Day"); lh.addStaticHoliday ("15-AUG-2006", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2006", "National Holiday"); lh.addStaticHoliday ("01-NOV-2006", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2006", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2006", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2006", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2006", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2007", "New Years Day"); lh.addStaticHoliday ("19-MAR-2007", "St. Josephs Day"); lh.addStaticHoliday ("05-APR-2007", "Holy Thursday"); lh.addStaticHoliday ("06-APR-2007", "Good Friday"); lh.addStaticHoliday ("01-MAY-2007", "Labour Day"); lh.addStaticHoliday ("02-MAY-2007", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2007", "San Isidro"); lh.addStaticHoliday ("07-JUN-2007", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2007", "St. James Day"); lh.addStaticHoliday ("15-AUG-2007", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2007", "National Holiday"); lh.addStaticHoliday ("01-NOV-2007", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2007", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2007", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2007", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2008", "New Years Day"); lh.addStaticHoliday ("19-MAR-2008", "St. Josephs Day"); lh.addStaticHoliday ("20-MAR-2008", "Holy Thursday"); lh.addStaticHoliday ("21-MAR-2008", "Good Friday"); lh.addStaticHoliday ("01-MAY-2008", "Labour Day"); lh.addStaticHoliday ("02-MAY-2008", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2008", "San Isidro"); lh.addStaticHoliday ("22-MAY-2008", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2008", "St. James Day"); lh.addStaticHoliday ("15-AUG-2008", "Assumption Day"); lh.addStaticHoliday ("08-DEC-2008", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2008", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2009", "New Years Day"); lh.addStaticHoliday ("06-JAN-2009", "Epiphany"); lh.addStaticHoliday ("19-MAR-2009", "St. Josephs Day"); lh.addStaticHoliday ("09-APR-2009", "Holy Thursday"); lh.addStaticHoliday ("10-APR-2009", "Good Friday"); lh.addStaticHoliday ("01-MAY-2009", "Labour Day"); lh.addStaticHoliday ("15-MAY-2009", "San Isidro"); lh.addStaticHoliday ("11-JUN-2009", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2009", "National Holiday"); lh.addStaticHoliday ("09-NOV-2009", "Our Lady of Almudena"); lh.addStaticHoliday ("08-DEC-2009", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2009", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2010", "New Years Day"); lh.addStaticHoliday ("06-JAN-2010", "Epiphany"); lh.addStaticHoliday ("19-MAR-2010", "St. Josephs Day"); lh.addStaticHoliday ("01-APR-2010", "Holy Thursday"); lh.addStaticHoliday ("02-APR-2010", "Good Friday"); lh.addStaticHoliday ("03-JUN-2010", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2010", "National Holiday"); lh.addStaticHoliday ("01-NOV-2010", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2010", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2010", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2010", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2011", "Epiphany"); lh.addStaticHoliday ("21-APR-2011", "Holy Thursday"); lh.addStaticHoliday ("22-APR-2011", "Good Friday"); lh.addStaticHoliday ("02-MAY-2011", "Madrid Day"); lh.addStaticHoliday ("23-JUN-2011", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2011", "St. James Day"); lh.addStaticHoliday ("15-AUG-2011", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2011", "National Holiday"); lh.addStaticHoliday ("01-NOV-2011", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2011", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2011", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2011", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2012", "Epiphany"); lh.addStaticHoliday ("19-MAR-2012", "St. Josephs Day"); lh.addStaticHoliday ("05-APR-2012", "Holy Thursday"); lh.addStaticHoliday ("06-APR-2012", "Good Friday"); lh.addStaticHoliday ("01-MAY-2012", "Labour Day"); lh.addStaticHoliday ("02-MAY-2012", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2012", "San Isidro"); lh.addStaticHoliday ("07-JUN-2012", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2012", "St. James Day"); lh.addStaticHoliday ("15-AUG-2012", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2012", "National Holiday"); lh.addStaticHoliday ("01-NOV-2012", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2012", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2012", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2012", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2013", "New Years Day"); lh.addStaticHoliday ("19-MAR-2013", "St. Josephs Day"); lh.addStaticHoliday ("28-MAR-2013", "Holy Thursday"); lh.addStaticHoliday ("29-MAR-2013", "Good Friday"); lh.addStaticHoliday ("01-MAY-2013", "Labour Day"); lh.addStaticHoliday ("02-MAY-2013", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2013", "San Isidro"); lh.addStaticHoliday ("30-MAY-2013", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2013", "St. James Day"); lh.addStaticHoliday ("15-AUG-2013", "Assumption Day"); lh.addStaticHoliday ("01-NOV-2013", "All Saints Day"); lh.addStaticHoliday ("06-DEC-2013", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2013", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2014", "New Years Day"); lh.addStaticHoliday ("06-JAN-2014", "Epiphany"); lh.addStaticHoliday ("19-MAR-2014", "St. Josephs Day"); lh.addStaticHoliday ("17-APR-2014", "Holy Thursday"); lh.addStaticHoliday ("18-APR-2014", "Good Friday"); lh.addStaticHoliday ("01-MAY-2014", "Labour Day"); lh.addStaticHoliday ("02-MAY-2014", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2014", "San Isidro"); lh.addStaticHoliday ("19-JUN-2014", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2014", "St. James Day"); lh.addStaticHoliday ("15-AUG-2014", "Assumption Day"); lh.addStaticHoliday ("08-DEC-2014", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2014", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2015", "New Years Day"); lh.addStaticHoliday ("06-JAN-2015", "Epiphany"); lh.addStaticHoliday ("19-MAR-2015", "St. Josephs Day"); lh.addStaticHoliday ("02-APR-2015", "Holy Thursday"); lh.addStaticHoliday ("03-APR-2015", "Good Friday"); lh.addStaticHoliday ("01-MAY-2015", "Labour Day"); lh.addStaticHoliday ("15-MAY-2015", "San Isidro"); lh.addStaticHoliday ("04-JUN-2015", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2015", "National Holiday"); lh.addStaticHoliday ("09-NOV-2015", "Our Lady of Almudena"); lh.addStaticHoliday ("08-DEC-2015", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2015", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2016", "New Years Day"); lh.addStaticHoliday ("06-JAN-2016", "Epiphany"); lh.addStaticHoliday ("24-MAR-2016", "Holy Thursday"); lh.addStaticHoliday ("25-MAR-2016", "Good Friday"); lh.addStaticHoliday ("02-MAY-2016", "Madrid Day"); lh.addStaticHoliday ("26-MAY-2016", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2016", "St. James Day"); lh.addStaticHoliday ("15-AUG-2016", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2016", "National Holiday"); lh.addStaticHoliday ("01-NOV-2016", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2016", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2016", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2016", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2017", "Epiphany"); lh.addStaticHoliday ("13-APR-2017", "Holy Thursday"); lh.addStaticHoliday ("14-APR-2017", "Good Friday"); lh.addStaticHoliday ("01-MAY-2017", "Labour Day"); lh.addStaticHoliday ("02-MAY-2017", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2017", "San Isidro"); lh.addStaticHoliday ("15-JUN-2017", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2017", "St. James Day"); lh.addStaticHoliday ("15-AUG-2017", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2017", "National Holiday"); lh.addStaticHoliday ("01-NOV-2017", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2017", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2017", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2017", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2017", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2018", "New Years Day"); lh.addStaticHoliday ("19-MAR-2018", "St. Josephs Day"); lh.addStaticHoliday ("29-MAR-2018", "Holy Thursday"); lh.addStaticHoliday ("30-MAR-2018", "Good Friday"); lh.addStaticHoliday ("01-MAY-2018", "Labour Day"); lh.addStaticHoliday ("02-MAY-2018", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2018", "San Isidro"); lh.addStaticHoliday ("31-MAY-2018", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2018", "St. James Day"); lh.addStaticHoliday ("15-AUG-2018", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2018", "National Holiday"); lh.addStaticHoliday ("01-NOV-2018", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2018", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2018", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2018", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2019", "New Years Day"); lh.addStaticHoliday ("19-MAR-2019", "St. Josephs Day"); lh.addStaticHoliday ("18-APR-2019", "Holy Thursday"); lh.addStaticHoliday ("19-APR-2019", "Good Friday"); lh.addStaticHoliday ("01-MAY-2019", "Labour Day"); lh.addStaticHoliday ("02-MAY-2019", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2019", "San Isidro"); lh.addStaticHoliday ("20-JUN-2019", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2019", "St. James Day"); lh.addStaticHoliday ("15-AUG-2019", "Assumption Day"); lh.addStaticHoliday ("01-NOV-2019", "All Saints Day"); lh.addStaticHoliday ("06-DEC-2019", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2019", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2020", "New Years Day"); lh.addStaticHoliday ("06-JAN-2020", "Epiphany"); lh.addStaticHoliday ("19-MAR-2020", "St. Josephs Day"); lh.addStaticHoliday ("09-APR-2020", "Holy Thursday"); lh.addStaticHoliday ("10-APR-2020", "Good Friday"); lh.addStaticHoliday ("01-MAY-2020", "Labour Day"); lh.addStaticHoliday ("15-MAY-2020", "San Isidro"); lh.addStaticHoliday ("11-JUN-2020", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2020", "National Holiday"); lh.addStaticHoliday ("09-NOV-2020", "Our Lady of Almudena"); lh.addStaticHoliday ("08-DEC-2020", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2020", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2021", "New Years Day"); lh.addStaticHoliday ("06-JAN-2021", "Epiphany"); lh.addStaticHoliday ("19-MAR-2021", "St. Josephs Day"); lh.addStaticHoliday ("01-APR-2021", "Holy Thursday"); lh.addStaticHoliday ("02-APR-2021", "Good Friday"); lh.addStaticHoliday ("03-JUN-2021", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2021", "National Holiday"); lh.addStaticHoliday ("01-NOV-2021", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2021", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2021", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2021", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2022", "Epiphany"); lh.addStaticHoliday ("14-APR-2022", "Holy Thursday"); lh.addStaticHoliday ("15-APR-2022", "Good Friday"); lh.addStaticHoliday ("02-MAY-2022", "Madrid Day"); lh.addStaticHoliday ("16-JUN-2022", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2022", "St. James Day"); lh.addStaticHoliday ("15-AUG-2022", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2022", "National Holiday"); lh.addStaticHoliday ("01-NOV-2022", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2022", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2022", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2022", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2023", "Epiphany"); lh.addStaticHoliday ("06-APR-2023", "Holy Thursday"); lh.addStaticHoliday ("07-APR-2023", "Good Friday"); lh.addStaticHoliday ("01-MAY-2023", "Labour Day"); lh.addStaticHoliday ("02-MAY-2023", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2023", "San Isidro"); lh.addStaticHoliday ("08-JUN-2023", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2023", "St. James Day"); lh.addStaticHoliday ("15-AUG-2023", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2023", "National Holiday"); lh.addStaticHoliday ("01-NOV-2023", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2023", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2023", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2023", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2023", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2024", "New Years Day"); lh.addStaticHoliday ("19-MAR-2024", "St. Josephs Day"); lh.addStaticHoliday ("28-MAR-2024", "Holy Thursday"); lh.addStaticHoliday ("29-MAR-2024", "Good Friday"); lh.addStaticHoliday ("01-MAY-2024", "Labour Day"); lh.addStaticHoliday ("02-MAY-2024", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2024", "San Isidro"); lh.addStaticHoliday ("30-MAY-2024", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2024", "St. James Day"); lh.addStaticHoliday ("15-AUG-2024", "Assumption Day"); lh.addStaticHoliday ("01-NOV-2024", "All Saints Day"); lh.addStaticHoliday ("06-DEC-2024", "Constitution Day"); lh.addStaticHoliday ("25-DEC-2024", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2025", "New Years Day"); lh.addStaticHoliday ("06-JAN-2025", "Epiphany"); lh.addStaticHoliday ("19-MAR-2025", "St. Josephs Day"); lh.addStaticHoliday ("17-APR-2025", "Holy Thursday"); lh.addStaticHoliday ("18-APR-2025", "Good Friday"); lh.addStaticHoliday ("01-MAY-2025", "Labour Day"); lh.addStaticHoliday ("02-MAY-2025", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2025", "San Isidro"); lh.addStaticHoliday ("19-JUN-2025", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2025", "St. James Day"); lh.addStaticHoliday ("15-AUG-2025", "Assumption Day"); lh.addStaticHoliday ("08-DEC-2025", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2025", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2026", "New Years Day"); lh.addStaticHoliday ("06-JAN-2026", "Epiphany"); lh.addStaticHoliday ("19-MAR-2026", "St. Josephs Day"); lh.addStaticHoliday ("02-APR-2026", "Holy Thursday"); lh.addStaticHoliday ("03-APR-2026", "Good Friday"); lh.addStaticHoliday ("01-MAY-2026", "Labour Day"); lh.addStaticHoliday ("15-MAY-2026", "San Isidro"); lh.addStaticHoliday ("04-JUN-2026", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2026", "National Holiday"); lh.addStaticHoliday ("09-NOV-2026", "Our Lady of Almudena"); lh.addStaticHoliday ("08-DEC-2026", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2026", "Christmas Day"); lh.addStaticHoliday ("01-JAN-2027", "New Years Day"); lh.addStaticHoliday ("06-JAN-2027", "Epiphany"); lh.addStaticHoliday ("19-MAR-2027", "St. Josephs Day"); lh.addStaticHoliday ("25-MAR-2027", "Holy Thursday"); lh.addStaticHoliday ("26-MAR-2027", "Good Friday"); lh.addStaticHoliday ("27-MAY-2027", "Corpus Christi"); lh.addStaticHoliday ("12-OCT-2027", "National Holiday"); lh.addStaticHoliday ("01-NOV-2027", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2027", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2027", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2027", "Immaculate Conception"); lh.addStaticHoliday ("06-JAN-2028", "Epiphany"); lh.addStaticHoliday ("13-APR-2028", "Holy Thursday"); lh.addStaticHoliday ("14-APR-2028", "Good Friday"); lh.addStaticHoliday ("01-MAY-2028", "Labour Day"); lh.addStaticHoliday ("02-MAY-2028", "Madrid Day"); lh.addStaticHoliday ("15-MAY-2028", "San Isidro"); lh.addStaticHoliday ("15-JUN-2028", "Corpus Christi"); lh.addStaticHoliday ("25-JUL-2028", "St. James Day"); lh.addStaticHoliday ("15-AUG-2028", "Assumption Day"); lh.addStaticHoliday ("12-OCT-2028", "National Holiday"); lh.addStaticHoliday ("01-NOV-2028", "All Saints Day"); lh.addStaticHoliday ("09-NOV-2028", "Our Lady of Almudena"); lh.addStaticHoliday ("06-DEC-2028", "Constitution Day"); lh.addStaticHoliday ("08-DEC-2028", "Immaculate Conception"); lh.addStaticHoliday ("25-DEC-2028", "Christmas Day"); lh.addStandardWeekend(); return lh; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: grpc/meta_master.proto package alluxio.grpc; /** * Protobuf type {@code alluxio.grpc.meta.ConfigProperties} */ public final class ConfigProperties extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:alluxio.grpc.meta.ConfigProperties) ConfigPropertiesOrBuilder { private static final long serialVersionUID = 0L; // Use ConfigProperties.newBuilder() to construct. private ConfigProperties(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ConfigProperties() { properties_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ConfigProperties( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { properties_ = new java.util.ArrayList<alluxio.grpc.ConfigProperty>(); mutable_bitField0_ |= 0x00000001; } properties_.add( input.readMessage(alluxio.grpc.ConfigProperty.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { properties_ = java.util.Collections.unmodifiableList(properties_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_ConfigProperties_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_ConfigProperties_fieldAccessorTable .ensureFieldAccessorsInitialized( alluxio.grpc.ConfigProperties.class, alluxio.grpc.ConfigProperties.Builder.class); } public static final int PROPERTIES_FIELD_NUMBER = 1; private java.util.List<alluxio.grpc.ConfigProperty> properties_; /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public java.util.List<alluxio.grpc.ConfigProperty> getPropertiesList() { return properties_; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public java.util.List<? extends alluxio.grpc.ConfigPropertyOrBuilder> getPropertiesOrBuilderList() { return properties_; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public int getPropertiesCount() { return properties_.size(); } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public alluxio.grpc.ConfigProperty getProperties(int index) { return properties_.get(index); } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public alluxio.grpc.ConfigPropertyOrBuilder getPropertiesOrBuilder( int index) { return properties_.get(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < properties_.size(); i++) { output.writeMessage(1, properties_.get(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < properties_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, properties_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof alluxio.grpc.ConfigProperties)) { return super.equals(obj); } alluxio.grpc.ConfigProperties other = (alluxio.grpc.ConfigProperties) obj; boolean result = true; result = result && getPropertiesList() .equals(other.getPropertiesList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getPropertiesCount() > 0) { hash = (37 * hash) + PROPERTIES_FIELD_NUMBER; hash = (53 * hash) + getPropertiesList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static alluxio.grpc.ConfigProperties parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static alluxio.grpc.ConfigProperties parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static alluxio.grpc.ConfigProperties parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static alluxio.grpc.ConfigProperties parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static alluxio.grpc.ConfigProperties parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static alluxio.grpc.ConfigProperties parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static alluxio.grpc.ConfigProperties parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static alluxio.grpc.ConfigProperties parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static alluxio.grpc.ConfigProperties parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static alluxio.grpc.ConfigProperties parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static alluxio.grpc.ConfigProperties parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static alluxio.grpc.ConfigProperties parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(alluxio.grpc.ConfigProperties prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code alluxio.grpc.meta.ConfigProperties} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:alluxio.grpc.meta.ConfigProperties) alluxio.grpc.ConfigPropertiesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_ConfigProperties_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_ConfigProperties_fieldAccessorTable .ensureFieldAccessorsInitialized( alluxio.grpc.ConfigProperties.class, alluxio.grpc.ConfigProperties.Builder.class); } // Construct using alluxio.grpc.ConfigProperties.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getPropertiesFieldBuilder(); } } public Builder clear() { super.clear(); if (propertiesBuilder_ == null) { properties_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { propertiesBuilder_.clear(); } return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return alluxio.grpc.MetaMasterProto.internal_static_alluxio_grpc_meta_ConfigProperties_descriptor; } public alluxio.grpc.ConfigProperties getDefaultInstanceForType() { return alluxio.grpc.ConfigProperties.getDefaultInstance(); } public alluxio.grpc.ConfigProperties build() { alluxio.grpc.ConfigProperties result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public alluxio.grpc.ConfigProperties buildPartial() { alluxio.grpc.ConfigProperties result = new alluxio.grpc.ConfigProperties(this); int from_bitField0_ = bitField0_; if (propertiesBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { properties_ = java.util.Collections.unmodifiableList(properties_); bitField0_ = (bitField0_ & ~0x00000001); } result.properties_ = properties_; } else { result.properties_ = propertiesBuilder_.build(); } onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof alluxio.grpc.ConfigProperties) { return mergeFrom((alluxio.grpc.ConfigProperties)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(alluxio.grpc.ConfigProperties other) { if (other == alluxio.grpc.ConfigProperties.getDefaultInstance()) return this; if (propertiesBuilder_ == null) { if (!other.properties_.isEmpty()) { if (properties_.isEmpty()) { properties_ = other.properties_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePropertiesIsMutable(); properties_.addAll(other.properties_); } onChanged(); } } else { if (!other.properties_.isEmpty()) { if (propertiesBuilder_.isEmpty()) { propertiesBuilder_.dispose(); propertiesBuilder_ = null; properties_ = other.properties_; bitField0_ = (bitField0_ & ~0x00000001); propertiesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPropertiesFieldBuilder() : null; } else { propertiesBuilder_.addAllMessages(other.properties_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { alluxio.grpc.ConfigProperties parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (alluxio.grpc.ConfigProperties) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<alluxio.grpc.ConfigProperty> properties_ = java.util.Collections.emptyList(); private void ensurePropertiesIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { properties_ = new java.util.ArrayList<alluxio.grpc.ConfigProperty>(properties_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< alluxio.grpc.ConfigProperty, alluxio.grpc.ConfigProperty.Builder, alluxio.grpc.ConfigPropertyOrBuilder> propertiesBuilder_; /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public java.util.List<alluxio.grpc.ConfigProperty> getPropertiesList() { if (propertiesBuilder_ == null) { return java.util.Collections.unmodifiableList(properties_); } else { return propertiesBuilder_.getMessageList(); } } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public int getPropertiesCount() { if (propertiesBuilder_ == null) { return properties_.size(); } else { return propertiesBuilder_.getCount(); } } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public alluxio.grpc.ConfigProperty getProperties(int index) { if (propertiesBuilder_ == null) { return properties_.get(index); } else { return propertiesBuilder_.getMessage(index); } } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder setProperties( int index, alluxio.grpc.ConfigProperty value) { if (propertiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropertiesIsMutable(); properties_.set(index, value); onChanged(); } else { propertiesBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder setProperties( int index, alluxio.grpc.ConfigProperty.Builder builderForValue) { if (propertiesBuilder_ == null) { ensurePropertiesIsMutable(); properties_.set(index, builderForValue.build()); onChanged(); } else { propertiesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder addProperties(alluxio.grpc.ConfigProperty value) { if (propertiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropertiesIsMutable(); properties_.add(value); onChanged(); } else { propertiesBuilder_.addMessage(value); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder addProperties( int index, alluxio.grpc.ConfigProperty value) { if (propertiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePropertiesIsMutable(); properties_.add(index, value); onChanged(); } else { propertiesBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder addProperties( alluxio.grpc.ConfigProperty.Builder builderForValue) { if (propertiesBuilder_ == null) { ensurePropertiesIsMutable(); properties_.add(builderForValue.build()); onChanged(); } else { propertiesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder addProperties( int index, alluxio.grpc.ConfigProperty.Builder builderForValue) { if (propertiesBuilder_ == null) { ensurePropertiesIsMutable(); properties_.add(index, builderForValue.build()); onChanged(); } else { propertiesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder addAllProperties( java.lang.Iterable<? extends alluxio.grpc.ConfigProperty> values) { if (propertiesBuilder_ == null) { ensurePropertiesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, properties_); onChanged(); } else { propertiesBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder clearProperties() { if (propertiesBuilder_ == null) { properties_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { propertiesBuilder_.clear(); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public Builder removeProperties(int index) { if (propertiesBuilder_ == null) { ensurePropertiesIsMutable(); properties_.remove(index); onChanged(); } else { propertiesBuilder_.remove(index); } return this; } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public alluxio.grpc.ConfigProperty.Builder getPropertiesBuilder( int index) { return getPropertiesFieldBuilder().getBuilder(index); } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public alluxio.grpc.ConfigPropertyOrBuilder getPropertiesOrBuilder( int index) { if (propertiesBuilder_ == null) { return properties_.get(index); } else { return propertiesBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public java.util.List<? extends alluxio.grpc.ConfigPropertyOrBuilder> getPropertiesOrBuilderList() { if (propertiesBuilder_ != null) { return propertiesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(properties_); } } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public alluxio.grpc.ConfigProperty.Builder addPropertiesBuilder() { return getPropertiesFieldBuilder().addBuilder( alluxio.grpc.ConfigProperty.getDefaultInstance()); } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public alluxio.grpc.ConfigProperty.Builder addPropertiesBuilder( int index) { return getPropertiesFieldBuilder().addBuilder( index, alluxio.grpc.ConfigProperty.getDefaultInstance()); } /** * <code>repeated .alluxio.grpc.ConfigProperty properties = 1;</code> */ public java.util.List<alluxio.grpc.ConfigProperty.Builder> getPropertiesBuilderList() { return getPropertiesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< alluxio.grpc.ConfigProperty, alluxio.grpc.ConfigProperty.Builder, alluxio.grpc.ConfigPropertyOrBuilder> getPropertiesFieldBuilder() { if (propertiesBuilder_ == null) { propertiesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< alluxio.grpc.ConfigProperty, alluxio.grpc.ConfigProperty.Builder, alluxio.grpc.ConfigPropertyOrBuilder>( properties_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); properties_ = null; } return propertiesBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:alluxio.grpc.meta.ConfigProperties) } // @@protoc_insertion_point(class_scope:alluxio.grpc.meta.ConfigProperties) private static final alluxio.grpc.ConfigProperties DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new alluxio.grpc.ConfigProperties(); } public static alluxio.grpc.ConfigProperties getDefaultInstance() { return DEFAULT_INSTANCE; } @java.lang.Deprecated public static final com.google.protobuf.Parser<ConfigProperties> PARSER = new com.google.protobuf.AbstractParser<ConfigProperties>() { public ConfigProperties parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ConfigProperties(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ConfigProperties> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ConfigProperties> getParserForType() { return PARSER; } public alluxio.grpc.ConfigProperties getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * 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.connector.kinesis.table; import org.apache.flink.api.connector.sink2.Sink; import org.apache.flink.connector.kinesis.sink.KinesisStreamsSink; import org.apache.flink.table.api.DataTypes; import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.catalog.Column; import org.apache.flink.table.catalog.ResolvedSchema; import org.apache.flink.table.connector.sink.DynamicTableSink; import org.apache.flink.table.connector.sink.SinkV2Provider; import org.apache.flink.table.data.RowData; import org.apache.flink.table.factories.TableOptionsBuilder; import org.apache.flink.table.factories.TestFormatFactory; import org.apache.flink.table.runtime.connector.sink.SinkRuntimeProviderContext; import org.apache.flink.table.types.DataType; import org.apache.flink.table.types.logical.RowType; import org.apache.flink.util.TestLogger; import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.FLUSH_BUFFER_SIZE; import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.FLUSH_BUFFER_TIMEOUT; import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.MAX_BATCH_SIZE; import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.MAX_BUFFERED_REQUESTS; import static org.apache.flink.connector.base.table.AsyncSinkConnectorOptions.MAX_IN_FLIGHT_REQUESTS; import static org.apache.flink.connector.kinesis.table.KinesisConnectorOptions.SINK_FAIL_ON_ERROR; import static org.apache.flink.table.factories.utils.FactoryMocks.createTableSink; /** Test for {@link KinesisDynamicSink} created by {@link KinesisDynamicTableSinkFactory}. */ public class KinesisDynamicTableSinkFactoryTest extends TestLogger { private static final String STREAM_NAME = "myStream"; @Test public void testGoodTableSinkForPartitionedTable() { ResolvedSchema sinkSchema = defaultSinkSchema(); DataType physicalDataType = sinkSchema.toPhysicalRowDataType(); Map<String, String> sinkOptions = defaultTableOptions().build(); List<String> sinkPartitionKeys = Arrays.asList("name", "curr_id"); // Construct actual DynamicTableSink using FactoryUtil KinesisDynamicSink actualSink = (KinesisDynamicSink) createTableSink(sinkSchema, sinkPartitionKeys, sinkOptions); // Construct expected DynamicTableSink using factory under test KinesisDynamicSink expectedSink = (KinesisDynamicSink) new KinesisDynamicSink.KinesisDynamicTableSinkBuilder() .setConsumedDataType(physicalDataType) .setStream(STREAM_NAME) .setKinesisClientProperties(defaultProducerProperties()) .setEncodingFormat(new TestFormatFactory.EncodingFormatMock(",")) .setPartitioner( new RowDataFieldsKinesisPartitionKeyGenerator( (RowType) physicalDataType.getLogicalType(), sinkPartitionKeys)) .build(); // verify that the constructed DynamicTableSink is as expected Assertions.assertThat(actualSink).isEqualTo(expectedSink); // verify the produced sink DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider = actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false)); Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink(); Assertions.assertThat(sinkFunction).isInstanceOf(KinesisStreamsSink.class); } @Test public void testGoodTableSinkCopyForPartitionedTable() { ResolvedSchema sinkSchema = defaultSinkSchema(); DataType physicalDataType = sinkSchema.toPhysicalRowDataType(); Map<String, String> sinkOptions = defaultTableOptions().build(); List<String> sinkPartitionKeys = Arrays.asList("name", "curr_id"); // Construct actual DynamicTableSink using FactoryUtil KinesisDynamicSink actualSink = (KinesisDynamicSink) createTableSink(sinkSchema, sinkPartitionKeys, sinkOptions); // Construct expected DynamicTableSink using factory under test KinesisDynamicSink expectedSink = (KinesisDynamicSink) new KinesisDynamicSink.KinesisDynamicTableSinkBuilder() .setConsumedDataType(physicalDataType) .setStream(STREAM_NAME) .setKinesisClientProperties(defaultProducerProperties()) .setEncodingFormat(new TestFormatFactory.EncodingFormatMock(",")) .setPartitioner( new RowDataFieldsKinesisPartitionKeyGenerator( (RowType) physicalDataType.getLogicalType(), sinkPartitionKeys)) .build(); Assertions.assertThat(actualSink).isEqualTo(expectedSink.copy()); Assertions.assertThat(expectedSink).isNotSameAs(expectedSink.copy()); } @Test public void testGoodTableSinkForNonPartitionedTable() { ResolvedSchema sinkSchema = defaultSinkSchema(); Map<String, String> sinkOptions = defaultTableOptions().build(); // Construct actual DynamicTableSink using FactoryUtil KinesisDynamicSink actualSink = (KinesisDynamicSink) createTableSink(sinkSchema, sinkOptions); // Construct expected DynamicTableSink using factory under test KinesisDynamicSink expectedSink = (KinesisDynamicSink) new KinesisDynamicSink.KinesisDynamicTableSinkBuilder() .setConsumedDataType(sinkSchema.toPhysicalRowDataType()) .setStream(STREAM_NAME) .setKinesisClientProperties(defaultProducerProperties()) .setEncodingFormat(new TestFormatFactory.EncodingFormatMock(",")) .setPartitioner(new RandomKinesisPartitionKeyGenerator<>()) .build(); Assertions.assertThat(actualSink).isEqualTo(expectedSink); // verify the produced sink DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider = actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false)); Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink(); Assertions.assertThat(sinkFunction).isInstanceOf(KinesisStreamsSink.class); } @Test public void testGoodTableSinkForNonPartitionedTableWithSinkOptions() { ResolvedSchema sinkSchema = defaultSinkSchema(); Map<String, String> sinkOptions = defaultTableOptionsWithSinkOptions().build(); // Construct actual DynamicTableSink using FactoryUtil KinesisDynamicSink actualSink = (KinesisDynamicSink) createTableSink(sinkSchema, sinkOptions); // Construct expected DynamicTableSink using factory under test KinesisDynamicSink expectedSink = (KinesisDynamicSink) getDefaultSinkBuilder() .setConsumedDataType(sinkSchema.toPhysicalRowDataType()) .setStream(STREAM_NAME) .setKinesisClientProperties(defaultProducerProperties()) .setEncodingFormat(new TestFormatFactory.EncodingFormatMock(",")) .setPartitioner(new RandomKinesisPartitionKeyGenerator<>()) .build(); Assertions.assertThat(actualSink).isEqualTo(expectedSink); // verify the produced sink DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider = actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false)); Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink(); Assertions.assertThat(sinkFunction).isInstanceOf(KinesisStreamsSink.class); } @Test public void testGoodTableSinkForNonPartitionedTableWithProducerOptions() { ResolvedSchema sinkSchema = defaultSinkSchema(); Map<String, String> sinkOptions = defaultTableOptionsWithDeprecatedOptions().build(); // Construct actual DynamicTableSink using FactoryUtil KinesisDynamicSink actualSink = (KinesisDynamicSink) createTableSink(sinkSchema, sinkOptions); // Construct expected DynamicTableSink using factory under test KinesisDynamicSink expectedSink = (KinesisDynamicSink) new KinesisDynamicSink.KinesisDynamicTableSinkBuilder() .setFailOnError(true) .setMaxBatchSize(100) .setMaxInFlightRequests(100) .setMaxTimeInBufferMS(1000) .setConsumedDataType(sinkSchema.toPhysicalRowDataType()) .setStream(STREAM_NAME) .setKinesisClientProperties(defaultProducerProperties()) .setEncodingFormat(new TestFormatFactory.EncodingFormatMock(",")) .setPartitioner(new RandomKinesisPartitionKeyGenerator<>()) .build(); // verify that the constructed DynamicTableSink is as expected Assertions.assertThat(actualSink).isEqualTo(expectedSink); // verify the produced sink DynamicTableSink.SinkRuntimeProvider sinkFunctionProvider = actualSink.getSinkRuntimeProvider(new SinkRuntimeProviderContext(false)); Sink<RowData> sinkFunction = ((SinkV2Provider) sinkFunctionProvider).createSink(); Assertions.assertThat(sinkFunction).isInstanceOf(KinesisStreamsSink.class); } @Test public void testBadTableSinkForCustomPartitionerForPartitionedTable() { ResolvedSchema sinkSchema = defaultSinkSchema(); Map<String, String> sinkOptions = defaultTableOptions() .withTableOption(KinesisConnectorOptions.SINK_PARTITIONER, "random") .build(); Assertions.assertThatExceptionOfType(ValidationException.class) .isThrownBy( () -> createTableSink( sinkSchema, Arrays.asList("name", "curr_id"), sinkOptions)) .havingCause() .withMessageContaining( String.format( "Cannot set %s option for a table defined with a PARTITIONED BY clause", KinesisConnectorOptions.SINK_PARTITIONER.key())); } @Test public void testBadTableSinkForNonExistingPartitionerClass() { ResolvedSchema sinkSchema = defaultSinkSchema(); Map<String, String> sinkOptions = defaultTableOptions() .withTableOption(KinesisConnectorOptions.SINK_PARTITIONER, "abc") .build(); Assertions.assertThatExceptionOfType(ValidationException.class) .isThrownBy(() -> createTableSink(sinkSchema, sinkOptions)) .havingCause() .withMessageContaining("Could not find and instantiate partitioner class 'abc'"); } private ResolvedSchema defaultSinkSchema() { return ResolvedSchema.of( Column.physical("name", DataTypes.STRING()), Column.physical("curr_id", DataTypes.BIGINT()), Column.physical("time", DataTypes.TIMESTAMP(3))); } private TableOptionsBuilder defaultTableOptionsWithSinkOptions() { return defaultTableOptions() .withTableOption(SINK_FAIL_ON_ERROR.key(), "true") .withTableOption(MAX_BATCH_SIZE.key(), "100") .withTableOption(MAX_IN_FLIGHT_REQUESTS.key(), "100") .withTableOption(MAX_BUFFERED_REQUESTS.key(), "100") .withTableOption(FLUSH_BUFFER_SIZE.key(), "1000") .withTableOption(FLUSH_BUFFER_TIMEOUT.key(), "1000"); } private TableOptionsBuilder defaultTableOptionsWithDeprecatedOptions() { return defaultTableOptions() .withTableOption("sink.producer.record-max-buffered-time", "1000") .withTableOption("sink.producer.collection-max-size", "100") .withTableOption("sink.producer.collection-max-count", "100") .withTableOption("sink.producer.fail-on-error", "true"); } private TableOptionsBuilder defaultTableOptions() { String connector = KinesisDynamicTableSinkFactory.IDENTIFIER; String format = TestFormatFactory.IDENTIFIER; return new TableOptionsBuilder(connector, format) // default table options .withTableOption(KinesisConnectorOptions.STREAM, STREAM_NAME) .withTableOption("aws.region", "us-west-2") .withTableOption("aws.credentials.provider", "BASIC") .withTableOption("aws.credentials.basic.accesskeyid", "ververicka") .withTableOption( "aws.credentials.basic.secretkey", "SuperSecretSecretSquirrel") // default format options .withFormatOption(TestFormatFactory.DELIMITER, ",") .withFormatOption(TestFormatFactory.FAIL_ON_MISSING, "true"); } private KinesisDynamicSink.KinesisDynamicTableSinkBuilder getDefaultSinkBuilder() { return new KinesisDynamicSink.KinesisDynamicTableSinkBuilder() .setFailOnError(true) .setMaxBatchSize(100) .setMaxInFlightRequests(100) .setMaxBufferSizeInBytes(1000) .setMaxBufferedRequests(100) .setMaxTimeInBufferMS(1000); } private Properties defaultProducerProperties() { return new Properties() { { setProperty("aws.region", "us-west-2"); setProperty("aws.credentials.provider", "BASIC"); setProperty("aws.credentials.provider.basic.accesskeyid", "ververicka"); setProperty( "aws.credentials.provider.basic.secretkey", "SuperSecretSecretSquirrel"); } }; } }
package gr.cryptocurrencies.bitcoinpos.utilities; import android.content.Context; import android.widget.Toast; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; public class AddressValidator { public AddressValidator(Context context){ this.context=context; } private static Context context; private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); private static final int[] INDEXES = new int[128]; private static final MessageDigest digest; public final static String showAddressInvalidMessage = "showAddressInvalidMessage";//transferred from BitcoinUtils static { try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } for (int i = 0; i < INDEXES.length; i++) { INDEXES[i] = -1; } for (int i = 0; i < ALPHABET.length; i++) { INDEXES[ALPHABET[i]] = i; } } // easy way to change between testnet and mainnet for development only public static boolean isMainNet(String btcAddress) { //if(btcAddress.startsWith("m")||btcAddress.startsWith("n")) //{return false;} //finding if address is testnet, for development only //requires String address to be passed to method //return false: using for testnet return true; } public static boolean isAddressUsingBIP21(String addressString) { return addressString.indexOf(":") != -1; } public static String getAddressFromBip21String(String addressString) { int cryptoUriIndex = addressString.indexOf(":"); int paramsIndex = addressString.indexOf("?"); if(cryptoUriIndex != -1) { // get address from bitcoin uri scheme if(paramsIndex != -1) return addressString.substring(cryptoUriIndex + 1, paramsIndex); else return addressString.substring(cryptoUriIndex + 1); } else { // not using BIP 21 return addressString; } } public static boolean validate(String addr, String cryptocurrency) { if(cryptocurrency.equals(String.valueOf(CurrencyUtils.CurrencyType.BTC))) { try { int addressHeader = getAddressHeader(addr); //Toast.makeText(context, String.valueOf(addressHeader), Toast.LENGTH_SHORT).show(); return ( addressHeader == 0 || addressHeader == 5 ); } catch (Exception x) { x.printStackTrace(); } } else if(cryptocurrency.equals(String.valueOf(CurrencyUtils.CurrencyType.BCH))) { //bitcoin cash address return true // if (addr.startsWith("q") || addr.startsWith("p") || addr.startsWith("1") || addr.startsWith("3")) { // return true; // } try { int addressHeader = getAddressHeader(addr); return ( addressHeader == 0 || addressHeader == 5 ); } catch (Exception x) { x.printStackTrace(); } } else if (cryptocurrency.equals(String.valueOf(CurrencyUtils.CurrencyType.LTC))){ try { int addressHeader = getAddressHeader(addr); return ( addressHeader == 0 || addressHeader == 5 || addressHeader == 48 || addressHeader == 50); //addresses starting with //L// and /////////////M/ } catch (Exception x) { x.printStackTrace(); } } else if(cryptocurrency.equals(String.valueOf(CurrencyUtils.CurrencyType.BTCTEST))){ try { int addressHeader = getAddressHeader(addr); return ( addressHeader == 111 || addressHeader == 196 ); } catch (Exception x) { x.printStackTrace(); } } return false; } private static int getAddressHeader(String address) throws IOException { byte[] tmp = decodeChecked(address); return tmp[0] & 0xFF; } private static byte[] decodeChecked(String input) throws IOException { byte[] tmp = decode(input); if (tmp.length < 4) throw new IOException("BTC AddressFormatException Input too short"); byte[] bytes = copyOfRange(tmp, 0, tmp.length - 4); byte[] checksum = copyOfRange(tmp, tmp.length - 4, tmp.length); tmp = doubleDigest(bytes); byte[] hash = copyOfRange(tmp, 0, 4); if (!Arrays.equals(checksum, hash)) throw new IOException("BTC AddressFormatException Checksum does not validate"); return bytes; } private static byte[] doubleDigest(byte[] input) { return doubleDigest(input, 0, input.length); } private static byte[] doubleDigest(byte[] input, int offset, int length) { synchronized (digest) { digest.reset(); digest.update(input, offset, length); byte[] first = digest.digest(); return digest.digest(first); } } private static byte[] decode(String input) throws IOException { if (input.length() == 0) { return new byte[0]; } byte[] input58 = new byte[input.length()]; // Transform the String to a base58 byte sequence for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); int digit58 = -1; if (c >= 0 && c < 128) { digit58 = INDEXES[c]; } if (digit58 < 0) { throw new IOException("Bitcoin AddressFormatException Illegal character " + c + " at " + i); } input58[i] = (byte) digit58; } // Count leading zeroes int zeroCount = 0; while (zeroCount < input58.length && input58[zeroCount] == 0) { ++zeroCount; } // The encoding byte[] temp = new byte[input.length()]; int j = temp.length; int startAt = zeroCount; while (startAt < input58.length) { byte mod = divmod256(input58, startAt); if (input58[startAt] == 0) { ++startAt; } temp[--j] = mod; } // Do no add extra leading zeroes, move j to first non null byte. while (j < temp.length && temp[j] == 0) { ++j; } return copyOfRange(temp, j - zeroCount, temp.length); } private static byte divmod256(byte[] number58, int startAt) { int remainder = 0; for (int i = startAt; i < number58.length; i++) { int digit58 = (int) number58[i] & 0xFF; int temp = remainder * 58 + digit58; number58[i] = (byte) (temp / 256); remainder = temp % 256; } return (byte) remainder; } private static byte[] copyOfRange(byte[] source, int from, int to) { byte[] range = new byte[to - from]; System.arraycopy(source, from, range, 0, range.length); return range; } }
/************************************************************************ TextArea.java is part of Ti4j 3.1.0 Copyright 2013 Emitrom 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.emitrom.ti4j.mobile.client.ui; import java.util.ArrayList; import com.emitrom.ti4j.core.client.ProxyObject; import com.emitrom.ti4j.mobile.client.core.Unit; import com.emitrom.ti4j.mobile.client.core.handlers.ui.CallbackRegistration; import com.emitrom.ti4j.mobile.client.core.handlers.ui.TextChangedHandler; import com.emitrom.ti4j.mobile.client.core.handlers.ui.TextReturnHandler; import com.emitrom.ti4j.mobile.client.ui.style.Font; import com.emitrom.ti4j.mobile.client.ui.style.Position; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; /** * The text area is a multiline field. * <p> * Both Text Areas and Text Fields can control the buttons displayed in a button * bar above the keyboard when it's visible. */ public class TextArea extends View { public TextArea() { createPeer(); } TextArea(JavaScriptObject obj) { jsObj = obj; } /** * @return Whether or not to convert text within jso area to clickable * links. iOs only. */ public native int getAutoLink() /*-{ var jso = [email protected]::getJsObj()(); return jso.autoLink; }-*/; public native void setAutoLink(int value) /*-{ var jso = [email protected]::getJsObj()(); jso.autoLink = value; }-*/; /** * @return The left padding of the text field */ public native <T> T getPaddingLeft() /*-{ var jso = [email protected]::getJsObj()(); return jso.paddingLeft; }-*/; /** * Sets the left padding * * @param value, the value of the left padding */ public void setPaddingLeft(double value) { UI.get().setSizePropertyAsDouble(jsObj, "paddingLeft", value); } /** * Sets the left padding * * @param value, the value of the left padding */ public void setPaddingLeft(String value) { UI.get().setSizePropertyAsString(jsObj, "paddingLeft", value); } /** * Sets the left padding with the given unit system * * @param value, the value of the left padding * @param unit, the unit system to use */ public void setPaddingLeft(String value, Unit unit) { UI.get().setSizePropertyAsString(jsObj, "paddingLeft", value, unit); } /** * @return The right padding of the text field */ public native <T> T getPaddingRight() /*-{ var jso = [email protected]::getJsObj()(); return jso.paddingRight; }-*/; /** * Sets the right padding. * * @param value, the value of the left padding */ public void setPaddingRight(double value) { UI.get().setSizePropertyAsDouble(jsObj, "paddingRight", value); } /** * Sets the right padding. * * @param value, the value of the left padding */ public void setPaddingRight(String value) { UI.get().setSizePropertyAsString(jsObj, "paddingRight", value); } /** * Sets the right padding with the given unit system * * @param value, the value of the left padding * @param unit, the unit system to be used */ public void setPaddingRight(String value, Unit unit) { UI.get().setSizePropertyAsString(jsObj, "paddingRight", value, unit); } /** * Sets the padding value. The left and right padding will be set * * @param value, the value of the padding */ public void setPadding(double value) { setPaddingLeft(value); setPaddingRight(value); } /** * Sets the padding value. The left and right padding will be set * * @param value, the value of the padding */ public void setPadding(String value) { setPaddingLeft(value); setPaddingRight(value); } /** * Sets the padding value. The left and right padding will be set using the * given unit * * @param value, the value of the padding */ public void setPadding(String value, Unit unit) { setPaddingLeft(value, unit); setPaddingRight(value, unit); } /** * Sets the left and right padding * * @param leftPadding, the left padding * @param rightPadding, the right padding */ public void setPadding(double leftPadding, double rightPadding) { setPaddingLeft(leftPadding); setPaddingRight(rightPadding); } /** * Sets the left and right padding * * @param leftPadding, the left padding * @param rightPadding, the right padding */ public void setPadding(String leftPadding, String rightPadding) { setPaddingLeft(leftPadding); setPaddingRight(rightPadding); } /** * Sets the left and right padding using the given unitsystem * * @param leftPadding, the left padding * @param rightPadding, the right padding * @param unit, the unit system to be used */ public void setPadding(String leftPadding, String rightPadding, Unit unit) { setPaddingLeft(leftPadding, unit); setPaddingRight(rightPadding, unit); } /** * @return The left button view */ public native Button getLeftButton() /*-{ var jso = [email protected]::getJsObj()(); var obj = jso.leftButton; var toReturn = @com.emitrom.ti4j.mobile.client.ui.Button::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj); return toReturn; }-*/; public native void setLeftButton(Button value) /*-{ var jso = [email protected]::getJsObj()(); jso.leftButton = [email protected]::getJsObj()(); }-*/; /** * @return The mode of the left button view */ public native int getLeftButtonMode() /*-{ var jso = [email protected]::getJsObj()(); return jso.leftButtonMode; }-*/; public native void setLeftButtonMode(int value) /*-{ var jso = [email protected]::getJsObj()(); jso.leftButtonMode = value; }-*/; /** * @return The right button view */ public native Button getRightButton() /*-{ var jso = [email protected]::getJsObj()(); var obj = jso.rightButton; var toReturn = @com.emitrom.ti4j.mobile.client.ui.Button::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj); return toReturn; }-*/; public native void setRightButton(Button value) /*-{ var jso = [email protected]::getJsObj()(); jso.rightButton = [email protected]::getJsObj()(); }-*/; /** * @return Boolean that indicates if the value of the field is cleared upon * editing */ public native boolean clearOnEdit() /*-{ var jso = [email protected]::getJsObj()(); return jso.clearOnEdit; }-*/; public native void setClearOnEdit(boolean value) /*-{ var jso = [email protected]::getJsObj()(); jso.clearOnEdit = value; }-*/; public native void setTextAlign(String value) /*-{ var jso = [email protected]::getJsObj()(); jso.textAlign = [email protected]::getJsObj()(); }-*/; public void setTextAlign(Position position) { setTextAlign(position.getValue()); } public native void setFont(Font value) /*-{ var jso = [email protected]::getJsObj()(); jso.font = [email protected]::getJsObj()(); }-*/; /** * set the keyborad type * * @param value, value of the keyboard type */ public native void setKeyboardType(int value) /*-{ var jso = [email protected]::getJsObj()(); jso.keyboardType = value; }-*/; /** * * @return the value of the keyboard type */ public native int getKeyboardType() /*-{ var jso = [email protected]::getJsObj()(); return jso.keyboardType; }-*/; /** * set the returnKey type * * @param value, value of the returnkey type */ public native void setReturnKeyType(int value) /*-{ var jso = [email protected]::getJsObj()(); jso.returnKeyType = value; }-*/; /** * * @return the value of the appearance */ public native int getAppearance() /*-{ var jso = [email protected]::getJsObj()(); return jso.appearance; }-*/; /** * set the appearance value * * @param value, value of the returnkey type */ public native void setAppearance(int value) /*-{ var jso = [email protected]::getJsObj()(); jso.appearance = value; }-*/; /** * sets wheter of not this TextField enables thr return key * * @param value */ public native void setEnableReturnKey(boolean value) /*-{ var jso = [email protected]::getJsObj()(); jso.enableReturnKey = value; }-*/; /** * wheter of not this TextField enables thr return key * * @param value */ public native boolean enableReturnKey() /*-{ var jso = [email protected]::getJsObj()(); return jso.enableReturnKey; }-*/; /** * * @return the value of the returnkey type */ public native int getReturnKeyType() /*-{ var jso = [email protected]::getJsObj()(); return jso.returnKeyType; }-*/; /** * @return One of * {@link com.emitrom.ti4j.mobile.client.ui.UI.TEXT_AUTOCAPITALIZATION_NONE} * , * {@link com.emitrom.ti4j.mobile.client.ui.UI.TEXT_AUTOCAPITALIZATION_WORDS} * , * {@link com.emitrom.ti4j.mobile.client.ui.UI.TEXT_AUTOCAPITALIZATION_SENTENCES} * , or * {@link com.emitrom.ti4j.mobile.client.ui.UI.TEXT_AUTOCAPITALIZATION_ALL} * to indicate how the field should be capitalized during typing. * (only android) * */ public native int getAutocapitalization() /*-{ var jso = [email protected]::getJsObj()(); return jso.autocapitalization; }-*/; public native void setAutocapitalization(int value) /*-{ var jso = [email protected]::getJsObj()(); jso.autocapitalization = value; }-*/; /** * @return Boolean indicating if the field is editable */ public native boolean isEditable() /*-{ var jso = [email protected]::getJsObj()(); return jso.editable; }-*/; public native void setEditable(boolean value) /*-{ var jso = [email protected]::getJsObj()(); jso.editable = value; }-*/; /** * @return Boolean indicating the enabled state of the field */ public native boolean isEnabled() /*-{ var jso = [email protected]::getJsObj()(); return jso.enabled; }-*/; public native void setEnabled(boolean value) /*-{ var jso = [email protected]::getJsObj()(); jso.enabled = value; }-*/; /** * @return Array of toolbar button objects to be used when the keyboard is * displayed */ public ArrayList<Button> getKeyboardToolbar() { ArrayList<Button> buttons = new ArrayList<Button>(); JsArray<JavaScriptObject> values = _getKeyboardToolbar(); for (int i = 0; i < values.length(); i++) { buttons.add(new Button(values.get(i))); } return buttons; } private native JsArray<JavaScriptObject> _getKeyboardToolbar() /*-{ var jso = [email protected]::getJsObj()(); return jso.keyboardToolbar; }-*/; public void setKeyboardToolbar(ArrayList<Button> buttons) { JsArray<JavaScriptObject> values = JsArray.createArray().cast(); for (Button button : buttons) { values.push(button.getJsObj()); } _setKeyboardToolbar(values); } public void setKeyboardToolbar(Button... buttons) { JsArray<JavaScriptObject> values = JsArray.createArray().cast(); for (Button button : buttons) { values.push(button.getJsObj()); } _setKeyboardToolbar(values); } private native void _setKeyboardToolbar(JsArray<JavaScriptObject> value) /*-{ var jso = [email protected]::getJsObj()(); jso.keyboardToolbar = value; }-*/; /** * @return The color of the keyboard toolbar */ public native String getKeyboardToolbarColor() /*-{ var jso = [email protected]::getJsObj()(); return jso.keyboardToolbarColor; }-*/; public native void setKeyboardToolbarColor(String value) /*-{ var jso = [email protected]::getJsObj()(); jso.keyboardToolbarColor = value; }-*/; /** * @return The height of the keyboard toolbar */ public native double getKeyboardToolbarHeight() /*-{ var jso = [email protected]::getJsObj()(); return jso.keyboardToolbarHeight; }-*/; public native void setKeyboardToolbarHeight(double value) /*-{ var jso = [email protected]::getJsObj()(); jso.keyboardToolbarHeight = value; }-*/; /** * @return Boolean to indicate if the return key should be suppressed during * entry */ public native boolean suppressReturn() /*-{ var jso = [email protected]::getJsObj()(); return jso.suppressReturn; }-*/; public native void setSuppressReturn(boolean value) /*-{ var jso = [email protected]::getJsObj()(); jso.suppressReturn = value; }-*/; public native void setSoftKeyboardOnFocus(int value) /*-{ var jso = [email protected]::getJsObj()(); jso.softKeyboardOnFocus = value; }-*/; /** * @return Value of the field */ public native String getValue() /*-{ var jso = [email protected]::getJsObj()(); return jso.value; }-*/; public native void setValue(String value) /*-{ var jso = [email protected]::getJsObj()(); jso.value = value; }-*/; /** * @return True (default) if textarea can be scrolled. * @platforms iphone, ipad */ public native boolean isScrollable() /*-{ var jso = [email protected]::getJsObj()(); return jso.scrollable; }-*/; public native void setScrollable(boolean value) /*-{ var jso = [email protected]::getJsObj()(); jso.scrollable = value; }-*/; /** * Force the field to lose focus */ public native void blur() /*-{ var jso = [email protected]::getJsObj()(); jso.blur(); }-*/; /** * Force the field to gain focus */ public native void focus() /*-{ var jso = [email protected]::getJsObj()(); jso.focus(); }-*/; /** * Return boolean (true) if the field has text */ public native boolean hasText() /*-{ var jso = [email protected]::getJsObj()(); return jso.hasText(); }-*/; public native CallbackRegistration addChangeHandler(TextChangedHandler handler)/*-{ var jso = [email protected]::getJsObj()(); var listener = function(e) { var eventObject = @com.emitrom.ti4j.mobile.client.core.events.ui.text.TextChangedEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.emitrom.ti4j.mobile.client.core.handlers.ui.TextChangedHandler::onChange(Lcom/emitrom/ti4j/mobile/client/core/events/ui/text/TextChangedEvent;)(eventObject); }; var name = @com.emitrom.ti4j.mobile.client.core.events.ui.text.TextChangedEvent::EVENT_NAME; var v = jso.addEventListener(name, listener); var toReturn = @com.emitrom.ti4j.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/emitrom/ti4j/mobile/client/ui/UIObject;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; public native CallbackRegistration addReturnHandler(TextReturnHandler handler)/*-{ var jso = [email protected]::getJsObj()(); var listener = function(e) { var eventObject = @com.emitrom.ti4j.mobile.client.core.events.ui.text.TextReturnEvent::new(Lcom/google/gwt/core/client/JavaScriptObject;)(e); handler.@com.emitrom.ti4j.mobile.client.core.handlers.ui.TextReturnHandler::onReturn(Lcom/emitrom/ti4j/mobile/client/core/events/ui/text/TextReturnEvent;)(eventObject); }; var name = @com.emitrom.ti4j.mobile.client.core.events.ui.text.TextReturnEvent::EVENT_NAME; var v = jso.addEventListener(name, listener); var toReturn = @com.emitrom.ti4j.mobile.client.core.handlers.ui.CallbackRegistration::new(Lcom/emitrom/ti4j/mobile/client/ui/UIObject;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(this,name,listener); return toReturn; }-*/; @Override public void createPeer() { jsObj = UI.createTextArea(); } public static TextArea from(ProxyObject proxy) { return new TextArea(proxy.getJsObj()); } }
package net.ggelardi.flucso; import net.ggelardi.flucso.data.SubscrAllAdapter; import net.ggelardi.flucso.data.SubscrAllAdapter.Scope; import net.ggelardi.flucso.serv.FFAPI.FeedList.SectionItem; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.TabHost; import android.widget.Toast; public class SearchActivity extends BaseActivity { private SubscrAllAdapter feeds; private TabHost tabs; private EditText edtFWhat; private Spinner spFWhere; private ListView lvFFeeds; private RadioButton rbPScop1; private RadioButton rbPScop2; private RadioButton rbPScop3; private RadioButton rbPScop4; private RadioButton rbPScop5; private Spinner spPLists; private EditText edtPUser; private EditText edtPRoom; private EditText edtPWhat; private EditText edtPTitl; private EditText edtPComm; private EditText edtPCmBy; private EditText edtPLkBy; private EditText edtPMinC; private EditText edtPMinL; private OnCheckedChangeListener rbListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); feeds = new SubscrAllAdapter(this); tabs = (TabHost) findViewById(android.R.id.tabhost); edtFWhat = (EditText) findViewById(R.id.edt_srcf_what); spFWhere = (Spinner) findViewById(R.id.sp_srcf_scope); lvFFeeds = (ListView) findViewById(R.id.lv_srcf_feeds); rbPScop1 = (RadioButton) findViewById(R.id.rb_srcp_scp1); rbPScop2 = (RadioButton) findViewById(R.id.rb_srcp_scp2); rbPScop3 = (RadioButton) findViewById(R.id.rb_srcp_scp3); rbPScop4 = (RadioButton) findViewById(R.id.rb_srcp_scp4); rbPScop5 = (RadioButton) findViewById(R.id.rb_srcp_scp5); spPLists = (Spinner) findViewById(R.id.sp_srcp_lists); edtPUser = (EditText) findViewById(R.id.edt_srcp_user); edtPRoom = (EditText) findViewById(R.id.edt_srcp_room); edtPWhat = (EditText) findViewById(R.id.edt_srcp_what); edtPTitl = (EditText) findViewById(R.id.edt_srcp_title); edtPComm = (EditText) findViewById(R.id.edt_srcp_comm); edtPCmBy = (EditText) findViewById(R.id.edt_srcp_comby); edtPLkBy = (EditText) findViewById(R.id.edt_srcp_likby); edtPMinC = (EditText) findViewById(R.id.edt_srcp_minc); edtPMinL = (EditText) findViewById(R.id.edt_srcp_minl); // setup tabs.setup(); tabs.addTab(tabs.newTabSpec("tabF").setContent(R.id.ll_srcf_tab).setIndicator(getString(R.string.search_tabf), getResources().getDrawable(R.drawable.ic_action_group))); tabs.addTab(tabs.newTabSpec("tabP").setContent(R.id.sv_srcp_tab).setIndicator(getString(R.string.search_tabp), getResources().getDrawable(R.drawable.ic_action_storage))); lvFFeeds.setAdapter(feeds); lvFFeeds.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent result = new Intent(); result.putExtra("feed", feeds.getItem(position).id); result.putExtra("name", feeds.getItem(position).name); setResult(RESULT_OK, result); finish(); } }); edtFWhat.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { feeds.getFilter().filter(s); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); spFWhere.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { feeds.setScope(Scope.fromValue(position)).getFilter().filter(edtFWhat.getText().toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); final RadioButton[] scopes = new RadioButton[] { rbPScop1, rbPScop2, rbPScop3, rbPScop4, rbPScop5 }; rbListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) for (RadioButton rb : scopes) if (rb.getId() != buttonView.getId()) rb.setChecked(false); } }; for (RadioButton rb : scopes) { rb.setOnCheckedChangeListener(rbListener); } if (session.getNavigation().lists == null || session.getNavigation().lists.length <= 0) { rbPScop3.setEnabled(false); spPLists.setVisibility(View.GONE); } else { ArrayAdapter<String> spData = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item); for (SectionItem si : session.getNavigation().lists) spData.add(si.name); spData.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spPLists.setAdapter(spData); } Button btnprun = (Button) findViewById(R.id.btn_srcp_exec); btnprun.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String query = edtPWhat.getText().toString(); String tmp = edtPTitl.getText().toString(); if (!TextUtils.isEmpty(tmp)) query += "+intitle:" + tmp; tmp = edtPComm.getText().toString(); if (!TextUtils.isEmpty(tmp)) query += "+incomment:" + tmp; tmp = edtPCmBy.getText().toString(); if (!TextUtils.isEmpty(tmp)) query += "+comment:" + tmp; tmp = edtPLkBy.getText().toString(); if (!TextUtils.isEmpty(tmp)) query += "+like:" + tmp; tmp = edtPMinC.getText().toString(); if (!TextUtils.isEmpty(tmp)) query += "+comments:" + tmp; tmp = edtPMinL.getText().toString(); if (!TextUtils.isEmpty(tmp)) query += "+likes:" + tmp; if (rbPScop2.isChecked()) query += "+friends:" + session.getUsername(); else if (rbPScop3.isChecked()) query += "+list:" + spPLists.getSelectedItem().toString(); else if (rbPScop4.isChecked()) { tmp = edtPUser.getText().toString(); if (TextUtils.isEmpty(tmp)) { Toast.makeText(getApplicationContext(), getString(R.string.search_error), Toast.LENGTH_LONG).show(); return; } query += "+from:" + tmp; } else if (rbPScop5.isChecked()) { tmp = edtPRoom.getText().toString(); if (TextUtils.isEmpty(tmp)) { Toast.makeText(getApplicationContext(), getString(R.string.search_error), Toast.LENGTH_LONG).show(); return; } query += "+group:" + tmp; } Intent result = new Intent(); result.putExtra("query", query); setResult(RESULT_OK, result); finish(); } }); } @Override protected void profileReady() { // nothing here } }
/* * 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.search.aggregations.bucket; import com.carrotsearch.hppc.ObjectIntMap; import com.carrotsearch.hppc.ObjectIntOpenHashMap; import com.carrotsearch.hppc.cursors.ObjectIntCursor; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.geo.GeoHashUtils; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.GeoBoundingBoxFilterBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.geogrid.GeoHashGrid; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.search.aggregations.AggregationBuilders.geohashGrid; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; @ElasticsearchIntegrationTest.SuiteScopeTest public class GeoHashGridTests extends ElasticsearchIntegrationTest { static ObjectIntMap<String> expectedDocCountsForGeoHash = null; static ObjectIntMap<String> multiValuedExpectedDocCountsForGeoHash = null; static int highestPrecisionGeohash = 12; static int numDocs = 100; static String smallestGeoHash = null; private static IndexRequestBuilder indexCity(String index, String name, List<String> latLon) throws Exception { XContentBuilder source = jsonBuilder().startObject().field("city", name); if (latLon != null) { source = source.field("location", latLon); } source = source.endObject(); return client().prepareIndex(index, "type").setSource(source); } private static IndexRequestBuilder indexCity(String index, String name, String latLon) throws Exception { return indexCity(index, name, Arrays.<String>asList(latLon)); } @Override public void setupSuiteScopeCluster() throws Exception { createIndex("idx_unmapped"); assertAcked(prepareCreate("idx") .addMapping("type", "location", "type=geo_point", "city", "type=string,index=not_analyzed")); List<IndexRequestBuilder> cities = new ArrayList<>(); Random random = getRandom(); expectedDocCountsForGeoHash = new ObjectIntOpenHashMap<>(numDocs * 2); for (int i = 0; i < numDocs; i++) { //generate random point double lat = (180d * random.nextDouble()) - 90d; double lng = (360d * random.nextDouble()) - 180d; String randomGeoHash = GeoHashUtils.encode(lat, lng, highestPrecisionGeohash); //Index at the highest resolution cities.add(indexCity("idx", randomGeoHash, lat + ", " + lng)); expectedDocCountsForGeoHash.put(randomGeoHash, expectedDocCountsForGeoHash.getOrDefault(randomGeoHash, 0) + 1); //Update expected doc counts for all resolutions.. for (int precision = highestPrecisionGeohash - 1; precision > 0; precision--) { String hash = GeoHashUtils.encode(lat, lng, precision); if ((smallestGeoHash == null) || (hash.length() < smallestGeoHash.length())) { smallestGeoHash = hash; } expectedDocCountsForGeoHash.put(hash, expectedDocCountsForGeoHash.getOrDefault(hash, 0) + 1); } } indexRandom(true, cities); assertAcked(prepareCreate("multi_valued_idx") .addMapping("type", "location", "type=geo_point", "city", "type=string,index=not_analyzed")); cities = new ArrayList<>(); multiValuedExpectedDocCountsForGeoHash = new ObjectIntOpenHashMap<>(numDocs * 2); for (int i = 0; i < numDocs; i++) { final int numPoints = random.nextInt(4); List<String> points = new ArrayList<>(); // TODO (#8512): this should be a Set, not a List. Currently if a document has two positions that have // the same geo hash, it will increase the doc_count for this geo hash by 2 instead of 1 List<String> geoHashes = new ArrayList<>(); for (int j = 0; j < numPoints; ++j) { double lat = (180d * random.nextDouble()) - 90d; double lng = (360d * random.nextDouble()) - 180d; points.add(lat + "," + lng); // Update expected doc counts for all resolutions.. for (int precision = highestPrecisionGeohash; precision > 0; precision--) { final String geoHash = GeoHashUtils.encode(lat, lng, precision); geoHashes.add(geoHash); } } cities.add(indexCity("multi_valued_idx", Integer.toString(i), points)); for (String hash : geoHashes) { multiValuedExpectedDocCountsForGeoHash.put(hash, multiValuedExpectedDocCountsForGeoHash.getOrDefault(hash, 0) + 1); } } indexRandom(true, cities); ensureSearchable(); } @Test public void simple() throws Exception { for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { SearchResponse response = client().prepareSearch("idx") .addAggregation(geohashGrid("geohashgrid") .field("location") .precision(precision) ) .execute().actionGet(); assertSearchResponse(response); GeoHashGrid geoGrid = response.getAggregations().get("geohashgrid"); for (GeoHashGrid.Bucket cell : geoGrid.getBuckets()) { String geohash = cell.getKey(); long bucketCount = cell.getDocCount(); int expectedBucketCount = expectedDocCountsForGeoHash.get(geohash); assertNotSame(bucketCount, 0); assertEquals("Geohash " + geohash + " has wrong doc count ", expectedBucketCount, bucketCount); } } } @Test public void multivalued() throws Exception { for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { SearchResponse response = client().prepareSearch("multi_valued_idx") .addAggregation(geohashGrid("geohashgrid") .field("location") .precision(precision) ) .execute().actionGet(); assertSearchResponse(response); GeoHashGrid geoGrid = response.getAggregations().get("geohashgrid"); for (GeoHashGrid.Bucket cell : geoGrid.getBuckets()) { String geohash = cell.getKey(); long bucketCount = cell.getDocCount(); int expectedBucketCount = multiValuedExpectedDocCountsForGeoHash.get(geohash); assertNotSame(bucketCount, 0); assertEquals("Geohash " + geohash + " has wrong doc count ", expectedBucketCount, bucketCount); } } } @Test public void filtered() throws Exception { GeoBoundingBoxFilterBuilder bbox = new GeoBoundingBoxFilterBuilder("location"); bbox.topLeft(smallestGeoHash).bottomRight(smallestGeoHash).filterName("bbox"); for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { SearchResponse response = client().prepareSearch("idx") .addAggregation( AggregationBuilders.filter("filtered").filter(bbox) .subAggregation( geohashGrid("geohashgrid") .field("location") .precision(precision) ) ) .execute().actionGet(); assertSearchResponse(response); Filter filter = response.getAggregations().get("filtered"); GeoHashGrid geoGrid = filter.getAggregations().get("geohashgrid"); for (GeoHashGrid.Bucket cell : geoGrid.getBuckets()) { String geohash = cell.getKey(); long bucketCount = cell.getDocCount(); int expectedBucketCount = expectedDocCountsForGeoHash.get(geohash); assertNotSame(bucketCount, 0); assertTrue("Buckets must be filtered", geohash.startsWith(smallestGeoHash)); assertEquals("Geohash " + geohash + " has wrong doc count ", expectedBucketCount, bucketCount); } } } @Test public void unmapped() throws Exception { for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { SearchResponse response = client().prepareSearch("idx_unmapped") .addAggregation(geohashGrid("geohashgrid") .field("location") .precision(precision) ) .execute().actionGet(); assertSearchResponse(response); GeoHashGrid geoGrid = response.getAggregations().get("geohashgrid"); assertThat(geoGrid.getBuckets().size(), equalTo(0)); } } @Test public void partiallyUnmapped() throws Exception { for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { SearchResponse response = client().prepareSearch("idx", "idx_unmapped") .addAggregation(geohashGrid("geohashgrid") .field("location") .precision(precision) ) .execute().actionGet(); assertSearchResponse(response); GeoHashGrid geoGrid = response.getAggregations().get("geohashgrid"); for (GeoHashGrid.Bucket cell : geoGrid.getBuckets()) { String geohash = cell.getKey(); long bucketCount = cell.getDocCount(); int expectedBucketCount = expectedDocCountsForGeoHash.get(geohash); assertNotSame(bucketCount, 0); assertEquals("Geohash " + geohash + " has wrong doc count ", expectedBucketCount, bucketCount); } } } @Test public void testTopMatch() throws Exception { for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { SearchResponse response = client().prepareSearch("idx") .addAggregation(geohashGrid("geohashgrid") .field("location") .size(1) .shardSize(100) .precision(precision) ) .execute().actionGet(); assertSearchResponse(response); GeoHashGrid geoGrid = response.getAggregations().get("geohashgrid"); //Check we only have one bucket with the best match for that resolution assertThat(geoGrid.getBuckets().size(), equalTo(1)); for (GeoHashGrid.Bucket cell : geoGrid.getBuckets()) { String geohash = cell.getKey(); long bucketCount = cell.getDocCount(); int expectedBucketCount = 0; for (ObjectIntCursor<String> cursor : expectedDocCountsForGeoHash) { if (cursor.key.length() == precision) { expectedBucketCount = Math.max(expectedBucketCount, cursor.value); } } assertNotSame(bucketCount, 0); assertEquals("Geohash " + geohash + " has wrong doc count ", expectedBucketCount, bucketCount); } } } @Test // making sure this doesn't runs into an OOME public void sizeIsZero() { for (int precision = 1; precision <= highestPrecisionGeohash; precision++) { final int size = randomBoolean() ? 0 : randomIntBetween(1, Integer.MAX_VALUE); final int shardSize = randomBoolean() ? -1 : 0; SearchResponse response = client().prepareSearch("idx") .addAggregation(geohashGrid("geohashgrid") .field("location") .size(size) .shardSize(shardSize) .precision(precision) ) .execute().actionGet(); assertSearchResponse(response); GeoHashGrid geoGrid = response.getAggregations().get("geohashgrid"); assertThat(geoGrid.getBuckets().size(), greaterThanOrEqualTo(1)); } } }
/* * 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.commons.lang3.text; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.nio.CharBuffer; import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; /** * Unit tests for {@link org.apache.commons.lang3.text.StrBuilder}. */ @Deprecated public class StrBuilderTest { //----------------------------------------------------------------------- @Test public void testConstructors() { final StrBuilder sb0 = new StrBuilder(); assertEquals(32, sb0.capacity()); assertEquals(0, sb0.length()); assertEquals(0, sb0.size()); final StrBuilder sb1 = new StrBuilder(32); assertEquals(32, sb1.capacity()); assertEquals(0, sb1.length()); assertEquals(0, sb1.size()); final StrBuilder sb2 = new StrBuilder(0); assertEquals(32, sb2.capacity()); assertEquals(0, sb2.length()); assertEquals(0, sb2.size()); final StrBuilder sb3 = new StrBuilder(-1); assertEquals(32, sb3.capacity()); assertEquals(0, sb3.length()); assertEquals(0, sb3.size()); final StrBuilder sb4 = new StrBuilder(1); assertEquals(1, sb4.capacity()); assertEquals(0, sb4.length()); assertEquals(0, sb4.size()); final StrBuilder sb5 = new StrBuilder(null); assertEquals(32, sb5.capacity()); assertEquals(0, sb5.length()); assertEquals(0, sb5.size()); final StrBuilder sb6 = new StrBuilder(""); assertEquals(32, sb6.capacity()); assertEquals(0, sb6.length()); assertEquals(0, sb6.size()); final StrBuilder sb7 = new StrBuilder("foo"); assertEquals(35, sb7.capacity()); assertEquals(3, sb7.length()); assertEquals(3, sb7.size()); } //----------------------------------------------------------------------- @Test public void testChaining() { final StrBuilder sb = new StrBuilder(); assertSame(sb, sb.setNewLineText(null)); assertSame(sb, sb.setNullText(null)); assertSame(sb, sb.setLength(1)); assertSame(sb, sb.setCharAt(0, 'a')); assertSame(sb, sb.ensureCapacity(0)); assertSame(sb, sb.minimizeCapacity()); assertSame(sb, sb.clear()); assertSame(sb, sb.reverse()); assertSame(sb, sb.trim()); } //----------------------------------------------------------------------- @Test public void testReadFromReader() throws Exception { String s = ""; for (int i = 0; i < 100; ++i) { final StrBuilder sb = new StrBuilder(); final int len = sb.readFrom(new StringReader(s)); assertEquals(s.length(), len); assertEquals(s, sb.toString()); s += Integer.toString(i); } } @Test public void testReadFromReaderAppendsToEnd() throws Exception { final StrBuilder sb = new StrBuilder("Test"); sb.readFrom(new StringReader(" 123")); assertEquals("Test 123", sb.toString()); } @Test public void testReadFromCharBuffer() throws Exception { String s = ""; for (int i = 0; i < 100; ++i) { final StrBuilder sb = new StrBuilder(); final int len = sb.readFrom(CharBuffer.wrap(s)); assertEquals(s.length(), len); assertEquals(s, sb.toString()); s += Integer.toString(i); } } @Test public void testReadFromCharBufferAppendsToEnd() throws Exception { final StrBuilder sb = new StrBuilder("Test"); sb.readFrom(CharBuffer.wrap(" 123")); assertEquals("Test 123", sb.toString()); } @Test public void testReadFromReadable() throws Exception { String s = ""; for (int i = 0; i < 100; ++i) { final StrBuilder sb = new StrBuilder(); final int len = sb.readFrom(new MockReadable(s)); assertEquals(s.length(), len); assertEquals(s, sb.toString()); s += Integer.toString(i); } } @Test public void testReadFromReadableAppendsToEnd() throws Exception { final StrBuilder sb = new StrBuilder("Test"); sb.readFrom(new MockReadable(" 123")); assertEquals("Test 123", sb.toString()); } private static class MockReadable implements Readable { private final CharBuffer src; MockReadable(final String src) { this.src = CharBuffer.wrap(src); } @Override public int read(final CharBuffer cb) throws IOException { return src.read(cb); } } //----------------------------------------------------------------------- @Test public void testGetSetNewLineText() { final StrBuilder sb = new StrBuilder(); assertNull(sb.getNewLineText()); sb.setNewLineText("#"); assertEquals("#", sb.getNewLineText()); sb.setNewLineText(""); assertEquals("", sb.getNewLineText()); sb.setNewLineText(null); assertNull(sb.getNewLineText()); } //----------------------------------------------------------------------- @Test public void testGetSetNullText() { final StrBuilder sb = new StrBuilder(); assertNull(sb.getNullText()); sb.setNullText("null"); assertEquals("null", sb.getNullText()); sb.setNullText(""); assertNull(sb.getNullText()); sb.setNullText("NULL"); assertEquals("NULL", sb.getNullText()); sb.setNullText(null); assertNull(sb.getNullText()); } //----------------------------------------------------------------------- @Test public void testCapacityAndLength() { final StrBuilder sb = new StrBuilder(); assertEquals(32, sb.capacity()); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.minimizeCapacity(); assertEquals(0, sb.capacity()); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.ensureCapacity(32); assertTrue(sb.capacity() >= 32); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.append("foo"); assertTrue(sb.capacity() >= 32); assertEquals(3, sb.length()); assertEquals(3, sb.size()); assertTrue(sb.isEmpty() == false); sb.clear(); assertTrue(sb.capacity() >= 32); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.append("123456789012345678901234567890123"); assertTrue(sb.capacity() > 32); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); sb.ensureCapacity(16); assertTrue(sb.capacity() > 16); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); sb.minimizeCapacity(); assertEquals(33, sb.capacity()); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); try { sb.setLength(-1); fail("setLength(-1) expected StringIndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } sb.setLength(33); assertEquals(33, sb.capacity()); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); sb.setLength(16); assertTrue(sb.capacity() >= 16); assertEquals(16, sb.length()); assertEquals(16, sb.size()); assertEquals("1234567890123456", sb.toString()); assertTrue(sb.isEmpty() == false); sb.setLength(32); assertTrue(sb.capacity() >= 32); assertEquals(32, sb.length()); assertEquals(32, sb.size()); assertEquals("1234567890123456\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sb.toString()); assertTrue(sb.isEmpty() == false); sb.setLength(0); assertTrue(sb.capacity() >= 32); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); } //----------------------------------------------------------------------- @Test public void testLength() { final StrBuilder sb = new StrBuilder(); assertEquals(0, sb.length()); sb.append("Hello"); assertEquals(5, sb.length()); } @Test public void testSetLength() { final StrBuilder sb = new StrBuilder(); sb.append("Hello"); sb.setLength(2); // shorten assertEquals("He", sb.toString()); sb.setLength(2); // no change assertEquals("He", sb.toString()); sb.setLength(3); // lengthen assertEquals("He\0", sb.toString()); try { sb.setLength(-1); fail("setLength(-1) expected StringIndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } } //----------------------------------------------------------------------- @Test public void testCapacity() { final StrBuilder sb = new StrBuilder(); assertEquals(sb.buffer.length, sb.capacity()); sb.append("HelloWorldHelloWorldHelloWorldHelloWorld"); assertEquals(sb.buffer.length, sb.capacity()); } @Test public void testEnsureCapacity() { final StrBuilder sb = new StrBuilder(); sb.ensureCapacity(2); assertTrue(sb.capacity() >= 2); sb.ensureCapacity(-1); assertTrue(sb.capacity() >= 0); sb.append("HelloWorld"); sb.ensureCapacity(40); assertTrue(sb.capacity() >= 40); } @Test public void testMinimizeCapacity() { final StrBuilder sb = new StrBuilder(); sb.minimizeCapacity(); assertEquals(0, sb.capacity()); sb.append("HelloWorld"); sb.minimizeCapacity(); assertEquals(10, sb.capacity()); } //----------------------------------------------------------------------- @Test public void testSize() { final StrBuilder sb = new StrBuilder(); assertEquals(0, sb.size()); sb.append("Hello"); assertEquals(5, sb.size()); } @Test public void testIsEmpty() { final StrBuilder sb = new StrBuilder(); assertTrue(sb.isEmpty()); sb.append("Hello"); assertFalse(sb.isEmpty()); sb.clear(); assertTrue(sb.isEmpty()); } @Test public void testClear() { final StrBuilder sb = new StrBuilder(); sb.append("Hello"); sb.clear(); assertEquals(0, sb.length()); assertTrue(sb.buffer.length >= 5); } //----------------------------------------------------------------------- @Test public void testCharAt() { final StrBuilder sb = new StrBuilder(); try { sb.charAt(0); fail("charAt(0) expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } try { sb.charAt(-1); fail("charAt(-1) expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } sb.append("foo"); assertEquals('f', sb.charAt(0)); assertEquals('o', sb.charAt(1)); assertEquals('o', sb.charAt(2)); try { sb.charAt(-1); fail("charAt(-1) expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } try { sb.charAt(3); fail("charAt(3) expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } } //----------------------------------------------------------------------- @Test public void testSetCharAt() { final StrBuilder sb = new StrBuilder(); try { sb.setCharAt(0, 'f'); fail("setCharAt(0,) expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } try { sb.setCharAt(-1, 'f'); fail("setCharAt(-1,) expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } sb.append("foo"); sb.setCharAt(0, 'b'); sb.setCharAt(1, 'a'); sb.setCharAt(2, 'r'); try { sb.setCharAt(3, '!'); fail("setCharAt(3,) expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // expected } assertEquals("bar", sb.toString()); } //----------------------------------------------------------------------- @Test public void testDeleteCharAt() { final StrBuilder sb = new StrBuilder("abc"); sb.deleteCharAt(0); assertEquals("bc", sb.toString()); try { sb.deleteCharAt(1000); fail("Expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) {} } //----------------------------------------------------------------------- @Test public void testToCharArray() { final StrBuilder sb = new StrBuilder(); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, sb.toCharArray()); char[] a = sb.toCharArray(); assertNotNull("toCharArray() result is null", a); assertEquals("toCharArray() result is too large", 0, a.length); sb.append("junit"); a = sb.toCharArray(); assertEquals("toCharArray() result incorrect length", 5, a.length); assertTrue("toCharArray() result does not match", Arrays.equals("junit".toCharArray(), a)); } @Test public void testToCharArrayIntInt() { final StrBuilder sb = new StrBuilder(); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, sb.toCharArray(0, 0)); sb.append("junit"); char[] a = sb.toCharArray(0, 20); // too large test assertEquals("toCharArray(int,int) result incorrect length", 5, a.length); assertTrue("toCharArray(int,int) result does not match", Arrays.equals("junit".toCharArray(), a)); a = sb.toCharArray(0, 4); assertEquals("toCharArray(int,int) result incorrect length", 4, a.length); assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a)); a = sb.toCharArray(0, 4); assertEquals("toCharArray(int,int) result incorrect length", 4, a.length); assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a)); a = sb.toCharArray(0, 1); assertNotNull("toCharArray(int,int) result is null", a); try { sb.toCharArray(-1, 5); fail("no string index out of bound on -1"); } catch (final IndexOutOfBoundsException e) { } try { sb.toCharArray(6, 5); fail("no string index out of bound on -1"); } catch (final IndexOutOfBoundsException e) { } } @Test public void testGetChars ( ) { final StrBuilder sb = new StrBuilder(); char[] input = new char[10]; char[] a = sb.getChars(input); assertSame (input, a); assertTrue(Arrays.equals(new char[10], a)); sb.append("junit"); a = sb.getChars(input); assertSame(input, a); assertTrue(Arrays.equals(new char[] {'j','u','n','i','t',0,0,0,0,0},a)); a = sb.getChars(null); assertNotSame(input,a); assertEquals(5,a.length); assertTrue(Arrays.equals("junit".toCharArray(),a)); input = new char[5]; a = sb.getChars(input); assertSame(input, a); input = new char[4]; a = sb.getChars(input); assertNotSame(input, a); } @Test public void testGetCharsIntIntCharArrayInt( ) { final StrBuilder sb = new StrBuilder(); sb.append("junit"); char[] a = new char[5]; sb.getChars(0,5,a,0); assertTrue(Arrays.equals(new char[] {'j','u','n','i','t'},a)); a = new char[5]; sb.getChars(0,2,a,3); assertTrue(Arrays.equals(new char[] {0,0,0,'j','u'},a)); try { sb.getChars(-1,0,a,0); fail("no exception"); } catch (final IndexOutOfBoundsException e) { } try { sb.getChars(0,-1,a,0); fail("no exception"); } catch (final IndexOutOfBoundsException e) { } try { sb.getChars(0,20,a,0); fail("no exception"); } catch (final IndexOutOfBoundsException e) { } try { sb.getChars(4,2,a,0); fail("no exception"); } catch (final IndexOutOfBoundsException e) { } } //----------------------------------------------------------------------- @Test public void testDeleteIntInt() { StrBuilder sb = new StrBuilder("abc"); sb.delete(0, 1); assertEquals("bc", sb.toString()); sb.delete(1, 2); assertEquals("b", sb.toString()); sb.delete(0, 1); assertEquals("", sb.toString()); sb.delete(0, 1000); assertEquals("", sb.toString()); try { sb.delete(1, 2); fail("Expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) {} try { sb.delete(-1, 1); fail("Expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) {} sb = new StrBuilder("anything"); try { sb.delete(2, 1); fail("Expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) {} } //----------------------------------------------------------------------- @Test public void testDeleteAll_char() { StrBuilder sb = new StrBuilder("abcbccba"); sb.deleteAll('X'); assertEquals("abcbccba", sb.toString()); sb.deleteAll('a'); assertEquals("bcbccb", sb.toString()); sb.deleteAll('c'); assertEquals("bbb", sb.toString()); sb.deleteAll('b'); assertEquals("", sb.toString()); sb = new StrBuilder(""); sb.deleteAll('b'); assertEquals("", sb.toString()); } @Test public void testDeleteFirst_char() { StrBuilder sb = new StrBuilder("abcba"); sb.deleteFirst('X'); assertEquals("abcba", sb.toString()); sb.deleteFirst('a'); assertEquals("bcba", sb.toString()); sb.deleteFirst('c'); assertEquals("bba", sb.toString()); sb.deleteFirst('b'); assertEquals("ba", sb.toString()); sb = new StrBuilder(""); sb.deleteFirst('b'); assertEquals("", sb.toString()); } // ----------------------------------------------------------------------- @Test public void testDeleteAll_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.deleteAll((String) null); assertEquals("abcbccba", sb.toString()); sb.deleteAll(""); assertEquals("abcbccba", sb.toString()); sb.deleteAll("X"); assertEquals("abcbccba", sb.toString()); sb.deleteAll("a"); assertEquals("bcbccb", sb.toString()); sb.deleteAll("c"); assertEquals("bbb", sb.toString()); sb.deleteAll("b"); assertEquals("", sb.toString()); sb = new StrBuilder("abcbccba"); sb.deleteAll("bc"); assertEquals("acba", sb.toString()); sb = new StrBuilder(""); sb.deleteAll("bc"); assertEquals("", sb.toString()); } @Test public void testDeleteFirst_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.deleteFirst((String) null); assertEquals("abcbccba", sb.toString()); sb.deleteFirst(""); assertEquals("abcbccba", sb.toString()); sb.deleteFirst("X"); assertEquals("abcbccba", sb.toString()); sb.deleteFirst("a"); assertEquals("bcbccba", sb.toString()); sb.deleteFirst("c"); assertEquals("bbccba", sb.toString()); sb.deleteFirst("b"); assertEquals("bccba", sb.toString()); sb = new StrBuilder("abcbccba"); sb.deleteFirst("bc"); assertEquals("abccba", sb.toString()); sb = new StrBuilder(""); sb.deleteFirst("bc"); assertEquals("", sb.toString()); } // ----------------------------------------------------------------------- @Test public void testDeleteAll_StrMatcher() { StrBuilder sb = new StrBuilder("A0xA1A2yA3"); sb.deleteAll((StrMatcher) null); assertEquals("A0xA1A2yA3", sb.toString()); sb.deleteAll(A_NUMBER_MATCHER); assertEquals("xy", sb.toString()); sb = new StrBuilder("Ax1"); sb.deleteAll(A_NUMBER_MATCHER); assertEquals("Ax1", sb.toString()); sb = new StrBuilder(""); sb.deleteAll(A_NUMBER_MATCHER); assertEquals("", sb.toString()); } @Test public void testDeleteFirst_StrMatcher() { StrBuilder sb = new StrBuilder("A0xA1A2yA3"); sb.deleteFirst((StrMatcher) null); assertEquals("A0xA1A2yA3", sb.toString()); sb.deleteFirst(A_NUMBER_MATCHER); assertEquals("xA1A2yA3", sb.toString()); sb = new StrBuilder("Ax1"); sb.deleteFirst(A_NUMBER_MATCHER); assertEquals("Ax1", sb.toString()); sb = new StrBuilder(""); sb.deleteFirst(A_NUMBER_MATCHER); assertEquals("", sb.toString()); } // ----------------------------------------------------------------------- @Test public void testReplace_int_int_String() { StrBuilder sb = new StrBuilder("abc"); sb.replace(0, 1, "d"); assertEquals("dbc", sb.toString()); sb.replace(0, 1, "aaa"); assertEquals("aaabc", sb.toString()); sb.replace(0, 3, ""); assertEquals("bc", sb.toString()); sb.replace(1, 2, null); assertEquals("b", sb.toString()); sb.replace(1, 1000, "text"); assertEquals("btext", sb.toString()); sb.replace(0, 1000, "text"); assertEquals("text", sb.toString()); sb = new StrBuilder("atext"); sb.replace(1, 1, "ny"); assertEquals("anytext", sb.toString()); try { sb.replace(2, 1, "anything"); fail("Expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) {} sb = new StrBuilder(); try { sb.replace(1, 2, "anything"); fail("Expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) {} try { sb.replace(-1, 1, "anything"); fail("Expected IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) {} } //----------------------------------------------------------------------- @Test public void testReplaceAll_char_char() { final StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceAll('x', 'y'); assertEquals("abcbccba", sb.toString()); sb.replaceAll('a', 'd'); assertEquals("dbcbccbd", sb.toString()); sb.replaceAll('b', 'e'); assertEquals("dececced", sb.toString()); sb.replaceAll('c', 'f'); assertEquals("defeffed", sb.toString()); sb.replaceAll('d', 'd'); assertEquals("defeffed", sb.toString()); } //----------------------------------------------------------------------- @Test public void testReplaceFirst_char_char() { final StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceFirst('x', 'y'); assertEquals("abcbccba", sb.toString()); sb.replaceFirst('a', 'd'); assertEquals("dbcbccba", sb.toString()); sb.replaceFirst('b', 'e'); assertEquals("decbccba", sb.toString()); sb.replaceFirst('c', 'f'); assertEquals("defbccba", sb.toString()); sb.replaceFirst('d', 'd'); assertEquals("defbccba", sb.toString()); } //----------------------------------------------------------------------- @Test public void testReplaceAll_String_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceAll((String) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceAll((String) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll("", null); assertEquals("abcbccba", sb.toString()); sb.replaceAll("", "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll("x", "y"); assertEquals("abcbccba", sb.toString()); sb.replaceAll("a", "d"); assertEquals("dbcbccbd", sb.toString()); sb.replaceAll("d", null); assertEquals("bcbccb", sb.toString()); sb.replaceAll("cb", "-"); assertEquals("b-c-", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceAll("b", "xbx"); assertEquals("axbxcxbxa", sb.toString()); sb = new StrBuilder("bb"); sb.replaceAll("b", "xbx"); assertEquals("xbxxbx", sb.toString()); } @Test public void testReplaceFirst_String_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceFirst((String) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst((String) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("", null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("", "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("x", "y"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("a", "d"); assertEquals("dbcbccba", sb.toString()); sb.replaceFirst("d", null); assertEquals("bcbccba", sb.toString()); sb.replaceFirst("cb", "-"); assertEquals("b-ccba", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceFirst("b", "xbx"); assertEquals("axbxcba", sb.toString()); sb = new StrBuilder("bb"); sb.replaceFirst("b", "xbx"); assertEquals("xbxb", sb.toString()); } //----------------------------------------------------------------------- @Test public void testReplaceAll_StrMatcher_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceAll((StrMatcher) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceAll((StrMatcher) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.noneMatcher(), null); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.noneMatcher(), "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.charMatcher('x'), "y"); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.charMatcher('a'), "d"); assertEquals("dbcbccbd", sb.toString()); sb.replaceAll(StrMatcher.charMatcher('d'), null); assertEquals("bcbccb", sb.toString()); sb.replaceAll(StrMatcher.stringMatcher("cb"), "-"); assertEquals("b-c-", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceAll(StrMatcher.charMatcher('b'), "xbx"); assertEquals("axbxcxbxa", sb.toString()); sb = new StrBuilder("bb"); sb.replaceAll(StrMatcher.charMatcher('b'), "xbx"); assertEquals("xbxxbx", sb.toString()); sb = new StrBuilder("A1-A2A3-A4"); sb.replaceAll(A_NUMBER_MATCHER, "***"); assertEquals("***-******-***", sb.toString()); sb = new StrBuilder("Dear X, hello X."); sb.replaceAll(StrMatcher.stringMatcher("X"), "012345678901234567"); assertEquals("Dear 012345678901234567, hello 012345678901234567.", sb.toString()); } @Test public void testReplaceFirst_StrMatcher_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceFirst((StrMatcher) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst((StrMatcher) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.noneMatcher(), null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.noneMatcher(), "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.charMatcher('x'), "y"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.charMatcher('a'), "d"); assertEquals("dbcbccba", sb.toString()); sb.replaceFirst(StrMatcher.charMatcher('d'), null); assertEquals("bcbccba", sb.toString()); sb.replaceFirst(StrMatcher.stringMatcher("cb"), "-"); assertEquals("b-ccba", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceFirst(StrMatcher.charMatcher('b'), "xbx"); assertEquals("axbxcba", sb.toString()); sb = new StrBuilder("bb"); sb.replaceFirst(StrMatcher.charMatcher('b'), "xbx"); assertEquals("xbxb", sb.toString()); sb = new StrBuilder("A1-A2A3-A4"); sb.replaceFirst(A_NUMBER_MATCHER, "***"); assertEquals("***-A2A3-A4", sb.toString()); } //----------------------------------------------------------------------- @Test public void testReplace_StrMatcher_String_int_int_int_VaryMatcher() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replace(null, "x", 0, sb.length(), -1); assertEquals("abcbccba", sb.toString()); sb.replace(StrMatcher.charMatcher('a'), "x", 0, sb.length(), -1); assertEquals("xbcbccbx", sb.toString()); sb.replace(StrMatcher.stringMatcher("cb"), "x", 0, sb.length(), -1); assertEquals("xbxcxx", sb.toString()); sb = new StrBuilder("A1-A2A3-A4"); sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1); assertEquals("***-******-***", sb.toString()); sb = new StrBuilder(); sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1); assertEquals("", sb.toString()); } @Test public void testReplace_StrMatcher_String_int_int_int_VaryReplace() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "cb", 0, sb.length(), -1); assertEquals("abcbccba", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "-", 0, sb.length(), -1); assertEquals("ab-c-a", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "+++", 0, sb.length(), -1); assertEquals("ab+++c+++a", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "", 0, sb.length(), -1); assertEquals("abca", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), null, 0, sb.length(), -1); assertEquals("abca", sb.toString()); } @Test public void testReplace_StrMatcher_String_int_int_int_VaryStartIndex() { StrBuilder sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, sb.length(), -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 1, sb.length(), -1); assertEquals("aax--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, sb.length(), -1); assertEquals("aax--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 3, sb.length(), -1); assertEquals("aax--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 4, sb.length(), -1); assertEquals("aaxa-ay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 5, sb.length(), -1); assertEquals("aaxaa-y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 6, sb.length(), -1); assertEquals("aaxaaaay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 7, sb.length(), -1); assertEquals("aaxaaaay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 8, sb.length(), -1); assertEquals("aaxaaaay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 9, sb.length(), -1); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 10, sb.length(), -1); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); try { sb.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb.length(), -1); fail(); } catch (final IndexOutOfBoundsException ex) {} assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); try { sb.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb.length(), -1); fail(); } catch (final IndexOutOfBoundsException ex) {} assertEquals("aaxaaaayaa", sb.toString()); } @Test public void testReplace_StrMatcher_String_int_int_int_VaryEndIndex() { StrBuilder sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 0, -1); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 2, -1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 3, -1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 4, -1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 5, -1); assertEquals("-x-aayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 6, -1); assertEquals("-x-aayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 7, -1); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 8, -1); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 9, -1); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 1000, -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); try { sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1); fail(); } catch (final IndexOutOfBoundsException ex) {} assertEquals("aaxaaaayaa", sb.toString()); } @Test public void testReplace_StrMatcher_String_int_int_int_VaryCount() { StrBuilder sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 0); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 2); assertEquals("-x-aayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 3); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 4); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 5); assertEquals("-x--y-", sb.toString()); } //----------------------------------------------------------------------- @Test public void testReverse() { final StrBuilder sb = new StrBuilder(); assertEquals("", sb.reverse().toString()); sb.clear().append(true); assertEquals("eurt", sb.reverse().toString()); assertEquals("true", sb.reverse().toString()); } //----------------------------------------------------------------------- @Test public void testTrim() { final StrBuilder sb = new StrBuilder(); assertEquals("", sb.reverse().toString()); sb.clear().append(" \u0000 "); assertEquals("", sb.trim().toString()); sb.clear().append(" \u0000 a b c"); assertEquals("a b c", sb.trim().toString()); sb.clear().append("a b c \u0000 "); assertEquals("a b c", sb.trim().toString()); sb.clear().append(" \u0000 a b c \u0000 "); assertEquals("a b c", sb.trim().toString()); sb.clear().append("a b c"); assertEquals("a b c", sb.trim().toString()); } //----------------------------------------------------------------------- @Test public void testStartsWith() { final StrBuilder sb = new StrBuilder(); assertFalse(sb.startsWith("a")); assertFalse(sb.startsWith(null)); assertTrue(sb.startsWith("")); sb.append("abc"); assertTrue(sb.startsWith("a")); assertTrue(sb.startsWith("ab")); assertTrue(sb.startsWith("abc")); assertFalse(sb.startsWith("cba")); } @Test public void testEndsWith() { final StrBuilder sb = new StrBuilder(); assertFalse(sb.endsWith("a")); assertFalse(sb.endsWith("c")); assertTrue(sb.endsWith("")); assertFalse(sb.endsWith(null)); sb.append("abc"); assertTrue(sb.endsWith("c")); assertTrue(sb.endsWith("bc")); assertTrue(sb.endsWith("abc")); assertFalse(sb.endsWith("cba")); assertFalse(sb.endsWith("abcd")); assertFalse(sb.endsWith(" abc")); assertFalse(sb.endsWith("abc ")); } //----------------------------------------------------------------------- @Test public void testSubSequenceIntInt() { final StrBuilder sb = new StrBuilder ("hello goodbye"); // Start index is negative try { sb.subSequence(-1, 5); fail(); } catch (final IndexOutOfBoundsException e) {} // End index is negative try { sb.subSequence(2, -1); fail(); } catch (final IndexOutOfBoundsException e) {} // End index greater than length() try { sb.subSequence(2, sb.length() + 1); fail(); } catch (final IndexOutOfBoundsException e) {} // Start index greater then end index try { sb.subSequence(3, 2); fail(); } catch (final IndexOutOfBoundsException e) {} // Normal cases assertEquals ("hello", sb.subSequence(0, 5)); assertEquals ("hello goodbye".subSequence(0, 6), sb.subSequence(0, 6)); assertEquals ("goodbye", sb.subSequence(6, 13)); assertEquals ("hello goodbye".subSequence(6,13), sb.subSequence(6, 13)); } @Test public void testSubstringInt() { final StrBuilder sb = new StrBuilder ("hello goodbye"); assertEquals ("goodbye", sb.substring(6)); assertEquals ("hello goodbye".substring(6), sb.substring(6)); assertEquals ("hello goodbye", sb.substring(0)); assertEquals ("hello goodbye".substring(0), sb.substring(0)); try { sb.substring(-1); fail (); } catch (final IndexOutOfBoundsException e) {} try { sb.substring(15); fail (); } catch (final IndexOutOfBoundsException e) {} } @Test public void testSubstringIntInt() { final StrBuilder sb = new StrBuilder ("hello goodbye"); assertEquals ("hello", sb.substring(0, 5)); assertEquals ("hello goodbye".substring(0, 6), sb.substring(0, 6)); assertEquals ("goodbye", sb.substring(6, 13)); assertEquals ("hello goodbye".substring(6,13), sb.substring(6, 13)); assertEquals ("goodbye", sb.substring(6, 20)); try { sb.substring(-1, 5); fail(); } catch (final IndexOutOfBoundsException e) {} try { sb.substring(15, 20); fail(); } catch (final IndexOutOfBoundsException e) {} } // ----------------------------------------------------------------------- @Test public void testMidString() { final StrBuilder sb = new StrBuilder("hello goodbye hello"); assertEquals("goodbye", sb.midString(6, 7)); assertEquals("hello", sb.midString(0, 5)); assertEquals("hello", sb.midString(-5, 5)); assertEquals("", sb.midString(0, -1)); assertEquals("", sb.midString(20, 2)); assertEquals("hello", sb.midString(14, 22)); } @Test public void testRightString() { final StrBuilder sb = new StrBuilder("left right"); assertEquals("right", sb.rightString(5)); assertEquals("", sb.rightString(0)); assertEquals("", sb.rightString(-5)); assertEquals("left right", sb.rightString(15)); } @Test public void testLeftString() { final StrBuilder sb = new StrBuilder("left right"); assertEquals("left", sb.leftString(4)); assertEquals("", sb.leftString(0)); assertEquals("", sb.leftString(-5)); assertEquals("left right", sb.leftString(15)); } // ----------------------------------------------------------------------- @Test public void testContains_char() { final StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz"); assertTrue(sb.contains('a')); assertTrue(sb.contains('o')); assertTrue(sb.contains('z')); assertFalse(sb.contains('1')); } @Test public void testContains_String() { final StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz"); assertTrue(sb.contains("a")); assertTrue(sb.contains("pq")); assertTrue(sb.contains("z")); assertFalse(sb.contains("zyx")); assertFalse(sb.contains((String) null)); } @Test public void testContains_StrMatcher() { StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz"); assertTrue(sb.contains(StrMatcher.charMatcher('a'))); assertTrue(sb.contains(StrMatcher.stringMatcher("pq"))); assertTrue(sb.contains(StrMatcher.charMatcher('z'))); assertFalse(sb.contains(StrMatcher.stringMatcher("zy"))); assertFalse(sb.contains((StrMatcher) null)); sb = new StrBuilder(); assertFalse(sb.contains(A_NUMBER_MATCHER)); sb.append("B A1 C"); assertTrue(sb.contains(A_NUMBER_MATCHER)); } // ----------------------------------------------------------------------- @Test public void testIndexOf_char() { final StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf('a')); // should work like String#indexOf assertEquals("abab".indexOf('a'), sb.indexOf('a')); assertEquals(1, sb.indexOf('b')); assertEquals("abab".indexOf('b'), sb.indexOf('b')); assertEquals(-1, sb.indexOf('z')); } @Test public void testIndexOf_char_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf('a', -1)); assertEquals(0, sb.indexOf('a', 0)); assertEquals(2, sb.indexOf('a', 1)); assertEquals(-1, sb.indexOf('a', 4)); assertEquals(-1, sb.indexOf('a', 5)); // should work like String#indexOf assertEquals("abab".indexOf('a', 1), sb.indexOf('a', 1)); assertEquals(3, sb.indexOf('b', 2)); assertEquals("abab".indexOf('b', 2), sb.indexOf('b', 2)); assertEquals(-1, sb.indexOf('z', 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.indexOf('z', 0)); assertEquals(-1, sb.indexOf('z', 3)); } @Test public void testLastIndexOf_char() { final StrBuilder sb = new StrBuilder("abab"); assertEquals (2, sb.lastIndexOf('a')); //should work like String#lastIndexOf assertEquals ("abab".lastIndexOf('a'), sb.lastIndexOf('a')); assertEquals(3, sb.lastIndexOf('b')); assertEquals ("abab".lastIndexOf('b'), sb.lastIndexOf('b')); assertEquals (-1, sb.lastIndexOf('z')); } @Test public void testLastIndexOf_char_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(-1, sb.lastIndexOf('a', -1)); assertEquals(0, sb.lastIndexOf('a', 0)); assertEquals(0, sb.lastIndexOf('a', 1)); // should work like String#lastIndexOf assertEquals("abab".lastIndexOf('a', 1), sb.lastIndexOf('a', 1)); assertEquals(1, sb.lastIndexOf('b', 2)); assertEquals("abab".lastIndexOf('b', 2), sb.lastIndexOf('b', 2)); assertEquals(-1, sb.lastIndexOf('z', 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.lastIndexOf('z', sb.length())); assertEquals(-1, sb.lastIndexOf('z', 1)); } // ----------------------------------------------------------------------- @Test public void testIndexOf_String() { final StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf("a")); //should work like String#indexOf assertEquals("abab".indexOf("a"), sb.indexOf("a")); assertEquals(0, sb.indexOf("ab")); //should work like String#indexOf assertEquals("abab".indexOf("ab"), sb.indexOf("ab")); assertEquals(1, sb.indexOf("b")); assertEquals("abab".indexOf("b"), sb.indexOf("b")); assertEquals(1, sb.indexOf("ba")); assertEquals("abab".indexOf("ba"), sb.indexOf("ba")); assertEquals(-1, sb.indexOf("z")); assertEquals(-1, sb.indexOf((String) null)); } @Test public void testIndexOf_String_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf("a", -1)); assertEquals(0, sb.indexOf("a", 0)); assertEquals(2, sb.indexOf("a", 1)); assertEquals(2, sb.indexOf("a", 2)); assertEquals(-1, sb.indexOf("a", 3)); assertEquals(-1, sb.indexOf("a", 4)); assertEquals(-1, sb.indexOf("a", 5)); assertEquals(-1, sb.indexOf("abcdef", 0)); assertEquals(0, sb.indexOf("", 0)); assertEquals(1, sb.indexOf("", 1)); //should work like String#indexOf assertEquals ("abab".indexOf("a", 1), sb.indexOf("a", 1)); assertEquals(2, sb.indexOf("ab", 1)); //should work like String#indexOf assertEquals("abab".indexOf("ab", 1), sb.indexOf("ab", 1)); assertEquals(3, sb.indexOf("b", 2)); assertEquals("abab".indexOf("b", 2), sb.indexOf("b", 2)); assertEquals(1, sb.indexOf("ba", 1)); assertEquals("abab".indexOf("ba", 2), sb.indexOf("ba", 2)); assertEquals(-1, sb.indexOf("z", 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.indexOf("za", 0)); assertEquals(-1, sb.indexOf("za", 3)); assertEquals(-1, sb.indexOf((String) null, 2)); } @Test public void testLastIndexOf_String() { final StrBuilder sb = new StrBuilder("abab"); assertEquals(2, sb.lastIndexOf("a")); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("a"), sb.lastIndexOf("a")); assertEquals(2, sb.lastIndexOf("ab")); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("ab"), sb.lastIndexOf("ab")); assertEquals(3, sb.lastIndexOf("b")); assertEquals("abab".lastIndexOf("b"), sb.lastIndexOf("b")); assertEquals(1, sb.lastIndexOf("ba")); assertEquals("abab".lastIndexOf("ba"), sb.lastIndexOf("ba")); assertEquals(-1, sb.lastIndexOf("z")); assertEquals(-1, sb.lastIndexOf((String) null)); } @Test public void testLastIndexOf_String_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(-1, sb.lastIndexOf("a", -1)); assertEquals(0, sb.lastIndexOf("a", 0)); assertEquals(0, sb.lastIndexOf("a", 1)); assertEquals(2, sb.lastIndexOf("a", 2)); assertEquals(2, sb.lastIndexOf("a", 3)); assertEquals(2, sb.lastIndexOf("a", 4)); assertEquals(2, sb.lastIndexOf("a", 5)); assertEquals(-1, sb.lastIndexOf("abcdef", 3)); assertEquals("abab".lastIndexOf("", 3), sb.lastIndexOf("", 3)); assertEquals("abab".lastIndexOf("", 1), sb.lastIndexOf("", 1)); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("a", 1), sb.lastIndexOf("a", 1)); assertEquals(0, sb.lastIndexOf("ab", 1)); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("ab", 1), sb.lastIndexOf("ab", 1)); assertEquals(1, sb.lastIndexOf("b", 2)); assertEquals("abab".lastIndexOf("b", 2), sb.lastIndexOf("b", 2)); assertEquals(1, sb.lastIndexOf("ba", 2)); assertEquals("abab".lastIndexOf("ba", 2), sb.lastIndexOf("ba", 2)); assertEquals(-1, sb.lastIndexOf("z", 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.lastIndexOf("za", sb.length())); assertEquals(-1, sb.lastIndexOf("za", 1)); assertEquals(-1, sb.lastIndexOf((String) null, 2)); } // ----------------------------------------------------------------------- @Test public void testIndexOf_StrMatcher() { final StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.indexOf((StrMatcher) null)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'))); sb.append("ab bd"); assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'))); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'))); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher())); assertEquals(4, sb.indexOf(StrMatcher.charMatcher('d'))); assertEquals(-1, sb.indexOf(StrMatcher.noneMatcher())); assertEquals(-1, sb.indexOf((StrMatcher) null)); sb.append(" A1 junction"); assertEquals(6, sb.indexOf(A_NUMBER_MATCHER)); } @Test public void testIndexOf_StrMatcher_int() { final StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.indexOf((StrMatcher) null, 2)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 0)); sb.append("ab bd"); assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'), -2)); assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'), 0)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 20)); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), -1)); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), 0)); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), 1)); assertEquals(3, sb.indexOf(StrMatcher.charMatcher('b'), 2)); assertEquals(3, sb.indexOf(StrMatcher.charMatcher('b'), 3)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 4)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 5)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 6)); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), -2)); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), 0)); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), 2)); assertEquals(-1, sb.indexOf(StrMatcher.spaceMatcher(), 4)); assertEquals(-1, sb.indexOf(StrMatcher.spaceMatcher(), 20)); assertEquals(-1, sb.indexOf(StrMatcher.noneMatcher(), 0)); assertEquals(-1, sb.indexOf((StrMatcher) null, 0)); sb.append(" A1 junction with A2"); assertEquals(6, sb.indexOf(A_NUMBER_MATCHER, 5)); assertEquals(6, sb.indexOf(A_NUMBER_MATCHER, 6)); assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 7)); assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 22)); assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 23)); assertEquals(-1, sb.indexOf(A_NUMBER_MATCHER, 24)); } @Test public void testLastIndexOf_StrMatcher() { final StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.lastIndexOf((StrMatcher) null)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'))); sb.append("ab bd"); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'))); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'))); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher())); assertEquals(4, sb.lastIndexOf(StrMatcher.charMatcher('d'))); assertEquals(-1, sb.lastIndexOf(StrMatcher.noneMatcher())); assertEquals(-1, sb.lastIndexOf((StrMatcher) null)); sb.append(" A1 junction"); assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER)); } @Test public void testLastIndexOf_StrMatcher_int() { final StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.lastIndexOf((StrMatcher) null, 2)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 0)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), -1)); sb.append("ab bd"); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), -2)); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 0)); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 20)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('b'), -1)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 0)); assertEquals(1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 1)); assertEquals(1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 2)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 3)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 4)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 5)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 6)); assertEquals(-1, sb.lastIndexOf(StrMatcher.spaceMatcher(), -2)); assertEquals(-1, sb.lastIndexOf(StrMatcher.spaceMatcher(), 0)); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 2)); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 4)); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 20)); assertEquals(-1, sb.lastIndexOf(StrMatcher.noneMatcher(), 0)); assertEquals(-1, sb.lastIndexOf((StrMatcher) null, 0)); sb.append(" A1 junction with A2"); assertEquals(-1, sb.lastIndexOf(A_NUMBER_MATCHER, 5)); assertEquals(-1, sb.lastIndexOf(A_NUMBER_MATCHER, 6)); // A matches, 1 is outside bounds assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 7)); assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 22)); assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 23)); // A matches, 2 is outside bounds assertEquals(23, sb.lastIndexOf(A_NUMBER_MATCHER, 24)); } static final StrMatcher A_NUMBER_MATCHER = new StrMatcher() { @Override public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) { if (buffer[pos] == 'A') { pos++; if (pos < bufferEnd && buffer[pos] >= '0' && buffer[pos] <= '9') { return 2; } } return 0; } }; //----------------------------------------------------------------------- @Test public void testAsTokenizer() throws Exception { // from Javadoc final StrBuilder b = new StrBuilder(); b.append("a b "); final StrTokenizer t = b.asTokenizer(); final String[] tokens1 = t.getTokenArray(); assertEquals(2, tokens1.length); assertEquals("a", tokens1[0]); assertEquals("b", tokens1[1]); assertEquals(2, t.size()); b.append("c d "); final String[] tokens2 = t.getTokenArray(); assertEquals(2, tokens2.length); assertEquals("a", tokens2[0]); assertEquals("b", tokens2[1]); assertEquals(2, t.size()); assertEquals("a", t.next()); assertEquals("b", t.next()); t.reset(); final String[] tokens3 = t.getTokenArray(); assertEquals(4, tokens3.length); assertEquals("a", tokens3[0]); assertEquals("b", tokens3[1]); assertEquals("c", tokens3[2]); assertEquals("d", tokens3[3]); assertEquals(4, t.size()); assertEquals("a", t.next()); assertEquals("b", t.next()); assertEquals("c", t.next()); assertEquals("d", t.next()); assertEquals("a b c d ", t.getContent()); } // ----------------------------------------------------------------------- @Test public void testAsReader() throws Exception { final StrBuilder sb = new StrBuilder("some text"); Reader reader = sb.asReader(); assertTrue(reader.ready()); final char[] buf = new char[40]; assertEquals(9, reader.read(buf)); assertEquals("some text", new String(buf, 0, 9)); assertEquals(-1, reader.read()); assertFalse(reader.ready()); assertEquals(0, reader.skip(2)); assertEquals(0, reader.skip(-1)); assertTrue(reader.markSupported()); reader = sb.asReader(); assertEquals('s', reader.read()); reader.mark(-1); char[] array = new char[3]; assertEquals(3, reader.read(array, 0, 3)); assertEquals('o', array[0]); assertEquals('m', array[1]); assertEquals('e', array[2]); reader.reset(); assertEquals(1, reader.read(array, 1, 1)); assertEquals('o', array[0]); assertEquals('o', array[1]); assertEquals('e', array[2]); assertEquals(2, reader.skip(2)); assertEquals(' ', reader.read()); assertTrue(reader.ready()); reader.close(); assertTrue(reader.ready()); reader = sb.asReader(); array = new char[3]; try { reader.read(array, -1, 0); fail(); } catch (final IndexOutOfBoundsException ex) {} try { reader.read(array, 0, -1); fail(); } catch (final IndexOutOfBoundsException ex) {} try { reader.read(array, 100, 1); fail(); } catch (final IndexOutOfBoundsException ex) {} try { reader.read(array, 0, 100); fail(); } catch (final IndexOutOfBoundsException ex) {} try { reader.read(array, Integer.MAX_VALUE, Integer.MAX_VALUE); fail(); } catch (final IndexOutOfBoundsException ex) {} assertEquals(0, reader.read(array, 0, 0)); assertEquals(0, array[0]); assertEquals(0, array[1]); assertEquals(0, array[2]); reader.skip(9); assertEquals(-1, reader.read(array, 0, 1)); reader.reset(); array = new char[30]; assertEquals(9, reader.read(array, 0, 30)); } //----------------------------------------------------------------------- @Test public void testAsWriter() throws Exception { final StrBuilder sb = new StrBuilder("base"); final Writer writer = sb.asWriter(); writer.write('l'); assertEquals("basel", sb.toString()); writer.write(new char[] {'i', 'n'}); assertEquals("baselin", sb.toString()); writer.write(new char[] {'n', 'e', 'r'}, 1, 2); assertEquals("baseliner", sb.toString()); writer.write(" rout"); assertEquals("baseliner rout", sb.toString()); writer.write("ping that server", 1, 3); assertEquals("baseliner routing", sb.toString()); writer.flush(); // no effect assertEquals("baseliner routing", sb.toString()); writer.close(); // no effect assertEquals("baseliner routing", sb.toString()); writer.write(" hi"); // works after close assertEquals("baseliner routing hi", sb.toString()); sb.setLength(4); // mix and match writer.write('d'); assertEquals("based", sb.toString()); } //----------------------------------------------------------------------- @Test public void testEqualsIgnoreCase() { final StrBuilder sb1 = new StrBuilder(); final StrBuilder sb2 = new StrBuilder(); assertTrue(sb1.equalsIgnoreCase(sb1)); assertTrue(sb1.equalsIgnoreCase(sb2)); assertTrue(sb2.equalsIgnoreCase(sb2)); sb1.append("abc"); assertFalse(sb1.equalsIgnoreCase(sb2)); sb2.append("ABC"); assertTrue(sb1.equalsIgnoreCase(sb2)); sb2.clear().append("abc"); assertTrue(sb1.equalsIgnoreCase(sb2)); assertTrue(sb1.equalsIgnoreCase(sb1)); assertTrue(sb2.equalsIgnoreCase(sb2)); sb2.clear().append("aBc"); assertTrue(sb1.equalsIgnoreCase(sb2)); } //----------------------------------------------------------------------- @Test public void testEquals() { final StrBuilder sb1 = new StrBuilder(); final StrBuilder sb2 = new StrBuilder(); assertTrue(sb1.equals(sb2)); assertTrue(sb1.equals(sb1)); assertTrue(sb2.equals(sb2)); assertTrue(sb1.equals((Object) sb2)); sb1.append("abc"); assertFalse(sb1.equals(sb2)); assertFalse(sb1.equals((Object) sb2)); sb2.append("ABC"); assertFalse(sb1.equals(sb2)); assertFalse(sb1.equals((Object) sb2)); sb2.clear().append("abc"); assertTrue(sb1.equals(sb2)); assertTrue(sb1.equals((Object) sb2)); assertFalse(sb1.equals(Integer.valueOf(1))); assertFalse(sb1.equals("abc")); } @Test public void test_LANG_1131_EqualsWithNullStrBuilder() throws Exception { final StrBuilder sb = new StrBuilder(); final StrBuilder other = null; assertFalse(sb.equals(other)); } //----------------------------------------------------------------------- @Test public void testHashCode() { final StrBuilder sb = new StrBuilder(); final int hc1a = sb.hashCode(); final int hc1b = sb.hashCode(); assertEquals(0, hc1a); assertEquals(hc1a, hc1b); sb.append("abc"); final int hc2a = sb.hashCode(); final int hc2b = sb.hashCode(); assertTrue(hc2a != 0); assertEquals(hc2a, hc2b); } //----------------------------------------------------------------------- @Test public void testToString() { final StrBuilder sb = new StrBuilder("abc"); assertEquals("abc", sb.toString()); } //----------------------------------------------------------------------- @Test public void testToStringBuffer() { final StrBuilder sb = new StrBuilder(); assertEquals(new StringBuffer().toString(), sb.toStringBuffer().toString()); sb.append("junit"); assertEquals(new StringBuffer("junit").toString(), sb.toStringBuffer().toString()); } //----------------------------------------------------------------------- @Test public void testToStringBuilder() { final StrBuilder sb = new StrBuilder(); assertEquals(new StringBuilder().toString(), sb.toStringBuilder().toString()); sb.append("junit"); assertEquals(new StringBuilder("junit").toString(), sb.toStringBuilder().toString()); } //----------------------------------------------------------------------- @Test public void testLang294() { final StrBuilder sb = new StrBuilder("\n%BLAH%\nDo more stuff\neven more stuff\n%BLAH%\n"); sb.deleteAll("\n%BLAH%"); assertEquals("\nDo more stuff\neven more stuff\n", sb.toString()); } @Test public void testIndexOfLang294() { final StrBuilder sb = new StrBuilder("onetwothree"); sb.deleteFirst("three"); assertEquals(-1, sb.indexOf("three")); } //----------------------------------------------------------------------- @Test public void testLang295() { final StrBuilder sb = new StrBuilder("onetwothree"); sb.deleteFirst("three"); assertFalse( "The contains(char) method is looking beyond the end of the string", sb.contains('h')); assertEquals( "The indexOf(char) method is looking beyond the end of the string", -1, sb.indexOf('h')); } //----------------------------------------------------------------------- @Test public void testLang412Right() { final StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadRight(null, 10, '*'); assertEquals( "Failed to invoke appendFixedWidthPadRight correctly", "**********", sb.toString()); } @Test public void testLang412Left() { final StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadLeft(null, 10, '*'); assertEquals( "Failed to invoke appendFixedWidthPadLeft correctly", "**********", sb.toString()); } @Test public void testAsBuilder() { final StrBuilder sb = new StrBuilder().appendAll("Lorem", " ", "ipsum", " ", "dolor"); assertEquals(sb.toString(), sb.build()); } //----------------------------------------------------------------------- @Test public void testAppendCharBuffer() { final StrBuilder sb1 = new StrBuilder(); final CharBuffer buf = CharBuffer.allocate(10); buf.append("0123456789"); buf.flip(); sb1.append(buf); assertEquals("0123456789", sb1.toString()); final StrBuilder sb2 = new StrBuilder(); sb2.append(buf, 1, 8); assertEquals("12345678", sb2.toString()); } //----------------------------------------------------------------------- @Test public void testAppendToWriter() throws Exception { final StrBuilder sb = new StrBuilder("1234567890"); final StringWriter writer = new StringWriter(); writer.append("Test "); sb.appendTo(writer); assertEquals("Test 1234567890", writer.toString()); } @Test public void testAppendToStringBuilder() throws Exception { final StrBuilder sb = new StrBuilder("1234567890"); final StringBuilder builder = new StringBuilder("Test "); sb.appendTo(builder); assertEquals("Test 1234567890", builder.toString()); } @Test public void testAppendToStringBuffer() throws Exception { final StrBuilder sb = new StrBuilder("1234567890"); final StringBuffer buffer = new StringBuffer("Test "); sb.appendTo(buffer); assertEquals("Test 1234567890", buffer.toString()); } @Test public void testAppendToCharBuffer() throws Exception { final StrBuilder sb = new StrBuilder("1234567890"); final String text = "Test "; final CharBuffer buffer = CharBuffer.allocate(sb.size() + text.length()); buffer.put(text); sb.appendTo(buffer); buffer.flip(); assertEquals("Test 1234567890", buffer.toString()); } }
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.impl.Constants; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.hash.THash; import gnu.trove.impl.hash.TObjectHash; import gnu.trove.procedure.TObjectLongProcedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.TLongProcedure; import gnu.trove.iterator.TObjectLongIterator; import gnu.trove.iterator.TLongIterator; import gnu.trove.iterator.hash.TObjectHashIterator; import gnu.trove.function.TLongFunction; import gnu.trove.map.TObjectLongMap; import gnu.trove.TLongCollection; import java.io.*; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * An open addressed Map implementation for Object keys and long values. * * Created: Sun Nov 4 08:52:45 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall */ public class TObjectLongHashMap<K> extends TObjectHash<K> implements TObjectLongMap<K>, Externalizable { static final long serialVersionUID = 1L; private final TObjectLongProcedure<K> PUT_ALL_PROC = new TObjectLongProcedure<K>() { public boolean execute(K key, long value) { put(key, value); return true; } }; /** the values of the map */ protected transient long[] _values; /** the value that represents null */ protected long no_entry_value; /** * Creates a new <code>TObjectLongHashMap</code> instance with the default * capacity and load factor. */ public TObjectLongHashMap() { super(); no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE; } /** * Creates a new <code>TObjectLongHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the default load factor. * * @param initialCapacity an <code>int</code> value */ public TObjectLongHashMap( int initialCapacity ) { super( initialCapacity ); no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE; } /** * Creates a new <code>TObjectLongHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the specified load factor. * * @param initialCapacity an <code>int</code> value * @param loadFactor a <code>float</code> value */ public TObjectLongHashMap( int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor ); no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE; } /** * Creates a new <code>TObjectLongHashMap</code> instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the inlineThreshold over which * rehashing takes place. * @param noEntryValue the value used to represent null. */ public TObjectLongHashMap( int initialCapacity, float loadFactor, long noEntryValue ) { super( initialCapacity, loadFactor ); no_entry_value = noEntryValue; //noinspection RedundantCast if ( no_entry_value != ( long ) 0 ) { Arrays.fill( _values, no_entry_value ); } } /** * Creates a new <code>TObjectLongHashMap</code> that contains the entries * in the map passed to it. * * @param map the <tt>TObjectLongMap</tt> to be copied. */ public TObjectLongHashMap( TObjectLongMap<? extends K> map ) { this( map.size(), 0.5f, map.getNoEntryValue() ); if ( map instanceof TObjectLongHashMap ) { TObjectLongHashMap hashmap = ( TObjectLongHashMap ) map; this._loadFactor = hashmap._loadFactor; this.no_entry_value = hashmap.no_entry_value; //noinspection RedundantCast if ( this.no_entry_value != ( long ) 0 ) { Arrays.fill( _values, this.no_entry_value ); } setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } putAll( map ); } /** * initializes the hashtable to a prime capacity which is at least * <tt>initialCapacity + 1</tt>. * * @param initialCapacity an <code>int</code> value * @return the actual capacity chosen */ public int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _values = new long[capacity]; return capacity; } /** * rehashes the map to the new capacity. * * @param newCapacity an <code>int</code> value */ protected void rehash( int newCapacity ) { int oldCapacity = _set.length; //noinspection unchecked K oldKeys[] = ( K[] ) _set; long oldVals[] = _values; _set = new Object[newCapacity]; Arrays.fill( _set, FREE ); _values = new long[newCapacity]; Arrays.fill( _values, no_entry_value ); for ( int i = oldCapacity; i-- > 0; ) { if( oldKeys[i] != FREE && oldKeys[i] != REMOVED ) { K o = oldKeys[i]; int index = insertKey(o); if ( index < 0 ) { throwObjectContractViolation( _set[ (-index -1) ], o); } _set[index] = o; _values[index] = oldVals[i]; } } } // Query Operations /** {@inheritDoc} */ public long getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public boolean containsKey( Object key ) { return contains( key ); } /** {@inheritDoc} */ public boolean containsValue( long val ) { Object[] keys = _set; long[] vals = _values; for ( int i = vals.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && val == vals[i] ) { return true; } } return false; } /** {@inheritDoc} */ public long get( Object key ) { int index = index( key ); return index < 0 ? no_entry_value : _values[index]; } // Modification Operations /** {@inheritDoc} */ public long put( K key, long value ) { int index = insertKey( key ); return doPut( value, index ); } /** {@inheritDoc} */ public long putIfAbsent( K key, long value ) { int index = insertKey(key); if ( index < 0 ) return _values[-index - 1]; return doPut( value, index ); } private long doPut( long value, int index ) { long previous = no_entry_value; boolean isNewMapping = true; if ( index < 0 ) { index = -index -1; previous = _values[index]; isNewMapping = false; } //noinspection unchecked _values[index] = value; if ( isNewMapping ) { postInsertHook( consumeFreeSlot ); } return previous; } /** {@inheritDoc} */ public long remove( Object key ) { long prev = no_entry_value; int index = index(key); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** * Removes the mapping at <tt>index</tt> from the map. * This method is used internally and public mainly because * of packaging reasons. Caveat Programmer. * * @param index an <code>int</code> value */ protected void removeAt( int index ) { _values[index] = no_entry_value; super.removeAt( index ); // clear key, state; adjust size } // Bulk Operations /** {@inheritDoc} */ public void putAll( Map<? extends K, ? extends Long> map ) { Set<? extends Map.Entry<? extends K,? extends Long>> set = map.entrySet(); for ( Map.Entry<? extends K,? extends Long> entry : set ) { put( entry.getKey(), entry.getValue() ); } } /** {@inheritDoc} */ public void putAll( TObjectLongMap<? extends K> map ){ map.forEachEntry( PUT_ALL_PROC ); } /** {@inheritDoc} */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, FREE ); Arrays.fill( _values, 0, _values.length, no_entry_value ); } // Views /** {@inheritDoc} */ public Set<K> keySet() { return new KeyView(); } /** {@inheritDoc} */ public Object[] keys() { //noinspection unchecked K[] keys = ( K[] ) new Object[size()]; Object[] k = _set; for ( int i = k.length, j = 0; i-- > 0; ) { if ( k[i] != FREE && k[i] != REMOVED ) { //noinspection unchecked keys[j++] = ( K ) k[i]; } } return keys; } /** {@inheritDoc} */ public K[] keys( K[] a ) { int size = size(); if ( a.length < size ) { //noinspection unchecked a = ( K[] ) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Object[] k = _set; for ( int i = k.length, j = 0; i-- > 0; ) { if ( k[i] != FREE && k[i] != REMOVED ) { //noinspection unchecked a[j++] = ( K ) k[i]; } } return a; } /** {@inheritDoc} */ public TLongCollection valueCollection() { return new TLongValueCollection(); } /** {@inheritDoc} */ public long[] values() { long[] vals = new long[size()]; long[] v = _values; Object[] keys = _set; for ( int i = v.length, j = 0; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { vals[j++] = v[i]; } } return vals; } /** {@inheritDoc} */ public long[] values( long[] array ) { int size = size(); if ( array.length < size ) { array = new long[size]; } long[] v = _values; Object[] keys = _set; for ( int i = v.length, j = 0; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { array[j++] = v[i]; } } if ( array.length > size ) { array[size] = no_entry_value; } return array; } /** * @return an iterator over the entries in this map */ public TObjectLongIterator<K> iterator() { return new TObjectLongHashIterator<K>( this ); } /** {@inheritDoc} */ @SuppressWarnings({"RedundantCast"}) public boolean increment( K key ) { //noinspection RedundantCast return adjustValue( key, (long)1 ); } /** {@inheritDoc} */ public boolean adjustValue( K key, long amount ) { int index = index(key); if ( index < 0 ) { return false; } else { _values[index] += amount; return true; } } /** {@inheritDoc} */ public long adjustOrPutValue( final K key, final long adjust_amount, final long put_amount ) { int index = insertKey( key ); final boolean isNewMapping; final long newValue; if ( index < 0 ) { index = -index -1; newValue = ( _values[index] += adjust_amount ); isNewMapping = false; } else { newValue = ( _values[index] = put_amount ); isNewMapping = true; } //noinspection unchecked if ( isNewMapping ) { postInsertHook( consumeFreeSlot ); } return newValue; } /** * Executes <tt>procedure</tt> for each key in the map. * * @param procedure a <code>TObjectProcedure</code> value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey( TObjectProcedure<? super K> procedure ) { return forEach( procedure ); } /** * Executes <tt>procedure</tt> for each value in the map. * * @param procedure a <code>TLongProcedure</code> value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue( TLongProcedure procedure ) { Object[] keys = _set; long[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( values[i] ) ) { return false; } } return true; } /** * Executes <tt>procedure</tt> for each key/value entry in the * map. * * @param procedure a <code>TOObjectLongProcedure</code> value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ @SuppressWarnings({"unchecked"}) public boolean forEachEntry( TObjectLongProcedure<? super K> procedure ) { Object[] keys = _set; long[] values = _values; for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( ( K ) keys[i], values[i] ) ) { return false; } } return true; } /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ public boolean retainEntries( TObjectLongProcedure<? super K> procedure ) { boolean modified = false; //noinspection unchecked K[] keys = ( K[] ) _set; long[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( keys[i], values[i] ) ) { removeAt(i); modified = true; } } } finally { reenableAutoCompaction( true ); } return modified; } /** * Transform the values in this map using <tt>function</tt>. * * @param function a <code>TLongFunction</code> value */ public void transformValues( TLongFunction function ) { Object[] keys = _set; long[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != null && keys[i] != REMOVED ) { values[i] = function.execute( values[i] ); } } } // Comparison and hashing /** * Compares this map with another map for equality of their stored * entries. * * @param other an <code>Object</code> value * @return a <code>boolean</code> value */ public boolean equals( Object other ) { if ( ! ( other instanceof TObjectLongMap ) ) { return false; } TObjectLongMap that = ( TObjectLongMap ) other; if ( that.size() != this.size() ) { return false; } try { TObjectLongIterator iter = this.iterator(); while ( iter.hasNext() ) { iter.advance(); Object key = iter.key(); long value = iter.value(); if ( value == no_entry_value ) { if ( !( that.get( key ) == that.getNoEntryValue() && that.containsKey( key ) ) ) { return false; } } else { if ( value != that.get( key ) ) { return false; } } } } catch ( ClassCastException ex ) { // unused. } return true; } /** {@inheritDoc} */ public int hashCode() { int hashcode = 0; Object[] keys = _set; long[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { hashcode += HashFunctions.hash( values[i] ) ^ ( keys[i] == null ? 0 : keys[i].hashCode() ); } } return hashcode; } /** a view onto the keys of the map. */ protected class KeyView extends MapBackedView<K> { @SuppressWarnings({"unchecked"}) public Iterator<K> iterator() { return new TObjectHashIterator( TObjectLongHashMap.this ); } public boolean removeElement( K key ) { return no_entry_value != TObjectLongHashMap.this.remove( key ); } public boolean containsElement( K key ) { return TObjectLongHashMap.this.contains( key ); } } private abstract class MapBackedView<E> extends AbstractSet<E> implements Set<E>, Iterable<E> { public abstract boolean removeElement( E key ); public abstract boolean containsElement( E key ); @SuppressWarnings({"unchecked"}) public boolean contains( Object key ) { return containsElement( (E) key ); } @SuppressWarnings({"unchecked"}) public boolean remove( Object o ) { return removeElement( (E) o ); } public void clear() { TObjectLongHashMap.this.clear(); } public boolean add( E obj ) { throw new UnsupportedOperationException(); } public int size() { return TObjectLongHashMap.this.size(); } public Object[] toArray() { Object[] result = new Object[size()]; Iterator<E> e = iterator(); for ( int i = 0; e.hasNext(); i++ ) { result[i] = e.next(); } return result; } public <T> T[] toArray( T[] a ) { int size = size(); if ( a.length < size ) { //noinspection unchecked a = (T[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Iterator<E> it = iterator(); Object[] result = a; for ( int i = 0; i < size; i++ ) { result[i] = it.next(); } if ( a.length > size ) { a[size] = null; } return a; } public boolean isEmpty() { return TObjectLongHashMap.this.isEmpty(); } public boolean addAll( Collection<? extends E> collection ) { throw new UnsupportedOperationException(); } @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection<?> collection ) { boolean changed = false; Iterator<E> i = iterator(); while ( i.hasNext() ) { if ( !collection.contains( i.next() ) ) { i.remove(); changed = true; } } return changed; } } class TLongValueCollection implements TLongCollection { /** {@inheritDoc} */ public TLongIterator iterator() { return new TObjectLongValueHashIterator(); } /** {@inheritDoc} */ public long getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( long entry ) { return TObjectLongHashMap.this.containsValue( entry ); } /** {@inheritDoc} */ public long[] toArray() { return TObjectLongHashMap.this.values(); } /** {@inheritDoc} */ public long[] toArray( long[] dest ) { return TObjectLongHashMap.this.values( dest ); } public boolean add( long entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( long entry ) { long[] values = _values; Object[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) { removeAt( i ); return true; } } return false; } /** {@inheritDoc} */ public boolean containsAll( Collection<?> collection ) { for ( Object element : collection ) { if ( element instanceof Long ) { long ele = ( ( Long ) element ).longValue(); if ( ! TObjectLongHashMap.this.containsValue( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( TLongCollection collection ) { TLongIterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! TObjectLongHashMap.this.containsValue( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( long[] array ) { for ( long element : array ) { if ( ! TObjectLongHashMap.this.containsValue( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection<? extends Long> collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( TLongCollection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( long[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection<?> collection ) { boolean modified = false; TLongIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( TLongCollection collection ) { if ( this == collection ) { return false; } boolean modified = false; TLongIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( long[] array ) { boolean changed = false; Arrays.sort( array ); long[] values = _values; Object[] set = _set; for ( int i = set.length; i-- > 0; ) { if ( set[i] != FREE && set[i] != REMOVED && ( Arrays.binarySearch( array, values[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection<?> collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof Long ) { long c = ( ( Long ) element ).longValue(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( TLongCollection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; TLongIterator iter = collection.iterator(); while ( iter.hasNext() ) { long element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( long[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { TObjectLongHashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( TLongProcedure procedure ) { return TObjectLongHashMap.this.forEachValue( procedure ); } @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachValue( new TLongProcedure() { private boolean first = true; public boolean execute( long value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } class TObjectLongValueHashIterator implements TLongIterator { protected THash _hash = TObjectLongHashMap.this; /** * the number of elements this iterator believes are in the * data structure it accesses. */ protected int _expectedSize; /** the index used for iteration. */ protected int _index; /** Creates an iterator over the specified map */ TObjectLongValueHashIterator() { _expectedSize = _hash.size(); _index = _hash.capacity(); } /** {@inheritDoc} */ public boolean hasNext() { return nextIndex() >= 0; } /** {@inheritDoc} */ public long next() { moveToNextIndex(); return _values[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for // bug 1642768. try { _hash.tempDisableAutoCompaction(); TObjectLongHashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } /** * Sets the internal <tt>index</tt> so that the `next' object * can be returned. */ protected final void moveToNextIndex() { // doing the assignment && < 0 in one line shaves // 3 opcodes... if ( ( _index = nextIndex() ) < 0 ) { throw new NoSuchElementException(); } } /** * Returns the index of the next value in the data structure * or a negative value if the iterator is exhausted. * * @return an <code>int</code> value * @throws ConcurrentModificationException * if the underlying * collection's size has been modified since the iterator was * created. */ protected final int nextIndex() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } Object[] set = TObjectLongHashMap.this._set; int i = _index; while ( i-- > 0 && ( set[i] == TObjectHash.FREE || set[i] == TObjectHash.REMOVED ) ) { // do nothing } return i; } } } class TObjectLongHashIterator<K> extends TObjectHashIterator<K> implements TObjectLongIterator<K> { /** the collection being iterated over */ private final TObjectLongHashMap<K> _map; public TObjectLongHashIterator( TObjectLongHashMap<K> map ) { super( map ); this._map = map; } /** {@inheritDoc} */ public void advance() { moveToNextIndex(); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public K key() { return ( K ) _map._set[_index]; } /** {@inheritDoc} */ public long value() { return _map._values[_index]; } /** {@inheritDoc} */ public long setValue( long val ) { long old = value(); _map._values[_index] = val; return old; } } // Externalization public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // NO_ENTRY_VALUE out.writeLong( no_entry_value ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _set.length; i-- > 0; ) { if ( _set[i] != REMOVED && _set[i] != FREE ) { out.writeObject( _set[i] ); out.writeLong( _values[i] ); } } } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // NO_ENTRY_VALUE no_entry_value = in.readLong(); // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while (size-- > 0) { //noinspection unchecked K key = ( K ) in.readObject(); long val = in.readLong(); put(key, val); } } /** {@inheritDoc} */ public String toString() { final StringBuilder buf = new StringBuilder("{"); forEachEntry( new TObjectLongProcedure<K>() { private boolean first = true; public boolean execute( K key, long value ) { if ( first ) first = false; else buf.append( "," ); buf.append( key ).append( "=" ).append( value ); return true; } }); buf.append( "}" ); return buf.toString(); } } // TObjectLongHashMap
package se.uu.it.cs.recsys.semantic; /* * #%L * CourseRecommenderDomainReasoner * %% * Copyright (C) 2015 Yong Huang <[email protected] > * %% * 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 com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.annotation.Import; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import se.uu.it.cs.recsys.semantic.config.ComputingDomainReasonerSpringConfig; /** * Can be used both and POJO and Spring Bean. When used as Spring bean, import * configuration {@link ComputingDomainReasonerSpringConfig} with Spring * {@link Import}. * * @author Yong Huang &lt;[email protected]&gt; */ @Component public class ComputingDomainReasoner { private static final Logger LOGGER = LoggerFactory.getLogger(ComputingDomainReasoner.class); private static final String TAXONOMY_PATH = "classpath:taxonomy/ACMComputingClassificationSystemSKOSTaxonomy.xml"; @Value(TAXONOMY_PATH) private Resource skosFile; /** * Get id and label pairs. * * @return non-null set * @throws java.io.IOException */ @Cacheable("ComputingDomainCache") public Map<String, String> getIdAndLabel() throws IOException { Query query = SparqlQueryFactory.getIdAndPrefLabelQuery(); Model model = getPopulatedModel(); try (QueryExecution qe = QueryExecutionFactory.create(query, model)) { return SparqlResultParser.parseIdAndPrefLabelQueryResult(qe.execSelect()); } } /** * * @param domainId the id of the domain * @return non-null instance of {@link Optional}, which may or may not * contains the preferred label of the domain. * @throws java.io.IOException */ public Optional<String> getPrefLabel(String domainId) throws IOException { Query query = SparqlQueryFactory.getPrefLabelQuery(domainId); Model model = getPopulatedModel(); try (QueryExecution qe = QueryExecutionFactory.create(query, model)) { return SparqlResultParser.parsePrefLabelQueryResult(qe.execSelect()); } } /** * @param domainId * @return non-null set of "narrower" subject ids * @throws java.io.IOException */ public Set<String> getNarrowerDomainIds(String domainId) throws IOException { Query query = SparqlQueryFactory.getNarrowerDomainIdsQuery(domainId); Model model = getPopulatedModel(); try (QueryExecution qe = QueryExecutionFactory.create(query, model)) { return SparqlResultParser.parseNarrowerDomainQueryResult(qe.execSelect()); } } /** * * @param domainId the id of the domain * @return the non-null set of "related" domain ids if no Exception happens * * @throws IOException if failing getting input stream from taxonomy file. */ public Set<String> getRelatedDomainIds(String domainId) throws IOException { Query query = SparqlQueryFactory.getRelatedDomainIdsQuery(domainId); Model model = getPopulatedModel(); try (QueryExecution qe = QueryExecutionFactory.create(query, model)) { return SparqlResultParser.parseRelatedDomainQueryResult(qe.execSelect()); } } @Cacheable("ComputingDomainCache") private Model getPopulatedModel() throws IOException { Model model = ModelFactory.createDefaultModel(); try { model.read(this.skosFile.getInputStream(), ""); } catch (IOException e) { LOGGER.error("Failed accessing taxonomy file!", e); throw e; } return model; } /** * The method first finds the related domains to the input domain; then find * the relevant courses to these domains. * * @param domainId id of the domain * @return get related course ids */ // public Set<String> getIndirectRelatedCourseIds(String domainId) { // Set<String> r = new HashSet<String>(); // // Set<String> dIds = getRelatedDomainIds(domainId); // // CourseDomainRelevanceDAO dao = new CourseDomainRelevanceDAO(); // // for (String dId : dIds) { // r.addAll(dao.getCourseIdsByDomainId(dId)); // } // // return r; // } /** * @param domainId id of the domain * @return set of direct and indirect related courses id to the input domain * id */ // public Set<String> getRelatedCourseIds(String domainId) { // Set<String> r = new HashSet<String>(); // // r.addAll(getIndirectRelatedCourseIds(domainId)); // r.addAll(getDirectRelatedCourseIds(domainId)); // // return r; // } /** * The method first finds the directly related courses to this domain. * * @param domainId id of the domain * @return set of course ids directly related to this domain. */ // public Set<String> getDirectRelatedCourseIds(String domainId) { // Set<String> r = new HashSet<String>(); // // CourseDomainRelevanceDAO dao = new CourseDomainRelevanceDAO(); // // r.addAll(dao.getCourseIdsByDomainId(domainId)); // // return r; // } /** * The method first finds the narrower ids to the input domain id and then * find related courses to these narrower ids. * * @param domainId id of the domain * @return set of narrower courses of this domain */ // public Set<String> getNarrowerCourseIds(String domainId) { // Set<String> r = new HashSet<String>(); // // Set<String> ids = getNarrowerDomainIds(domainId); // // CourseDomainRelevanceDAO dao = new CourseDomainRelevanceDAO(); // // for (String dId : ids) { // r.addAll(dao.getCourseIdsByDomainId(dId)); // } // // return r; // } /** * @param domainIds * @return join set of related course ids to each domain id, indirectly and * directly * @see DomainReasoner#getRelatedCourseIds(String) */ public Set<String> getRelatedCourseIdsForCollection(Set<String> domainIds) { Set<String> r = new HashSet<>(); domainIds.stream().forEach((id) -> { try { r.addAll(getRelatedDomainIds(id)); } catch (IOException ex) { LOGGER.error("Failed querying narrower ids for {}", id, ex); } }); return r; } /** * The method first get narrower domains ids and then get related course ids * to these domain ids * * @param domainIds * @return */ public Set<String> getNarrowerCourseIdsForCollection(Set<String> domainIds) { Set<String> r = new HashSet<>(); domainIds.stream().forEach((id) -> { try { r.addAll(getNarrowerDomainIds(id)); } catch (IOException ex) { LOGGER.error("Failed querying narrower ids for {}", id, ex); } }); return r; } }
/* * 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 io.tilt.minka.core.task.impl; import static io.tilt.minka.core.task.Semaphore.Permission.GRANTED; import static io.tilt.minka.core.task.Semaphore.Permission.RETRY; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.tilt.minka.api.Config; import io.tilt.minka.api.config.SchedulerSettings; import io.tilt.minka.core.task.Scheduler; import io.tilt.minka.shard.ShardIdentifier; /** * @author Cristian Gonzalez * @since Dec 28, 2015 */ public class SchedulerImpl extends SemaphoreImpl implements Scheduler { private final Logger logger = LoggerFactory.getLogger(getClass()); /* for scheduling and stopping tasks */ private final Map<Synchronized, ScheduledFuture<?>> futuresBySynchro; private final Map<Synchronized, Runnable> runnablesBySynchro; private final Map<Synchronized, Callable<?>> callablesBySynchro; private final Map<Action, Agent> agentsByAction; private final AgentFactory agentFactory; private final SynchronizedFactory syncFactory; private final String logName; private ScheduledThreadPoolExecutor executor; public SchedulerImpl( final Config config, final SpectatorSupplier supplier, final ShardIdentifier shardId, final AgentFactory agentFactory, final SynchronizedFactory syncFactory) { super(config, supplier, shardId.toString()); this.logName = shardId.toString(); this.agentFactory = agentFactory; this.syncFactory = syncFactory; this.executor = buildExecutor(config); this.futuresBySynchro = new HashMap<>(); this.runnablesBySynchro = new HashMap<>(); this.callablesBySynchro = new HashMap<>(); this.agentsByAction = new HashMap<>(); } public ScheduledThreadPoolExecutor buildExecutor(final Config config) { final ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor( config.getScheduler().getMaxConcurrency(), new ThreadFactoryBuilder() .setNameFormat(SchedulerSettings.THREAD_NAME_SCHEDULER + "-%d") .build(), (r, x) -> logger.error("{}: ({}) Rejecting task {} (no capacity)", getName(), logName, r.toString())) ; exec.setRemoveOnCancelPolicy(true); exec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); exec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); exec.allowCoreThreadTimeOut(false); exec.prestartAllCoreThreads(); return exec; } @Override public Map<Synchronized, ScheduledFuture<?>> getFutures() { return futuresBySynchro; } @Override public Agent get(Action action) { return agentsByAction.get(action); } @Override public void forward(Agent agent) { logger.info("{}: ({}) Forwarding task's execution ", getName(), logName, agent); if (stop(agent, false)) { schedule(getAgentFactory() .create( agent.getAction(), agent.getPriority(), agent.getFrequency(), //Frequency.ONCE, agent.getTask()) .build()); } } @Override public boolean stop(final Synchronized synchro) { return stop(synchro, true); } private boolean stop(final Synchronized synchro, final boolean withFire) { Validate.notNull(synchro); final Callable<?> callable = this.callablesBySynchro.get(synchro); final Runnable runnable = this.runnablesBySynchro.get(synchro); ScheduledFuture<?> future = this.futuresBySynchro.get(synchro); boolean dequeued = false; if (runnable != null) { logger.warn("{}: ({}) Removing synchronized {} from registry", getName(), logName, synchro); runnablesBySynchro.remove(synchro); dequeued = this.executor.remove(runnable); } else if (callable != null) { logger.warn("{}: ({}) Removing synchronized {} from registry", getName(), logName, synchro); callablesBySynchro.remove(synchro); } else { logger.error("{}: ({}) Runnable/Callable {} not found, finished or never scheduled", getName(), logName, synchro.getAction().name()); return false; } boolean cancelled = false; if (future != null) { cancelled = future.cancel(withFire); logger.warn("{}: ({}) Stopping - Task {} ({}) Cancelled = {}, Dequeued = {}", getName(), logName, synchro.getAction().name(), runnable.getClass().getSimpleName(), cancelled, dequeued); } else { logger.error("{}: ({}) Stopping - Task {} ({}) Not found !!", getName(), logName, synchro.getAction().name(), runnable.getClass().getSimpleName()); } this.executor.purge(); agentsByAction.remove(synchro.getAction()); return cancelled; } @Override public void run(Synchronized synchro) { runSynchronized(synchro); } @Override public void schedule(final Agent agent) { Validate.notNull(agent); Runnable runnable = null; ScheduledFuture<?> future = null; logger.debug("{}: ({}) Saving Agent = {} ", getName(), logName, agent.toString()); if (agent.getFrequency() == Frequency.PERIODIC) { future = executor.scheduleWithFixedDelay( runnable = () -> runSynchronized(agent), agent.getDelay(), agent.getPeriodicDelay(), agent.getTimeUnit()); } else if (agent.getFrequency() == Frequency.ONCE) { executor.execute(runnable = () -> runSynchronized(agent)); } else if (agent.getFrequency() == Frequency.ONCE_DELAYED) { future = executor.schedule(runnable = () -> runSynchronized(agent), agent.getDelay(), MILLISECONDS); } futuresBySynchro.put(agent, future); runnablesBySynchro.put(agent, runnable); agentsByAction.put(agent.getAction(), agent); } /** * Executes a lambda before acquiring a service permission, then it releases it. * It loops in the specified case. */ @SuppressWarnings("unchecked") private <R> R runSynchronized(final Synchronized sync) { try { sync.flagEnqueued(); Validate.notNull(sync); if (sync.getPriority() == PriorityLock.HIGH_ISOLATED) { call(sync, false); return (R) new Boolean(true); } final boolean untilGrant = sync.getPriority() == PriorityLock.MEDIUM_BLOCKING; int retries = 0; while (!Thread.interrupted()) { final Permission p = untilGrant ? acquireBlocking(sync.getAction()) : acquire(sync.getAction()); if (logger.isDebugEnabled()) { logger.debug("{}: ({}) {} operation {} to {}", getName(), logName, sync.getAction(), p, sync.getTask().getClass().getSimpleName()); } if (p == GRANTED) { return call(sync, true); } else if (p == RETRY && untilGrant) { if (retries++ < getConfig().getScheduler().getSemaphoreUnlockMaxRetries()) { if (logger.isDebugEnabled()) { logger.warn("{}: ({}) Sleeping while waiting to acquire lock: {}", getName(), logName, sync.getAction()); } // TODO: WTF -> LockSupport.parkUntil(Config.SEMAPHORE_UNLOCK_RETRY_DELAY_MS); try { Thread.sleep(getConfig().getScheduler().getSemaphoreUnlockRetryFrequencyMs()); continue; } catch (InterruptedException e) { logger.error("{}: ({}) While sleeping for unlock delay", getName(), logName, e); break; } } else { logger.warn("{}: ({}) Coordination starved ({}) for action: {} too many retries ({})", getName(), logName, p, sync .getAction(), retries); break; } } else { logger.error("{}: Unexpected situation !", getName()); break; } } } catch (Exception e) { logger.error("{}: Unexpected ", getName(), e); } return null; } @SuppressWarnings("unchecked") private <R> R call(final Synchronized sync, boolean inSync) { try { if (sync.getTask() instanceof Runnable) { if (logger.isDebugEnabled()) { logger.debug("{}: ({}) Executing {}", getName(), logName, sync.toString().toLowerCase()); } sync.execute(); return (R) new Boolean(true); } else if (sync.getTask() instanceof Callable) { R call = ((Callable<R>) sync.getTask()).call(); return call; } else { logger.error("{}: ({}) Cannot execute: {} task: {} IS NOT RUNNABLE NOR CALLABLE", getName(), logName, sync.getTask().getClass().getName(), sync.getAction()); } } catch (Throwable t) { logger.error("{}: ({}) Untrapped task's exception while executing: {} task: {}", getName(), logName, sync.getTask().getClass().getName(), sync.getAction(), t); } finally { try { if (inSync) { release(sync.getAction()); } } catch (Throwable t2) { logger.error("{}: ({}) Untrapped task's exception while Releasing: {} task: {}", getName(), logName, sync.getTask().getClass().getName(), sync.getAction(), t2); } } return null; } @Override public void start() { super.start(); } @Override public void stop() { this.executor.shutdownNow(); super.stop(); } @Override public Map<Action, Agent> getAgents() { return agentsByAction; } @Override public boolean inService() { return !this.executor.isShutdown(); } @Override public SynchronizedFactory getFactory() { return this.syncFactory; } @Override public ScheduledThreadPoolExecutor getExecutor() { return executor; } @Override public AgentFactory getAgentFactory() { return this.agentFactory; } }
/* * Copyright 2014 Red Hat, Inc. * * Red Hat 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 io.vertx.rxjava.ext.amqp; import java.util.Map; import io.vertx.lang.rxjava.InternalHelper; import rx.Observable; import io.vertx.ext.amqp.ServiceOptions; import io.vertx.ext.amqp.OutgoingLinkOptions; import io.vertx.rxjava.core.Vertx; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.ext.amqp.IncomingLinkOptions; /** * AMQP service allows a Vert.x application to, * <ul> * <li>Establish and cancel incoming/outgoing AMQP links, and map the link it to * an event-bus address.</li> * <li>Configure the link behavior</li> * <li>Control the flow of messages both incoming and outgoing to maintain QoS</li> * <li>Send and Receive messages from AMQP peers with different reliability * guarantees</li> * </ul> * <p/> * For more information on AMQP visit www.amqp.org This service speaks AMQP 1.0 * and use QPid Proton(http://qpid.apache.org/proton) for protocol support. * * <p/> * NOTE: This class has been automatically generated from the {@link io.vertx.ext.amqp.AMQPService original} non RX-ified interface using Vert.x codegen. */ public class AMQPService { final io.vertx.ext.amqp.AMQPService delegate; public AMQPService(io.vertx.ext.amqp.AMQPService delegate) { this.delegate = delegate; } public Object getDelegate() { return delegate; } public static AMQPService createEventBusProxy(Vertx vertx, String address) { AMQPService ret= AMQPService.newInstance(io.vertx.ext.amqp.AMQPService.createEventBusProxy((io.vertx.core.Vertx) vertx.getDelegate(), address)); return ret; } /** * Allows an application to establish a link to an AMQP message-source for * receiving messages. The vertx-amqp-service will receive the messages on * behalf of the application and forward it to the event-bus address * specified in the consume method. The application will be listening on * this address. * @param amqpAddress A link will be created to the the AMQP message-source identified by this address. . * @param eventbusAddress The event-bus address to be mapped to the above link. The application should register a handler for this address on the event bus to receive the messages. * @param notificationAddress The event-bus address to which notifications about the incoming link is sent. Ex. Errors. The application should register a handler with the event-bus to receive these updates. Please see {@link io.vertx.ext.amqp.NotificationType} and {@link io.vertx.ext.amqp.NotificationHelper} for more details. * @param options Options to configure the link behavior (Ex prefetch, reliability). {@link io.vertx.ext.amqp.IncomingLinkOptions} * @param result The AsyncResult contains a ref (string) to the mapping created. This is required when changing behavior or canceling the link and it' association. * @return A reference to the service. */ public AMQPService establishIncomingLink(String amqpAddress, String eventbusAddress, String notificationAddress, IncomingLinkOptions options, Handler<AsyncResult<String>> result) { this.delegate.establishIncomingLink(amqpAddress, eventbusAddress, notificationAddress, options, result); return this; } /** * Allows an application to establish a link to an AMQP message-source for * receiving messages. The vertx-amqp-service will receive the messages on * behalf of the application and forward it to the event-bus address * specified in the consume method. The application will be listening on * this address. * @param amqpAddress A link will be created to the the AMQP message-source identified by this address. . * @param eventbusAddress The event-bus address to be mapped to the above link. The application should register a handler for this address on the event bus to receive the messages. * @param notificationAddress The event-bus address to which notifications about the incoming link is sent. Ex. Errors. The application should register a handler with the event-bus to receive these updates. Please see {@link io.vertx.ext.amqp.NotificationType} and {@link io.vertx.ext.amqp.NotificationHelper} for more details. * @param options Options to configure the link behavior (Ex prefetch, reliability). {@link io.vertx.ext.amqp.IncomingLinkOptions} * @return */ public Observable<String> establishIncomingLinkObservable(String amqpAddress, String eventbusAddress, String notificationAddress, IncomingLinkOptions options) { io.vertx.rx.java.ObservableFuture<String> result = io.vertx.rx.java.RxHelper.observableFuture(); establishIncomingLink(amqpAddress, eventbusAddress, notificationAddress, options, result.toHandler()); return result; } /** * If prefetch was set to zero, this method allows the application to * explicitly fetch a certain number of messages. If prefetch > 0, the AMQP * service will prefetch messages for you automatically. * @param incomingLinkRef The String ref return by the establishIncommingLink method. This uniquely identifies the incoming link and it's mapping to an event-bus address. * @param messages The number of message to fetch. * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService fetch(String incomingLinkRef, int messages, Handler<AsyncResult<Void>> result) { this.delegate.fetch(incomingLinkRef, messages, result); return this; } /** * If prefetch was set to zero, this method allows the application to * explicitly fetch a certain number of messages. If prefetch > 0, the AMQP * service will prefetch messages for you automatically. * @param incomingLinkRef The String ref return by the establishIncommingLink method. This uniquely identifies the incoming link and it's mapping to an event-bus address. * @param messages The number of message to fetch. * @return */ public Observable<Void> fetchObservable(String incomingLinkRef, int messages) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); fetch(incomingLinkRef, messages, result.toHandler()); return result; } /** * Allows an application to cancel an incoming link and remove it's mapping * to an event-bus address. * @param incomingLinkRef The String ref return by the establishIncommingLink method. This uniquely identifies the incoming link and it's mapping to an event-bus address. * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService cancelIncomingLink(String incomingLinkRef, Handler<AsyncResult<Void>> result) { this.delegate.cancelIncomingLink(incomingLinkRef, result); return this; } /** * Allows an application to cancel an incoming link and remove it's mapping * to an event-bus address. * @param incomingLinkRef The String ref return by the establishIncommingLink method. This uniquely identifies the incoming link and it's mapping to an event-bus address. * @return */ public Observable<Void> cancelIncomingLinkObservable(String incomingLinkRef) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); cancelIncomingLink(incomingLinkRef, result.toHandler()); return result; } /** * Allows an application to establish a link to an AMQP message-sink for * sending messages. The application will send the messages to the event-bus * address. The AMQP service will receive these messages via the event-bus * and forward it to the respective AMQP message sink. * @param amqpAddress A link will be created to the the AMQP message-sink identified by this address. * @param eventbusAddress The event-bus address to be mapped to the above link. The application should send the messages using this address. * @param notificationAddress The event-bus address to which notifications about the outgoing link is sent. Ex. Errors, Delivery Status, credit availability. The application should register a handler with the event-bus to receive these updates. Please see {@link io.vertx.ext.amqp.NotificationType} and {@link io.vertx.ext.amqp.NotificationHelper} for more details. * @param options Options to configure the link behavior (Ex reliability). {@link io.vertx.ext.amqp.IncomingLinkOptions} * @param result The AsyncResult contains a ref (string) to the mapping created. This is required when changing behavior or canceling the link and it' association. * @return A reference to the service. */ public AMQPService establishOutgoingLink(String amqpAddress, String eventbusAddress, String notificationAddress, OutgoingLinkOptions options, Handler<AsyncResult<String>> result) { this.delegate.establishOutgoingLink(amqpAddress, eventbusAddress, notificationAddress, options, result); return this; } /** * Allows an application to establish a link to an AMQP message-sink for * sending messages. The application will send the messages to the event-bus * address. The AMQP service will receive these messages via the event-bus * and forward it to the respective AMQP message sink. * @param amqpAddress A link will be created to the the AMQP message-sink identified by this address. * @param eventbusAddress The event-bus address to be mapped to the above link. The application should send the messages using this address. * @param notificationAddress The event-bus address to which notifications about the outgoing link is sent. Ex. Errors, Delivery Status, credit availability. The application should register a handler with the event-bus to receive these updates. Please see {@link io.vertx.ext.amqp.NotificationType} and {@link io.vertx.ext.amqp.NotificationHelper} for more details. * @param options Options to configure the link behavior (Ex reliability). {@link io.vertx.ext.amqp.IncomingLinkOptions} * @return */ public Observable<String> establishOutgoingLinkObservable(String amqpAddress, String eventbusAddress, String notificationAddress, OutgoingLinkOptions options) { io.vertx.rx.java.ObservableFuture<String> result = io.vertx.rx.java.RxHelper.observableFuture(); establishOutgoingLink(amqpAddress, eventbusAddress, notificationAddress, options, result.toHandler()); return result; } /** * Allows an application to cancel an outgoing link and remove it's mapping * to an event-bus address. * @param outgoingLinkRef The String ref return by the establishOutgoingLink method. This uniquely identifies the outgoing link and it's mapping to an event-bus address. * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService cancelOutgoingLink(String outgoingLinkRef, Handler<AsyncResult<Void>> result) { this.delegate.cancelOutgoingLink(outgoingLinkRef, result); return this; } /** * Allows an application to cancel an outgoing link and remove it's mapping * to an event-bus address. * @param outgoingLinkRef The String ref return by the establishOutgoingLink method. This uniquely identifies the outgoing link and it's mapping to an event-bus address. * @return */ public Observable<Void> cancelOutgoingLinkObservable(String outgoingLinkRef) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); cancelOutgoingLink(outgoingLinkRef, result.toHandler()); return result; } /** * Allows an application to accept a message it has received. * @param msgRef The string ref. Use * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService accept(String msgRef, Handler<AsyncResult<Void>> result) { this.delegate.accept(msgRef, result); return this; } /** * Allows an application to accept a message it has received. * @param msgRef The string ref. Use * @return */ public Observable<Void> acceptObservable(String msgRef) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); accept(msgRef, result.toHandler()); return result; } /** * Allows an application to reject a message it has received. * @param msgRef The string ref. Use * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService reject(String msgRef, Handler<AsyncResult<Void>> result) { this.delegate.reject(msgRef, result); return this; } /** * Allows an application to reject a message it has received. * @param msgRef The string ref. Use * @return */ public Observable<Void> rejectObservable(String msgRef) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); reject(msgRef, result.toHandler()); return result; } /** * Allows an application to release a message it has received. * @param msgRef The string ref. Use * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService release(String msgRef, Handler<AsyncResult<Void>> result) { this.delegate.release(msgRef, result); return this; } /** * Allows an application to release a message it has received. * @param msgRef The string ref. Use * @return */ public Observable<Void> releaseObservable(String msgRef) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); release(msgRef, result.toHandler()); return result; } /** * Allows a vertx.application to register a Service it provides with the * vertx-amqp-service. This allows any AMQP peer to interact with this * service by sending (and receiving) messages with the service. * @param eventbusAddress The event-bus address the service is listening for incoming requests. The application needs to register a handler with the event-bus using this address to receive the above requests. * @param notificationAddres The event-bus address to which notifications about the service is sent. The application should register a handler with the event-bus to receive these updates. Ex notifies the application of an incoming link created by an AMQP peer to send requests. Please see {@link io.vertx.ext.amqp.NotificationType} and {@link io.vertx.ext.amqp.NotificationHelper} for more details. * @param options Options to configure the Service behavior (Ex initial capacity). {@link io.vertx.ext.amqp.ServiceOptions} * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService registerService(String eventbusAddress, String notificationAddres, ServiceOptions options, Handler<AsyncResult<Void>> result) { this.delegate.registerService(eventbusAddress, notificationAddres, options, result); return this; } /** * Allows a vertx.application to register a Service it provides with the * vertx-amqp-service. This allows any AMQP peer to interact with this * service by sending (and receiving) messages with the service. * @param eventbusAddress The event-bus address the service is listening for incoming requests. The application needs to register a handler with the event-bus using this address to receive the above requests. * @param notificationAddres The event-bus address to which notifications about the service is sent. The application should register a handler with the event-bus to receive these updates. Ex notifies the application of an incoming link created by an AMQP peer to send requests. Please see {@link io.vertx.ext.amqp.NotificationType} and {@link io.vertx.ext.amqp.NotificationHelper} for more details. * @param options Options to configure the Service behavior (Ex initial capacity). {@link io.vertx.ext.amqp.ServiceOptions} * @return */ public Observable<Void> registerServiceObservable(String eventbusAddress, String notificationAddres, ServiceOptions options) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); registerService(eventbusAddress, notificationAddres, options, result.toHandler()); return result; } /** * Allows an application to unregister a service with vertx-amqp-service. * @param eventbusAddress The event-bus address used when registering the service * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService unregisterService(String eventbusAddress, Handler<AsyncResult<Void>> result) { this.delegate.unregisterService(eventbusAddress, result); return this; } /** * Allows an application to unregister a service with vertx-amqp-service. * @param eventbusAddress The event-bus address used when registering the service * @return */ public Observable<Void> unregisterServiceObservable(String eventbusAddress) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); unregisterService(eventbusAddress, result.toHandler()); return result; } /** * Allows the service to issue credits to a particular incoming link * (created by a remote AMQP peer) for sending more service requests. This * allows the Service to always be in control of how many messages it * receives so it can maintain the required QoS requirements. * @param linkId The ref for the incoming link. The service gets notified of an incoming link by registering for notifications. Please and {@link io.vertx.ext.amqp.NotificationHelper} for more details. * @param credits The number of message (requests) the AMQP peer is allowed to send. * @param result Notifies if there is an error. * @return A reference to the service. */ public AMQPService issueCredits(String linkId, int credits, Handler<AsyncResult<Void>> result) { this.delegate.issueCredits(linkId, credits, result); return this; } /** * Allows the service to issue credits to a particular incoming link * (created by a remote AMQP peer) for sending more service requests. This * allows the Service to always be in control of how many messages it * receives so it can maintain the required QoS requirements. * @param linkId The ref for the incoming link. The service gets notified of an incoming link by registering for notifications. Please and {@link io.vertx.ext.amqp.NotificationHelper#getLinkRef} for more details. * @param credits The number of message (requests) the AMQP peer is allowed to send. * @return */ public Observable<Void> issueCreditsObservable(String linkId, int credits) { io.vertx.rx.java.ObservableFuture<Void> result = io.vertx.rx.java.RxHelper.observableFuture(); issueCredits(linkId, credits, result.toHandler()); return result; } /** * Adds an entry to the inbound routing table. If an existing entry exists * under the same pattern, the event-bus address will be added to the list. * @param pattern The pattern to be matched against the chosen message-property from the incoming message. * @param eventBusAddress The Vert.x event-bus address the message should be sent to if matched. * @return A reference to the service. */ public AMQPService addInboundRoute(String pattern, String eventBusAddress) { this.delegate.addInboundRoute(pattern, eventBusAddress); return this; } /** * Removes the entry from the inbound routing table. * @param pattern The pattern (key) used when adding the entry to the table. * @param eventBusAddress The Vert.x event-bus address the message should be sent to if matched. * @return */ public AMQPService removeInboundRoute(String pattern, String eventBusAddress) { this.delegate.removeInboundRoute(pattern, eventBusAddress); return this; } /** * Adds an entry to the outbound routing table. If an existing entry exists * under the same pattern, the amqp address will be added to the list. * @param pattern The pattern to be matched against the chosen message-property from the outgoing message. * @param amqpAddress The AMQP address the message should be sent to if matched. * @return A reference to the service. */ public AMQPService addOutboundRoute(String pattern, String amqpAddress) { this.delegate.addOutboundRoute(pattern, amqpAddress); return this; } /** * Removes the entry from the outbound routing table. * @param pattern The pattern (key) used when adding the entry to the table. * @param amqpAddress The AMQP address the message should be sent to if matched. * @return */ public AMQPService removeOutboundRoute(String pattern, String amqpAddress) { this.delegate.removeOutboundRoute(pattern, amqpAddress); return this; } /** * Start the vertx-amqp-service */ public void start() { this.delegate.start(); } /** * Stop the vertx-amqp-service */ public void stop() { this.delegate.stop(); } public static AMQPService newInstance(io.vertx.ext.amqp.AMQPService arg) { return arg != null ? new AMQPService(arg) : null; } }
/* * Microsoft JDBC Driver for SQL Server * * Copyright(c) Microsoft Corporation All rights reserved. * * This program is made available under the terms of the MIT License. See the LICENSE file in the project root for more information. */ package com.microsoft.sqlserver.jdbc; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.MessageFormat; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * A simple implementation of the ISQLServerBulkRecord interface that can be used to read in the basic Java data types from a delimited file where * each line represents a row of data. */ public class SQLServerBulkCSVFileRecord implements ISQLServerBulkRecord, java.lang.AutoCloseable { /* * Class to represent the column metadata */ private class ColumnMetadata { String columnName; int columnType; int precision; int scale; DateTimeFormatter dateTimeFormatter = null; ColumnMetadata(String name, int type, int precision, int scale, DateTimeFormatter dateTimeFormatter) { columnName = name; columnType = type; this.precision = precision; this.scale = scale; this.dateTimeFormatter = dateTimeFormatter; } } /* * Resources associated with reading in the file */ private BufferedReader fileReader; private InputStreamReader sr; private FileInputStream fis; /* * Metadata to represent the columns in the file. Each column should be mapped to its corresponding position within the file (from position 1 and * onwards) */ private Map<Integer, ColumnMetadata> columnMetadata; /* * Current line of data to parse. */ private String currentLine = null; /* * Delimiter to parse lines with. */ private final String delimiter; /* * Contains all the column names if firstLineIsColumnNames is true */ private String[] columnNames = null; /* * Contains the format that java.sql.Types.TIMESTAMP_WITH_TIMEZONE data should be read in as. */ private DateTimeFormatter dateTimeFormatter = null; /* * Contains the format that java.sql.Types.TIME_WITH_TIMEZONE data should be read in as. */ private DateTimeFormatter timeFormatter = null; /* * Class name for logging. */ private static final String loggerClassName = "com.microsoft.sqlserver.jdbc.SQLServerBulkCSVFileRecord"; /* * Logger */ private static final java.util.logging.Logger loggerExternal = java.util.logging.Logger.getLogger(loggerClassName); /** * Creates a simple reader to parse data from a delimited file with the given encoding. * * @param fileToParse * File to parse data from * @param encoding * Charset encoding to use for reading the file, or NULL for the default encoding. * @param delimiter * Delimiter to used to separate each column * @param firstLineIsColumnNames * True if the first line of the file should be parsed as column names; false otherwise * @throws SQLServerException * If the arguments are invalid, there are any errors in reading the file, or the file is empty */ public SQLServerBulkCSVFileRecord(String fileToParse, String encoding, String delimiter, boolean firstLineIsColumnNames) throws SQLServerException { loggerExternal.entering(loggerClassName, "SQLServerBulkCSVFileRecord", new Object[] {fileToParse, encoding, delimiter, firstLineIsColumnNames}); if (null == fileToParse) { throwInvalidArgument("fileToParse"); } else if (null == delimiter) { throwInvalidArgument("delimiter"); } this.delimiter = delimiter; try { // Create the file reader fis = new FileInputStream(fileToParse); if (null == encoding || 0 == encoding.length()) { sr = new InputStreamReader(fis); } else { sr = new InputStreamReader(fis, encoding); } fileReader = new BufferedReader(sr); if (firstLineIsColumnNames) { currentLine = fileReader.readLine(); if (null != currentLine) { columnNames = currentLine.split(delimiter, -1); } } } catch (UnsupportedEncodingException unsupportedEncoding) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedEncoding")); throw new SQLServerException(form.format(new Object[] {encoding}), null, 0, null); } catch (Exception e) { throw new SQLServerException(null, e.getMessage(), null, 0, false); } columnMetadata = new HashMap<Integer, SQLServerBulkCSVFileRecord.ColumnMetadata>(); loggerExternal.exiting(loggerClassName, "SQLServerBulkCSVFileRecord"); } /** * Creates a simple reader to parse data from a CSV file with the given encoding. * * @param fileToParse * File to parse data from * @param encoding * Charset encoding to use for reading the file. * @param firstLineIsColumnNames * True if the first line of the file should be parsed as column names; false otherwise * @throws SQLServerException * If the arguments are invalid, there are any errors in reading the file, or the file is empty */ public SQLServerBulkCSVFileRecord(String fileToParse, String encoding, boolean firstLineIsColumnNames) throws SQLServerException { this(fileToParse, encoding, ",", firstLineIsColumnNames); } /** * Creates a simple reader to parse data from a CSV file with the default encoding. * * @param fileToParse * File to parse data from * @param firstLineIsColumnNames * True if the first line of the file should be parsed as column names; false otherwise * @throws SQLServerException * If the arguments are invalid, there are any errors in reading the file, or the file is empty */ public SQLServerBulkCSVFileRecord(String fileToParse, boolean firstLineIsColumnNames) throws SQLServerException { this(fileToParse, null, ",", firstLineIsColumnNames); } /** * Adds metadata for the given column in the file. * * @param positionInFile * Indicates which column the metadata is for. Columns start at 1. * @param name * Name for the column (optional if only using column ordinal in a mapping for SQLServerBulkCopy operation) * @param jdbcType * JDBC data type of the column * @param precision * Precision for the column (ignored for the appropriate data types) * @param scale * Scale for the column (ignored for the appropriate data types) * @param dateTimeFormatter * format to parse data that is sent * @throws SQLServerException * when an error occurs */ public void addColumnMetadata(int positionInFile, String name, int jdbcType, int precision, int scale, DateTimeFormatter dateTimeFormatter) throws SQLServerException { addColumnMetadataInternal(positionInFile, name, jdbcType, precision, scale, dateTimeFormatter); } /** * Adds metadata for the given column in the file. * * @param positionInFile * Indicates which column the metadata is for. Columns start at 1. * @param name * Name for the column (optional if only using column ordinal in a mapping for SQLServerBulkCopy operation) * @param jdbcType * JDBC data type of the column * @param precision * Precision for the column (ignored for the appropriate data types) * @param scale * Scale for the column (ignored for the appropriate data types) * @throws SQLServerException * when an error occurs */ public void addColumnMetadata(int positionInFile, String name, int jdbcType, int precision, int scale) throws SQLServerException { addColumnMetadataInternal(positionInFile, name, jdbcType, precision, scale, null); } /** * Adds metadata for the given column in the file. * * @param positionInFile * Indicates which column the metadata is for. Columns start at 1. * @param name * Name for the column (optional if only using column ordinal in a mapping for SQLServerBulkCopy operation) * @param jdbcType * JDBC data type of the column * @param precision * Precision for the column (ignored for the appropriate data types) * @param scale * Scale for the column (ignored for the appropriate data types) * @param dateTimeFormatter * format to parse data that is sent * @throws SQLServerException * when an error occurs */ void addColumnMetadataInternal(int positionInFile, String name, int jdbcType, int precision, int scale, DateTimeFormatter dateTimeFormatter) throws SQLServerException { loggerExternal.entering(loggerClassName, "addColumnMetadata", new Object[] {positionInFile, name, jdbcType, precision, scale}); String colName = ""; if (0 >= positionInFile) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidColumnOrdinal")); Object[] msgArgs = {positionInFile}; throw new SQLServerException(form.format(msgArgs), SQLState.COL_NOT_FOUND, DriverError.NOT_SET, null); } if (null != name) colName = name.trim(); else if ((columnNames != null) && (columnNames.length >= positionInFile)) colName = columnNames[positionInFile - 1]; if ((columnNames != null) && (positionInFile > columnNames.length)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidColumn")); Object[] msgArgs = {positionInFile}; throw new SQLServerException(form.format(msgArgs), SQLState.COL_NOT_FOUND, DriverError.NOT_SET, null); } checkDuplicateColumnName(positionInFile, name); switch (jdbcType) { /* * SQL Server supports numerous string literal formats for temporal types, hence sending them as varchar with approximate * precision(length) needed to send supported string literals. string literal formats supported by temporal types are available in MSDN * page on data types. */ case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: case microsoft.sql.Types.DATETIMEOFFSET: // The precision is just a number long enough to hold all types of temporal data, doesn't need to be exact precision. columnMetadata.put(positionInFile, new ColumnMetadata(colName, jdbcType, 50, scale, dateTimeFormatter)); break; // Redirect SQLXML as LONGNVARCHAR // SQLXML is not valid type in TDS case java.sql.Types.SQLXML: columnMetadata.put(positionInFile, new ColumnMetadata(colName, java.sql.Types.LONGNVARCHAR, precision, scale, dateTimeFormatter)); break; // Redirecting Float as Double based on data type mapping // https://msdn.microsoft.com/en-us/library/ms378878%28v=sql.110%29.aspx case java.sql.Types.FLOAT: columnMetadata.put(positionInFile, new ColumnMetadata(colName, java.sql.Types.DOUBLE, precision, scale, dateTimeFormatter)); break; // redirecting BOOLEAN as BIT case java.sql.Types.BOOLEAN: columnMetadata.put(positionInFile, new ColumnMetadata(colName, java.sql.Types.BIT, precision, scale, dateTimeFormatter)); break; default: columnMetadata.put(positionInFile, new ColumnMetadata(colName, jdbcType, precision, scale, dateTimeFormatter)); } loggerExternal.exiting(loggerClassName, "addColumnMetadata"); } /** * Set the format for reading in dates from the file. * * @param dateTimeFormat * format to parse data sent as java.sql.Types.TIMESTAMP_WITH_TIMEZONE */ public void setTimestampWithTimezoneFormat(String dateTimeFormat) { DriverJDBCVersion.checkSupportsJDBC42(); loggerExternal.entering(loggerClassName, "setTimestampWithTimezoneFormat", dateTimeFormat); this.dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimeFormat); loggerExternal.exiting(loggerClassName, "setTimestampWithTimezoneFormat"); } /** * Set the format for reading in dates from the file. * * @param dateTimeFormatter * format to parse data sent as java.sql.Types.TIMESTAMP_WITH_TIMEZONE */ public void setTimestampWithTimezoneFormat(DateTimeFormatter dateTimeFormatter) { loggerExternal.entering(loggerClassName, "setTimestampWithTimezoneFormat", new Object[] {dateTimeFormatter}); this.dateTimeFormatter = dateTimeFormatter; loggerExternal.exiting(loggerClassName, "setTimestampWithTimezoneFormat"); } /** * Set the format for reading in dates from the file. * * @param timeFormat * format to parse data sent as java.sql.Types.TIME_WITH_TIMEZONE */ public void setTimeWithTimezoneFormat(String timeFormat) { DriverJDBCVersion.checkSupportsJDBC42(); loggerExternal.entering(loggerClassName, "setTimeWithTimezoneFormat", timeFormat); this.timeFormatter = DateTimeFormatter.ofPattern(timeFormat); loggerExternal.exiting(loggerClassName, "setTimeWithTimezoneFormat"); } /** * Set the format for reading in dates from the file. * * @param dateTimeFormatter * format to parse data sent as java.sql.Types.TIME_WITH_TIMEZONE */ public void setTimeWithTimezoneFormat(DateTimeFormatter dateTimeFormatter) { loggerExternal.entering(loggerClassName, "setTimeWithTimezoneFormat", new Object[] {dateTimeFormatter}); this.timeFormatter = dateTimeFormatter; loggerExternal.exiting(loggerClassName, "setTimeWithTimezoneFormat"); } /** * Releases any resources associated with the file reader. * * @throws SQLServerException * when an error occurs */ public void close() throws SQLServerException { loggerExternal.entering(loggerClassName, "close"); // Ignore errors since we are only cleaning up here if (fileReader != null) try { fileReader.close(); } catch (Exception e) { } if (sr != null) try { sr.close(); } catch (Exception e) { } if (fis != null) try { fis.close(); } catch (Exception e) { } loggerExternal.exiting(loggerClassName, "close"); } public DateTimeFormatter getColumnDateTimeFormatter(int column) { return columnMetadata.get(column).dateTimeFormatter; } @Override public Set<Integer> getColumnOrdinals() { return columnMetadata.keySet(); } @Override public String getColumnName(int column) { return columnMetadata.get(column).columnName; } @Override public int getColumnType(int column) { return columnMetadata.get(column).columnType; } @Override public int getPrecision(int column) { return columnMetadata.get(column).precision; } @Override public int getScale(int column) { return columnMetadata.get(column).scale; } @Override public boolean isAutoIncrement(int column) { return false; } @Override public Object[] getRowData() throws SQLServerException { if (null == currentLine) return null; else { // Binary data may be corrupted // The limit in split() function should be a negative value, otherwise trailing empty strings are discarded. // Empty string is returned if there is no value. String[] data = currentLine.split(delimiter, -1); // Cannot go directly from String[] to Object[] and expect it to act as an array. Object[] dataRow = new Object[data.length]; Iterator<Entry<Integer, ColumnMetadata>> it = columnMetadata.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, ColumnMetadata> pair = it.next(); ColumnMetadata cm = pair.getValue(); // Reading a column not available in csv // positionInFile > number of columns retrieved after split if (data.length < pair.getKey() - 1) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidColumn")); Object[] msgArgs = {pair.getKey()}; throw new SQLServerException(form.format(msgArgs), SQLState.COL_NOT_FOUND, DriverError.NOT_SET, null); } // Source header has more columns than current line read if (columnNames != null && (columnNames.length > data.length)) { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_BulkCSVDataSchemaMismatch")); Object[] msgArgs = {}; throw new SQLServerException(form.format(msgArgs), SQLState.COL_NOT_FOUND, DriverError.NOT_SET, null); } try { if (0 == data[pair.getKey() - 1].length()) { dataRow[pair.getKey() - 1] = null; continue; } switch (cm.columnType) { /* * Both BCP and BULK INSERT considers double quotes as part of the data and throws error if any data (say "10") is to be * inserted into an numeric column. Our implementation does the same. */ case java.sql.Types.INTEGER: { // Formatter to remove the decimal part as SQL Server floors the decimal in integer types DecimalFormat decimalFormatter = new DecimalFormat("#"); String formatedfInput = decimalFormatter.format(Double.parseDouble(data[pair.getKey() - 1])); dataRow[pair.getKey() - 1] = Integer.valueOf(formatedfInput); break; } case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: { // Formatter to remove the decimal part as SQL Server floors the decimal in integer types DecimalFormat decimalFormatter = new DecimalFormat("#"); String formatedfInput = decimalFormatter.format(Double.parseDouble(data[pair.getKey() - 1])); dataRow[pair.getKey() - 1] = Short.valueOf(formatedfInput); break; } case java.sql.Types.BIGINT: { BigDecimal bd = new BigDecimal(data[pair.getKey() - 1].trim()); try { dataRow[pair.getKey() - 1] = bd.setScale(0, BigDecimal.ROUND_DOWN).longValueExact(); } catch (ArithmeticException ex) { String value = "'" + data[pair.getKey() - 1] + "'"; MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue")); throw new SQLServerException(form.format(new Object[] {value, JDBCType.of(cm.columnType)}), null, 0, null); } break; } case java.sql.Types.DECIMAL: case java.sql.Types.NUMERIC: { BigDecimal bd = new BigDecimal(data[pair.getKey() - 1].trim()); dataRow[pair.getKey() - 1] = bd.setScale(cm.scale, RoundingMode.HALF_UP); break; } case java.sql.Types.BIT: { // "true" => 1, "false" => 0 // Any non-zero value (integer/double) => 1, 0/0.0 => 0 try { dataRow[pair.getKey() - 1] = (0 == Double.parseDouble(data[pair.getKey() - 1])) ? Boolean.FALSE : Boolean.TRUE; } catch (NumberFormatException e) { dataRow[pair.getKey() - 1] = Boolean.parseBoolean(data[pair.getKey() - 1]); } break; } case java.sql.Types.REAL: { dataRow[pair.getKey() - 1] = Float.parseFloat(data[pair.getKey() - 1]); break; } case java.sql.Types.DOUBLE: { dataRow[pair.getKey() - 1] = Double.parseDouble(data[pair.getKey() - 1]); break; } case java.sql.Types.BINARY: case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: case java.sql.Types.BLOB: { /* * For binary data, the value in file may or may not have the '0x' prefix. We will try to match our implementation with * 'BULK INSERT' except that we will allow 0x prefix whereas 'BULK INSERT' command does not allow 0x prefix. A BULK INSERT * example: A sample csv file containing data for 2 binary columns and 1 row: 61,62 Table definition: create table t1(c1 * varbinary(10), c2 varbinary(10)) BULK INSERT command: bulk insert t1 from 'C:\in.csv' * with(DATAFILETYPE='char',firstrow=1,FIELDTERMINATOR=',') select * from t1 shows 1 row with columns: 0x61, 0x62 */ // Strip off 0x if present. String binData = data[pair.getKey() - 1].trim(); if (binData.startsWith("0x") || binData.startsWith("0X")) { dataRow[pair.getKey() - 1] = binData.substring(2); } else { dataRow[pair.getKey() - 1] = binData; } break; } case 2013: // java.sql.Types.TIME_WITH_TIMEZONE { DriverJDBCVersion.checkSupportsJDBC42(); OffsetTime offsetTimeValue = null; // The per-column DateTimeFormatter gets priority. if (null != cm.dateTimeFormatter) offsetTimeValue = OffsetTime.parse(data[pair.getKey() - 1], cm.dateTimeFormatter); else if (timeFormatter != null) offsetTimeValue = OffsetTime.parse(data[pair.getKey() - 1], timeFormatter); else offsetTimeValue = OffsetTime.parse(data[pair.getKey() - 1]); dataRow[pair.getKey() - 1] = offsetTimeValue; break; } case 2014: // java.sql.Types.TIMESTAMP_WITH_TIMEZONE { DriverJDBCVersion.checkSupportsJDBC42(); OffsetDateTime offsetDateTimeValue = null; // The per-column DateTimeFormatter gets priority. if (null != cm.dateTimeFormatter) offsetDateTimeValue = OffsetDateTime.parse(data[pair.getKey() - 1], cm.dateTimeFormatter); else if (dateTimeFormatter != null) offsetDateTimeValue = OffsetDateTime.parse(data[pair.getKey() - 1], dateTimeFormatter); else offsetDateTimeValue = OffsetDateTime.parse(data[pair.getKey() - 1]); dataRow[pair.getKey() - 1] = offsetDateTimeValue; break; } case java.sql.Types.NULL: { dataRow[pair.getKey() - 1] = null; break; } case java.sql.Types.DATE: case java.sql.Types.CHAR: case java.sql.Types.NCHAR: case java.sql.Types.VARCHAR: case java.sql.Types.NVARCHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.LONGNVARCHAR: case java.sql.Types.CLOB: default: { // The string is copied as is. /* * Handling double quotes: Both BCP (without a format file) and BULK INSERT behaves the same way for double quotes. They * treat double quotes as part of the data. For a CSV file as follows, data is inserted as is: ""abc"" "abc" abc a"b"c * a""b""c Excel on the other hand, shows data as follows. It strips off beginning and ending quotes, and sometimes quotes * get messed up. When the same CSV is saved from Excel again, Excel adds additional quotes. abc"" abc abc a"b"c a""b""c * In our implementation we will match the behavior with BCP and BULK INSERT. BCP command: bcp table1 in in.csv -c -t , -r * 0x0A -S localhost -U sa -P <pwd> BULK INSERT command: bulk insert table1 from 'in.csv' with (FIELDTERMINATOR=',') * * Handling delimiters in data: Excel allows comma in data when data is surrounded with quotes. For example, * "Hello, world" is treated as one cell. BCP and BULK INSERT deos not allow field terminators in data: * https://technet.microsoft.com/en-us/library/aa196735%28v=sql.80%29.aspx?f=255&MSPPError=-2147217396 */ dataRow[pair.getKey() - 1] = data[pair.getKey() - 1]; break; } } } catch (IllegalArgumentException e) { String value = "'" + data[pair.getKey() - 1] + "'"; MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue")); throw new SQLServerException(form.format(new Object[] {value, JDBCType.of(cm.columnType)}), null, 0, null); } catch (ArrayIndexOutOfBoundsException e) { throw new SQLServerException(SQLServerException.getErrString("R_BulkCSVDataSchemaMismatch"), null); } } return dataRow; } } @Override public boolean next() throws SQLServerException { try { currentLine = fileReader.readLine(); } catch (IOException e) { throw new SQLServerException(null, e.getMessage(), null, 0, false); } return (null != currentLine); } /* * Helper method to throw a SQLServerExeption with the invalidArgument message and given argument. */ private void throwInvalidArgument(String argument) throws SQLServerException { MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidArgument")); Object[] msgArgs = {argument}; SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), null, false); } /* * Method to throw a SQLServerExeption for duplicate column names */ private void checkDuplicateColumnName(int positionInFile, String colName) throws SQLServerException { if (null != colName && colName.trim().length() != 0) { for (Entry<Integer, ColumnMetadata> entry : columnMetadata.entrySet()) { // duplicate check is not performed in case of same positionInFile value if (null != entry && entry.getKey() != positionInFile) { if (null != entry.getValue() && colName.trim().equalsIgnoreCase(entry.getValue().columnName)) { throw new SQLServerException(SQLServerException.getErrString("R_BulkCSVDataDuplicateColumn"), null); } } } } } }
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]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.helger.web.fileupload.parse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Locale; import java.util.NoSuchElementException; import javax.annotation.CheckForSigned; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.collection.impl.CommonsArrayList; import com.helger.commons.collection.impl.ICommonsList; import com.helger.commons.collection.impl.ICommonsMap; import com.helger.commons.string.StringParser; import com.helger.servlet.request.RequestHelper; import com.helger.web.fileupload.IFileItem; import com.helger.web.fileupload.IFileItemFactory; import com.helger.web.fileupload.IFileItemHeaders; import com.helger.web.fileupload.IFileItemHeadersSupport; import com.helger.web.fileupload.IFileItemIterator; import com.helger.web.fileupload.IFileItemStream; import com.helger.web.fileupload.IRequestContext; import com.helger.web.fileupload.exception.FileUploadException; import com.helger.web.fileupload.exception.FileUploadIOException; import com.helger.web.fileupload.exception.IOFileUploadException; import com.helger.web.fileupload.exception.InvalidContentTypeException; import com.helger.web.fileupload.exception.SizeLimitExceededException; import com.helger.web.fileupload.io.AbstractLimitedInputStream; import com.helger.web.multipart.MultipartProgressNotifier; import com.helger.web.multipart.MultipartStream; import com.helger.web.progress.IProgressListener; /** * <p> * High level API for processing file uploads. * </p> * <p> * This class handles multiple files per single HTML widget, sent using * <code>multipart/mixed</code> encoding type, as specified by * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. * </p> * <p> * How the data for individual parts is stored is determined by the factory used * to create them; a given part may be in memory, on disk, or somewhere else. * </p> * * @author <a href="mailto:[email protected]">Rafal Krzewski</a> * @author <a href="mailto:[email protected]">Daniel Rall</a> * @author <a href="mailto:[email protected]">Jason van Zyl</a> * @author <a href="mailto:[email protected]">John McNally</a> * @author <a href="mailto:[email protected]">Martin Cooper</a> * @author Sean C. Sullivan * @version $Id: FileUploadBase.java 963609 2010-07-13 06:56:47Z jochen $ */ public abstract class AbstractFileUploadBase { private static final Logger LOGGER = LoggerFactory.getLogger (AbstractFileUploadBase.class); /** * The maximum size permitted for the complete request, as opposed to * {@link #m_nFileSizeMax}. A value of -1 indicates no maximum. */ private long m_nSizeMax = -1; /** * The maximum size permitted for a single uploaded file, as opposed to * {@link #m_nSizeMax}. A value of -1 indicates no maximum. */ private long m_nFileSizeMax = -1; /** * The content encoding to use when reading part headers. */ private String m_sHeaderEncoding; /** * The progress listener. */ private IProgressListener m_aListener; public AbstractFileUploadBase () {} /** * Returns the factory class used when creating file items. * * @return The factory class for new file items. */ @Nonnull public abstract IFileItemFactory getFileItemFactory (); /** * Returns the maximum allowed size of a complete request, as opposed to * {@link #getFileSizeMax()}. * * @return The maximum allowed size, in bytes. The default value of -1 * indicates, that there is no limit. * @see #setSizeMax(long) */ @CheckForSigned public long getSizeMax () { return m_nSizeMax; } /** * Sets the maximum allowed size of a complete request, as opposed to * {@link #setFileSizeMax(long)}. * * @param nSizeMax * The maximum allowed size, in bytes. The default value of -1 * indicates, that there is no limit. * @see #getSizeMax() */ public void setSizeMax (final long nSizeMax) { m_nSizeMax = nSizeMax; } /** * Returns the maximum allowed size of a single uploaded file, as opposed to * {@link #getSizeMax()}. * * @see #setFileSizeMax(long) * @return Maximum size of a single uploaded file. */ @CheckForSigned public long getFileSizeMax () { return m_nFileSizeMax; } /** * Sets the maximum allowed size of a single uploaded file, as opposed to * {@link #getSizeMax()}. * * @see #getFileSizeMax() * @param nFileSizeMax * Maximum size of a single uploaded file. */ public void setFileSizeMax (final long nFileSizeMax) { m_nFileSizeMax = nFileSizeMax; } /** * Retrieves the character encoding used when reading the headers of an * individual part. When not specified, or <code>null</code>, the request * encoding is used. If that is also not specified, or <code>null</code>, the * platform default encoding is used. * * @return The encoding used to read part headers. */ @Nullable public String getHeaderEncoding () { return m_sHeaderEncoding; } /** * Specifies the character encoding to be used when reading the headers of * individual part. When not specified, or <code>null</code>, the request * encoding is used. If that is also not specified, or <code>null</code>, the * platform default encoding is used. * * @param sHeaderEncoding * The encoding used to read part headers. */ public void setHeaderEncoding (@Nullable final String sHeaderEncoding) { m_sHeaderEncoding = sHeaderEncoding; } /** * Returns the progress listener. * * @return The progress listener, if any. Maybe <code>null</code>. */ @Nullable public IProgressListener getProgressListener () { return m_aListener; } /** * Sets the progress listener. * * @param aListener * The progress listener, if any. May be to <code>null</code>. */ public void setProgressListener (@Nullable final IProgressListener aListener) { m_aListener = aListener; } /** * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> * compliant <code>multipart/form-data</code> stream. * * @param aCtx * The context for the request to be parsed. * @return An iterator to instances of <code>FileItemStream</code> parsed from * the request, in the order that they were transmitted. * @throws FileUploadException * if there are problems reading/parsing the request or storing files. * @throws IOException * An I/O error occurred. This may be a network error while * communicating with the client or a problem while storing the * uploaded content. */ @Nonnull public IFileItemIterator getItemIterator (@Nonnull final IRequestContext aCtx) throws FileUploadException, IOException { return new FileItemIterator (aCtx); } /** * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> * compliant <code>multipart/form-data</code> stream. * * @param aCtx * The context for the request to be parsed. * @return A list of <code>FileItem</code> instances parsed from the request, * in the order that they were transmitted. * @throws FileUploadException * if there are problems reading/parsing the request or storing files. */ @Nonnull @ReturnsMutableCopy public ICommonsList <IFileItem> parseRequest (@Nonnull final IRequestContext aCtx) throws FileUploadException { final ICommonsList <IFileItem> aItems = new CommonsArrayList <> (); boolean bSuccessful = false; try { final IFileItemIterator aItemIter = getItemIterator (aCtx); final IFileItemFactory aFileItemFactory = getFileItemFactory (); if (aFileItemFactory == null) throw new IllegalStateException ("No FileItemFactory has been set."); while (aItemIter.hasNext ()) { final IFileItemStream aFileItemStream = aItemIter.next (); // Don't use getName() here to prevent an InvalidFileNameException. final IFileItem aFileItem = aFileItemFactory.createItem (aFileItemStream.getFieldName (), aFileItemStream.getContentType (), aFileItemStream.isFormField (), aFileItemStream.getNameUnchecked ()); aItems.add (aFileItem); try (final InputStream aIS = aFileItemStream.openStream (); final OutputStream aOS = aFileItem.getOutputStream ()) { final byte [] aBuffer = new byte [8192]; int nBytesRead; // potentially blocking read while ((nBytesRead = aIS.read (aBuffer, 0, aBuffer.length)) > -1) { aOS.write (aBuffer, 0, nBytesRead); } } catch (final FileUploadIOException ex) { throw (FileUploadException) ex.getCause (); } catch (final IOException ex) { throw new IOFileUploadException ("Processing of " + RequestHelper.MULTIPART_FORM_DATA + " request failed. " + ex.getMessage (), ex); } if (aFileItem instanceof IFileItemHeadersSupport) { final IFileItemHeaders aFileItemHeaders = aFileItemStream.getHeaders (); ((IFileItemHeadersSupport) aFileItem).setHeaders (aFileItemHeaders); } } bSuccessful = true; return aItems; } catch (final FileUploadIOException ex) { throw (FileUploadException) ex.getCause (); } catch (final IOException ex) { throw new FileUploadException (ex.getMessage (), ex); } finally { if (!bSuccessful) { // Delete all file items for (final IFileItem aFileItem : aItems) { try { aFileItem.delete (); } catch (final Exception ex) { // ignore it if (LOGGER.isErrorEnabled ()) LOGGER.error ("Failed to delete fileItem " + aFileItem, ex); } } } } } /** * Retrieves the boundary from the <code>Content-type</code> header. * * @param sContentType * The value of the content type header from which to extract the * boundary value. * @return The boundary, as a byte array. */ @Nullable protected byte [] getBoundary (@Nonnull final String sContentType) { // Parameter parser can handle null input final ICommonsMap <String, String> aParams = new ParameterParser ().setLowerCaseNames (true) .parse (sContentType, new char [] { ';', ',' }); final String sBoundaryStr = aParams.get ("boundary"); if (sBoundaryStr == null) return null; return sBoundaryStr.getBytes (StandardCharsets.ISO_8859_1); } /** * Retrieves the file name from the <code>Content-disposition</code> header. * * @param aHeaders * The HTTP headers object. * @return The file name for the current <code>encapsulation</code>. */ @Nullable protected String getFileName (@Nonnull final IFileItemHeaders aHeaders) { return _getFilename (aHeaders.getHeaderContentDisposition ()); } /** * Returns the given content-disposition headers file name. * * @param sContentDisposition * The content-disposition headers value. * @return The file name or <code>null</code>. */ @Nullable private static String _getFilename (@Nullable final String sContentDisposition) { String sFilename = null; if (sContentDisposition != null) { final String sContentDispositionLC = sContentDisposition.toLowerCase (Locale.US); if (sContentDispositionLC.startsWith (RequestHelper.FORM_DATA) || sContentDispositionLC.startsWith (RequestHelper.ATTACHMENT)) { // Parameter parser can handle null input final ICommonsMap <String, String> aParams = new ParameterParser ().setLowerCaseNames (true).parse (sContentDisposition, ';'); if (aParams.containsKey ("filename")) { sFilename = aParams.get ("filename"); if (sFilename != null) { sFilename = sFilename.trim (); } else { // Even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. sFilename = ""; } } } } return sFilename; } /** * Retrieves the field name from the <code>Content-disposition</code> header. * * @param aFileItemHeaders * A <code>Map</code> containing the HTTP request headers. * @return The field name for the current <code>encapsulation</code>. */ @Nullable protected String getFieldName (@Nonnull final IFileItemHeaders aFileItemHeaders) { return _getFieldName (aFileItemHeaders.getHeaderContentDisposition ()); } /** * Returns the field name, which is given by the content-disposition header. * * @param sContentDisposition * The content-dispositions header value. * @return The field name */ @Nullable private static String _getFieldName (@Nullable final String sContentDisposition) { String sFieldName = null; if (sContentDisposition != null && sContentDisposition.toLowerCase (Locale.US).startsWith (RequestHelper.FORM_DATA)) { // Parameter parser can handle null input final ICommonsMap <String, String> aParams = new ParameterParser ().setLowerCaseNames (true).parse (sContentDisposition, ';'); sFieldName = aParams.get ("name"); if (sFieldName != null) sFieldName = sFieldName.trim (); } return sFieldName; } /** * <p> * Parses the <code>header-part</code> and returns as key/value pairs. * <p> * If there are multiple headers of the same names, the name will map to a * comma-separated list containing the values. * * @param sHeaderPart * The <code>header-part</code> of the current * <code>encapsulation</code>. * @return A <code>Map</code> containing the parsed HTTP request headers. */ @Nonnull protected IFileItemHeaders getParsedHeaders (@Nonnull final String sHeaderPart) { final int nLen = sHeaderPart.length (); final FileItemHeaders aHeaders = createFileItemHeaders (); int nStart = 0; for (;;) { int nEnd = _parseEndOfLine (sHeaderPart, nStart); if (nStart == nEnd) { break; } final StringBuilder aHeader = new StringBuilder (sHeaderPart.substring (nStart, nEnd)); nStart = nEnd + 2; while (nStart < nLen) { int nNonWs = nStart; while (nNonWs < nLen) { final char c = sHeaderPart.charAt (nNonWs); if (c != ' ' && c != '\t') break; ++nNonWs; } if (nNonWs == nStart) break; // Continuation line found nEnd = _parseEndOfLine (sHeaderPart, nNonWs); aHeader.append (' ').append (sHeaderPart.substring (nNonWs, nEnd)); nStart = nEnd + 2; } _parseHeaderLine (aHeaders, aHeader.toString ()); } return aHeaders; } /** * Creates a new instance of {@link IFileItemHeaders}. * * @return The new instance. */ @Nonnull protected FileItemHeaders createFileItemHeaders () { return new FileItemHeaders (); } /** * Skips bytes until the end of the current line. * * @param sHeaderPart * The headers, which are being parsed. * @param nEnd * Index of the last byte, which has yet been processed. * @return Index of the \r\n sequence, which indicates end of line. */ private static int _parseEndOfLine (@Nonnull final String sHeaderPart, final int nEnd) { int nIndex = nEnd; for (;;) { final int nOffset = sHeaderPart.indexOf ('\r', nIndex); if (nOffset == -1 || nOffset + 1 >= sHeaderPart.length ()) throw new IllegalStateException ("Expected headers to be terminated by an empty line."); if (sHeaderPart.charAt (nOffset + 1) == '\n') return nOffset; nIndex = nOffset + 1; } } /** * Reads the next header line. * * @param aHeaders * String with all headers. * @param sHeader * Map where to store the current header. */ private static void _parseHeaderLine (@Nonnull final FileItemHeaders aHeaders, @Nonnull final String sHeader) { final int nColonOffset = sHeader.indexOf (':'); if (nColonOffset == -1) { // This header line is malformed, skip it. if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Found malformed HTTP header line '" + sHeader + "'"); return; } final String sHeaderName = sHeader.substring (0, nColonOffset).trim (); final String sHeaderValue = sHeader.substring (sHeader.indexOf (':') + 1).trim (); aHeaders.addHeader (sHeaderName, sHeaderValue); } /** * The iterator, which is returned by * {@link AbstractFileUploadBase#getItemIterator(IRequestContext)}. */ private final class FileItemIterator implements IFileItemIterator { /** * The multi part stream to process. */ private final MultipartStream m_aMulti; /** * The notifier, which used for triggering the {@link IProgressListener}. */ private final MultipartProgressNotifier m_aNotifier; /** * The boundary, which separates the various parts. */ private final byte [] m_aBoundary; /** * The item, which we currently process. */ private FileItemStream m_aCurrentItem; /** * The current items field name. */ private String m_sCurrentFieldName; /** * Whether we are currently skipping the preamble. */ private boolean m_bSkipPreamble; /** * Whether the current item may still be read. */ private boolean m_bItemValid; /** * Whether we have seen the end of the file. */ private boolean m_bEOF; /** * Creates a new instance. * * @param aCtx * The request context. * @throws FileUploadException * An error occurred while parsing the request. * @throws IOException * An I/O error occurred. */ FileItemIterator (@Nonnull final IRequestContext aCtx) throws FileUploadException, IOException { ValueEnforcer.notNull (aCtx, "RequestContext"); final String sContentType = aCtx.getContentType (); if (!RequestHelper.isMultipartContent (sContentType)) { throw new InvalidContentTypeException ("the request doesn't contain a " + RequestHelper.MULTIPART_FORM_DATA + " or " + RequestHelper.MULTIPART_MIXED + " stream, content-type header is '" + sContentType + "'"); } InputStream aIS = aCtx.getInputStream (); final long nContentLength = aCtx.getContentLength (); if (m_nSizeMax >= 0) { if (nContentLength < 0) { aIS = new AbstractLimitedInputStream (aIS, m_nSizeMax) { @Override protected void onLimitExceeded (final long nSizeMax, final long nCount) throws IOException { final FileUploadException ex = new SizeLimitExceededException ("the request was rejected because its size (" + nCount + ") exceeds the configured maximum (" + nSizeMax + ")", nCount, nSizeMax); throw new FileUploadIOException (ex); } }; } else { // Request size is known if (m_nSizeMax >= 0 && nContentLength > m_nSizeMax) { throw new SizeLimitExceededException ("the request was rejected because its size (" + nContentLength + ") exceeds the configured maximum (" + m_nSizeMax + ")", nContentLength, m_nSizeMax); } } } String sHeaderEncoding = m_sHeaderEncoding; if (sHeaderEncoding == null) sHeaderEncoding = aCtx.getCharacterEncoding (); m_aBoundary = getBoundary (sContentType); if (m_aBoundary == null) throw new FileUploadException ("the request was rejected because no multipart boundary was found"); // Content length may be -1 if not specified by sender m_aNotifier = new MultipartProgressNotifier (m_aListener, nContentLength); m_aMulti = new MultipartStream (aIS, m_aBoundary, m_aNotifier); m_aMulti.setHeaderEncoding (sHeaderEncoding); m_bSkipPreamble = true; _findNextItem (); } /** * Called for finding the next item, if any. * * @return True, if an next item was found, otherwise false. * @throws IOException * An I/O error occurred. */ private boolean _findNextItem () throws IOException { if (m_bEOF) return false; if (m_aCurrentItem != null) { m_aCurrentItem.close (); m_aCurrentItem = null; } for (;;) { boolean bNextPart; if (m_bSkipPreamble) bNextPart = m_aMulti.skipPreamble (); else bNextPart = m_aMulti.readBoundary (); if (!bNextPart) { if (m_sCurrentFieldName == null) { // Outer multipart terminated -> No more data m_bEOF = true; return false; } // Inner multipart terminated -> Return to parsing the outer m_aMulti.setBoundary (m_aBoundary); m_sCurrentFieldName = null; continue; } final IFileItemHeaders aFileItemHeaders = getParsedHeaders (m_aMulti.readHeaders ()); final String sSubContentType = aFileItemHeaders.getHeaderContentType (); if (m_sCurrentFieldName == null) { // We're parsing the outer multipart final String sFieldName = getFieldName (aFileItemHeaders); if (sFieldName != null) { if (sSubContentType != null && sSubContentType.toLowerCase (Locale.US).startsWith (RequestHelper.MULTIPART_MIXED)) { m_sCurrentFieldName = sFieldName; // Multiple files associated with this field name final byte [] aSubBoundary = getBoundary (sSubContentType); m_aMulti.setBoundary (aSubBoundary); m_bSkipPreamble = true; continue; } final String sFilename = getFileName (aFileItemHeaders); m_aCurrentItem = new FileItemStream (sFilename, sFieldName, sSubContentType, sFilename == null, _getContentLength (aFileItemHeaders), m_aMulti, m_nFileSizeMax); m_aNotifier.onNextFileItem (); m_bItemValid = true; return true; } } else { final String sFilename = getFileName (aFileItemHeaders); if (sFilename != null) { m_aCurrentItem = new FileItemStream (sFilename, m_sCurrentFieldName, sSubContentType, false, _getContentLength (aFileItemHeaders), m_aMulti, m_nFileSizeMax); m_aNotifier.onNextFileItem (); m_bItemValid = true; return true; } } m_aMulti.discardBodyData (); } } private long _getContentLength (@Nonnull final IFileItemHeaders aHeaders) { return StringParser.parseLong (aHeaders.getHeaderContentLength (), -1L); } /** * Returns, whether another instance of {@link IFileItemStream} is * available. * * @throws FileUploadException * Parsing or processing the file item failed. * @throws IOException * Reading the file item failed. * @return True, if one or more additional file items are available, * otherwise false. */ public boolean hasNext () throws FileUploadException, IOException { if (m_bEOF) return false; if (m_bItemValid) return true; return _findNextItem (); } /** * Returns the next available {@link IFileItemStream}. * * @throws NoSuchElementException * No more items are available. Use {@link #hasNext()} to prevent * this exception. * @throws FileUploadException * Parsing or processing the file item failed. * @throws IOException * Reading the file item failed. * @return FileItemStream instance, which provides access to the next file * item. */ @Nonnull public IFileItemStream next () throws FileUploadException, IOException { if (m_bEOF || (!m_bItemValid && !hasNext ())) throw new NoSuchElementException (); m_bItemValid = false; return m_aCurrentItem; } } }
/* * Copyright 2010 the original author or 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.hs.mail.smtp.message; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.text.DateFormat; import java.util.Date; import java.util.Set; import java.util.TreeSet; import java.util.Vector; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MailDateFormat; import javax.mail.internet.MimeMessage; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import com.hs.mail.container.config.Config; import com.hs.mail.imap.message.MailMessage; import com.hs.mail.smtp.SmtpException; /** * * @author Won Chul Doh * @since May 31, 2010 * */ public class SmtpMessage implements Serializable { private static final long serialVersionUID = 7983042396136261548L; private static final DateFormat SMTP_DATE_FORMAT = new MailDateFormat(); public static final int LOCAL = 1; public static final int REMOTE = 2; public static final int ALL = 3; /** * The number of mails generated. Access needs to be synchronized for * thread safety and to ensure that all threads see the latest value. */ private static long count; private String name; private int node; /** * The sender of this message. */ private MailAddress from; /** * The remained recipients of this message. */ private Set<Recipient> recipients; /** * The retry count. */ private int retryCount = 0; /** * The last time this message was updated. */ private Date lastUpdate = new Date(); /** * The error message, if any, associated with this mail. */ private transient String errorMessage = ""; /** * The MailMessage that holds the mail data. */ private transient MailMessage mailMessage = null; /** * The time this message was created. */ private transient long time; /* * The identifiers of recipient who has received this mail. */ private transient Vector<Long> delivered; public SmtpMessage(MailAddress from, int node) { this.time = System.currentTimeMillis(); this.from = from; this.recipients = new TreeSet<Recipient>(); this.name = getId(); this.node = node; this.errorMessage = ""; } public SmtpMessage(MailAddress from) { this(from, ALL); } public String getName() { return name; } public int getNode() { return node; } public void setNode(int node) { this.node = node; } public MailAddress getFrom() { return from; } public Set<Recipient> getRecipients() { return recipients; } public void addRecipient(Recipient recipient) { recipients.add(recipient); } public int getRecipientsSize() { return recipients.size(); } public long getTime() { return time; } public int getRetryCount() { return retryCount; } public void setRetryCount(int retryCount) { this.retryCount = retryCount; } public String getDate() { return SMTP_DATE_FORMAT.format(new Date(time)); } public Date getLastUpdate() { return lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } public String getErrorMessage() { return errorMessage; } public boolean isNotificationMessage() { return "".equals(getFrom().getMailbox()); } public void appendErrorMessage(String errorMessage) { if (this.errorMessage == null) this.errorMessage = errorMessage; else this.errorMessage += errorMessage; } public void delivered(long soleRecipientID) { if (delivered == null) { delivered = new Vector<Long>(); } delivered.add(soleRecipientID); } public Vector<Long> getDelivered() { return delivered; } public File getDataFile() { return new File(Config.getSpoolDirectory(), getName()); } private File getControlFile() { return new File(Config.getSpoolDirectory(), getName() + ".control"); } public void setContent(InputStream is) throws IOException { OutputStream os = null; try { os = new FileOutputStream(getDataFile()); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); } } public void setContent(MimeMessage msg) throws IOException, MessagingException { OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(getDataFile())); msg.writeTo(os); } finally { IOUtils.closeQuietly(os); } } public void store() throws IOException { File file = getControlFile(); ObjectOutputStream os = null; try { OutputStream out = new BufferedOutputStream(new FileOutputStream( file), 1024 * 4); os = new ObjectOutputStream(out); os.writeObject(this); os.flush(); } finally { IOUtils.closeQuietly(os); } } public void moveTo(File directory) throws IOException { FileUtils.moveFileToDirectory(getControlFile(), directory, false); FileUtils.moveFileToDirectory(getDataFile(), directory, false); } public void createTrigger() throws IOException { File file = new File(Config.getSnapshotDirectory(), getName()); file.createNewFile(); } public MailMessage getMailMessage() throws IOException { if (mailMessage == null) { mailMessage = MailMessage.createMailMessage(getDataFile()); } return mailMessage; } public MimeMessage getMimeMessage() throws MessagingException { Session session = Session.getInstance(System.getProperties(), null); InputStream is = null; try { is = new FileInputStream(getDataFile()); return new MimeMessage(session, is); } catch (FileNotFoundException e) { throw new MessagingException(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } } public void dispose() { File file = getDataFile(); if (file.exists()) { if (file.delete()) { file = getControlFile(); if (file.exists()) { file.delete(); } } } } private String getId() { File d = Config.getSpoolDirectory(); File f; String id; do { f = new File(d, (id = _getId())); } while (f.exists()); return id; } private String _getId() { long localCount = -1; synchronized (SmtpMessage.class) { localCount = count++; } return new StringBuffer(64) .append(time) .append("-") .append(localCount) .toString(); } public static SmtpMessage readMessage(String name) throws SmtpException { File dir = Config.getSpoolDirectory(); File file = new File(dir, name + ".control"); ObjectInputStream is = null; try { InputStream in = new BufferedInputStream(new FileInputStream(file), 1024); is = new ObjectInputStream(in); SmtpMessage message = (SmtpMessage) is.readObject(); return message; } catch (Exception e) { throw new SmtpException("Error while reading message file: " + file); } finally { IOUtils.closeQuietly(is); } } }
package org.statsbiblioteket.digital_pligtaflevering_aviser.ui.panels; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.server.ThemeResource; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.Table; import com.vaadin.ui.VerticalLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.statsbiblioteket.digital_pligtaflevering_aviser.ui.datamodel.DeliveryInformationComponent; import org.statsbiblioteket.digital_pligtaflevering_aviser.ui.datamodel.UiDataConverter; import org.statsbiblioteket.digital_pligtaflevering_aviser.ui.datamodel.DeliveryInformationComponent.ValidationState; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import static org.statsbiblioteket.digital_pligtaflevering_aviser.ui.datamodel.DeliveryInformationComponent.ValidationState.DATE; /** * EventDatePanel contains a table which can be used for viewing deliveries plotted into a month-layout */ public class EventDatePanel extends VerticalLayout { public static final String WEEKNO = "Weekno"; private static SimpleDateFormat sdf = new SimpleDateFormat("MMM"); private final Map<Integer, String> dayMap; private Logger log = LoggerFactory.getLogger(getClass()); private CheckBox checkbox; private Table table; private static Button.ClickListener buttonListener; private Date month; public EventDatePanel() { dayMap = new LinkedHashMap<Integer, String>();//LinkedHashMap to keep insertion order dayMap.put(Calendar.MONDAY,"Mon"); dayMap.put(Calendar.TUESDAY,"Tue"); dayMap.put(Calendar.WEDNESDAY,"Wed"); dayMap.put(Calendar.THURSDAY,"Thu"); dayMap.put(Calendar.FRIDAY,"Fri"); dayMap.put(Calendar.SATURDAY,"Sat"); dayMap.put(Calendar.SUNDAY,"Sun"); checkbox = new CheckBox("Visible", true); checkbox.setEnabled(false); // Bind a table to it table = new Table("", null); table.addContainerProperty(WEEKNO, String.class, null); for (String day : dayMap.values()) { table.addContainerProperty(day, List.class, null); table.addGeneratedColumn(day, new EventDatePanel.FieldGenerator()); } table.setSortContainerPropertyId(WEEKNO); table.setWidth("100%"); table.setHeightUndefined(); table.setPageLength(0); table.setSelectable(true); table.setImmediate(true); this.addComponent(checkbox); this.addComponent(table); } public void addClickListener(Button.ClickListener buttonListener) { this.buttonListener = buttonListener; } /** * Set the month to be viewed in the panel * @param month */ public void setMonth(Date month) { this.month = month; table.setCaption(sdf.format(month)); } /** * Set the content to be viewed in the calendar * @param delStat */ public void setInfo(List<DeliveryInformationComponent> delStat) { table.removeAllItems(); Item newItemId = null; Calendar calendar = Calendar.getInstance(); calendar.setTime(month); calendar.setFirstDayOfWeek(Calendar.MONDAY); int lowerDatelimit = calendar.getActualMinimum(Calendar.DAY_OF_MONTH); int higherDatelimit = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); for(int i=lowerDatelimit; i<=higherDatelimit; i++) { Calendar day = Calendar.getInstance(); day.setFirstDayOfWeek(Calendar.MONDAY); day.setTime(calendar.getTime()); day.add(Calendar.DAY_OF_YEAR,i-1); String weekday_no = day.get(Calendar.WEEK_OF_YEAR)+""; String weekday_name = dayMap.get(day.get(Calendar.DAY_OF_WEEK)); if (table.getItem(weekday_no) == null) { newItemId = table.addItem(weekday_no); newItemId.getItemProperty(WEEKNO).setValue(weekday_no); } ArrayList itemList = new ArrayList(); itemList.add(new DeliveryInformationComponent(day.get(Calendar.DAY_OF_MONTH)+"", DATE)); newItemId.getItemProperty(weekday_name).setValue(itemList); } for (DeliveryInformationComponent item : delStat) { try { Matcher matcher = UiDataConverter.getPatternMatcher(item.getDeliveryName()); if (matcher.matches()) { Calendar day = Calendar.getInstance(); day.setFirstDayOfWeek(Calendar.MONDAY); day.setTime(UiDataConverter.getDateFromDeliveryItemDirectoryName(item.getDeliveryName())); String weekday_no = day.get(Calendar.WEEK_OF_YEAR)+""; String weekday_name = dayMap.get(day.get(Calendar.DAY_OF_WEEK)); Item tableRow = table.getItem(weekday_no); Property tableCell = tableRow.getItemProperty(weekday_name); List oldCellValue = (List)tableCell.getValue(); if (oldCellValue!=null) { oldCellValue.add(item); tableCell.setValue(oldCellValue); } } } catch (ParseException e) { Notification.show("The application can not show all deliveries", Notification.Type.WARNING_MESSAGE); log.error("Strings could not get parsed into Dates in DatePanel", e); } table.sort(); } } /** * Set the component to be vieved as enabled in the UI * * @param enabled */ @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); } /** * Set a caption of the embedded Table * * @param caption */ @Override public void setCaption(String caption) { table.setCaption(caption); } /** * Generate textareas as cells in the table */ static class FieldGenerator implements Table.ColumnGenerator { @Override public Component generateCell(Table source, Object itemId, Object columnId) { VerticalLayout vl = new VerticalLayout(); Property prop = source.getItem(itemId).getItemProperty(columnId); Object propertyValue = prop.getValue(); if(propertyValue!=null) { List<DeliveryInformationComponent> componentList = (List<DeliveryInformationComponent>)prop.getValue(); if(componentList.size()==0) { Button expectationButton = new Button("", new ThemeResource("icons/events/unknown.png")); vl.addComponent(expectationButton); } else { for(DeliveryInformationComponent deliveryComponent : componentList) { String id = deliveryComponent.getDeliveryName(); String name = id; if (deliveryComponent.isOverridden()){ name = name+" *"; } ValidationState state = deliveryComponent.getValidationState(); ThemeResource themeRecourse; Button expectationButton; switch(state) { case FAIL: themeRecourse = new ThemeResource("icons/events/fail.png"); expectationButton = new Button(name, themeRecourse); expectationButton.setId(id); expectationButton.addClickListener(buttonListener); vl.addComponent(expectationButton); break; case PROGRESS: themeRecourse = new ThemeResource("icons/events/progress.png"); expectationButton = new Button(name, themeRecourse); expectationButton.setId(id); expectationButton.addClickListener(buttonListener); vl.addComponent(expectationButton); break; case STOPPED: themeRecourse = new ThemeResource("icons/events/stopped.png"); expectationButton = new Button(name, themeRecourse); expectationButton.setId(id); expectationButton.addClickListener(buttonListener); vl.addComponent(expectationButton); break; case MANUAL_QA_COMPLETE: themeRecourse = new ThemeResource("icons/events/manualQA.png"); expectationButton = new Button(name, themeRecourse); expectationButton.setId(id); expectationButton.addClickListener(buttonListener); vl.addComponent(expectationButton); break; case APPROVED: themeRecourse = new ThemeResource("icons/events/approved.png"); expectationButton = new Button(name, themeRecourse); expectationButton.setId(id); expectationButton.addClickListener(buttonListener); vl.addComponent(expectationButton); break; case DATE: vl.addComponent(new Label(id)); break; } } } } return vl; } } }
package it.feio.android.omninotes; import it.feio.android.omninotes.db.DbHelper; import it.feio.android.omninotes.models.ONStyle; import it.feio.android.omninotes.models.PasswordValidator; import it.feio.android.omninotes.utils.Constants; import it.feio.android.omninotes.utils.Security; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import de.keyboardsurfer.android.widget.crouton.Crouton; public class PasswordActivity extends BaseActivity { private EditText passwordCheck; private EditText password; private Button confirm; private EditText question; private EditText answer; private EditText answerCheck; private Button reset; private PasswordActivity mActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_password); mActivity = this; setActionBarTitle(getString(R.string.title_activity_password)); initViews(); } private void initViews() { password = (EditText)findViewById(R.id.password); passwordCheck = (EditText)findViewById(R.id.password_check); question = (EditText)findViewById(R.id.question); answer = (EditText)findViewById(R.id.answer); answerCheck = (EditText)findViewById(R.id.answer_check); confirm = (Button)findViewById(R.id.password_confirm); confirm.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (checkData()){ final String passwordText = password.getText().toString(); final String questionText = question.getText().toString(); final String answerText = answer.getText().toString(); if (prefs.getString(Constants.PREF_PASSWORD, null) != null) { requestPassword(mActivity, new PasswordValidator() { @Override public void onPasswordValidated(boolean result) { if (result) { updatePassword(passwordText, questionText, answerText); } } }); } else { updatePassword(passwordText, questionText, answerText); } } } }); reset = (Button)findViewById(R.id.password_reset); reset.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (prefs.getString(Constants.PREF_PASSWORD, "").length() == 0) { Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN).show(); return; } AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity); // Inflate layout View layout = getLayoutInflater().inflate(R.layout.password_reset_dialog_layout, null); alertDialogBuilder.setView(layout); TextView questionTextView = (TextView) layout.findViewById(R.id.reset_password_question); questionTextView.setText(prefs.getString(Constants.PREF_PASSWORD_QUESTION, "")); final EditText answerEditText = (EditText) layout.findViewById(R.id.reset_password_answer); // Set dialog message and button alertDialogBuilder .setCancelable(false) .setPositiveButton(R.string.confirm, null) .setNegativeButton(R.string.cancel, null); AlertDialog dialog = alertDialogBuilder.create(); // Set a listener for dialog button press dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button pos = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); pos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // When positive button is pressed answer correctness is checked String oldAnswer = prefs.getString(Constants.PREF_PASSWORD_ANSWER, ""); String answer = answerEditText.getText().toString(); // The check is done on password's hash stored in preferences boolean result = Security.md5(answer).equals(oldAnswer); if (result) { dialog.dismiss(); prefs.edit() .remove(Constants.PREF_PASSWORD) .remove(Constants.PREF_PASSWORD_QUESTION) .remove(Constants.PREF_PASSWORD_ANSWER) .remove("settings_password_access") .commit(); DbHelper.getInstance(getApplicationContext()).unlockAllNotes(); Crouton.makeText(mActivity, R.string.password_successfully_removed, ONStyle.ALERT).show(); } else { answerEditText.setError(getString(R.string.wrong_answer)); } } }); Button neg = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE); neg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); } }); dialog.show(); } }); } private void updatePassword(String passwordText, String questionText, String answerText) { // If password have to be removed will be prompted to user to agree to unlock all notes if (password.length() == 0) { if (prefs.getString(Constants.PREF_PASSWORD, "").length() == 0) { Crouton.makeText(mActivity, R.string.password_not_set, ONStyle.WARN).show(); return; } AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity); alertDialogBuilder .setMessage(R.string.agree_unlocking_all_notes) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { prefs.edit() .remove(Constants.PREF_PASSWORD) .remove(Constants.PREF_PASSWORD_QUESTION) .remove(Constants.PREF_PASSWORD_ANSWER) .commit(); DbHelper.getInstance(getApplicationContext()).unlockAllNotes(); Crouton.makeText(mActivity, R.string.password_successfully_removed, ONStyle.ALERT).show(); // onBackPressed(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else { prefs.edit() .putString(Constants.PREF_PASSWORD, Security.md5(passwordText)) .putString(Constants.PREF_PASSWORD_QUESTION, questionText) .putString(Constants.PREF_PASSWORD_ANSWER, Security.md5(answerText)) .commit(); // onBackPressed(); Crouton.makeText(mActivity, R.string.password_successfully_changed, ONStyle.CONFIRM).show(); } } /** * Checks correctness of form data * @return */ private boolean checkData(){ boolean res = true; if (password.getText().length() == passwordCheck.getText().length() && passwordCheck.getText().length() == 0) { return true; } boolean passwordOk = password.getText().toString().length() > 0; boolean passwordCheckOk = passwordCheck.getText().toString().length() > 0 && password.getText().toString().equals(passwordCheck.getText().toString()); boolean questionOk = question.getText().toString().length() > 0; boolean answerOk = answer.getText().toString().length() > 0; boolean answerCheckOk = answerCheck.getText().toString().length() > 0 && answer.getText().toString().equals(answerCheck.getText().toString()); if (!passwordOk || !passwordCheckOk || !questionOk || !answerOk || !answerCheckOk){ res = false; if (!passwordOk) { password.setError(getString(R.string.settings_password_not_matching)); } if (!passwordCheckOk) { passwordCheck.setError(getString(R.string.settings_password_not_matching)); } if (!questionOk) { question.setError(getString(R.string.settings_password_question)); } if (!answerOk) { answer.setError(getString(R.string.settings_answer_not_matching)); } if (!answerCheckOk) { answerCheck.setError(getString(R.string.settings_answer_not_matching)); } } return res; } @Override public void onBackPressed() { setResult(RESULT_OK); finish(); } }
package edu.utk.phys.fern; // ------------------------------------------------------------------------------------------------------------ // Class ParamSetup to set up basic parameters for calculation. // Launches window in which these parameters can be specified. (Window // is opened from button in instance of SegreFrame.) // ------------------------------------------------------------------------------------------------------------ import java.awt.BorderLayout; import java.awt.Button; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.Choice; import java.awt.Color; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.PrintJob; import java.awt.TextArea; import java.awt.TextField; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; class ParamSetup extends Frame implements ItemListener { static boolean helpWindowOpen = false; GenericHelpFrame hf = new GenericHelpFrame("","",0,0,0,0,0,0); static final double LOG10 = 0.434294482; Font titleFont = new java.awt.Font("SanSerif", Font.BOLD, 12); FontMetrics titleFontMetrics = getFontMetrics(titleFont); Font buttonFont = new java.awt.Font("SanSerif", Font.BOLD, 11); FontMetrics buttonFontMetrics = getFontMetrics(buttonFont); Font textFont = new java.awt.Font("SanSerif", Font.PLAIN, 12); FontMetrics textFontMetrics = getFontMetrics(textFont); Color panelForeColor = Color.black; Color panelBackColor = Color.white; Color disablebgColor = new Color(230,230,230); Color disablefgColor = new Color(153,153,153); Color framebgColor = new Color(230,230,230); Panel panel4, panel5; TextField profile, rho, T9; Label profileL, rhoL, T9L; CheckboxGroup cbg = new CheckboxGroup(); final Checkbox [] checkBox = new Checkbox[2]; public ParamSetup (int width, int height, String title, String text) { this.pack(); this.setSize(width,height); this.setTitle(title); this.setBackground(framebgColor); String temp; Panel panel0 = new Panel(); panel0.setLayout(new GridLayout(1,1)); panel0.setFont(titleFont); panel0.setForeground(panelForeColor); Label first = new Label(" Integration Parameters",Label.LEFT); panel0.add(first); Panel panel1 = new Panel(); panel1.setLayout(new FlowLayout()); panel1.setFont(textFont); panel1.setForeground(panelForeColor); Label sfL = new Label("Precision",Label.RIGHT); panel1.add(sfL); final TextField sf = new TextField(6); sf.setFont(textFont); if (StochasticElements.stochasticFactor != 0) { temp = Double.toString(StochasticElements.stochasticFactor); } else { temp = ""; } sf.setText(temp); sf.setBackground(panelBackColor); panel1.add(sf); Label asymptoticL = new Label("Integration method",Label.RIGHT); panel1.add(asymptoticL); final Choice asymptotic = new Choice(); asymptotic.setFont(textFont); asymptotic.setBackground(panelBackColor); asymptotic.addItem("Asy"); asymptotic.addItem("QSS"); asymptotic.addItem("AsyMott"); asymptotic.addItem("AsyOB"); asymptotic.addItem("Explicit"); asymptotic.addItem("F90Asy"); asymptotic.addItem("Asy+PE"); asymptotic.addItem("QSS+PE"); if(!StochasticElements.integrateWithJava){ asymptotic.select(5); } else if (StochasticElements.doAsymptotic && StochasticElements.imposeEquil) { asymptotic.select(6); } else if (StochasticElements.doSS && StochasticElements.imposeEquil) { asymptotic.select(7); } else if (StochasticElements.doSS) { asymptotic.select(1); } else if (StochasticElements.doAsymptotic && ! StochasticElements.asyPC){ asymptotic.select(0); } else if (StochasticElements.doAsymptotic && StochasticElements.asyPC && StochasticElements.isMott){ asymptotic.select(2); } else if (StochasticElements.doAsymptotic && StochasticElements.asyPC && ! StochasticElements.isMott){ asymptotic.select(3); } else { asymptotic.select(4); } panel1.add(asymptotic); Label massTolL = new Label("dX",Label.RIGHT); panel1.add(massTolL); final TextField massTol = new TextField(5); massTol.setFont(textFont); temp = Double.toString(StochasticElements.massTol); massTol.setText(temp); massTol.setBackground(panelBackColor); panel1.add(massTol); Panel panel2 = new Panel(); panel2.setLayout(new FlowLayout()); panel2.setFont(textFont); panel2.setForeground(panelForeColor); Label logtminL = new Label("Log10 Start time (s)",Label.RIGHT); panel2.add(logtminL); final TextField logtmin = new TextField(8); logtmin.setFont(textFont); temp = Double.toString(StochasticElements.logtmin); logtmin.setText(temp); logtmin.setBackground(panelBackColor); panel2.add(logtmin); Label logtmaxL = new Label("Log10 End time (s)",Label.RIGHT); panel2.add(logtmaxL); final TextField logtmax = new TextField(8); logtmax.setFont(textFont); temp = Double.toString(StochasticElements.logtmax); logtmax.setText(temp); logtmax.setBackground(panelBackColor); panel2.add(logtmax); // --- Panel for equilibrium quantities Panel panelEq = new Panel(); panelEq.setLayout(new FlowLayout()); panelEq.setFont(textFont); panelEq.setForeground(panelForeColor); Label LtrackEq = new Label("Track Equil ",Label.RIGHT); panelEq.add(LtrackEq); final Choice trackEq = new Choice(); trackEq.setFont(textFont); trackEq.setBackground(panelBackColor); trackEq.addItem("No"); trackEq.addItem("Yes"); if(StochasticElements.equilibrate) { trackEq.select(1); } else { trackEq.select(0); } panelEq.add(trackEq); Label eqTimeL = new Label("Equil time",Label.RIGHT); panelEq.add(eqTimeL); final TextField eqTime = new TextField(6); eqTime.setFont(textFont); if (StochasticElements.equilibrateTime != 0) { temp = Double.toString(StochasticElements.equilibrateTime); } else { temp = ""; } eqTime.setText(temp); eqTime.setBackground(panelBackColor); panelEq.add(eqTime); Label eqTolL = new Label("Equil tolerance",Label.RIGHT); panelEq.add(eqTolL); final TextField eqTol = new TextField(6); eqTol.setFont(textFont); if (StochasticElements.equiTol != 0) { temp = Double.toString(StochasticElements.equiTol); } else { temp = ""; } eqTol.setText(temp); eqTol.setBackground(panelBackColor); panelEq.add(eqTol); // ----------------- Panel panel2B = new Panel(); panel2B.setLayout(new FlowLayout()); panel2B.setFont(textFont); panel2B.setForeground(panelForeColor); Label lpFormatL = new Label("Lineplot",Label.RIGHT); panel2B.add(lpFormatL); final Choice lpFormat = new Choice(); lpFormat.setFont(textFont); lpFormat.setBackground(panelBackColor); lpFormat.addItem("Short"); lpFormat.addItem("Tall"); if(StochasticElements.longFormat) { lpFormat.select(1); } else { lpFormat.select(0); } panel2B.add(lpFormat); // Population 2D animation color maps. See the class MyColors for definitions Label popCML = new Label("Pop CM",Label.RIGHT); panel2B.add(popCML); final Choice popCM = new Choice(); popCM.setFont(textFont); popCM.setBackground(panelBackColor); popCM.addItem("guidry2"); popCM.addItem("guidry"); popCM.addItem("hot"); popCM.addItem("bluehot"); popCM.addItem("greyscale"); popCM.addItem("caleblack"); popCM.addItem("calewhite"); popCM.addItem("cardall"); popCM.select(StochasticElements.popColorMap); panel2B.add(popCM); // Flux 2D animation color maps. See the class MyColors for definitions Label fluxCML = new Label("Flux CM",Label.RIGHT); panel2B.add(fluxCML); final Choice fluxCM = new Choice(); fluxCM.setFont(textFont); fluxCM.setBackground(panelBackColor); fluxCM.addItem("guidry2"); fluxCM.addItem("guidry"); fluxCM.addItem("hot"); fluxCM.addItem("bluehot"); fluxCM.addItem("greyscale"); fluxCM.addItem("caleblack"); fluxCM.addItem("calewhite"); fluxCM.addItem("cardall"); fluxCM.select(StochasticElements.fluxColorMap); if(StochasticElements.doFluxPlots) { fluxCM.enable(); } else { fluxCM.disable(); } panel2B.add(fluxCM); Panel panel3 = new Panel(); panel3.setLayout(new GridLayout(1,1)); panel3.setFont(titleFont); panel3.setForeground(panelForeColor); Label trho = new Label(" Hydrodynamic Variables",Label.LEFT); panel3.add(trho); // Create two checkboxes checkBox[0] = new Checkbox("Specify profile"); checkBox[1] = new Checkbox("Constant:"); // Make them part of a checkbox group (exclusive radio buttons) checkBox[0].setCheckboxGroup(cbg); checkBox[1].setCheckboxGroup(cbg); // Add itemListeners to listen for checkbox events. These events // will be processed by the method itemStateChanged checkBox[0].addItemListener(this); checkBox[1].addItemListener(this); panel4 = new Panel(); panel4.setLayout(new FlowLayout()); panel4.setFont(textFont); panel4.setForeground(panelForeColor); panel4.add(checkBox[0]); profileL = new Label("File",Label.RIGHT); panel4.add(profileL); profile = new TextField(29); profile.setFont(textFont); temp = StochasticElements.profileFileName; profile.setText(temp); panel4.add(profile); panel5 = new Panel(); panel5.setLayout(new FlowLayout()); panel5.setFont(textFont); panel5.setForeground(panelForeColor); panel5.add(checkBox[1]); T9L = new Label("T9",Label.RIGHT); panel5.add(T9L); T9 = new TextField(7); T9.setFont(textFont); if(StochasticElements.T9 != 0) { temp = Double.toString(StochasticElements.T9); } else {temp="";} T9.setText(temp); T9.setBackground(panelBackColor); panel5.add(T9); rhoL = new Label("rho(cgs)",Label.RIGHT); panel5.add(rhoL); rho = new TextField(7); rho.setFont(textFont); if(StochasticElements.rho != 0) { temp = Double.toString(StochasticElements.rho); } else {temp="";} rho.setText(temp); rho.setBackground(panelBackColor); panel5.add(rho); Label YeL = new Label("Ye",Label.RIGHT); panel5.add(YeL); final TextField Ye = new TextField(4); Ye.setFont(textFont); if(StochasticElements.Ye != 0) { temp = Double.toString(StochasticElements.Ye); } else {temp="";} Ye.setText(temp); Ye.setBackground(panelBackColor); panel5.add(Ye); // Set the current values of the temperature/density fields if(StochasticElements.constantHydro) { // Constant T, rho profileL.setForeground(disablefgColor); profile.disable(); profile.setBackground(disablebgColor); rhoL.setForeground(panelForeColor); rho.enable(); rho.setBackground(panelBackColor); T9.setForeground(panelForeColor); T9.enable(); T9.setBackground(panelBackColor); cbg.setSelectedCheckbox(checkBox[1]); } else { // T, rho time profile profileL.setForeground(panelForeColor); profile.enable(); profile.setBackground(panelBackColor); rhoL.setForeground(disablefgColor); rho.disable(); rho.setBackground(disablebgColor); T9L.setForeground(disablefgColor); T9.disable(); T9.setBackground(disablebgColor); cbg.setSelectedCheckbox(checkBox[0]); } Panel panel6a = new Panel(); panel6a.setLayout(new GridLayout(1,1)); panel6a.setFont(titleFont); panel6a.setForeground(panelForeColor); Label lab6a = new Label(" Plot Control Parameters",Label.LEFT); panel6a.add(lab6a); Panel panel6 = new Panel(); panel6.setLayout(new FlowLayout()); panel6.setFont(textFont); panel6.setForeground(panelForeColor); Label LtminPlot = new Label("logx-",Label.RIGHT); panel6.add(LtminPlot); final TextField logtminPlot = new TextField(6); logtminPlot.setFont(textFont); logtminPlot.setText(Double.toString(StochasticElements.logtminPlot)); logtminPlot.setBackground(panelBackColor); panel6.add(logtminPlot); Label LtmaxPlot = new Label("logx+",Label.RIGHT); panel6.add(LtmaxPlot); final TextField logtmaxPlot = new TextField(6); logtmaxPlot.setFont(textFont); logtmaxPlot.setText(Double.toString(StochasticElements.logtmaxPlot)); logtmaxPlot.setBackground(panelBackColor); panel6.add(logtmaxPlot); Label LXmin = new Label("logy-",Label.RIGHT); panel6.add(LXmin); final TextField XminPlot = new TextField(4); XminPlot.setFont(textFont); temp = Double.toString(StochasticElements.yminPlot ); XminPlot.setText(temp); XminPlot.setBackground(panelBackColor); panel6.add(XminPlot); Label LXmax = new Label("logy+",Label.RIGHT); panel6.add(LXmax); final TextField XmaxPlot = new TextField(4); XmaxPlot.setFont(textFont); temp = Double.toString(StochasticElements.ymaxPlot); XmaxPlot.setText(temp); XmaxPlot.setBackground(panelBackColor); panel6.add(XmaxPlot); Panel panel8 = new Panel(); panel8.setLayout(new FlowLayout()); panel8.setFont(textFont); panel8.setForeground(panelForeColor); Label Lxtics = new Label("x tics",Label.RIGHT); panel8.add(Lxtics); final TextField xtics = new TextField(3); xtics.setFont(textFont); if(StochasticElements.xtics != 0) { temp = Integer.toString(StochasticElements.xtics); } else {temp="";} xtics.setText(temp); xtics.setBackground(panelBackColor); panel8.add(xtics); Label Lytics = new Label("y tics",Label.RIGHT); panel8.add(Lytics); final TextField ytics = new TextField(3); ytics.setFont(textFont); if(StochasticElements.ytics != 0) { temp = Integer.toString(StochasticElements.ytics); } else {temp="";} ytics.setText(temp); ytics.setBackground(panelBackColor); panel8.add(ytics); Label LmaxCurves = new Label("Isotopes",Label.RIGHT); panel8.add(LmaxCurves); final TextField maxCurves = new TextField(4); maxCurves.setFont(textFont); if(StochasticElements.maxToPlot != 0) { temp = Integer.toString(StochasticElements.maxToPlot); } else {temp="";} maxCurves.setText(temp); maxCurves.setBackground(panelBackColor); panel8.add(maxCurves); Label energyL = new Label("E/dE ",Label.RIGHT); panel8.add(energyL); final Choice energy = new Choice(); energy.setFont(textFont); energy.setBackground(panelBackColor); energy.addItem("E"); energy.addItem("dE"); energy.addItem("None"); if(!StochasticElements.plotEnergy) { energy.select(2); } else if(StochasticElements.plotdE){ energy.select(1); } else { energy.select(0); } panel8.add(energy); Panel panel9 = new Panel(); panel9.setLayout(new FlowLayout()); panel9.setFont(textFont); panel9.setForeground(panelForeColor); Label LplotY = new Label("X/Y ",Label.RIGHT); panel9.add(LplotY); final Choice plotY = new Choice(); plotY.setFont(textFont); plotY.setBackground(panelBackColor); plotY.addItem("X"); plotY.addItem("Y"); if(StochasticElements.plotY) { plotY.select(1); } else { plotY.select(0); } panel9.add(plotY); Label LlinesOnly = new Label("Lines/Symbols",Label.RIGHT); panel9.add(LlinesOnly); final Choice linesOnly = new Choice(); linesOnly.setFont(textFont); linesOnly.setBackground(panelBackColor); linesOnly.addItem("Lines"); linesOnly.addItem("Symbols"); if(StochasticElements.linesOnly) { linesOnly.select(0); } else { linesOnly.select(1); } panel9.add(linesOnly); Label LblackOnly = new Label("Color/BW",Label.RIGHT); panel9.add(LblackOnly); final Choice blackOnly = new Choice(); blackOnly.setFont(textFont); blackOnly.setBackground(panelBackColor); blackOnly.addItem("Color"); blackOnly.addItem("B/W"); if(StochasticElements.blackOnly) { blackOnly.select(1); } else { blackOnly.select(0); } panel9.add(blackOnly); Panel panel10 = new Panel(); panel10.setLayout(new FlowLayout()); panel10.setFont(textFont); panel10.setForeground(panelForeColor); Label nintervalsL = new Label("Steps",Label.RIGHT); panel10.add(nintervalsL); final TextField nintervals = new TextField(3); nintervals.setFont(textFont); if(StochasticElements.nintervals != 0) { temp = Integer.toString(StochasticElements.nintervals); } else {temp="";} nintervals.setText(temp); nintervals.setBackground(panelBackColor); panel10.add(nintervals); Label LminContour = new Label("MinCon",Label.RIGHT); panel10.add(LminContour); final TextField minContour = new TextField(6); minContour.setFont(textFont); if(StochasticElements.minLogContour != 0) { temp = Double.toString(StochasticElements.minLogContour); } else {temp="";} minContour.setText(temp); minContour.setBackground(panelBackColor); panel10.add(minContour); Label Lwrite3D = new Label("3D",Label.RIGHT); panel10.add(Lwrite3D); final Choice write3D = new Choice(); write3D.setFont(textFont); write3D.setBackground(panelBackColor); write3D.addItem("No"); write3D.addItem("Yes"); if(StochasticElements.write3DOutput) { write3D.select(1); } else { write3D.select(0); } panel10.add(write3D); Label LalphaOnly = new Label("AlphaOnly",Label.RIGHT); panel10.add(LalphaOnly); final Choice alphaOnly = new Choice(); alphaOnly.setFont(textFont); alphaOnly.setBackground(panelBackColor); alphaOnly.addItem("No"); alphaOnly.addItem("Yes"); if(StochasticElements.tripleAlphaOnly) { alphaOnly.select(1); } else { alphaOnly.select(0); } panel10.add(alphaOnly); Panel panel11 = new Panel(); panel11.setLayout(new FlowLayout()); panel11.setFont(textFont); panel11.setForeground(panelForeColor); Label Lxdeci = new Label("x deci",Label.RIGHT); panel11.add(Lxdeci); final TextField xdeci = new TextField(2); xdeci.setFont(textFont); temp = Integer.toString(StochasticElements.xdeci); xdeci.setText(temp); xdeci.setBackground(panelBackColor); panel11.add(xdeci); Label Lydeci = new Label("y deci",Label.RIGHT); panel11.add(Lydeci); final TextField ydeci = new TextField(2); ydeci.setFont(textFont); temp = Integer.toString(StochasticElements.ydeci); ydeci.setText(temp); ydeci.setBackground(panelBackColor); panel11.add(ydeci); Label LYmin = new Label("Ymin",Label.RIGHT); panel11.add(LYmin); final TextField Ymin = new TextField(6); Ymin.setFont(textFont); temp = Double.toString(StochasticElements.Ymin); Ymin.setText(temp); Ymin.setBackground(panelBackColor); panel11.add(Ymin); Label LrenormX = new Label("normX",Label.RIGHT); panel11.add(LrenormX); final Choice renormX = new Choice(); renormX.setFont(textFont); renormX.setBackground(panelBackColor); renormX.addItem("No"); renormX.addItem("Yes"); if(StochasticElements.renormalizeMassFractions) { renormX.select(1); } else { renormX.select(0); } panel11.add(renormX); Panel panel12 = new Panel(); panel12.setLayout(new FlowLayout()); panel12.setFont(textFont); panel12.setForeground(panelForeColor); final TextArea commy = new TextArea("",1, 55, TextArea.SCROLLBARS_NONE); commy.setFont(textFont); temp = StochasticElements.myComment; commy.setText(temp); commy.setBackground(panelBackColor); panel12.add(commy); // Remove the following options for now /* Panel panelA = new Panel(); panelA.setLayout(new GridLayout(1,1)); panelA.setFont(titleFont); panelA.setForeground(panelForeColor); Label last = new Label(" Integration Isotope Ranges",Label.LEFT); panelA.add(last); Panel panel7 = new Panel(); panel7.setLayout(new FlowLayout()); panel7.setFont(textFont); panel7.setForeground(panelForeColor); Label zmaxL = new Label("Zmax",Label.RIGHT); panel7.add(zmaxL); final TextField zmax = new TextField(3); zmax.setFont(textFont); if(StochasticElements.pmax != 0) { temp = Integer.toString(StochasticElements.pmax); } else {temp="";} zmax.setText(temp); zmax.setBackground(panelBackColor); panel7.add(zmax); Label nmaxL = new Label("Nmax",Label.RIGHT); panel7.add(nmaxL); final TextField nmax = new TextField(3); nmax.setFont(textFont); if(StochasticElements.nmax != 0) { temp = Integer.toString(StochasticElements.nmax); } else {temp="";} nmax.setText(temp); nmax.setBackground(panelBackColor); panel7.add(nmax); Label zminL = new Label("Zmin",Label.RIGHT); panel7.add(zminL); final TextField zmin = new TextField(3); zmin.setFont(textFont); if(StochasticElements.pmin != 0) { temp = Integer.toString(StochasticElements.pmin); } else {temp="";} zmin.setText(temp); zmin.setBackground(panelBackColor); panel7.add(zmin); */ // Panel to hold all the textfields, labels, and checkboxes Panel cboxPanel = new Panel(); cboxPanel.setLayout(new GridLayout(15,1,2,2)); cboxPanel.add(panel0); cboxPanel.add(panel2); cboxPanel.add(panel1); cboxPanel.add(panelEq); cboxPanel.add(panel3); cboxPanel.add(panel5); cboxPanel.add(panel4); cboxPanel.add(panel6a); cboxPanel.add(panel6); cboxPanel.add(panel8); cboxPanel.add(panel9); cboxPanel.add(panel10); cboxPanel.add(panel11); cboxPanel.add(panel2B); cboxPanel.add(panel12); // cboxPanel.add(panelA); // cboxPanel.add(panel7); // Add the cboxPanel to Panel p this.add(cboxPanel,"West"); // Add Dismiss, Save Changes, Print, and Help buttons Panel botPanel = new Panel(); botPanel.setFont(buttonFont); botPanel.setBackground(MyColors.gray204); Label label1 = new Label(); Label label2 = new Label(); Label label3 = new Label(); Label label4 = new Label(); Button dismissButton = new Button("Cancel"); Button saveButton = new Button("Save Changes"); Button printButton = new Button(" Print "); Button helpButton = new Button(" Help "); botPanel.add(label1); botPanel.add(dismissButton); botPanel.add(label2); botPanel.add(saveButton); botPanel.add(label3); botPanel.add(printButton); botPanel.add(label4); botPanel.add(helpButton); this.add("South", botPanel); // Add inner class event handler for Dismiss button dismissButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ hide(); dispose(); } }); // Add inner class event handler for Save Changes button saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ try { // Catch NumberFormatExceptions and warn user // Following String -> double and then cast to int // is to allow exponential notation in the entry // field (e.g., 1.0e5 is valid as an entry now, // but would not be if totalSeeds were converted // directly from String to int.) StochasticElements.Ye = SegreFrame.stringToDouble(Ye.getText().trim()); StochasticElements.logtmin = SegreFrame.stringToDouble(logtmin.getText().trim()); StochasticElements.logtmax = SegreFrame.stringToDouble(logtmax.getText().trim()); StochasticElements.nintervals = SegreFrame.stringToInt(nintervals.getText().trim()); // Math.max and Math.min in following to ensure that plotting limits // stored below lie within integration limits stored above StochasticElements.logtmax = Math.max( Cvert.stringToDouble(logtmaxPlot.getText().trim()), StochasticElements.logtmax ); StochasticElements.logtminPlot = Math.max(StochasticElements.logtmin, SegreFrame.stringToDouble(logtminPlot.getText().trim()) ); StochasticElements.logtmaxPlot = Math.min(StochasticElements.logtmax, SegreFrame.stringToDouble(logtmaxPlot.getText().trim()) ); StochasticElements.yminPlot = SegreFrame.stringToDouble(XminPlot.getText().trim()); StochasticElements.ymaxPlot = SegreFrame.stringToDouble(XmaxPlot.getText().trim()); StochasticElements.xtics = SegreFrame.stringToInt(xtics.getText().trim()); StochasticElements.ytics = SegreFrame.stringToInt(ytics.getText().trim()); StochasticElements.maxToPlot = SegreFrame.stringToInt(maxCurves.getText().trim()); StochasticElements.xdeci = SegreFrame.stringToInt(xdeci.getText().trim()); StochasticElements.ydeci = SegreFrame.stringToInt(ydeci.getText().trim()); StochasticElements.Ymin = SegreFrame.stringToDouble(Ymin.getText().trim()); StochasticElements.myComment = commy.getText().trim(); StochasticElements.equilibrateTime = SegreFrame.stringToDouble( eqTime.getText().trim()); StochasticElements.equiTol = SegreFrame.stringToDouble(eqTol.getText().trim()); if(trackEq.getSelectedIndex()==0){ StochasticElements.equilibrate=false; } else { StochasticElements.equilibrate=true; } if(energy.getSelectedIndex() == 0) { StochasticElements.plotdE = false; StochasticElements.plotEnergy = true; } else if(energy.getSelectedIndex() == 1){ StochasticElements.plotdE = true; StochasticElements.plotEnergy = true; } else { StochasticElements.plotEnergy = false; } if(plotY.getSelectedIndex() == 0) { StochasticElements.plotY =false; } else { StochasticElements.plotY = true; } if(linesOnly.getSelectedIndex() == 0) { StochasticElements.linesOnly =true; } else { StochasticElements.linesOnly = false; } if(blackOnly.getSelectedIndex() == 0) { StochasticElements.blackOnly =false; } else { StochasticElements.blackOnly = true; } if(write3D.getSelectedIndex() == 0) { StochasticElements.write3DOutput =false; } else { StochasticElements.write3DOutput = true; } if(alphaOnly.getSelectedIndex()==0){ StochasticElements.tripleAlphaOnly=false; } else { StochasticElements.tripleAlphaOnly=true; } if(renormX.getSelectedIndex() == 0) { StochasticElements.renormalizeMassFractions =false; } else { StochasticElements.renormalizeMassFractions = true; } StochasticElements.minLogContour = SegreFrame.stringToDouble(minContour.getText().trim()); if(asymptotic.getSelectedIndex() == 5) { // F90 asymptotic StochasticElements.integrateWithJava = false; } else if(asymptotic.getSelectedIndex() == 0) { // Normal asymptotic StochasticElements.doAsymptotic = true; StochasticElements.doSS = false; StochasticElements.asyPC = false; StochasticElements.imposeEquil = false; StochasticElements.integrateWithJava = true; } else if (asymptotic.getSelectedIndex() == 1) { // Quasi-steady-state StochasticElements.doSS = true; StochasticElements.doAsymptotic = false; StochasticElements.imposeEquil = false; StochasticElements.integrateWithJava = true; } else if (asymptotic.getSelectedIndex() == 2) { // Mott asymptotic StochasticElements.doSS = false; StochasticElements.doAsymptotic = true; StochasticElements.asyPC = true; StochasticElements.isMott = true; StochasticElements.imposeEquil = false; StochasticElements.integrateWithJava = true; } else if (asymptotic.getSelectedIndex() == 3) { // Oran-Boris asymptotic StochasticElements.doSS = false; StochasticElements.doAsymptotic = true; StochasticElements.asyPC = true; StochasticElements.isMott = false; StochasticElements.imposeEquil = false; StochasticElements.integrateWithJava = true; } else if (asymptotic.getSelectedIndex() == 6) { // Asy + PE StochasticElements.doAsymptotic = true; StochasticElements.doSS = false; StochasticElements.asyPC = false; StochasticElements.imposeEquil = true; StochasticElements.integrateWithJava = true; } else if (asymptotic.getSelectedIndex() == 7) { // QSS + PE StochasticElements.doAsymptotic = false; StochasticElements.doSS = true; StochasticElements.asyPC = false; StochasticElements.imposeEquil = true; StochasticElements.integrateWithJava = true; } else if (asymptotic.getSelectedIndex() == 4) { // Explicit StochasticElements.doSS = false; StochasticElements.doAsymptotic = false; StochasticElements.imposeEquil = false; StochasticElements.integrateWithJava = true; } else { Cvert.callExit("*** Call exit: inconsistent integration method choice"); } StochasticElements.massTol = SegreFrame.stringToDouble(massTol.getText().trim()); if(lpFormat.getSelectedIndex() == 0) { StochasticElements.longFormat = false; } else { StochasticElements.longFormat = true; } StochasticElements.popColorMap = popCM.getSelectedItem(); StochasticElements.fluxColorMap = fluxCM.getSelectedItem(); if( checkBox[1].getState() ) { StochasticElements.rho = SegreFrame.stringToDouble(rho.getText().trim()); StochasticElements.T9 = SegreFrame.stringToDouble(T9.getText().trim()); StochasticElements.constantHydro = true; } else { StochasticElements.profileFileName = profile.getText(); StochasticElements.constantHydro = false; } StochasticElements.stochasticFactor = SegreFrame.stringToDouble(sf.getText().trim()); // Remove following for now /* if( (byte)SegreFrame.stringToInt(zmax.getText()) > StochasticElements.pmax || (byte)SegreFrame.stringToInt(nmax.getText())>StochasticElements.nmax ){ String message = "Zmax can't be greater than "; message += StochasticElements.pmax; message += " (set by pmax in StochasticElements)"; message+= " and Nmax can't be greater than "; message += StochasticElements.nmax; message += " (set by nmax in the class StochasticElements)."; message += " Change Zmax and/or Nmax entries to conform, or"; message += " change pmax or nmax in StochasticElements."; message += " There must also exist files in the date subdirectory"; message += " isoZ_N.ser corresponding to the ranges of Z and N chosen."; makeTheWarning(300,300,250,250,Color.black, Color.yellow, " Error!", message, false, ParamSetup.this); return; } else { StochasticElements.pmax = (byte) SegreFrame.stringToInt(zmax.getText().trim()); StochasticElements.nmax = (byte) SegreFrame.stringToInt(nmax.getText().trim()); StochasticElements.pmin = (byte) SegreFrame.stringToInt(zmin.getText().trim()); } */ hide(); dispose(); } catch(NumberFormatException e) { String screwup = "NumberFormatException."; screwup += " At least one required data field has"; screwup += " a blank or invalid entry."; System.out.println(screwup); makeTheWarning(300,300,200,150,Color.black, Color.lightGray, " Warning!", screwup, false , ParamSetup.this); } } }); // -- end inner class for Save button processing // Help button actions. Handle with an inner class. helpButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ if(helpWindowOpen) { hf.toFront(); } else { hf = new GenericHelpFrame(ParamSetup.makeHelpString(), " Help for parameter setup", 500,400,10,10,200,10); hf.show(); helpWindowOpen = true; } } }); // Add inner class event handler for Print button printButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ printThisFrame(20,20,false); } }); // Add window closing button (inner class) this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { hide(); dispose(); } }); } // ------------------------------------------------------------------------------------------- // Method to act when state of Checkboxes changes. // Requires that the class implement the // ItemListener interface, which in turn requires that the // method itemStateChanged be defined explicitly since // ItemListener is abstract. // -------------------------------------------------------------------------------------------- public void itemStateChanged(ItemEvent check) { // Process the reaction class checkboxes. First // get the components of the relevant panels // and store in Component arrays (Note: the method // getComponents() is inherited from the Container // class by the subclass Panel). Component [] components4 = panel4.getComponents(); Component [] components5 = panel5.getComponents(); // Now process these components that are checkboxes // (only the first element of each array is). First cast the // Component to a Checkbox. Then use the getState() // method of Checkbox to return boolean true if // checked and false otherwise. Checkbox cb4 = (Checkbox)components4[0]; // Checkbox for panel4 Checkbox cb5 = (Checkbox)components5[0]; // Checkbox for panel5 // Then use the getState() method of Checkbox to // return boolean true if checked and false otherwise. // Use this logic to disable one or the other sets of // choices for temperature and density input. if( cb4.getState() ) { checkBox[1].setState(false); // Seems needed despite CheckBoxGroup rho.disable(); rho.setBackground(disablebgColor); rhoL.setForeground(disablefgColor); T9.disable(); T9.setBackground(disablebgColor); T9L.setForeground(disablefgColor); profile.enable(); profile.setBackground(panelBackColor); profileL.setForeground(panelForeColor); } else if ( cb5.getState() ) { checkBox[0].setState(false); rho.enable(); rho.setBackground(panelBackColor); rhoL.setForeground(panelForeColor); T9.enable(); T9.setBackground(panelBackColor); T9L.setForeground(panelForeColor); profile.disable(); profile.setBackground(disablebgColor); profileL.setForeground(disablefgColor); } } // ---------------------------------------------------------------------------------------------- // Method printThisFrame prints an entire Frame (Java 1.1 API). // To print a Frame or class subclassed from Frame, place this // method in its class description and invoke it to print. // It MUST be in a Frame or subclass of Frame. // It invokes a normal print dialogue, // which permits standard printer setup choices. I have found // that rescaling of the output in the print dialogue works // properly on some printers but not on others. Also, I tried // printing to a PDF file through PDFwriter but that caused // the program to freeze, requiring a hard reboot to recover. // (You can use the PSfile method to output to a .ps file.) // // Variables: // xoff = horizontal offset from upper left corner // yoff = vertical offset from upper left corner // makeBorder = turn rectangular border on or off // ------------------------------------------------------------------------------------------------ public void printThisFrame(int xoff, int yoff, boolean makeBorder) { java.util.Properties printprefs = new java.util.Properties(); Toolkit toolkit = this.getToolkit(); PrintJob job = toolkit.getPrintJob(this,"Java Print",printprefs); if (job == null) {return;} Graphics g = job.getGraphics(); g.translate(xoff,yoff); // Offset from upper left corner Dimension size = this.getSize(); if (makeBorder) { // Rectangular border g.drawRect(-1,-1,size.width+2,size.height+2); } g.setClip(0,0,size.width,size.height); this.printAll(g); g.dispose(); job.end(); } // -------------------------------------------------------------------------------------------------------------------- // The method makeTheWarning creates a modal warning window when invoked // from within an object that subclasses Frame. The window is // modally blocked (the window from which the warning window is // launched is blocked from further input until the warning window // is dismissed by the user). Method arguments: // // X = x-position of window on screen (relative upper left) // Y = y-position of window on screen (relative upper left) // width = width of window // height = height of window // fg = foreground (font) color // bg = background color // title = title string // text = warning string text // oneLine = display as one-line Label (true) // or multiline TextArea (false) // frame = A Frame that is the parent window modally // blocked by the warning window. If the parent // class from which this method is invoked extends // Frame, this argument can be just "this" (or // "ParentClass.this" if invoked from an // inner class event handler of ParentClass). // Otherwise, it must be the name of an object derived from // Frame that represents the window modally blocked. // // If oneLine is true, you must make width large enough to display all // text on one line. // --------------------------------------------------------------------------------------------------------------------- public void makeTheWarning (int X, int Y, int width, int height, Color fg, Color bg, String title, String text, boolean oneLine, Frame frame) { Font warnFont = new java.awt.Font("SanSerif", Font.BOLD, 12); FontMetrics warnFontMetrics = getFontMetrics(warnFont); // Create Dialog window with modal blocking set to true. // Make final so inner class below can access it. final Dialog mww = new Dialog(frame, title, true); mww.setLayout(new BorderLayout()); mww.setSize(width,height); mww.setLocation(X,Y); // Use Label for 1-line warning if (oneLine) { Label hT = new Label(text,Label.CENTER); hT.setForeground(fg); hT.setBackground(bg); hT.setFont(warnFont); mww.add("Center", hT); // Use TextArea for multiline warning } else { TextArea hT = new TextArea("",height,width, TextArea.SCROLLBARS_NONE); hT.setEditable(false); hT.setForeground(fg); hT.setBackground(bg); // no effect once setEditable (false)? hT.setFont(warnFont); mww.add("Center", hT); hT.appendText(text); } mww.setTitle(title); // Add dismiss button Panel botPanel = new Panel(); botPanel.setBackground(Color.lightGray); Label label1 = new Label(); Label label2 = new Label(); Button dismissButton = new Button("Dismiss"); botPanel.add(label1); botPanel.add(dismissButton); botPanel.add(label2); // Add inner class event handler for Dismiss button. This must be // added to the dismissButton before botPanel is added to mww. dismissButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ mww.hide(); mww.dispose(); } }); mww.add("South", botPanel); // Add window closing button (inner class) mww.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { mww.hide(); mww.dispose(); } }); mww.show(); // Note that this show must come after all the above // additions; otherwise they are not added before the // window is displayed. } // ---------------------------------------------------------------------- // Static method to generate string for Help file // ---------------------------------------------------------------------- static String makeHelpString() { String s; s="The parameters set through this interface control many of the"; s+=" details of the calculation. Once the parameters are set,"; s+=" store them by clicking the \"Save Changes\" button.\n\n"; s+="Log10 Start Time\nBase-10 logarithm of the start time for"; s+=" integration, in seconds. Distinguish from logx- below, which is"; s+= " the start time for the plot. \n\n"; s+="Log10 END TIME\nBase-10 logarithm of the final time for"; s+=" integration, in seconds. Distinguish from logx+ below, which is"; s+= " the end time for the plot. \n\n"; s+="Precision\nPrecision factor for integration timestep."; s+=" Smaller values give smaller adaptive timestep and more precision.\n\n"; s+="CalcMode\nCalculation mode (QSS=quasi-steady-state, Asy=normal asymptotic,"; s+=" AsyMott=Mott asymptotic, AsyOB=Oran-Boris asymptotic, Explicit=explicit, F90Asy=F90).\n\n"; s+="dX\nPermitted tolerance in deviation of sum of mass fractions X"; s+=" from unity. For example, a value of 0.01 requires the timestep to be"; s+=" adjusted such that sum X lies between 0.99 and 1.01"; s+=" after each timestep.\n\n"; // s+="Max Light-Ion Mass\nMaximum mass light ion permitted to"; // s+=" contribute to reactions. For example, if this variable is set"; // s+=" to 4, p + O16 and He4 + O16 reactions can contribute (if"; // s+=" the corresponding Reaction Class is selected), but C12 + O16"; // s+=" would be excluded since 12 is larger than 4. As another"; // s+=" example, if Reaction Class 5 is selected and this variable"; // s+=" is set equal to 1, p-gamma reactions contribute but not"; // s+=" alpha-p reactions.\n\n"; s+="HYDRODYNAMIC VARIABLES\nThe temperature (in units"; s+=" of 10^9 K), the density (in units of g/cm^3), and electron fraction Ye are set in"; s+=" one of two mutually exclusive ways, chosen through the radio"; s+=" buttons. If \"Constant\" is selected the (constant)"; s+=" temperature (T), density (rho), and electron fraction (Ye) are entered in the"; s+=" corresponding fields. If \"Specify Profile\""; s+=" is selected instead, a file name is specified that"; s+=" contains the time profile for T, rho, and Ye to be used in the"; s+=" calculation"; s+=" (note: assume to be case-sensitive) if in the same directory"; s+=" as the Java class files, or by a properly qualified path"; s+=" for the machine in question if in another directory. For"; s+=" example, on a Unix machine \"../file.ext\" would specify the"; s+=" file with name \"file.ext\" in the parent directory."; s+=" See the file jin/sampleHydroProfile.inp for sample file format\n\n"; s+="logx-\nThe lower limit in log time for plot."; s+=" This differs from LOG10 START TIME, which is the integration start time."; s+=" Generally logx- must be greater than or equal to LOG10 START TIME "; s+= " (the program will set logx- = LOG10 START TIME otherwise).\n\n"; s+="logx+\nThe upper limit in log time for plot."; s+=" This differs from LOG10 END TIME, which is the integration stop time."; s+=" Generally logx+ must be less than or equal to LOG10 END TIME "; s+= " (the program will set logx+ = LOG10 END TIME otherwise).\n\n"; s+="logy-\nThe lower limit in log X (mass fraction) or log Y (abundance) for plot"; s+= " (which one is determined by the X/Y selection widget).\n\n"; s+="logy+\nThe upper limit in log X (mass fraction) or log Y (abundance) for plot."; s+= " (which one is determined by the X/Y selection widget).\n\n"; s+="x tics\nNumber of tic marks on x axis.\n\n"; s+="y tics\nNumber of tic marks on y axis.\n\n"; s+="Isotopes\nMaximum number of curves to plot (500 is the largest permitted value).\n\n"; s+="E/dE\nWhether integrated energy E or differential energy dE is plotted.\n\n"; s+="X/Y\nWhether mass fraction X or molar abundance Y is plotted.\n\n"; s+="Lines/Symbols\nWhether curves are drawn with lines or series of symbols.\n\n"; s+="Color/BW\nWhether curves are drawn in color or black and white.\n\n"; s+="Steps\nNumber of time intervals to plot (time intervals"; s+=" will be equally spaced on log scale). Typical values are ~100. Max is"; s+=" StochasticElements.tintMax. Larger values give better plot resolution but"; s+=" larger postscript files.\n\n"; s+="MinCon\nApproximate minimum contour for 2D and 3D plots.\n\n"; s+="3D\nWhether to output data in ascii file 3D.data for 3D plot animation by rateViewer3D.\n\n"; s+="AlphaOnly\nIf No, include only triple-alpha among alpha reactions with light ions"; s+=" (for alpha network). Otherwise, include all alpha reactions with light ions.\n\n"; s+="x deci\nNumber of digits beyond decimal for x-axis labels.\n\n"; s+="y deci\nNumber of digits beyond decimal for y-axis labels.\n\n"; s+="Ymin\nFractional particle number threshold for including a box in network in a given"; s+=" timestep. Roughly, in given timestep only isotopes having an an abundance Y"; s+=" larger than Ymin will be processed.\n\n"; s+="renormX\nWhether to renormalize sum of mass fractions to 1 after each timestep.\n\n"; s+="Lineplot\nDetermines whether the lineplot produced"; s+=" of populations as a function of time has a tall or "; s+=" short vertical aspect.\n\n"; s+="PopCM\nChooses colormap for 2D population animation.\n\n"; s+="FluxCM\nChooses colormap for 2D flux ratio animation.\n\n"; s+="Comments\nOptional comments that will be included in output text and graphics.\n\n"; // Remove following for now /* s+="Zmax\nThe maximum value of proton number that will be considered"; s+=" in the calculation. Set larger than the highest Z likely"; s+=" to be encountered in the reactions of the network."; s+=" Can't be larger than StochasticElements.pmax.\n\n"; s+="Nmax\nThe maximum value of neutron number that will be considered"; s+=" in the calculation. Set larger than the highest N likely"; s+=" to be encountered in the reactions of the network."; s+=" Can't be larger than StochasticElements.nmax.\n\n"; s+="Zmin\nThe minimum value of proton number that will be considered"; s+=" in the calculation for heavier ions. (Note: protons, neutrons,"; s+=" He3, and He4 are always considered, irrespective of this"; s+=" parameter). For example, if Zmin=6, no isotopes with mass"; s+=" numbers less than 6 will be considered, except for protons,"; s+=" neutrons (if Include Neutrons is set to \"Yes\"), He3, and"; s+=" alpha particles. Normally changed only for diagnostic purposes. \n\n"; */ return s; } } /* End class ParamSetup */
// Copyright 2008 Google Inc. All Rights Reserved package org.waveprotocol.wave.model.document.util; import org.waveprotocol.wave.model.document.ReadableDocument; import org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema.PermittedCharacters; import org.waveprotocol.wave.model.util.Preconditions; import org.waveprotocol.wave.model.util.Utf16Util; import java.util.Map; /** * Implementation class for XmlStringBuilder, plus extension of its interface * for converting nodes to strings using a doc view. For details, * * @see XmlStringBuilder * * * @author [email protected] (Daniel Danilatos) */ public class XmlStringBuilderDoc<N, E extends N, T extends N> extends XmlStringBuilder { /** * The xml string itself */ private final StringBuilder builder = new StringBuilder(); /** * The "item length" of the xml string */ private int length = 0; private final ReadableDocument<N, E, T> view; private final PermittedCharacters permittedChars; private XmlStringBuilderDoc(ReadableDocument<N, E, T> view, PermittedCharacters permittedChars) { this.view = view; this.permittedChars = permittedChars; } /** * Constructs empty xml */ public static <N, E extends N, T extends N> XmlStringBuilderDoc<N,E,T> createEmpty(ReadableDocument<N, E, T> view) { return new XmlStringBuilderDoc<N,E,T>(view, PermittedCharacters.ANY); } /** * Constructs empty xml with restriction on PermittedCharacters */ public static <N, E extends N, T extends N> XmlStringBuilderDoc<N,E,T> createEmptyWithCharConstraints(ReadableDocument<N, E, T> view, PermittedCharacters permittedChars) { return new XmlStringBuilderDoc<N,E,T>(view, permittedChars); } /** {@inheritDoc} */ @Override public void clear() { builder.setLength(0); length = 0; } /** {@inheritDoc} */ @Override public int getLength() { return length; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public XmlStringBuilderDoc<N,E,T> append(XmlStringBuilder xml) { // Note(user): The CharSequence assignment here is a workaround for some // eclipse problem: if we pass xml.builder directly to append, eclipse's // compiler OKs is although the method is private, because there's a // public method append(CharSequence), and StringBuilder implements // CharSequence. But then we get an IlelgalAccessError at runtime! // Note that casting (vs. assigning) xml.builder cases eclipse to tell // you the cast is unnecessary for the same faulty reason... if (xml instanceof XmlStringBuilderDoc) { CharSequence seq = ((XmlStringBuilderDoc<N,E,T>)xml).builder; builder.append(seq); } else { builder.append(xml.toString()); } length += xml.getLength(); return this; } /** {@inheritDoc} */ @Override public XmlStringBuilderDoc<N,E,T> wrap(String tagName) { checkValidTagName(tagName); builder.insert(0, "<" + tagName + ">"); builder.append("</" + tagName + ">"); length += 2; return this; } /** {@inheritDoc} */ @Override public XmlStringBuilderDoc<N,E,T> wrapWithNs(String ns, String tagName) { return wrap(ns + ":" + tagName); } /** {@inheritDoc} */ @Override public XmlStringBuilderDoc<N,E,T> wrap(String tagName, String... attribs) { checkValidTagName(tagName); Preconditions.checkArgument(attribs.length % 2 == 0, "Attribs must come in string pairs"); String startTag = "<" + tagName; for (int i = 0; i < attribs.length; i += 2) { if (attribs[i + 1] != null) { String attrName = attribs[i]; checkValidAttributeName(attrName); startTag += " " + attrName + "=\"" + attrEscape(attribs[i + 1]) + "\""; } } startTag += ">"; builder.insert(0, startTag); builder.append("</" + tagName + ">"); length += 2; return this; } /** {@inheritDoc} */ @Override public XmlStringBuilderDoc<N,E,T> wrapWithNs(String ns, String tagName, String... attribs) { return wrap(ns + ":" + tagName, attribs); } private void checkValidTagName(String tagName) { if (!Utf16Util.isXmlName(tagName)) { Preconditions.illegalArgument("Invalid tag name: '" + tagName + "'"); } } private void checkValidAttributeName(String tagName) { if (!Utf16Util.isXmlName(tagName)) { Preconditions.illegalArgument("Invalid attribute name: '" + tagName + "'"); } } /** {@inheritDoc} */ @Override public XmlStringBuilderDoc<N,E,T> appendText(String text) { return appendText(text, PermittedCharacters.BLIP_TEXT); } /** {@inheritDoc} */ @Override public XmlStringBuilderDoc<N,E,T> appendText(String text, PermittedCharacters permittedChars) { length += addText(permittedChars.coerceString(text)); return this; } /** * Appends the "outerXML" representation of the node * @param node * @return self for convenience */ public XmlStringBuilderDoc<N,E,T> appendNode(N node) { length += addNode(node); return this; } /** * Appends the "innerXML" representation of the element * @param element * @return self for convenience */ public XmlStringBuilderDoc<N,E,T> appendChildXmlFragment(E element) { length += addChildXmlFragment(element); return this; } /** * Helper * @param element * @param selfClosing Whether this tag is self-closing * @return Opening tag of the given element as a String. */ public String startTag(E element, boolean selfClosing) { return "<" + view.getTagName(element) + getAttributesString(element) + (selfClosing ? "/>" : ">"); } /** * Helper * @param element * @return Closing tag of the given element as a String. */ public String endTag(E element) { return "</" + view.getTagName(element) + ">"; } /** * TODO(user): generalise this. * @param element * @return true if the element may self-close */ private boolean isSelfClosing(E element) { return view.getTagName(element).equals("br"); } /** * Worker for appendNode * @param node * @return item length of node */ private int addNode(N node) { E element = view.asElement(node); if (element != null) { boolean selfClosing = isSelfClosing(element) && view.getFirstChild(element) == null; builder.append(startTag(element, selfClosing)); int len = 2; if (!selfClosing) { len += addChildXmlFragment(element); builder.append(endTag(element)); } return len; } else { String data = view.getData(view.asText(node)); return addText(permittedChars.coerceString(data)); } } /** * Worker * @param text * @return length of text */ private int addText(String text) { builder.append(xmlEscape(text)); return text.length(); } /** * Worker * @param element * @return XML fragment describing children */ private int addChildXmlFragment(E element) { int size = 0; for (N n = view.getFirstChild(element); n != null; n = view.getNextSibling(n)) { size += addNode(n); } return size; } /** * Worker to get the attributes from the element as a string * @param element * @return string of attributes, e.g., " name1='value1' name1='value2'" */ private String getAttributesString(E element) { // TODO(danilatos): Investigate if it's worth optimising for ContentElement // StringMap attributes Map<String, String> attributes = view.getAttributes(element); String soFar = ""; for (String key : attributes.keySet()) { soFar += " " + key + "=\"" + attrEscape(attributes.get(key)) + "\""; } return soFar; } /** Copied from Utils in util.client to avoid dependency issues */ public static String xmlEscape(String xml) { return xml .replaceAll("&", "&amp;") .replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } /** Copied from Utils in util.client to avoid dependency issues */ public static String attrEscape(String attrValue) { return xmlEscape(attrValue) .replaceAll("\"", "&quot;") .replaceAll("'", "&apos;"); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof XmlStringBuilderDoc) { // NOTE(danilatos): As of this writing, GWT implementation of toString() for StringBuilder // essentially caches the result, so it's not bad for performance to call it multiple times. // However, the JRE version creates a copy every time. The equals() method on StringBuilders // uses referential equality, so it is not usable. Need to be careful GWT doesn't change // their implementation to make this equals implementation here slow. return builder.toString().equals(((XmlStringBuilderDoc)o).builder.toString()) && length == ((XmlStringBuilderDoc)o).length; } return false; } /** {@inheritDoc} */ @Override public int hashCode() { return toString().hashCode(); } @Override public String getXmlString() { return builder.toString(); } @Override public String toString() { return getXmlString(); } }
/** * 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.tez.runtime.library.common.shuffle; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.annotations.VisibleForTesting; import org.apache.tez.http.BaseHttpConnection; import org.apache.tez.http.HttpConnectionParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RawLocalFileSystem; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.util.DiskChecker.DiskErrorException; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.tez.common.CallableWithNdc; import org.apache.tez.common.security.JobTokenSecretManager; import org.apache.tez.dag.api.TezUncheckedException; import org.apache.tez.runtime.library.api.TezRuntimeConfiguration; import org.apache.tez.runtime.library.common.Constants; import org.apache.tez.runtime.library.common.InputAttemptIdentifier; import org.apache.tez.runtime.library.common.shuffle.orderedgrouped.ShuffleHeader; import org.apache.tez.runtime.library.common.sort.impl.TezIndexRecord; import org.apache.tez.runtime.library.common.sort.impl.TezSpillRecord; import org.apache.tez.runtime.library.exceptions.FetcherReadTimeoutException; import org.apache.tez.runtime.library.common.shuffle.FetchedInput.Type; import com.google.common.base.Preconditions; /** * Responsible for fetching inputs served by the ShuffleHandler for a single * host. Construct using {@link FetcherBuilder} */ public class Fetcher extends CallableWithNdc<FetchResult> { private static final Logger LOG = LoggerFactory.getLogger(Fetcher.class); private static final AtomicInteger fetcherIdGen = new AtomicInteger(0); private final Configuration conf; private final int shufflePort; // Configurable fields. private CompressionCodec codec; private boolean ifileReadAhead = TezRuntimeConfiguration.TEZ_RUNTIME_IFILE_READAHEAD_DEFAULT; private int ifileReadAheadLength = TezRuntimeConfiguration.TEZ_RUNTIME_IFILE_READAHEAD_BYTES_DEFAULT; private final JobTokenSecretManager jobTokenSecretMgr; private final FetcherCallback fetcherCallback; private final FetchedInputAllocator inputManager; private final ApplicationId appId; private final String logIdentifier; private final String localHostname; private final AtomicBoolean isShutDown = new AtomicBoolean(false); private final int fetcherIdentifier; // Parameters to track work. private List<InputAttemptIdentifier> srcAttempts; private String host; private int port; private int partition; // Maps from the pathComponents (unique per srcTaskId) to the specific taskId private final Map<String, InputAttemptIdentifier> pathToAttemptMap; private List<InputAttemptIdentifier> remaining; private URL url; private volatile DataInputStream input; BaseHttpConnection httpConnection; private HttpConnectionParams httpConnectionParams; private final boolean localDiskFetchEnabled; private final boolean sharedFetchEnabled; private final LocalDirAllocator localDirAllocator; private final Path lockPath; private final RawLocalFileSystem localFs; // Initiative value is 0, which means it hasn't retried yet. private long retryStartTime = 0; private final boolean asyncHttp; private final boolean isDebugEnabled = LOG.isDebugEnabled(); private Fetcher(FetcherCallback fetcherCallback, HttpConnectionParams params, FetchedInputAllocator inputManager, ApplicationId appId, JobTokenSecretManager jobTokenSecretManager, String srcNameTrimmed, Configuration conf, RawLocalFileSystem localFs, LocalDirAllocator localDirAllocator, Path lockPath, boolean localDiskFetchEnabled, boolean sharedFetchEnabled, String localHostname, int shufflePort, boolean asyncHttp) { this.asyncHttp = asyncHttp; this.fetcherCallback = fetcherCallback; this.inputManager = inputManager; this.jobTokenSecretMgr = jobTokenSecretManager; this.appId = appId; this.pathToAttemptMap = new HashMap<String, InputAttemptIdentifier>(); this.httpConnectionParams = params; this.conf = conf; this.localDiskFetchEnabled = localDiskFetchEnabled; this.sharedFetchEnabled = sharedFetchEnabled; this.fetcherIdentifier = fetcherIdGen.getAndIncrement(); this.logIdentifier = " fetcher [" + srcNameTrimmed +"] " + fetcherIdentifier; this.localFs = localFs; this.localDirAllocator = localDirAllocator; this.lockPath = lockPath; this.localHostname = localHostname; this.shufflePort = shufflePort; try { if (this.sharedFetchEnabled) { this.localFs.mkdirs(this.lockPath); } } catch (Exception e) { LOG.warn("Error initializing local dirs for shared transfer " + e); } } @Override protected FetchResult callInternal() throws Exception { boolean multiplex = (this.sharedFetchEnabled && this.localDiskFetchEnabled); if (srcAttempts.size() == 0) { return new FetchResult(host, port, partition, srcAttempts); } for (InputAttemptIdentifier in : srcAttempts) { pathToAttemptMap.put(in.getPathComponent(), in); // do only if all of them are shared fetches multiplex &= in.isShared(); } if (multiplex) { Preconditions.checkArgument(partition == 0, "Shared fetches cannot be done for partitioned input" + "- partition is non-zero (%d)", partition); } //Similar to TEZ-2172 (remove can be expensive with list) remaining = new LinkedList<InputAttemptIdentifier>(srcAttempts); HostFetchResult hostFetchResult; if (localDiskFetchEnabled && host.equals(localHostname) && port == shufflePort) { hostFetchResult = setupLocalDiskFetch(); } else if (multiplex) { hostFetchResult = doSharedFetch(); } else{ hostFetchResult = doHttpFetch(); } if (hostFetchResult.failedInputs != null && hostFetchResult.failedInputs.length > 0) { if (!isShutDown.get()) { LOG.warn("copyInputs failed for tasks " + Arrays.toString(hostFetchResult.failedInputs)); for (InputAttemptIdentifier left : hostFetchResult.failedInputs) { fetcherCallback.fetchFailed(host, left, hostFetchResult.connectFailed); } } else { LOG.info("Ignoring failed fetch reports for " + hostFetchResult.failedInputs.length + " inputs since the fetcher has already been stopped"); } } shutdown(); // Sanity check if (hostFetchResult.failedInputs == null && !remaining.isEmpty()) { if (!multiplex) { throw new IOException("server didn't return all expected map outputs: " + remaining.size() + " left."); } else { LOG.info("Shared fetch failed to return " + remaining.size() + " inputs on this try"); } } return hostFetchResult.fetchResult; } private final class CachingCallBack { // this is a closure object wrapping this in an inner class public void cache(String host, InputAttemptIdentifier srcAttemptId, FetchedInput fetchedInput, long compressedLength, long decompressedLength) { try { // this breaks badly on partitioned input - please use responsibly Preconditions.checkArgument(partition == 0, "Partition == 0"); final String tmpSuffix = "" + System.currentTimeMillis() + ".tmp"; final String finalOutput = getMapOutputFile(srcAttemptId.getPathComponent()); final Path outputPath = localDirAllocator.getLocalPathForWrite(finalOutput, compressedLength, conf); final TezSpillRecord spillRec = new TezSpillRecord(1); final TezIndexRecord indexRec; Path tmpIndex = outputPath.suffix(Constants.TEZ_RUNTIME_TASK_OUTPUT_INDEX_SUFFIX_STRING+tmpSuffix); if (localFs.exists(tmpIndex)) { LOG.warn("Found duplicate instance of input index file " + tmpIndex); return; } Path tmpPath = null; switch (fetchedInput.getType()) { case DISK: { DiskFetchedInput input = (DiskFetchedInput) fetchedInput; indexRec = new TezIndexRecord(0, decompressedLength, compressedLength); localFs.mkdirs(outputPath.getParent()); // avoid pit-falls of speculation tmpPath = outputPath.suffix(tmpSuffix); // JDK7 - TODO: use Files implementation to speed up this process localFs.copyFromLocalFile(input.getInputPath(), tmpPath); // rename is atomic boolean renamed = localFs.rename(tmpPath, outputPath); if(!renamed) { LOG.warn("Could not rename to cached file name " + outputPath); localFs.delete(tmpPath, false); return; } } break; default: LOG.warn("Incorrect use of CachingCallback for " + srcAttemptId); return; } spillRec.putIndex(indexRec, 0); spillRec.writeToFile(tmpIndex, conf); // everything went well so far - rename it boolean renamed = localFs.rename(tmpIndex, outputPath .suffix(Constants.TEZ_RUNTIME_TASK_OUTPUT_INDEX_SUFFIX_STRING)); if (!renamed) { localFs.delete(tmpIndex, false); // invariant: outputPath was renamed from tmpPath localFs.delete(outputPath, false); LOG.warn("Could not rename the index file to " + outputPath .suffix(Constants.TEZ_RUNTIME_TASK_OUTPUT_INDEX_SUFFIX_STRING)); return; } } catch (IOException ioe) { // do mostly nothing LOG.warn("Cache threw an error " + ioe); } } } private int findInputs() throws IOException { int k = 0; for (InputAttemptIdentifier src : srcAttempts) { try { if (getShuffleInputFileName(src.getPathComponent(), Constants.TEZ_RUNTIME_TASK_OUTPUT_INDEX_SUFFIX_STRING) != null) { k++; } } catch (DiskErrorException de) { // missing file, ignore } } return k; } private FileLock getLock() throws OverlappingFileLockException, InterruptedException, IOException { File lockFile = localFs.pathToFile(new Path(lockPath, host + ".lock")); final boolean created = lockFile.createNewFile(); if (created == false && !lockFile.exists()) { // bail-out cleanly return null; } // invariant - file created (winner writes to this file) // caveat: closing lockChannel does close the file (do not double close) // JDK7 - TODO: use AsynchronousFileChannel instead of RandomAccessFile FileChannel lockChannel = new RandomAccessFile(lockFile, "rws") .getChannel(); FileLock xlock = null; xlock = lockChannel.tryLock(0, Long.MAX_VALUE, false); if (xlock != null) { return xlock; } lockChannel.close(); return null; } private void releaseLock(FileLock lock) throws IOException { if (lock != null && lock.isValid()) { FileChannel lockChannel = lock.channel(); lock.release(); lockChannel.close(); } } protected HostFetchResult doSharedFetch() throws IOException { int inputs = findInputs(); if (inputs == srcAttempts.size()) { if (isDebugEnabled) { LOG.debug("Using the copies found locally"); } return doLocalDiskFetch(true); } if (inputs > 0) { if (isDebugEnabled) { LOG.debug("Found " + input + " local fetches right now, using them first"); } return doLocalDiskFetch(false); } FileLock lock = null; try { lock = getLock(); if (lock == null) { // re-queue until we get a lock LOG.info("Requeuing " + host + ":" + port + " downloads because we didn't get a lock"); return new HostFetchResult(new FetchResult(host, port, partition, remaining), null, false); } else { if (findInputs() == srcAttempts.size()) { // double checked after lock releaseLock(lock); lock = null; return doLocalDiskFetch(true); } // cache data if possible return doHttpFetch(new CachingCallBack()); } } catch (OverlappingFileLockException jvmCrossLock) { // fall back to HTTP fetch below LOG.warn("Double locking detected for " + host); } catch (InterruptedException sleepInterrupted) { Thread.currentThread().interrupt(); // fall back to HTTP fetch below LOG.warn("Lock was interrupted for " + host); } finally { releaseLock(lock); } if (isShutDown.get()) { // if any exception was due to shut-down don't bother firing any more // requests return new HostFetchResult(new FetchResult(host, port, partition, remaining), null, false); } // no more caching return doHttpFetch(); } @VisibleForTesting protected HostFetchResult doHttpFetch() { return doHttpFetch(null); } private HostFetchResult setupConnection(List<InputAttemptIdentifier> attempts) { try { StringBuilder baseURI = ShuffleUtils.constructBaseURIForShuffleHandler(host, port, partition, appId.toString(), httpConnectionParams.isSslShuffle()); this.url = ShuffleUtils.constructInputURL(baseURI.toString(), attempts, httpConnectionParams.isKeepAlive()); httpConnection = ShuffleUtils.getHttpConnection(asyncHttp, url, httpConnectionParams, logIdentifier, jobTokenSecretMgr); httpConnection.connect(); } catch (IOException | InterruptedException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } // ioErrs.increment(1); // If connect did not succeed, just mark all the maps as failed, // indirectly penalizing the host InputAttemptIdentifier[] failedFetches = null; if (isShutDown.get()) { LOG.info( "Not reporting fetch failure during connection establishment, since an Exception was caught after shutdown." + e.getClass().getName() + ", Message: " + e.getMessage()); } else { failedFetches = remaining.toArray(new InputAttemptIdentifier[remaining.size()]); } return new HostFetchResult(new FetchResult(host, port, partition, remaining), failedFetches, true); } if (isShutDown.get()) { // shutdown would have no effect if in the process of establishing the connection. shutdownInternal(); LOG.info("Detected fetcher has been shutdown after connection establishment. Returning"); return new HostFetchResult(new FetchResult(host, port, partition, remaining), null, false); } try { input = httpConnection.getInputStream(); httpConnection.validate(); //validateConnectionResponse(msgToEncode, encHash); } catch (IOException e) { // ioErrs.increment(1); // If we got a read error at this stage, it implies there was a problem // with the first map, typically lost map. So, penalize only that map // and add the rest if (isShutDown.get()) { LOG.info( "Not reporting fetch failure during connection establishment, since an Exception was caught after shutdown." + e.getClass().getName() + ", Message: " + e.getMessage()); } else { InputAttemptIdentifier firstAttempt = attempts.get(0); LOG.warn("Fetch Failure from host while connecting: " + host + ", attempt: " + firstAttempt + " Informing ShuffleManager: ", e); return new HostFetchResult(new FetchResult(host, port, partition, remaining), new InputAttemptIdentifier[] { firstAttempt }, false); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); //reset status return null; } return null; } @VisibleForTesting protected HostFetchResult doHttpFetch(CachingCallBack callback) { HostFetchResult connectionsWithRetryResult = setupConnection(srcAttempts); if (connectionsWithRetryResult != null) { return connectionsWithRetryResult; } // By this point, the connection is setup and the response has been // validated. // Handle any shutdown which may have been invoked. if (isShutDown.get()) { // shutdown would have no effect if in the process of establishing the connection. shutdownInternal(); LOG.info("Detected fetcher has been shutdown after opening stream. Returning"); return new HostFetchResult(new FetchResult(host, port, partition, remaining), null, false); } // After this point, closing the stream and connection, should cause a // SocketException, // which will be ignored since shutdown has been invoked. // Loop through available map-outputs and fetch them // On any error, faildTasks is not null and we exit // after putting back the remaining maps to the // yet_to_be_fetched list and marking the failed tasks. InputAttemptIdentifier[] failedInputs = null; while (!remaining.isEmpty() && failedInputs == null) { if (isShutDown.get()) { shutdownInternal(true); LOG.info("Fetcher already shutdown. Aborting queued fetches for " + remaining.size() + " inputs"); return new HostFetchResult(new FetchResult(host, port, partition, remaining), null, false); } try { failedInputs = fetchInputs(input, callback); } catch (FetcherReadTimeoutException e) { //clean up connection shutdownInternal(true); if (isShutDown.get()) { LOG.info("Fetcher already shutdown. Aborting reconnection and queued fetches for " + remaining.size() + " inputs"); return new HostFetchResult(new FetchResult(host, port, partition, remaining), null, false); } // Connect again. connectionsWithRetryResult = setupConnection( new LinkedList<InputAttemptIdentifier>(remaining)); if (connectionsWithRetryResult != null) { break; } } } if (isShutDown.get() && failedInputs != null && failedInputs.length > 0) { LOG.info("Fetcher already shutdown. Not reporting fetch failures for: " + failedInputs.length + " failed inputs"); failedInputs = null; } return new HostFetchResult(new FetchResult(host, port, partition, remaining), failedInputs, false); } @VisibleForTesting protected HostFetchResult setupLocalDiskFetch() { return doLocalDiskFetch(true); } @VisibleForTesting private HostFetchResult doLocalDiskFetch(boolean failMissing) { Iterator<InputAttemptIdentifier> iterator = remaining.iterator(); while (iterator.hasNext()) { if (isShutDown.get()) { LOG.info("Already shutdown. Skipping fetch for " + remaining.size() + " inputs"); break; } InputAttemptIdentifier srcAttemptId = iterator.next(); long startTime = System.currentTimeMillis(); FetchedInput fetchedInput = null; try { TezIndexRecord idxRecord; // for missing files, this will throw an exception idxRecord = getTezIndexRecord(srcAttemptId); fetchedInput = new LocalDiskFetchedInput(idxRecord.getStartOffset(), idxRecord.getRawLength(), idxRecord.getPartLength(), srcAttemptId, getShuffleInputFileName(srcAttemptId.getPathComponent(), null), conf, new FetchedInputCallback() { @Override public void fetchComplete(FetchedInput fetchedInput) {} @Override public void fetchFailed(FetchedInput fetchedInput) {} @Override public void freeResources(FetchedInput fetchedInput) {} }); LOG.info("fetcher" + " about to shuffle output of srcAttempt (direct disk)" + srcAttemptId + " decomp: " + idxRecord.getRawLength() + " len: " + idxRecord.getPartLength() + " to " + fetchedInput.getType()); long endTime = System.currentTimeMillis(); fetcherCallback.fetchSucceeded(host, srcAttemptId, fetchedInput, idxRecord.getPartLength(), idxRecord.getRawLength(), (endTime - startTime)); iterator.remove(); } catch (IOException e) { cleanupFetchedInput(fetchedInput); if (isShutDown.get()) { LOG.info( "Already shutdown. Ignoring Local Fetch Failure for " + srcAttemptId + " from host " + host + " : " + e.getClass().getName() + ", message=" + e.getMessage()); break; } LOG.warn("Failed to shuffle output of " + srcAttemptId + " from " + host + "(local fetch)", e); } } InputAttemptIdentifier[] failedFetches = null; if (failMissing && remaining.size() > 0) { if (isShutDown.get()) { LOG.info("Already shutdown, not reporting fetch failures for: " + remaining.size() + " remaining inputs"); } else { failedFetches = remaining.toArray(new InputAttemptIdentifier[remaining.size()]); } } else { // nothing needs to be done to requeue remaining entries } return new HostFetchResult(new FetchResult(host, port, partition, remaining), failedFetches, false); } @VisibleForTesting protected TezIndexRecord getTezIndexRecord(InputAttemptIdentifier srcAttemptId) throws IOException { TezIndexRecord idxRecord; Path indexFile = getShuffleInputFileName(srcAttemptId.getPathComponent(), Constants.TEZ_RUNTIME_TASK_OUTPUT_INDEX_SUFFIX_STRING); TezSpillRecord spillRecord = new TezSpillRecord(indexFile, conf); idxRecord = spillRecord.getIndex(partition); return idxRecord; } private static final String getMapOutputFile(String pathComponent) { return Constants.TEZ_RUNTIME_TASK_OUTPUT_DIR + Path.SEPARATOR + pathComponent + Path.SEPARATOR + Constants.TEZ_RUNTIME_TASK_OUTPUT_FILENAME_STRING; } @VisibleForTesting protected Path getShuffleInputFileName(String pathComponent, String suffix) throws IOException { suffix = suffix != null ? suffix : ""; String pathFromLocalDir = getMapOutputFile(pathComponent) + suffix; return localDirAllocator.getLocalPathToRead(pathFromLocalDir, conf); } static class HostFetchResult { private final FetchResult fetchResult; private final InputAttemptIdentifier[] failedInputs; private final boolean connectFailed; public HostFetchResult(FetchResult fetchResult, InputAttemptIdentifier[] failedInputs, boolean connectFailed) { this.fetchResult = fetchResult; this.failedInputs = failedInputs; this.connectFailed = connectFailed; } } public void shutdown() { if (!isShutDown.getAndSet(true)) { shutdownInternal(); } } private void shutdownInternal() { shutdownInternal(false); } private void shutdownInternal(boolean disconnect) { // Synchronizing on isShutDown to ensure we don't run into a parallel close // Can't synchronize on the main class itself since that would cause the // shutdown request to block synchronized (isShutDown) { try { if (httpConnection != null) { httpConnection.cleanup(disconnect); } } catch (IOException e) { LOG.info("Exception while shutting down fetcher on " + logIdentifier + " : " + e.getMessage()); if (LOG.isDebugEnabled()) { LOG.debug(StringUtils.EMPTY, e); } } } } private InputAttemptIdentifier[] fetchInputs(DataInputStream input, CachingCallBack callback) throws FetcherReadTimeoutException { FetchedInput fetchedInput = null; InputAttemptIdentifier srcAttemptId = null; long decompressedLength = -1; long compressedLength = -1; try { long startTime = System.currentTimeMillis(); int responsePartition = -1; // Read the shuffle header String pathComponent = null; try { ShuffleHeader header = new ShuffleHeader(); header.readFields(input); pathComponent = header.getMapId(); srcAttemptId = pathToAttemptMap.get(pathComponent); compressedLength = header.getCompressedLength(); decompressedLength = header.getUncompressedLength(); responsePartition = header.getPartition(); } catch (IllegalArgumentException e) { // badIdErrs.increment(1); if (!isShutDown.get()) { LOG.warn("Invalid src id ", e); // Don't know which one was bad, so consider all of them as bad return remaining.toArray(new InputAttemptIdentifier[remaining.size()]); } else { LOG.info("Already shutdown. Ignoring badId error with message: " + e.getMessage()); return null; } } // Do some basic sanity verification if (!verifySanity(compressedLength, decompressedLength, responsePartition, srcAttemptId, pathComponent)) { if (!isShutDown.get()) { if (srcAttemptId == null) { LOG.warn("Was expecting " + getNextRemainingAttempt() + " but got null"); srcAttemptId = getNextRemainingAttempt(); } assert (srcAttemptId != null); return new InputAttemptIdentifier[]{srcAttemptId}; } else { LOG.info("Already shutdown. Ignoring verification failure."); return null; } } if (LOG.isDebugEnabled()) { LOG.debug("header: " + srcAttemptId + ", len: " + compressedLength + ", decomp len: " + decompressedLength); } // TODO TEZ-957. handle IOException here when Broadcast has better error checking if (srcAttemptId.isShared() && callback != null) { // force disk if input is being shared fetchedInput = inputManager.allocateType(Type.DISK, decompressedLength, compressedLength, srcAttemptId); } else { fetchedInput = inputManager.allocate(decompressedLength, compressedLength, srcAttemptId); } // No concept of WAIT at the moment. // // Check if we can shuffle *now* ... // if (fetchedInput.getType() == FetchedInput.WAIT) { // LOG.info("fetcher#" + id + // " - MergerManager returned Status.WAIT ..."); // //Not an error but wait to process data. // return EMPTY_ATTEMPT_ID_ARRAY; // } // Go! LOG.info("fetcher" + " about to shuffle output of srcAttempt " + fetchedInput.getInputAttemptIdentifier() + " decomp: " + decompressedLength + " len: " + compressedLength + " to " + fetchedInput.getType()); if (fetchedInput.getType() == Type.MEMORY) { ShuffleUtils.shuffleToMemory(((MemoryFetchedInput) fetchedInput).getBytes(), input, (int) decompressedLength, (int) compressedLength, codec, ifileReadAhead, ifileReadAheadLength, LOG, fetchedInput.getInputAttemptIdentifier().toString()); } else if (fetchedInput.getType() == Type.DISK) { ShuffleUtils.shuffleToDisk(((DiskFetchedInput) fetchedInput).getOutputStream(), (host +":" +port), input, compressedLength, LOG, fetchedInput.getInputAttemptIdentifier().toString()); } else { throw new TezUncheckedException("Bad fetchedInput type while fetching shuffle data " + fetchedInput); } // offer the fetched input for caching if (srcAttemptId.isShared() && callback != null) { // this has to be before the fetchSucceeded, because that goes across // threads into the reader thread and can potentially shutdown this thread // while it is still caching. callback.cache(host, srcAttemptId, fetchedInput, compressedLength, decompressedLength); } // Inform the shuffle scheduler long endTime = System.currentTimeMillis(); // Reset retryStartTime as map task make progress if retried before. retryStartTime = 0; fetcherCallback.fetchSucceeded(host, srcAttemptId, fetchedInput, compressedLength, decompressedLength, (endTime - startTime)); // Note successful shuffle remaining.remove(srcAttemptId); // metrics.successFetch(); return null; } catch (IOException ioe) { if (isShutDown.get()) { cleanupFetchedInput(fetchedInput); LOG.info("Already shutdown. Ignoring exception during fetch " + ioe.getClass().getName() + ", Message: " + ioe.getMessage()); return null; } if (shouldRetry(srcAttemptId, ioe)) { //release mem/file handles cleanupFetchedInput(fetchedInput); throw new FetcherReadTimeoutException(ioe); } // ioErrs.increment(1); if (srcAttemptId == null || fetchedInput == null) { LOG.info("fetcher" + " failed to read map header" + srcAttemptId + " decomp: " + decompressedLength + ", " + compressedLength, ioe); // Cleanup the fetchedInput before returning. cleanupFetchedInput(fetchedInput); if (srcAttemptId == null) { return remaining .toArray(new InputAttemptIdentifier[remaining.size()]); } else { return new InputAttemptIdentifier[] { srcAttemptId }; } } LOG.warn("Failed to shuffle output of " + srcAttemptId + " from " + host, ioe); // Cleanup the fetchedInput cleanupFetchedInput(fetchedInput); // metrics.failedFetch(); return new InputAttemptIdentifier[] { srcAttemptId }; } } private void cleanupFetchedInput(FetchedInput fetchedInput) { if (fetchedInput != null) { try { fetchedInput.abort(); } catch (IOException e) { LOG.info("Failure to cleanup fetchedInput: " + fetchedInput); } } } /** * Check connection needs to be re-established. * * @param srcAttemptId * @param ioe * @return true to indicate connection retry. false otherwise. * @throws IOException */ private boolean shouldRetry(InputAttemptIdentifier srcAttemptId, IOException ioe) { if (!(ioe instanceof SocketTimeoutException)) { return false; } // First time to retry. long currentTime = System.currentTimeMillis(); if (retryStartTime == 0) { retryStartTime = currentTime; } if (currentTime - retryStartTime < httpConnectionParams.getReadTimeout()) { LOG.warn("Shuffle output from " + srcAttemptId + " failed, retry it."); //retry connecting to the host return true; } else { // timeout, prepare to be failed. LOG.warn("Timeout for copying MapOutput with retry on host " + host + "after " + httpConnectionParams.getReadTimeout() + "milliseconds."); return false; } } /** * Do some basic verification on the input received -- Being defensive * * @param compressedLength * @param decompressedLength * @param fetchPartition * @param srcAttemptId * @param pathComponent * @return true/false, based on if the verification succeeded or not */ private boolean verifySanity(long compressedLength, long decompressedLength, int fetchPartition, InputAttemptIdentifier srcAttemptId, String pathComponent) { if (compressedLength < 0 || decompressedLength < 0) { // wrongLengthErrs.increment(1); LOG.warn(" invalid lengths in input header -> headerPathComponent: " + pathComponent + ", nextRemainingSrcAttemptId: " + getNextRemainingAttempt() + ", mappedSrcAttemptId: " + srcAttemptId + " len: " + compressedLength + ", decomp len: " + decompressedLength); return false; } if (fetchPartition != this.partition) { // wrongReduceErrs.increment(1); LOG.warn(" data for the wrong reduce -> headerPathComponent: " + pathComponent + "nextRemainingSrcAttemptId: " + getNextRemainingAttempt() + ", mappedSrcAttemptId: " + srcAttemptId + " len: " + compressedLength + " decomp len: " + decompressedLength + " for reduce " + fetchPartition); return false; } // Sanity check if (!remaining.contains(srcAttemptId)) { // wrongMapErrs.increment(1); LOG.warn("Invalid input. Received output for headerPathComponent: " + pathComponent + "nextRemainingSrcAttemptId: " + getNextRemainingAttempt() + ", mappedSrcAttemptId: " + srcAttemptId); return false; } return true; } private InputAttemptIdentifier getNextRemainingAttempt() { if (remaining.size() > 0) { return remaining.iterator().next(); } else { return null; } } /** * Builder for the construction of Fetchers */ public static class FetcherBuilder { private Fetcher fetcher; private boolean workAssigned = false; public FetcherBuilder(FetcherCallback fetcherCallback, HttpConnectionParams params, FetchedInputAllocator inputManager, ApplicationId appId, JobTokenSecretManager jobTokenSecretMgr, String srcNameTrimmed, Configuration conf, boolean localDiskFetchEnabled, String localHostname, int shufflePort, boolean asyncHttp) { this.fetcher = new Fetcher(fetcherCallback, params, inputManager, appId, jobTokenSecretMgr, srcNameTrimmed, conf, null, null, null, localDiskFetchEnabled, false, localHostname, shufflePort, asyncHttp); } public FetcherBuilder(FetcherCallback fetcherCallback, HttpConnectionParams params, FetchedInputAllocator inputManager, ApplicationId appId, JobTokenSecretManager jobTokenSecretMgr, String srcNameTrimmed, Configuration conf, RawLocalFileSystem localFs, LocalDirAllocator localDirAllocator, Path lockPath, boolean localDiskFetchEnabled, boolean sharedFetchEnabled, String localHostname, int shufflePort, boolean asyncHttp) { this.fetcher = new Fetcher(fetcherCallback, params, inputManager, appId, jobTokenSecretMgr, srcNameTrimmed, conf, localFs, localDirAllocator, lockPath, localDiskFetchEnabled, sharedFetchEnabled, localHostname, shufflePort, asyncHttp); } public FetcherBuilder setHttpConnectionParameters(HttpConnectionParams httpParams) { fetcher.httpConnectionParams = httpParams; return this; } public FetcherBuilder setCompressionParameters(CompressionCodec codec) { fetcher.codec = codec; return this; } public FetcherBuilder setIFileParams(boolean readAhead, int readAheadBytes) { fetcher.ifileReadAhead = readAhead; fetcher.ifileReadAheadLength = readAheadBytes; return this; } public FetcherBuilder assignWork(String host, int port, int partition, List<InputAttemptIdentifier> inputs) { fetcher.host = host; fetcher.port = port; fetcher.partition = partition; fetcher.srcAttempts = inputs; workAssigned = true; return this; } public Fetcher build() { Preconditions.checkState(workAssigned == true, "Cannot build a fetcher withot assigning work to it"); return fetcher; } } @Override public int hashCode() { return fetcherIdentifier; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Fetcher other = (Fetcher) obj; if (fetcherIdentifier != other.fetcherIdentifier) return false; return true; } }
/* * Copyright 2017 TrollSoftware ([email protected]) * * 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 jcomposition.processor.utils; import com.google.auto.common.MoreElements; import com.squareup.javapoet.*; import jcomposition.api.IComposition; import jcomposition.api.types.IExecutableElementContainer; import jcomposition.api.types.ITypeElementPairContainer; import javax.annotation.processing.ProcessingEnvironment; import javax.inject.Inject; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import java.util.*; public final class CompositionUtils { public static TypeSpec getCompositionTypeSpec(Map<IExecutableElementContainer, List<ITypeElementPairContainer>> methodsMap, TypeElement typeElement, ProcessingEnvironment env) { TypeSpec.Builder builder = TypeSpec.classBuilder("Composition"); builder.addModifiers(Modifier.FINAL, Modifier.PUBLIC); HashMap<FieldSpec, TypeSpec> fieldSpecs = getFieldsSpecs(methodsMap, typeElement, env); if (fieldSpecs.isEmpty()) return builder.build(); if (AnnotationUtils.hasInheritedInjectionAnnotation(typeElement)) { builder.addMethod(MethodSpec.constructorBuilder() .addStatement(AnnotationUtils.getCompositionName(typeElement, env) + ".this.onInject(this)") .addModifiers(Modifier.PRIVATE) .build()); } for (Map.Entry<FieldSpec, TypeSpec> entry : fieldSpecs.entrySet()) { builder.addField(entry.getKey()); if (entry.getValue() != null) { builder.addType(entry.getValue()); } } return builder.build(); } private static HashMap<FieldSpec, TypeSpec> getFieldsSpecs(Map<IExecutableElementContainer, List<ITypeElementPairContainer>> methodsMap, TypeElement typeElement, ProcessingEnvironment env) { String compositionName = AnnotationUtils.getCompositionName(typeElement, env); HashMap<ITypeElementPairContainer, TypeSpec.Builder> typeBuilders = new HashMap<ITypeElementPairContainer, TypeSpec.Builder>(); HashMap<FieldSpec, TypeSpec> specs = new HashMap<FieldSpec, TypeSpec>(); HashSet<ITypeElementPairContainer> finalContainers = new HashSet<ITypeElementPairContainer>(); for (Map.Entry<IExecutableElementContainer, List<ITypeElementPairContainer>> entry : methodsMap.entrySet()) { if (entry.getValue().isEmpty()) continue; for (ITypeElementPairContainer eContainer : entry.getValue()) { if (eContainer.isFinal()) { finalContainers.add(eContainer); continue; } TypeSpec.Builder tBuilder = typeBuilders.get(eContainer); if (tBuilder == null) { tBuilder = getFieldTypeBuilder(eContainer, env); } tBuilder.addMethods(getShareMethodSpecs(eContainer, entry, compositionName, env)); typeBuilders.put(eContainer, tBuilder); } } for (Map.Entry<ITypeElementPairContainer, TypeSpec.Builder> entry : typeBuilders.entrySet()) { TypeSpec typeSpec = entry.getValue().build(); specs.put(getFieldSpec(entry.getKey(), typeSpec), typeSpec); } for (ITypeElementPairContainer finalContainer : finalContainers) { // No type for final specs.put(getFieldSpec(finalContainer, finalContainer.getBind().getQualifiedName().toString()), null); } return specs; } private static FieldSpec getFieldSpec(ITypeElementPairContainer elementContainer, String typeName) { ClassName bestGuess = ClassName.bestGuess(typeName); String initializer = elementContainer.hasUseInjection() ? "null" : "new " + bestGuess.simpleName() + "()"; FieldSpec.Builder specBuilder = FieldSpec.builder(bestGuess, "composition_" + elementContainer.getBind().getSimpleName()) .addModifiers(Modifier.PROTECTED) .initializer(initializer); if (elementContainer.hasUseInjection()) { specBuilder.addAnnotation(ClassName.get(Inject.class)); } return specBuilder.build(); } private static FieldSpec getFieldSpec(ITypeElementPairContainer elementContainer, TypeSpec typeSpec) { return getFieldSpec(elementContainer, typeSpec.name); } private static TypeSpec.Builder getFieldTypeBuilder(ITypeElementPairContainer container, ProcessingEnvironment env) { DeclaredType baseDt = container.getDeclaredType(); TypeElement bindClassType = container.getBind(); TypeElement concreteIntf = container.getIntf(); boolean isInjected = container.hasUseInjection(); DeclaredType dt = Util.getDeclaredType(baseDt, concreteIntf, bindClassType, env); return TypeSpec.classBuilder("Composition_" + bindClassType.getSimpleName()) .addModifiers(Modifier.FINAL, isInjected ? Modifier.PUBLIC : Modifier.PROTECTED) .superclass(TypeName.get(dt)); } private static List<MethodSpec> getShareMethodSpecs(ITypeElementPairContainer tContainer, Map.Entry<IExecutableElementContainer, List<ITypeElementPairContainer>> entry, String compositionName, ProcessingEnvironment env) { List<MethodSpec> result = new ArrayList<MethodSpec>(); ExecutableElement executableElement = entry.getKey().getExecutableElement(); DeclaredType declaredType = entry.getKey().getDeclaredType(); MethodSpec.Builder builder = MethodSpec.overriding(executableElement, declaredType, env.getTypeUtils()); String statement = getShareExecutableStatement(executableElement, compositionName + ".this"); builder.addStatement(statement); MethodSpec spec = builder.build(); result.add(spec); if (tContainer.isAbstract()) { return result; } MethodSpec.Builder _builder = MethodSpec.methodBuilder("_super_" + executableElement.getSimpleName().toString()) .addModifiers(Modifier.PROTECTED) .addParameters(spec.parameters) .returns(spec.returnType); String _statement = getShareExecutableStatement(executableElement); _builder.addStatement(_statement); result.add(_builder.build()); return result; } private static String getShareExecutableStatement(ExecutableElement executableElement) { return getShareExecutableStatement(executableElement, "super"); } private static String getShareExecutableStatement(ExecutableElement executableElement, String className) { StringBuilder builder = new StringBuilder(); if (executableElement.getReturnType().getKind() != TypeKind.VOID) { builder.append("return "); } builder.append(String.format("%s.%s(%s)", className, executableElement.getSimpleName(), getParametersScope(executableElement))); return builder.toString(); } private static String getParametersScope(ExecutableElement element) { StringBuilder paramBuilder = new StringBuilder(); List<? extends VariableElement> parameters = element.getParameters(); for (int i = 0; i < parameters.size(); i++) { VariableElement variableElement = parameters.get(i); paramBuilder.append(variableElement.getSimpleName()); if (i < parameters.size() - 1) { paramBuilder.append(", "); } } return paramBuilder.toString(); } public static ClassName getNestedCompositionClassName(TypeElement typeElement, ProcessingEnvironment env) { String name = AnnotationUtils.getCompositionName(typeElement, env); ClassName nested = ClassName.get(MoreElements.getPackage(typeElement).toString(), name, "Composition"); return nested; } public static TypeName getInheritedCompositionInterface(TypeElement typeElement, ProcessingEnvironment env) { ClassName composition = ClassName.get(IComposition.class); ClassName nested = getNestedCompositionClassName(typeElement, env); return ParameterizedTypeName.get(composition, nested); } public static FieldSpec getCompositeFieldSpec(TypeElement typeElement) { TypeName compositionTypeName = TypeVariableName.get("Composition"); return FieldSpec.builder(compositionTypeName, "_composition") .addModifiers(Modifier.FINAL, Modifier.PRIVATE) .initializer("new " + compositionTypeName.toString() +"()") .build(); } public static MethodSpec getCompositeMethodSpec(TypeElement typeElement, ProcessingEnvironment env) { return MethodSpec.methodBuilder("getComposition") .addModifiers(Modifier.FINAL, Modifier.PUBLIC) .returns(TypeVariableName.get("Composition")) .addAnnotation(Override.class) .addStatement("return this._composition") .build(); } }
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Test; import io.reactivex.*; import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; import io.reactivex.internal.fuseable.*; import io.reactivex.observers.*; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; public class ObservableFlatMapCompletableTest { @Test public void normalObservable() { Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }).toObservable() .test() .assertResult(); } @Test public void mapperThrowsObservable() { PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<Integer> to = ps .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { throw new TestException(); } }).<Integer>toObservable() .test(); assertTrue(ps.hasObservers()); ps.onNext(1); to.assertFailure(TestException.class); assertFalse(ps.hasObservers()); } @Test public void mapperReturnsNullObservable() { PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<Integer> to = ps .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return null; } }).<Integer>toObservable() .test(); assertTrue(ps.hasObservers()); ps.onNext(1); to.assertFailure(NullPointerException.class); assertFalse(ps.hasObservers()); } @Test public void normalDelayErrorObservable() { Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }, true).toObservable() .test() .assertResult(); } @Test public void normalAsyncObservable() { Observable.range(1, 1000) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Observable.range(1, 100).subscribeOn(Schedulers.computation()).ignoreElements(); } }).toObservable() .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(); } @Test public void normalDelayErrorAllObservable() { TestObserver<Integer> to = Observable.range(1, 10).concatWith(Observable.<Integer>error(new TestException())) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.error(new TestException()); } }, true).<Integer>toObservable() .test() .assertFailure(CompositeException.class); List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); for (int i = 0; i < 11; i++) { TestHelper.assertError(errors, i, TestException.class); } } @Test public void normalDelayInnerErrorAllObservable() { TestObserver<Integer> to = Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.error(new TestException()); } }, true).<Integer>toObservable() .test() .assertFailure(CompositeException.class); List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); for (int i = 0; i < 10; i++) { TestHelper.assertError(errors, i, TestException.class); } } @Test public void normalNonDelayErrorOuterObservable() { Observable.range(1, 10).concatWith(Observable.<Integer>error(new TestException())) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }, false).toObservable() .test() .assertFailure(TestException.class); } @Test public void fusedObservable() { TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }).<Integer>toObservable() .subscribe(to); to .assertOf(ObserverFusion.<Integer>assertFuseable()) .assertOf(ObserverFusion.<Integer>assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } @Test public void disposedObservable() { TestHelper.checkDisposed(Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }).toObservable()); } @Test public void normal() { Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }) .test() .assertResult(); } @Test public void mapperThrows() { PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<Void> to = ps .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { throw new TestException(); } }) .test(); assertTrue(ps.hasObservers()); ps.onNext(1); to.assertFailure(TestException.class); assertFalse(ps.hasObservers()); } @Test public void mapperReturnsNull() { PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<Void> to = ps .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return null; } }) .test(); assertTrue(ps.hasObservers()); ps.onNext(1); to.assertFailure(NullPointerException.class); assertFalse(ps.hasObservers()); } @Test public void normalDelayError() { Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }, true) .test() .assertResult(); } @Test public void normalAsync() { Observable.range(1, 1000) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Observable.range(1, 100).subscribeOn(Schedulers.computation()).ignoreElements(); } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(); } @Test public void normalDelayErrorAll() { TestObserver<Void> to = Observable.range(1, 10).concatWith(Observable.<Integer>error(new TestException())) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.error(new TestException()); } }, true) .test() .assertFailure(CompositeException.class); List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); for (int i = 0; i < 11; i++) { TestHelper.assertError(errors, i, TestException.class); } } @Test public void normalDelayInnerErrorAll() { TestObserver<Void> to = Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.error(new TestException()); } }, true) .test() .assertFailure(CompositeException.class); List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); for (int i = 0; i < 10; i++) { TestHelper.assertError(errors, i, TestException.class); } } @Test public void normalNonDelayErrorOuter() { Observable.range(1, 10).concatWith(Observable.<Integer>error(new TestException())) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }, false) .test() .assertFailure(TestException.class); } @Test public void fused() { TestObserver<Integer> to = ObserverFusion.newTest(QueueFuseable.ANY); Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }) .<Integer>toObservable() .subscribe(to); to .assertOf(ObserverFusion.<Integer>assertFuseable()) .assertOf(ObserverFusion.<Integer>assertFusionMode(QueueFuseable.ASYNC)) .assertResult(); } @Test public void disposed() { TestHelper.checkDisposed(Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } })); } @Test public void innerObserver() { Observable.range(1, 3) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return new Completable() { @Override protected void subscribeActual(CompletableObserver observer) { observer.onSubscribe(Disposables.empty()); assertFalse(((Disposable)observer).isDisposed()); ((Disposable)observer).dispose(); assertTrue(((Disposable)observer).isDisposed()); } }; } }) .test(); } @Test public void badSource() { TestHelper.checkBadSourceObservable(new Function<Observable<Integer>, Object>() { @Override public Object apply(Observable<Integer> o) throws Exception { return o.flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }); } }, false, 1, null); } @Test public void fusedInternalsObservable() { Observable.range(1, 10) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }) .toObservable() .subscribe(new Observer<Object>() { @Override public void onSubscribe(Disposable d) { QueueDisposable<?> qd = (QueueDisposable<?>)d; try { assertNull(qd.poll()); } catch (Throwable ex) { throw new RuntimeException(ex); } assertTrue(qd.isEmpty()); qd.clear(); } @Override public void onNext(Object t) { } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); } @Test public void innerObserverObservable() { Observable.range(1, 3) .flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return new Completable() { @Override protected void subscribeActual(CompletableObserver observer) { observer.onSubscribe(Disposables.empty()); assertFalse(((Disposable)observer).isDisposed()); ((Disposable)observer).dispose(); assertTrue(((Disposable)observer).isDisposed()); } }; } }) .toObservable() .test(); } @Test public void badSourceObservable() { TestHelper.checkBadSourceObservable(new Function<Observable<Integer>, Object>() { @Override public Object apply(Observable<Integer> o) throws Exception { return o.flatMapCompletable(new Function<Integer, CompletableSource>() { @Override public CompletableSource apply(Integer v) throws Exception { return Completable.complete(); } }).toObservable(); } }, false, 1, null); } }
/* * 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.athena.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The completion date, current state, submission time, and state change reason (if applicable) for the query execution. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/QueryExecutionStatus" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class QueryExecutionStatus implements Serializable, Cloneable, StructuredPojo { /** * <p> * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is reserved for * future use. <code>RUNNING</code> indicates that the query has been submitted to the service, and Athena will * execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates that the query completed * without errors. <code>FAILED</code> indicates that the query experienced an error and did not complete * processing. <code>CANCELLED</code> indicates that a user input interrupted query execution. * </p> */ private String state; /** * <p> * Further detail about the status of the query. * </p> */ private String stateChangeReason; /** * <p> * The date and time that the query was submitted. * </p> */ private java.util.Date submissionDateTime; /** * <p> * The date and time that the query completed. * </p> */ private java.util.Date completionDateTime; /** * <p> * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is reserved for * future use. <code>RUNNING</code> indicates that the query has been submitted to the service, and Athena will * execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates that the query completed * without errors. <code>FAILED</code> indicates that the query experienced an error and did not complete * processing. <code>CANCELLED</code> indicates that a user input interrupted query execution. * </p> * * @param state * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is * reserved for future use. <code>RUNNING</code> indicates that the query has been submitted to the service, * and Athena will execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates * that the query completed without errors. <code>FAILED</code> indicates that the query experienced an error * and did not complete processing. <code>CANCELLED</code> indicates that a user input interrupted query * execution. * @see QueryExecutionState */ public void setState(String state) { this.state = state; } /** * <p> * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is reserved for * future use. <code>RUNNING</code> indicates that the query has been submitted to the service, and Athena will * execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates that the query completed * without errors. <code>FAILED</code> indicates that the query experienced an error and did not complete * processing. <code>CANCELLED</code> indicates that a user input interrupted query execution. * </p> * * @return The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is * reserved for future use. <code>RUNNING</code> indicates that the query has been submitted to the service, * and Athena will execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates * that the query completed without errors. <code>FAILED</code> indicates that the query experienced an * error and did not complete processing. <code>CANCELLED</code> indicates that a user input interrupted * query execution. * @see QueryExecutionState */ public String getState() { return this.state; } /** * <p> * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is reserved for * future use. <code>RUNNING</code> indicates that the query has been submitted to the service, and Athena will * execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates that the query completed * without errors. <code>FAILED</code> indicates that the query experienced an error and did not complete * processing. <code>CANCELLED</code> indicates that a user input interrupted query execution. * </p> * * @param state * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is * reserved for future use. <code>RUNNING</code> indicates that the query has been submitted to the service, * and Athena will execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates * that the query completed without errors. <code>FAILED</code> indicates that the query experienced an error * and did not complete processing. <code>CANCELLED</code> indicates that a user input interrupted query * execution. * @return Returns a reference to this object so that method calls can be chained together. * @see QueryExecutionState */ public QueryExecutionStatus withState(String state) { setState(state); return this; } /** * <p> * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is reserved for * future use. <code>RUNNING</code> indicates that the query has been submitted to the service, and Athena will * execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates that the query completed * without errors. <code>FAILED</code> indicates that the query experienced an error and did not complete * processing. <code>CANCELLED</code> indicates that a user input interrupted query execution. * </p> * * @param state * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is * reserved for future use. <code>RUNNING</code> indicates that the query has been submitted to the service, * and Athena will execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates * that the query completed without errors. <code>FAILED</code> indicates that the query experienced an error * and did not complete processing. <code>CANCELLED</code> indicates that a user input interrupted query * execution. * @see QueryExecutionState */ public void setState(QueryExecutionState state) { withState(state); } /** * <p> * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is reserved for * future use. <code>RUNNING</code> indicates that the query has been submitted to the service, and Athena will * execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates that the query completed * without errors. <code>FAILED</code> indicates that the query experienced an error and did not complete * processing. <code>CANCELLED</code> indicates that a user input interrupted query execution. * </p> * * @param state * The state of query execution. <code>QUEUED</code> state is listed but is not used by Athena and is * reserved for future use. <code>RUNNING</code> indicates that the query has been submitted to the service, * and Athena will execute the query as soon as resources are available. <code>SUCCEEDED</code> indicates * that the query completed without errors. <code>FAILED</code> indicates that the query experienced an error * and did not complete processing. <code>CANCELLED</code> indicates that a user input interrupted query * execution. * @return Returns a reference to this object so that method calls can be chained together. * @see QueryExecutionState */ public QueryExecutionStatus withState(QueryExecutionState state) { this.state = state.toString(); return this; } /** * <p> * Further detail about the status of the query. * </p> * * @param stateChangeReason * Further detail about the status of the query. */ public void setStateChangeReason(String stateChangeReason) { this.stateChangeReason = stateChangeReason; } /** * <p> * Further detail about the status of the query. * </p> * * @return Further detail about the status of the query. */ public String getStateChangeReason() { return this.stateChangeReason; } /** * <p> * Further detail about the status of the query. * </p> * * @param stateChangeReason * Further detail about the status of the query. * @return Returns a reference to this object so that method calls can be chained together. */ public QueryExecutionStatus withStateChangeReason(String stateChangeReason) { setStateChangeReason(stateChangeReason); return this; } /** * <p> * The date and time that the query was submitted. * </p> * * @param submissionDateTime * The date and time that the query was submitted. */ public void setSubmissionDateTime(java.util.Date submissionDateTime) { this.submissionDateTime = submissionDateTime; } /** * <p> * The date and time that the query was submitted. * </p> * * @return The date and time that the query was submitted. */ public java.util.Date getSubmissionDateTime() { return this.submissionDateTime; } /** * <p> * The date and time that the query was submitted. * </p> * * @param submissionDateTime * The date and time that the query was submitted. * @return Returns a reference to this object so that method calls can be chained together. */ public QueryExecutionStatus withSubmissionDateTime(java.util.Date submissionDateTime) { setSubmissionDateTime(submissionDateTime); return this; } /** * <p> * The date and time that the query completed. * </p> * * @param completionDateTime * The date and time that the query completed. */ public void setCompletionDateTime(java.util.Date completionDateTime) { this.completionDateTime = completionDateTime; } /** * <p> * The date and time that the query completed. * </p> * * @return The date and time that the query completed. */ public java.util.Date getCompletionDateTime() { return this.completionDateTime; } /** * <p> * The date and time that the query completed. * </p> * * @param completionDateTime * The date and time that the query completed. * @return Returns a reference to this object so that method calls can be chained together. */ public QueryExecutionStatus withCompletionDateTime(java.util.Date completionDateTime) { setCompletionDateTime(completionDateTime); 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 (getState() != null) sb.append("State: ").append(getState()).append(","); if (getStateChangeReason() != null) sb.append("StateChangeReason: ").append(getStateChangeReason()).append(","); if (getSubmissionDateTime() != null) sb.append("SubmissionDateTime: ").append(getSubmissionDateTime()).append(","); if (getCompletionDateTime() != null) sb.append("CompletionDateTime: ").append(getCompletionDateTime()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof QueryExecutionStatus == false) return false; QueryExecutionStatus other = (QueryExecutionStatus) obj; if (other.getState() == null ^ this.getState() == null) return false; if (other.getState() != null && other.getState().equals(this.getState()) == false) return false; if (other.getStateChangeReason() == null ^ this.getStateChangeReason() == null) return false; if (other.getStateChangeReason() != null && other.getStateChangeReason().equals(this.getStateChangeReason()) == false) return false; if (other.getSubmissionDateTime() == null ^ this.getSubmissionDateTime() == null) return false; if (other.getSubmissionDateTime() != null && other.getSubmissionDateTime().equals(this.getSubmissionDateTime()) == false) return false; if (other.getCompletionDateTime() == null ^ this.getCompletionDateTime() == null) return false; if (other.getCompletionDateTime() != null && other.getCompletionDateTime().equals(this.getCompletionDateTime()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode()); hashCode = prime * hashCode + ((getStateChangeReason() == null) ? 0 : getStateChangeReason().hashCode()); hashCode = prime * hashCode + ((getSubmissionDateTime() == null) ? 0 : getSubmissionDateTime().hashCode()); hashCode = prime * hashCode + ((getCompletionDateTime() == null) ? 0 : getCompletionDateTime().hashCode()); return hashCode; } @Override public QueryExecutionStatus clone() { try { return (QueryExecutionStatus) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.athena.model.transform.QueryExecutionStatusMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package com.dtflys.forest.backend.okhttp3.executor; import com.dtflys.forest.backend.BodyBuilder; import com.dtflys.forest.backend.HttpExecutor; import com.dtflys.forest.backend.okhttp3.logging.OkHttp3LogBodyMessage; import com.dtflys.forest.backend.url.URLBuilder; import com.dtflys.forest.exceptions.ForestRetryException; import com.dtflys.forest.http.ForestRequest; import com.dtflys.forest.http.ForestResponse; import com.dtflys.forest.logging.LogBodyMessage; import com.dtflys.forest.logging.LogConfiguration; import com.dtflys.forest.logging.ForestLogHandler; import com.dtflys.forest.logging.LogHeaderMessage; import com.dtflys.forest.logging.RequestLogMessage; import com.dtflys.forest.logging.RequestProxyLogMessage; import com.dtflys.forest.logging.ResponseLogMessage; import com.dtflys.forest.utils.RequestNameValue; import com.dtflys.forest.utils.StringUtils; import com.dtflys.forest.backend.okhttp3.conn.OkHttp3ConnectionManager; import com.dtflys.forest.backend.okhttp3.response.OkHttp3ForestResponseFactory; import com.dtflys.forest.backend.okhttp3.response.OkHttp3ResponseFuture; import com.dtflys.forest.backend.okhttp3.response.OkHttp3ResponseHandler; import com.dtflys.forest.converter.json.ForestJsonConverter; import com.dtflys.forest.exceptions.ForestNetworkException; import com.dtflys.forest.handler.LifeCycleHandler; import com.dtflys.forest.mapping.MappingTemplate; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.SocketAddress; import java.util.Date; import java.util.List; /** * @author gongjun[[email protected]] * @since 2018-02-27 17:55 */ public abstract class AbstractOkHttp3Executor implements HttpExecutor { private final static Logger log = LoggerFactory.getLogger(AbstractOkHttp3Executor.class); protected final ForestRequest request; private final OkHttp3ConnectionManager connectionManager; private final OkHttp3ResponseHandler okHttp3ResponseHandler; protected RequestLogMessage buildRequestMessage(int retryCount, Request okRequest) { RequestLogMessage message = new RequestLogMessage(); HttpUrl url = okRequest.url(); String scheme = url.scheme().toUpperCase(); String uri = url.uri().toString(); String method = okRequest.method(); message.setUri(uri); message.setType(method); message.setScheme(scheme); message.setRetryCount(retryCount); setLogHeaders(message, okRequest); setLogBody(message, okRequest); return message; } protected void setLogHeaders(RequestLogMessage message, Request okRequest) { Headers headers = okRequest.headers(); for (int i = 0; i < headers.size(); i++) { String name = headers.name(i); String value = headers.value(i); message.addHeader(new LogHeaderMessage(name, value)); } } protected void setLogBody(RequestLogMessage message, Request okRequest) { RequestBody requestBody = okRequest.body(); LogBodyMessage logBodyMessage = new OkHttp3LogBodyMessage(requestBody); message.setBody(logBodyMessage); } public void logRequest(int retryCount, Request okRequest, OkHttpClient okHttpClient) { LogConfiguration logConfiguration = request.getLogConfiguration(); if (!logConfiguration.isLogEnabled() || !logConfiguration.isLogRequest()) { return; } RequestLogMessage requestLogMessage = buildRequestMessage(retryCount, okRequest); requestLogMessage.setRequest(request); requestLogMessage.setRetryCount(retryCount); Proxy proxy = okHttpClient.proxy(); if (proxy != null) { RequestProxyLogMessage proxyLogMessage = new RequestProxyLogMessage(); SocketAddress address = proxy.address(); if (address instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) address; proxyLogMessage.setHost(inetSocketAddress.getHostString()); proxyLogMessage.setPort(inetSocketAddress.getPort() + ""); } } request.setRequestLogMessage(requestLogMessage); logConfiguration.getLogHandler().logRequest(requestLogMessage); } public void logResponse(long startTime, ForestResponse response) { LogConfiguration logConfiguration = request.getLogConfiguration(); if (!logConfiguration.isLogEnabled()) { return; } long endTime = System.currentTimeMillis(); ResponseLogMessage logMessage = new ResponseLogMessage(response, startTime, endTime, response.getStatusCode()); ForestLogHandler logHandler = logConfiguration.getLogHandler(); if (logHandler != null) { if (logConfiguration.isLogResponseStatus()) { logHandler.logResponseStatus(logMessage); } if (logConfiguration.isLogResponseContent() && response.isSuccess()) { logHandler.logResponseContent(logMessage); } } } protected AbstractOkHttp3Executor(ForestRequest request, OkHttp3ConnectionManager connectionManager, OkHttp3ResponseHandler okHttp3ResponseHandler) { this.request = request; this.connectionManager = connectionManager; this.okHttp3ResponseHandler = okHttp3ResponseHandler; } protected abstract BodyBuilder<Request.Builder> getBodyBuilder(); protected abstract URLBuilder getURLBuilder(); protected OkHttpClient getClient(ForestRequest request, LifeCycleHandler lifeCycleHandler) { return connectionManager.getClient(request, lifeCycleHandler); } protected void prepareMethod(Request.Builder builder) { } protected void prepareHeaders(Request.Builder builder) { ForestJsonConverter jsonConverter = request.getConfiguration().getJsonConverter(); List<RequestNameValue> headerList = request.getHeaderNameValueList(); String contentType = request.getContentType(); String contentEncoding = request.getContentEncoding(); if (headerList != null && !headerList.isEmpty()) { for (RequestNameValue nameValue : headerList) { String name = nameValue.getName(); if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Encoding".equalsIgnoreCase(name)) { builder.addHeader(name, MappingTemplate.getParameterValue(jsonConverter, nameValue.getValue())); } } } if (StringUtils.isNotEmpty(contentType)) { builder.addHeader("Content-Type", contentType); } if (StringUtils.isNotEmpty(contentEncoding)) { builder.addHeader("Content-Encoding", contentEncoding); } } protected void prepareBody(Request.Builder builder, final LifeCycleHandler lifeCycleHandler) { getBodyBuilder().buildBody(builder, request, lifeCycleHandler); } public void execute(final LifeCycleHandler lifeCycleHandler, int retryCount) { OkHttpClient okHttpClient = getClient(request, lifeCycleHandler); URLBuilder urlBuilder = getURLBuilder(); String url = urlBuilder.buildUrl(request); Request.Builder builder = new Request.Builder().url(url); prepareMethod(builder); prepareHeaders(builder); prepareBody(builder, lifeCycleHandler); final Request okRequest = builder.build(); Call call = okHttpClient.newCall(okRequest); final OkHttp3ForestResponseFactory factory = new OkHttp3ForestResponseFactory(); logRequest(retryCount, okRequest, okHttpClient); Date startDate = new Date(); long startTime = startDate.getTime(); if (request.isAsync()) { final OkHttp3ResponseFuture future = new OkHttp3ResponseFuture(); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { ForestRetryException retryException = new ForestRetryException( e, request, request.getRetryCount(), retryCount); try { request.getRetryer().canRetry(retryException); } catch (Throwable throwable) { future.failed(e); ForestResponse response = factory.createResponse(request, null, lifeCycleHandler, throwable); logResponse(startTime, response); lifeCycleHandler.handleError(request, response, e); return; } execute(lifeCycleHandler, retryCount + 1); } @Override public void onResponse(Call call, Response okResponse) throws IOException { ForestResponse response = factory.createResponse(request, okResponse, lifeCycleHandler, null); logResponse(startTime, response); Object result = null; if (response.isSuccess()) { if (request.getOnSuccess() != null) { result = okHttp3ResponseHandler.handleSuccess(response); } else { result = okHttp3ResponseHandler.handleSync(okResponse, response); } future.completed(result); } else { retryOrDoError(response, okResponse, future, lifeCycleHandler, retryCount, startTime); } } }); okHttp3ResponseHandler.handleFuture(future, factory); } else { Response okResponse = null; try { okResponse = call.execute(); } catch (IOException e) { ForestRetryException retryException = new ForestRetryException( e, request, request.getRetryCount(), retryCount); try { request.getRetryer().canRetry(retryException); } catch (Throwable throwable) { ForestResponse response = factory.createResponse(request, null, lifeCycleHandler, e); logResponse(startTime, response); lifeCycleHandler.handleSyncWithException(request, response, e); return; } execute(lifeCycleHandler, retryCount + 1); return; } ForestResponse response = factory.createResponse(request, okResponse, lifeCycleHandler, null); logResponse(startTime, response); if (response.isError()) { retryOrDoError(response, okResponse, null, lifeCycleHandler, retryCount, startTime); return; } okHttp3ResponseHandler.handleSync(okResponse, response); } } private void retryOrDoError( ForestResponse response, Response okResponse, OkHttp3ResponseFuture future, LifeCycleHandler lifeCycleHandler, int retryCount, long startTime) { ForestNetworkException networkException = new ForestNetworkException(okResponse.message(), okResponse.code(), response); ForestRetryException retryException = new ForestRetryException( networkException, request, request.getRetryCount(), retryCount); try { request.getRetryer().canRetry(retryException); } catch (Throwable throwable) { if (future != null) { future.failed(new ForestNetworkException(okResponse.message(), okResponse.code(), response)); } logResponse(startTime, response); okHttp3ResponseHandler.handleSync(okResponse, response); return; } execute(lifeCycleHandler, retryCount + 1); } @Override public void execute(final LifeCycleHandler lifeCycleHandler) { execute(lifeCycleHandler, 0); } @Override public void close() { } }
/* ************************************************************************************ * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011 * encuestame Development Team. * Licensed under the Apache Software License version 2.0 * 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.encuestame.persistence.domain; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.encuestame.persistence.domain.security.Account; import org.encuestame.persistence.domain.security.Group; import org.encuestame.persistence.domain.security.UserAccount; import org.encuestame.persistence.domain.survey.SurveyGroup; import org.encuestame.utils.enums.Status; import org.hibernate.search.annotations.DocumentId; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; /** * Project. * @author Picado, Juan juanATencuestame.org * @since October 17, 2009 * @version $Id$ */ @Entity @Table(name = "project") @Indexed(index="Project") public class Project { private Long proyectId; private String projectDescription; private String projectName; private Status projectStatus = Status.ACTIVE; private String projectInfo; private Date projectDateStart; private Date projectDateFinish; private Account users; private Priority priority = Priority.MEDIUM; private UserAccount lead; private Boolean notifyMembers; private Boolean hideProject; private Boolean published; /** Survey Groups on the project. **/ private Set<SurveyGroup> surveyGroups = new HashSet<SurveyGroup>(); /** Locations selected for this project. **/ private Set<GeoPoint> locations = new HashSet<GeoPoint>(); /** Group of user for this project. **/ private Set<Group> groups = new HashSet<Group>(); /** List of User for the project. **/ private Set<UserAccount> secUserSecondaries = new HashSet<UserAccount>(); /** */ public enum Priority { /** * */ HIGH, /** * */ MEDIUM, /** * */ LOW;} /** * @return proyectId */ @Id @DocumentId @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "project_id", unique = true, nullable = false) public Long getProyectId() { return this.proyectId; } /** * @param proyectId proyectId */ public void setProyectId(Long proyectId) { this.proyectId = proyectId; } /** * @return projectDescription */ @Field(index = Index.TOKENIZED) @Column(name = "description", nullable = true, length = 600) public String getProjectDescription() { return this.projectDescription; } /** * @param projectDescription projectDescription */ public void setProjectDescription(final String projectDescription) { this.projectDescription = projectDescription; } /** * @return the projectName */ @Field(index = Index.TOKENIZED) @Column(name = "project_name", nullable = false) public String getProjectName() { return projectName; } /** * @param projectName the projectName to set */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * @return projectInfo */ @Column(name = "project_info") @Lob @Field(index = Index.TOKENIZED) public String getProjectInfo() { return this.projectInfo; } /** * @param projectInfo projectInfo */ public void setProjectInfo(final String projectInfo) { this.projectInfo = projectInfo; } /** * @return projectDateStart */ @Temporal(TemporalType.TIMESTAMP) @Field(index=Index.TOKENIZED, store=Store.YES) @Column(name = "date_start", nullable = false) public Date getProjectDateStart() { return this.projectDateStart; } /** * @param projectDateStart projectDateStart */ public void setProjectDateStart(final Date projectDateStart) { this.projectDateStart = projectDateStart; } /** * @return projectDateFinish */ @Temporal(TemporalType.TIMESTAMP) @Field(index=Index.TOKENIZED, store=Store.YES) @Column(name = "date_finish", nullable = false) public Date getProjectDateFinish() { return this.projectDateFinish; } /** * @param projectDateFinish projectDateFinish */ public void setProjectDateFinish(final Date projectDateFinish) { this.projectDateFinish = projectDateFinish; } /** * @return the locations */ @ManyToMany() @JoinTable(name="project_geoPoint", joinColumns={@JoinColumn(name="cat_id_project")}, inverseJoinColumns={@JoinColumn(name="cat_id_loc")}) public Set<GeoPoint> getLocations() { return locations; } /** * @param locations the locations to set */ public void setLocations(final Set<GeoPoint> locations) { this.locations = locations; } /** * @return the groups */ @ManyToMany() @JoinTable(name="project_group", joinColumns={@JoinColumn(name="cat_id_project")}, inverseJoinColumns={@JoinColumn(name="sec_id_group")}) public Set<Group> getGroups() { return groups; } /** * @param groups the groups to set */ public void setGroups(final Set<Group> groups) { this.groups = groups; } /** * @return the secUserSecondaries */ @ManyToMany() @JoinTable(name="userAccount_project", joinColumns={@JoinColumn(name="cat_id_project")}, inverseJoinColumns={@JoinColumn(name="sec_id_secondary")}) public Set<UserAccount> getSecUserSecondaries() { return secUserSecondaries; } /** * @param secUserSecondaries the secUserSecondaries to set */ public void setSecUserSecondaries(final Set<UserAccount> secUserSecondaries) { this.secUserSecondaries = secUserSecondaries; } /** * @return the surveyGroups */ @ManyToMany() @JoinTable(name="survey_group_project", joinColumns={@JoinColumn(name="cat_id_project")}, inverseJoinColumns={@JoinColumn(name="id_sid_format")}) public Set<SurveyGroup> getSurveyGroups() { return surveyGroups; } /** * @param surveyGroups the surveyGroups to set */ public void setSurveyGroups(final Set<SurveyGroup> surveyGroups) { this.surveyGroups = surveyGroups; } /** * @return the users */ @ManyToOne() public Account getUsers() { return users; } /** * @param users the users to set */ public void setUsers(Account users) { this.users = users; } /** * @return the priority */ @Column(name="priority") @Enumerated(EnumType.STRING) public Priority getPriority() { return priority; } /** * @param priority the priority to set */ public void setPriority(final Priority priority) { this.priority = priority; } /** * @return the lead */ @ManyToOne() public UserAccount getLead() { return lead; } /** * @param lead the lead to set */ public void setLead(UserAccount lead) { this.lead = lead; } /** * @return the notifyMembers */ @Column(name="notify_members") public Boolean getNotifyMembers() { return notifyMembers; } /** * @param notifyMembers the notifyMembers to set */ public void setNotifyMembers(Boolean notifyMembers) { this.notifyMembers = notifyMembers; } /** * @return the hideProject */ @Column(name="hide_project") public Boolean getHideProject() { return hideProject; } /** * @param hideProject the hideProject to set */ public void setHideProject(Boolean hideProject) { this.hideProject = hideProject; } /** * @return the projectStatus */ @Column(name="project_status") @Enumerated(EnumType.STRING) public Status getProjectStatus() { return projectStatus; } /** * @param projectStatus the projectStatus to set */ public void setProjectStatus(Status projectStatus) { this.projectStatus = projectStatus; } /** * @return the published */ @Column(name="published") public Boolean getPublished() { return published; } /** * @param published the published to set */ public void setPublished(Boolean published) { this.published = published; } }
/* * 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.calcite.linq4j.tree; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Builder for {@link BlockStatement}. * * <p>Has methods that help ensure that variable names are unique.</p> */ public class BlockBuilder { final List<Statement> statements = new ArrayList<>(); final Set<String> variables = new HashSet<>(); /** Contains final-fine-to-reuse-declarations. * An entry to this map is added when adding final declaration of a * statement with optimize=true parameter. */ final Map<Expression, DeclarationStatement> expressionForReuse = new HashMap<>(); private final boolean optimizing; private final BlockBuilder parent; private static final Shuttle OPTIMIZE_SHUTTLE = new OptimizeShuttle(); /** * Creates a non-optimizing BlockBuilder. */ public BlockBuilder() { this(true); } /** * Creates a BlockBuilder. * * @param optimizing Whether to eliminate common sub-expressions */ public BlockBuilder(boolean optimizing) { this(optimizing, null); } /** * Creates a BlockBuilder. * * @param optimizing Whether to eliminate common sub-expressions */ public BlockBuilder(boolean optimizing, BlockBuilder parent) { this.optimizing = optimizing; this.parent = parent; } /** * Clears this BlockBuilder. */ public void clear() { statements.clear(); variables.clear(); expressionForReuse.clear(); } /** * Appends a block to a list of statements and returns an expression * (possibly a variable) that represents the result of the newly added * block. */ public Expression append(String name, BlockStatement block) { return append(name, block, true); } /** * Appends an expression to a list of statements, optionally optimizing it * to a variable if it is used more than once. * * @param name Suggested variable name * @param block Expression * @param optimize Whether to try to optimize by assigning the expression to * a variable. Do not do this if the expression has * side-effects or a time-dependent value. */ public Expression append(String name, BlockStatement block, boolean optimize) { if (statements.size() > 0) { Statement lastStatement = statements.get(statements.size() - 1); if (lastStatement instanceof GotoStatement) { // convert "return expr;" into "expr;" statements.set(statements.size() - 1, Expressions.statement(((GotoStatement) lastStatement).expression)); } } Expression result = null; final Map<ParameterExpression, Expression> replacements = new IdentityHashMap<>(); final Shuttle shuttle = new SubstituteVariableVisitor(replacements); for (int i = 0; i < block.statements.size(); i++) { Statement statement = block.statements.get(i); if (!replacements.isEmpty()) { // Save effort, and only substitute variables if there are some. statement = statement.accept(shuttle); } if (statement instanceof DeclarationStatement) { DeclarationStatement declaration = (DeclarationStatement) statement; if (!variables.contains(declaration.parameter.name)) { add(statement); } else { String newName = newName(declaration.parameter.name, optimize); Expression x; // When initializer is null, append(name, initializer) can't deduce expression type if (declaration.initializer != null && isSafeForReuse(declaration)) { x = append(newName, declaration.initializer); } else { ParameterExpression pe = Expressions.parameter( declaration.parameter.type, newName); DeclarationStatement newDeclaration = Expressions.declare( declaration.modifiers, pe, declaration.initializer); x = pe; add(newDeclaration); } statement = null; result = x; if (declaration.parameter != x) { // declaration.parameter can be equal to x if exactly the same // declaration was present in BlockBuilder replacements.put(declaration.parameter, x); } } } else { add(statement); } if (i == block.statements.size() - 1) { if (statement instanceof DeclarationStatement) { result = ((DeclarationStatement) statement).parameter; } else if (statement instanceof GotoStatement) { statements.remove(statements.size() - 1); result = append_(name, ((GotoStatement) statement).expression, optimize); if (isSimpleExpression(result)) { // already simple; no need to declare a variable or // even to evaluate the expression } else { DeclarationStatement declare = Expressions.declare(Modifier.FINAL, newName(name, optimize), result); add(declare); result = declare.parameter; } } else { // not an expression -- result remains null } } } return result; } /** * Appends an expression to a list of statements, and returns an expression * (possibly a variable) that represents the result of the newly added * block. */ public Expression append(String name, Expression expression) { return append(name, expression, true); } /** * Appends an expression to a list of statements, if it is not null. */ public Expression appendIfNotNull(String name, Expression expression) { if (expression == null) { return null; } return append(name, expression, true); } /** * Appends an expression to a list of statements, optionally optimizing if * the expression is used more than once. */ public Expression append(String name, Expression expression, boolean optimize) { if (statements.size() > 0) { Statement lastStatement = statements.get(statements.size() - 1); if (lastStatement instanceof GotoStatement) { // convert "return expr;" into "expr;" statements.set(statements.size() - 1, Expressions.statement(((GotoStatement) lastStatement).expression)); } } return append_(name, expression, optimize); } private Expression append_(String name, Expression expression, boolean optimize) { if (isSimpleExpression(expression)) { // already simple; no need to declare a variable or // even to evaluate the expression return expression; } if (optimizing && optimize) { DeclarationStatement decl = getComputedExpression(expression); if (decl != null) { return decl.parameter; } } DeclarationStatement declare = Expressions.declare(Modifier.FINAL, newName(name, optimize), expression); add(declare); return declare.parameter; } /** * Checks if expression is simple enough to always inline at zero cost. * * @param expr expression to test * @return true when given expression is safe to always inline */ protected boolean isSimpleExpression(Expression expr) { if (expr instanceof ParameterExpression || expr instanceof ConstantExpression) { return true; } if (expr instanceof UnaryExpression) { UnaryExpression una = (UnaryExpression) expr; return una.getNodeType() == ExpressionType.Convert && isSimpleExpression(una.expression); } return false; } protected boolean isSafeForReuse(DeclarationStatement decl) { return (decl.modifiers & Modifier.FINAL) != 0 && !decl.parameter.name.startsWith("_"); } protected void addExpressionForReuse(DeclarationStatement decl) { if (isSafeForReuse(decl)) { Expression expr = normalizeDeclaration(decl); expressionForReuse.put(expr, decl); } } private boolean isCostly(DeclarationStatement decl) { return decl.initializer instanceof NewExpression; } /** * Prepares declaration for inlining: adds cast * @param decl inlining candidate * @return normalized expression */ private Expression normalizeDeclaration(DeclarationStatement decl) { Expression expr = decl.initializer; Type declType = decl.parameter.getType(); if (expr == null) { expr = Expressions.constant(null, declType); } else if (expr.getType() != declType) { expr = Expressions.convert_(expr, declType); } return expr; } /** * Returns the reference to ParameterExpression if given expression was * already computed and stored to local variable * @param expr expression to test * @return existing ParameterExpression or null */ public DeclarationStatement getComputedExpression(Expression expr) { if (parent != null) { DeclarationStatement decl = parent.getComputedExpression(expr); if (decl != null) { return decl; } } return optimizing ? expressionForReuse.get(expr) : null; } public void add(Statement statement) { statements.add(statement); if (statement instanceof DeclarationStatement) { DeclarationStatement decl = (DeclarationStatement) statement; String name = decl.parameter.name; if (!variables.add(name)) { throw new AssertionError("duplicate variable " + name); } addExpressionForReuse(decl); } } public void add(Expression expression) { add(Expressions.return_(null, expression)); } /** * Returns a block consisting of the current list of statements. */ public BlockStatement toBlock() { if (optimizing) { // We put an artificial limit of 10 iterations just to prevent an endless // loop. Optimize should not loop forever, however it is hard to prove if // it always finishes in reasonable time. for (int i = 0; i < 10; i++) { if (!optimize(createOptimizeShuttle(), true)) { break; } } optimize(createFinishingOptimizeShuttle(), false); } return Expressions.block(statements); } /** * Optimizes the list of statements. If an expression is used only once, * it is inlined. * * @return whether any optimizations were made */ private boolean optimize(Shuttle optimizer, boolean performInline) { int optimizeCount = 0; final UseCounter useCounter = new UseCounter(); for (Statement statement : statements) { if (statement instanceof DeclarationStatement && performInline) { DeclarationStatement decl = (DeclarationStatement) statement; useCounter.map.put(decl.parameter, new Slot()); } // We are added only counters up to current statement. // It is fine to count usages as the latter declarations cannot be used // in more recent statements. if (!useCounter.map.isEmpty()) { statement.accept(useCounter); } } final Map<ParameterExpression, Expression> subMap = new IdentityHashMap<>(useCounter.map.size()); final Shuttle visitor = new InlineVariableVisitor( subMap); final ArrayList<Statement> oldStatements = new ArrayList<>(statements); statements.clear(); for (Statement oldStatement : oldStatements) { if (oldStatement instanceof DeclarationStatement) { DeclarationStatement statement = (DeclarationStatement) oldStatement; final Slot slot = useCounter.map.get(statement.parameter); int count = slot == null ? Integer.MAX_VALUE - 10 : slot.count; if (count > 1 && isSimpleExpression(statement.initializer)) { // Inline simple final constants count = 1; } if (!isSafeForReuse(statement)) { // Don't inline variables that are not final. They might be assigned // more than once. count = 100; } if (isCostly(statement)) { // Don't inline variables that are costly, such as "new MyFunction()". // Later we will make their declarations static. count = 100; } if (statement.parameter.name.startsWith("_")) { // Don't inline variables whose name begins with "_". This // is a hacky way to prevent inlining. E.g. // final int _count = collection.size(); // foo(collection); // return collection.size() - _count; count = Integer.MAX_VALUE; } if (statement.initializer instanceof NewExpression && ((NewExpression) statement.initializer).memberDeclarations != null) { // Don't inline anonymous inner classes. Janino gets // confused referencing variables from deeply nested // anonymous classes. count = Integer.MAX_VALUE; } Expression normalized = normalizeDeclaration(statement); expressionForReuse.remove(normalized); switch (count) { case 0: // Only declared, never used. Throw away declaration. break; case 1: // declared, used once. inline it. subMap.put(statement.parameter, normalized); break; default: Statement beforeOptimize = oldStatement; if (!subMap.isEmpty()) { oldStatement = oldStatement.accept(visitor); // remap } oldStatement = oldStatement.accept(optimizer); if (beforeOptimize != oldStatement) { ++optimizeCount; if (count != Integer.MAX_VALUE && oldStatement instanceof DeclarationStatement && isSafeForReuse((DeclarationStatement) oldStatement) && isSimpleExpression( ((DeclarationStatement) oldStatement).initializer)) { // Allow to inline the expression that became simple after // optimizations. DeclarationStatement newDecl = (DeclarationStatement) oldStatement; subMap.put(newDecl.parameter, normalizeDeclaration(newDecl)); oldStatement = OptimizeShuttle.EMPTY_STATEMENT; } } if (oldStatement != OptimizeShuttle.EMPTY_STATEMENT) { if (oldStatement instanceof DeclarationStatement) { addExpressionForReuse((DeclarationStatement) oldStatement); } statements.add(oldStatement); } break; } } else { Statement beforeOptimize = oldStatement; if (!subMap.isEmpty()) { oldStatement = oldStatement.accept(visitor); // remap } oldStatement = oldStatement.accept(optimizer); if (beforeOptimize != oldStatement) { ++optimizeCount; } if (oldStatement != OptimizeShuttle.EMPTY_STATEMENT) { statements.add(oldStatement); } } } return optimizeCount > 0; } /** * Creates a shuttle that will be used during block optimization. * Sub-classes might provide more specific optimizations (e.g. partial * evaluation). * * @return shuttle used to optimize the statements when converting to block */ protected Shuttle createOptimizeShuttle() { return OPTIMIZE_SHUTTLE; } /** * Creates a final optimization shuttle. * Typically, the visitor will factor out constant expressions. * * @return shuttle that is used to finalize the optimization */ protected Shuttle createFinishingOptimizeShuttle() { return ClassDeclarationFinder.create(); } /** * Creates a name for a new variable, unique within this block, controlling * whether the variable can be inlined later. */ private String newName(String suggestion, boolean optimize) { if (!optimize && !suggestion.startsWith("_")) { // "_" prefix reminds us not to consider the variable for inlining suggestion = '_' + suggestion; } return newName(suggestion); } /** * Creates a name for a new variable, unique within this block. */ public String newName(String suggestion) { int i = 0; String candidate = suggestion; while (hasVariable(candidate)) { candidate = suggestion + (i++); } return candidate; } public boolean hasVariable(String name) { return variables.contains(name) || (parent != null && parent.hasVariable(name)); } public BlockBuilder append(Expression expression) { add(expression); return this; } /** Substitute Variable Visitor. */ private static class SubstituteVariableVisitor extends Shuttle { protected final Map<ParameterExpression, Expression> map; private final Map<ParameterExpression, Boolean> actives = new IdentityHashMap<>(); SubstituteVariableVisitor(Map<ParameterExpression, Expression> map) { this.map = map; } @Override public Expression visit(ParameterExpression parameterExpression) { Expression e = map.get(parameterExpression); if (e != null) { try { final Boolean put = actives.put(parameterExpression, true); if (put != null) { throw new AssertionError( "recursive expansion of " + parameterExpression + " in " + actives.keySet()); } // recursively substitute return e.accept(this); } finally { actives.remove(parameterExpression); } } return super.visit(parameterExpression); } } /** Inline Variable Visitor. */ private static class InlineVariableVisitor extends SubstituteVariableVisitor { InlineVariableVisitor( Map<ParameterExpression, Expression> map) { super(map); } @Override public Expression visit(UnaryExpression unaryExpression, Expression expression) { if (unaryExpression.getNodeType().modifiesLvalue) { expression = unaryExpression.expression; // avoid substitution if (expression instanceof ParameterExpression) { // avoid "optimization of" int t=1; t++; to 1++ return unaryExpression; } } return super.visit(unaryExpression, expression); } @Override public Expression visit(BinaryExpression binaryExpression, Expression expression0, Expression expression1) { if (binaryExpression.getNodeType().modifiesLvalue) { expression0 = binaryExpression.expression0; // avoid substitution if (expression0 instanceof ParameterExpression) { // If t is a declaration used only once, replace // int t; // int v = (t = 1) != a ? c : d; // with // int v = 1 != a ? c : d; if (map.containsKey(expression0)) { return expression1.accept(this); } } } return super.visit(binaryExpression, expression0, expression1); } } /** Use counter. */ private static class UseCounter extends VisitorImpl<Void> { private final Map<ParameterExpression, Slot> map = new IdentityHashMap<>(); @Override public Void visit(ParameterExpression parameter) { final Slot slot = map.get(parameter); if (slot != null) { // Count use of parameter, if it's registered. It's OK if // parameter is not registered. It might be beyond the control // of this block. slot.count++; } return super.visit(parameter); } @Override public Void visit(DeclarationStatement declarationStatement) { // Unlike base class, do not visit declarationStatement.parameter. if (declarationStatement.initializer != null) { declarationStatement.initializer.accept(this); } return null; } } /** * Holds the number of times a declaration was used. */ private static class Slot { private int count; } }
package ru.r2cloud.jradio.qarman; import java.io.IOException; import ru.r2cloud.jradio.util.BitInputStream; public class LongFrame extends ShortFrame { private static final double TWO_POWER_15 = Math.pow(2, 15); private static final double TWO_POWER_16 = Math.pow(2, 16); private boolean panelXpBeingReleased; private boolean panelYpBeingReleased; private boolean panelYmBeingReleased; private boolean panelXmBeingReleased; private Double solarPanelCurrentXpInside; private Double solarPanelCurrentXpOutside; private Double solarPanelCurrentYmInside; private Double solarPanelCurrentYmOutside; private Double solarPanelCurrentXmInside; private Double solarPanelCurrentXmOutside; private Double solarPanelCurrentYpInside; private Double solarPanelCurrentYpOutside; private Double solarPanelVoltageXp; private Double solarPanelVoltageYm; private Double solarPanelVoltageXm; private Double solarPanelVoltageYp; private AdcsState adcsState; private AttitudeEstimationMode attitudeEstimationMode; private ControlMode controlMode; private double cubeControl3V3Current; private double cubeControl5VCurrent; private double cubeControlVbatCurrent; private double magnetorquerCurrent; private double momentumWheelCurrent; private double magneticFieldX; private double magneticFieldY; private double magneticFieldZ; private double yAngularRate; private double yWheelSpeed; private double estimatedRollAngle; private double estimatedPitchAngle; private double estimatedYawAngle; private double estimatedXAngluarRate; private double estimatedYAngluarRate; private double estimatedZAngluarRate; private short temperatureAdcs; public LongFrame() { // do nothing } public LongFrame(BitInputStream bis) throws IOException { super(bis); panelXpBeingReleased = bis.readBoolean(); panelYpBeingReleased = bis.readBoolean(); panelYmBeingReleased = bis.readBoolean(); panelXmBeingReleased = bis.readBoolean(); solarPanelCurrentXpInside = calculateSolarPanelCurrent(bis); solarPanelCurrentXpOutside = calculateSolarPanelCurrent(bis); solarPanelCurrentYmInside = calculateSolarPanelCurrent(bis); solarPanelCurrentYmOutside = calculateSolarPanelCurrent(bis); solarPanelCurrentXmInside = calculateSolarPanelCurrent(bis); solarPanelCurrentXmOutside = calculateSolarPanelCurrent(bis); solarPanelCurrentYpInside = calculateSolarPanelCurrent(bis); solarPanelCurrentYpOutside = calculateSolarPanelCurrent(bis); solarPanelVoltageXp = calculateSolarPanelVoltage(bis); solarPanelVoltageYm = calculateSolarPanelVoltage(bis); solarPanelVoltageXm = calculateSolarPanelVoltage(bis); solarPanelVoltageYp = calculateSolarPanelVoltage(bis); int raw = bis.readUnsignedByte(); adcsState = AdcsState.valueOfCode(raw & 0b11); attitudeEstimationMode = AttitudeEstimationMode.valueOfCode((raw >> 2) & 0b111); controlMode = ControlMode.valueOfCode((raw >> 5) & 0b111); cubeControl3V3Current = bis.readUnsignedShort() * 0.48828125; cubeControl5VCurrent = bis.readUnsignedShort() * 0.48828125; cubeControlVbatCurrent = bis.readUnsignedShort() * 0.48828125; magnetorquerCurrent = bis.readUnsignedShort() * 0.1; momentumWheelCurrent = bis.readUnsignedShort() * 0.01; magneticFieldX = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; magneticFieldY = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; magneticFieldZ = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; yAngularRate = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; yWheelSpeed = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15); estimatedRollAngle = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; estimatedPitchAngle = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; estimatedYawAngle = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; estimatedXAngluarRate = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; estimatedYAngluarRate = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; estimatedZAngluarRate = (((bis.readUnsignedShort() + TWO_POWER_15) % TWO_POWER_16) - TWO_POWER_15) * 0.01; temperatureAdcs = bis.readShort(); } private static Double calculateSolarPanelVoltage(BitInputStream bis) throws IOException { int rawValue = bis.readUnsignedInt(10); if (rawValue == 0x3FF) { return null; } return rawValue * -0.0148 + 22.7614; } private static Double calculateSolarPanelCurrent(BitInputStream bis) throws IOException { int rawValue = bis.readUnsignedInt(10); if (rawValue == 0x3FF) { return null; } return rawValue * -0.5431 + 528.5093; } public boolean isPanelXpBeingReleased() { return panelXpBeingReleased; } public void setPanelXpBeingReleased(boolean panelXpBeingReleased) { this.panelXpBeingReleased = panelXpBeingReleased; } public boolean isPanelYpBeingReleased() { return panelYpBeingReleased; } public void setPanelYpBeingReleased(boolean panelYpBeingReleased) { this.panelYpBeingReleased = panelYpBeingReleased; } public boolean isPanelYmBeingReleased() { return panelYmBeingReleased; } public void setPanelYmBeingReleased(boolean panelYmBeingReleased) { this.panelYmBeingReleased = panelYmBeingReleased; } public boolean isPanelXmBeingReleased() { return panelXmBeingReleased; } public void setPanelXmBeingReleased(boolean panelXmBeingReleased) { this.panelXmBeingReleased = panelXmBeingReleased; } public AdcsState getAdcsState() { return adcsState; } public void setAdcsState(AdcsState adcsState) { this.adcsState = adcsState; } public AttitudeEstimationMode getAttitudeEstimationMode() { return attitudeEstimationMode; } public void setAttitudeEstimationMode(AttitudeEstimationMode attitudeEstimationMode) { this.attitudeEstimationMode = attitudeEstimationMode; } public ControlMode getControlMode() { return controlMode; } public void setControlMode(ControlMode controlMode) { this.controlMode = controlMode; } public double getCubeControl3V3Current() { return cubeControl3V3Current; } public void setCubeControl3V3Current(double cubeControl3V3Current) { this.cubeControl3V3Current = cubeControl3V3Current; } public double getCubeControl5VCurrent() { return cubeControl5VCurrent; } public void setCubeControl5VCurrent(double cubeControl5VCurrent) { this.cubeControl5VCurrent = cubeControl5VCurrent; } public double getCubeControlVbatCurrent() { return cubeControlVbatCurrent; } public void setCubeControlVbatCurrent(double cubeControlVbatCurrent) { this.cubeControlVbatCurrent = cubeControlVbatCurrent; } public double getMagnetorquerCurrent() { return magnetorquerCurrent; } public void setMagnetorquerCurrent(double magnetorquerCurrent) { this.magnetorquerCurrent = magnetorquerCurrent; } public double getMomentumWheelCurrent() { return momentumWheelCurrent; } public void setMomentumWheelCurrent(double momentumWheelCurrent) { this.momentumWheelCurrent = momentumWheelCurrent; } public double getMagneticFieldX() { return magneticFieldX; } public void setMagneticFieldX(double magneticFieldX) { this.magneticFieldX = magneticFieldX; } public double getMagneticFieldY() { return magneticFieldY; } public void setMagneticFieldY(double magneticFieldY) { this.magneticFieldY = magneticFieldY; } public double getMagneticFieldZ() { return magneticFieldZ; } public void setMagneticFieldZ(double magneticFieldZ) { this.magneticFieldZ = magneticFieldZ; } public double getYAngularRate() { return yAngularRate; } public void setYAngularRate(double yAngularRate) { this.yAngularRate = yAngularRate; } public double getYWheelSpeed() { return yWheelSpeed; } public void setYWheelSpeed(double yWheelSpeed) { this.yWheelSpeed = yWheelSpeed; } public double getEstimatedRollAngle() { return estimatedRollAngle; } public void setEstimatedRollAngle(double estimatedRollAngle) { this.estimatedRollAngle = estimatedRollAngle; } public double getEstimatedPitchAngle() { return estimatedPitchAngle; } public void setEstimatedPitchAngle(double estimatedPitchAngle) { this.estimatedPitchAngle = estimatedPitchAngle; } public double getEstimatedYawAngle() { return estimatedYawAngle; } public void setEstimatedYawAngle(double estimatedYawAngle) { this.estimatedYawAngle = estimatedYawAngle; } public double getEstimatedXAngluarRate() { return estimatedXAngluarRate; } public void setEstimatedXAngluarRate(double estimatedXAngluarRate) { this.estimatedXAngluarRate = estimatedXAngluarRate; } public double getEstimatedYAngluarRate() { return estimatedYAngluarRate; } public void setEstimatedYAngluarRate(double estimatedYAngluarRate) { this.estimatedYAngluarRate = estimatedYAngluarRate; } public double getEstimatedZAngluarRate() { return estimatedZAngluarRate; } public void setEstimatedZAngluarRate(double estimatedZAngluarRate) { this.estimatedZAngluarRate = estimatedZAngluarRate; } public short getTemperatureAdcs() { return temperatureAdcs; } public void setTemperatureAdcs(short temperatureAdcs) { this.temperatureAdcs = temperatureAdcs; } public Double getSolarPanelCurrentXpInside() { return solarPanelCurrentXpInside; } public void setSolarPanelCurrentXpInside(Double solarPanelCurrentXpInside) { this.solarPanelCurrentXpInside = solarPanelCurrentXpInside; } public Double getSolarPanelCurrentXpOutside() { return solarPanelCurrentXpOutside; } public void setSolarPanelCurrentXpOutside(Double solarPanelCurrentXpOutside) { this.solarPanelCurrentXpOutside = solarPanelCurrentXpOutside; } public Double getSolarPanelCurrentYmInside() { return solarPanelCurrentYmInside; } public void setSolarPanelCurrentYmInside(Double solarPanelCurrentYmInside) { this.solarPanelCurrentYmInside = solarPanelCurrentYmInside; } public Double getSolarPanelCurrentYmOutside() { return solarPanelCurrentYmOutside; } public void setSolarPanelCurrentYmOutside(Double solarPanelCurrentYmOutside) { this.solarPanelCurrentYmOutside = solarPanelCurrentYmOutside; } public Double getSolarPanelCurrentXmInside() { return solarPanelCurrentXmInside; } public void setSolarPanelCurrentXmInside(Double solarPanelCurrentXmInside) { this.solarPanelCurrentXmInside = solarPanelCurrentXmInside; } public Double getSolarPanelCurrentXmOutside() { return solarPanelCurrentXmOutside; } public void setSolarPanelCurrentXmOutside(Double solarPanelCurrentXmOutside) { this.solarPanelCurrentXmOutside = solarPanelCurrentXmOutside; } public Double getSolarPanelCurrentYpInside() { return solarPanelCurrentYpInside; } public void setSolarPanelCurrentYpInside(Double solarPanelCurrentYpInside) { this.solarPanelCurrentYpInside = solarPanelCurrentYpInside; } public Double getSolarPanelCurrentYpOutside() { return solarPanelCurrentYpOutside; } public void setSolarPanelCurrentYpOutside(Double solarPanelCurrentYpOutside) { this.solarPanelCurrentYpOutside = solarPanelCurrentYpOutside; } public Double getSolarPanelVoltageXp() { return solarPanelVoltageXp; } public void setSolarPanelVoltageXp(Double solarPanelVoltageXp) { this.solarPanelVoltageXp = solarPanelVoltageXp; } public Double getSolarPanelVoltageYm() { return solarPanelVoltageYm; } public void setSolarPanelVoltageYm(Double solarPanelVoltageYm) { this.solarPanelVoltageYm = solarPanelVoltageYm; } public Double getSolarPanelVoltageXm() { return solarPanelVoltageXm; } public void setSolarPanelVoltageXm(Double solarPanelVoltageXm) { this.solarPanelVoltageXm = solarPanelVoltageXm; } public Double getSolarPanelVoltageYp() { return solarPanelVoltageYp; } public void setSolarPanelVoltageYp(Double solarPanelVoltageYp) { this.solarPanelVoltageYp = solarPanelVoltageYp; } }
/******************************************************************************* "FreePastry" Peer-to-Peer Application Development Substrate Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute for Software Systems. 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 Rice University (RICE), Max Planck Institute for Software Systems (MPI-SWS) 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 RICE, MPI-SWS and the contributors on an "as is" basis, without any representations or warranties of any kind, express or implied including, but not limited to, representations or warranties of non-infringement, merchantability or fitness for a particular purpose. In no event shall RICE, MPI-SWS 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 rice.pastry.testing; import rice.environment.Environment; import rice.environment.random.RandomSource; import rice.pastry.*; import java.io.IOException; import java.util.*; /** * NodeIdUnit tests the NodeId class. * * @version $Id: NodeIdUnit.java 3613 2007-02-15 14:45:14Z jstewart $ * * @author Andrew Ladd */ public class NodeIdUnit { private Id nid; private RandomSource rng; public Id createNodeId() { byte raw[] = new byte[Id.IdBitLength >> 3]; rng.nextBytes(raw); Id nodeId = Id.build(raw); System.out.println("created node " + nodeId); byte copy[] = new byte[raw.length]; nodeId.blit(copy); for (int i = 0; i < raw.length; i++) if (copy[i] != raw[i]) System.out.println("blit test failed!"); copy = nodeId.copy(); for (int i = 0; i < raw.length; i++) if (copy[i] != raw[i]) System.out.println("copy test failed!"); return nodeId; } public void equalityTest() { System.out.println("--------------------------"); System.out.println("Creating oth"); Id oth = createNodeId(); if (nid.equals(oth) == false) System.out.println("not equal - as expected."); else System.out .println("ALERT: equal - warning this happens with very low probability"); if (nid.equals(nid) == true) System.out.println("equality seems reflexive."); else System.out.println("ALERT: equality is not reflexive."); System.out.println("hash code of nid: " + nid.hashCode()); System.out.println("hash code of oth: " + oth.hashCode()); System.out.println("--------------------------"); } public void distanceTest() { System.out.println("--------------------------"); System.out.println("creating a and b respectively"); Id a = createNodeId(); Id b = createNodeId(); for (int i = 0; i < 100; i++) { Id.Distance adist = nid.distance(a); Id.Distance adist2 = a.distance(nid); Id.Distance bdist = nid.distance(b); System.out.println("adist =" + adist + "\n bdist=" + bdist); if (adist.equals(adist2) == true) System.out.println("distance seems reflexive"); else System.out.println("ALERT: distance is non-reflexive."); if (adist.equals(bdist) == true) System.out .println("ALERT: nodes seem at equal distance - very unlikely"); else System.out.println("nodes have different distance as expected."); System.out.println("result of comparison with a and b " + adist.compareTo(bdist)); System.out.println("result of comparison with a to itself " + adist.compareTo(adist2)); if (a.clockwise(b)) System.out.println("b is clockwise from a"); else System.out.println("b is counter-clockwise from a"); Id.Distance abs = a.distance(b); Id.Distance abl = a.longDistance(b); if (abs.compareTo(abl) != -1) System.out.println("ERROR: abs.compareTo(abl)=" + abs.compareTo(abl)); System.out.println("abs=" + abs); abs.shift(-1, 1); System.out.println("abs.shift(-1)=" + abs); abs.shift(1, 0); System.out.println("abs.shift(1)=" + abs); if (!abs.equals(a.distance(b))) System.out.println("SHIFT ERROR!"); a = createNodeId(); b = createNodeId(); } byte[] raw0 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] raw80 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -128 }; byte[] raw7f = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 127 }; byte[] t1 = { 0x62, (byte) 0xac, 0x0a, 0x6d, 0x26, 0x3a, (byte) 0xeb, (byte) 0xb1, (byte) 0xe4, (byte) 0x8e, 0x25, (byte) 0xf2, (byte) 0xe5, 0x0e, (byte) 0xa2, 0x13 }; byte[] t2 = { 0x3a, 0x3f, (byte) 0xfa, (byte) 0x82, 0x00, (byte) 0x91, (byte) 0xfb, (byte) 0x82, (byte) 0x9d, (byte) 0xd2, (byte) 0xd8, 0x42, (byte) 0x86, 0x40, 0x5d, (byte) 0xd7 }; a = Id.build(t1/* raw80 */); b = Id.build(t2/* raw7f */); Id n0 = Id.build(raw0); Id n7f = Id.build(raw7f); Id n80 = Id.build(raw80); Id c = n0; System.out.println("a=" + a + "b=" + b + "c=" + c); System.out.println("a.clockwise(b)=" + a.clockwise(b)); System.out.println("a.clockwise(a)=" + a.clockwise(a)); System.out.println("b.clockwise(b)=" + b.clockwise(b)); if (a.clockwise(c)) System.out.println("c is clockwise from a"); else System.out.println("c is counter-clockwise from a"); if (b.clockwise(c)) System.out.println("c is clockwise from b"); else System.out.println("c is counter-clockwise from b"); System.out.println("a.distance(b)" + a.distance(b) + "b.distance(a)=" + b.distance(a)); System.out.println("a.longDistance(b)" + a.longDistance(b) + "b.longDistance(a)=" + b.longDistance(a)); System.out.println("a.distance(a)" + a.distance(a) + "a.longDistance(a)=" + a.longDistance(a)); System.out.println("a.isBetween(a,n7f)=" + a.isBetween(a, n7f)); System.out.println("a.isBetween(n0,a)=" + a.isBetween(n0, a)); System.out.println("a.isBetween(n0,n7f)=" + a.isBetween(n0, n7f)); System.out.println("b.isBetween(n0,n80)=" + b.isBetween(n0, n80)); System.out.println("a.isBetween(a,n80)=" + a.isBetween(a, n80)); System.out.println("b.isBetween(n0,b)=" + b.isBetween(n0, b)); System.out.println("--------------------------"); } public void baseFiddlingTest() { System.out.println("--------------------------"); String bitRep = ""; for (int i = 0; i < Id.IdBitLength; i++) { if (nid.checkBit(i) == true) bitRep = bitRep + "1"; else bitRep = bitRep + "0"; } System.out.println(bitRep); String digRep = ""; for (int i = 0; i < Id.IdBitLength; i++) { digRep = digRep + nid.getDigit(i, 1); } System.out.println(digRep); if (bitRep.equals(digRep) == true) System.out.println("strings the same - as expected"); else System.out.println("ALERT: strings differ - this is wrong."); System.out.println("--------------------------"); } public void msdTest() { System.out.println("--------------------------"); System.out.println("creating a and b respectively"); Id a = createNodeId(); Id b = createNodeId(); Id.Distance adist = nid.distance(a); Id.Distance bdist = nid.distance(b); Id.Distance aldist = nid.longDistance(a); Id.Distance bldist = nid.longDistance(b); System.out.println("nid.dist(a)=" + adist); System.out.println("nid.longDist(a)=" + aldist); System.out.println("nid.dist(b)=" + bdist); System.out.println("nid.longDist(b)=" + bldist); System.out.println("adist.compareTo(bdist) " + adist.compareTo(bdist)); System.out.println("aldist.compareTo(bldist) " + aldist.compareTo(bldist)); System.out.println("msdb a and nid " + nid.indexOfMSDB(a)); System.out.println("msdb b and nid " + nid.indexOfMSDB(b)); if (nid.indexOfMSDB(a) == a.indexOfMSDB(nid)) System.out.println("msdb is symmetric"); else System.out.println("ALERT: msdb is not symmetric"); for (int i = 2; i <= 6; i++) { int msdd; System.out.println("msdd a and nid (base " + (1 << i) + ") " + (msdd = nid.indexOfMSDD(a, i)) + " val=" + a.getDigit(msdd, i) + "," + nid.getDigit(msdd, i)); System.out.println("msdd b and nid (base " + (1 << i) + ") " + (msdd = nid.indexOfMSDD(b, i)) + " val=" + b.getDigit(msdd, i) + "," + nid.getDigit(msdd, i)); } System.out.println("--------------------------"); } public void alternateTest() { System.out.println("--------------------------"); System.out.println("nid=" + nid); for (int b = 2; b < 7; b++) for (int num = 2; num <= (1 << b); num *= 2) for (int i = 1; i < num; i++) System.out.println("alternate (b=" + b + ") " + i + ":" + nid.getAlternateId(num, b, i)); System.out.println("--------------------------"); } public void domainPrefixTest() { System.out.println("--------------------------"); System.out.println("nid=" + nid); for (int b = 2; b < 7; b++) for (int row = nid.IdBitLength / b - 1; row >= 0; row--) for (int col = 0; col < (1 << b); col++) { Id domainFirst = nid.getDomainPrefix(row, col, 0, b); Id domainLast = nid.getDomainPrefix(row, col, -1, b); System.out.println("prefixes " + nid + domainFirst + domainLast); int cmp = domainFirst.compareTo(domainLast); boolean equal = domainFirst.equals(domainLast); if ((cmp == 0) != equal) System.out.println("ERROR, compareTo=" + cmp + " equal=" + equal); if (cmp == 1) System.out.println("ERROR, compareTo=" + cmp); } System.out.println("--------------------------"); } public NodeIdUnit() { Environment env = new Environment(); rng = env.getRandomSource(); System.out.println("Creating nid"); nid = createNodeId(); equalityTest(); distanceTest(); baseFiddlingTest(); msdTest(); alternateTest(); domainPrefixTest(); } public static void main(String args[]) { NodeIdUnit niu = new NodeIdUnit(); } }
package org.subzero.core.helper; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.subzero.core.bean.TvShowInfo; /** * TV Show Info Helper * @author Julien * */ public class TvShowInfoHelper { // Constants private static String PATTERN_S_TYPE = "(?<serie>.*?([\\(\\)\\-\\s](19|20)[0-9][0-9][\\(\\)\\-]?)*)[\\.\\_\\-\\s][s](?<season>\\d{2})(?<episodes>([e]\\d{2})*)(?<title>[\\.\\_\\-\\s].*?)?(?<releasegroup>-[^- ]*)?"; private static String EPISODE_SEPARATOR_S_TYPE = "e"; private static String PATTERN_X_TYPE = "(?<serie>.*?([\\(\\)\\-\\s](19|20)[0-9][0-9][\\(\\)\\-]?)*)[\\.\\_\\-\\s](?<season>\\d{1,2})(?<episodes>([x]\\d{2})*)(?<title>[\\.\\_\\-\\s].*?)?(?<releasegroup>-[^- ]*)?"; private static String EPISODE_SEPARATOR_X_TYPE = "x"; private static String PATTERN_N_TYPE = "(?<serie>.*?([\\(\\)\\-\\s](19|20)[0-9][0-9][\\(\\)\\-]?)*)[\\.\\_\\-\\s](?<season>\\d{1})(?<episodes>(\\d{2})*)(?<title>[\\.\\_\\-\\s].*?)?(?<releasegroup>-[^- ]*)?"; private static String PATTERN_EXT = "\\.(?<filetype>[0-9a-z]*)"; private static String PATTERN_SERIE_NO_YEAR = "(?<serie>.*?)([\\(\\)\\-\\s](19|20)[0-9][0-9][\\(\\)\\-]?)*[\\.\\_\\-\\s]$"; private static String OUTPUT_SEASON_PREFIX = "S"; private static String OUTPUT_EPISODE_PREFIX = "E"; private static char OUTPUT_RELEASE_GROUP_SEPARATOR = '-'; private static char OUTPUT_RELEASE_GROUP_STOPPER = '['; private static char OUTPUT_SEPARATOR = '.'; private static String OUTPUT_ZIPPED_SUBTITLE_EXTENSION = "zip"; /** * Clean the naming part for input * @param part * @return */ private static String cleanInputNamingPart(String namingPart) { if (namingPart == null) { return ""; } else { return namingPart.replace('.',' ').replace('_',' ').replace('-',' ').trim(); } } /** * Extract the release group from the naming part * @param namingPart * @return * @throws Exception */ public static String extractReleaseGroupNamingPart(String namingPart) throws Exception { if (namingPart == null) { return ""; } // Remove '-' first character String releaseGroupSeparator = String.valueOf(OUTPUT_RELEASE_GROUP_SEPARATOR); if (namingPart.startsWith(releaseGroupSeparator)) { namingPart = namingPart.substring(releaseGroupSeparator.length(), namingPart.length()).trim(); } return namingPart; } /** * Clean the release group from the naming part * @param namingPart * @return * @throws Exception */ public static String cleanReleaseGroupNamingPart(String namingPart) throws Exception { namingPart = extractReleaseGroupNamingPart(namingPart); // Remove '[...]' at the end of release group int posStopper = namingPart.indexOf(OUTPUT_RELEASE_GROUP_STOPPER); if (posStopper > -1) { namingPart = namingPart.substring(0, posStopper); } // Remove fake release groups (populated by SickBeard, SickRage, etc) for (String fakeReleaseGroup : PropertiesHelper.getSubLeecherReleaseGroupFakeList()) { if (fakeReleaseGroup != null && fakeReleaseGroup.toLowerCase().equals(namingPart.toLowerCase())) { return ""; } } return namingPart; } /** * Normalize the naming part for ouput * @param namingPart * @return */ private static String normalizeOutputNamingPart(String namingPart) { return namingPart.trim().replace(' ',TvShowInfoHelper.OUTPUT_SEPARATOR); } /** * Normalize the season or episode number for output * @param input * @return */ private static String normalizeOutputSeasonOrEpisode(Integer input) { if (input > 9) { return input.toString(); } else { return "0" + input.toString(); } } /** * Test if all episodes match between the two episodes lists * @param episodesToSearch * @param episodesInResult * @return */ public static boolean testIfAllEpisodeMatch(List<Integer> episodesToSearch, List<Integer> episodesInResult) { int nbEp = episodesToSearch.size(); if (nbEp != episodesInResult.size()) { return false; } for (int i = 0 ; i < nbEp ; i++) { if (!episodesToSearch.get(i).equals(episodesInResult.get(i))) { return false; } } return true; } /** * Test if at least one episode matches between the two episodes lists * @param episodesToSearch * @param episodesInResult * @return */ public static boolean testIfOneEpisodeMatches(List<Integer> episodesToSearch, List<Integer> episodesInResult) { boolean episodeMatch = false; for (Integer episodeToSearch : episodesToSearch) { for (Integer episodeInResult : episodesInResult) { if (episodeToSearch.intValue() == episodeInResult.intValue()) { episodeMatch = true; break; } } if (episodeMatch) { break; } } return episodeMatch; } /** * Test if at least one episode matches between the two episodes lists * @param episodesToSearch * @param episodeInResult * @return */ public static boolean testIfOneEpisodeMatches(List<Integer> episodesToSearch, Integer episodeInResult) { List<Integer> episodesInResult = new ArrayList<Integer>(); episodesInResult.add(episodeInResult); return testIfOneEpisodeMatches(episodesToSearch, episodesInResult); } /** * Test if two tv show info match (serie, season and episodes) * @param tvShowInfo1 * @param tvShowInfo2 * @return */ public static boolean testIfTvShowInfoMatch(TvShowInfo tvShowInfo1, TvShowInfo tvShowInfo2) { if (tvShowInfo1 == null && tvShowInfo2 == null) { return true; } if (tvShowInfo1 == null || tvShowInfo2 == null) { return false; } if ((tvShowInfo1.getSerie() == null && tvShowInfo2.getSerie() == null) || (tvShowInfo1.getSerie().equals(tvShowInfo2.getSerie())) && (tvShowInfo1.getSeason() == null && tvShowInfo2.getSeason() == null) || (tvShowInfo1.getSeason().equals(tvShowInfo2.getSeason())) && (tvShowInfo1.getEpisodes() == null && tvShowInfo2.getEpisodes() == null) || testIfAllEpisodeMatch(tvShowInfo1.getEpisodes(), tvShowInfo2.getEpisodes()) ) { // Serie, Season and Episodes match return true; } else { return false; } } /** * Populate structured TV Show Info for a type * @param value * @param cleanedValue * @param patternType * @param episodeSeparatorType * @param isFile if true, retrieve and test file extension (must be video) * @param removeYearFromSerieName * @param checkVideoFileExt * @return * @throws Exception */ private static TvShowInfo populateTvShowInfoForType(String value, String cleanedValue, String patternType, String episodeSeparatorType, boolean isFile, boolean removeYearFromSerieName, boolean checkVideoFileExt) throws Exception { Pattern ps = Pattern.compile(patternType, 2); Matcher ms = ps.matcher(cleanedValue); if (ms.matches()) { TvShowInfo tvShowInfo = new TvShowInfo(); String stSerie = TvShowInfoHelper.cleanInputNamingPart(ms.group("serie")); if (removeYearFromSerieName) { stSerie = removeYearsFromSerieName(stSerie); } tvShowInfo.setSerie(stSerie); tvShowInfo.setSeason(Integer.parseInt(TvShowInfoHelper.cleanInputNamingPart(ms.group("season")))); List<Integer> episodes = new ArrayList<Integer>(); String stEpisodes = TvShowInfoHelper.cleanInputNamingPart(ms.group("episodes")).toLowerCase(); if (episodeSeparatorType == null) { for (int i = 0 ; i < stEpisodes.length() ; i = i+2) { episodes.add(Integer.parseInt(stEpisodes.substring(i, i+2))); } } else { for (String episode : stEpisodes.split(episodeSeparatorType)) { if (!episode.equals("")) { episodes.add(Integer.parseInt(episode)); } } } tvShowInfo.setEpisodes(episodes); tvShowInfo.setTitle(TvShowInfoHelper.cleanInputNamingPart(ms.group("title"))); tvShowInfo.setReleaseGroup(TvShowInfoHelper.extractReleaseGroupNamingPart(ms.group("releasegroup"))); tvShowInfo.setCleanedReleaseGroup(TvShowInfoHelper.cleanReleaseGroupNamingPart(ms.group("releasegroup"))); if (isFile) { // Input string is a file name tvShowInfo.setFileType(TvShowInfoHelper.cleanInputNamingPart(ms.group("filetype")).toLowerCase()); tvShowInfo.setInputVideoFileName(value); } if (isValidTvShowInfo(tvShowInfo, checkVideoFileExt)) { return tvShowInfo; } } return null; } /** * Check if the TV Show Info is valid or not (all properties populated + video file type only if specified) * @param tvShowInfo * @param checkVideoFileExt * @return * @throws Exception */ private static boolean isValidTvShowInfo(TvShowInfo tvShowInfo, boolean checkVideoFileExt) throws Exception { if (tvShowInfo == null || (tvShowInfo.getSerie() == null || tvShowInfo.getSerie().equals("")) || (tvShowInfo.getSeason() == null || tvShowInfo.getSeason().intValue() < 1) || (tvShowInfo.getEpisodes() == null || tvShowInfo.getEpisodes().size() == 0)) { return false; } if (checkVideoFileExt) { // Check if file type exists and is video if (tvShowInfo.getFileType() != null && !tvShowInfo.getFileType().equals("") && tvShowInfo.getInputVideoFileName() != null && !tvShowInfo.getInputVideoFileName().equals("")) { for (String videoExtension : PropertiesHelper.getVideoFileExtensions()) { if (tvShowInfo.getFileType().toLowerCase().equals(videoExtension.toLowerCase())) { return true; } } } return false; } else { // No file extension test return true; } } /** * Clean the value from all noise strings in properties * @param inputVideofileName * @return * @throws Exception */ private static String cleanFromNoiseStrings(String value) throws Exception { for (String noiseString : PropertiesHelper.getInputFileNoiseStrings()) { value = value.replace(noiseString, ""); } return value; } /** * Populate structured TV Show Info from input value * @param value * @param isFile if true, retrieve and test file extension (must be video) * @param removeYearFromSerieName * @param checkVideoFileExt * @return * @throws Exception */ private static TvShowInfo populateTvShowInfo(String value, boolean isFile, boolean removeYearFromSerieName, boolean checkVideoFileExt) throws Exception { String cleanedValue = TvShowInfoHelper.cleanFromNoiseStrings(value); // Try with S type String patternS = TvShowInfoHelper.PATTERN_S_TYPE; if (isFile) { patternS += TvShowInfoHelper.PATTERN_EXT; } TvShowInfo tvShowInfo = populateTvShowInfoForType(value, cleanedValue, patternS, TvShowInfoHelper.EPISODE_SEPARATOR_S_TYPE, isFile, removeYearFromSerieName, checkVideoFileExt); if (tvShowInfo != null) { return tvShowInfo; } // Try with X type String patternX = TvShowInfoHelper.PATTERN_X_TYPE; if (isFile) { patternX += TvShowInfoHelper.PATTERN_EXT; } tvShowInfo = populateTvShowInfoForType(value, cleanedValue, patternX, TvShowInfoHelper.EPISODE_SEPARATOR_X_TYPE, isFile, removeYearFromSerieName, checkVideoFileExt); if (tvShowInfo != null) { return tvShowInfo; } // Try with N type String patternN = TvShowInfoHelper.PATTERN_N_TYPE; if (isFile) { patternN += TvShowInfoHelper.PATTERN_EXT; } tvShowInfo = populateTvShowInfoForType(value, cleanedValue, patternN, null, isFile, removeYearFromSerieName, checkVideoFileExt); return tvShowInfo; } /** * Populate structured TV Show Info from input video file name * @param inputVideoFileName * @param removeYearFromSerieName * @return * @throws Exception */ public static TvShowInfo populateTvShowInfo(String inputVideoFileName, boolean removeYearFromSerieName) throws Exception { return populateTvShowInfo(inputVideoFileName, removeYearFromSerieName, true); } /** * Populate structured TV Show Info from input video file name * @param inputVideoFileName * @param removeYearFromSerieName * @param checkVideoFileExt * @return * @throws Exception */ public static TvShowInfo populateTvShowInfo(String inputVideoFileName, boolean removeYearFromSerieName, boolean checkVideoFileExt) throws Exception { return populateTvShowInfo(inputVideoFileName, true, removeYearFromSerieName, checkVideoFileExt); } /** * Populate structured TV Show Info from free-text * @param freeText * @param removeYearFromSerieName * @return * @throws Exception */ public static TvShowInfo populateTvShowInfoFromFreeText(String freeText, boolean removeYearFromSerieName) throws Exception { return populateTvShowInfoFromFreeText(freeText, removeYearFromSerieName, false); } /** * Populate structured TV Show Info from free-text * @param freeText * @param removeYearFromSerieName * @return * @throws Exception */ public static TvShowInfo populateTvShowInfoFromFreeText(String freeText, boolean removeYearFromSerieName, boolean checkVideoFileExt) throws Exception { return populateTvShowInfo(freeText, false, removeYearFromSerieName, checkVideoFileExt); } /** * Get short name from structured TV Show Info (type-S) * @param tvShowInfo * @return */ public static String getShortName(TvShowInfo tvShowInfo) { StringBuilder sb = new StringBuilder(); sb.append(TvShowInfoHelper.normalizeOutputNamingPart(tvShowInfo.getSerie())); sb.append(TvShowInfoHelper.OUTPUT_SEPARATOR); sb.append(TvShowInfoHelper.OUTPUT_SEASON_PREFIX); sb.append(TvShowInfoHelper.normalizeOutputSeasonOrEpisode(tvShowInfo.getSeason())); for (Integer episode : tvShowInfo.getEpisodes()) { sb.append(TvShowInfoHelper.OUTPUT_EPISODE_PREFIX); sb.append(TvShowInfoHelper.normalizeOutputSeasonOrEpisode(episode)); } return sb.toString(); } /** * Get short name from structured TV Show Info (type-X) * @param tvShowInfo * @return */ public static String getShortNameTypeX(TvShowInfo tvShowInfo) { StringBuilder sb = new StringBuilder(); sb.append(TvShowInfoHelper.normalizeOutputNamingPart(tvShowInfo.getSerie())); sb.append(TvShowInfoHelper.OUTPUT_SEPARATOR); sb.append(tvShowInfo.getSeason()); for (Integer episode : tvShowInfo.getEpisodes()) { sb.append(TvShowInfoHelper.EPISODE_SEPARATOR_X_TYPE); sb.append(TvShowInfoHelper.normalizeOutputSeasonOrEpisode(episode)); } return sb.toString(); } /** * Prepare base output file name from structured TV Show Info * @param tvShowInfo * @return * @throws Exception */ public static String prepareBaseOutputFileName(TvShowInfo tvShowInfo, String language) throws Exception { StringBuilder sb = new StringBuilder(); sb.append(TvShowInfoHelper.getShortName(tvShowInfo)); if (!tvShowInfo.getTitle().equals("")) { sb.append(TvShowInfoHelper.OUTPUT_SEPARATOR); sb.append(TvShowInfoHelper.normalizeOutputNamingPart(tvShowInfo.getTitle())); } if (!tvShowInfo.getReleaseGroup().equals("")) { sb.append(TvShowInfoHelper.OUTPUT_RELEASE_GROUP_SEPARATOR); sb.append(TvShowInfoHelper.normalizeOutputNamingPart(tvShowInfo.getReleaseGroup())); } sb.append(TvShowInfoHelper.OUTPUT_SEPARATOR); sb.append(PropertiesHelper.getSubfileLanguageSuffix(language)); return sb.toString(); } /** * Prepare suffix file name of subtitle (e.g. .fr.srt) * @param language * @param subFileType * @return * @throws Exception */ public static String prepareSubtitleSuffixFileName(String language, String subFileType) throws Exception { StringBuilder sb = new StringBuilder(); sb.append(PropertiesHelper.getSubfileLanguageSuffix(language)); sb.append(TvShowInfoHelper.OUTPUT_SEPARATOR); sb.append(subFileType); return sb.toString(); } /** * Prepare output zipped subtitle file name from structured TV Show Info and subtitle language * @param tvShowInfo * @return * @throws Exception */ public static String prepareZippedSubtitleFileName(TvShowInfo tvShowInfo, String language) throws Exception { StringBuilder sb = new StringBuilder(); sb.append(TvShowInfoHelper.prepareBaseOutputFileName(tvShowInfo, language)); sb.append(TvShowInfoHelper.OUTPUT_SEPARATOR); sb.append(TvShowInfoHelper.OUTPUT_ZIPPED_SUBTITLE_EXTENSION); return sb.toString(); } /** * Prepare output subtitle file name from structured TV Show Info and subtitle language * @param tvShowInfo * @param language * @param subtitleFileType * @return * @throws Exception */ public static String prepareSubtitleFileName(TvShowInfo tvShowInfo, String language, String subtitleFileType) throws Exception { StringBuilder sb = new StringBuilder(); sb.append(TvShowInfoHelper.prepareBaseOutputFileName(tvShowInfo, language)); sb.append(TvShowInfoHelper.OUTPUT_SEPARATOR); sb.append(subtitleFileType); return sb.toString(); } /** * Remove years part from the serie name * @param serieName Example : House M.D. (2004-2013) ; Doctor Who 2005 * @return Example : House M.D. ; Doctor Who */ public static String removeYearsFromSerieName(String serieName) { if (serieName == null || serieName.equals("")) { return null; } serieName = serieName + " "; Pattern ps = Pattern.compile(TvShowInfoHelper.PATTERN_SERIE_NO_YEAR, 2); Matcher ms = ps.matcher(serieName); if (ms.matches()) { return ms.group("serie").trim(); } else { return serieName.trim(); } } }
package com.cmput402w2016.t1.data; import com.cmput402w2016.t1.util.Util; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Java object representing a given OSM node */ public class Node { // OSM ID of the Node private long osmId = Long.MIN_VALUE; // Where the node is (lat/lon/geohash) private Location location = new Location(Double.MIN_VALUE, Double.MIN_VALUE); // The mapping of all the node tags defined in OSM private Map<String, String> tags = new HashMap<>(); /** * Empty constructor */ public Node() { } /** * Construct the node with a geohash only * * @param geohash String geohash */ public Node(String geohash) { this.location = new Location(geohash); } /** * Construct the node with the lat lon only * * @param lat Double value of lat * @param lon Double value of lon */ public Node(Double lat, Double lon) { this.location = new Location(lat, lon); } /** * Construct the node with the location only * * @param loc Location object, value of loc */ public Node(Location loc) { this.location = loc; } /** * Custom equality for the Node object * * @param o Other object to compare to * @return Boolean, true if equals, false otherwise */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; if (osmId != node.osmId) return false; if (!location.equals(node.location)) return false; return tags.equals(node.tags); } /** * Custom hash code for the node object * * @return String hash code value of the node's location */ @Override public int hashCode() { return location.hashCode(); } /** * Constructor for the node with the full location and the serialized node tags * * @param geohash Location of the current node * @param serialized_tags String with a json object for all the node tags */ public Node(String geohash, String serialized_tags) { this.location = new Location(geohash); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(serialized_tags); JsonObject jsonObject = jsonElement.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { String key = entry.getKey(); JsonElement val = entry.getValue(); if (key.equals("id")) { this.osmId = val.getAsLong(); } else { this.tags.put(key, val.toString()); } } } /** * Constructor for the node with the full location and the serialized node tags * * @param geohash Location of the current node * @param tags Map of String:String containing all the node tags */ public Node(String geohash, Map<String, String> tags) { this.location = new Location(geohash); this.tags.putAll(tags); } /** * Set the OSM ID * * @param osmId String value of the OSM id */ public void setOsmId(String osmId) { this.osmId = Long.parseLong(osmId); } /** * Get the OSM ID * * @return long value of the OSM id */ public long getOsmId() { return this.osmId; } /** * Set the node's lat * * @param lat String value of the lat to set */ public void setLat(String lat) { this.location.setLat(Double.parseDouble(lat)); } /** * Set the node's lon * * @param lon String value of the lon to set */ public void setLon(String lon) { this.location.setLon(Double.parseDouble(lon)); } /** * Get the node's lat * * @return Double value of the node's lat */ public Double getLat() { return this.location.getLat(); } /** * Get the node's lon * * @return Double value of the node's lon */ public Double getLon() { return this.location.getLon(); } /** * Check if the node contains all the necessary values for operations * * @return True if all required fields are set, false otherwise */ public boolean isComplete() { return location.isValid() && osmId != Long.MIN_VALUE; } /** * Return the node's geohash * * @return String value of the node's geohash */ public String getGeohash() { return location.getGeohash(); } /** * Return the node's location * * @return Location object of the node's location */ public Location getLocation() { return location; } /** * Add a tag to the node's tags * * @param key Key of the tag, String * @param value Value of the tag, String */ public void addTag(String key, String value) { tags.put(key, value); } /** * Get all of the node's tags with the node id incorporated in the serialized json output * * @return String, serialized json output with node tags and ID */ public String getTagsWithIDAsSerializedJSON() { Map<String, String> m_tags = new HashMap<>(this.tags); m_tags.put("id", String.valueOf(this.getOsmId())); Gson gson = new Gson(); return gson.toJson(m_tags); } /** * Return the node as a serialized json string, matching the documentation specified in the project wiki * * @return String, current node as a serialized json object */ public String toSerializedJson() { JsonObject json = new JsonObject(); json.addProperty("geohash", this.getGeohash()); json.addProperty("lat", this.getLat()); json.addProperty("lon", this.getLon()); json.addProperty("osm_id", this.getOsmId()); JsonObject tags = new JsonObject(); for (Map.Entry<String, String> e : this.tags.entrySet()) { String key = e.getKey(); String value = e.getValue(); tags.addProperty(key, value); } json.add("tags", tags); return json.toString(); } /** * Return the string geohash of the closest neighbor to the actual specified location. * * @param segment_table HBase table containing the * @param actual Location that the user provided * @return String geohash representing the closet neighbor to the current node. Null if no neighbors. */ public String getClosestNeighborGeohash(Table segment_table, Location actual) { String[] neighbors = Segment.getNeighborGeohashesAsGeohashArray(this.getGeohash(), segment_table); String closest_neighbor = null; if (neighbors != null) { double distance = Double.MAX_VALUE; for (String neighbor : neighbors) { double temp_distance = actual.distance(new Location(neighbor)); if (Double.compare(temp_distance, distance) < 0) { distance = temp_distance; closest_neighbor = neighbor; } } } return closest_neighbor; } /** * Given a location object, return the closest node to that location. * * @param location Location object representing the lat and lon * @param node_table HBase table containing the nodes * @return Node object, null if node doesn't exist */ public static Node getClosestNodeFromLocation(Location location, Table node_table) { return getClosestNodeFromGeohash(location.getGeohash(), node_table); } /** * Given a lat and lon, return the closest node to that given location. * * @param lat String representing lat * @param lon String representing lon * @param node_table HBase table containing the nodes * @return Node object, null if node doesn't exist */ public static Node getClosestNodeFromLatLon(String lat, String lon, Table node_table) { Location location = new Location(lat, lon); String geoHash = location.getGeohash(); return getClosestNodeFromGeohash(geoHash, node_table); } /** * Take a geohash, get the node object with all fields populated. * * @param original_geohash String geohash representing the node (substring search) * @param node_table HBase table where all the nodes are stored * @return Node object, null if node doesn't exist */ public static Node getClosestNodeFromGeohash(String original_geohash, Table node_table) { String geohash = original_geohash; try { while (geohash != null) { Scan scan = new Scan(); scan.setRowPrefixFilter(Bytes.toBytes(geohash)); ResultScanner rs = node_table.getScanner(scan); Result r = rs.next(); if (r != null) { String actual_geohash = Bytes.toString(r.getRow()); String tags = Bytes.toString(r.getValue(Bytes.toBytes("data"), Bytes.toBytes("tags"))); return new Node(actual_geohash, tags); } geohash = Util.shorten(geohash); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * Take an osm node id, get the node object with all fields populated * * @param osm_id String osm id matching the node exactly * @param node_table HBase table where all the nodes are stored * @return Node object, null if node doesn't exist */ public static Node getNodeFromID(String osm_id, Table node_table) { try { Scan scan = new Scan(); scan.setFilter(new SingleColumnValueFilter( Bytes.toBytes("data"), Bytes.toBytes("osm_id"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(osm_id))); ResultScanner rs = node_table.getScanner(scan); Result r = rs.next(); if (r != null) { String actual_geohash = Bytes.toString(r.getRow()); String tags = Bytes.toString(r.getValue(Bytes.toBytes("data"), Bytes.toBytes("tags"))); return new Node(actual_geohash, tags); } } catch (IOException e) { e.printStackTrace(); } return null; } /** * Return the boolean if the location is valid * * @return Boolean, true if location is valid, false otherwise */ public boolean isValid() { return location.isValid(); } }
/* This file was generated by SableCC's ObjectMacro. */ package org.sablecc.objectmacro.codegeneration.java.macro; import java.util.*; public class MVersionEnumeration extends Macro { private DSeparator PackageDeclarationSeparator; private DBeforeFirst PackageDeclarationBeforeFirst; private DAfterLast PackageDeclarationAfterLast; private DNone PackageDeclarationNone; final List<Macro> list_PackageDeclaration; final Context PackageDeclarationContext = new Context(); final MacroValue PackageDeclarationValue; private DSeparator VersionsSeparator; private DBeforeFirst VersionsBeforeFirst; private DAfterLast VersionsAfterLast; private DNone VersionsNone; final List<String> list_Versions; final Context VersionsContext = new Context(); final StringValue VersionsValue; MVersionEnumeration( Macros macros) { setMacros(macros); this.list_PackageDeclaration = new LinkedList<>(); this.list_Versions = new LinkedList<>(); this.PackageDeclarationValue = new MacroValue( this.list_PackageDeclaration, this.PackageDeclarationContext); this.VersionsValue = new StringValue(this.list_Versions, this.VersionsContext); } MVersionEnumeration( List<Macro> pPackageDeclaration, String pVersions, Macros macros) { setMacros(macros); this.list_PackageDeclaration = new LinkedList<>(); this.list_Versions = new LinkedList<>(); this.PackageDeclarationValue = new MacroValue( this.list_PackageDeclaration, this.PackageDeclarationContext); this.VersionsValue = new StringValue(this.list_Versions, this.VersionsContext); if (pPackageDeclaration != null) { addAllPackageDeclaration(pPackageDeclaration); } if (pVersions != null) { addVersions(pVersions); } } public void addAllPackageDeclaration( List<Macro> macros) { if (macros == null) { throw ObjectMacroException.parameterNull("PackageDeclaration"); } if (this.cacheBuilder != null) { throw ObjectMacroException .cannotModify(this.getClass().getSimpleName()); } int i = 0; for (Macro macro : macros) { if (macro == null) { throw ObjectMacroException.macroNull(i, "PackageDeclaration"); } if (getMacros() != macro.getMacros()) { throw ObjectMacroException.diffMacros(); } verifyTypePackageDeclaration(macro); this.list_PackageDeclaration.add(macro); this.children.add(macro); Macro.cycleDetector.detectCycle(this, macro); i++; } } void verifyTypePackageDeclaration( Macro macro) { macro.apply(new InternalsInitializer("PackageDeclaration") { @Override void setPackageDeclaration( MPackageDeclaration mPackageDeclaration) { } }); } public void addPackageDeclaration( MPackageDeclaration macro) { if (macro == null) { throw ObjectMacroException.parameterNull("PackageDeclaration"); } if (this.cacheBuilder != null) { throw ObjectMacroException .cannotModify(this.getClass().getSimpleName()); } if (getMacros() != macro.getMacros()) { throw ObjectMacroException.diffMacros(); } this.list_PackageDeclaration.add(macro); this.children.add(macro); Macro.cycleDetector.detectCycle(this, macro); } public void addAllVersions( List<String> strings) { if (this.macros == null) { throw ObjectMacroException.parameterNull("Versions"); } if (this.cacheBuilder != null) { throw ObjectMacroException .cannotModify(this.getClass().getSimpleName()); } for (String string : strings) { if (string == null) { throw ObjectMacroException.parameterNull("Versions"); } this.list_Versions.add(string); } } public void addVersions( String string) { if (string == null) { throw ObjectMacroException.parameterNull("Versions"); } if (this.cacheBuilder != null) { throw ObjectMacroException .cannotModify(this.getClass().getSimpleName()); } this.list_Versions.add(string); } private String buildPackageDeclaration() { StringBuilder sb = new StringBuilder(); Context local_context = this.PackageDeclarationContext; List<Macro> macros = this.list_PackageDeclaration; int i = 0; int nb_macros = macros.size(); String expansion = null; if (this.PackageDeclarationBeforeFirst == null) { initPackageDeclarationDirectives(); } for (Macro macro : macros) { expansion = macro.build(local_context); expansion = this.PackageDeclarationBeforeFirst.apply(i, expansion, nb_macros); sb.append(expansion); i++; } return sb.toString(); } private String buildVersions() { StringBuilder sb = new StringBuilder(); List<String> strings = this.list_Versions; int i = 0; int nb_strings = strings.size(); if (this.VersionsSeparator == null) { initVersionsDirectives(); } for (String string : strings) { string = this.VersionsSeparator.apply(i, string, nb_strings); sb.append(string); i++; } return sb.toString(); } MacroValue getPackageDeclaration() { return this.PackageDeclarationValue; } StringValue getVersions() { return this.VersionsValue; } private void initPackageDeclarationInternals( Context context) { for (Macro macro : this.list_PackageDeclaration) { macro.apply(new InternalsInitializer("PackageDeclaration") { @Override void setPackageDeclaration( MPackageDeclaration mPackageDeclaration) { } }); } } private void initPackageDeclarationDirectives() { StringBuilder sb1 = new StringBuilder(); sb1.append(LINE_SEPARATOR); this.PackageDeclarationBeforeFirst = new DBeforeFirst(sb1.toString()); this.PackageDeclarationValue .setBeforeFirst(this.PackageDeclarationBeforeFirst); } private void initVersionsDirectives() { StringBuilder sb1 = new StringBuilder(); sb1.append(", "); this.VersionsSeparator = new DSeparator(sb1.toString()); this.VersionsValue.setSeparator(this.VersionsSeparator); } @Override void apply( InternalsInitializer internalsInitializer) { internalsInitializer.setVersionEnumeration(this); } public String build() { CacheBuilder cache_builder = this.cacheBuilder; if (cache_builder == null) { cache_builder = new CacheBuilder(); } else if (cache_builder.getExpansion() == null) { throw new InternalException("Cycle detection detected lately"); } else { return cache_builder.getExpansion(); } this.cacheBuilder = cache_builder; List<String> indentations = new LinkedList<>(); initPackageDeclarationInternals(null); initPackageDeclarationDirectives(); initVersionsDirectives(); StringBuilder sb0 = new StringBuilder(); MHeader m1 = getMacros().newHeader(); sb0.append(m1.build(null)); sb0.append(LINE_SEPARATOR); sb0.append(buildPackageDeclaration()); sb0.append(LINE_SEPARATOR); sb0.append(LINE_SEPARATOR); sb0.append("public enum VERSIONS"); sb0.append("{"); sb0.append(LINE_SEPARATOR); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); sb2.append(" "); indentations.add(sb2.toString()); sb1.append(buildVersions()); sb0.append(applyIndent(sb1.toString(), indentations.remove(indentations.size() - 1))); sb0.append(LINE_SEPARATOR); sb0.append("}"); cache_builder.setExpansion(sb0.toString()); return sb0.toString(); } @Override String build( Context context) { return build(); } private void setMacros( Macros macros) { if (macros == null) { throw new InternalException("macros cannot be null"); } this.macros = macros; } }
/* 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 java.nio; /** * HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose * the implementation of array based byte buffers. * <p> * ReadWriteHeapByteBuffer extends HeapByteBuffer with all the write methods. * </p> * <p> * This class is marked final for runtime performance. * </p> * */ final class ReadWriteHeapByteBuffer extends HeapByteBuffer { static ReadWriteHeapByteBuffer copy(HeapByteBuffer other, int markOfOther) { ReadWriteHeapByteBuffer buf = new ReadWriteHeapByteBuffer( other.backingArray, other.capacity(), other.offset); buf.limit = other.limit(); buf.position = other.position(); buf.mark = markOfOther; buf.order(other.order()); return buf; } ReadWriteHeapByteBuffer(byte[] backingArray) { super(backingArray); } ReadWriteHeapByteBuffer(int capacity) { super(capacity); } ReadWriteHeapByteBuffer(byte[] backingArray, int capacity, int arrayOffset) { super(backingArray, capacity, arrayOffset); } @Override public ByteBuffer asReadOnlyBuffer() { return ReadOnlyHeapByteBuffer.copy(this, mark); } @Override public ByteBuffer compact() { System.arraycopy(backingArray, position + offset, backingArray, offset, remaining()); position = limit - position; limit = capacity; mark = UNSET_MARK; return this; } @Override public ByteBuffer duplicate() { return copy(this, mark); } @Override public boolean isReadOnly() { return false; } @Override protected byte[] protectedArray() { return backingArray; } @Override protected int protectedArrayOffset() { return offset; } @Override protected boolean protectedHasArray() { return true; } @Override public ByteBuffer put(byte b) { if (position == limit) { throw new BufferOverflowException(); } backingArray[offset + position++] = b; return this; } @Override public ByteBuffer put(int index, byte b) { if (index < 0 || index >= limit) { throw new IndexOutOfBoundsException(); } backingArray[offset + index] = b; return this; } /* * Override ByteBuffer.put(byte[], int, int) to improve performance. * * (non-Javadoc) * * @see java.nio.ByteBuffer#put(byte[], int, int) */ @Override public ByteBuffer put(byte[] src, int off, int len) { if (off < 0 || len < 0 || (long) off + (long) len > src.length) { throw new IndexOutOfBoundsException(); } if (len > remaining()) { throw new BufferOverflowException(); } if (isReadOnly()) { throw new ReadOnlyBufferException(); } System.arraycopy(src, off, backingArray, offset + position, len); position += len; return this; } @Override public ByteBuffer putDouble(double value) { return putLong(Double.doubleToRawLongBits(value)); } @Override public ByteBuffer putDouble(int index, double value) { return putLong(index, Double.doubleToRawLongBits(value)); } @Override public ByteBuffer putFloat(float value) { return putInt(Float.floatToIntBits(value)); } @Override public ByteBuffer putFloat(int index, float value) { return putInt(index, Float.floatToIntBits(value)); } @Override public ByteBuffer putInt(int value) { int newPosition = position + 4; if (newPosition > limit) { throw new BufferOverflowException(); } store(position, value); position = newPosition; return this; } @Override public ByteBuffer putInt(int index, int value) { if (index < 0 || (long) index + 4 > limit) { throw new IndexOutOfBoundsException(); } store(index, value); return this; } @Override public ByteBuffer putLong(int index, long value) { if (index < 0 || (long) index + 8 > limit) { throw new IndexOutOfBoundsException(); } store(index, value); return this; } @Override public ByteBuffer putLong(long value) { int newPosition = position + 8; if (newPosition > limit) { throw new BufferOverflowException(); } store(position, value); position = newPosition; return this; } @Override public ByteBuffer putShort(int index, short value) { if (index < 0 || (long) index + 2 > limit) { throw new IndexOutOfBoundsException(); } store(index, value); return this; } @Override public ByteBuffer putShort(short value) { int newPosition = position + 2; if (newPosition > limit) { throw new BufferOverflowException(); } store(position, value); position = newPosition; return this; } @Override public ByteBuffer slice() { ReadWriteHeapByteBuffer slice = new ReadWriteHeapByteBuffer( backingArray, remaining(), offset + position); slice.order = order; return slice; } }
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.source.codeStyle.lineIndent; import com.intellij.lang.Language; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.project.Project; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.lineIndent.LineIndentProvider; import com.intellij.psi.impl.source.codeStyle.SemanticEditorPosition; import com.intellij.psi.impl.source.codeStyle.SemanticEditorPosition.SyntaxElement; import com.intellij.psi.impl.source.codeStyle.lineIndent.IndentCalculator.BaseLineOffsetCalculator; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.intellij.formatting.Indent.Type; import static com.intellij.formatting.Indent.Type.*; import static com.intellij.psi.impl.source.codeStyle.lineIndent.JavaLikeLangLineIndentProvider.JavaLikeElement.*; /** * A base class Java-like language line indent provider. If JavaLikeLangLineIndentProvider is unable to calculate * the indentation, it forwards the request to FormatterBasedLineIndentProvider. */ public abstract class JavaLikeLangLineIndentProvider implements LineIndentProvider{ public enum JavaLikeElement implements SyntaxElement { Whitespace, Semicolon, BlockOpeningBrace, BlockClosingBrace, ArrayOpeningBracket, ArrayClosingBracket, RightParenthesis, LeftParenthesis, Colon, SwitchCase, SwitchDefault, ElseKeyword, IfKeyword, ForKeyword, DoKeyword, BlockComment, DocBlockStart, DocBlockEnd, LineComment, Comma, LanguageStartDelimiter } @Nullable @Override public String getLineIndent(@NotNull Project project, @NotNull Editor editor, @Nullable Language language, int offset) { if (offset > 0) { IndentCalculator indentCalculator = getIndent(project, editor, language, offset - 1); if (indentCalculator != null) { return indentCalculator.getIndentString(language, getPosition(editor, offset - 1)); } } else { return ""; } return null; } @Nullable protected IndentCalculator getIndent(@NotNull Project project, @NotNull Editor editor, @Nullable Language language, int offset) { IndentCalculatorFactory myFactory = new IndentCalculatorFactory(project, editor); if (getPosition(editor, offset).matchesRule( position -> position.isAt(Whitespace) && position.isAtMultiline())) { if (getPosition(editor, offset).before().isAt(Comma)) { SemanticEditorPosition position = getPosition(editor,offset); if (position.hasEmptyLineAfter(offset) && !position.after().isAtAnyOf(ArrayClosingBracket, BlockOpeningBrace, BlockClosingBrace, RightParenthesis) && !position.isAtEnd()) { return myFactory.createIndentCalculator(NONE, IndentCalculator.LINE_AFTER); } } else if (getPosition(editor, offset + 1).matchesRule( position -> position.isAt(BlockClosingBrace) && !position.after().afterOptional(Whitespace).isAt(Comma))) { return myFactory.createIndentCalculator( NONE, position -> { position.findLeftParenthesisBackwardsSkippingNested(BlockOpeningBrace, BlockClosingBrace); if (!position.isAtEnd()) { return getBlockStatementStartOffset(position); } return -1; }); } else if (getPosition(editor, offset).matchesRule( position -> position .before() .beforeOptional(Whitespace) .isAt(BlockClosingBrace))) { return myFactory.createIndentCalculator(getBlockIndentType(project, language), IndentCalculator.LINE_BEFORE); } else if (getPosition(editor, offset).matchesRule(position -> position.before().isAt(Semicolon))) { SemanticEditorPosition beforeSemicolon = getPosition(editor, offset).before().beforeOptional(Semicolon); if (beforeSemicolon.isAt(BlockClosingBrace)) { beforeSemicolon.beforeParentheses(BlockOpeningBrace, BlockClosingBrace); } int statementStart = getStatementStartOffset(beforeSemicolon); SemanticEditorPosition atStatementStart = getPosition(editor, statementStart); if (!atStatementStart.isAfterOnSameLine(ForKeyword)) { return myFactory.createIndentCalculator(NONE, position -> statementStart); } } else if (getPosition(editor, offset).matchesRule( position -> position.before().isAt(ArrayOpeningBracket) )) { return myFactory.createIndentCalculator(getIndentTypeInBrackets(), IndentCalculator.LINE_BEFORE); } else if (getPosition(editor, offset).matchesRule( position -> position.before().isAt(LeftParenthesis) )) { return myFactory.createIndentCalculator(CONTINUATION, IndentCalculator.LINE_BEFORE); } else if (getPosition(editor, offset).matchesRule( position -> position.before().isAt(BlockOpeningBrace) && !position.before().beforeOptional(Whitespace).isAt(LeftParenthesis) )) { SemanticEditorPosition position = getPosition(editor, offset).before(); return myFactory.createIndentCalculator(getIndentTypeInBlock(project, language, position), this::getBlockStatementStartOffset); } else if (getPosition(editor, offset).matchesRule( position -> position.before().isAt(Colon) && position.isAfterOnSameLine(SwitchCase, SwitchDefault) ) || getPosition(editor, offset).matchesRule( position -> position.before().isAtAnyOf(ElseKeyword, DoKeyword) )) { return myFactory.createIndentCalculator(NORMAL, IndentCalculator.LINE_BEFORE); } else if (getPosition(editor, offset).matchesRule( position -> position.before().isAt(BlockComment) && position.before().isAt(Whitespace) && position.isAtMultiline() )) { return myFactory.createIndentCalculator(NONE, position -> position.findStartOf(BlockComment)); } else if (getPosition(editor, offset).matchesRule( position -> position.before().isAt(DocBlockEnd) )) { return myFactory.createIndentCalculator(NONE, position -> position.findStartOf(DocBlockStart)); } else { SemanticEditorPosition position = getPosition(editor, offset); position = position.before().beforeOptionalMix(LineComment, BlockComment, Whitespace); if (position.isAt(RightParenthesis)) { int offsetAfterParen = position.getStartOffset() + 1; position.beforeParentheses(LeftParenthesis, RightParenthesis); if (!position.isAtEnd()) { position.beforeOptional(Whitespace); if (position.isAt(IfKeyword) || position.isAt(ForKeyword)) { SyntaxElement element = position.getCurrElement(); assert element != null; final int controlKeywordOffset = position.getStartOffset(); Type indentType = getPosition(editor, offsetAfterParen).afterOptional(Whitespace).isAt(BlockOpeningBrace) ? NONE : NORMAL; return myFactory.createIndentCalculator(indentType, baseLineOffset -> controlKeywordOffset); } } } } } //return myFactory.createIndentCalculator(NONE, IndentCalculator.LINE_BEFORE); /* TO CHECK UNCOVERED CASES */ return null; } private int getBlockStatementStartOffset(@NotNull SemanticEditorPosition position) { position.before().beforeOptional(BlockOpeningBrace); if (position.isAt(Whitespace)) { if (position.isAtMultiline()) return position.after().getStartOffset(); position.before(); } return getStatementStartOffset(position); } private int getStatementStartOffset(@NotNull SemanticEditorPosition position) { Language currLanguage = position.getLanguage(); while (!position.isAtEnd()) { if (currLanguage == Language.ANY || currLanguage == null) currLanguage = position.getLanguage(); if (position.isAt(Colon)) { SemanticEditorPosition afterColon = getPosition(position.getEditor(), position.getStartOffset()).after().afterOptional(Whitespace); if (position.isAfterOnSameLine(SwitchCase, SwitchDefault)) { return afterColon.getStartOffset(); } } else if (position.isAt(RightParenthesis)) { position.beforeParentheses(LeftParenthesis, RightParenthesis); } else if (position.isAt(BlockClosingBrace)) { position.beforeParentheses(BlockOpeningBrace, BlockClosingBrace); } else if (position.isAt(ArrayClosingBracket)) { position.beforeParentheses(ArrayOpeningBracket, ArrayClosingBracket); } else if (position.isAtAnyOf(Semicolon, BlockOpeningBrace, BlockComment, DocBlockEnd, LeftParenthesis, LanguageStartDelimiter) || (position.getLanguage() != Language.ANY) && !position.isAtLanguage(currLanguage)) { SemanticEditorPosition statementStart = getPosition(position.getEditor(), position.getStartOffset()); statementStart.after().afterOptionalMix(Whitespace, LineComment); if (!statementStart.isAtEnd()) { return statementStart.getStartOffset(); } } position.before(); } return 0; } protected SemanticEditorPosition getPosition(@NotNull Editor editor, int offset) { return new SemanticEditorPosition((EditorEx)editor, offset) { @Override public SyntaxElement map(@NotNull IElementType elementType) { return mapType(elementType); } }; } @Nullable protected abstract SyntaxElement mapType(@NotNull IElementType tokenType); @Nullable protected Type getIndentTypeInBlock(@NotNull Project project, @Nullable Language language, @NotNull SemanticEditorPosition blockStartPosition) { if (language != null) { CommonCodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project).getCommonSettings(language); if (settings.BRACE_STYLE == CommonCodeStyleSettings.NEXT_LINE_SHIFTED) { return settings.METHOD_BRACE_STYLE == CommonCodeStyleSettings.NEXT_LINE_SHIFTED ? NONE : null; } } return NORMAL; } @Nullable private static Type getBlockIndentType(@NotNull Project project, @Nullable Language language) { if (language != null) { CommonCodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project).getCommonSettings(language); if (settings.BRACE_STYLE == CommonCodeStyleSettings.NEXT_LINE || settings.BRACE_STYLE == CommonCodeStyleSettings.END_OF_LINE) { return NONE; } } return null; } public static class IndentCalculatorFactory { private Project myProject; private Editor myEditor; public IndentCalculatorFactory(Project project, Editor editor) { myProject = project; myEditor = editor; } @Nullable public IndentCalculator createIndentCalculator(@Nullable Type indentType, @Nullable BaseLineOffsetCalculator baseLineOffsetCalculator) { return indentType != null ? new IndentCalculator(myProject, myEditor, baseLineOffsetCalculator != null ? baseLineOffsetCalculator : IndentCalculator.LINE_BEFORE, indentType) : null; } } @Override public final boolean isSuitableFor(@Nullable Language language) { return language != null && isSuitableForLanguage(language); } public abstract boolean isSuitableForLanguage(@NotNull Language language); protected Type getIndentTypeInBrackets() { return CONTINUATION; } }
/* * Created on Mar 4, 2008 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright @2008-2013 the original author or authors. */ package org.fest.swing.core; import java.awt.Component; import java.awt.Container; import java.util.Collection; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.JLabel; import org.fest.swing.annotation.RunsInEDT; import org.fest.swing.exception.ComponentLookupException; /** * Looks up AWT and Swing {@code Component}s based on different search criteria, such as a {@code Component}'s name, * type or label, and custom search criteria as well. * * @author Alex Ruiz */ @RunsInEDT public interface ComponentFinder { /** * @return the {@code ComponentPrinter} in this finder. */ @Nonnull ComponentPrinter printer(); /** * <p> * Finds an AWT or Swing {@code Component} by type. If this finder is attached to a {@link Robot}, it will use the * component lookup scope in the {@code Robot}'s {@link Settings} to determine whether the component to find should be * showing or not. If this finder is <em>not</em> attached to any {@code Robot}, the component to find does not have * to be showing. * </p> * * <p> * Example: * <pre> * JTextField textbox = finder.findByType(JTextField.class); * </pre> * </p> * * @param type the type of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope */ @Nonnull <T extends Component> T findByType(@Nonnull Class<T> type); /** * Finds an AWT or Swing {@code Component} by type. For example: * * @param type the type of the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByType(Class) */ @Nonnull <T extends Component> T findByType(@Nonnull Class<T> type, boolean showing); /** * <p> * Finds an AWT or Swing {@code Component} by type in the hierarchy under the given root. If this finder is attached * to a {@link Robot}, it will use the component lookup scope in the {@code Robot}'s {@link Settings} to determine * whether the component to find should be showing or not. If this finder is <em>not</em> attached to any * {@code Robot}, the component to find does not have to be showing. * </p> * * <p> * Let's assume we have the following {@code JFrame} containing a {@code JTextField}: * <pre> * JFrame myFrame = new JFrame(); * myFrame.add(new JTextField()); * </pre> * </p> * * <p> * If we want to get a reference to the {@code JTextField} in that particular {@code JFrame} without going through the * whole AWT component hierarchy, we could simply specify: * <pre> * JTextField textbox = finder.findByType(myFrame, JTextField.class); * </pre> * </p> * * @param root the root used as the starting point of the search. * @param type the type of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope */ @Nonnull <T extends Component> T findByType(@Nonnull Container root, @Nonnull Class<T> type); /** * Finds an AWT or Swing {@code Component} by type in the hierarchy under the given root. * * @param root the root used as the starting point of the search. * @param showing indicates whether the component to find should be visible (or showing) or not. * @param type the type of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByType(Container, Class) */ @Nonnull <T extends Component> T findByType(@Nonnull Container root, @Nonnull Class<T> type, boolean showing); /** * <p> * Finds an AWT or Swing {@code Component} by by the text of its associated {@code JLabel}. If this finder is attached * to a {@link Robot}, it will use the component lookup scope in the {@code Robot}'s {@link Settings} to determine * whether the component to find should be showing or not. If this finder is <em>not</em> attached to any * {@code Robot}, the component to find does not have to be showing. * </p> * * <p> * Let's assume we have the {@code JTextField} with a {@code JLabel} with text "Name"; * <pre> * JLabel label = new JLabel(&quot;Name&quot;); * JTextField textbox = new JTextField(); * label.setLabelFor(textBox); * </pre> * </p> * * <p> * To get a reference to this {@code JTextField} by the text of its associated {@code JLabel}, we can specify: * <pre> * JTextField textBox = (JTextField) finder.findByLabel(&quot;Name&quot;); * </pre> * </p> * * <p> * Please note that you need to cast the result of the lookup to the right type. To avoid casting, please use one of * following: * <ol> * <li>{@link #findByLabel(String, Class)}</li> * <li>{@link #findByLabel(String, Class, boolean)}</li> * <li>{@link #findByLabel(Container, String, Class)}</li> * <li>{@link #findByLabel(Container, String, Class, boolean)}</li> * </ol> * </p> * * @param label the text of the {@code JLabel} associated to the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope */ @Nonnull Component findByLabel(@Nullable String label); /** * Finds an AWT or Swing {@code Component} by the text of its associated {@code JLabel} and type. If this finder is * attached to a {@link Robot}, it will use the component lookup scope in the {@code Robot}'s {@link Settings} to * determine whether the component to find should be showing or not. If this finder is <em>not</em> attached to any * {@code Robot}, the component to find does not have to be showing. * * @param label the text of the {@code JLabel} associated to the component to find. * @param type the type of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByLabel(String) * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope */ @Nonnull <T extends Component> T findByLabel(@Nullable String label, @Nonnull Class<T> type); /** * Finds an AWT or Swing {@code Component} by the text of its associated {@code JLabel} and type. * * @param label the text of the {@code JLabel} associated to the component to find. * @param type the type of the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByLabel(String) * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) */ @Nonnull <T extends Component> T findByLabel(@Nullable String label, @Nonnull Class<T> type, boolean showing); /** * Finds an AWT or Swing {@code Component} by by the text of its associated {@code JLabel}. * * @param label the text of the {@code JLabel} associated to the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByLabel(String) * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) */ @Nonnull Component findByLabel(@Nullable String label, boolean showing); /** * Finds an AWT or Swing {@code Component} by the text of its associated {@code JLabel}, in the hierarchy under the * given root. If this finder is attached to a {@link Robot}, it will use the component lookup scope in the * {@code Robot}'s {@link Settings} to determine whether the component to find should be showing or not. If this * finder is <em>not</em> attached to any {@code Robot}, the component to find does not have to be showing. * * @param root the root used as the starting point of the search. * @param label the text of the {@code JLabel} associated to the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByLabel(String) * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope */ @Nonnull Component findByLabel(@Nonnull Container root, @Nullable String label); /** * Finds an AWT or Swing {@code Component} by the text of its associated {@code JLabel}, in the hierarchy under the * given root. * * @param root the root used as the starting point of the search. * @param label the text of the {@code JLabel} associated to the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByLabel(String) * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) */ @Nonnull Component findByLabel(@Nonnull Container root, @Nullable String label, boolean showing); /** * Finds an AWT or Swing {@code Component} by the text of its associated {@code JLabel} and type, in the hierarchy * under the given root. If this finder is attached to a {@link Robot}, it will use the component lookup scope in the * {@code Robot}'s {@link Settings} to determine whether the component to find should be showing or not. If this * finder is <em>not</em> attached to any {@code Robot}, the component to find does not have to be showing. * * @param root the root used as the starting point of the search. * @param label the text of the {@code JLabel} associated to the component to find. * @param type the type of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByLabel(String) * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope */ @Nonnull <T extends Component> T findByLabel(@Nonnull Container root, @Nullable String label, @Nonnull Class<T> type); /** * Finds an AWT or Swing {@code Component} by the text of its associated {@code JLabel} and type, in the hierarchy * under the given root. * * @param root the root used as the starting point of the search. * @param label the text of the {@code JLabel} associated to the component to find. * @param type the type of the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByLabel(String) * @see JLabel#getLabelFor() * @see JLabel#setLabelFor(Component) */ @Nonnull <T extends Component> T findByLabel( @Nonnull Container root, @Nullable String label, @Nonnull Class<T> type, boolean showing); /** * <p> * Finds an AWT or Swing {@code Component} by name. If this finder is attached to a {@link Robot}, it will use the * component lookup scope in the {@code Robot}'s {@link Settings} to determine whether the component to find should be * showing or not. If this finder is <em>not</em> attached to any {@code Robot}, the component to find does not have * to be showing. * </p> * * <p> * Let's assume we have the {@code JTextField} with name "myTextBox"; * <pre> * JTextField textbox = new JTextField(); * textBox.setName(&quot;myTextBox&quot;); * </pre> * </p> * * <p> * To get a reference to this {@code JTextField} by its name, we can specify: * <pre> * JTextField textBox = (JTextField) finder.findByName(&quot;myTextBox&quot;); * </pre> * </p> * * <p> * Please note that you need to cast the result of the lookup to the right type. To avoid casting, please use one of * following: * <ol> * <li>{@link #findByName(String, Class)}</li> * <li>{@link #findByName(String, Class, boolean)}</li> * <li>{@link #findByName(Container, String, Class)}</li> * <li>{@link #findByName(Container, String, Class, boolean)}</li> * </ol> * </p> * * @param name the name of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope */ @Nonnull Component findByName(@Nullable String name); /** * Finds an AWT or Swing {@code Component} by name and type. If this finder is attached to a {@link Robot} , it will * use the component lookup scope in the {@code Robot}'s {@link Settings} to determine whether the component to find * should be showing or not. If this finder is <em>not</em> attached to any {@code Robot}, the component to find does * not have to be showing. * * @param name the name of the component to find. * @param type the type of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope * @see #findByName(String) */ @Nonnull <T extends Component> T findByName(@Nullable String name, @Nonnull Class<T> type); /** * Finds an AWT or Swing {@code Component} by name and type. * * @param name the name of the component to find. * @param type the type of the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByName(String) */ @Nonnull <T extends Component> T findByName(@Nullable String name, @Nonnull Class<T> type, boolean showing); /** * Finds an AWT or Swing {@code Component} by name. * * @param name the name of the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByName(String) */ @Nonnull Component findByName(@Nullable String name, boolean showing); /** * Finds an AWT or Swing {@code Component} by name, in the hierarchy under the given root. If this finder is attached * to a {@link Robot}, it will use the component lookup scope in the {@code Robot}'s {@link Settings} to determine * whether the component to find should be showing or not. If this finder is <em>not</em> attached to any * {@code Robot}, the component to find does not have to be showing. * * @param root the root used as the starting point of the search. * @param name the name of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope * @see #findByName(String) */ @Nonnull Component findByName(@Nonnull Container root, @Nullable String name); /** * Finds an AWT or Swing {@code Component} by name, in the hierarchy under the given root. * * @param root the root used as the starting point of the search. * @param name the name of the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByName(String) */ @Nonnull Component findByName(@Nonnull Container root, @Nullable String name, boolean showing); /** * Finds an AWT or Swing {@code Component} by name and type, in the hierarchy under the given root. If this finder is * attached to a {@link Robot}, it will use the component lookup scope in the {@code Robot}'s {@link Settings} to * determine whether the component to find should be showing or not. If this finder is <em>not</em> attached to any * {@code Robot}, the component to find does not have to be showing. * * @param root the root used as the starting point of the search. * @param name the name of the component to find. * @param type the type of the component to find. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see Robot#settings() * @see Settings#componentLookupScope() * @see ComponentLookupScope * @see #findByName(String) */ @Nonnull <T extends Component> T findByName(@Nonnull Container root, @Nullable String name, @Nonnull Class<T> type); /** * Finds an AWT or Swing {@code Component} by name and type, in the hierarchy under the given root. * * @param root the root used as the starting point of the search. * @param name the name of the component to find. * @param type the type of the component to find. * @param showing indicates whether the component to find should be visible (or showing) or not. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. * @see #findByName(String) */ @Nonnull <T extends Component> T findByName( @Nonnull Container root, @Nullable String name, @Nonnull Class<T> type, boolean showing); /** * Finds an AWT or Swing {@code Component} using the given {@link ComponentMatcher}. The given matcher will be * evaluated in the event dispatch thread (EDT.) Implementations of {@code ComponentMatcher} do not need to be * concerned about the event dispatch thread (EDT.) * * @param m the matcher to use to find the component of interest. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. */ @Nonnull Component find(@Nonnull ComponentMatcher m); /** * Finds an AWT or Swing {@code Component} using the given {@link GenericTypeMatcher}. The given matcher will be * evaluated in the event dispatch thread (EDT.) Implementations of {@code GenericTypeMatcher} do not need to be * concerned about the event dispatch thread (EDT.) * * @param m the matcher to use to find the component of interest. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. */ @Nonnull <T extends Component> T find(@Nonnull GenericTypeMatcher<T> m); /** * Finds an AWT or Swing {@code Component} using the given {@link GenericTypeMatcher} in the hierarchy under the given * root. The given matcher will be evaluated in the event dispatch thread (EDT.) Implementations of * {@code GenericTypeMatcher} do not need to be concerned about the event dispatch thread (EDT.) * * @param root the root used as the starting point of the search. * @param m the matcher to use to find the component. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. */ @Nonnull <T extends Component> T find(@Nonnull Container root, @Nonnull GenericTypeMatcher<T> m); /** * Finds an AWT or Swing {@code Component} using the given {@link ComponentMatcher} in the hierarchy under the given * root. The given matcher will be evaluated in the event dispatch thread (EDT.) Implementations of * {@code ComponentMatcher} do not need to be concerned about the event dispatch thread (EDT.) * * @param root the root used as the starting point of the search. * @param m the matcher to use to find the component. * @return the found component. * @throws ComponentLookupException if a matching component could not be found. * @throws ComponentLookupException if more than one matching component is found. */ @Nonnull Component find(@Nullable Container root, @Nonnull ComponentMatcher m); /** * Returns all the AWT or Swing {@code Component}s that match the search criteria specified in the given * {@link ComponentMatcher}. * * @param m the matcher to use to find the component. * @return all the {@code Component}s that match the search criteria specified in the given {@code ComponentMatcher}; * or an empty collection, if there are no matching components. */ @Nonnull Collection<Component> findAll(@Nonnull ComponentMatcher m); /** * Returns all the AWT or Swing {@code Component}s under the given root that match the search criteria specified in * the given {@link ComponentMatcher}. * * @param root the root used as the starting point of the search. * @param m the matcher to use to find the component. * @return all the {@code Component}s under the given root that match the search criteria specified in the given * {@code ComponentMatcher}; or an empty collection, if there are no matching components. */ @Nonnull Collection<Component> findAll(@Nonnull Container root, @Nonnull ComponentMatcher m); /** * Returns all the AWT or Swing {@code Component}s that match the search criteria specified in the given * {@link GenericTypeMatcher}. * * @param m the matcher to use to find the component. * @return all the {@code Component}s that match the search criteria specified in the given {@code GenericTypeMatcher} * ; or an empty collection, if there are no matching components. */ @Nonnull <T extends Component> Collection<T> findAll(@Nonnull GenericTypeMatcher<T> m); /** * Returns all the AWT or Swing {@code Component}s under the given root that match the search criteria specified in * the given {@link GenericTypeMatcher}. * * @param root the root used as the starting point of the search. * @param m the matcher to use to find the component. * @return all the {@code Component}s under the given root that match the search criteria specified in the given * {@code GenericTypeMatcher}; or an empty collection, if there are no matching components. */ @Nonnull <T extends Component> Collection<T> findAll(@Nonnull Container root, @Nonnull GenericTypeMatcher<T> m); /** * Returns whether the message in a {@link ComponentLookupException} should include the current component hierarchy. * The default value is {@code true}. * * @return {@code true} if the component hierarchy is included as part of the {@code ComponentLookupException} * message, {@code false} otherwise. */ boolean includeHierarchyIfComponentNotFound(); /** * Updates whether the message in a {@link ComponentLookupException} should include the current component hierarchy. * The default value is {@code true}. * * @param newValue the new value to set. */ void includeHierarchyIfComponentNotFound(boolean newValue); }
/* 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.activiti.engine.delegate; import org.activiti.bpmn.model.*; import org.activiti.engine.ActivitiException; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.delegate.ActivityBehavior; import org.activiti.engine.impl.el.ExpressionManager; import org.activiti.engine.impl.el.FixedValue; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.util.ProcessDefinitionUtil; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Class that provides helper operations for use in the {@link JavaDelegate}, * {@link ActivityBehavior}, {@link ExecutionListener} and {@link TaskListener} * interfaces. * * @author Joram Barrez */ public class DelegateHelper { /** * To be used in an {@link ActivityBehavior} or {@link JavaDelegate}: leaves * according to the default BPMN 2.0 rules: all sequenceflow with a condition * that evaluates to true are followed. */ public static void leaveDelegate(DelegateExecution delegateExecution) { Context.getAgenda().planTakeOutgoingSequenceFlowsOperation((ExecutionEntity) delegateExecution, true); } /** * To be used in an {@link ActivityBehavior} or {@link JavaDelegate}: leaves * the current activity via one specific sequenceflow. */ public static void leaveDelegate(DelegateExecution delegateExecution, String sequenceFlowId) { String processDefinitionId = delegateExecution.getProcessDefinitionId(); org.activiti.bpmn.model.Process process = ProcessDefinitionUtil.getProcess(processDefinitionId); FlowElement flowElement = process.getFlowElement(sequenceFlowId); if (flowElement instanceof SequenceFlow) { delegateExecution.setCurrentFlowElement(flowElement); Context.getAgenda().planTakeOutgoingSequenceFlowsOperation((ExecutionEntity) delegateExecution, false); } else { throw new ActivitiException(sequenceFlowId + " does not match a sequence flow"); } } /** * Returns the {@link BpmnModel} matching the process definition bpmn model * for the process definition of the passed {@link DelegateExecution}. */ public static BpmnModel getBpmnModel(DelegateExecution execution) { if (execution == null) { throw new ActivitiException("Null execution passed"); } return ProcessDefinitionUtil.getBpmnModel(execution.getProcessDefinitionId()); } /** * Returns the current {@link FlowElement} where the {@link DelegateExecution} is currently at. */ public static FlowElement getFlowElement(DelegateExecution execution) { BpmnModel bpmnModel = getBpmnModel(execution); FlowElement flowElement = bpmnModel.getFlowElement(execution.getCurrentActivityId()); if (flowElement == null) { throw new ActivitiException("Could not find a FlowElement for activityId " + execution.getCurrentActivityId()); } return flowElement; } /** * Returns whether or not the provided execution is being use for executing an {@link ExecutionListener}. */ public static boolean isExecutingExecutionListener(DelegateExecution execution) { return execution.getCurrentActivitiListener() != null; } /** * Returns for the activityId of the passed {@link DelegateExecution} the * {@link Map} of {@link ExtensionElement} instances. These represent the * extension elements defined in the BPMN 2.0 XML as part of that particular * activity. * * If the execution is currently being used for executing an * {@link ExecutionListener}, the extension elements of the listener will be * used. Use the {@link #getFlowElementExtensionElements(DelegateExecution)} * or {@link #getListenerExtensionElements(DelegateExecution)} instead to * specifically get the extension elements of either the flow element or the * listener. */ public static Map<String, List<ExtensionElement>> getExtensionElements(DelegateExecution execution) { if (isExecutingExecutionListener(execution)) { return getListenerExtensionElements(execution); } else { return getFlowElementExtensionElements(execution); } } public static Map<String, List<ExtensionElement>> getFlowElementExtensionElements(DelegateExecution execution) { return getFlowElement(execution).getExtensionElements(); } public static Map<String, List<ExtensionElement>> getListenerExtensionElements(DelegateExecution execution) { return execution.getCurrentActivitiListener().getExtensionElements(); } /** * Returns the list of field extensions, represented as instances of * {@link FieldExtension}, for the current activity of the passed * {@link DelegateExecution}. * * If the execution is currently being used for executing an * {@link ExecutionListener}, the fields of the listener will be returned. Use * {@link #getFlowElementFields(DelegateExecution)} or * {@link #getListenerFields(DelegateExecution)} if needing the flow element * of listener fields specifically. */ public static List<FieldExtension> getFields(DelegateExecution execution) { if (isExecutingExecutionListener(execution)) { return getListenerFields(execution); } else { return getFlowElementFields(execution); } } public static List<FieldExtension> getFlowElementFields(DelegateExecution execution) { FlowElement flowElement = getFlowElement(execution); if (flowElement instanceof TaskWithFieldExtensions) { return ((TaskWithFieldExtensions) flowElement).getFieldExtensions(); } return new ArrayList<FieldExtension>(); } public static List<FieldExtension> getListenerFields(DelegateExecution execution) { return execution.getCurrentActivitiListener().getFieldExtensions(); } /** * Returns the {@link FieldExtension} matching the provided 'fieldName' which * is defined for the current activity of the provided * {@link DelegateExecution}. * * Returns null if no such {@link FieldExtension} can be found. * * If the execution is currently being used for executing an * {@link ExecutionListener}, the field of the listener will be returned. Use * {@link #getFlowElementField(DelegateExecution, String)} or * {@link #getListenerField(DelegateExecution, String)} for specifically * getting the field from either the flow element or the listener. */ public static FieldExtension getField(DelegateExecution execution, String fieldName) { if (isExecutingExecutionListener(execution)) { return getListenerField(execution, fieldName); } else { return getFlowElementField(execution, fieldName); } } public static FieldExtension getFlowElementField(DelegateExecution execution, String fieldName) { List<FieldExtension> fieldExtensions = getFlowElementFields(execution); if (fieldExtensions == null || fieldExtensions.size() == 0) { return null; } for (FieldExtension fieldExtension : fieldExtensions) { if (fieldExtension.getFieldName() != null && fieldExtension.getFieldName().equals(fieldName)) { return fieldExtension; } } return null; } public static FieldExtension getListenerField(DelegateExecution execution, String fieldName) { List<FieldExtension> fieldExtensions = getListenerFields(execution); if (fieldExtensions == null || fieldExtensions.size() == 0) { return null; } for (FieldExtension fieldExtension : fieldExtensions) { if (fieldExtension.getFieldName() != null && fieldExtension.getFieldName().equals(fieldName)) { return fieldExtension; } } return null; } /** * Creates an {@link Expression} for the {@link FieldExtension}. */ public static Expression createExpressionForField(FieldExtension fieldExtension) { if (StringUtils.isNotEmpty(fieldExtension.getExpression())) { ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager(); return expressionManager.createExpression(fieldExtension.getExpression()); } else { return new FixedValue(fieldExtension.getStringValue()); } } /** * Returns the {@link Expression} for the field defined for the current * activity of the provided {@link DelegateExecution}. * * Returns null if no such field was found in the process definition xml. * * If the execution is currently being used for executing an * {@link ExecutionListener}, it will return the field expression for the * listener. Use * {@link #getFlowElementFieldExpression(DelegateExecution, String)} or * {@link #getListenerFieldExpression(DelegateExecution, String)} for * specifically getting the flow element or listener field expression. */ public static Expression getFieldExpression(DelegateExecution execution, String fieldName) { if (isExecutingExecutionListener(execution)) { return getListenerFieldExpression(execution, fieldName); } else { return getFlowElementFieldExpression(execution, fieldName); } } /** * Similar to {@link #getFieldExpression(DelegateExecution, String)}, but for use within a {@link TaskListener}. */ public static Expression getFieldExpression(DelegateTask task, String fieldName) { if (task.getCurrentActivitiListener() != null) { List<FieldExtension> fieldExtensions = task.getCurrentActivitiListener().getFieldExtensions(); if (fieldExtensions != null && fieldExtensions.size() > 0) { for (FieldExtension fieldExtension : fieldExtensions) { if (fieldName.equals(fieldExtension.getFieldName())) { return createExpressionForField(fieldExtension); } } } } return null; } public static Expression getFlowElementFieldExpression(DelegateExecution execution, String fieldName) { FieldExtension fieldExtension = getFlowElementField(execution, fieldName); if (fieldExtension != null) { return createExpressionForField(fieldExtension); } return null; } public static Expression getListenerFieldExpression(DelegateExecution execution, String fieldName) { FieldExtension fieldExtension = getListenerField(execution, fieldName); if (fieldExtension != null) { return createExpressionForField(fieldExtension); } return null; } }
/* * 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.unique.common.tools; import java.util.Random; /** * <p>Operations for random {@code String}s.</p> * <p>Currently <em>private high surrogate</em> characters are ignored. * These are Unicode characters that fall between the values 56192 (db80) * and 56319 (dbff) as we don't know how to handle them. * High and low surrogates are correctly dealt with - that is if a * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) * then it is followed by a low surrogate. If a low surrogate is chosen, * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly * chosen high surrogate. </p> * * <p>#ThreadSafe#</p> * @since 1.0 * @version $Id: RandomStringUtils.java 1532684 2013-10-16 08:28:42Z bayard $ */ public class RandomStringUtils { /** * <p>Random object used by random method. This has to be not local * to the random method so as to not return the same value in the * same millisecond.</p> */ private static final Random RANDOM = new Random(); /** * <p>{@code RandomStringUtils} instances should NOT be constructed in * standard programming. Instead, the class should be used as * {@code RandomStringUtils.random(5);}.</p> * * <p>This constructor is public to permit tools that require a JavaBean instance * to operate.</p> */ public RandomStringUtils() { super(); } // Random //----------------------------------------------------------------------- /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of all characters.</p> * * @param count the length of random string to create * @return the random string */ public static String random(final int count) { return random(count, false, false); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of characters whose * ASCII value is between {@code 32} and {@code 126} (inclusive).</p> * * @param count the length of random string to create * @return the random string */ public static String randomAscii(final int count) { return random(count, 32, 127, false, false); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of alphabetic * characters.</p> * * @param count the length of random string to create * @return the random string */ public static String randomAlphabetic(final int count) { return random(count, true, false); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of alpha-numeric * characters.</p> * * @param count the length of random string to create * @return the random string */ public static String randomAlphanumeric(final int count) { return random(count, true, true); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of numeric * characters.</p> * * @param count the length of random string to create * @return the random string */ public static String randomNumeric(final int count) { return random(count, false, true); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of alpha-numeric * characters as indicated by the arguments.</p> * * @param count the length of random string to create * @param letters if {@code true}, generated string may include * alphabetic characters * @param numbers if {@code true}, generated string may include * numeric characters * @return the random string */ public static String random(final int count, final boolean letters, final boolean numbers) { return random(count, 0, 0, letters, numbers); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of alpha-numeric * characters as indicated by the arguments.</p> * * @param count the length of random string to create * @param start the position in set of chars to start at * @param end the position in set of chars to end before * @param letters if {@code true}, generated string may include * alphabetic characters * @param numbers if {@code true}, generated string may include * numeric characters * @return the random string */ public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers) { return random(count, start, end, letters, numbers, null, RANDOM); } /** * <p>Creates a random string based on a variety of options, using * default source of randomness.</p> * * <p>This method has exactly the same semantics as * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but * instead of using an externally supplied source of randomness, it uses * the internal static {@link Random} instance.</p> * * @param count the length of random string to create * @param start the position in set of chars to start at * @param end the position in set of chars to end before * @param letters only allow letters? * @param numbers only allow numbers? * @param chars the set of chars to choose randoms from. * If {@code null}, then it will use the set of all chars. * @return the random string * @throws ArrayIndexOutOfBoundsException if there are not * {@code (end - start) + 1} characters in the set array. */ public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers, final char... chars) { return random(count, start, end, letters, numbers, chars, RANDOM); } /** * <p>Creates a random string based on a variety of options, using * supplied source of randomness.</p> * * <p>If start and end are both {@code 0}, start and end are set * to {@code ' '} and {@code 'z'}, the ASCII printable * characters, will be used, unless letters and numbers are both * {@code false}, in which case, start and end are set to * {@code 0} and {@code Integer.MAX_VALUE}. * * <p>If set is not {@code null}, characters between start and * end are chosen.</p> * * <p>This method accepts a user-supplied {@link Random} * instance to use as a source of randomness. By seeding a single * {@link Random} instance with a fixed seed and using it for each call, * the same random sequence of strings can be generated repeatedly * and predictably.</p> * * @param count the length of random string to create * @param start the position in set of chars to start at * @param end the position in set of chars to end before * @param letters only allow letters? * @param numbers only allow numbers? * @param chars the set of chars to choose randoms from, must not be empty. * If {@code null}, then it will use the set of all chars. * @param random a source of randomness. * @return the random string * @throws ArrayIndexOutOfBoundsException if there are not * {@code (end - start) + 1} characters in the set array. * @throws IllegalArgumentException if {@code count} &lt; 0 or the provided chars array is empty. * @since 2.0 */ public static String random(int count, int start, int end, final boolean letters, final boolean numbers, final char[] chars, final Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (chars != null && chars.length == 0) { throw new IllegalArgumentException("The chars array must not be empty"); } if (start == 0 && end == 0) { if (chars != null) { end = chars.length; } else { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ' '; } } } else { if (end <= start) { throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")"); } } final char[] buffer = new char[count]; final int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of characters * specified by the string, must not be empty. * If null, the set of all characters is used.</p> * * @param count the length of random string to create * @param chars the String containing the set of characters to use, * may be null, but must not be empty * @return the random string * @throws IllegalArgumentException if {@code count} &lt; 0 or the string is empty. */ public static String random(final int count, final String chars) { if (chars == null) { return random(count, 0, 0, false, false, null, RANDOM); } return random(count, chars.toCharArray()); } /** * <p>Creates a random string whose length is the number of characters * specified.</p> * * <p>Characters will be chosen from the set of characters specified.</p> * * @param count the length of random string to create * @param chars the character array containing the set of characters to use, * may be null * @return the random string * @throws IllegalArgumentException if {@code count} &lt; 0. */ public static String random(final int count, final char... chars) { if (chars == null) { return random(count, 0, 0, false, false, null, RANDOM); } return random(count, 0, chars.length, false, false, chars, RANDOM); } }
package io.cattle.platform.configitem.context.impl; import io.cattle.platform.configitem.context.data.LoadBalancerTargetInfo; import io.cattle.platform.configitem.context.data.LoadBalancerTargetsInfo; import io.cattle.platform.configitem.server.model.ConfigItem; import io.cattle.platform.configitem.server.model.impl.ArchiveContext; import io.cattle.platform.core.addon.InstanceHealthCheck; import io.cattle.platform.core.addon.LoadBalancerAppCookieStickinessPolicy; import io.cattle.platform.core.addon.LoadBalancerCookieStickinessPolicy; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.constants.LoadBalancerConstants; import io.cattle.platform.core.dao.IpAddressDao; import io.cattle.platform.core.dao.LoadBalancerDao; import io.cattle.platform.core.dao.LoadBalancerTargetDao; import io.cattle.platform.core.model.Agent; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.IpAddress; import io.cattle.platform.core.model.LoadBalancer; import io.cattle.platform.core.model.LoadBalancerConfig; import io.cattle.platform.core.model.LoadBalancerListener; import io.cattle.platform.core.model.LoadBalancerTarget; import io.cattle.platform.core.model.Nic; import io.cattle.platform.core.util.LoadBalancerTargetPortSpec; import io.cattle.platform.json.JsonMapper; import io.cattle.platform.lb.instance.service.LoadBalancerInstanceManager; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.util.DataAccessor; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; @Named public class LoadBalancerInfoFactory extends AbstractAgentBaseContextFactory { @Inject LoadBalancerInstanceManager lbMgr; @Inject ObjectManager objectManager; @Inject IpAddressDao ipAddressDao; @Inject LoadBalancerDao lbDao; @Inject JsonMapper jsonMapper; @Inject LoadBalancerTargetDao lbTargetDao; @Override protected void populateContext(Agent agent, Instance instance, ConfigItem item, ArchiveContext context) { List<? extends LoadBalancerListener> listeners = new ArrayList<>(); LoadBalancer lb = lbMgr.getLoadBalancerForInstance(instance); List<LoadBalancerTargetsInfo> targetsInfo = new ArrayList<>(); InstanceHealthCheck lbHealthCheck = null; LoadBalancerAppCookieStickinessPolicy appPolicy = null; LoadBalancerCookieStickinessPolicy lbPolicy = null; if (lb != null) { // populate targets and listeners listeners = lbDao.listActiveListenersForConfig(lb.getLoadBalancerConfigId()); if (listeners.isEmpty()) { return; } LoadBalancerConfig config = objectManager.loadResource(LoadBalancerConfig.class, lb.getLoadBalancerConfigId()); appPolicy = DataAccessor.field(config, LoadBalancerConstants.FIELD_LB_APP_COOKIE_POLICY, jsonMapper, LoadBalancerAppCookieStickinessPolicy.class); // LEGACY: to support the case when healtcheck is defined on LB lbHealthCheck = DataAccessor.field(config, LoadBalancerConstants.FIELD_LB_HEALTH_CHECK, jsonMapper, InstanceHealthCheck.class); lbPolicy = DataAccessor.field(config, LoadBalancerConstants.FIELD_LB_COOKIE_POLICY, jsonMapper, LoadBalancerCookieStickinessPolicy.class); targetsInfo = populateTargetsInfo(lb, lbHealthCheck); if (targetsInfo.isEmpty()) { return; } } context.getData().put("listeners", listeners); context.getData().put("publicIp", lbMgr.getLoadBalancerInstanceIp(instance).getAddress()); context.getData().put("backends", sortTargets(targetsInfo)); context.getData().put("appPolicy", appPolicy); context.getData().put("lbPolicy", lbPolicy); } protected List<LoadBalancerTargetsInfo> sortTargets(List<LoadBalancerTargetsInfo> targetsInfo) { List<LoadBalancerTargetsInfo> toReturn = new ArrayList<>(); // sort by path length first Collections.sort(targetsInfo, new Comparator<LoadBalancerTargetsInfo>() { @Override public int compare(LoadBalancerTargetsInfo s1, LoadBalancerTargetsInfo s2) { return s1.getPortSpec().getPath().length() >= s2.getPortSpec().getPath().length() ? -1 : 1; } }); List<LoadBalancerTargetsInfo> notNullDomainAndPath = new ArrayList<>(); List<LoadBalancerTargetsInfo> notNullDomain = new ArrayList<>(); List<LoadBalancerTargetsInfo> notNullPath = new ArrayList<>(); List<LoadBalancerTargetsInfo> defaultDomainAndPath = new ArrayList<>(); /* * The order on haproxy should be as follows (from top to bottom): * 1) acls with domain/url * 2) acls with domain * 3) acls with /url * 4) default rules */ for (LoadBalancerTargetsInfo targetInfo : targetsInfo) { boolean pathNotNull = !targetInfo.getPortSpec().getPath() .equalsIgnoreCase(LoadBalancerTargetPortSpec.DEFAULT); boolean domainNotNull = !targetInfo.getPortSpec().getDomain() .equalsIgnoreCase(LoadBalancerTargetPortSpec.DEFAULT); if (pathNotNull && domainNotNull) { notNullDomainAndPath.add(targetInfo); } else if (domainNotNull) { notNullDomain.add(targetInfo); } else if (pathNotNull) { notNullPath.add(targetInfo); } else { defaultDomainAndPath.add(targetInfo); } } toReturn.addAll(notNullDomainAndPath); toReturn.addAll(notNullDomain); toReturn.addAll(notNullPath); toReturn.addAll(defaultDomainAndPath); return toReturn; } private List<LoadBalancerTargetsInfo> populateTargetsInfo(LoadBalancer lb, InstanceHealthCheck lbHealthCheck) { List<? extends LoadBalancerTarget> targets = objectManager.mappedChildren(objectManager.loadResource(LoadBalancer.class, lb.getId()), LoadBalancerTarget.class); Map<String, List<LoadBalancerTargetInfo>> uuidToTargetInfos = new HashMap<>(); for (LoadBalancerTarget target : targets) { if (!(target.getState().equalsIgnoreCase(CommonStatesConstants.ACTIVATING) || target.getState().equalsIgnoreCase(CommonStatesConstants.ACTIVE) || target.getState() .equalsIgnoreCase(CommonStatesConstants.UPDATING_ACTIVE))) { continue; } String ipAddress = target.getIpAddress(); InstanceHealthCheck healthCheck = null; if (ipAddress == null) { Instance userInstance = objectManager.loadResource(Instance.class, target.getInstanceId()); healthCheck = DataAccessor.field(userInstance, InstanceConstants.FIELD_HEALTH_CHECK, jsonMapper, InstanceHealthCheck.class); if (userInstance.getState().equalsIgnoreCase(InstanceConstants.STATE_RUNNING) || userInstance.getState().equalsIgnoreCase(InstanceConstants.STATE_STARTING) || userInstance.getState().equalsIgnoreCase(InstanceConstants.STATE_RESTARTING)) { for (Nic nic : objectManager.children(userInstance, Nic.class)) { IpAddress ip = ipAddressDao.getPrimaryIpAddress(nic); if (ip != null) { ipAddress = ip.getAddress(); break; } } } } if (ipAddress != null) { String targetName = (target.getName() == null ? target.getUuid() : target.getName()); List<LoadBalancerTargetPortSpec> portSpecs = lbTargetDao.getLoadBalancerTargetPorts(target); for (LoadBalancerTargetPortSpec portSpec : portSpecs) { LoadBalancerTargetInfo targetInfo = new LoadBalancerTargetInfo(ipAddress, targetName, target.getUuid(), portSpec, healthCheck); List<LoadBalancerTargetInfo> targetInfos = uuidToTargetInfos.get(targetInfo.getUuid()); if (targetInfos == null) { targetInfos = new ArrayList<>(); } targetInfos.add(targetInfo); uuidToTargetInfos.put(targetInfo.getUuid(), targetInfos); } } } List<LoadBalancerTargetsInfo> targetsInfo = new ArrayList<>(); int count = 0; for (String uuid : uuidToTargetInfos.keySet()) { LoadBalancerTargetsInfo target = new LoadBalancerTargetsInfo(uuidToTargetInfos.get(uuid), lbHealthCheck, count); targetsInfo.add(target); count++; } return targetsInfo; } }
/* * Copyright 2014 Mingyuan Xia (http://mxia.me) and contributors * * 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. * * Contributors: * Mingyuan Xia * Lu Gong */ package patdroid.core; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import patdroid.util.Log; /** * The details of a class, including its methods, fields, inheritance relationship. * These details are only available when the class is loaded. * The details of a class are only supposed to be filled by class loader. */ public final class ClassDetail { /** * This wrapper relies on the signature hash of MethodInfo */ private final class MethodInfoWrapper { private final MethodInfo m; private final int signatureHash; public MethodInfoWrapper(MethodInfo m) { this.m = m; this.signatureHash = m.computeSignatureHash(); } @Override public int hashCode() { return signatureHash; } @Override public boolean equals(Object o) { return this.signatureHash == (((MethodInfoWrapper)o).signatureHash); } @Override public String toString() { return m.toString(); } } final static ClassDetail missingDetail = new ClassDetail(null, new ClassInfo[0], 0, new MethodInfo[0], new HashMap<String, ClassInfo>(), new HashMap<String, ClassInfo>(), true); private final ClassInfo superClass; private final ClassInfo[] interfaces; private final HashMap<MethodInfoWrapper, MethodInfo> methods; private final HashMap<String, ClassInfo> fields; private final HashMap<String, ClassInfo> staticFields; private final boolean isFrameworkClass; public ArrayList<ClassInfo> derivedClasses = new ArrayList<ClassInfo>(); public final int accessFlags; /** * Create a details class for a class. * Only a ClassDetailLoader could construct a ClassDetail * @param superClass its base class * @param interfaces interfaces * @param accessFlags * @param methods methods, stored in a name-type map * @param fields non-static fields, stored in a name-type map * @param staticFields static fields, stored in a name-type map * @param isFrameworkClass whether it is a framework class */ ClassDetail(ClassInfo superClass, ClassInfo[] interfaces, int accessFlags, MethodInfo[] methods, HashMap<String, ClassInfo> fields, HashMap<String, ClassInfo> staticFields, boolean isFrameworkClass) { this.accessFlags = accessFlags; this.superClass = superClass; this.interfaces = interfaces; this.methods = new HashMap<MethodInfoWrapper, MethodInfo>(); for (MethodInfo mi : methods) { this.methods.put(new MethodInfoWrapper(mi), mi); } this.fields = fields; this.staticFields = new HashMap<String, ClassInfo>(staticFields); this.isFrameworkClass = isFrameworkClass; } /** * Get the type of a non-static field. This functions will look into the base class. * @param fieldName the field name * @return the type of the field, or null if the field is not found */ public ClassInfo getFieldType(String fieldName) { ClassInfo r = fields.get(fieldName); if (r != null) { return r; } else { if (superClass == null) { Log.warnwarn("failed to find field: "+ fieldName); return null; } return superClass.getDetails().getFieldType(fieldName); } } /** * Get the type of a static field. This functions will look into the base class. * @param fieldName the field name * @return the type of the field, or null if the field is not found */ public ClassInfo getStaticFieldType(String fieldName) { ClassInfo r = staticFields.get(fieldName); if (r != null) { return r; } else { if (superClass == null) { Log.warnwarn("failed to find static field: "+ fieldName); return null; } return superClass.getDetails().getStaticFieldType(fieldName); } } /** * Get all non-static fields declared in this class. * @return all non-static fields stored in a name-type map */ public HashMap<String, ClassInfo> getAllFieldsHere() { return fields; } /** * Get all static fields declared in this class. * @return all static fields stored in a name-type map */ public HashMap<String, ClassInfo> getAllStaticFieldsHere() { return staticFields; } /** * Find a method declared in this class * @param mproto the method prototype * @return the method in the class, or null if not found */ public MethodInfo findMethodHere(MethodInfo mproto) { return methods.get(new MethodInfoWrapper(mproto)); } /** * Find a concrete method given a method prototype * * @param mproto The prototype of a method * @return The method matching the prototype in the class */ public MethodInfo findMethod(MethodInfo mproto) { Deque<ClassDetail> q = new ArrayDeque<ClassDetail>(); q.push(this); while (!q.isEmpty()) { ClassDetail detail = q.pop(); MethodInfo mi = detail.findMethodHere(mproto); if (mi != null) { return mi; } if (detail.superClass != null) q.push(detail.superClass.getDetails()); for (ClassInfo i : detail.interfaces) q.push(i.getDetails()); } return null; } /** * Find all concrete methods given a name * @param name The method name * @return All rebound methods */ public MethodInfo[] findMethods(String name) { ArrayList<MethodInfo> result = new ArrayList<MethodInfo>(); ArrayDeque<ClassDetail> q = new ArrayDeque<ClassDetail>(); q.push(this); while (!q.isEmpty()) { ClassDetail detail = q.pop(); MethodInfo[] mis = detail.findMethodsHere(name); for (MethodInfo mi : mis) { boolean overrided = false; for (MethodInfo mi0 : result) { // N.B. mi and mi0 may belong to different super class or // interfaces that have no inheritance relationship if (mi0.canOverride(mi)) { overrided = true; break; } } if (!overrided) result.add(mi); } if (detail.superClass != null) q.push(detail.superClass.getDetails()); for (ClassInfo i : detail.interfaces) q.push(i.getDetails()); } return result.toArray(new MethodInfo[result.size()]); } /** * Find all methods that is only in the declaration of this class * @param name The method name * @return The real methods */ public MethodInfo[] findMethodsHere(String name) { ArrayList<MethodInfo> result = new ArrayList<MethodInfo>(); for (MethodInfo m : methods.values()) { if (m.name.equals(name)) { result.add(m); } } return result.toArray(new MethodInfo[result.size()]); } /** * TypeA is convertible to TypeB if and only if TypeB is an (indirect) * superclass or an (indirect) interface of TypeA. * * @param type typeB * @return if this class can be converted to the other. */ public final boolean isConvertibleTo(ClassInfo type) { ClassDetail that = type.getDetails(); if (this == that) { return true; } if (superClass != null && superClass.isConvertibleTo(type)) { return true; } for (ClassInfo c : interfaces) { if (c.isConvertibleTo(type)) { return true; } } return false; // derivedClasses is not that reliable // return type.derivedClasses.contains(this); } public final ClassInfo getSuperClass() { return superClass; } public final boolean isFrameworkClass() { return this.isFrameworkClass; } public final void updateDerivedClasses(ClassInfo ci) { // TODO derivedClasses only covers loaded classes ArrayDeque<ClassDetail> a = new ArrayDeque<ClassDetail>(); if (superClass != null) a.add(superClass.getDetails()); for (ClassInfo i : interfaces) { a.add(i.getDetails()); } while (!a.isEmpty()) { ClassDetail detail = a.pop(); detail.derivedClasses.add(ci); detail.derivedClasses.addAll(derivedClasses); if (detail.superClass != null) a.add(detail.superClass.getDetails()); for (ClassInfo i : detail.interfaces) { a.add(i.getDetails()); } } } }
/* * 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.druid.testing; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.jackson.JacksonUtils; import org.apache.druid.java.util.common.logger.Logger; import java.io.File; import java.io.IOException; import java.util.Map; public class ConfigFileConfigProvider implements IntegrationTestingConfigProvider { private static final Logger LOG = new Logger(ConfigFileConfigProvider.class); private String routerHost; private String brokerHost; private String historicalHost; private String coordinatorHost; private String coordinatorTwoHost; private String overlordHost; private String overlordTwoHost; private String routerUrl; private String brokerUrl; private String historicalUrl; private String coordinatorUrl; private String coordinatorTwoUrl; private String overlordUrl; private String overlordTwoUrl; private String permissiveRouterUrl; private String noClientAuthRouterUrl; private String customCertCheckRouterUrl; private String routerTLSUrl; private String brokerTLSUrl; private String historicalTLSUrl; private String coordinatorTLSUrl; private String coordinatorTwoTLSUrl; private String overlordTLSUrl; private String overlordTwoTLSUrl; private String permissiveRouterTLSUrl; private String noClientAuthRouterTLSUrl; private String customCertCheckRouterTLSUrl; private String middleManagerHost; private String zookeeperHosts; // comma-separated list of host:port private String kafkaHost; private String schemaRegistryHost; private Map<String, String> props = null; private String username; private String password; private String cloudBucket; private String cloudPath; private String cloudRegion; private String hadoopGcsCredentialsPath; private String azureKey; private String streamEndpoint; @JsonCreator ConfigFileConfigProvider(@JsonProperty("configFile") String configFile) { loadProperties(configFile); } private void loadProperties(String configFile) { ObjectMapper jsonMapper = new ObjectMapper(); try { props = jsonMapper.readValue( new File(configFile), JacksonUtils.TYPE_REFERENCE_MAP_STRING_STRING ); } catch (IOException ex) { throw new RuntimeException(ex); } routerHost = props.get("router_host"); // there might not be a router; we want routerHost to be null in that case routerUrl = props.get("router_url"); if (routerUrl == null) { if (null != routerHost) { routerUrl = StringUtils.format("http://%s:%s", routerHost, props.get("router_port")); } } routerTLSUrl = props.get("router_tls_url"); if (routerTLSUrl == null) { if (null != routerHost) { routerTLSUrl = StringUtils.format("https://%s:%s", routerHost, props.get("router_tls_port")); } } permissiveRouterUrl = props.get("router_permissive_url"); if (permissiveRouterUrl == null) { String permissiveRouterHost = props.get("router_permissive_host"); if (null != permissiveRouterHost) { permissiveRouterUrl = StringUtils.format("http://%s:%s", permissiveRouterHost, props.get("router_permissive_port")); } } permissiveRouterTLSUrl = props.get("router_permissive_tls_url"); if (permissiveRouterTLSUrl == null) { String permissiveRouterHost = props.get("router_permissive_host"); if (null != permissiveRouterHost) { permissiveRouterTLSUrl = StringUtils.format("https://%s:%s", permissiveRouterHost, props.get("router_permissive_tls_port")); } } noClientAuthRouterUrl = props.get("router_no_client_auth_url"); if (noClientAuthRouterUrl == null) { String noClientAuthRouterHost = props.get("router_no_client_auth_host"); if (null != noClientAuthRouterHost) { noClientAuthRouterUrl = StringUtils.format("http://%s:%s", noClientAuthRouterHost, props.get("router_no_client_auth_port")); } } noClientAuthRouterTLSUrl = props.get("router_no_client_auth_tls_url"); if (noClientAuthRouterTLSUrl == null) { String noClientAuthRouterHost = props.get("router_no_client_auth_host"); if (null != noClientAuthRouterHost) { noClientAuthRouterTLSUrl = StringUtils.format("https://%s:%s", noClientAuthRouterHost, props.get("router_no_client_auth_tls_port")); } } customCertCheckRouterUrl = props.get("router_no_client_auth_url"); if (customCertCheckRouterUrl == null) { String customCertCheckRouterHost = props.get("router_no_client_auth_host"); if (null != customCertCheckRouterHost) { customCertCheckRouterUrl = StringUtils.format("http://%s:%s", customCertCheckRouterHost, props.get("router_no_client_auth_port")); } } customCertCheckRouterTLSUrl = props.get("router_no_client_auth_tls_url"); if (customCertCheckRouterTLSUrl == null) { String customCertCheckRouterHost = props.get("router_no_client_auth_host"); if (null != customCertCheckRouterHost) { customCertCheckRouterTLSUrl = StringUtils.format("https://%s:%s", customCertCheckRouterHost, props.get("router_no_client_auth_tls_port")); } } brokerHost = props.get("broker_host"); brokerUrl = props.get("broker_url"); if (brokerUrl == null) { brokerUrl = StringUtils.format("http://%s:%s", props.get("broker_host"), props.get("broker_port")); } brokerTLSUrl = props.get("broker_tls_url"); if (brokerTLSUrl == null) { if (null != brokerHost) { brokerTLSUrl = StringUtils.format("https://%s:%s", brokerHost, props.get("broker_tls_port")); } } historicalHost = props.get("historical_host"); historicalUrl = props.get("historical_url"); if (historicalUrl == null) { historicalUrl = StringUtils.format("http://%s:%s", props.get("historical_host"), props.get("historical_port")); } historicalTLSUrl = props.get("historical_tls_url"); if (historicalTLSUrl == null) { if (null != historicalHost) { historicalTLSUrl = StringUtils.format("https://%s:%s", historicalHost, props.get("historical_tls_port")); } } coordinatorHost = props.get("coordinator_host"); coordinatorUrl = props.get("coordinator_url"); if (coordinatorUrl == null) { coordinatorUrl = StringUtils.format("http://%s:%s", coordinatorHost, props.get("coordinator_port")); } coordinatorTLSUrl = props.get("coordinator_tls_url"); if (coordinatorTLSUrl == null) { if (null != coordinatorHost) { coordinatorTLSUrl = StringUtils.format("https://%s:%s", coordinatorHost, props.get("coordinator_tls_port")); } } overlordHost = props.get("indexer_host"); overlordUrl = props.get("indexer_url"); if (overlordUrl == null) { overlordUrl = StringUtils.format("http://%s:%s", overlordHost, props.get("indexer_port")); } overlordTLSUrl = props.get("indexer_tls_url"); if (overlordTLSUrl == null) { if (null != overlordHost) { overlordTLSUrl = StringUtils.format("https://%s:%s", overlordHost, props.get("indexer_tls_port")); } } coordinatorTwoHost = props.get("coordinator_two_host"); coordinatorTwoUrl = props.get("coordinator_two_url"); if (coordinatorTwoUrl == null) { coordinatorTwoUrl = StringUtils.format("http://%s:%s", coordinatorTwoHost, props.get("coordinator_two_port")); } coordinatorTwoTLSUrl = props.get("coordinator_two_tls_url"); if (coordinatorTwoTLSUrl == null) { if (null != coordinatorTwoHost) { coordinatorTwoTLSUrl = StringUtils.format("https://%s:%s", coordinatorTwoHost, props.get("coordinator_two_tls_port")); } } overlordTwoHost = props.get("overlord_two_host"); overlordTwoUrl = props.get("overlord_two_url"); if (overlordTwoUrl == null) { overlordTwoUrl = StringUtils.format("http://%s:%s", overlordTwoHost, props.get("overlord_two_port")); } overlordTwoTLSUrl = props.get("overlord_two_tls_url"); if (overlordTwoTLSUrl == null) { if (null != overlordTwoHost) { overlordTwoTLSUrl = StringUtils.format("https://%s:%s", overlordTwoHost, props.get("overlord_two_tls_port")); } } middleManagerHost = props.get("middlemanager_host"); zookeeperHosts = props.get("zookeeper_hosts"); kafkaHost = props.get("kafka_host") + ":" + props.get("kafka_port"); schemaRegistryHost = props.get("schema_registry_host") + ":" + props.get("schema_registry_port"); username = props.get("username"); password = props.get("password"); cloudBucket = props.get("cloud_bucket"); cloudPath = props.get("cloud_path"); cloudRegion = props.get("cloud_region"); hadoopGcsCredentialsPath = props.get("hadoopGcsCredentialsPath"); azureKey = props.get("azureKey"); streamEndpoint = props.get("stream_endpoint"); LOG.info("router: [%s], [%s]", routerUrl, routerTLSUrl); LOG.info("broker: [%s], [%s]", brokerUrl, brokerTLSUrl); LOG.info("historical: [%s], [%s]", historicalUrl, historicalTLSUrl); LOG.info("coordinator: [%s], [%s]", coordinatorUrl, coordinatorTLSUrl); LOG.info("overlord: [%s], [%s]", overlordUrl, overlordTLSUrl); LOG.info("middle manager: [%s]", middleManagerHost); LOG.info("zookeepers: [%s]", zookeeperHosts); LOG.info("kafka: [%s]", kafkaHost); LOG.info("Username: [%s]", username); } @Override public IntegrationTestingConfig get() { return new IntegrationTestingConfig() { @Override public String getCoordinatorUrl() { return coordinatorUrl; } @Override public String getCoordinatorTLSUrl() { return coordinatorTLSUrl; } @Override public String getCoordinatorTwoUrl() { return coordinatorTwoUrl; } @Override public String getCoordinatorTwoTLSUrl() { return coordinatorTwoTLSUrl; } @Override public String getOverlordUrl() { return overlordUrl; } @Override public String getOverlordTLSUrl() { return overlordTLSUrl; } @Override public String getOverlordTwoUrl() { return overlordTwoUrl; } @Override public String getOverlordTwoTLSUrl() { return overlordTwoTLSUrl; } @Override public String getIndexerUrl() { // no way to configure this since the config was stolen by the overlord return null; } @Override public String getIndexerTLSUrl() { // no way to configure this since the config was stolen by the overlord return null; } @Override public String getRouterUrl() { return routerUrl; } @Override public String getRouterTLSUrl() { return routerTLSUrl; } @Override public String getPermissiveRouterUrl() { return permissiveRouterUrl; } @Override public String getPermissiveRouterTLSUrl() { return permissiveRouterTLSUrl; } @Override public String getNoClientAuthRouterUrl() { return noClientAuthRouterUrl; } @Override public String getNoClientAuthRouterTLSUrl() { return noClientAuthRouterTLSUrl; } @Override public String getCustomCertCheckRouterUrl() { return customCertCheckRouterUrl; } @Override public String getCustomCertCheckRouterTLSUrl() { return customCertCheckRouterTLSUrl; } @Override public String getBrokerUrl() { return brokerUrl; } @Override public String getBrokerTLSUrl() { return brokerTLSUrl; } @Override public String getHistoricalUrl() { return historicalUrl; } @Override public String getHistoricalTLSUrl() { return historicalTLSUrl; } @Override public String getMiddleManagerHost() { return middleManagerHost; } @Override public String getHistoricalHost() { return historicalHost; } @Override public String getZookeeperHosts() { return zookeeperHosts; } @Override public String getKafkaHost() { return kafkaHost; } @Override public String getBrokerHost() { return brokerHost; } @Override public String getRouterHost() { return routerHost; } @Override public String getCoordinatorHost() { return coordinatorHost; } @Override public String getCoordinatorTwoHost() { return coordinatorTwoHost; } @Override public String getOverlordHost() { return overlordHost; } @Override public String getOverlordTwoHost() { return overlordTwoHost; } @Override public String getProperty(String keyword) { return props.get(keyword); } @Override public String getUsername() { return username; } @Override public String getPassword() { return password; } @Override public String getCloudBucket() { return cloudBucket; } @Override public String getCloudPath() { return cloudPath; } @Override public String getCloudRegion() { return cloudRegion; } @Override public String getAzureKey() { return azureKey; } @Override public String getHadoopGcsCredentialsPath() { return hadoopGcsCredentialsPath; } @Override public String getStreamEndpoint() { return streamEndpoint; } @Override public String getSchemaRegistryHost() { return schemaRegistryHost; } @Override public Map<String, String> getProperties() { return props; } @Override public boolean manageKafkaTopic() { return Boolean.valueOf(props.getOrDefault("manageKafkaTopic", "true")); } @Override public String getExtraDatasourceNameSuffix() { return ""; } @Override public boolean isDocker() { return false; } }; } }
/* * 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 java.beans; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.apache.harmony.beans.internal.nls.Messages; public class IndexedPropertyDescriptor extends PropertyDescriptor { private Method indexedGetter; private Method indexedSetter; public IndexedPropertyDescriptor(String propertyName, Class<?> beanClass, String getterName, String setterName, String indexedGetterName, String indexedSetterName) throws IntrospectionException { super(propertyName, beanClass, getterName, setterName); // RI behaves like this if (indexedGetterName == null && indexedSetterName == null && (getterName != null || setterName != null)) { throw new IntrospectionException(Messages.getString("beans.50")); } setIndexedReadMethod(beanClass, indexedGetterName); setIndexedWriteMethod(beanClass, indexedSetterName); } public IndexedPropertyDescriptor(String propertyName, Method getter, Method setter, Method indexedGetter, Method indexedSetter) throws IntrospectionException { super(propertyName, getter, setter); // we need this in order to be compatible with RI if (indexedGetter == null && indexedSetter == null && (getter != null || setter != null)) { throw new IntrospectionException(Messages.getString("beans.50")); } setIndexedReadMethod(indexedGetter); setIndexedWriteMethod(indexedSetter); } public IndexedPropertyDescriptor(String propertyName, Class<?> beanClass) throws IntrospectionException { super(propertyName, beanClass, null, null); String getterName; String setterName; String indexedGetterName; String indexedSetterName; // array getter getterName = createDefaultMethodName(propertyName, "get"); //$NON-NLS-1$ if (hasMethod(beanClass, getterName)) { setReadMethod(beanClass, getterName); } // array setter setterName = createDefaultMethodName(propertyName, "set"); //$NON-NLS-1$ if (hasMethod(beanClass, setterName)) { setWriteMethod(beanClass, setterName); } // indexed getter indexedGetterName = createDefaultMethodName(propertyName, "get"); //$NON-NLS-1$ if (hasMethod(beanClass, indexedGetterName)) { setIndexedReadMethod(beanClass, indexedGetterName); } // indexed setter indexedSetterName = createDefaultMethodName(propertyName, "set"); //$NON-NLS-1$ if (hasMethod(beanClass, indexedSetterName)) { setIndexedWriteMethod(beanClass, indexedSetterName); } // RI seems to behave a bit differently if (indexedGetter == null && indexedSetter == null && getReadMethod() == null && getWriteMethod() == null) { throw new IntrospectionException( Messages.getString("beans.01", propertyName)); //$NON-NLS-1$ } if (indexedGetter == null && indexedSetter == null) { // not an indexed property indeed throw new IntrospectionException(Messages.getString("beans.50")); } } public void setIndexedReadMethod(Method indexedGetter) throws IntrospectionException { if (indexedGetter != null) { int modifiers = indexedGetter.getModifiers(); Class<?>[] parameterTypes; Class<?> returnType; Class<?> indexedPropertyType; if (!Modifier.isPublic(modifiers)) { throw new IntrospectionException(Messages.getString("beans.21")); //$NON-NLS-1$ } parameterTypes = indexedGetter.getParameterTypes(); if (parameterTypes.length != 1) { throw new IntrospectionException(Messages.getString("beans.22")); //$NON-NLS-1$ } if (!parameterTypes[0].equals(int.class)) { throw new IntrospectionException(Messages.getString("beans.23")); //$NON-NLS-1$ } returnType = indexedGetter.getReturnType(); indexedPropertyType = getIndexedPropertyType(); if ((indexedPropertyType != null) && !returnType.equals(indexedPropertyType)) { throw new IntrospectionException(Messages.getString("beans.24")); //$NON-NLS-1$ } } this.indexedGetter = indexedGetter; } public void setIndexedWriteMethod(Method indexedSetter) throws IntrospectionException { if (indexedSetter != null) { int modifiers = indexedSetter.getModifiers(); Class<?>[] parameterTypes; Class<?> firstParameterType; Class<?> secondParameterType; Class<?> propType; if (!Modifier.isPublic(modifiers)) { throw new IntrospectionException(Messages.getString("beans.25")); //$NON-NLS-1$ } parameterTypes = indexedSetter.getParameterTypes(); if (parameterTypes.length != 2) { throw new IntrospectionException(Messages.getString("beans.26")); //$NON-NLS-1$ } firstParameterType = parameterTypes[0]; if (!firstParameterType.equals(int.class)) { throw new IntrospectionException(Messages.getString("beans.27")); //$NON-NLS-1$ } secondParameterType = parameterTypes[1]; propType = getIndexedPropertyType(); if (propType != null && !secondParameterType.equals(propType)) { throw new IntrospectionException(Messages.getString("beans.28")); //$NON-NLS-1$ } } this.indexedSetter = indexedSetter; } public Method getIndexedWriteMethod() { return indexedSetter; } public Method getIndexedReadMethod() { return indexedGetter; } @Override public boolean equals(Object obj) { boolean result = super.equals(obj); if (result) { IndexedPropertyDescriptor pd = (IndexedPropertyDescriptor) obj; if (indexedGetter != null) { result = indexedGetter.equals(pd.getIndexedReadMethod()); } else if (result && indexedGetter == null) { result = pd.getIndexedReadMethod() == null; } if (result) { if (indexedSetter != null) { result = indexedSetter.equals(pd.getIndexedWriteMethod()); } else if (indexedSetter == null) { result = pd.getIndexedWriteMethod() == null; } } } return result; } public Class<?> getIndexedPropertyType() { Class<?> result = null; if (indexedGetter != null) { result = indexedGetter.getReturnType(); } else if (indexedSetter != null) { Class<?>[] parameterTypes = indexedSetter.getParameterTypes(); result = parameterTypes[1]; } return result; } private void setIndexedReadMethod(Class<?> beanClass, String indexedGetterName) { Method[] getters = findMethods(beanClass, indexedGetterName); boolean result = false; for (Method element : getters) { try { setIndexedReadMethod(element); result = true; } catch (IntrospectionException ie) {} if (result) { break; } } } private void setIndexedWriteMethod(Class<?> beanClass, String indexedSetterName) { Method[] setters = findMethods(beanClass, indexedSetterName); boolean result = false; for (Method element : setters) { try { setIndexedWriteMethod(element); result = true; } catch (IntrospectionException ie) {} if (result) { break; } } } }
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/edu-services/tags/sakai-10.6/sections-service/sections-api/src/java/org/sakaiproject/section/api/SectionManager.java $ * $Id: SectionManager.java 105077 2012-02-24 22:54:29Z [email protected] $ *********************************************************************************** * * Copyright (c) 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.section.api; import java.sql.Time; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Calendar; import org.sakaiproject.section.api.coursemanagement.Course; import org.sakaiproject.section.api.coursemanagement.CourseSection; import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord; import org.sakaiproject.section.api.coursemanagement.Meeting; import org.sakaiproject.section.api.coursemanagement.ParticipationRecord; import org.sakaiproject.section.api.coursemanagement.SectionEnrollments; import org.sakaiproject.section.api.coursemanagement.User; import org.sakaiproject.section.api.exception.MembershipException; import org.sakaiproject.section.api.exception.SectionFullException; import org.sakaiproject.section.api.exception.RoleConfigurationException; import org.sakaiproject.section.api.facade.Role; /** * An internal service interface for the Section Manager Tool (AKA "Section Info") * to provide for the creation, modification, and removal of CourseSections, along * with the membership of of these sections. * * This service is not to be used outside of the Section Manager Tool. * * @author <a href="mailto:[email protected]">Josh Holtzman</a> * */ public interface SectionManager { /** * Gets the course (whatever that means) associated with this site context. * * @param siteContext The site context * @return The course (whatever that means) */ public Course getCourse(String siteContext); /** * Gets the sections associated with this site context. * * @param siteContext The site context * * @return The List of * {@link org.sakaiproject.section.api.coursemanagement.CourseSection CourseSections} * associated with this site context. */ public List<CourseSection> getSections(String siteContext); /** * Lists the sections in this context that are a member of the given category. * * @param siteContext The site context * @param categoryId * * @return A List of {@link org.sakaiproject.section.api.coursemanagement.CourseSection CourseSections} */ public List<CourseSection> getSectionsInCategory(String siteContext, String categoryId); /** * Gets a {@link org.sakaiproject.section.api.coursemanagement.CourseSection CourseSection} * by its uuid. * * @param sectionUuid The uuid of a section * * @return A section */ public CourseSection getSection(String sectionUuid); /** * Gets a list of {@link org.sakaiproject.section.api.coursemanagement.ParticipationRecord * ParticipationRecord}s for all instructors in the current site. * * @param siteContext The current site context * @return The instructors */ public List<ParticipationRecord> getSiteInstructors(String siteContext); /** * Gets a list of {@link org.sakaiproject.section.api.coursemanagement.ParticipationRecord * ParticipationRecord}s for all TAs in the current site. * * @param siteContext The current site context * @return The TAs */ public List<ParticipationRecord> getSiteTeachingAssistants(String siteContext); /** * Gets a list of {@link org.sakaiproject.section.api.coursemanagement.ParticipationRecord * ParticipationRecord}s for all TAs in a section. * * @param sectionUuid The section uuid * @return The TAs */ public List<ParticipationRecord> getSectionTeachingAssistants(String sectionUuid); /** * Gets a list of {@link org.sakaiproject.section.api.coursemanagement.EnrollmentRecord * EnrollmentRecord}s belonging to the current site. * * @param siteContext The current site context * @return The enrollments */ public List<EnrollmentRecord> getSiteEnrollments(String siteContext); /** * Gets a list of {@link org.sakaiproject.section.api.coursemanagement.EnrollmentRecord * EnrollmentRecord}s belonging to a section. * * @param sectionUuid The section uuid * @return The enrollments */ public List<EnrollmentRecord> getSectionEnrollments(String sectionUuid); /** * Finds a list of {@link org.sakaiproject.section.api.coursemanagement.EnrollmentRecord * EnrollmentRecord}s belonging to the current site and whose sort name, display name, * or display id start with the given string pattern. * * @param siteContext The current site context * @param pattern The pattern to match students names or ids * * @return The enrollments */ public List<EnrollmentRecord> findSiteEnrollments(String siteContext, String pattern); /** * Gets a SectionEnrollments data structure for the given students. * * @param siteContext The site context * @param studentUids The Set of userUids to include in the SectionEnrollments * * @return */ public SectionEnrollments getSectionEnrollmentsForStudents(String siteContext, Set studentUids); /** * Adds the current user to a section as a student. This is a convenience * method for addSectionMembership(currentUserId, Role.STUDENT, sectionId). * @param sectionUuid * @throws RoleConfigurationException If there is no valid student role, or * if there is more than one group-scoped role flagged as a student role. */ public EnrollmentRecord joinSection(String sectionUuid) throws RoleConfigurationException; /** * Adds the current user to a section as a student, enforcing a maximum permitted size. * @param sectionUuid * @param maxSize * @throws RoleConfigurationException If there is no valid student role, or * if there is more than one group-scoped role flagged as a student role. * @throws SectionFullException If adding the user would exceed the size limit */ public EnrollmentRecord joinSection(String sectionUuid, int maxSize) throws RoleConfigurationException, SectionFullException; /** * Switches a student's currently assigned section. If the student is enrolled * in another section of the same type, that enrollment will be dropped. * * This is a convenience method to allow a drop/add (a switch) in a single transaction. * * @param newSectionUuid The new section uuid to which the student should be assigned * @throws RoleConfigurationException If there is no valid student role, or * if there is more than one group-scoped role flagged as a student role. */ public void switchSection(String newSectionUuid) throws RoleConfigurationException; /** * Switches a student's currently assigned section, enforcing a maximum permitted size. * If the student is enrolled in another section of the same type, that enrollment * will be dropped. * * This is a convenience method to allow a drop/add (a switch) in a single transaction. * * @param newSectionUuid The new section uuid to which the student should be assigned * @throws RoleConfigurationException If there is no valid student role, or * if there is more than one group-scoped role flagged as a student role. * @throws SectionFullException If adding the user would exceed the size limit */ public void switchSection(String newSectionUuid, int maxSize) throws RoleConfigurationException, SectionFullException; /** * Returns the total number of students enrolled in a learning context. Useful for * comparing to the max number of enrollments allowed in a section. * * @param sectionUuid * @return */ public int getTotalEnrollments(String learningContextUuid); /** * Returns the total number of students enrolled in a learning context by section role. * Useful for comparing to the max number of enrollments allowed in a section. * * @param sectionUuid * @return */ public Map getTotalEnrollmentsMap(String learningContextUuid); /** * Adds a user to a section under the specified role. If a student is added * to a section, s/he will be automatically removed from any other section * of the same category in this site. So adding 'student1' to 'Lab1', for * example, will automatically remove 'student1' from 'Lab2'. TAs may be * added to multiple sections in a site regardless of category. * * @param userUid * @param role * @param sectionUuid * @throws MembershipException Only students and TAs can be members of a * section. Instructor roles are assigned only at the course level. * @throws RoleConfigurationException Thrown when no sakai role can be * identified to represent the given role. */ public ParticipationRecord addSectionMembership(String userUid, Role role, String sectionUuid) throws MembershipException, RoleConfigurationException; /** * Defines the complete set of users that make up the members of a section in * a given role. This is useful when doing bulk modifications of section * membership. * * @param userUids The set of userUids as strings * @param sectionId The sectionId * * @throws RoleConfigurationException If there is no properly configured role * in the site matching the role specified. */ public void setSectionMemberships(Set userUids, Role role, String sectionId) throws RoleConfigurationException; /** * Removes a user from a section. * * @param userUid * @param sectionUuid */ public void dropSectionMembership(String userUid, String sectionUuid); /** * Removes the user from any enrollment to a section of the given category. * * @param studentUid * @param siteContext * @param category */ public void dropEnrollmentFromCategory(String studentUid, String siteContext, String category); /** * Adds a CourseSection with a single meeting time to a parent CourseSection. * This method is deprecated. Please use addSection(String courseUuid, String title, * String category, Integer maxEnrollments, List meetings) * * @param courseUuid * @param title * @param category * @param maxEnrollments * @param location * @param startTime * @param startTimeAm * @param endTime * @param endTimeAm * @param monday * @param tuesday * @param wednesday * @param thursday * @param friday * @param saturday * @param sunday * * @deprecated * * @return */ public CourseSection addSection(String courseUuid, String title, String category, Integer maxEnrollments, String location, Time startTime, Time endTime, boolean monday, boolean tuesday, boolean wednesday, boolean thursday, boolean friday, boolean saturday, boolean sunday); /** * Adds multiple sections at once. This should help address the inefficiencies * described in http://bugs.sakaiproject.org/jira/browse/SAK-7503. * * Meeting times should be, but are not handled by an external calendar service. * So, the added functionality of linking course sections to repeating events (meet * every 2nd Tuesday of the month at 3pm) is currently out of scope. Instead, * meetings are represented as a start time, end time, and seven booleans * representing the days that the section meets. * * @param courseUuid * @param sections */ public Collection<CourseSection> addSections(String courseUuid, Collection<CourseSection> sections); /** * Updates the persistent representation of the given CourseSection. Once * a section is created, its category is immutable. This method will remove all * but one Meeting associated with this CourseSection. To update a CourseSection * and all of its meetings, use updateSection(String sectionUuid, String title, * Integer maxEnrollments, List meetings). * * @param sectionUuid * @param title * @param maxEnrollments * @param location * @param startTime * @param startTimeAm * @param endTime * @param endTimeAm * @param monday * @param tuesday * @param wednesday * @param thursday * @param friday * @param saturday * @param sunday * * @deprecated */ public void updateSection(String sectionUuid, String title, Integer maxEnrollments, String location, Time startTime, Time endTime, boolean monday, boolean tuesday, boolean wednesday, boolean thursday, boolean friday, boolean saturday, boolean sunday); /** * Updates a section and all of its meetings. Notice that you can not change a * section's category once it's been created. * * @param sectionUuid * @param title * @param maxEnrollments * @param meetings */ public void updateSection(String sectionUuid, String title, Integer maxEnrollments, List<Meeting> meetings); /** * Disbands a course section. This does not affect enrollment records for * the course. * * @param sectionUuid */ public void disbandSection(String sectionUuid); /** * Disbands course sections. This does not affect enrollment records for * the course. * * @param sectionUuids */ public void disbandSections(Set<String> sectionUuids); /** * Determines whether students can enroll themselves in a section. * * * @param courseUuid * @return */ public boolean isSelfRegistrationAllowed(String courseUuid); /** * Determines whether students can switch sections once they are enrolled in * a section of a given category (for instance, swapping one lab for another). * * @param courseUuid * @return */ public boolean isSelfSwitchingAllowed(String courseUuid); /** * Sets the join/switch options for a course. * * @param courseUuid * @param joinAllowed * @param switchAllowed */ public void setJoinOptions(String courseUuid, boolean joinAllowed, boolean switchAllowed); /** * Determines whether a course is externally managed. * * @param courseUuid * @return */ public boolean isExternallyManaged(String courseUuid); /** * Sets a course as externally or internally managed. * * @param courseUuid * @param externallyManaged */ public void setExternallyManaged(String courseUuid, boolean externallyManaged); /** * The Section Manager tool could use more specific queries on membership, * such as this: getting all students in a primary section that are not * enrolled in any secondary sections of a given type. For instance, 'Who * are the students who are not enrolled in any lab?' * * @return A List of {@link * org.sakaiproject.section.api.coursemanagement.EnrollmentRecord * EnrollmentRecords} of students who are enrolled in the course but are * not enrolled in a section of the given section category. */ public List<EnrollmentRecord> getUnsectionedEnrollments(String courseUuid, String category); /** * Gets the enrollment size for a set of sections. * * @param sectionSet * @return A Map (sectionUuid, size) */ public Map getEnrollmentCount(List sectionSet); /** * Gets the list of Teaching Assistants for a set of sections * * @param sectionSet * @return A Map (sectionUuid, List<ParticipationRecord> ) of TAs for each section */ public Map<String,List<ParticipationRecord>> getSectionTeachingAssistantsMap(List sectionSet); /** * Gets all of the section enrollments for a user in a course. Useful for * listing all of the sections in which a student is enrolled. * * @param userUid * @param courseUuid * @return A Set of EnrollmentRecords */ public Set<EnrollmentRecord> getSectionEnrollments(String userUid, String courseUuid); /** * Gets the localized name of a given category. * * @param categoryId A string identifying the category * @param locale The locale of the client * * @return An internationalized string to display for this category. * */ public String getCategoryName(String categoryId, Locale locale); /** * Gets the list of section categories. These are not configurable on a per-course * or per-context bases. * * @param siteContext The site context (which is not used in the * current implementation) * * @return A List of unique Strings that identify the available section * categories. */ public List<String> getSectionCategories(String siteContext); /** * Gets a single User object for a student in a site. * * @param siteContext Needed by the standalone implementation to find the user * @param studentUid * @return The User representing this student */ public User getSiteEnrollment(String siteContext, String studentUid); //// Configuration /** * Describes the configuration for the SectionManager service and the Section * Info tool: * * <ul> * <li><b>MANUAL_MANDATORY</b> - The Section Info tool does not allow for * externally managed sections, and sections will never be created automatically</li> * * <li><b>MANUAL_DEFAULT</b> - The Section Info tool allows the user * to choose whether sections should be internally or externally managed. * Sections will not be generated for sites unless a site maintainer switches the * default "manual" setting to automatic.</li> * * <li><b>AUTOMATIC_DEFAULT</b> - The Section Info tool allows the user * to choose whether sections should be internally or externally managed. * Sections will be generated for sites associated with any number of rosters. * The default setting for new sites will be automatic management of sections.</li> * * <li><b>AUTOMATIC_MANDATORY</b> - The Section Info tool does not allow * for internally managed sections. All sections are created automatically, based * on the rosters associated with the site.</li> * </ul> * */ public enum ExternalIntegrationConfig {MANUAL_MANDATORY, MANUAL_DEFAULT, AUTOMATIC_DEFAULT, AUTOMATIC_MANDATORY}; /** * Gets the application-wide configuration setting. * * @param obj An object to pass any necessary context information. * @return */ public ExternalIntegrationConfig getConfiguration(Object obj); public static final String CONFIGURATION_KEY="section.info.integration"; /** * Determines when the section options are open to students. * * @param courseUuid * @return */ public Calendar getOpenDate(String courseUid); public void setOpenDate(String courseUuid,Calendar openDate); }
/** * Copyright 2016, 2017 Peter Zybrick and others. * * 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 Pete Zybrick * @version 1.0.0, 2017-09 * */ package com.pzybrick.iote2e.ws.nrt; import java.time.Instant; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import javax.websocket.server.ServerContainer; import org.apache.avro.util.Utf8; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer; import com.pzybrick.iote2e.common.config.MasterConfig; import com.pzybrick.iote2e.common.utils.Iote2eConstants; import com.pzybrick.iote2e.common.utils.Iote2eUtils; import com.pzybrick.iote2e.schema.avro.Iote2eResult; import com.pzybrick.iote2e.schema.util.Iote2eSchemaConstants; /** * The Class ThreadEntryPointNearRealTime. */ public class ThreadEntryPointNearRealTime extends Thread { /** The Constant logger. */ private static final Logger logger = LogManager.getLogger(ThreadEntryPointNearRealTime.class); /** The Constant serverSideSocketNearRealTimes. */ public static final Map<String, ServerSideSocketNearRealTime> serverSideSocketNearRealTimes = new ConcurrentHashMap<String, ServerSideSocketNearRealTime>(); /** The Constant toClientIote2eResults. */ public static final ConcurrentLinkedQueue<Iote2eResult> toClientIote2eResults = new ConcurrentLinkedQueue<Iote2eResult>(); /** The server. */ private Server server; /** The connector. */ private ServerConnector connector; /** The master config. */ public static MasterConfig masterConfig; /** * Instantiates a new thread entry point near real time. */ public ThreadEntryPointNearRealTime( ) { } /** * Instantiates a new thread entry point near real time. * * @param masterConfig the master config */ public ThreadEntryPointNearRealTime( MasterConfig masterConfig ) { ThreadEntryPointNearRealTime.masterConfig = masterConfig; } /* (non-Javadoc) * @see java.lang.Thread#run() */ public void run( ) { logger.info(masterConfig.toString()); try { server = new Server(); connector = new ServerConnector(server); connector.setPort(masterConfig.getWsNrtServerListenPort()); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); try { ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context); wscontainer.addEndpoint(ServerSideSocketNearRealTime.class); ThreadToBrowserNrtMonitor threadToBrowserNrtMonitor = new ThreadToBrowserNrtMonitor(); threadToBrowserNrtMonitor.start(); logger.info("Server starting"); server.start(); logger.info("Server started"); server.join(); threadToBrowserNrtMonitor.shutdown(); threadToBrowserNrtMonitor.join(15 * 1000L); } catch (Throwable t) { logger.error("Server Exception",t); } finally { } } catch( Exception e ) { logger.error(e.getMessage(), e); } } /** * The Class ThreadToBrowserNrtMonitor. */ public class ThreadToBrowserNrtMonitor extends Thread { /** The shutdown. */ private boolean shutdown; /** * Shutdown. */ public void shutdown() { logger.info("Shutdown"); shutdown = true; interrupt(); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { final CharSequence checkTemp = new Utf8("temperature"); final CharSequence checkBloodPressure = new Utf8("blood-pressure"); final CharSequence checkSystolic = new Utf8("SYSTOLIC"); final CharSequence checkDiastolic = new Utf8("DIASTOLIC"); final CharSequence checkEngineOilPressure = new Utf8("oil-pressure"); final CharSequence checkEngine1 = new Utf8("engine1"); final CharSequence checkEngine2 = new Utf8("engine2"); final CharSequence checkEngine3 = new Utf8("engine3"); final CharSequence checkEngine4 = new Utf8("engine4"); TemperatureSensorItem temperatureSensorItem = new TemperatureSensorItem(); BloodPressureSensorItem bloodPressureSensorItem = new BloodPressureSensorItem(); EngineOilPressureSensorItem engineOilPressureSensorItem = new EngineOilPressureSensorItem(); logger.info("ThreadToBrowserNrtMonitor Run"); try { while (true) { logger.info("ThreadToBrowserNrtMonitor alive"); while (!toClientIote2eResults.isEmpty()) { Iote2eResult iote2eResult = toClientIote2eResults.poll(); if( iote2eResult != null ) { logger.debug("sourceType {}", iote2eResult.getSourceType() ); ServerSideSocketNearRealTime socket = null; socket = serverSideSocketNearRealTimes.get(Iote2eConstants.SOCKET_KEY_NRT); logger.debug("socket {}", socket ); if( socket != null ) { try { if( checkTemp.equals(iote2eResult.getSourceType())) { logger.debug("processing temperature"); // Create TemperatureSensorItem from values in Iote2eResult float degreesC = Float.parseFloat(iote2eResult.getPairs().get(new Utf8(Iote2eSchemaConstants.PAIRNAME_SENSOR_VALUE)).toString()); temperatureSensorItem .setSourceName(iote2eResult.getSourceName().toString()) .setDegreesC(degreesC) .setTimeMillis( Instant.parse( iote2eResult.getRequestTimestamp() ).toEpochMilli()); String rawJson = Iote2eUtils.getGsonInstance().toJson(temperatureSensorItem); socket.getSession().getBasicRemote().sendText(rawJson); } else if( checkBloodPressure.equals(iote2eResult.getSourceType())) { logger.debug("processing blood pressure systolic: {}", iote2eResult.getPairs().get(checkSystolic)); int systolic = Integer.parseInt(iote2eResult.getPairs().get(checkSystolic).toString()); int diastolic = Integer.parseInt(iote2eResult.getPairs().get(checkDiastolic).toString()); logger.debug("systolic {}, diastolic {}", systolic, diastolic); bloodPressureSensorItem .setSourceName(iote2eResult.getSourceName().toString()) .setTimeMillis( Instant.parse( iote2eResult.getRequestTimestamp() ).toEpochMilli()) .setSystolic(systolic) .setDiastolic(diastolic); String rawJson = Iote2eUtils.getGsonInstance().toJson(bloodPressureSensorItem); logger.debug("blood pressure raw json: {}", rawJson ); socket.getSession().getBasicRemote().sendText(rawJson); } else if( checkEngineOilPressure.equals(iote2eResult.getSourceType())) { // this is a hack Float engine1 = null; Float engine2 = null; Float engine3 = null; Float engine4 = null; if(iote2eResult.getPairs().containsKey(checkEngine1)) { engine1 = Float.parseFloat(iote2eResult.getPairs().get(checkEngine1).toString()); } if(iote2eResult.getPairs().containsKey(checkEngine2)) { engine2 = Float.parseFloat(iote2eResult.getPairs().get(checkEngine2).toString()); } if(iote2eResult.getPairs().containsKey(checkEngine3)) { engine3 = Float.parseFloat(iote2eResult.getPairs().get(checkEngine3).toString()); } if(iote2eResult.getPairs().containsKey(checkEngine4)) { engine4 = Float.parseFloat(iote2eResult.getPairs().get(checkEngine4).toString()); } logger.debug("processing engine oil pressure 1: {}, 2: {}, 3: {}, 4: {}", engine1, engine2, engine3, engine4 ); engineOilPressureSensorItem .setFlightNumber(iote2eResult.getSourceName().toString()) .setTimeMillis( Instant.parse( iote2eResult.getRequestTimestamp() ).toEpochMilli()) .setEngine1(engine1) .setEngine2(engine2) .setEngine3(engine3) .setEngine4(engine4); String rawJson = Iote2eUtils.getGsonInstance().toJson(engineOilPressureSensorItem); logger.debug("engine oil pressure raw json: {}", rawJson ); socket.getSession().getBasicRemote().sendText(rawJson); } else logger.warn("No match on sourceType: {} ", iote2eResult.getSourceType()); } catch (Throwable e) { logger.error("Exception sending text message",e); break; } finally { } } } } try { sleep(500L); } catch (InterruptedException e) {} if (shutdown) break; } } catch (Exception e) { logger.error("Exception processing target text message", e); } logger.info("Exit"); } } }
/* * Copyright (C) 2011 Everit Kft. (http://www.everit.org) * * 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.everit.blobstore.testbase; import java.lang.Thread.State; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import org.everit.blobstore.BlobReader; import org.everit.blobstore.Blobstore; import org.everit.transaction.propagator.TransactionPropagator; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; /** * Abstract class to test blobstore use-cases. Tests can be skipped if {@link #getBlobStore()} * returns <code>null</code>. */ public abstract class AbstractBlobstoreTest { private static final int DEFAULT_TIMEOUT = 5000; private LambdaBlobstore lambdaBlobstore; @After public void after() { getLambdaBlobStore().deleteAllCreatedBlobs(); lambdaBlobstore = null; } /** * Returns the {@link Blobstore} to test with. If the method returns <code>null</code>, all tests * will be skipped. * * @return The {@link Blobstore} to test with or <code>null</code> if the tests should be skipped. */ protected abstract Blobstore getBlobStore(); /** * Gets a Java 8 Blobstore that will delete all blobs created by the tests in the end. * * @return The lambda based blobstore. */ protected LambdaBlobstore getLambdaBlobStore() { if (lambdaBlobstore != null) { return lambdaBlobstore; } Blobstore blobStore = getBlobStore(); Assume.assumeNotNull(blobStore); lambdaBlobstore = new LambdaBlobstore(blobStore, getTransactionPropagator()); return lambdaBlobstore; } protected abstract TransactionPropagator getTransactionPropagator(); @Test public void testBlobCreationWithContent() { LambdaBlobstore blobStore = getLambdaBlobStore(); long blobId = blobStore.createBlob((blobAccessor) -> { blobAccessor.write(new byte[] { 2, 1, 2, 1 }, 1, 2); }); blobStore.readBlob(blobId, (blobReader) -> { Assert.assertEquals(2, blobReader.getSize()); final int bufferSize = 5; byte[] buffer = new byte[bufferSize]; final int readLength = 3; int read = blobReader.read(buffer, 1, readLength); Assert.assertEquals(2, read); Assert.assertArrayEquals(new byte[] { 0, 1, 2, 0, 0 }, buffer); }); } @Test public void testParallelBlobManipulationWithTwoTransactions() { LambdaBlobstore blobStore = getLambdaBlobStore(); long blobId = blobStore.createBlob((blobAccessor) -> { blobAccessor.write(new byte[] { 0 }, 0, 1); }); BooleanHolder waitForAppendByBlockedThread = new BooleanHolder(false); getTransactionPropagator().required(() -> { blobStore.updateBlob(blobId, (blobAccessor) -> { blobAccessor.seek(blobAccessor.getSize()); blobAccessor.write(new byte[] { 1 }, 0, 1); }); blobStore.readBlob(blobId, (blobReader) -> Assert.assertEquals(2, blobReader.getSize())); getTransactionPropagator().requiresNew(() -> { blobStore.readBlob(blobId, (blobReader) -> Assert.assertEquals(1, blobReader.getSize())); return null; }); long blobId2 = blobStore.createBlob(null); blobStore.updateBlob(blobId2, (blobAccessor) -> { }); blobStore.deleteBlob(blobId2); Thread otherUpdatingThread = new Thread(() -> { try { blobStore.updateBlob(blobId, (blobAccessor) -> { blobAccessor.seek(blobAccessor.getSize()); blobAccessor.write(new byte[] { 2 }, 0, 1); }); } finally { BlobstoreTestUtil.notifyAboutEvent(waitForAppendByBlockedThread); } }); otherUpdatingThread.start(); final int maxWaitTime = 1000; BlobstoreTestUtil.waitForThreadStateOrSocketRead(otherUpdatingThread, State.WAITING, maxWaitTime); blobStore.readBlob(blobId, (blobReader) -> Assert.assertEquals(2, blobReader.getSize())); return null; }); Assert .assertTrue(BlobstoreTestUtil.waitForEvent(waitForAppendByBlockedThread, DEFAULT_TIMEOUT)); final int expectedBlobSize = 3; blobStore.readBlob(blobId, (blobReader) -> Assert.assertEquals(expectedBlobSize, blobReader.getSize())); blobStore.deleteBlob(blobId); } @Test public void testReadBlobDuringOngoingUpdateOnOtherThread() { LambdaBlobstore blobStore = getLambdaBlobStore(); long blobId = blobStore.createBlob((blobAccessor) -> { blobAccessor.write(new byte[] { 2 }, 0, 1); }); BooleanHolder waitForReadCheck = new BooleanHolder(false); BooleanHolder waitForUpdate = new BooleanHolder(false); new Thread(() -> { try { blobStore.updateBlob(blobId, (blobAccessor) -> { blobAccessor.seek(blobAccessor.getSize()); blobAccessor.write(new byte[] { 1 }, 0, 1); Assert.assertTrue(BlobstoreTestUtil.waitForEvent(waitForReadCheck, DEFAULT_TIMEOUT)); }); } finally { BlobstoreTestUtil.notifyAboutEvent(waitForUpdate); } }).start(); try { // Do some test read before update finishes blobStore.readBlob(blobId, (blobReader) -> { byte[] buffer = new byte[2]; int read = blobReader.read(buffer, 0, 2); Assert.assertEquals(1, read); Assert.assertEquals(2, buffer[0]); }); // Create another blob until lock of first blob holds long blobIdOfSecondBlob = blobStore.createBlob(null); blobStore.readBlob(blobIdOfSecondBlob, (blobReader) -> { Assert.assertEquals(0, blobReader.getSize()); }); blobStore.deleteBlob(blobIdOfSecondBlob); } finally { BlobstoreTestUtil.notifyAboutEvent(waitForReadCheck); Assert.assertTrue(BlobstoreTestUtil.waitForEvent(waitForUpdate, DEFAULT_TIMEOUT)); } blobStore.readBlob(blobId, (blobReader) -> Assert.assertEquals(2, blobReader.getSize())); blobStore.deleteBlob(blobId); } @Test public void testSeek() { LambdaBlobstore blobStore = getLambdaBlobStore(); final int sampleContentSize = 1024 * 1024; long blobId = blobStore.createBlob((blobAccessor) -> { byte[] sampleContent = new byte[sampleContentSize]; final int byteMaxUnsignedDivider = 256; for (int i = 0; i < sampleContentSize; i++) { sampleContent[i] = (byte) (i % byteMaxUnsignedDivider); } blobAccessor.write(sampleContent, 0, sampleContentSize); testSeekAndRead(blobAccessor, sampleContentSize); }); blobStore.readBlob(blobId, (blobReader) -> testSeekAndRead(blobReader, sampleContentSize)); blobStore.updateBlob(blobId, (blobAccessor) -> { blobAccessor.seek(sampleContentSize); byte[] dataOnEnd = new byte[] { 2, 2 }; blobAccessor.write(dataOnEnd, 0, dataOnEnd.length); blobAccessor.seek(sampleContentSize / 2); byte[] dataOnMiddle = new byte[] { 1, 1 }; blobAccessor.write(dataOnMiddle, 0, dataOnMiddle.length); byte[] result = new byte[2]; blobAccessor.seek(sampleContentSize); blobAccessor.read(result, 0, result.length); Assert.assertArrayEquals(dataOnEnd, result); blobAccessor.seek(sampleContentSize / 2); blobAccessor.read(result, 0, result.length); Assert.assertArrayEquals(dataOnMiddle, result); }); blobStore.deleteBlob(blobId); } private void testSeekAndRead(final BlobReader blobAccessor, final int sampleContentSize) { byte[] buffer = new byte[2]; blobAccessor.seek(sampleContentSize / 2); blobAccessor.read(buffer, 0, buffer.length); Assert.assertArrayEquals(new byte[] { 0, 1 }, buffer); blobAccessor.seek(1); blobAccessor.read(buffer, 0, buffer.length); Assert.assertArrayEquals(new byte[] { 1, 2 }, buffer); } @Test public void testVersionIsUpgradedDuringUpdate() { LambdaBlobstore blobstore = getLambdaBlobStore(); Set<Long> usedVersions = Collections.synchronizedSet(new HashSet<>()); final long blobId = blobstore.createBlob((blobAccessor) -> { }); final int threadNum = 4; final int iterationNum = 50; AtomicBoolean sameVersionWasUsedTwice = new AtomicBoolean(false); CountDownLatch countDownLatch = new CountDownLatch(threadNum); for (int i = 0; i < threadNum; i++) { new Thread(() -> { try { for (int j = 0; j < iterationNum; j++) { blobstore.updateBlob(blobId, (blobAccessor) -> { boolean added = usedVersions.add(blobAccessor.getVersion()); if (!added) { sameVersionWasUsedTwice.set(true); } }); } } finally { countDownLatch.countDown(); } }).start(); } try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } Assert.assertFalse(sameVersionWasUsedTwice.get()); } @Test public void testZeroLengthBlob() { LambdaBlobstore blobStore = getLambdaBlobStore(); long blobId = blobStore.createBlob((blobAccessor) -> { }); blobStore.readBlob(blobId, (blobReader) -> { Assert.assertEquals(0, blobReader.getSize()); }); } }
/** * 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.ql.plan; import java.util.List; import java.util.Map; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Order; import org.apache.hadoop.hive.ql.exec.Task; import org.apache.hadoop.hive.ql.exec.TaskFactory; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer; import org.apache.hadoop.hive.ql.parse.EximUtil; import org.apache.hadoop.hive.ql.parse.ReplicationSpec; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.plan.CreateTableDesc; import org.apache.hadoop.hive.ql.plan.CreateViewDesc; /** * ImportTableDesc. * */ public class ImportTableDesc { private String dbName = null; private Table table = null; private CreateTableDesc createTblDesc = null; private CreateViewDesc createViewDesc = null; public enum TYPE { TABLE, VIEW }; public ImportTableDesc(String dbName, Table table) throws Exception { this.dbName = dbName; this.table = table; switch (getTableType()) { case TABLE: this.createTblDesc = new CreateTableDesc(dbName, table.getTableName(), false, // isExternal: set to false here, can be overwritten by the IMPORT stmt table.isTemporary(), table.getSd().getCols(), table.getPartitionKeys(), table.getSd().getBucketCols(), table.getSd().getSortCols(), table.getSd().getNumBuckets(), null, null, null, null, null, // these 5 delims passed as serde params null, // comment passed as table params table.getSd().getInputFormat(), table.getSd().getOutputFormat(), null, // location: set to null here, can be overwritten by the IMPORT stmt table.getSd().getSerdeInfo().getSerializationLib(), null, // storagehandler passed as table params table.getSd().getSerdeInfo().getParameters(), table.getParameters(), false, (null == table.getSd().getSkewedInfo()) ? null : table.getSd().getSkewedInfo() .getSkewedColNames(), (null == table.getSd().getSkewedInfo()) ? null : table.getSd().getSkewedInfo() .getSkewedColValues(), null, null); this.createTblDesc.setStoredAsSubDirectories(table.getSd().isStoredAsSubDirectories()); break; case VIEW: String[] qualViewName = { dbName, table.getTableName() }; String dbDotView = BaseSemanticAnalyzer.getDotName(qualViewName); if (table.isMaterializedView()) { this.createViewDesc = new CreateViewDesc(dbDotView, table.getAllCols(), null, // comment passed as table params table.getParameters(), table.getPartColNames(), false,false,false,false, table.getSd().getInputFormat(), table.getSd().getOutputFormat(), null, // location: set to null here, can be overwritten by the IMPORT stmt table.getSd().getSerdeInfo().getSerializationLib(), null, // storagehandler passed as table params table.getSd().getSerdeInfo().getParameters()); } else { this.createViewDesc = new CreateViewDesc(dbDotView, table.getAllCols(), null, // comment passed as table params table.getParameters(), table.getPartColNames(), false,false,false, table.getSd().getInputFormat(), table.getSd().getOutputFormat(), table.getSd().getSerdeInfo().getSerializationLib()); } this.setViewAsReferenceText(dbName, table); this.createViewDesc.setPartCols(table.getPartCols()); break; default: throw new HiveException("Invalid table type"); } } public TYPE getTableType() { if (table.isView() || table.isMaterializedView()) { return TYPE.VIEW; } return TYPE.TABLE; } public void setViewAsReferenceText(String dbName, Table table) { String originalText = table.getViewOriginalText(); String expandedText = table.getViewExpandedText(); if (!dbName.equals(table.getDbName())) { // TODO: If the DB name doesn't match with the metadata from dump, then need to rewrite the original and expanded // texts using new DB name. Currently it refers to the source database name. } this.createViewDesc.setViewOriginalText(originalText); this.createViewDesc.setViewExpandedText(expandedText); } public void setReplicationSpec(ReplicationSpec replSpec) { switch (getTableType()) { case TABLE: createTblDesc.setReplicationSpec(replSpec); break; case VIEW: createViewDesc.setReplicationSpec(replSpec); break; } } public void setExternal(boolean isExternal) { if (TYPE.TABLE.equals(getTableType())) { createTblDesc.setExternal(isExternal); } } public boolean isExternal() { if (TYPE.TABLE.equals(getTableType())) { return createTblDesc.isExternal(); } return false; } public void setLocation(String location) { switch (getTableType()) { case TABLE: createTblDesc.setLocation(location); break; case VIEW: createViewDesc.setLocation(location); break; } } public String getLocation() { switch (getTableType()) { case TABLE: return createTblDesc.getLocation(); case VIEW: return createViewDesc.getLocation(); } return null; } public void setTableName(String tableName) throws SemanticException { switch (getTableType()) { case TABLE: createTblDesc.setTableName(tableName); break; case VIEW: String[] qualViewName = { dbName, tableName }; String dbDotView = BaseSemanticAnalyzer.getDotName(qualViewName); createViewDesc.setViewName(dbDotView); break; } } public String getTableName() throws SemanticException { switch (getTableType()) { case TABLE: return createTblDesc.getTableName(); case VIEW: String dbDotView = createViewDesc.getViewName(); String[] names = Utilities.getDbTableName(dbDotView); return names[1]; // names[0] have the Db name and names[1] have the view name } return null; } public List<FieldSchema> getPartCols() { switch (getTableType()) { case TABLE: return createTblDesc.getPartCols(); case VIEW: return createViewDesc.getPartCols(); } return null; } public List<FieldSchema> getCols() { switch (getTableType()) { case TABLE: return createTblDesc.getCols(); case VIEW: return createViewDesc.getSchema(); } return null; } public Map<String, String> getTblProps() { switch (getTableType()) { case TABLE: return createTblDesc.getTblProps(); case VIEW: return createViewDesc.getTblProps(); } return null; } public String getInputFormat() { switch (getTableType()) { case TABLE: return createTblDesc.getInputFormat(); case VIEW: return createViewDesc.getInputFormat(); } return null; } public String getOutputFormat() { switch (getTableType()) { case TABLE: return createTblDesc.getOutputFormat(); case VIEW: return createViewDesc.getOutputFormat(); } return null; } public String getSerName() { switch (getTableType()) { case TABLE: return createTblDesc.getSerName(); case VIEW: return createViewDesc.getSerde(); } return null; } public Map<String, String> getSerdeProps() { switch (getTableType()) { case TABLE: return createTblDesc.getSerdeProps(); case VIEW: return createViewDesc.getSerdeProps(); } return null; } public List<String> getBucketCols() { if (TYPE.TABLE.equals(getTableType())) { return createTblDesc.getBucketCols(); } return null; } public List<Order> getSortCols() { if (TYPE.TABLE.equals(getTableType())) { return createTblDesc.getSortCols(); } return null; } /** * @param replaceMode Determine if this CreateTable should behave like a replace-into alter instead */ public void setReplaceMode(boolean replaceMode) { if (TYPE.TABLE.equals(getTableType())) { createTblDesc.setReplaceMode(replaceMode); } } public String getDatabaseName() { return dbName; } public Task <?> getCreateTableTask(EximUtil.SemanticAnalyzerWrapperContext x) { switch (getTableType()) { case TABLE: return TaskFactory.get(new DDLWork(x.getInputs(), x.getOutputs(), createTblDesc), x.getConf()); case VIEW: return TaskFactory.get(new DDLWork(x.getInputs(), x.getOutputs(), createViewDesc), x.getConf()); } return null; } /** * @return whether this table is actually a view */ public boolean isView() { return table.isView(); } public boolean isMaterializedView() { return table.isMaterializedView(); } }
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import org.junit.*; import org.mockito.Mockito; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.exceptions.TestException; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.*; public class FlowableOnErrorResumeNextViaFunctionTest { @Test public void testResumeNextWithSynchronousExecution() { final AtomicReference<Throwable> receivedException = new AtomicReference<Throwable>(); Flowable<String> w = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> observer) { observer.onSubscribe(new BooleanSubscription()); observer.onNext("one"); observer.onError(new Throwable("injected failure")); observer.onNext("two"); observer.onNext("three"); } }); Function<Throwable, Flowable<String>> resume = new Function<Throwable, Flowable<String>>() { @Override public Flowable<String> apply(Throwable t1) { receivedException.set(t1); return Flowable.just("twoResume", "threeResume"); } }; Flowable<String> observable = w.onErrorResumeNext(resume); Subscriber<String> observer = TestHelper.mockSubscriber(); observable.subscribe(observer); verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("twoResume"); verify(observer, times(1)).onNext("threeResume"); assertNotNull(receivedException.get()); } @Test public void testResumeNextWithAsyncExecution() { final AtomicReference<Throwable> receivedException = new AtomicReference<Throwable>(); Subscription s = mock(Subscription.class); TestFlowable w = new TestFlowable(s, "one"); Function<Throwable, Flowable<String>> resume = new Function<Throwable, Flowable<String>>() { @Override public Flowable<String> apply(Throwable t1) { receivedException.set(t1); return Flowable.just("twoResume", "threeResume"); } }; Flowable<String> observable = Flowable.unsafeCreate(w).onErrorResumeNext(resume); Subscriber<String> observer = TestHelper.mockSubscriber(); observable.subscribe(observer); try { w.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("twoResume"); verify(observer, times(1)).onNext("threeResume"); assertNotNull(receivedException.get()); } /** * Test that when a function throws an exception this is propagated through onError. */ @Test public void testFunctionThrowsError() { Subscription s = mock(Subscription.class); TestFlowable w = new TestFlowable(s, "one"); Function<Throwable, Flowable<String>> resume = new Function<Throwable, Flowable<String>>() { @Override public Flowable<String> apply(Throwable t1) { throw new RuntimeException("exception from function"); } }; Flowable<String> observable = Flowable.unsafeCreate(w).onErrorResumeNext(resume); @SuppressWarnings("unchecked") DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); observable.subscribe(observer); try { w.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } // we should get the "one" value before the error verify(observer, times(1)).onNext("one"); // we should have received an onError call on the Observer since the resume function threw an exception verify(observer, times(1)).onError(any(Throwable.class)); verify(observer, times(0)).onComplete(); } /** * Test that we receive the onError if an exception is thrown from an operator that * does not have manual try/catch handling like map does. */ @Test @Ignore("Failed operator may leave the child subscriber in an inconsistent state which prevents further error delivery.") public void testOnErrorResumeReceivesErrorFromPreviousNonProtectedOperator() { TestSubscriber<String> ts = new TestSubscriber<String>(); Flowable.just(1).lift(new FlowableOperator<String, Integer>() { @Override public Subscriber<? super Integer> apply(Subscriber<? super String> t1) { throw new RuntimeException("failed"); } }).onErrorResumeNext(new Function<Throwable, Flowable<String>>() { @Override public Flowable<String> apply(Throwable t1) { if (t1.getMessage().equals("failed")) { return Flowable.just("success"); } else { return Flowable.error(t1); } } }).subscribe(ts); ts.assertTerminated(); System.out.println(ts.values()); ts.assertValue("success"); } /** * Test that we receive the onError if an exception is thrown from an operator that * does not have manual try/catch handling like map does. */ @Test @Ignore("A crashing operator may leave the downstream in an inconsistent state and not suitable for event delivery") public void testOnErrorResumeReceivesErrorFromPreviousNonProtectedOperatorOnNext() { TestSubscriber<String> ts = new TestSubscriber<String>(); Flowable.just(1).lift(new FlowableOperator<String, Integer>() { @Override public Subscriber<? super Integer> apply(final Subscriber<? super String> t1) { return new FlowableSubscriber<Integer>() { @Override public void onSubscribe(Subscription s) { t1.onSubscribe(s); } @Override public void onComplete() { throw new RuntimeException("failed"); } @Override public void onError(Throwable e) { throw new RuntimeException("failed"); } @Override public void onNext(Integer t) { throw new RuntimeException("failed"); } }; } }).onErrorResumeNext(new Function<Throwable, Flowable<String>>() { @Override public Flowable<String> apply(Throwable t1) { if (t1.getMessage().equals("failed")) { return Flowable.just("success"); } else { return Flowable.error(t1); } } }).subscribe(ts); ts.assertTerminated(); System.out.println(ts.values()); ts.assertValue("success"); } @Test public void testMapResumeAsyncNext() { // Trigger multiple failures Flowable<String> w = Flowable.just("one", "fail", "two", "three", "fail"); // Introduce map function that fails intermittently (Map does not prevent this when the observer is a // rx.operator incl onErrorResumeNextViaFlowable) w = w.map(new Function<String, String>() { @Override public String apply(String s) { if ("fail".equals(s)) { throw new RuntimeException("Forced Failure"); } System.out.println("BadMapper:" + s); return s; } }); Flowable<String> observable = w.onErrorResumeNext(new Function<Throwable, Flowable<String>>() { @Override public Flowable<String> apply(Throwable t1) { return Flowable.just("twoResume", "threeResume").subscribeOn(Schedulers.computation()); } }); @SuppressWarnings("unchecked") DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); TestSubscriber<String> ts = new TestSubscriber<String>(observer, Long.MAX_VALUE); observable.subscribe(ts); ts.awaitTerminalEvent(); verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onComplete(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("twoResume"); verify(observer, times(1)).onNext("threeResume"); } private static class TestFlowable implements Publisher<String> { final String[] values; Thread t; TestFlowable(Subscription s, String... values) { this.values = values; } @Override public void subscribe(final Subscriber<? super String> observer) { System.out.println("TestFlowable subscribed to ..."); observer.onSubscribe(new BooleanSubscription()); t = new Thread(new Runnable() { @Override public void run() { try { System.out.println("running TestFlowable thread"); for (String s : values) { System.out.println("TestFlowable onNext: " + s); observer.onNext(s); } throw new RuntimeException("Forced Failure"); } catch (Throwable e) { observer.onError(e); } } }); System.out.println("starting TestFlowable thread"); t.start(); System.out.println("done starting TestFlowable thread"); } } @Test public void testBackpressure() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Flowable.range(0, 100000) .onErrorResumeNext(new Function<Throwable, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Throwable t1) { return Flowable.just(1); } }) .observeOn(Schedulers.computation()) .map(new Function<Integer, Integer>() { int c; @Override public Integer apply(Integer t1) { if (c++ <= 1) { // slow try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } return t1; } }) .subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); } @Test public void normalBackpressure() { TestSubscriber<Integer> ts = TestSubscriber.create(0); PublishProcessor<Integer> pp = PublishProcessor.create(); pp.onErrorResumeNext(new Function<Throwable, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Throwable v) { return Flowable.range(3, 2); } }).subscribe(ts); ts.request(2); pp.onNext(1); pp.onNext(2); pp.onError(new TestException("Forced failure")); ts.assertValues(1, 2); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(2); ts.assertValues(1, 2, 3, 4); ts.assertNoErrors(); ts.assertComplete(); } @Test public void badOtherSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override public Object apply(Flowable<Integer> o) throws Exception { return Flowable.error(new IOException()) .onErrorResumeNext(Functions.justFunction(o)); } }, false, 1, 1, 1); } }
package org.nearbyshops.DAORoles; import com.zaxxer.hikari.HikariDataSource; import org.nearbyshops.Globals.GlobalConstants; import org.nearbyshops.Globals.Globals; import org.nearbyshops.ModelAnalytics.ItemAnalytics; import org.nearbyshops.ModelRoles.User; import org.nearbyshops.ModelRoles.UserMarkets; import java.sql.*; public class DAOLoginUsingOTP { private HikariDataSource dataSource = Globals.getDataSource(); public int upsertUserProfile(User userProfile, boolean getRowCount) { Connection connection = null; PreparedStatement statement = null; int idOfInsertedRow = -1; int rowCountItems = -1; String insertItemSubmission = "INSERT INTO " + User.TABLE_NAME + "(" + User.PHONE + "," + User.ROLE + "," + User.PASSWORD + "" + ") values(?,?,?)" + " ON CONFLICT (" + User.PHONE + ")" + " DO UPDATE " + " SET " + User.PASSWORD + " = " + " excluded." + User.PASSWORD + ""; // + EmailVerificationCode.TABLE_NAME try { connection = dataSource.getConnection(); connection.setAutoCommit(false); statement = connection.prepareStatement(insertItemSubmission,PreparedStatement.RETURN_GENERATED_KEYS); int i = 0; statement.setObject(++i,userProfile.getPhone()); statement.setObject(++i, GlobalConstants.ROLE_END_USER_CODE); statement.setObject(++i,userProfile.getPassword()); rowCountItems = statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); if(rs.next()) { idOfInsertedRow = rs.getInt(1); } connection.commit(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); if (connection != null) { try { idOfInsertedRow=-1; rowCountItems = 0; connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } try { if(connection!=null) {connection.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(getRowCount) { return rowCountItems; } else { return idOfInsertedRow; } } public int upsertUserProfileNew(User userProfile, boolean getRowCount) { Connection connection = null; PreparedStatement statement = null; int idOfInsertedRow = -1; int rowCountItems = -1; String insertItemSubmission = "INSERT INTO " + User.TABLE_NAME + "(" + User.PHONE + "," + User.E_MAIL + "," + User.ROLE + "," + User.PASSWORD + "" + ") values(?,?,?,?)" + " ON CONFLICT (" + User.PHONE+ "," + User.E_MAIL + ")" + " DO UPDATE " + " SET " + User.PASSWORD + " = " + " excluded." + User.PASSWORD + ""; // + EmailVerificationCode.TABLE_NAME try { connection = dataSource.getConnection(); connection.setAutoCommit(false); statement = connection.prepareStatement(insertItemSubmission,PreparedStatement.RETURN_GENERATED_KEYS); int i = 0; statement.setObject(++i,userProfile.getPhone()); statement.setObject(++i,userProfile.getEmail()); statement.setObject(++i, GlobalConstants.ROLE_END_USER_CODE); statement.setObject(++i,userProfile.getPassword()); rowCountItems = statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); if(rs.next()) { idOfInsertedRow = rs.getInt(1); } connection.commit(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); if (connection != null) { try { idOfInsertedRow=-1; rowCountItems = 0; connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } try { if(connection!=null) {connection.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(getRowCount) { return rowCountItems; } else { return idOfInsertedRow; } } public User checkUserExists(String email, String phone) { boolean isFirst = true; // // String queryPassword = "SELECT " // // + User.USER_ID + "," // + User.USERNAME + "," // + User.ROLE + "" // // + " FROM " + User.TABLE_NAME // + " WHERE " // + " ( " + User.USERNAME + " = ? " // + " OR " + " CAST ( " + User.USER_ID + " AS text ) " + " = ? " // + " OR " + " ( " + User.E_MAIL + " = ?" + ")" // + " OR " + " ( " + User.PHONE + " = ?" + ")" + ")"; String queryPassword = "SELECT " + User.USER_ID + "," + User.USERNAME + "," + User.ROLE + "" + " FROM " + User.TABLE_NAME + " WHERE " + " ( " + " ( " + User.E_MAIL + " = ?" + ")" + " OR " + " ( " + User.PHONE + " = ?" + ")" + ")"; // CAST (" + User.TIMESTAMP_TOKEN_EXPIRES + " AS TIMESTAMP)" Connection connection = null; PreparedStatement statement = null; ResultSet rs = null; //Distributor distributor = null; User user = null; try { // System.out.println(query); connection = dataSource.getConnection(); statement = connection.prepareStatement(queryPassword); int i = 0; // statement.setString(++i,username); // username // statement.setString(++i,username); // userID statement.setString(++i,email); // email statement.setString(++i,phone); // phone // statement.setTimestamp(++i,new Timestamp(System.currentTimeMillis())); rs = statement.executeQuery(); while(rs.next()) { user = new User(); user.setUserID(rs.getInt(User.USER_ID)); user.setUsername(rs.getString(User.USERNAME)); user.setRole(rs.getInt(User.ROLE)); } //System.out.println("Total itemCategories queried " + itemCategoryList.size()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(rs!=null) {rs.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(statement!=null) {statement.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(connection!=null) {connection.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return user; } public int updateUserProfile(User user) { // + User.USERNAME + " = ?" // Gson gson = new Gson(); // System.out.println(gson.toJson(user) + "\nOldPassword : " + oldPassword); String updateStatement = "UPDATE " + User.TABLE_NAME + " SET " + User.PASSWORD + "=?," + User.E_MAIL + "=?," + User.PHONE + "=?," + User.NAME + "=?," + User.GENDER + "=?," + User.IS_ACCOUNT_PRIVATE + "=?," + User.ABOUT + "=?" + " WHERE " + " ( " + " ( " + User.E_MAIL + " = ?" + ")" + " OR " + " ( " + User.PHONE + " = ?" + ")" + ")"; Connection connection = null; PreparedStatement statement = null; int rowCountUpdated = 0; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(updateStatement); int i = 0; // statement.setString(++i,user.getToken()); // statement.setTimestamp(++i,user.getTimestampTokenExpires()); statement.setString(++i,user.getPassword()); statement.setString(++i,user.getEmail()); statement.setString(++i,user.getPhone()); statement.setString(++i,user.getName()); statement.setBoolean(++i,user.getGender()); statement.setBoolean(++i,user.isAccountPrivate()); statement.setString(++i,user.getAbout()); statement.setString(++i,user.getEmail()); statement.setString(++i,user.getPhone()); rowCountUpdated = statement.executeUpdate(); // System.out.println("Profile Updated Using GLobal : Total rows updated: " + rowCountUpdated); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(statement!=null) {statement.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(connection!=null) {connection.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return rowCountUpdated; } public int insertUserProfile(User user, String service_url_of_sds,boolean getRowCount) { Connection connection = null; PreparedStatement statement = null; PreparedStatement statementUserMarkets = null; int idOfInsertedRow = -1; int rowCountItems = -1; String insertUser = "INSERT INTO " + User.TABLE_NAME + "(" + User.ROLE + "," + User.PASSWORD + "," + User.E_MAIL + "," + User.PHONE + "," + User.NAME + "," + User.GENDER + "," + User.IS_ACCOUNT_PRIVATE + "," + User.ABOUT + "" + ") values(?,?, ?,?,?,?, ?,?)"; String insertUserMarkets = "INSERT INTO " + UserMarkets.TABLE_NAME + "(" + UserMarkets.LOCAL_USER_ID + "," + UserMarkets.GLOBAL_USER_ID + "," + UserMarkets.MARKET_AGGREGATOR_URL + "" + ") values(?,?,?)"; try { connection = dataSource.getConnection(); connection.setAutoCommit(false); statement = connection.prepareStatement(insertUser,PreparedStatement.RETURN_GENERATED_KEYS); int i = 0; statement.setObject(++i,GlobalConstants.ROLE_END_USER_CODE); statement.setString(++i,user.getPassword()); statement.setString(++i,user.getEmail()); statement.setString(++i,user.getPhone()); statement.setString(++i,user.getName()); statement.setBoolean(++i,user.getGender()); statement.setBoolean(++i,user.isAccountPrivate()); statement.setString(++i,user.getAbout()); rowCountItems = statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); if(rs.next()) { idOfInsertedRow = rs.getInt(1); } if(rowCountItems==1) { statementUserMarkets = connection.prepareStatement(insertUserMarkets,PreparedStatement.RETURN_GENERATED_KEYS); i = 0; statementUserMarkets.setObject(++i,idOfInsertedRow); statementUserMarkets.setObject(++i,user.getUserID()); statementUserMarkets.setString(++i,service_url_of_sds); // rowCountItems = rowCountItems + statementUserMarkets.executeUpdate(); statementUserMarkets.executeUpdate(); } connection.commit(); System.out.println("Profile Created using Global Profile : Row count : " + rowCountItems); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); if (connection != null) { try { idOfInsertedRow=-1; rowCountItems = 0; connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statementUserMarkets != null) { try { statementUserMarkets.close(); } catch (SQLException e) { e.printStackTrace(); } } try { if(connection!=null) {connection.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(getRowCount) { return rowCountItems; } else { return idOfInsertedRow; } } public User checkUserExistsUsingAssociations(int global_user_id, String url_for_sds) { String queryPassword = "SELECT " + User.USER_ID + "," + User.USERNAME + "," + User.ROLE + "" + " FROM " + User.TABLE_NAME + " INNER JOIN " + UserMarkets.TABLE_NAME + " ON ( " + User.TABLE_NAME + "." + User.USER_ID + " = " + UserMarkets.TABLE_NAME + "." + UserMarkets.LOCAL_USER_ID + " ) " + " WHERE " + " ( " + " ( " + UserMarkets.GLOBAL_USER_ID + " = ?" + ")" + " AND " + " ( " + UserMarkets.MARKET_AGGREGATOR_URL + " = ?" + ")" + ")"; // CAST (" + User.TIMESTAMP_TOKEN_EXPIRES + " AS TIMESTAMP)" Connection connection = null; PreparedStatement statement = null; ResultSet rs = null; //Distributor distributor = null; User user = null; try { // System.out.println(query); connection = dataSource.getConnection(); statement = connection.prepareStatement(queryPassword); int i = 0; statement.setObject(++i,global_user_id); // global user id statement.setString(++i,url_for_sds); // url for sds rs = statement.executeQuery(); while(rs.next()) { user = new User(); user.setUserID(rs.getInt(User.USER_ID)); user.setUsername(rs.getString(User.USERNAME)); user.setRole(rs.getInt(User.ROLE)); } //System.out.println("Total itemCategories queried " + itemCategoryList.size()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(rs!=null) {rs.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(statement!=null) {statement.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(connection!=null) {connection.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return user; } public int updateUserProfileAssociated(User user, String url_for_sds) { // + User.USERNAME + " = ?" // Gson gson = new Gson(); // System.out.println(gson.toJson(user) + "\nOldPassword : " + oldPassword); String updateStatement = "UPDATE " + User.TABLE_NAME + " SET " + User.PASSWORD + "=?," + User.E_MAIL + "=?," + User.PHONE + "=?," + User.NAME + "=?," + User.GENDER + "=?," + User.IS_ACCOUNT_PRIVATE + "=?," + User.ABOUT + "=?" + " FROM " + UserMarkets.TABLE_NAME + " WHERE " + UserMarkets.TABLE_NAME + "." + UserMarkets.LOCAL_USER_ID + " = " + User.TABLE_NAME + "." + User.USER_ID + " AND " + " ( " + " ( " + UserMarkets.TABLE_NAME + "." + UserMarkets.GLOBAL_USER_ID + " = ?" + ")" + " AND " + " ( " + UserMarkets.TABLE_NAME + "." + UserMarkets.MARKET_AGGREGATOR_URL + " = ?" + ")" + ")"; Connection connection = null; PreparedStatement statement = null; int rowCountUpdated = 0; try { connection = dataSource.getConnection(); statement = connection.prepareStatement(updateStatement); int i = 0; // statement.setString(++i,user.getToken()); // statement.setTimestamp(++i,user.getTimestampTokenExpires()); statement.setString(++i,user.getPassword()); statement.setString(++i,user.getEmail()); statement.setString(++i,user.getPhone()); statement.setString(++i,user.getName()); statement.setBoolean(++i,user.getGender()); statement.setBoolean(++i,user.isAccountPrivate()); statement.setString(++i,user.getAbout()); statement.setObject(++i,user.getUserID()); statement.setObject(++i,url_for_sds); rowCountUpdated = statement.executeUpdate(); // System.out.println("Profile Updated Using GLobal : Total rows updated: " + rowCountUpdated); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(statement!=null) {statement.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(connection!=null) {connection.close();} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return rowCountUpdated; } }
/* * * * Copyright 2012-2015 Viant. * * * * 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.sm.replica.server.grizzly; import com.sm.message.Request; import com.sm.replica.ParaList; import com.sm.store.OpType; import com.sm.store.StoreParas; import com.sm.transport.Utils; import com.sm.transport.grizzly.ServerFilter; import com.sm.utils.ThreadPoolFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.glassfish.grizzly.filterchain.FilterChainContext; import org.glassfish.grizzly.filterchain.NextAction; import voldemort.store.cachestore.Key; import voldemort.store.cachestore.StoreException; import voldemort.store.cachestore.Value; import voldemort.store.cachestore.impl.CacheStore; import voldemort.store.cachestore.impl.CacheValue; import voldemort.versioning.ObsoleteVersionException; import java.io.IOException; import java.util.Map; import java.util.concurrent.*; import static com.sm.store.StoreParas.*; public class ReplicaServerFilter extends ServerFilter { private static final Log logger = LogFactory.getLog(ReplicaServerFilter.class); private Map<String, CacheStore> storeMap; protected Utils.ServerState serverState; protected int freq =20; protected int maxThreads; protected int maxQueue ; protected Executor threadPools; public ReplicaServerFilter(){} public ReplicaServerFilter(Map<String, CacheStore> storeMap) { this(storeMap, Runtime.getRuntime().availableProcessors() ); } public ReplicaServerFilter(Map<String, CacheStore> storeMap, int maxThreads) { this.storeMap = storeMap; serverState = Utils.ServerState.Active; this.maxThreads = maxThreads; init(); } protected void init() { if ( Runtime.getRuntime().availableProcessors() > maxThreads ) this.maxThreads = Runtime.getRuntime().availableProcessors(); if ( maxQueue < maxThreads * 1000 ) maxQueue = maxThreads * 1000; BlockingQueue<Runnable> queue= new LinkedBlockingQueue<Runnable>(maxQueue ); threadPools = new ThreadPoolExecutor( maxThreads, maxThreads , 30, TimeUnit.SECONDS , queue, new ThreadPoolFactory("Replica") ); } public void shutdown() { logger.warn("server in shutdown state"); serverState = Utils.ServerState.Shutdown; } public int getFreq() { return freq; } public void setFreq(int freq) { this.freq = freq; } @Override public NextAction handleRead(FilterChainContext ctx) throws IOException { // Peer address is used for non-connected UDP Connection :) final Object peerAddress = ctx.getAddress(); final Request req = ctx.getMessage(); if ( req.getHeader().getVersion() % freq == 0) logger.info("receive "+ req.getHeader().toString()+ " from "+ctx.getAddress().toString()+" payload len " + (req.getPayload() == null ? 0 : req.getPayload().length ) ) ; processParaList( req, ctx, peerAddress); ctx.write(peerAddress, req, null); return ctx.getStopAction(); } protected void setError(ParaList paraList, String message) { for (StoreParas each : paraList.getLists()) { // set for Store Exception each.setErrorCode(2 ); if ( each.getOpType() == OpType.Put ) { each.getValue().setData( message.getBytes()); } } } protected void processParaList(Request req, FilterChainContext ctx, Object peerAddress) { ParaList paraList = null; try { CacheStore store = storeMap.get( req.getHeader().getName() ); if ( store == null ) throw new StoreException("Store "+req.getHeader().getName()+" not exits"); //check request type it must be Normal which was send by Replica Client if ( req.getType() != Request.RequestType.Normal) { logger.error("wrong request type expect Normal but get "+req.getType().toString()); ctx.getConnection().close(); } else { paraList = ParaList.toParaList( req.getPayload() ); if ( store.isShutDown() ) { logger.error("server in shut down state, close channel"); ctx.getConnection().close(); return; } for ( int i=0; i< paraList.getSize() ; i++) { processRequest( store, paraList.getLists().get(i)); } req.setPayload( paraList.toBytes()); } } catch (Exception ex) { logger.error("close channel "+ex.getMessage()+" "+ctx.getConnection().getPeerAddress().toString(), ex); if ( paraList != null ) { setError( paraList, ex.getMessage()); req.setPayload( paraList.toBytes()); } else ctx.getConnection().close(); } } private void processRequest(CacheStore store, StoreParas paras) { try { switch( paras.getOpType() ) { case Get: { Value value = processGet(store, paras.getKey() ); paras.setErrorCode(NO_ERROR ); paras.setValue(value); break; } case Put: { processPut(store, paras.getKey(), paras.getValue() ); paras.setErrorCode( NO_ERROR); paras.setValue(null); break; } case Remove: { boolean rs = processRemove(store, paras.getKey()); paras.setErrorCode( NO_ERROR); paras.setRemove( rs ? (byte) 0 : (byte) 1); break; } default: { logger.warn("unknown type "+paras.getKey().toString()); paras.setErrorCode( STORE_EXCEPTION); checkValue( paras); paras.getValue().setData( "unknown type".getBytes()); } } } catch( ObsoleteVersionException sx) { paras.setErrorCode( OBSOLETE); paras.getValue().setData( sx.getMessage().toString().getBytes()); } catch (Exception ex) { logger.error( ex.getMessage(), ex); paras.setErrorCode( STORE_EXCEPTION); byte[] data ; if ( ex.getMessage() != null ) data = ex.getMessage().getBytes(); else data = new byte[0]; checkValue( paras); paras.getValue().setData(data ); } } // make sure value is not null private void checkValue(StoreParas paras) { if ( paras.getValue() == null ) { paras.setValue(CacheValue.createValue(new byte[0])); } } private Value processGet(CacheStore store, Key key) { return store.get(key); } private void processPut(CacheStore store, Key key, Value value) { store.put(key, value); } private boolean processRemove(CacheStore store, Key key){ return store.remove(key); } }
package com.ocdsoft.bacta.swg.archive.delta.set; import com.ocdsoft.bacta.engine.buffer.ByteBufferWritable; import com.ocdsoft.bacta.engine.utils.BufferUtil; import com.ocdsoft.bacta.swg.archive.delta.AutoDeltaContainer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; public class AutoDeltaStringSet extends AutoDeltaContainer { private transient final List<Command> commands; private final Set<String> set; private transient int baselineCommandCount; public AutoDeltaStringSet() { this.commands = new ArrayList<>(5); this.set = new TreeSet<>(); this.baselineCommandCount = 0; } public Set<String> get() { return set; } public int size() { return set.size(); } public boolean isEmpty() { return set.isEmpty(); } public boolean contains(final String value) { return set.contains(value); } public void clear() { if (!isEmpty()) { final Command command = new Command(Command.CLEAR, null); commands.add(command); ++baselineCommandCount; set.forEach(value -> { erase(value); }); set.clear(); touch(); onChanged(); } } public void erase(final String value) { if (set.contains(value)) { final Command command = new Command(Command.ERASE, value); commands.add(command); ++baselineCommandCount; set.remove(value); touch(); onErase(value); onChanged(); } } public void insert(final String value) { if (set.add(value)) { final Command command = new Command(Command.INSERT, value); commands.add(command); ++baselineCommandCount; touch(); onInsert(value); onChanged(); } } @Override public boolean isDirty() { return commands.size() > 0; } @Override public void clearDelta() { commands.clear(); } @Override public void pack(ByteBuffer buffer) { buffer.putInt(set.size()); buffer.putInt(baselineCommandCount); set.forEach(value -> BufferUtil.put(buffer, value)); } @Override public void packDelta(ByteBuffer buffer) { buffer.putInt(commands.size()); buffer.putInt(baselineCommandCount); for (final Command command : commands) command.writeToBuffer(buffer); clearDelta(); } @Override public void unpackDelta(ByteBuffer buffer) { int skipCount; final int commandCount = buffer.getInt(); final int targetBaselineCommandCount = buffer.getInt(); // if (commandCount+baselineCommandCount) < targetBaselineCommandCount, it // means that we have missed some changes and are behind; when this happens, // catch up by applying all the deltas that came in, and set // baselineCommandCount to targetBaselineCommandCount if ((commandCount + baselineCommandCount) > targetBaselineCommandCount) skipCount = commandCount + baselineCommandCount - targetBaselineCommandCount; else skipCount = 0; if (skipCount > commandCount) skipCount = commandCount; int i; for (i = 0; i < skipCount; ++i) { final byte cmd = buffer.get(); if (cmd != Command.CLEAR) BufferUtil.getAscii(buffer); } for (; i < commandCount; ++i) { final Command command = new Command(buffer); switch (command.cmd) { case Command.ERASE: erase(command.value); break; case Command.INSERT: insert(command.value); break; case Command.CLEAR: clear(); break; } } // if we are behind, catch up if (baselineCommandCount < targetBaselineCommandCount) baselineCommandCount = targetBaselineCommandCount; } @Override public void unpack(ByteBuffer buffer) { set.clear(); clearDelta(); final int commandCount = buffer.getInt(); baselineCommandCount = buffer.getInt(); for (int i = 0; i < commandCount; ++i) { final String value = BufferUtil.getAscii(buffer); set.add(value); } onChanged(); } private void onChanged() { //implement on changed callback } private void onErase(final String value) { //implement on erase callback } private void onInsert(final String value) { //implement on insert callback } public final class Command implements ByteBufferWritable { private static final byte ERASE = 0x00; private static final byte INSERT = 0x01; private static final byte CLEAR = 0x02; public final byte cmd; public final String value; public Command(final byte cmd, final String value) { this.cmd = cmd; this.value = value; } public Command(final ByteBuffer buffer) { cmd = buffer.get(); switch (cmd) { case ERASE: case INSERT: value = BufferUtil.getAscii(buffer); break; case CLEAR: value = null; break; default: value = null; assert false : "Unknown command type."; } } @Override public void writeToBuffer(ByteBuffer buffer) { buffer.put(cmd); switch (cmd) { case ERASE: case INSERT: BufferUtil.put(buffer, value); break; case CLEAR: break; default: assert false : "Unknown command type."; } } } }
package org.apereo.cas.pm.config; import org.apereo.cas.audit.AuditActionResolvers; import org.apereo.cas.audit.AuditPrincipalResolvers; import org.apereo.cas.audit.AuditResourceResolvers; import org.apereo.cas.audit.AuditTrailRecordResolutionPlanConfigurer; import org.apereo.cas.authentication.principal.PrincipalResolver; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.configuration.support.CasFeatureModule; import org.apereo.cas.notifications.CommunicationsManager; import org.apereo.cas.pm.PasswordManagementService; import org.apereo.cas.pm.web.flow.ForgotUsernameCaptchaWebflowConfigurer; import org.apereo.cas.pm.web.flow.ForgotUsernameWebflowConfigurer; import org.apereo.cas.pm.web.flow.actions.SendForgotUsernameInstructionsAction; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.util.spring.beans.BeanCondition; import org.apereo.cas.util.spring.beans.BeanSupplier; import org.apereo.cas.util.spring.boot.ConditionalOnFeature; import org.apereo.cas.web.CaptchaActivationStrategy; import org.apereo.cas.web.CaptchaValidator; import org.apereo.cas.web.DefaultCaptchaActivationStrategy; import org.apereo.cas.web.flow.CasWebflowConfigurer; import org.apereo.cas.web.flow.CasWebflowConstants; import org.apereo.cas.web.flow.CasWebflowExecutionPlanConfigurer; import org.apereo.cas.web.flow.InitializeCaptchaAction; import org.apereo.cas.web.flow.ValidateCaptchaAction; import org.apereo.cas.web.flow.actions.ConsumerExecutionAction; import org.apereo.cas.web.support.WebUtils; import lombok.val; import org.apereo.inspektr.audit.spi.AuditResourceResolver; import org.apereo.inspektr.audit.spi.support.DefaultAuditActionResolver; import org.apereo.inspektr.audit.spi.support.SpringWebflowActionExecutionAuditablePrincipalResolver; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.webflow.definition.registry.FlowDefinitionRegistry; import org.springframework.webflow.engine.builder.support.FlowBuilderServices; import org.springframework.webflow.execution.Action; /** * This is {@link PasswordManagementForgotUsernameConfiguration}. * * @author Misagh Moayyed * @since 6.4.0 */ @Configuration(value = "PasswordManagementForgotUsernameConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) @ConditionalOnFeature(feature = CasFeatureModule.FeatureCatalog.ForgotUsername) public class PasswordManagementForgotUsernameConfiguration { private static final BeanCondition CONDITION = BeanCondition.on("cas.authn.pm.forgot-username.enabled").isTrue().evenIfMissing(); @Configuration(value = "PasswordManagementForgotUsernameAuditConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public static class PasswordManagementForgotUsernameAuditConfiguration { @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) @ConditionalOnMissingBean(name = "forgotUsernameAuditTrailRecordResolutionPlanConfigurer") public AuditTrailRecordResolutionPlanConfigurer forgotUsernameAuditTrailRecordResolutionPlanConfigurer( final ConfigurableApplicationContext applicationContext, @Qualifier("returnValueResourceResolver") final AuditResourceResolver returnValueResourceResolver) { return BeanSupplier.of(AuditTrailRecordResolutionPlanConfigurer.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> plan -> { plan.registerAuditActionResolver(AuditActionResolvers.REQUEST_FORGOT_USERNAME_ACTION_RESOLVER, new DefaultAuditActionResolver()); plan.registerAuditResourceResolver(AuditResourceResolvers.REQUEST_FORGOT_USERNAME_RESOURCE_RESOLVER, returnValueResourceResolver); plan.registerAuditPrincipalResolver(AuditPrincipalResolvers.REQUEST_FORGOT_USERNAME_PRINCIPAL_RESOLVER, new SpringWebflowActionExecutionAuditablePrincipalResolver(SendForgotUsernameInstructionsAction.REQUEST_PARAMETER_EMAIL)); }) .otherwiseProxy() .get(); } } @Configuration(value = "PasswordManagementForgotUsernameWebflowConfiguration", proxyBeanMethods = false) @EnableConfigurationProperties(CasConfigurationProperties.class) public static class PasswordManagementForgotUsernameWebflowConfiguration { @ConditionalOnMissingBean(name = CasWebflowConstants.ACTION_ID_SEND_FORGOT_USERNAME_INSTRUCTIONS_ACTION) @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public Action sendForgotUsernameInstructionsAction( final ConfigurableApplicationContext applicationContext, final CasConfigurationProperties casProperties, @Qualifier(CommunicationsManager.BEAN_NAME) final CommunicationsManager communicationsManager, @Qualifier(PasswordManagementService.DEFAULT_BEAN_NAME) final PasswordManagementService passwordManagementService, @Qualifier(PrincipalResolver.BEAN_NAME_PRINCIPAL_RESOLVER) final PrincipalResolver defaultPrincipalResolver) { return BeanSupplier.of(Action.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> new SendForgotUsernameInstructionsAction(casProperties, communicationsManager, passwordManagementService, defaultPrincipalResolver)) .otherwise(() -> ConsumerExecutionAction.NONE) .get(); } @ConditionalOnMissingBean(name = "forgotUsernameWebflowConfigurer") @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public CasWebflowConfigurer forgotUsernameWebflowConfigurer( final ConfigurableApplicationContext applicationContext, final CasConfigurationProperties casProperties, @Qualifier(CasWebflowConstants.BEAN_NAME_LOGIN_FLOW_DEFINITION_REGISTRY) final FlowDefinitionRegistry loginFlowDefinitionRegistry, @Qualifier(CasWebflowConstants.BEAN_NAME_FLOW_BUILDER_SERVICES) final FlowBuilderServices flowBuilderServices) { return BeanSupplier.of(CasWebflowConfigurer.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> new ForgotUsernameWebflowConfigurer(flowBuilderServices, loginFlowDefinitionRegistry, applicationContext, casProperties)) .otherwiseProxy() .get(); } @Bean @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) @ConditionalOnMissingBean(name = "forgotUsernameCasWebflowExecutionPlanConfigurer") public CasWebflowExecutionPlanConfigurer forgotUsernameCasWebflowExecutionPlanConfigurer( final ConfigurableApplicationContext applicationContext, @Qualifier("forgotUsernameWebflowConfigurer") final CasWebflowConfigurer forgotUsernameWebflowConfigurer) { return BeanSupplier.of(CasWebflowExecutionPlanConfigurer.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> plan -> plan.registerWebflowConfigurer(forgotUsernameWebflowConfigurer)) .otherwiseProxy() .get(); } } @ConditionalOnFeature(feature = CasFeatureModule.FeatureCatalog.ForgotUsername, module = "captcha") @Configuration(value = "ForgotUsernameCaptchaConfiguration", proxyBeanMethods = false) public static class ForgotUsernameCaptchaConfiguration { private static final BeanCondition CONDITION = BeanCondition.on("cas.authn.pm.forgot-username.google-recaptcha.enabled").isTrue(); @ConditionalOnMissingBean(name = "forgotUsernameCaptchaWebflowConfigurer") @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) @Bean public CasWebflowConfigurer forgotUsernameCaptchaWebflowConfigurer( final ConfigurableApplicationContext applicationContext, final CasConfigurationProperties casProperties, @Qualifier(CasWebflowConstants.BEAN_NAME_LOGIN_FLOW_DEFINITION_REGISTRY) final FlowDefinitionRegistry loginFlowDefinitionRegistry, @Qualifier(CasWebflowConstants.BEAN_NAME_FLOW_BUILDER_SERVICES) final FlowBuilderServices flowBuilderServices) { return BeanSupplier.of(CasWebflowConfigurer.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> { val configurer = new ForgotUsernameCaptchaWebflowConfigurer(flowBuilderServices, loginFlowDefinitionRegistry, applicationContext, casProperties); configurer.setOrder(casProperties.getAuthn().getPm().getWebflow().getOrder() + 2); return configurer; }) .otherwiseProxy() .get(); } @ConditionalOnMissingBean(name = CasWebflowConstants.ACTION_ID_FORGOT_USERNAME_VALIDATE_CAPTCHA) @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) @Bean public Action forgotUsernameValidateCaptchaAction( final ConfigurableApplicationContext applicationContext, final CasConfigurationProperties casProperties, @Qualifier("forgotUsernameCaptchaActivationStrategy") final CaptchaActivationStrategy forgotUsernameCaptchaActivationStrategy) { return BeanSupplier.of(Action.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> { val recaptcha = casProperties.getAuthn().getPm().getForgotUsername().getGoogleRecaptcha(); return new ValidateCaptchaAction(CaptchaValidator.getInstance(recaptcha), forgotUsernameCaptchaActivationStrategy); }) .otherwiseProxy() .get(); } @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) @Bean @ConditionalOnMissingBean(name = CasWebflowConstants.ACTION_ID_FORGOT_USERNAME_INIT_CAPTCHA) public Action forgotUsernameInitializeCaptchaAction( final ConfigurableApplicationContext applicationContext, @Qualifier("forgotUsernameCaptchaActivationStrategy") final CaptchaActivationStrategy forgotUsernameCaptchaActivationStrategy, final CasConfigurationProperties casProperties) { return BeanSupplier.of(Action.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> { val recaptcha = casProperties.getAuthn().getPm().getForgotUsername().getGoogleRecaptcha(); return new InitializeCaptchaAction(forgotUsernameCaptchaActivationStrategy, requestContext -> WebUtils.putRecaptchaForgotUsernameEnabled(requestContext, recaptcha), recaptcha); }) .otherwiseProxy() .get(); } @Bean @ConditionalOnMissingBean(name = "forgotUsernameCaptchaActivationStrategy") @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public CaptchaActivationStrategy forgotUsernameCaptchaActivationStrategy( final ConfigurableApplicationContext applicationContext, @Qualifier(ServicesManager.BEAN_NAME) final ServicesManager servicesManager) { return BeanSupplier.of(CaptchaActivationStrategy.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> new DefaultCaptchaActivationStrategy(servicesManager)) .otherwiseProxy() .get(); } @Bean @ConditionalOnMissingBean(name = "forgotUsernameCaptchaWebflowExecutionPlanConfigurer") @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT) public CasWebflowExecutionPlanConfigurer forgotUsernameCaptchaWebflowExecutionPlanConfigurer( final ConfigurableApplicationContext applicationContext, @Qualifier("forgotUsernameCaptchaWebflowConfigurer") final CasWebflowConfigurer cfg) { return BeanSupplier.of(CasWebflowExecutionPlanConfigurer.class) .when(CONDITION.given(applicationContext.getEnvironment())) .supply(() -> plan -> plan.registerWebflowConfigurer(cfg)) .otherwiseProxy() .get(); } } }
package net.anotheria.moskito.core.util.storage; import net.anotheria.moskito.core.predefined.Constants; import net.anotheria.moskito.core.producers.AbstractStats; import net.anotheria.moskito.core.stats.Interval; import net.anotheria.moskito.core.stats.StatValue; import net.anotheria.moskito.core.stats.TimeUnit; import net.anotheria.moskito.core.stats.impl.StatValueFactory; /** * This class gathers statistics for storages. Storages are map like containers. */ public class StorageStats extends AbstractStats { /** * Number of calls of the get method. */ private StatValue gets; /** * Nnumber of the calls of the get method which returned null. */ private StatValue missedGets; /** * Number of total calls to put. */ private StatValue puts; /** * Number of calls to put which overwrote existing data. */ private StatValue overwritePuts; /** * Number of remove calls. */ private StatValue removes; /** * Number of remove calls which did no effect (no value for this key in the storage). */ private StatValue noopRemoves; /** * Size of the storage. Tricky calculated on each operation, may differ from the real size. */ private StatValue size; /** * Number of calls of the containsKey method. */ private StatValue containsKeyCalls; /** * Number of calls of the containsKey method which returned true. */ private StatValue containsKeyHits; /** * Number of calls of the containsValue method. */ private StatValue containsValueCalls; /** * Number of calls of the containsValue method which returned true. */ private StatValue containsValueHits; /** * Name of this storage. */ private String name; /** * Creates a new storage stats object without a name and with support for default intervals. */ public StorageStats(){ this("unnamed", Constants.getDefaultIntervals()); } /** * Creates a new storage stats object with the given name and with support for default intervals. * @param name */ public StorageStats(String name){ this(name, Constants.getDefaultIntervals()); } /** * Creates a new storage stats object with the given name and intervals. * @param aName name of the storage. * @param selectedIntervals supported intervals. */ public StorageStats(String aName, Interval[] selectedIntervals){ Long longPattern = Long.valueOf(0); name = aName; gets = StatValueFactory.createStatValue(longPattern, "gets", selectedIntervals); missedGets = StatValueFactory.createStatValue(longPattern, "missedGets", selectedIntervals); puts = StatValueFactory.createStatValue(longPattern, "puts", selectedIntervals); overwritePuts = StatValueFactory.createStatValue(longPattern, "overwritePuts", selectedIntervals); removes = StatValueFactory.createStatValue(longPattern, "removes", selectedIntervals); noopRemoves = StatValueFactory.createStatValue(longPattern, "noopRemoves", selectedIntervals); containsKeyCalls = StatValueFactory.createStatValue(longPattern, "containsKeyCalls", selectedIntervals); containsKeyHits = StatValueFactory.createStatValue(longPattern, "containsKeyHits", selectedIntervals); containsValueCalls = StatValueFactory.createStatValue(longPattern, "containsValueCalls", selectedIntervals); containsValueHits = StatValueFactory.createStatValue(longPattern, "containsValueHits", selectedIntervals); size = StatValueFactory.createStatValue(longPattern, "size", selectedIntervals); } public String getName(){ return name; } @Override public String toStatsString(String intervalName, TimeUnit unit) { StringBuilder b = new StringBuilder(); b.append(getName()).append(' '); b.append(" G: ").append(gets.getValueAsLong(intervalName)); b.append(" mG: ").append(missedGets.getValueAsLong(intervalName)); b.append(" mG R: ").append(getMissedGetRatio(intervalName)); b.append(" hG R: ").append(getHitGetRatio(intervalName)); b.append(" P: ").append(puts.getValueAsLong(intervalName)); b.append(" oP: ").append(overwritePuts.getValueAsLong(intervalName)); b.append(" oP R: ").append(getOverwritePutRatio(intervalName)); b.append(" nP R: ").append(getNewPutRatio(intervalName)); b.append(" RM: ").append(removes.getValueAsLong(intervalName)); b.append(" noRM: ").append(noopRemoves.getValueAsLong(intervalName)); b.append(" noRM R: ").append(getNoopRemoveRatio(intervalName)); b.append(" PG R: ").append(getPutGetRatio(intervalName)); b.append(" PRM R: ").append(getPutRemoveRatio(intervalName)); b.append(" SZ: ").append(size.getValueAsLong(intervalName)); b.append(" CKC: ").append(containsKeyCalls.getValueAsLong(intervalName)); b.append(" CKH: ").append(containsKeyHits.getValueAsLong(intervalName)); b.append(" CK HR: ").append(containsKeyHits.getValueAsLong(intervalName)); b.append(" CVC: ").append(containsValueCalls.getValueAsLong(intervalName)); b.append(" CVH: ").append(getContainsKeyHitRatio(intervalName)); b.append(" CV HR: ").append(getContainsValueHitRatio(intervalName)); return b.toString(); } /** * Returns the ratio of remove operation that had no effect. * @param intervalName the name of the interval. * @return noon remove ratio. */ public double getNoopRemoveRatio(String intervalName){ return noopRemoves.getValueAsDouble(intervalName) / removes.getValueAsDouble(intervalName); } /** * Returns the ratio of overwriting puts compared to all puts. * @param intervalName the name of the interval. * @return */ public double getOverwritePutRatio(String intervalName){ return overwritePuts.getValueAsDouble(intervalName) / puts.getValueAsDouble(intervalName); } /** * * @param intervalName the name of the interval. * @return */ public double getNewPutRatio(String intervalName){ long putsAsLong = puts.getValueAsLong(intervalName); return ((double)(putsAsLong - overwritePuts.getValueAsLong(intervalName))) / putsAsLong; } /** * Returns the ratio os gets that got no reply. * @param intervalName the name of the interval. * @return */ public double getMissedGetRatio(String intervalName){ return missedGets.getValueAsDouble(intervalName) / gets.getValueAsDouble(intervalName); } /** * * @param intervalName the name of the interval. * @return */ public double getHitGetRatio(String intervalName){ long getAsLong = gets.getValueAsLong(intervalName); return ((double)(getAsLong - missedGets.getValueAsLong(intervalName)))/getAsLong; } /** * * @param intervalName the name of the interval. * @return */ public double getContainsKeyHitRatio(String intervalName){ return containsKeyHits.getValueAsDouble(intervalName) / containsKeyCalls.getValueAsLong(intervalName); } /** * * @param intervalName the name of the interval. * @return */ public double getContainsValueHitRatio(String intervalName){ return containsValueHits.getValueAsDouble(intervalName) / containsValueCalls.getValueAsLong(intervalName); } /** * * @param intervalName the name of the interval. * @return */ public double getPutGetRatio(String intervalName){ return puts.getValueAsDouble(intervalName) / gets.getValueAsLong(intervalName); } /** * * @param intervalName the name of the interval. * @return */ public double getPutRemoveRatio(String intervalName){ return puts.getValueAsDouble(intervalName) / removes.getValueAsLong(intervalName); } /** * Adds a new get call. */ public void addGet(){ gets.increase(); } /** * Adds a new miss on get (returned null). */ public void addMissedGet(){ missedGets.increase(); } /** * Adds a new put. */ public void addPut(){ puts.increase(); } /** * Adds a new put that has overwritten previous value. */ public void addOverwritePut(){ overwritePuts.increase(); } public void increaseSize(){ size.increase(); } public void decreaseSize(){ size.decrease(); } public void setSize(int aSize){ size.setValueAsInt(aSize); } /** * Adds a new contains key call that was a hit (returned an object). */ public void addContainsKeyHit(){ containsKeyCalls.increase(); containsKeyHits.increase(); } /** * Adds a new contains key call that was a miss (returned null). */ public void addContainsKeyMiss(){ containsKeyCalls.increase(); } public void addContainsValueHit(){ containsValueCalls.increase(); containsValueHits.increase(); } public void addContainsValueMiss(){ containsValueCalls.increase(); } public void addRemove(){ removes.increase(); } public void addNoopRemove(){ noopRemoves.increase(); } public long getContainsKeyCalls(String intervalName) { return containsKeyCalls.getValueAsLong(intervalName); } public long getContainsKeyHits(String intervalName) { return containsKeyHits.getValueAsLong(intervalName); } public long getContainsValueCalls(String intervalName) { return containsValueCalls.getValueAsLong(intervalName); } public long getContainsValueHits(String intervalName) { return containsValueHits.getValueAsLong(intervalName); } public long getGets(String intervalName) { return gets.getValueAsLong(intervalName); } public long getMissedGets(String intervalName) { return missedGets.getValueAsLong(intervalName); } public long getNoopRemoves(String intervalName) { return noopRemoves.getValueAsLong(intervalName); } public long getOverwritePuts(String intervalName) { return overwritePuts.getValueAsLong(intervalName); } public long getPuts(String intervalName) { return puts.getValueAsLong(intervalName); } public long getRemoves(String intervalName) { return removes.getValueAsLong(intervalName); } public long getSize(String intervalName) { return size.getValueAsLong(intervalName); } }
package org.aries; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.enterprise.inject.InjectionException; import com.sun.faces.util.DebugObjectOutputStream; /** * Provides library of common assertion methods. * Throws common {@link RuntimeException} exceptions when assertions fail. */ public class Assert { protected static final double ZERO_TOLERANCE = 0.00; protected static final double SMALL_TOLERANCE = 1e-6d; protected static final double REALLY_SMALL_TOLERANCE = 1e-10d; protected static final double LENGTH_TOLERANCE = 0.0001; public static void isTrue(boolean value) { isTrue(value, "[Assertion failed] - boolean must be true"); } public static void isTrue(boolean value, String message) { if (!value) { throw new AssertionFailure(message); } } public static void isTrue(AtomicBoolean value) { notNull(value); isTrue(value.get()); } public static void isTrue(AtomicBoolean value, String message) { notNull(value, message); isTrue(value.get(), message); } public static void isFalse(boolean value) { isFalse(value, "[Assertion failed] - boolean must be false"); } public static void isFalse(boolean value, String message) { if (value) { throw new AssertionFailure(message); } } public static void isFalse(AtomicBoolean value) { notNull(value); isFalse(value.get()); } public static void isFalse(AtomicBoolean value, String message) { notNull(value, message); isFalse(value.get(), message); } public static void isNull(Object object) { isNull(object, "[Assertion failed] - object must be null"); } public static void isNull(Object object, String message) { if (object != null) { throw new AssertionFailure(message); } } public static void notNull(Object object) { notNull(object, "[Assertion failed] - object must not be null"); } public static void notNull(Object object, String message) { if (object == null) { //Thread.currentThread().dumpStack(); throw new AssertionFailure(message); } } public static void hasLength(String text) { hasLength(text, "[Assertion failed] - string must have length"); } public static void hasLength(String text, String message) { if (text == null || text.length() == 0) { throw new AssertionFailure(message); } } public static void isLength(Object[] array, int length) { notNull(array, "[Assertion failed] - array null"); isTrue(array.length == length, "[Assertion failed] - array length not correct, expected="+length+", actual="+array.length); } public static void isLength(Collection<?> collection, int length) { notNull(collection, "[Assertion failed] - collection null"); isTrue(collection.size() == length, "[Assertion failed] - collection size not correct, expected="+length+", actual="+collection.size()); } //TODO make this count only the non-null items public static void isSize(Object[] array, int length) { notNull(array, "[Assertion failed] - array null"); isTrue(array.length == length, "[Assertion failed] - array length not correct, expected="+length+", actual="+array.length); } //TODO make this count only the non-null items public static void isSize(Collection<?> collection, int size) { notNull(collection, "[Assertion failed] - collection null"); isTrue(collection.size() == size, "[Assertion failed] - collection size not correct, expected="+size+", actual="+collection.size()); } public static void isEmpty(String string) { notNull(string, "[Assertion failed] - string null"); isTrue(string.length() == 0, "[Assertion failed] - string not empty"); } public static void isEmpty(Object[] array) { notNull(array, "[Assertion failed] - array null"); isTrue(array.length == 0, "[Assertion failed] - array not empty"); } public static void isEmpty(Collection<?> collection) { notNull(collection, "[Assertion failed] - collection null"); isTrue(collection.size() == 0, "[Assertion failed] - collection not empty"); } public static void isEmpty(Collection<?> collection, String message) { notNull(collection, "[Assertion failed] - "+message+" collection null"); isTrue(collection.size() == 0, "[Assertion failed] - "+message+" - collection not empty"); } public static void isEmpty(Map<?, ?> map) { notNull(map, "[Assertion failed] - map null"); isTrue(map.size() == 0, "[Assertion failed] - map not empty"); } public static void isEmpty(Map<?, ?> map, String message) { notNull(map, "[Assertion failed] - "+message+" map null"); isTrue(map.size() == 0, "[Assertion failed] - "+message+" - map not empty"); } public static void notEmpty(String string) { notNull(string, "[Assertion failed] - string null"); notEmpty(string, "[Assertion failed] - string empty"); } public static void notEmpty(String string, String message) { notNull(string, message+", string null"); if (string.length() == 0) { throw new AssertionFailure(message); } } public static void notEmpty(Object[] array) { notNull(array, "[Assertion failed] - array null"); notEmpty(array, "[Assertion failed] - array empty"); } public static void notEmpty(Object[] array, String message) { notNull(array, "[Assertion failed] - array null"); if (array.length == 0) { throw new AssertionFailure(message); } } public static void noNullElements(Object[] array) { noNullElements(array, "[Assertion failed] - array must not contain null elements"); } public static void noNullElements(Object[] array, String message) { notNull(array, "Array must not be null"); for (int i = 0; i < array.length; i++) { notNull(array[i], message); } } public static void notEmpty(Collection<?> collection) { notNull(collection, "[Assertion failed] - collection null"); notEmpty(collection, "[Assertion failed] - collection empty"); } public static void notEmpty(Collection<?> collection, String message) { notNull(collection, "[Assertion failed] - collection null"); if (collection.isEmpty()) { throw new AssertionFailure(message); } } public static void notEmpty(Map map) { notNull(map, "[Assertion failed] - map null"); notEmpty(map, "[Assertion failed] - map empty"); } public static void notEmpty(Map map, String message) { notNull(map, "[Assertion failed] - map null"); if (map.isEmpty()) { throw new AssertionFailure(message); } } public static void isInstanceOf(Class clazz, Object object) { isInstanceOf(clazz, object, ""); } public static void isInstanceOf(Class type, Object object, String message) { notNull(type, "[Assertion failed] - type null"); notNull(type, "[Assertion failed] - object null"); if (!type.isInstance(object)) { throw new AssertionFailure(message + "[Assertion failed] - "+ "Object of class ["+object.getClass().getCanonicalName()+"] is not an instance of "+type.getCanonicalName()); } } public static void isAssignable(Class superType, Class subType) { isAssignable(superType, subType, ""); } public static void isAssignable(Class superType, Class subType, String message) { notNull(superType, "[Assertion failed] - super-type null"); notNull(subType, "[Assertion failed] - sub-type null"); if (!superType.isAssignableFrom(subType)) { throw new AssertionFailure(message+subType+" is not assignable to "+superType); } } public static void isSerializable(Object expectedObject) { serializeObject(expectedObject); } public static void isValidEquals(Serializable object) { Serializable serializedObject = serializeObject(object); String message = "[Assertion failed] - object of type "+object.getClass()+" should implement equals() correctly"; isTrue(object.equals(serializedObject), message); } private static Serializable serializeObject(Object expectedObject) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(expectedObject); objectOutputStream.close(); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); Serializable serializedObject = (Serializable) objectInputStream.readObject(); return serializedObject; } catch (Exception e) { String message = "[Assertion failed] - class "+expectedObject.getClass().getName()+" should be serializable: "+e; throw new AssertionFailure(message); } } public static void equals(Object object1, Object object2) { equals(object1, object2, "[Assertion failed] - \""+object1+"\" should equal \""+object2+"\""); } public static void equals(Object object1, Object object2, String message) { notNull(object1); notNull(object2); if (!object1.equals(object2)) { throw new AssertionFailure(message); } } public static void equals(Serializable object1, Serializable object2, String message) { notNull(object1); notNull(object2); isSerializable(object1); isSerializable(object2); if (!object1.equals(object2)) { throw new AssertionFailure(message); } } //TODO make full set of equals() methods for Dates that have different levels of reduced precision public static void equals(Date date1, Date date2, String message) { notNull(date1); notNull(date2); long time1 = date1.getTime() / 1000L; long time2 = date2.getTime() / 1000L; if (time1 != time2) { throw new AssertionFailure("Dates not equal: "+message); } } public static <T> void equals(Collection<T> objectList1, Collection<T> objectList2, String message) { notNull(objectList1); notNull(objectList2); equals(objectList1.size(), objectList2.size(), message); Iterator<T> iterator1 = objectList1.iterator(); Iterator<T> iterator2 = objectList2.iterator(); while (iterator1.hasNext() && iterator1.hasNext()) { T object1 = iterator1.next(); T object2 = iterator2.next(); if (!object1.equals(object2)) { throw new AssertionFailure(message); } } } public static void equals(String expected, String actual, String message) { if (expected == null && actual == null) return; if (expected == null || actual == null) throw new AssertionFailure(message); String newExpected = expected.replace("\r\n", "\n"); String newActual = actual.replace("\r\n", "\n"); if (!newExpected.equals(newActual)) { throw new AssertionFailure(message+": expected=\""+expected+"\", actual=\""+actual+"\""); } } public static void equals(int expected, Number actual, String message) { equals(expected, actual.intValue(), message); } public static void equals(int expected, int actual, String message) { if (expected != actual) { throw new AssertionFailure(message+": expected="+expected+", actual="+actual); } } public static void equals(String message, long expected, long actual) { equals(expected, actual, ZERO_TOLERANCE, message); } public static void equals(String message, short expected, short actual) { equals(expected, actual, ZERO_TOLERANCE, message); } public static void equals(String message, double expected, double actual) { equals(expected, actual, ZERO_TOLERANCE, message); } public static void equals(int[] expected, int[] actual, String message) { equals(message+" arrays not same size", expected.length, actual.length); for (int count = 0; count < expected.length; count++) { equals(message+" item with index "+count+" not equal", expected[count], actual[count]); } } public static void equals(long[] expected, long[] actual, String message) { equals(expected.length, actual.length, message+" arrays not same size"); for (int count = 0; count < expected.length; count++) { equals(expected[count], actual[count], message+" item with index "+count+" not equal"); } } public static void equals(double[] expected, double[] actual, double tolerance, String message) { equals(expected.length, actual.length, message+" arrays not same size"); for (int count = 0; count < expected.length; count++) { equals(expected[count], actual[count],tolerance, message+" item with index "+count+" not equal"); } } public static void equals(short[] expected, short[] actual, String message) { equals(expected.length, actual.length, message+" arrays not same size"); for (int count = 0; count < expected.length; count++) { equals(expected[count], actual[count], message+" item with index "+count+" not equal"); } } public static void equals(Object[] expected, Object[] actual, String message) { equals(expected.length, actual.length, message+" arrays not same size"); for (int count = 0; count < expected.length; count++) { equals(expected[count], actual[count], message+" item with index "+count+" not equal"); } } public static void equals(double d, double e, double tolerance, String message) { } public static void startsWith(String string1, String string2) { String message = "[Assertion failed] string1 does not start with string2:\n"; message += "string1: " + string1 + "\n"; message += "string2: " + string2 + "\n"; startsWith(string1, string2, message); } public static void startsWith(String string1, String string2, String message) { notNull(string1); notNull(string2); if (!string1.startsWith(string2)) { throw new AssertionFailure(message); } } public static boolean isInteger(String value, String message) { notNull(value); try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } public static boolean isDouble(String value, String message) { notNull(value); try { Double.parseDouble(value); return true; } catch (NumberFormatException e) { return false; } } public static void exception(Throwable e, String message) { Assert.isTrue(e.getMessage().contains(message), "Exception message: \""+e.getMessage()+"\", does not contain: \""+message+"\""); } public static void exception(Throwable e, Class<? extends Throwable> classObject) { Assert.equals(e.getClass(), classObject); } public static void exception(Throwable e, Class<? extends Throwable> classObject, String message) { exception(e, classObject); exception(e, message); } /** * Asserts method don't declare primitive parameters. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertNoPrimitiveParameters(final Method method, Class<? extends Annotation> annotation) { for (Class<?> type : method.getParameterTypes()) { if (type.isPrimitive()) { throw new InjectionException("Method " + getAnnotationMessage(annotation) + "can't declare primitive parameters: " + method); } } } /** * Asserts method don't declare primitive parameters. * * @param method to validate */ public static void assertNoPrimitiveParameters(final Method method) { assertNoPrimitiveParameters(method, null); } /** * Asserts field is not of primitive type. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertNotPrimitiveType(final Field field, Class<? extends Annotation> annotation) { if (field.getType().isPrimitive()) { throw new InjectionException("Field " + getAnnotationMessage(annotation) + "can't be of primitive type: " + field); } } /** * Asserts field is not of primitive type. * * @param method to validate */ public static void assertNotPrimitiveType(final Field field) { assertNotPrimitiveType(field, null); } /** * Asserts method have no parameters. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertNoParameters(final Method method, Class<? extends Annotation> annotation) { if (method.getParameterTypes().length != 0) { throw new InjectionException("Method " + getAnnotationMessage(annotation) + "have to have no parameters: " + method); } } /** * Asserts method have no parameters. * * @param method to validate */ public static void assertNoParameters(final Method method) { assertNoParameters(method, null); } /** * Asserts method return void. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertVoidReturnType(final Method method, Class<? extends Annotation> annotation) { if ((!method.getReturnType().equals(Void.class)) && (!method.getReturnType().equals(Void.TYPE))) { throw new InjectionException("Method " + getAnnotationMessage(annotation) + "have to return void: " + method); } } /** * Asserts method return void. * * @param method to validate */ public static void assertVoidReturnType(final Method method) { assertVoidReturnType(method, null); } /** * Asserts field isn't of void type. * * @param field to validate * @param annotation annotation to propagate in exception message */ public static void assertNotVoidType(final Field field, Class<? extends Annotation> annotation) { if ((field.getClass().equals(Void.class)) && (field.getClass().equals(Void.TYPE))) { throw new InjectionException("Field " + getAnnotationMessage(annotation) + "cannot be of void type: " + field); } } /** * Asserts field isn't of void type. * * @param field to validate */ public static void assertNotVoidType(final Field field) { assertNotVoidType(field, null); } /** * Asserts method don't throw checked exceptions. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertNoCheckedExceptionsAreThrown(final Method method, Class<? extends Annotation> annotation) { Class<?>[] declaredExceptions = method.getExceptionTypes(); for (int i = 0; i < declaredExceptions.length; i++) { Class<?> exception = declaredExceptions[i]; if (!exception.isAssignableFrom(RuntimeException.class)) { throw new InjectionException("Method " + getAnnotationMessage(annotation) + "cannot throw checked exceptions: " + method); } } } /** * Asserts method don't throw checked exceptions. * * @param method to validate */ public static void assertNoCheckedExceptionsAreThrown(final Method method) { assertNoCheckedExceptionsAreThrown(method, null); } /** * Asserts method is not static. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertNotStatic(final Method method, Class<? extends Annotation> annotation) { if (Modifier.isStatic(method.getModifiers())) { throw new InjectionException("Method " + getAnnotationMessage(annotation) + "cannot be static: " + method); } } /** * Asserts method is not static. * * @param method to validate */ public static void assertNotStatic(final Method method) { assertNotStatic(method, null); } /** * Asserts field is not static. * * @param field to validate * @param annotation annotation to propagate in exception message */ public static void assertNotStatic(final Field field, Class<? extends Annotation> annotation) { if (Modifier.isStatic(field.getModifiers())) { throw new InjectionException("Field " + getAnnotationMessage(annotation) + "cannot be static: " + field); } } /** * Asserts field is not static. * * @param field to validate */ public static void assertNotStatic(final Field field) { assertNotStatic(field, null); } /** * Asserts field is not final. * * @param field to validate * @param annotation annotation to propagate in exception message */ public static void assertNotFinal(final Field field, Class<? extends Annotation> annotation) { if (Modifier.isFinal(field.getModifiers())) { throw new InjectionException("Field " + getAnnotationMessage(annotation) + "cannot be final: " + field); } } /** * Asserts field is not final. * * @param field to validate */ public static void assertNotFinal(final Field field) { assertNotFinal(field, null); } /** * Asserts method have exactly one parameter. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertOneParameter(final Method method, Class<? extends Annotation> annotation) { if (method.getParameterTypes().length != 1) { throw new InjectionException("Method " + getAnnotationMessage(annotation) + "have to declare exactly one parameter: " + method); } } /** * Asserts method have exactly one parameter. * * @param method to validate */ public static void assertOneParameter(final Method method) { assertOneParameter(method, null); } /** * Asserts valid Java Beans setter method name. * * @param method to validate * @param annotation annotation to propagate in exception message */ public static void assertValidSetterName(final Method method, Class<? extends Annotation> annotation) { final String methodName = method.getName(); final boolean correctMethodNameLength = methodName.length() > 3; final boolean isSetterMethodName = methodName.startsWith("set"); final boolean isUpperCasedPropertyName = correctMethodNameLength ? Character.isUpperCase(methodName.charAt(3)) : false; if (!correctMethodNameLength || !isSetterMethodName || !isUpperCasedPropertyName) { throw new InjectionException("Method " + getAnnotationMessage(annotation) + "doesn't follow Java Beans setter method name: " + method); } } /** * Asserts valid Java Beans setter method name. * * @param method to validate */ public static void assertValidSetterName(final Method method) { assertValidSetterName(method, null); } /** * Asserts only one method is annotated with annotation. * * @param method collection of methods to validate * @param annotation annotation to propagate in exception message */ public static void assertOnlyOneMethod(final Collection<Method> methods, Class<? extends Annotation> annotation) { if (methods.size() > 1) { throw new InjectionException("Only one method " + getAnnotationMessage(annotation) + "can exist"); } } /** * Asserts only one method is annotated with annotation. * * @param method collection of methods to validate */ public static void assertOnlyOneMethod(final Collection<Method> methods) { assertOnlyOneMethod(methods, null); } /** * Constructs annotation message. If annotation class is null it returns empty string. * * @param annotation to construct message for * @return annotation message or empty string */ private static String getAnnotationMessage(Class<? extends Annotation> annotation) { return annotation == null ? "" : "annotated with @" + annotation + " annotation "; } private static void assertSerializability(StringBuilder builder, Object toPrint) { DebugObjectOutputStream doos = null; try { OutputStream base = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(base); doos = new DebugObjectOutputStream(oos); doos.writeObject(toPrint); } catch (IOException ioe) { List pathToBadObject = doos.getStack(); builder.append("Path to non-Serializable Object: \n"); for (Object cur : pathToBadObject) { builder.append(cur.toString()).append("\n"); } } } }
/* * 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.nifi.processors.poi; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.annotation.behavior.WritesAttribute; import org.apache.nifi.annotation.behavior.WritesAttributes; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.flowfile.attributes.CoreAttributes; import org.apache.nifi.processor.AbstractProcessor; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.ProcessorInitializationContext; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.io.InputStreamCallback; import org.apache.nifi.processor.io.OutputStreamCallback; import org.apache.nifi.processor.util.StandardValidators; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; @Tags({"excel", "csv", "poi"}) @CapabilityDescription("Consumes a Microsoft Excel document and converts each worksheet to csv. Each sheet from the incoming Excel " + "document will generate a new Flowfile that will be output from this processor. Each output Flowfile's contents will be formatted as a csv file " + "where the each row from the excel sheet is output as a newline in the csv file. This processor is currently only capable of processing .xlsx " + "(XSSF 2007 OOXML file format) Excel documents and not older .xls (HSSF '97(-2007) file format) documents. This processor also expects well formatted " + "CSV content and will not escape cell's containing invalid content such as newlines or additional commas.") @WritesAttributes({@WritesAttribute(attribute="sheetname", description="The name of the Excel sheet that this particular row of data came from in the Excel document"), @WritesAttribute(attribute="numrows", description="The number of rows in this Excel Sheet"), @WritesAttribute(attribute="sourcefilename", description="The name of the Excel document file that this data originated from"), @WritesAttribute(attribute="convertexceltocsvprocessor.error", description="Error message that was encountered on a per Excel sheet basis. This attribute is" + " only populated if an error was occured while processing the particular sheet. Having the error present at the sheet level will allow for the end" + " user to better understand what syntax errors in their excel doc on a larger scale caused the error.")}) public class ConvertExcelToCSVProcessor extends AbstractProcessor { private static final String CSV_MIME_TYPE = "text/csv"; public static final String SHEET_NAME = "sheetname"; public static final String ROW_NUM = "numrows"; public static final String SOURCE_FILE_NAME = "sourcefilename"; private static final String SAX_CELL_REF = "c"; private static final String SAX_CELL_TYPE = "t"; private static final String SAX_CELL_ADDRESS = "r"; private static final String SAX_CELL_STRING = "s"; private static final String SAX_CELL_CONTENT_REF = "v"; private static final String SAX_ROW_REF = "row"; private static final String SAX_SHEET_NAME_REF = "sheetPr"; private static final String DESIRED_SHEETS_DELIMITER = ","; private static final String UNKNOWN_SHEET_NAME = "UNKNOWN"; private static final String SAX_PARSER = "org.apache.xerces.parsers.SAXParser"; private static final Pattern CELL_ADDRESS_REGEX = Pattern.compile("^([a-zA-Z]+)([\\d]+)$"); public static final PropertyDescriptor DESIRED_SHEETS = new PropertyDescriptor .Builder().name("extract-sheets") .displayName("Sheets to Extract") .description("Comma separated list of Excel document sheet names that should be extracted from the excel document. If this property" + " is left blank then all of the sheets will be extracted from the Excel document. The list of names is case in-sensitive. Any sheets not " + "specified in this value will be ignored.") .required(false) .expressionLanguageSupported(true) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); public static final Relationship ORIGINAL = new Relationship.Builder() .name("original") .description("Original Excel document received by this processor") .build(); public static final Relationship SUCCESS = new Relationship.Builder() .name("success") .description("Excel data converted to csv") .build(); public static final Relationship FAILURE = new Relationship.Builder() .name("failure") .description("Failed to parse the Excel document") .build(); private List<PropertyDescriptor> descriptors; private Set<Relationship> relationships; @Override protected void init(final ProcessorInitializationContext context) { final List<PropertyDescriptor> descriptors = new ArrayList<>(); descriptors.add(DESIRED_SHEETS); this.descriptors = Collections.unmodifiableList(descriptors); final Set<Relationship> relationships = new HashSet<>(); relationships.add(ORIGINAL); relationships.add(SUCCESS); relationships.add(FAILURE); this.relationships = Collections.unmodifiableSet(relationships); } @Override public Set<Relationship> getRelationships() { return this.relationships; } @Override public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { return descriptors; } @Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final FlowFile flowFile = session.get(); if ( flowFile == null ) { return; } try { session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream inputStream) throws IOException { try { String desiredSheetsDelimited = context.getProperty(DESIRED_SHEETS) .evaluateAttributeExpressions().getValue(); OPCPackage pkg = OPCPackage.open(inputStream); XSSFReader r = new XSSFReader(pkg); SharedStringsTable sst = r.getSharedStringsTable(); XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) r.getSheetsData(); if (desiredSheetsDelimited != null) { String[] desiredSheets = StringUtils .split(desiredSheetsDelimited, DESIRED_SHEETS_DELIMITER); if (desiredSheets != null) { while (iter.hasNext()) { InputStream sheet = iter.next(); String sheetName = iter.getSheetName(); for (int i = 0; i < desiredSheets.length; i++) { //If the sheetName is a desired one parse it if (sheetName.equalsIgnoreCase(desiredSheets[i])) { handleExcelSheet(session, flowFile, sst, sheet, sheetName); break; } } } } else { getLogger().debug("Excel document was parsed but no sheets with the specified desired names were found."); } } else { //Get all of the sheets in the document. while (iter.hasNext()) { handleExcelSheet(session, flowFile, sst, iter.next(), iter.getSheetName()); } } } catch (InvalidFormatException ife) { getLogger().error("Only .xlsx Excel 2007 OOXML files are supported", ife); throw new UnsupportedOperationException("Only .xlsx Excel 2007 OOXML files are supported", ife); } catch (OpenXML4JException e) { getLogger().error("Error occurred while processing Excel document metadata", e); } } }); session.transfer(flowFile, ORIGINAL); } catch (RuntimeException ex) { getLogger().error("Failed to process incoming Excel document", ex); FlowFile failedFlowFile = session.putAttribute(flowFile, ConvertExcelToCSVProcessor.class.getName() + ".error", ex.getMessage()); session.transfer(failedFlowFile, FAILURE); } } /** * Handles an individual Excel sheet from the entire Excel document. Each sheet will result in an individual flowfile. * * @param session * The NiFi ProcessSession instance for the current invocation. */ private void handleExcelSheet(ProcessSession session, FlowFile originalParentFF, SharedStringsTable sst, final InputStream sheetInputStream, String sName) throws IOException { FlowFile ff = session.create(); try { XMLReader parser = XMLReaderFactory.createXMLReader( SAX_PARSER ); ExcelSheetRowHandler handler = new ExcelSheetRowHandler(sst); parser.setContentHandler(handler); ff = session.write(ff, new OutputStreamCallback() { @Override public void process(OutputStream out) throws IOException { InputSource sheetSource = new InputSource(sheetInputStream); ExcelSheetRowHandler eh = null; try { eh = (ExcelSheetRowHandler) parser.getContentHandler(); eh.setFlowFileOutputStream(out); parser.setContentHandler(eh); parser.parse(sheetSource); sheetInputStream.close(); } catch (SAXException se) { getLogger().error("Error occurred while processing Excel sheet {}", new Object[]{eh.getSheetName()}, se); } } }); if (handler.getSheetName().equals(UNKNOWN_SHEET_NAME)) { //Used the named parsed from the handler. This logic is only here because IF the handler does find a value that should take precedence. ff = session.putAttribute(ff, SHEET_NAME, sName); } else { ff = session.putAttribute(ff, SHEET_NAME, handler.getSheetName()); sName = handler.getSheetName(); } ff = session.putAttribute(ff, ROW_NUM, new Long(handler.getRowCount()).toString()); if (StringUtils.isNotEmpty(originalParentFF.getAttribute(CoreAttributes.FILENAME.key()))) { ff = session.putAttribute(ff, SOURCE_FILE_NAME, originalParentFF.getAttribute(CoreAttributes.FILENAME.key())); } else { ff = session.putAttribute(ff, SOURCE_FILE_NAME, UNKNOWN_SHEET_NAME); } //Update the CoreAttributes.FILENAME to have the .csv extension now. Also update MIME.TYPE ff = session.putAttribute(ff, CoreAttributes.FILENAME.key(), updateFilenameToCSVExtension(ff.getAttribute(CoreAttributes.UUID.key()), ff.getAttribute(CoreAttributes.FILENAME.key()), sName)); ff = session.putAttribute(ff, CoreAttributes.MIME_TYPE.key(), CSV_MIME_TYPE); session.transfer(ff, SUCCESS); } catch (SAXException saxE) { getLogger().error("Failed to create instance of SAXParser {}", new Object[]{SAX_PARSER}, saxE); ff = session.putAttribute(ff, ConvertExcelToCSVProcessor.class.getName() + ".error", saxE.getMessage()); session.transfer(ff, FAILURE); } finally { sheetInputStream.close(); } } static Integer columnToIndex(String col) { int length = col.length(); int accumulator = 0; for (int i = length; i > 0; i--) { char c = col.charAt(i - 1); int x = ((int) c) - 64; accumulator += x * Math.pow(26, length - i); } // Make it to start with 0. return accumulator - 1; } private static class CellAddress { final int row; final int col; private CellAddress(int row, int col) { this.row = row; this.col = col; } } /** * Extracts every row from an Excel Sheet and generates a corresponding JSONObject whose key is the Excel CellAddress and value * is the content of that CellAddress converted to a String */ private class ExcelSheetRowHandler extends DefaultHandler { private SharedStringsTable sst; private String currentContent; private boolean nextIsString; private CellAddress firstCellAddress; private CellAddress firstRowLastCellAddress; private CellAddress previousCellAddress; private CellAddress nextCellAddress; private OutputStream outputStream; private boolean firstColInRow; long rowCount; String sheetName; private ExcelSheetRowHandler(SharedStringsTable sst) { this.sst = sst; this.firstColInRow = true; this.rowCount = 0l; this.sheetName = UNKNOWN_SHEET_NAME; } public void setFlowFileOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if (name.equals(SAX_CELL_REF)) { String cellType = attributes.getValue(SAX_CELL_TYPE); // Analyze cell address. Matcher cellAddressMatcher = CELL_ADDRESS_REGEX.matcher(attributes.getValue(SAX_CELL_ADDRESS)); if (cellAddressMatcher.matches()) { String col = cellAddressMatcher.group(1); String row = cellAddressMatcher.group(2); nextCellAddress = new CellAddress(Integer.parseInt(row), columnToIndex(col)); if (firstCellAddress == null) { firstCellAddress = nextCellAddress; } } if (cellType != null && cellType.equals(SAX_CELL_STRING)) { nextIsString = true; } else { nextIsString = false; } } else if (name.equals(SAX_ROW_REF)) { if (firstRowLastCellAddress == null) { firstRowLastCellAddress = previousCellAddress; } firstColInRow = true; previousCellAddress = null; nextCellAddress = null; } else if (name.equals(SAX_SHEET_NAME_REF)) { sheetName = attributes.getValue(0); } currentContent = ""; } private void fillEmptyColumns(int nextColumn) throws IOException { final CellAddress previousCell = previousCellAddress != null ? previousCellAddress : firstCellAddress; if (previousCell != null) { for (int i = 0; i < (nextColumn - previousCell.col); i++) { // Fill columns. outputStream.write(",".getBytes()); } } } public void endElement(String uri, String localName, String name) throws SAXException { if (nextIsString) { int idx = Integer.parseInt(currentContent); currentContent = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); nextIsString = false; } if (name.equals(SAX_CELL_CONTENT_REF) // Limit scanning from the first column, and up to the last column. && (firstCellAddress == null || firstCellAddress.col <= nextCellAddress.col) && (firstRowLastCellAddress == null || nextCellAddress.col <= firstRowLastCellAddress.col)) { try { // A cell is found. fillEmptyColumns(nextCellAddress.col); firstColInRow = false; outputStream.write(currentContent.getBytes()); // Keep previously found cell address. previousCellAddress = nextCellAddress; } catch (IOException e) { getLogger().error("IO error encountered while writing content of parsed cell " + "value from sheet {}", new Object[]{getSheetName()}, e); } } if (name.equals(SAX_ROW_REF)) { //If this is the first row and the end of the row element has been encountered then that means no columns were present. if (!firstColInRow) { try { if (firstRowLastCellAddress != null) { fillEmptyColumns(firstRowLastCellAddress.col); } rowCount++; outputStream.write("\n".getBytes()); } catch (IOException e) { getLogger().error("IO error encountered while writing new line indicator", e); } } } } public void characters(char[] ch, int start, int length) throws SAXException { currentContent += new String(ch, start, length); } public long getRowCount() { return rowCount; } public String getSheetName() { return sheetName; } } /** * Takes the original input filename and updates it by removing the file extension and replacing it with * the .csv extension. * * @param origFileName * Original filename from the input file. * * @return * The new filename with the .csv extension that should be place in the output flowfile's attributes */ private String updateFilenameToCSVExtension(String nifiUUID, String origFileName, String sheetName) { StringBuilder stringBuilder = new StringBuilder(); if (StringUtils.isNotEmpty(origFileName)) { String ext = FilenameUtils.getExtension(origFileName); if (StringUtils.isNotEmpty(ext)) { stringBuilder.append(StringUtils.replace(origFileName, ("." + ext), "")); } else { stringBuilder.append(origFileName); } } else { stringBuilder.append(nifiUUID); } stringBuilder.append("_"); stringBuilder.append(sheetName); stringBuilder.append("."); stringBuilder.append("csv"); return stringBuilder.toString(); } }
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.externalSystem.service.task.ui; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings; import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo; import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; import com.intellij.openapi.project.Project; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Alarm; import com.intellij.util.Producer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.ui.tree.TreeModelAdapter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.TreePath; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.*; /** * @author Denis Zhdanov */ public class ExternalSystemTasksTree extends Tree implements Producer<ExternalTaskExecutionInfo> { private static final int COLLAPSE_STATE_PROCESSING_DELAY_MILLIS = 200; @NotNull private static final Comparator<TreePath> PATH_COMPARATOR = (o1, o2) -> o2.getPathCount() - o1.getPathCount(); @NotNull private final Alarm myCollapseStateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); /** Holds list of paths which 'expand/collapse' state should be restored. */ @NotNull private final Set<TreePath> myPathsToProcessCollapseState = ContainerUtilRt.newHashSet(); @NotNull private final Map<String/*tree path*/, Boolean/*expanded*/> myExpandedStateHolder; private boolean mySuppressCollapseTracking; public ExternalSystemTasksTree(@NotNull ExternalSystemTasksTreeModel model, @NotNull Map<String/*tree path*/, Boolean/*expanded*/> expandedStateHolder, @NotNull final Project project, @NotNull final ProjectSystemId externalSystemId) { super(model); myExpandedStateHolder = expandedStateHolder; setRootVisible(false); addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillExpand(TreeExpansionEvent event) { if (!mySuppressCollapseTracking) { myExpandedStateHolder.put(getPath(event.getPath()), true); } } @Override public void treeWillCollapse(TreeExpansionEvent event) { if (!mySuppressCollapseTracking) { myExpandedStateHolder.put(getPath(event.getPath()), false); } } }); model.addTreeModelListener(new TreeModelAdapter() { @Override public void treeStructureChanged(TreeModelEvent e) { scheduleCollapseStateAppliance(e.getTreePath()); } @Override public void treeNodesInserted(TreeModelEvent e) { scheduleCollapseStateAppliance(e.getTreePath()); } }); new TreeSpeedSearch(this); getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); getActionMap().put("Enter", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ExternalTaskExecutionInfo task = produce(); if (task == null) { return; } ExternalSystemUtil.runTask(task.getSettings(), task.getExecutorId(), project, externalSystemId); } }); } /** * Schedules 'collapse/expand' state restoring for the given path. We can't do that immediately from the tree model listener * as there is a possible case that other listeners have not been notified about the model state change, hence, attempt to define * 'collapse/expand' state may bring us to the inconsistent state. * * @param path target path */ private void scheduleCollapseStateAppliance(@NotNull TreePath path) { myPathsToProcessCollapseState.add(path); myCollapseStateAlarm.cancelAllRequests(); myCollapseStateAlarm.addRequest(() -> { // We assume that the paths collection is modified only from the EDT, so, ConcurrentModificationException doesn't have // a chance. // Another thing is that we sort the paths in order to process the longest first. That is related to the JTree specifics // that it automatically expands parent paths on child path expansion. List<TreePath> paths = ContainerUtilRt.newArrayList(myPathsToProcessCollapseState); myPathsToProcessCollapseState.clear(); Collections.sort(paths, PATH_COMPARATOR); for (TreePath treePath : paths) { applyCollapseState(treePath); } final TreePath rootPath = new TreePath(getModel().getRoot()); if (isCollapsed(rootPath)) { expandPath(rootPath); } }, COLLAPSE_STATE_PROCESSING_DELAY_MILLIS); } /** * Applies stored 'collapse/expand' state to the node located at the given path. * * @param path target path */ private void applyCollapseState(@NotNull TreePath path) { final String key = getPath(path); final Boolean expanded = myExpandedStateHolder.get(key); if (expanded == null) { return; } boolean s = mySuppressCollapseTracking; mySuppressCollapseTracking = true; try { if (expanded) { expandPath(path); } else { collapsePath(path); } } finally { mySuppressCollapseTracking = s; } } @NotNull private static String getPath(@NotNull TreePath path) { StringBuilder buffer = new StringBuilder(); for (TreePath current = path; current != null; current = current.getParentPath()) { buffer.append(current.getLastPathComponent().toString()).append('/'); } buffer.setLength(buffer.length() - 1); return buffer.toString(); } @Nullable @Override public ExternalTaskExecutionInfo produce() { TreePath[] selectionPaths = getSelectionPaths(); if (selectionPaths == null || selectionPaths.length == 0) { return null; } Map<String, ExternalTaskExecutionInfo> map = ContainerUtil.newHashMap(); for (TreePath selectionPath : selectionPaths) { Object component = selectionPath.getLastPathComponent(); if (!(component instanceof ExternalSystemNode)) { continue; } Object element = ((ExternalSystemNode)component).getDescriptor().getElement(); if (element instanceof ExternalTaskExecutionInfo) { ExternalTaskExecutionInfo taskExecutionInfo = (ExternalTaskExecutionInfo)element; ExternalSystemTaskExecutionSettings executionSettings = taskExecutionInfo.getSettings(); String key = executionSettings.getExternalSystemIdString() + executionSettings.getExternalProjectPath() + executionSettings.getVmOptions(); ExternalTaskExecutionInfo executionInfo = map.get(key); if(executionInfo == null) { ExternalSystemTaskExecutionSettings taskExecutionSettings = new ExternalSystemTaskExecutionSettings(); taskExecutionSettings.setExternalProjectPath(executionSettings.getExternalProjectPath()); taskExecutionSettings.setExternalSystemIdString(executionSettings.getExternalSystemIdString()); taskExecutionSettings.setVmOptions(executionSettings.getVmOptions()); taskExecutionSettings.setScriptParameters(executionSettings.getScriptParameters()); taskExecutionSettings.setExecutionName(executionSettings.getExecutionName()); executionInfo = new ExternalTaskExecutionInfo(taskExecutionSettings, taskExecutionInfo.getExecutorId()); map.put(key, executionInfo); } executionInfo.getSettings().getTaskNames().addAll(executionSettings.getTaskNames()); executionInfo.getSettings().getTaskDescriptions().addAll(executionSettings.getTaskDescriptions()); } } // Disable tasks execution if it comes from different projects if(map.values().size() != 1) return null; return map.values().iterator().next(); } }
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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.jasig.portal.groups.pags; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.portal.EntityIdentifier; import org.jasig.portal.EntityTypes; import org.jasig.portal.groups.EntityImpl; import org.jasig.portal.groups.EntityTestingGroupImpl; import org.jasig.portal.groups.GroupsException; import org.jasig.portal.groups.IEntity; import org.jasig.portal.groups.IEntityGroup; import org.jasig.portal.groups.IEntityGroupStore; import org.jasig.portal.groups.IEntitySearcher; import org.jasig.portal.groups.IEntityStore; import org.jasig.portal.groups.IGroupMember; import org.jasig.portal.groups.ILockableEntityGroup; import org.jasig.portal.security.IPerson; import org.jasig.portal.security.PersonFactory; import org.jasig.portal.security.provider.RestrictedPerson; import org.jasig.portal.spring.locator.PersonAttributeDaoLocator; import org.jasig.services.persondir.IPersonAttributeDao; import org.jasig.services.persondir.IPersonAttributes; /** * The Person Attributes Group Store uses attributes stored in the IPerson object to determine * group membership. It can use attributes from any data source supported by the PersonDirectory * service. * * @author Al Wold * @version $Revision$ */ public class PersonAttributesGroupStore implements IEntityGroupStore, IEntityStore, IEntitySearcher { private static final Log log = LogFactory.getLog(PersonAttributesGroupStore.class); private static final Class<IPerson> IPERSON_CLASS = IPerson.class; private static final EntityIdentifier[] EMPTY_SEARCH_RESULTS = new EntityIdentifier[0]; private Properties props; private Map groupDefinitions; private Map<String, IEntityGroup> groups; private Map<String, List> containingGroups; public PersonAttributesGroupStore() { groups = new HashMap<String, IEntityGroup>(); containingGroups = new HashMap<String, List>(); try { props = new Properties(); props.load(PersonAttributesGroupStore.class.getResourceAsStream("/properties/groups/pags.properties")); IPersonAttributesConfiguration config = getConfig(props.getProperty("org.jasig.portal.groups.pags.PersonAttributesGroupStore.configurationClass")); groupDefinitions = config.getConfig(); initGroups(); } catch ( Exception e ) { throw new RuntimeException("Problem initializing groups", e); } } private IPersonAttributesConfiguration getConfig(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class configClass = Class.forName(className); Object o = configClass.newInstance(); return (IPersonAttributesConfiguration)o; } /** * Iterates over the groupDefinitions Collection and creates the * corresponding groups. Then, caches parents for each child group. */ private void initGroups() throws GroupsException { Iterator<IEntityGroup> i = null; Collection<IEntityGroup> groupDefs = groupDefinitions.values(); for ( i=groupDefs.iterator(); i.hasNext(); ) { GroupDefinition groupDef = (GroupDefinition) i.next(); IEntityGroup group = new EntityTestingGroupImpl(groupDef.getKey(), IPERSON_CLASS); group.setName(groupDef.getName()); group.setDescription(groupDef.getDescription()); cachePut(group); } cacheContainingGroupsForGroups(); } private IPersonTester initializeTester(String tester, String attribute, String value) { try { Class testerClass = Class.forName(tester); Constructor c = testerClass.getConstructor(new Class[]{String.class, String.class}); Object o = c.newInstance(new Object[]{attribute, value}); return (IPersonTester)o; } catch (Exception e) { e.printStackTrace(); return null; } } private IEntityGroup cacheGet(String key) { return groups.get(key); } private void cachePut(IEntityGroup group) { groups.put(group.getLocalKey(), group); } public boolean contains(IEntityGroup group, IGroupMember member) throws GroupsException { GroupDefinition groupDef = (GroupDefinition)groupDefinitions.get(group.getLocalKey()); if (member.isGroup()) { String key = ((IEntityGroup)member).getLocalKey(); return groupDef.hasMember(key); } else { if (member.getEntityType() != IPERSON_CLASS) { return false; } IPerson person = null; try { IPersonAttributeDao pa = PersonAttributeDaoLocator.getPersonAttributeDao(); final IPersonAttributes personAttributes = pa.getPerson(member.getKey()); RestrictedPerson rp = PersonFactory.createRestrictedPerson(); if (personAttributes != null) { rp.setAttributes(personAttributes.getAttributes()); } person = rp; } catch (Exception ex) { log.error("Exception acquiring attributes for member " + member + " while checking if group " + group + " contains this member.", ex); return false; } return testRecursively(groupDef, person, member); } } public void delete(IEntityGroup group) throws GroupsException { throw new UnsupportedOperationException("PersonAttributesGroupStore: Method delete() not supported."); } public IEntityGroup find(String key) throws GroupsException { return groups.get(key); } private void cacheContainingGroupsForGroups() throws GroupsException { Iterator<IEntityGroup> i = null; // Find potential parent groups, those whose GroupDefinitions have members. List<IEntityGroup> parentGroupsList = new ArrayList<IEntityGroup>(); for (i=groupDefinitions.values().iterator(); i.hasNext();) { GroupDefinition groupDef = (GroupDefinition) i.next(); if (! groupDef.members.isEmpty()) { parentGroupsList.add(cacheGet(groupDef.getKey())); } } IEntityGroup[] parentGroupsArray = parentGroupsList.toArray(new IEntityGroup[parentGroupsList.size()]); // Check each group for its parents and cache the references. for (i=groups.values().iterator(); i.hasNext();) { IEntityGroup childGroup = i.next(); parentGroupsList = new ArrayList<IEntityGroup>(5); for (int idx=0; idx<parentGroupsArray.length; idx++) { if ( contains(parentGroupsArray[idx], childGroup) ) { parentGroupsList.add(parentGroupsArray[idx]); } } containingGroups.put(childGroup.getLocalKey(), parentGroupsList); } } private boolean testRecursively(GroupDefinition groupDef, IPerson person, IGroupMember member) throws GroupsException { if ( ! groupDef.contains(person) ) { return false;} else { IEntityGroup group = cacheGet(groupDef.getKey()); IEntityGroup parentGroup = null; Set<IEntityGroup> allParents = primGetAllContainingGroups(group, new HashSet<IEntityGroup>()); boolean testPassed = true; for (Iterator<IEntityGroup> i=allParents.iterator(); i.hasNext() && testPassed;) { parentGroup = i.next(); GroupDefinition parentGroupDef = (GroupDefinition) groupDefinitions.get(parentGroup.getLocalKey()); testPassed = parentGroupDef.test(person); } if (!testPassed && log.isWarnEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("PAGS group=").append(group.getKey()); sb.append(" contained person=").append(member.getKey()); sb.append(", but the person failed to be contained in "); sb.append("ancesters of this group"); sb.append((parentGroup != null ? " (parentGroup="+parentGroup.getKey()+")" : "")); sb.append(". This may indicate a "); sb.append("misconfigured PAGS group "); sb.append("store. Please check PAGSGroupStoreConfig.xml."); log.warn(sb.toString()); } return testPassed; } } private java.util.Set<IEntityGroup> primGetAllContainingGroups(IEntityGroup group, Set<IEntityGroup> s) throws GroupsException { Iterator i = findContainingGroups(group); while ( i.hasNext() ) { IEntityGroup parentGroup = (IEntityGroup) i.next(); s.add(parentGroup); primGetAllContainingGroups(parentGroup, s); } return s; } public Iterator findContainingGroups(IGroupMember member) throws GroupsException { return (member.isEntity()) ? findContainingGroupsForEntity((IEntity)member) : findContainingGroupsForGroup((IEntityGroup)member); } private Iterator findContainingGroupsForGroup(IEntityGroup group) { List parents = containingGroups.get(group.getLocalKey()); return (parents !=null) ? parents.iterator() : Collections.EMPTY_LIST.iterator(); } private Iterator<IEntityGroup> findContainingGroupsForEntity(IEntity member) throws GroupsException { List<IEntityGroup> results = new ArrayList<IEntityGroup>(); for (Iterator<IEntityGroup> i = groups.values().iterator(); i.hasNext(); ) { IEntityGroup group = i.next(); if ( contains(group, member)) { results.add(group); } } return results.iterator(); } public Iterator findEntitiesForGroup(IEntityGroup group) throws GroupsException { return Collections.EMPTY_LIST.iterator(); } public ILockableEntityGroup findLockable(String key) throws GroupsException { throw new UnsupportedOperationException("PersonAttributesGroupStore: Method findLockable() not supported"); } public String[] findMemberGroupKeys(IEntityGroup group) throws GroupsException { List<String> keys = new ArrayList<String>(); GroupDefinition groupDef = (GroupDefinition) groupDefinitions.get(group.getLocalKey()); if (groupDef != null) { for (Iterator<String> i = groupDef.members.iterator(); i.hasNext(); ) { keys.add(i.next()); } } return keys.toArray(new String[]{}); } public Iterator<IEntityGroup> findMemberGroups(IEntityGroup group) throws GroupsException { String[] keys = findMemberGroupKeys(group); List<IEntityGroup> results = new ArrayList<IEntityGroup>(); for (int i = 0; i < keys.length; i++) { IEntityGroup g = cacheGet(keys[i]); if (g == null) { log.warn("Couldn't find a group with key '" + keys[i] + "' referenced by '" + group.getKey() + "'. Please check PAGSGroupStoreConfig.xml"); } results.add(g); } return results.iterator(); } public IEntityGroup newInstance(Class entityType) throws GroupsException { throw new UnsupportedOperationException("PersonAttributesGroupStore: Method newInstance() not supported"); } public EntityIdentifier[] searchForGroups(String query, int method, Class leaftype) throws GroupsException { if ( leaftype != IPERSON_CLASS ) { return EMPTY_SEARCH_RESULTS; } List<EntityIdentifier> results = new ArrayList<EntityIdentifier>(); switch (method) { case IS: for (Iterator<IEntityGroup> i = groups.values().iterator(); i.hasNext(); ) { IEntityGroup g = i.next(); if (g.getName().equalsIgnoreCase(query)) { results.add(g.getEntityIdentifier()); } } break; case STARTS_WITH: for (Iterator<IEntityGroup> i = groups.values().iterator(); i.hasNext(); ) { IEntityGroup g = i.next(); if (g.getName().toUpperCase().startsWith(query.toUpperCase())) { results.add(g.getEntityIdentifier()); } } break; case ENDS_WITH: for (Iterator<IEntityGroup> i = groups.values().iterator(); i.hasNext(); ) { IEntityGroup g = i.next(); if (g.getName().toUpperCase().endsWith(query.toUpperCase())) { results.add(g.getEntityIdentifier()); } } break; case CONTAINS: for (Iterator<IEntityGroup> i = groups.values().iterator(); i.hasNext(); ) { IEntityGroup g = i.next(); if (g.getName().toUpperCase().indexOf(query.toUpperCase()) != -1) { results.add(g.getEntityIdentifier()); } } break; } return results.toArray(new EntityIdentifier[]{}); } public void update(IEntityGroup group) throws GroupsException { throw new UnsupportedOperationException("PersonAttributesGroupStore: Method update() not supported."); } public void updateMembers(IEntityGroup group) throws GroupsException { throw new UnsupportedOperationException("PersonAttributesGroupStore: Method updateMembers() not supported."); } public static class GroupDefinition { private String key; private String name; private String description; private List<String> members; private List<TestGroup> testGroups; public GroupDefinition() { members = new Vector<String>(); testGroups = new Vector<TestGroup>(); } public void setKey(String key) { this.key = key; } public String getKey() { return key; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void addMember(String key) { members.add(key); } public boolean hasMember(String key) { return members.contains(key); } public void addTestGroup(TestGroup testGroup) { testGroups.add(testGroup); } public boolean contains(IPerson person) { return ( testGroups.isEmpty() ) ? false : test(person); } public boolean test(IPerson person) { if (testGroups.isEmpty()) return true; for (Iterator<TestGroup> i = testGroups.iterator(); i.hasNext(); ) { TestGroup testGroup = i.next(); if (testGroup.test(person)) { return true; } } return false; } public String toString() { return "GroupDefinition " + key + " (" + name + ")"; } } public static class TestGroup { private List<IPersonTester> tests; public TestGroup() { tests = new Vector<IPersonTester>(); } public void addTest(IPersonTester test) { tests.add(test); } public boolean test(IPerson person) { for (Iterator<IPersonTester> i = tests.iterator(); i.hasNext(); ) { IPersonTester tester = i.next(); if (!tester.test(person)) { return false; } } return true; } } public IEntity newInstance(String key, Class type) throws GroupsException { if (EntityTypes.getEntityTypeID(type) == null) { throw new GroupsException("Invalid entity type: "+type.getName()); } return new EntityImpl(key, type); } public IEntity newInstance(String key) throws GroupsException { return new EntityImpl(key, null); } public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException { return EMPTY_SEARCH_RESULTS; } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.core.database; import org.pentaho.di.core.Const; import org.pentaho.di.core.row.ValueMetaInterface; /** * Contains Sybase specific information through static final members * * @author Matt * @since 11-mrt-2005 */ public class SybaseDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface { @Override public int[] getAccessTypeList() { return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI }; } @Override public int getDefaultDatabasePort() { if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_NATIVE ) { return 5001; } return -1; } /** * @see org.pentaho.di.core.database.DatabaseInterface#getNotFoundTK(boolean) */ @Override public int getNotFoundTK( boolean use_autoinc ) { if ( supportsAutoInc() && use_autoinc ) { return 1; } return super.getNotFoundTK( use_autoinc ); } @Override public String getDriverClass() { if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_ODBC ) { return "sun.jdbc.odbc.JdbcOdbcDriver"; } else { return "net.sourceforge.jtds.jdbc.Driver"; } } @Override public String getURL( String hostname, String port, String databaseName ) { if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_ODBC ) { return "jdbc:odbc:" + databaseName; } else { // jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]] return "jdbc:jtds:sybase://" + hostname + ":" + port + "/" + databaseName; } } /** * @see org.pentaho.di.core.database.DatabaseInterface#getSchemaTableCombination(java.lang.String, java.lang.String) */ @Override public String getSchemaTableCombination( String schema_name, String table_part ) { return table_part; } /** * @return true if Kettle can create a repository on this type of database. */ @Override public boolean supportsRepository() { return false; } /** * @return true if this database needs a transaction to perform a query (auto-commit turned off). */ @Override public boolean isRequiringTransactionsOnQueries() { return false; } /** * Generates the SQL statement to add a column to the specified table * * @param tablename * The table to add * @param v * The column defined as a value * @param tk * the name of the technical key field * @param use_autoinc * whether or not this field uses auto increment * @param pk * the name of the primary key field * @param semicolon * whether or not to add a semi-colon behind the statement. * @return the SQL statement to add a column to the specified table */ @Override public String getAddColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon ) { return "ALTER TABLE " + tablename + " ADD " + getFieldDefinition( v, tk, pk, use_autoinc, true, false ); } /** * Generates the SQL statement to modify a column in the specified table * * @param tablename * The table to add * @param v * The column defined as a value * @param tk * the name of the technical key field * @param use_autoinc * whether or not this field uses auto increment * @param pk * the name of the primary key field * @param semicolon * whether or not to add a semi-colon behind the statement. * @return the SQL statement to modify a column in the specified table */ @Override public String getModifyColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon ) { return "ALTER TABLE " + tablename + " MODIFY " + getFieldDefinition( v, tk, pk, use_autoinc, true, false ); } @Override public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr ) { String retval = ""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); if ( add_fieldname ) { retval += fieldname + " "; } int type = v.getType(); switch ( type ) { case ValueMetaInterface.TYPE_DATE: retval += "DATETIME NULL"; break; case ValueMetaInterface.TYPE_BOOLEAN: if ( supportsBooleanDataType() ) { retval += "BOOLEAN"; } else { retval += "CHAR(1)"; } break; case ValueMetaInterface.TYPE_NUMBER: case ValueMetaInterface.TYPE_INTEGER: case ValueMetaInterface.TYPE_BIGNUMBER: if ( fieldname.equalsIgnoreCase( tk ) || // Technical key: auto increment field! fieldname.equalsIgnoreCase( pk ) // Primary key ) { if ( use_autoinc ) { retval += "INTEGER IDENTITY NOT NULL"; } else { retval += "INTEGER NOT NULL PRIMARY KEY"; } } else { if ( precision != 0 || ( precision == 0 && length > 9 ) ) { if ( precision > 0 && length > 0 ) { retval += "DECIMAL(" + length + ", " + precision + ") NULL"; } else { retval += "DOUBLE PRECISION NULL"; } } else { // Precision == 0 && length<=9 if ( length < 3 ) { retval += "TINYINT NULL"; } else if ( length < 5 ) { retval += "SMALLINT NULL"; } else { retval += "INTEGER NULL"; } } } break; case ValueMetaInterface.TYPE_STRING: if ( length >= 2048 ) { retval += "TEXT NULL"; } else { retval += "VARCHAR"; if ( length > 0 ) { retval += "(" + length + ")"; } retval += " NULL"; } break; default: retval += " UNKNOWN"; break; } if ( add_cr ) { retval += Const.CR; } return retval; } @Override public String getExtraOptionsHelpText() { return "http://jtds.sourceforge.net/faq.html#urlFormat"; } @Override public String[] getUsedLibraries() { return new String[] { "jtds-1.2.jar" }; } /** * Get the SQL to insert a new empty unknown record in a dimension. * * @param schemaTable * the schema-table name to insert into * @param keyField * The key field * @param versionField * the version field * @return the SQL to insert the unknown record into the SCD. */ @Override public String getSQLInsertAutoIncUnknownDimensionRow( String schemaTable, String keyField, String versionField ) { return "insert into " + schemaTable + "(" + versionField + ") values (1)"; } /** * @param string * @return A string that is properly quoted for use in a SQL statement (insert, update, delete, etc) */ @Override public String quoteSQLString( String string ) { string = string.replaceAll( "'", "''" ); string = string.replaceAll( "\\n", "\\0xd" ); string = string.replaceAll( "\\r", "\\0xa" ); return "'" + string + "'"; } }
package de.fu_berlin.inf.ag_se.browser; import de.fu_berlin.inf.ag_se.browser.exception.JavaScriptException; import de.fu_berlin.inf.ag_se.browser.html.IElement; import de.fu_berlin.inf.ag_se.browser.utils.ImageUtils; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; @SuppressWarnings("restriction") public class BrowserUtils { private static Logger LOGGER = Logger.getLogger(BrowserUtils.class); public static final String ERROR_RETURN_MARKER = BrowserUtils.class .getCanonicalName() + ".error_return"; private static final String TRACK_ATTR_NAME = "data-nebula-track"; private static final String TRACK_ATTR_VALUE = "true"; private static Pattern TAG_NAME_PATTERN = Pattern.compile( "^[^<]*<(\\w+)[^<>]*\\/?>.*", Pattern.DOTALL); /** * Returns the first tag name that could be found in the given HTML code. * * @param html * @return */ public static String getFirstTagName(String html) { if (html == null) { return null; } Matcher matcher = TAG_NAME_PATTERN.matcher(html); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 1) { return null; } return matcher.group(1); } public static boolean fuzzyEquals(String uri1, String uri2) { if (uri1 == null && uri2 == null) { return true; } else if (uri1 == null || uri2 == null) { return false; } else if (uri1.endsWith(uri2) || uri2.endsWith(uri1)) { return true; } return false; } public static IElement extractElement(String html) { if (html == null) { return null; } String tagName = getFirstTagName(html); if (tagName == null) { return null; } // add attribute to make the element easily locatable String trackAttr = " " + TRACK_ATTR_NAME + "=\"" + TRACK_ATTR_VALUE + "\""; if (html.endsWith("/>")) { html = html.substring(0, html.length() - 2) + trackAttr + "/>"; } else { html = html.replaceFirst(">", trackAttr + ">"); } // add missing tags, otherwise JSoup will simply delete those // "mis-placed" tags if (tagName.equals("td")) { html = "<table><tbody><tr>" + html + "</tr></tbody></table>"; } else if (tagName.equals("tr")) { html = "<table><tbody>" + html + "</tbody></table>"; } else if (tagName.equals("tbody")) { html = "<table>" + html + "</table>"; } Document document = Jsoup.parse(html); Element element = document.getElementsByAttributeValue(TRACK_ATTR_NAME, TRACK_ATTR_VALUE).first(); element.removeAttr(TRACK_ATTR_NAME); if (element.attr("href") == null) { element.attr("href", element.attr("data-cke-saved-href")); } return new de.fu_berlin.inf.ag_se.browser.html.Element( element); } private BrowserUtils() { } /** * Creates a random name for a JavaScript function. This is especially handy for callback functions injected by {@link * org.eclipse.swt.browser.BrowserFunction}. * * @return */ public static String createRandomFunctionName() { return "_" + de.fu_berlin.inf.ag_se.browser.utils.StringUtils.createRandomString(32); } /** * Returns a Base64-encoded {@link String} data URI that can be used for the <code>src</code> attribute of an HTML <code>img</code>. * * @param file must point to a readable image file * @return */ public static String createDataUri(File file) throws IOException { return createDataUri(ImageIO.read(file)); } /** * Returns a Base64-encoded {@link String} data URI that can be used for the <code>src</code> attribute of an HTML <code>img</code>. * * @param image * @return */ public static String createDataUri(Image image) { return createDataUri(image.getImageData()); } /** * Returns a Base64-encoded {@link String} data URI that can be used for the <code>src</code> attribute of an HTML <code>img</code>. * * @param data * @return */ public static String createDataUri(ImageData data) { return createDataUri(ImageUtils.convertToAWT(data)); } /** * Returns a Base64-encoded {@link String} data URI that can be used for the <code>src</code> attribute of an HTML <code>img</code>. * * @param image * @return */ public static String createDataUri(BufferedImage image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); } catch (IOException e) { throw new RuntimeException(e); } String encodedImage = DatatypeConverter.printBase64Binary(baos.toByteArray()); return "data:image/png;base64," + encodedImage; } /** * Checks a the return value of {@link org.eclipse.swt.browser.Browser#evaluate(String)} for a caught exception. If an exception was * found, an appropriate JavaScriptException is thrown. <p> This feature only works if the evaluated script was returned by {@link * JavascriptString#getExceptionReturningScript}. * * @param script * @param returnValue * @throws JavaScriptException */ public static void rethrowJavascriptException(final String script, Object returnValue) throws JavaScriptException { // exception handling if (returnValue instanceof Object[]) { Object[] rt = (Object[]) returnValue; if (rt.length == 5 && rt[0] != null && rt[0].equals(ERROR_RETURN_MARKER)) { throw new JavaScriptException(script, (String) rt[1], rt[2] != null ? Math.round((Double) rt[2]) : null, rt[3] != null ? Math.round((Double) rt[3]) : null, (String) rt[4]); } } } public static URI createBlankHTMLFile() { File empty = null; try { empty = File.createTempFile("blank", ".html"); FileUtils.writeStringToFile(empty, "<!DOCTYPE html><html><head></head><body></body></html>", "UTF-8"); } catch (IOException e) { LOGGER.error("Error creating blank.html in temp folder.", e); } return empty.toURI(); } }
/* * Copyright 2012 Lars Werkman * * 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 colorpicker; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import sekagra.android.binaryclock.R; public class SaturationBar extends View { /* * Constants used to save/restore the instance state. */ private static final String STATE_PARENT = "parent"; private static final String STATE_COLOR = "color"; private static final String STATE_SATURATION = "saturation"; /** * The thickness of the bar. */ private int mBarThickness; /** * The length of the bar. */ private int mBarLength; private int mPreferredBarLength; /** * The radius of the pointer. */ private int mBarPointerRadius; /** * The radius of the halo of the pointer. */ private int mBarPointerHaloRadius; /** * The position of the pointer on the bar. */ private int mBarPointerPosition; /** * {@code Paint} instance used to draw the bar. */ private Paint mBarPaint; /** * {@code Paint} instance used to draw the pointer. */ private Paint mBarPointerPaint; /** * {@code Paint} instance used to draw the halo of the pointer. */ private Paint mBarPointerHaloPaint; /** * The rectangle enclosing the bar. */ private RectF mBarRect = new RectF(); /** * {@code Shader} instance used to fill the shader of the paint. */ private Shader shader; /** * {@code true} if the user clicked on the pointer to start the move mode. <br> * {@code false} once the user stops touching the screen. * * @see #onTouchEvent(android.view.MotionEvent) */ private boolean mIsMovingPointer; /** * The ARGB value of the currently selected color. */ private int mColor; /** * An array of floats that can be build into a {@code Color} <br> * Where we can extract the color from. */ private float[] mHSVColor = new float[3]; /** * Factor used to calculate the position to the Opacity on the bar. */ private float mPosToSatFactor; /** * Factor used to calculate the Opacity to the postion on the bar. */ private float mSatToPosFactor; /** * {@code ColorPicker} instance used to control the ColorPicker. */ private ColorPicker mPicker = null; public SaturationBar(Context context) { super(context); init(null, 0); } public SaturationBar(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public SaturationBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } private void init(AttributeSet attrs, int defStyle) { final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ColorBars, defStyle, 0); final Resources b = getContext().getResources(); mBarThickness = a.getDimensionPixelSize( R.styleable.ColorBars_bar_thickness, b.getDimensionPixelSize(R.dimen.bar_thickness)); mBarLength = a.getDimensionPixelSize(R.styleable.ColorBars_bar_length, b.getDimensionPixelSize(R.dimen.bar_length)); mPreferredBarLength = mBarLength; mBarPointerRadius = a.getDimensionPixelSize( R.styleable.ColorBars_bar_pointer_radius, b.getDimensionPixelSize(R.dimen.bar_pointer_radius)); mBarPointerHaloRadius = a.getDimensionPixelSize( R.styleable.ColorBars_bar_pointer_halo_radius, b.getDimensionPixelSize(R.dimen.bar_pointer_halo_radius)); a.recycle(); mBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBarPaint.setShader(shader); mBarPointerPosition = mBarLength + mBarPointerHaloRadius; mBarPointerHaloPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBarPointerHaloPaint.setColor(Color.BLACK); mBarPointerHaloPaint.setAlpha(0x50); mBarPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBarPointerPaint.setColor(0xff81ff00); mPosToSatFactor = 1 / ((float) mBarLength); mSatToPosFactor = ((float) mBarLength) / 1; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int intrinsicSize = mPreferredBarLength + (mBarPointerHaloRadius * 2); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int width; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else if (widthMode == MeasureSpec.AT_MOST) { width = Math.min(intrinsicSize, widthSize); } else { width = intrinsicSize; } mBarLength = width - (mBarPointerHaloRadius * 2); setMeasuredDimension((mBarLength + (mBarPointerHaloRadius * 2)), (mBarPointerHaloRadius * 2)); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mBarLength = w - (mBarPointerHaloRadius * 2); // Fill the rectangle instance. mBarRect.set(mBarPointerHaloRadius, (mBarPointerHaloRadius - (mBarThickness / 2)), (mBarLength + (mBarPointerHaloRadius)), (mBarPointerHaloRadius + (mBarThickness / 2))); // Update variables that depend of mBarLength. if(!isInEditMode()){ shader = new LinearGradient(mBarPointerHaloRadius, 0, (mBarLength + mBarPointerHaloRadius), mBarThickness, new int[] { Color.WHITE, Color.HSVToColor(0xFF, mHSVColor) }, null, Shader.TileMode.CLAMP); } else { shader = new LinearGradient(mBarPointerHaloRadius, 0, (mBarLength + mBarPointerHaloRadius), mBarThickness, new int[] { Color.WHITE, 0xff81ff00 }, null, Shader.TileMode.CLAMP); Color.colorToHSV(0xff81ff00, mHSVColor); } mBarPaint.setShader(shader); mPosToSatFactor = 1 / ((float) mBarLength); mSatToPosFactor = ((float) mBarLength) / 1; float[] hsvColor = new float[3]; Color.colorToHSV(mColor, hsvColor); if(!isInEditMode()){ mBarPointerPosition = Math.round((mSatToPosFactor * hsvColor[1]) + mBarPointerHaloRadius); } else { mBarPointerPosition = mBarLength + mBarPointerHaloRadius; } } @Override protected void onDraw(Canvas canvas) { // Draw the bar. canvas.drawRect(mBarRect, mBarPaint); // Draw the pointer halo. canvas.drawCircle(mBarPointerPosition, mBarPointerHaloRadius, mBarPointerHaloRadius, mBarPointerHaloPaint); // Draw the pointer. canvas.drawCircle(mBarPointerPosition, mBarPointerHaloRadius, mBarPointerRadius, mBarPointerPaint); }; @Override public boolean onTouchEvent(MotionEvent event) { getParent().requestDisallowInterceptTouchEvent(true); // Convert coordinates to our internal coordinate system float x = event.getX(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mIsMovingPointer = true; // Check whether the user pressed on (or near) the pointer if (x >= (mBarPointerHaloRadius) && x <= (mBarPointerHaloRadius + mBarLength)) { mBarPointerPosition = Math.round(x); calculateColor(Math.round(x)); mBarPointerPaint.setColor(mColor); invalidate(); } break; case MotionEvent.ACTION_MOVE: if (mIsMovingPointer) { // Move the the pointer on the bar. if (x >= mBarPointerHaloRadius && x <= (mBarPointerHaloRadius + mBarLength)) { mBarPointerPosition = Math.round(x); calculateColor(Math.round(x)); mBarPointerPaint.setColor(mColor); if (mPicker != null) { mPicker.setNewCenterColor(mColor); mPicker.changeValueBarColor(mColor); mPicker.changeOpacityBarColor(mColor); } invalidate(); } else if (x < mBarPointerHaloRadius) { mBarPointerPosition = mBarPointerHaloRadius; mColor = Color.WHITE; mBarPointerPaint.setColor(mColor); if (mPicker != null) { mPicker.setNewCenterColor(mColor); mPicker.changeValueBarColor(mColor); mPicker.changeOpacityBarColor(mColor); } invalidate(); } else if (x > (mBarPointerHaloRadius + mBarLength)) { mBarPointerPosition = mBarPointerHaloRadius + mBarLength; mColor = Color.HSVToColor(mHSVColor); mBarPointerPaint.setColor(mColor); if (mPicker != null) { mPicker.setNewCenterColor(mColor); mPicker.changeValueBarColor(mColor); mPicker.changeOpacityBarColor(mColor); } invalidate(); } } break; case MotionEvent.ACTION_UP: mIsMovingPointer = false; break; } return true; } /** * Set the bar color. <br> * <br> * Its discouraged to use this method. * * @param color */ public void setColor(int color) { Color.colorToHSV(color, mHSVColor); shader = new LinearGradient(mBarPointerHaloRadius, 0, (mBarLength + mBarPointerHaloRadius), mBarThickness, new int[] { Color.WHITE, color }, null, Shader.TileMode.CLAMP); mBarPaint.setShader(shader); calculateColor(mBarPointerPosition); mBarPointerPaint.setColor(mColor); if (mPicker != null) { mPicker.setNewCenterColor(mColor); mPicker.changeValueBarColor(mColor); mPicker.changeOpacityBarColor(mColor); } invalidate(); } /** * Set the pointer on the bar. With the opacity value. * * @param saturation * float between 0 > 1 */ public void setSaturation(float saturation) { mBarPointerPosition = Math.round((mSatToPosFactor * saturation)) + mBarPointerHaloRadius; calculateColor(mBarPointerPosition); mBarPointerPaint.setColor(mColor); if (mPicker != null) { mPicker.setNewCenterColor(mColor); mPicker.changeValueBarColor(mColor); mPicker.changeOpacityBarColor(mColor); } invalidate(); } /** * Calculate the color selected by the pointer on the bar. * * @param x * X-Coordinate of the pointer. */ private void calculateColor(int x) { x = x - mBarPointerHaloRadius; if (x < 0) { x = 0; } else if (x > mBarLength) { x = mBarLength; } mColor = Color.HSVToColor(new float[]{mHSVColor[0], (float) ((mPosToSatFactor * x)), 1f}); } /** * Get the currently selected color. * * @return The ARGB value of the currently selected color. */ public int getColor() { return mColor; } /** * Adds a {@code ColorPicker} instance to the bar. <br> * <br> * WARNING: Don't change the color picker. it is done already when the bar * is added to the ColorPicker * * @see ColorPicker#addSVBar(SVBar) * @param picker */ public void setColorPicker(ColorPicker picker) { mPicker = picker; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); Bundle state = new Bundle(); state.putParcelable(STATE_PARENT, superState); state.putFloatArray(STATE_COLOR, mHSVColor); float[] hsvColor = new float[3]; Color.colorToHSV(mColor, hsvColor); state.putFloat(STATE_SATURATION, hsvColor[1]); return state; } @Override protected void onRestoreInstanceState(Parcelable state) { Bundle savedState = (Bundle) state; Parcelable superState = savedState.getParcelable(STATE_PARENT); super.onRestoreInstanceState(superState); setColor(Color.HSVToColor(savedState.getFloatArray(STATE_COLOR))); setSaturation(savedState.getFloat(STATE_SATURATION)); } }
/* * Copyright (c) 2015, salesforce.com, inc. * 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 salesforce.com, inc. nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.dataloader.config; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; /** * A simple replacement for properties that will allow us to maintain order on a proprties object */ public class LinkedProperties extends Properties { private final LinkedHashMap<Object, Object> sorted =new LinkedHashMap<>(); @Override public String getProperty(String key) { Object oval = sorted.get(key); String sval = (oval instanceof String) ? (String)oval : null; return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval; } @Override public synchronized int size() { return sorted.size(); } @Override public synchronized Enumeration<Object> keys() { return new Enumeration<Object>(){ Iterator<Object> iterator = sorted.keySet().iterator(); @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public Object nextElement() { return iterator.next(); } }; } @Override public synchronized Enumeration<Object> elements() { return new Enumeration<Object>(){ Iterator<Object> iterator = sorted.values().iterator(); @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public Object nextElement() { return iterator.next(); } }; } @Override public synchronized boolean isEmpty() { return sorted.isEmpty(); } @Override public synchronized boolean contains(Object value) { return sorted.containsValue(value); } @Override public boolean containsValue(Object value) { return contains(value); } @Override public synchronized boolean containsKey(Object key) { return sorted.containsKey(key); } @Override public synchronized Object get(Object key) { return sorted.get(key); } @Override public synchronized Object put(Object key, Object value) { return sorted.put(key, value); } @Override public synchronized Object remove(Object key) { return sorted.remove(key); } @Override public synchronized void putAll(Map<?, ?> t) { for (Map.Entry<?, ?> e : t.entrySet()) sorted.put(e.getKey(), e.getValue()); } @Override public synchronized void clear() { sorted.clear(); } @Override public synchronized Object clone() { LinkedProperties properties = new LinkedProperties(); properties.putAll(sorted); return properties; } @Override public Set<Object> keySet() { return sorted.keySet(); } @Override public Set<Map.Entry<Object,Object>> entrySet() { return sorted.entrySet(); } @Override public Collection<Object> values() { return sorted.values(); } @Override public synchronized Object getOrDefault(Object key, Object defaultValue) { return sorted.getOrDefault(key, defaultValue); } @Override public synchronized void forEach(BiConsumer<? super Object, ? super Object> action) { sorted.forEach(action); } @Override public synchronized void replaceAll(BiFunction<? super Object, ? super Object, ?> function) { sorted.replaceAll(function); } @Override public synchronized Object putIfAbsent(Object key, Object value) { return sorted.putIfAbsent(key, value); } @Override public synchronized boolean remove(Object key, Object value) { return sorted.remove(key, value); } @Override public synchronized boolean replace(Object key, Object oldValue, Object newValue) { return sorted.replace(key, oldValue, newValue); } @Override public synchronized Object replace(Object key, Object value) { return sorted.replace(key, value); } @Override public synchronized Object computeIfAbsent(Object key, Function<? super Object, ?> mappingFunction) { return sorted.computeIfAbsent(key, mappingFunction); } @Override public synchronized Object computeIfPresent(Object key, BiFunction<? super Object, ? super Object, ?> remappingFunction) { return sorted.computeIfPresent(key, remappingFunction); } @Override public synchronized Object compute(Object key, BiFunction<? super Object, ? super Object, ?> remappingFunction) { return sorted.compute(key, remappingFunction); } @Override public synchronized Object merge(Object key, Object value, BiFunction<? super Object, ? super Object, ?> remappingFunction) { return sorted.merge(key, value, remappingFunction); } }
// Copyright 2017 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.crypto.tink.subtle; import static com.google.crypto.tink.testing.TestUtil.assertExceptionContains; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import com.google.crypto.tink.testing.StreamingTestUtil.ByteBufferChannel; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.ReadableByteChannel; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for RewindableReadableByteChannel */ @RunWith(JUnit4.class) public class RewindableReadableByteChannelTest { @Test public void testOpenClose() throws Exception { ReadableByteChannel baseChannel = new ByteBufferChannel("some data".getBytes(UTF_8)); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); assertTrue(baseChannel.isOpen()); rewindableChannel.close(); assertFalse(rewindableChannel.isOpen()); assertFalse(baseChannel.isOpen()); } @Test public void testSingleRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); assertTrue(baseChannel.isOpen()); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer)); assertArrayEquals(buffer.array(), Arrays.copyOf(inputData, 20)); } @Test public void testReadTwice() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); assertTrue(baseChannel.isOpen()); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer1)); ByteBuffer buffer2 = ByteBuffer.allocate(200); assertEquals(inputData.length - 20, rewindableChannel.read(buffer2)); assertArrayEquals(buffer1.array(), Arrays.copyOf(inputData, 20)); assertArrayEquals( Arrays.copyOf(buffer2.array(), buffer2.position()), Arrays.copyOfRange(inputData, 20, inputData.length)); } @Test public void testReadAfterEof() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(1000); assertEquals(inputData.length, rewindableChannel.read(buffer1)); ByteBuffer buffer2 = ByteBuffer.allocate(10); assertEquals(-1, rewindableChannel.read(buffer2)); assertArrayEquals(Arrays.copyOf(buffer2.array(), buffer2.position()), new byte[]{}); } @Test public void testReadRewindShorterReads() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer)); rewindableChannel.rewind(); ByteBuffer buffer2 = ByteBuffer.allocate(15); assertEquals(15, rewindableChannel.read(buffer2)); ByteBuffer buffer3 = ByteBuffer.allocate(15); assertEquals(15, rewindableChannel.read(buffer3)); assertArrayEquals(buffer2.array(), Arrays.copyOf(inputData, 15)); assertArrayEquals(buffer3.array(), Arrays.copyOfRange(inputData, 15, 30)); } @Test public void testReadRewindLongerRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer)); rewindableChannel.rewind(); ByteBuffer buffer2 = ByteBuffer.allocate(30); assertEquals(30, rewindableChannel.read(buffer2)); assertArrayEquals(buffer2.array(), Arrays.copyOf(inputData, 30)); } @Test public void testReadRewindReadEverything() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer1)); rewindableChannel.rewind(); ByteBuffer buffer2 = ByteBuffer.allocate(300); assertEquals(inputData.length, rewindableChannel.read(buffer2)); assertArrayEquals(Arrays.copyOf(buffer2.array(), buffer2.position()), inputData); } @Test public void testReadTwiceRewindRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); // this will allocate a buffer ByteBuffer buffer1 = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer1)); // this will extend the buffer ByteBuffer buffer2 = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer2)); rewindableChannel.rewind(); ByteBuffer buffer3 = ByteBuffer.allocate(300); assertEquals(inputData.length, rewindableChannel.read(buffer3)); assertArrayEquals(Arrays.copyOf(buffer3.array(), buffer3.position()), inputData); } @Test public void testRewindAfterCloseFails() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); rewindableChannel.close(); IOException expected = assertThrows(IOException.class, rewindableChannel::rewind); assertExceptionContains(expected, "Cannot rewind"); } @Test public void testReadAfterCloseFails() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); rewindableChannel.close(); ByteBuffer buffer = ByteBuffer.allocate(42); assertThrows( ClosedChannelException.class, () -> { int unused = rewindableChannel.read(buffer); }); } @Test public void testReadToEmptyBuffer() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(0); assertEquals(0, rewindableChannel.read(buffer)); } @Test public void testNoData() throws Exception { byte[] inputData = "".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(10); assertEquals(-1, rewindableChannel.read(buffer)); } @Test public void testReadEverything() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(1000); assertEquals(inputData.length, rewindableChannel.read(buffer)); assertArrayEquals(Arrays.copyOf(buffer.array(), buffer.position()), inputData); } @Test public void testReadEverythingInChunks() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData, /*maxChunkSize=*/ 20); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(1000); assertEquals(20, rewindableChannel.read(buffer)); assertEquals(20, rewindableChannel.read(buffer)); assertEquals(inputData.length - 40, rewindableChannel.read(buffer)); assertEquals(-1, rewindableChannel.read(buffer)); assertArrayEquals(Arrays.copyOf(buffer.array(), inputData.length) , inputData); } @Test public void testSmallChunksNoDataEveryOtherRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData, /*maxChunkSize=*/ 10, /*noDataEveryOtherRead=*/ true); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(15); assertEquals(0, rewindableChannel.read(buffer1)); assertEquals(10, rewindableChannel.read(buffer1)); assertEquals(0, rewindableChannel.read(buffer1)); assertEquals(5, rewindableChannel.read(buffer1)); assertArrayEquals(buffer1.array(), Arrays.copyOf(inputData, 15)); } @Test public void testNoDataEveryOtherReadShorterSecondRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData, /*maxChunkSize=*/ 1000, /*noDataEveryOtherRead=*/ true); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(20); assertEquals(0, rewindableChannel.read(buffer1)); assertEquals(20, rewindableChannel.read(buffer1)); rewindableChannel.rewind(); ByteBuffer buffer2 = ByteBuffer.allocate(10); // read a shorter sequence // no read to baseChannel needed, return buffered data. assertEquals(10, rewindableChannel.read(buffer2)); assertArrayEquals(buffer2.array(), Arrays.copyOf(inputData, 10)); } @Test public void testNoDataEveryOtherReadLongerSecondRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData, /*maxChunkSize=*/ 1000, /*noDataEveryOtherRead=*/ true); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(20); assertEquals(0, rewindableChannel.read(buffer1)); assertEquals(20, rewindableChannel.read(buffer1)); rewindableChannel.rewind(); ByteBuffer buffer2 = ByteBuffer.allocate(30); // read a longer sequence // tries to read from baseChannel, but no new data. So only data in buffer is availalbe. assertEquals(20, rewindableChannel.read(buffer2)); // reads remaining bytes from baseChannel assertEquals(10, rewindableChannel.read(buffer2)); assertArrayEquals(buffer2.array(), Arrays.copyOf(inputData, 30)); } @Test public void testSmallChunksNoDataEveryOtherReadLongerSecondRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData, /*maxChunkSize=*/ 10, /*noDataEveryOtherRead=*/ true); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(12); assertEquals(0, rewindableChannel.read(buffer1)); assertEquals(10, rewindableChannel.read(buffer1)); assertEquals(0, rewindableChannel.read(buffer1)); assertEquals(2, rewindableChannel.read(buffer1)); rewindableChannel.rewind(); ByteBuffer buffer2 = ByteBuffer.allocate(30); // read a longer sequence // tries to read from baseChannel, but no new data. So only data in buffer is availalbe. assertEquals(12, rewindableChannel.read(buffer2)); // reads remaining bytes from baseChannel, in chunks assertEquals(10, rewindableChannel.read(buffer2)); assertEquals(0, rewindableChannel.read(buffer2)); assertEquals(8, rewindableChannel.read(buffer2)); assertArrayEquals(buffer2.array(), Arrays.copyOf(inputData, 30)); } @Test public void testNoDataEveryOtherReadEverythingOnSecondRead() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData, /*maxChunkSize=*/ 1000, /*noDataEveryOtherRead=*/ true); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(20); assertEquals(0, rewindableChannel.read(buffer1)); assertEquals(20, rewindableChannel.read(buffer1)); rewindableChannel.rewind(); ByteBuffer buffer2 = ByteBuffer.allocate(inputData.length); // tries to read from baseChannel, but no new data. So only data in buffer is availalbe. assertEquals(20, rewindableChannel.read(buffer2)); // is able to read data from baseCannel assertEquals(inputData.length - 20, rewindableChannel.read(buffer2)); assertArrayEquals(buffer2.array(), inputData); } @Test public void testReadToLimit() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(40); buffer.limit(10); assertEquals(10, rewindableChannel.read(buffer)); buffer.limit(30); assertEquals(20, rewindableChannel.read(buffer)); assertArrayEquals(Arrays.copyOf(buffer.array(), 30), Arrays.copyOf(inputData, 30)); } @Test public void testReadLongInputByteByByte() throws Exception { int size = 400000; byte[] inputData = new byte[size]; for (int i = 0; i < size; i++) { inputData[i] = (byte) (i % 253); } ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer = ByteBuffer.allocate(size); ByteBuffer byteBuffer = ByteBuffer.allocate(1); while (true) { int s = rewindableChannel.read(byteBuffer); byteBuffer.flip(); buffer.put(byteBuffer); if (s == -1) { break; } byteBuffer.clear(); } assertArrayEquals(Arrays.copyOf(buffer.array(), buffer.position()), inputData); } @Test public void testRewindAfterDisableRewindFails() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); rewindableChannel.disableRewinding(); IOException expected = assertThrows(IOException.class, rewindableChannel::rewind); assertExceptionContains(expected, "Cannot rewind"); } @Test public void testDisableRewindingAtBeginning() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); rewindableChannel.disableRewinding(); ByteBuffer buffer = ByteBuffer.allocate(100); assertEquals(inputData.length, rewindableChannel.read(buffer)); assertArrayEquals(Arrays.copyOf(buffer.array(), buffer.position()), inputData); } @Test public void testDisableRewindingBetweenReading() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(10); assertEquals(10, rewindableChannel.read(buffer1)); rewindableChannel.disableRewinding(); ByteBuffer buffer2 = ByteBuffer.allocate(100); assertEquals(inputData.length - 10, rewindableChannel.read(buffer2)); assertArrayEquals( Arrays.copyOf(buffer1.array(), buffer1.position()), Arrays.copyOf(inputData, 10)); assertArrayEquals( Arrays.copyOf(buffer2.array(), buffer2.position()), Arrays.copyOfRange(inputData, 10, inputData.length)); } @Test public void testDisableRewindingAfterRewind() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer1 = ByteBuffer.allocate(10); assertEquals(10, rewindableChannel.read(buffer1)); rewindableChannel.rewind(); rewindableChannel.disableRewinding(); ByteBuffer buffer2 = ByteBuffer.allocate(100); assertEquals(inputData.length, rewindableChannel.read(buffer2)); assertArrayEquals(Arrays.copyOf(buffer2.array(), buffer2.position()), inputData); } @Test public void testDisableRewindingAfterRewindBetweenReading() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); ByteBuffer buffer0 = ByteBuffer.allocate(20); assertEquals(20, rewindableChannel.read(buffer0)); rewindableChannel.rewind(); ByteBuffer buffer1 = ByteBuffer.allocate(10); assertEquals(10, rewindableChannel.read(buffer1)); rewindableChannel.disableRewinding(); ByteBuffer buffer2 = ByteBuffer.allocate(100); assertEquals(inputData.length - 10, rewindableChannel.read(buffer2)); assertArrayEquals( Arrays.copyOf(buffer1.array(), buffer1.position()), Arrays.copyOf(inputData, 10)); assertArrayEquals( Arrays.copyOf(buffer2.array(), buffer2.position()), Arrays.copyOfRange(inputData, 10, inputData.length)); } @Test public void testReadingWhenBaseIsClosedFails() throws Exception { byte[] inputData = "The quick brown fox jumps over the lazy dog.".getBytes(UTF_8); ReadableByteChannel baseChannel = new ByteBufferChannel(inputData); baseChannel.close(); assertFalse(baseChannel.isOpen()); RewindableReadableByteChannel rewindableChannel = new RewindableReadableByteChannel(baseChannel); assertFalse(rewindableChannel.isOpen()); ByteBuffer buffer = ByteBuffer.allocate(42); assertThrows( ClosedChannelException.class, () -> { int unused = rewindableChannel.read(buffer); }); } }
/** * 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.ambari.server.state.cluster; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import junit.framework.Assert; import org.apache.ambari.server.AmbariException; import org.apache.ambari.server.agent.AgentEnv; import org.apache.ambari.server.agent.AgentEnv.Directory; import org.apache.ambari.server.agent.DiskInfo; import org.apache.ambari.server.agent.HostInfo; import org.apache.ambari.server.api.services.AmbariMetaInfo; import org.apache.ambari.server.controller.ClusterResponse; import org.apache.ambari.server.orm.GuiceJpaInitializer; import org.apache.ambari.server.orm.InMemoryDefaultTestModule; import org.apache.ambari.server.orm.dao.HostConfigMappingDAO; import org.apache.ambari.server.orm.entities.*; import org.apache.ambari.server.state.*; import org.apache.ambari.server.state.DesiredConfig.HostOverride; import org.apache.ambari.server.state.fsm.InvalidStateTransitionException; import org.apache.ambari.server.state.host.HostHealthyHeartbeatEvent; import org.apache.ambari.server.state.host.HostRegistrationRequestEvent; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.persist.PersistService; public class ClusterTest { private static final Logger LOG = LoggerFactory.getLogger(ClusterTest.class); private Clusters clusters; private Cluster c1; private Injector injector; private ServiceFactory serviceFactory; private ServiceComponentFactory serviceComponentFactory; private ServiceComponentHostFactory serviceComponentHostFactory; private AmbariMetaInfo metaInfo; private ConfigFactory configFactory; @Before public void setup() throws Exception { injector = Guice.createInjector(new InMemoryDefaultTestModule()); injector.getInstance(GuiceJpaInitializer.class); clusters = injector.getInstance(Clusters.class); serviceFactory = injector.getInstance(ServiceFactory.class); serviceComponentFactory = injector.getInstance( ServiceComponentFactory.class); serviceComponentHostFactory = injector.getInstance( ServiceComponentHostFactory.class); configFactory = injector.getInstance(ConfigFactory.class); metaInfo = injector.getInstance(AmbariMetaInfo.class); metaInfo.init(); clusters.addCluster("c1"); c1 = clusters.getCluster("c1"); Assert.assertEquals("c1", c1.getClusterName()); Assert.assertEquals(1, c1.getClusterId()); clusters.addHost("h1"); Host host = clusters.getHost("h1"); host.setIPv4("ipv4"); host.setIPv6("ipv6"); host.setOsType("centos5"); host.persist(); c1.setDesiredStackVersion(new StackId("HDP-0.1")); clusters.mapHostToCluster("h1", "c1"); } @After public void teardown() { injector.getInstance(PersistService.class).stop(); } @Test public void testAddHost() throws AmbariException { clusters.addHost("h2"); try { clusters.addHost("h2"); fail("Duplicate add should fail"); } catch (AmbariException e) { // Expected } } @Test public void testGetHostState() throws AmbariException { Assert.assertEquals(HostState.INIT, clusters.getHost("h1").getState()); } @Test public void testSetHostState() throws AmbariException { clusters.getHost("h1").setState(HostState.HEARTBEAT_LOST); Assert.assertEquals(HostState.HEARTBEAT_LOST, clusters.getHost("h1").getState()); } @Test public void testHostEvent() throws AmbariException, InvalidStateTransitionException { HostInfo hostInfo = new HostInfo(); hostInfo.setHostName("h1"); hostInfo.setInterfaces("fip_4"); hostInfo.setArchitecture("os_arch"); hostInfo.setOS("os_type"); hostInfo.setMemoryTotal(10); hostInfo.setMemorySize(100); hostInfo.setProcessorCount(10); List<DiskInfo> mounts = new ArrayList<DiskInfo>(); mounts.add(new DiskInfo("/dev/sda", "/mnt/disk1", "5000000", "4000000", "10%", "size", "fstype")); hostInfo.setMounts(mounts); AgentEnv agentEnv = new AgentEnv(); Directory dir1 = new Directory(); dir1.setName("/etc/hadoop"); dir1.setType("not_exist"); Directory dir2 = new Directory(); dir2.setName("/var/log/hadoop"); dir2.setType("not_exist"); agentEnv.setStackFoldersAndFiles(new Directory[] { dir1, dir2 }); AgentVersion agentVersion = new AgentVersion("0.0.x"); long currentTime = 1001; clusters.getHost("h1").handleEvent(new HostRegistrationRequestEvent( "h1", agentVersion, currentTime, hostInfo, agentEnv)); Assert.assertEquals(HostState.WAITING_FOR_HOST_STATUS_UPDATES, clusters.getHost("h1").getState()); clusters.getHost("h1").setState(HostState.HEARTBEAT_LOST); try { clusters.getHost("h1").handleEvent( new HostHealthyHeartbeatEvent("h1", currentTime, null)); fail("Exception should be thrown on invalid event"); } catch (InvalidStateTransitionException e) { // Expected } } @Test public void testBasicClusterSetup() throws AmbariException { String clusterName = "c2"; try { clusters.getCluster(clusterName); fail("Exception expected for invalid cluster"); } catch (Exception e) { // Expected } clusters.addCluster(clusterName); Cluster c2 = clusters.getCluster(clusterName); Assert.assertNotNull(c2); Assert.assertEquals(clusterName, c2.getClusterName()); c2.setClusterName("foo2"); Assert.assertEquals("foo2", c2.getClusterName()); Assert.assertNotNull(c2.getDesiredStackVersion()); Assert.assertEquals("", c2.getDesiredStackVersion().getStackId()); StackId stackVersion = new StackId("HDP-1.0"); c2.setDesiredStackVersion(stackVersion); Assert.assertEquals("HDP-1.0", c2.getDesiredStackVersion().getStackId()); } @Test public void testAddAndGetServices() throws AmbariException { // TODO write unit tests for // public void addService(Service service) throws AmbariException; // public Service getService(String serviceName) throws AmbariException; // public Map<String, Service> getServices(); Service s1 = serviceFactory.createNew(c1, "HDFS"); Service s2 = serviceFactory.createNew(c1, "MAPREDUCE"); c1.addService(s1); c1.addService(s2); s1.persist(); s2.persist(); Service s3 = serviceFactory.createNew(c1, "MAPREDUCE"); try { c1.addService(s3); fail("Expected error on adding dup service"); } catch (Exception e) { // Expected } Service s = c1.getService("HDFS"); Assert.assertNotNull(s); Assert.assertEquals("HDFS", s.getName()); Assert.assertEquals(c1.getClusterId(), s.getClusterId()); try { c1.getService("HBASE"); fail("Expected error for unknown service"); } catch (Exception e) { // Expected } Map<String, Service> services = c1.getServices(); Assert.assertEquals(2, services.size()); Assert.assertTrue(services.containsKey("HDFS")); Assert.assertTrue(services.containsKey("MAPREDUCE")); } @Test public void testGetServiceComponentHosts() throws AmbariException { // TODO write unit tests // public List<ServiceComponentHost> getServiceComponentHosts(String hostname); Service s = serviceFactory.createNew(c1, "HDFS"); c1.addService(s); s.persist(); ServiceComponent sc = serviceComponentFactory.createNew(s, "NAMENODE"); s.addServiceComponent(sc); sc.persist(); ServiceComponentHost sch = serviceComponentHostFactory.createNew(sc, "h1", false); sc.addServiceComponentHost(sch); sch.persist(); List<ServiceComponentHost> scHosts = c1.getServiceComponentHosts("h1"); Assert.assertEquals(1, scHosts.size()); } @Test public void testGetAndSetConfigs() { Config config1 = configFactory.createNew(c1, "global", new HashMap<String, String>() {{ put("a", "b"); }}); config1.setVersionTag("version1"); Config config2 = configFactory.createNew(c1, "global", new HashMap<String, String>() {{ put("x", "y"); }}); config2.setVersionTag("version2"); Config config3 = configFactory.createNew(c1, "core-site", new HashMap<String, String>() {{ put("x", "y"); }}); config3.setVersionTag("version2"); c1.addConfig(config1); c1.addConfig(config2); c1.addConfig(config3); c1.addDesiredConfig("_test", config1); Config res = c1.getDesiredConfigByType("global"); Assert.assertNotNull("Expected non-null config", res); res = c1.getDesiredConfigByType("core-site"); Assert.assertNull("Expected null config", res); c1.addDesiredConfig("_test", config2); res = c1.getDesiredConfigByType("global"); Assert.assertEquals("Expected version tag to be 'version2'", "version2", res.getVersionTag()); } @Test public void testDesiredConfigs() throws Exception { Config config1 = configFactory.createNew(c1, "global", new HashMap<String, String>() {{ put("a", "b"); }}); config1.setVersionTag("version1"); Config config2 = configFactory.createNew(c1, "global", new HashMap<String, String>() {{ put("x", "y"); }}); config2.setVersionTag("version2"); Config config3 = configFactory.createNew(c1, "core-site", new HashMap<String, String>() {{ put("x", "y"); }}); config3.setVersionTag("version2"); c1.addConfig(config1); c1.addConfig(config2); c1.addConfig(config3); try { c1.addDesiredConfig(null, config1); fail("Cannot set a null user with config"); } catch (Exception e) { // test failure } c1.addDesiredConfig("_test1", config1); c1.addDesiredConfig("_test3", config3); Map<String, DesiredConfig> desiredConfigs = c1.getDesiredConfigs(); Assert.assertFalse("Expect desired config not contain 'mapred-site'", desiredConfigs.containsKey("mapred-site")); Assert.assertTrue("Expect desired config contain " + config1.getType(), desiredConfigs.containsKey("global")); Assert.assertTrue("Expect desired config contain " + config3.getType(), desiredConfigs.containsKey("core-site")); Assert.assertEquals("Expect desired config for global should be " + config1.getVersionTag(), config1.getVersionTag(), desiredConfigs.get(config1.getType()).getVersion()); Assert.assertEquals("_test1", desiredConfigs.get(config1.getType()).getUser()); Assert.assertEquals("_test3", desiredConfigs.get(config3.getType()).getUser()); DesiredConfig dc = desiredConfigs.get(config1.getType()); Assert.assertTrue("Expect no host-level overrides", (null == dc.getHostOverrides() || dc.getHostOverrides().size() == 0)); c1.addDesiredConfig("_test2", config2); Assert.assertEquals("_test2", c1.getDesiredConfigs().get(config2.getType()).getUser()); c1.addDesiredConfig("_test1", config1); // setup a host that also has a config override Host host = clusters.getHost("h1"); host.addDesiredConfig(c1.getClusterId(), true, "_test2", config2); desiredConfigs = c1.getDesiredConfigs(); dc = desiredConfigs.get(config1.getType()); Assert.assertNotNull("Expect host-level overrides", dc.getHostOverrides()); Assert.assertEquals("Expect one host-level override", 1, dc.getHostOverrides().size()); } public ClusterEntity createDummyData() { ClusterEntity clusterEntity = new ClusterEntity(); clusterEntity.setClusterName("test_cluster1"); clusterEntity.setClusterInfo("test_cluster_info1"); HostEntity host1 = new HostEntity(); HostEntity host2 = new HostEntity(); HostEntity host3 = new HostEntity(); host1.setHostName("test_host1"); host2.setHostName("test_host2"); host3.setHostName("test_host3"); host1.setIpv4("192.168.0.1"); host2.setIpv4("192.168.0.2"); host3.setIpv4("192.168.0.3"); List<HostEntity> hostEntities = new ArrayList<HostEntity>(); hostEntities.add(host1); hostEntities.add(host2); clusterEntity.setHostEntities(hostEntities); clusterEntity.setClusterConfigEntities(Collections.EMPTY_LIST); //both sides of relation should be set when modifying in runtime host1.setClusterEntities(Arrays.asList(clusterEntity)); host2.setClusterEntities(Arrays.asList(clusterEntity)); HostStateEntity hostStateEntity1 = new HostStateEntity(); hostStateEntity1.setCurrentState(HostState.HEARTBEAT_LOST); hostStateEntity1.setHostEntity(host1); HostStateEntity hostStateEntity2 = new HostStateEntity(); hostStateEntity2.setCurrentState(HostState.HEALTHY); hostStateEntity2.setHostEntity(host2); host1.setHostStateEntity(hostStateEntity1); host2.setHostStateEntity(hostStateEntity2); ClusterServiceEntity clusterServiceEntity = new ClusterServiceEntity(); clusterServiceEntity.setServiceName("HDFS"); clusterServiceEntity.setClusterEntity(clusterEntity); clusterServiceEntity.setServiceComponentDesiredStateEntities( Collections.EMPTY_LIST); clusterServiceEntity.setServiceConfigMappings(Collections.EMPTY_LIST); ServiceDesiredStateEntity stateEntity = mock(ServiceDesiredStateEntity.class); Gson gson = new Gson(); when(stateEntity.getDesiredStackVersion()).thenReturn(gson.toJson(new StackId("HDP-0.1"), StackId.class)); clusterServiceEntity.setServiceDesiredStateEntity(stateEntity); List<ClusterServiceEntity> clusterServiceEntities = new ArrayList<ClusterServiceEntity>(); clusterServiceEntities.add(clusterServiceEntity); clusterEntity.setClusterServiceEntities(clusterServiceEntities); return clusterEntity; } @Test public void testClusterRecovery() throws AmbariException { ClusterEntity entity = createDummyData(); ClusterImpl cluster = new ClusterImpl(entity, injector); Service service = cluster.getService("HDFS"); /* make sure the services are recovered */ Assert.assertEquals("HDFS",service.getName()); Map<String, Service> services = cluster.getServices(); Assert.assertNotNull(services.get("HDFS")); } @Test public void testConvertToResponse() throws AmbariException { ClusterResponse r = c1.convertToResponse(); Assert.assertEquals(c1.getClusterId(), r.getClusterId().longValue()); Assert.assertEquals(c1.getClusterName(), r.getClusterName()); Assert.assertEquals(1, r.getHostNames().size()); // TODO write unit tests for debug dump StringBuilder sb = new StringBuilder(); c1.debugDump(sb); } @Test public void testDeleteService() throws Exception { c1.addService("MAPREDUCE").persist(); Service hdfs = c1.addService("HDFS"); hdfs.persist(); ServiceComponent nameNode = hdfs.addServiceComponent("NAMENODE"); nameNode.persist(); assertEquals(2, c1.getServices().size()); assertEquals(2, injector.getProvider(EntityManager.class).get(). createQuery("SELECT service FROM ClusterServiceEntity service").getResultList().size()); c1.deleteService("HDFS"); assertEquals(1, c1.getServices().size()); assertEquals(1, injector.getProvider(EntityManager.class).get(). createQuery("SELECT service FROM ClusterServiceEntity service").getResultList().size()); } @Test public void testGetHostsDesiredConfigs() throws Exception { Host host1 = clusters.getHost("h1"); Config config = configFactory.createNew(c1, "hdfs-site", new HashMap<String, String>(){{ put("test", "test"); }}); config.setVersionTag("1"); host1.addDesiredConfig(c1.getClusterId(), true, "test", config); Map<String, Map<String, DesiredConfig>> configs = c1.getAllHostsDesiredConfigs(); assertTrue(configs.containsKey("h1")); assertEquals(1, configs.get("h1").size()); List<String> hostnames = new ArrayList<String>(); hostnames.add("h1"); configs = c1.getHostsDesiredConfigs(hostnames); assertTrue(configs.containsKey("h1")); assertEquals(1, configs.get("h1").size()); } }
/** * Copyright 2015 alex * <p> * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.ap.common.image; import com.ap.common.model.Kernel; import com.ap.common.util.ImageUtils; import javafx.scene.image.Image; import javafx.scene.image.PixelFormat; import javafx.scene.image.PixelFormat.Type; import javafx.scene.image.PixelReader; import javafx.scene.image.PixelWriter; import javafx.scene.image.WritableImage; import javafx.scene.image.WritablePixelFormat; import javafx.scene.paint.Color; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.ByteBuffer; public class AbstractImageWrapper implements IImage { final WritableImage writableImage; private PixelReader pixelReader; private PixelWriter pixelWriter; private PixelFormat<ByteBuffer> pixelFormat; private PixelFormat<ByteBuffer> writablePixelFormat; private Integer label; private int indexr; private int indexg; private int indexb; private int indexa; double COLOR_MAX_INTENSITY = 255; int COLOR_HISTOGRAM_SIZE = (int) (COLOR_MAX_INTENSITY + 1); double HUE_MAX_INTENSITY = 359; int HUE_HISTOGRAM_SIZE = (int) (HUE_MAX_INTENSITY + 1); Type type; public enum CHANNEL { RED, GREEN, BLUE, OPACITY } public WritableImage getWritableImage() { return writableImage; } public PixelWriter getPixelWriter() { return pixelWriter; } public PixelFormat<ByteBuffer> getWritablePixelFormat() { return writablePixelFormat; } // TODO: 12/01/16 Label as parameter everywhere public AbstractImageWrapper(WritableImage writableImage) { pixelReader = writableImage.getPixelReader(); this.writableImage = writableImage; initFields(writableImage.toString()); } public AbstractImageWrapper(javafx.scene.image.Image image) { this.writableImage = getWritebleImage(image); initFields(writableImage.toString()); } public AbstractImageWrapper(WritablePixelFormat<ByteBuffer> wpixelFormat, byte[] buffer, int width, int height) { pixelFormat = wpixelFormat; this.writableImage = new WritableImage(width, height); pixelReader = writableImage.getPixelReader(); pixelWriter = this.writableImage.getPixelWriter(); pixelWriter.setPixels(0, 0, width, height, wpixelFormat, buffer, 0, width * 4); initFields(writableImage.toString()); } public AbstractImageWrapper(String url) { javafx.scene.image.Image image = new Image(url); this.writableImage = getWritebleImage(image); initFields(url); } public AbstractImageWrapper(File file) throws Exception { try (InputStream inputStream = new FileInputStream(file)) { javafx.scene.image.Image image = new Image(inputStream); this.writableImage = getWritebleImage(image); initFields(file.getName()); } } private WritableImage getWritebleImage(Image image) { pixelReader = image.getPixelReader(); int width = (int) image.getWidth(); int height = (int) image.getHeight(); return new javafx.scene.image.WritableImage(pixelReader, width, height); } private void initFields(String label) { int start = label.indexOf("#"); int end = label.lastIndexOf("."); if (start > -1) { this.label = new Integer(label.substring(start + 1, end)); } else { this.label = -1; } pixelWriter = this.writableImage.getPixelWriter(); pixelFormat = pixelReader.getPixelFormat(); type = pixelFormat.getType(); switch (type) { case BYTE_BGRA: writablePixelFormat = PixelFormat.getByteBgraInstance(); indexr = 2; indexg = 1; indexb = 0; indexa = 3; break; case BYTE_BGRA_PRE: writablePixelFormat = PixelFormat.getByteBgraPreInstance(); indexr = 2; indexg = 1; indexb = 0; indexa = 3; break; case BYTE_INDEXED: throw new UnsupportedOperationException(); case BYTE_RGB: writablePixelFormat = PixelFormat.getByteRgbInstance(); indexr = 0; indexg = 1; indexb = 2; indexa = -1; break; case INT_ARGB: throw new UnsupportedOperationException(); case INT_ARGB_PRE: throw new UnsupportedOperationException(); default: break; } } private int c256(double color) { return (int) Math.round(color * COLOR_MAX_INTENSITY); } private int cropY(double lastY, int side) { return ((int) lastY + side > getHeight()) ? (int) getHeight() - side : (int) lastY; } private int cropX(double lastX, int side) { return ((int) lastX + side > getWidth()) ? (int) getWidth() - side : (int) lastX; } public double[] asGrayDoubleArray() { assert pixelFormat.isPremultiplied(); PixelReader reader = writableImage.getPixelReader(); double[] data = new double[getSize()]; for (int y = 0; y < writableImage.getHeight(); y++) { for (int x = 0; x < writableImage.getWidth(); x++) { Color color = reader.getColor(x, y).grayscale(); double red = color.getRed(); data[x + (int) writableImage.getWidth() * y] = red; System.out.printf("%4x", Math.round(red * 256));// } System.out.println(); } return data; } byte[] getBuffer() { byte[] buffer = new byte[((int) getWidth() * (int) getHeight() * 4)]; pixelReader.getPixels(0, 0, (int) getWidth(), (int) getHeight(), (WritablePixelFormat<ByteBuffer>) writablePixelFormat, buffer, 0, (int) getWidth() * 4); return buffer; } @Override public int getSize() { return (int) (writableImage.getWidth() * writableImage.getHeight()); } @Override public Integer getLabel() { return label; } @Override public double getWidth() { return writableImage.getWidth(); } @Override public double getHeight() { return writableImage.getHeight(); } @Override public byte[] getBuffer(double lastX, double lastY, int width, int height) { byte[] buffer = new byte[width * height * 4]; int X = cropX(lastX, width); int Y = cropY(lastY, height); pixelReader.getPixels((X > 0 ? X : 0), (Y > 0 ? Y : 0), width, height, (WritablePixelFormat<ByteBuffer>) writablePixelFormat, buffer, 0, width * 4); return buffer; } public javafx.scene.image.WritableImage asFX() { return writableImage; } public void setPixels(int x, int y, ImageData result) { int scanlineStride = result.getWidth() * FxImageUtils.bytesInPixel(pixelFormat); pixelWriter.setPixels(x, y, result.getWidth(), result.getImageData().length / scanlineStride, writablePixelFormat, result.getImageData(), 0, scanlineStride); } public PixelReader getPixelReader() { return pixelReader; } public PixelFormat<ByteBuffer> getPixelFormat() { return writablePixelFormat; } public byte[] getArea(double centerX, double centerY, int half) { int side = half * 2 + 1; byte[] buffer = new byte[side * side * 4]; double X = (centerX + side < getWidth()) ? centerX : getWidth() - side - 1; double Y = (centerY + side < getHeight()) ? centerY : getHeight() - side - 1; pixelReader.getPixels((X > 0 ? (int) X : 0), (Y > 0 ? (int) Y : 0), side, side, (WritablePixelFormat<ByteBuffer>) writablePixelFormat, buffer, 0, side * 4); return buffer; } public double[] getDataConvolved(Kernel kernel) { assert pixelFormat.isPremultiplied(); double[] data = asGrayDoubleArray(); double[] dbuffer = new double[data.length]; int width = kernel.getWidth(); int height = kernel.getHeight(); for (int x = 0; x < getWidth(); x++) { for (int y = 0; y < getHeight(); y++) { double[] kBuffer = ImageUtils.getSubData(data, x, y, (int) getWidth(), width, height); dbuffer[(int) (x + y * getWidth())] = kernel.convolve(kBuffer); } } return dbuffer; } public double[] getHistogramEqualization(double[] LUT, boolean inverse) { int pixelCount = (int) (getWidth() * getHeight()); double[] buffer = new double[pixelCount]; double sum = 0; double[] lut; if (LUT == null) { lut = getHistogramLUT(); } else { lut = LUT; } for (int i = 0; i < pixelCount; ++i) { if (inverse) { buffer[i] = lut[(int) (COLOR_MAX_INTENSITY - c256(gray(i)))]; } else { buffer[i] = lut[c256(gray(i))]; } } return buffer; } public double[] getHistogramLUT() { int pixelCount = (int) getWidth() * (int) getHeight(); double sum = 0; double[] lut = new double[COLOR_HISTOGRAM_SIZE]; int[] histogram = new int[COLOR_HISTOGRAM_SIZE]; for (int i = 0; i < pixelCount; i++) { int index = c256(gray(i)); histogram[index]++; } for (int i = 0; i < COLOR_HISTOGRAM_SIZE; ++i) { sum += histogram[i]; lut[i] = sum / pixelCount; } return lut; } private double gray(int i) { int y = (int) (i / getWidth()); int x = (int) (i % getWidth()); Color color = pixelReader.getColor(x, y).grayscale(); return color.getRed(); } public double[] getChannel(double lastX, double lastY, int width, int height, CHANNEL name) { byte[] buffer = getBuffer(lastX, lastY, width, height); int pixelCount = width * height; double[] channel = new double[width * height]; int offset = 0; switch (name) { case RED: offset = indexr; break; case GREEN: offset = indexg; break; case BLUE: offset = indexb; break; case OPACITY: offset = indexa; break; default: break; } for (int i = 0; i < pixelCount; i++) { channel[i] = (buffer[i * 4 + offset] & 0xff) / COLOR_MAX_INTENSITY; } return channel; } public double[] getHistogramHUELUT() { byte[] buffer = getBuffer(); int pixelCount = (int) getWidth() * (int) getHeight(); double sum = 0; double[] lut = new double[HUE_HISTOGRAM_SIZE]; int[] histogram = new int[HUE_HISTOGRAM_SIZE]; for (int i = 0; i < pixelCount; i++) { int ired = 0xff & buffer[i * 4 + indexr]; int igreen = 0xff & buffer[i * 4 + indexg]; int iblue = 0xff & buffer[i * 4 + indexb]; int ia = 0xff & buffer[i * 4 + indexa]; Color color = Color.rgb(ired, igreen, iblue, ia / COLOR_MAX_INTENSITY); double hue = color.getHue(); assert hue <= 360.; int index = (int) Math.round(hue); histogram[index >= HUE_MAX_INTENSITY ? 0 : index]++; } for (int i = 0; i < HUE_HISTOGRAM_SIZE; ++i) { sum += histogram[i]; lut[i] = sum / pixelCount; } return lut; } byte[] getBufferPosterize(double lastX, double lastY, int side, float level, FOrtoCube cube) { byte[] buffer = getBuffer(lastX, lastY, side, side); float[] hsv = new float[3]; for (int i = 0; i < side * side; i++) { int ired = 0xff & buffer[i * 4 + indexr]; int igreen = 0xff & buffer[i * 4 + indexg]; int iblue = 0xff & buffer[i * 4 + indexb]; java.awt.Color.RGBtoHSB(ired, igreen, iblue, hsv); if (i == 0) { System.out.print("*,* " + ired + " | " + igreen + " | " + iblue + " | " + hsv[0] + " | " + hsv[1] + " | " + hsv[2]); } float r = (float) (ired / 255.); float g = (float) (igreen / 255.); float b = (float) (iblue / 255.); int ir = (int) ((Math.round(r * level) / level) * COLOR_MAX_INTENSITY); int ig = (int) ((Math.round(g * level) / level) * COLOR_MAX_INTENSITY); int ib = (int) ((Math.round(b * level) / level) * COLOR_MAX_INTENSITY); java.awt.Color.RGBtoHSB(ir, ig, ib, hsv); if (i == 0) { System.out.println(" -> *,* " + ir + " | " + ig + " | " + ib + " | " + hsv[0] + " | " + hsv[1] + " | " + hsv[2]); } if (cube.isBelong(hsv)) { buffer[i * 4 + indexr] = (byte) (0xff & ir); buffer[i * 4 + indexg] = (byte) (0xff & ig); buffer[i * 4 + indexb] = (byte) (0xff & ib); } else { buffer[i * 4 + indexr] = 0; buffer[i * 4 + indexg] = 0; buffer[i * 4 + indexb] = 0; if (indexa >= 0) { buffer[i * 4 + indexa] = 0; } } } return buffer; } byte[] getBufferConvolved(double lastX, double lastY, int side, Kernel kernel) { assert pixelFormat.isPremultiplied(); byte[] buffer = getBuffer(lastX, lastY, side, side); int X = cropX(lastX, side); int Y = cropY(lastY, side); assert kernel.getWidth() == kernel.getHeight(); int kernelSide = kernel.getHeight(); for (int x = X; x < X + side; x++) { for (int y = Y; y < Y + side; y++) { byte[] kBuffer = getBuffer(x, y, kernelSide, kernelSide); double[] kCBuffer = new double[kernelSide * kernelSide]; for (int i = 0; i < 4; i++) { if (kernel.getFmsum() == 0 && i == indexa) { continue; } for (int xi = 0; xi < kernelSide; xi++) { for (int yi = 0; yi < kernelSide; yi++) { kCBuffer[xi + yi * kernelSide] = (kBuffer[xi * 4 + yi * kernelSide * 4 + i] & 0xff) / COLOR_MAX_INTENSITY; } } buffer[(x - X) * 4 + (y - Y) * side * 4 + i] = (byte) ((int) (kernel.convolve(kCBuffer) * COLOR_MAX_INTENSITY) & 0xff); } } } return buffer; } @Override public int getPixel(int x, int y) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setPixel(int x, int y, int color) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int[] getPixels(int offset, int stride, int x, int y, int width, int height) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height) { throw new UnsupportedOperationException("Not supported yet."); } @Override public IImage resize(int width, int height) { throw new UnsupportedOperationException("Not supported yet."); } @Override public IImage crop(int x1, int y1, int x2, int y2) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getType() { throw new UnsupportedOperationException("Not supported yet."); } }
/* * 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.lightsail.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetContainerServiceMetricData" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetContainerServiceMetricDataResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The name of the metric returned. * </p> */ private String metricName; /** * <p> * An array of objects that describe the metric data returned. * </p> */ private java.util.List<MetricDatapoint> metricData; /** * <p> * The name of the metric returned. * </p> * * @param metricName * The name of the metric returned. * @see ContainerServiceMetricName */ public void setMetricName(String metricName) { this.metricName = metricName; } /** * <p> * The name of the metric returned. * </p> * * @return The name of the metric returned. * @see ContainerServiceMetricName */ public String getMetricName() { return this.metricName; } /** * <p> * The name of the metric returned. * </p> * * @param metricName * The name of the metric returned. * @return Returns a reference to this object so that method calls can be chained together. * @see ContainerServiceMetricName */ public GetContainerServiceMetricDataResult withMetricName(String metricName) { setMetricName(metricName); return this; } /** * <p> * The name of the metric returned. * </p> * * @param metricName * The name of the metric returned. * @return Returns a reference to this object so that method calls can be chained together. * @see ContainerServiceMetricName */ public GetContainerServiceMetricDataResult withMetricName(ContainerServiceMetricName metricName) { this.metricName = metricName.toString(); return this; } /** * <p> * An array of objects that describe the metric data returned. * </p> * * @return An array of objects that describe the metric data returned. */ public java.util.List<MetricDatapoint> getMetricData() { return metricData; } /** * <p> * An array of objects that describe the metric data returned. * </p> * * @param metricData * An array of objects that describe the metric data returned. */ public void setMetricData(java.util.Collection<MetricDatapoint> metricData) { if (metricData == null) { this.metricData = null; return; } this.metricData = new java.util.ArrayList<MetricDatapoint>(metricData); } /** * <p> * An array of objects that describe the metric data returned. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setMetricData(java.util.Collection)} or {@link #withMetricData(java.util.Collection)} if you want to * override the existing values. * </p> * * @param metricData * An array of objects that describe the metric data returned. * @return Returns a reference to this object so that method calls can be chained together. */ public GetContainerServiceMetricDataResult withMetricData(MetricDatapoint... metricData) { if (this.metricData == null) { setMetricData(new java.util.ArrayList<MetricDatapoint>(metricData.length)); } for (MetricDatapoint ele : metricData) { this.metricData.add(ele); } return this; } /** * <p> * An array of objects that describe the metric data returned. * </p> * * @param metricData * An array of objects that describe the metric data returned. * @return Returns a reference to this object so that method calls can be chained together. */ public GetContainerServiceMetricDataResult withMetricData(java.util.Collection<MetricDatapoint> metricData) { setMetricData(metricData); 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 (getMetricName() != null) sb.append("MetricName: ").append(getMetricName()).append(","); if (getMetricData() != null) sb.append("MetricData: ").append(getMetricData()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetContainerServiceMetricDataResult == false) return false; GetContainerServiceMetricDataResult other = (GetContainerServiceMetricDataResult) obj; if (other.getMetricName() == null ^ this.getMetricName() == null) return false; if (other.getMetricName() != null && other.getMetricName().equals(this.getMetricName()) == false) return false; if (other.getMetricData() == null ^ this.getMetricData() == null) return false; if (other.getMetricData() != null && other.getMetricData().equals(this.getMetricData()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMetricName() == null) ? 0 : getMetricName().hashCode()); hashCode = prime * hashCode + ((getMetricData() == null) ? 0 : getMetricData().hashCode()); return hashCode; } @Override public GetContainerServiceMetricDataResult clone() { try { return (GetContainerServiceMetricDataResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }