Unnamed: 0
int64
0
6.45k
func
stringlengths
37
161k
target
class label
2 classes
project
stringlengths
33
167
244
service.submitToKeyOwner(callable, "key", new ExecutionCallback() { public void onResponse(Object response) { result.set(response); responseLatch.countDown(); } public void onFailure(Throwable t) { } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java
648
public class CollectionContainsOperation extends CollectionOperation { Set<Data> valueSet; public CollectionContainsOperation() { } public CollectionContainsOperation(String name, Set<Data> valueSet) { super(name); this.valueSet = valueSet; } @Override public int getId() { return CollectionDataSerializerHook.COLLECTION_CONTAINS; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { response = getOrCreateContainer().contains(valueSet); } @Override public void afterRun() throws Exception { } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeInt(valueSet.size()); for (Data value : valueSet) { value.writeData(out); } } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); final int size = in.readInt(); valueSet = new HashSet<Data>(size); for (int i = 0; i < size; i++) { final Data value = new Data(); value.readData(in); valueSet.add(value); } } }
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionContainsOperation.java
258
public final class StoreUtils { private StoreUtils() { } public static String toString(Directory directory) { if (directory instanceof NIOFSDirectory) { NIOFSDirectory niofsDirectory = (NIOFSDirectory)directory; return "niofs(" + niofsDirectory.getDirectory() + ")"; } if (directory instanceof MMapDirectory) { MMapDirectory mMapDirectory = (MMapDirectory)directory; return "mmapfs(" + mMapDirectory.getDirectory() + ")"; } if (directory instanceof SimpleFSDirectory) { SimpleFSDirectory simpleFSDirectory = (SimpleFSDirectory)directory; return "simplefs(" + simpleFSDirectory.getDirectory() + ")"; } return directory.toString(); } }
0true
src_main_java_org_apache_lucene_store_StoreUtils.java
411
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface AdminPresentation { /** * <p>Optional - only required if you want to display a friendly name to the user</p> * * <p><The friendly name to present to a user for this field in a GUI. If supporting i18N, * the friendly name may be a key to retrieve a localized friendly name using * the GWT support for i18N.</p> * * @return the friendly name */ String friendlyName() default ""; /** * Optional - only required if you want to restrict this field * * If a security level is specified, it is registered with org.broadleafcommerce.openadmin.client.security.SecurityManager * The SecurityManager checks the permission of the current user to * determine if this field should be disabled based on the specified level. * * @return the security level */ String securityLevel() default ""; /** * Optional - only required if you want to order the appearance of this field in the UI * * The order in which this field will appear in a GUI relative to other fields from the same class * * @return the display order */ int order() default 99999; /** * Optional - required only if you want to order the appearance of this field as it relates to other fields in a * Note that this field will only be relevant if {@link #prominent()} is also set to true. * * @return */ int gridOrder() default 9999; /** * Optional - only required if you want to restrict the visibility of this field in the admin tool * * Describes how the field is shown in admin GUI. * * @return whether or not to hide the form field. */ VisibilityEnum visibility() default VisibilityEnum.VISIBLE_ALL; /** * Optional - only required if you want to explicitly specify the field type. This * value is normally inferred by the system based on the field type in the entity class. * * Explicity specify the type the GUI should consider this field * Specifying UNKNOWN will cause the system to make its best guess * * @return the field type */ SupportedFieldType fieldType() default SupportedFieldType.UNKNOWN; /** * Optional - only required if you want to specify a grouping for this field * * Specify a GUI grouping for this field * Fields in the same group will be visually grouped together in the GUI * <br /> * <br /> * Note: for support I18N, this can also be a key to retrieve a localized String * * @return the group for this field */ String group() default "General"; /** * Optional - only required if you want to order the appearance of groups in the UI * * Specify an order for this group. Groups will be sorted in the resulting * form in ascending order based on this parameter. * * @return the order for this group */ int groupOrder() default 99999; /** * Optional - only required if you want to control the initial collapsed state of the group * * Specify whether a group is collapsed by default in the admin UI. * * @return whether or not the group is collapsed by default */ boolean groupCollapsed() default false; /** * Optional - only required if you want the field to appear under a different tab * * Specify a GUI tab for this field * * @return the tab for this field */ String tab() default "General"; /** * Optional - only required if you want to order the appearance of the tabs in the UI * * Specify an order for this tab. Tabs will be sorted int he resulting form in * ascending order based on this parameter. * * The default tab will render with an order of 100. * * @return the order for this tab */ int tabOrder() default 100; /** * Optional - only required if you want to give the user extra room to enter a value * for this field in the UI * * If the field is a string, specify that the GUI * provide a text area * * @return is a text area field */ boolean largeEntry() default false; /** * Optional - only required if you want this field to appear as one of the default * columns in a grid in the admin tool * * Provide a hint to the GUI about the prominence of this field. * For example, prominent fields will show up as a column in any * list grid in the admin that displays this entity. * * @return whether or not this is a prominent field */ boolean prominent() default false; /** * Optional - only required if you want to explicitly control column width * for this field in a grid in the admin tool * * Specify the column space this field will occupy in grid widgets. * This value can be an absolute integer or a percentage. A value * of "*" will make this field use up equally distributed space. * * @return the space utilized in grids for this field */ String columnWidth() default "*"; /** * Optional - only required for BROADLEAF_ENUMERATION field types * * For fields with a SupportedFieldType of BROADLEAF_ENUMERATION, * you must specify the fully qualified class name of the Broadleaf Enumeration here. * * @return Broadleaf enumeration class name */ String broadleafEnumeration() default ""; /** * Optional - only required if you want to make the field immutable * * Explicityly specify whether or not this field is mutable. * * @return whether or not this field is read only */ boolean readOnly() default false; /** * Optional - only required if you want to provide validation for this field * * Specify the validation to use for this field in the admin, if any * * @return the configuration for the validation */ ValidationConfiguration[] validationConfigurations() default {}; /** * Optional - only required if you want to explicitly make a field required. This * setting is normally inferred by the JPA annotations on the field. * * Specify whether you would like the admin to require this field, * even if it is not required by the ORM. * * @return the required override enumeration */ RequiredOverride requiredOverride() default RequiredOverride.IGNORED; /** * Optional - only required if you want to explicitly exclude this field from * dynamic management by the admin tool * * Specify if this field should be excluded from inclusion in the * admin presentation layer * * @return whether or not the field should be excluded */ boolean excluded() default false; /** * Optional - only required if you want to provide a tooltip for the field * * Helpful tooltip to be displayed when the admin user hovers over the field. * This can be localized by providing a key which will use the GWT * support for i18N. * */ String tooltip() default ""; /** * Optional - only required if you want to provide help text for this field * * On the form for this entity, this will show a question * mark icon next to the field. When the user clicks on the icon, whatever * HTML that is specified in this helpText is shown in a popup. * * For i18n support, this can also be a key to a localized version of the text * * Reference implementation: http://www.smartclient.com/smartgwt/showcase/#form_details_hints * */ String helpText() default ""; /** * Optional - only required if you want to provide a hint for this field * * Text to display immediately to the right of a form field. For instance, if the user needs * to put in a date, the hint could be the format the date needs to be in like 'MM/YYYY'. * * For i18n support, this can also be a key to a localized version of the text * * Reference implementation: http://www.smartclient.com/smartgwt/showcase/#form_details_hints */ String hint() default ""; /** * <p>Optional - propertyName , only required if you want hide the field based on this property's value</p> * * <p>If the property is defined and found to be set to false, in the AppConfiguraionService, then this field will be excluded in the * admin presentation layer</p> * * @return name of the property */ String showIfProperty() default ""; /** * Optional - If you have FieldType set to SupportedFieldType.MONEY, * then you can specify a money currency property field. * * @return the currency property field */ String currencyCodeField() default ""; /** * <p>Optional - only required if the fieldType is SupportedFieldType.RULE_SIMPLE or SupportedFieldType.RULE_COMPLEX</p> * * <p>Identifies the type for which this rule builder is targeted. See <tt>RuleIdentifier</tt> for a list of * identifier types supported out-of-the-box. Note - one of the main uses of this value is to help identify * the proper <tt>RuleBuilderService</tt> instance to generate the correct field value options for this rule builder.</p> * * @return The identifier value that denotes what type of rule builder this is - especially influences the fields that are available in the UI */ String ruleIdentifier() default ""; /** * <p>Optional - marks this field as being translatable, which will render the translations modal in the admin UI</p> * * @return whether or not this field is translatable */ boolean translatable() default false; }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentation.java
198
Analyzer analyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer t = new WhitespaceTokenizer(Lucene.VERSION, reader); return new TokenStreamComponents(t, new UniqueTokenFilter(t)); } };
0true
src_test_java_org_apache_lucene_analysis_miscellaneous_UniqueTokenFilterTests.java
1,337
public class Hadoop2Compiler extends HybridConfigured implements HadoopCompiler { private static final String MAPRED_COMPRESS_MAP_OUTPUT = "mapred.compress.map.output"; private static final String MAPRED_MAP_OUTPUT_COMPRESSION_CODEC = "mapred.map.output.compression.codec"; enum State {MAPPER, REDUCER, NONE} private static final String ARROW = " > "; private static final String MAPREDUCE_MAP_OUTPUT_COMPRESS = "mapreduce.map.output.compress"; private static final String MAPREDUCE_MAP_OUTPUT_COMPRESS_CODEC = "mapreduce.map.output.compress.codec"; public static final Logger logger = Logger.getLogger(Hadoop2Compiler.class); private HadoopGraph graph; protected final List<Job> jobs = new ArrayList<Job>(); private State state = State.NONE; private static final Class<? extends InputFormat> INTERMEDIATE_INPUT_FORMAT = SequenceFileInputFormat.class; private static final Class<? extends OutputFormat> INTERMEDIATE_OUTPUT_FORMAT = SequenceFileOutputFormat.class; static final String JOB_JAR = "titan-hadoop-2-" + TitanConstants.VERSION + "-job.jar"; private static final String MAPRED_JAR = "mapred.jar"; public Hadoop2Compiler(final HadoopGraph graph) { this.graph = graph; this.setConf(new Configuration(this.graph.getConf())); } private String makeClassName(final Class klass) { return klass.getCanonicalName().replace(klass.getPackage().getName() + ".", ""); } @Override public void addMapReduce(final Class<? extends Mapper> mapper, final Class<? extends Reducer> combiner, final Class<? extends Reducer> reducer, final Class<? extends WritableComparable> mapOutputKey, final Class<? extends WritableComparable> mapOutputValue, final Class<? extends WritableComparable> reduceOutputKey, final Class<? extends WritableComparable> reduceOutputValue, final Configuration configuration) { this.addMapReduce(mapper, combiner, reducer, null, mapOutputKey, mapOutputValue, reduceOutputKey, reduceOutputValue, configuration); } @Override public void addMapReduce(final Class<? extends Mapper> mapper, final Class<? extends Reducer> combiner, final Class<? extends Reducer> reducer, final Class<? extends WritableComparator> comparator, final Class<? extends WritableComparable> mapOutputKey, final Class<? extends WritableComparable> mapOutputValue, final Class<? extends WritableComparable> reduceOutputKey, final Class<? extends WritableComparable> reduceOutputValue, final Configuration configuration) { Configuration mergedConf = overlayConfiguration(getConf(), configuration); try { final Job job; if (State.NONE == this.state || State.REDUCER == this.state) { // Create a new job with a reference to mergedConf job = Job.getInstance(mergedConf); job.setJobName(makeClassName(mapper) + ARROW + makeClassName(reducer)); HBaseAuthHelper.setHBaseAuthToken(mergedConf, job); this.jobs.add(job); } else { job = this.jobs.get(this.jobs.size() - 1); job.setJobName(job.getJobName() + ARROW + makeClassName(mapper) + ARROW + makeClassName(reducer)); } job.setNumReduceTasks(this.getConf().getInt("mapreduce.job.reduces", this.getConf().getInt("mapreduce.tasktracker.reduce.tasks.maximum", 1))); ChainMapper.addMapper(job, mapper, NullWritable.class, FaunusVertex.class, mapOutputKey, mapOutputValue, mergedConf); ChainReducer.setReducer(job, reducer, mapOutputKey, mapOutputValue, reduceOutputKey, reduceOutputValue, mergedConf); if (null != comparator) job.setSortComparatorClass(comparator); if (null != combiner) job.setCombinerClass(combiner); if (null == job.getConfiguration().get(MAPREDUCE_MAP_OUTPUT_COMPRESS, null)) job.getConfiguration().setBoolean(MAPREDUCE_MAP_OUTPUT_COMPRESS, true); if (null == job.getConfiguration().get(MAPREDUCE_MAP_OUTPUT_COMPRESS_CODEC, null)) job.getConfiguration().setClass(MAPREDUCE_MAP_OUTPUT_COMPRESS_CODEC, DefaultCodec.class, CompressionCodec.class); this.state = State.REDUCER; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } @Override public void addMap(final Class<? extends Mapper> mapper, final Class<? extends WritableComparable> mapOutputKey, final Class<? extends WritableComparable> mapOutputValue, Configuration configuration) { Configuration mergedConf = overlayConfiguration(getConf(), configuration); try { final Job job; if (State.NONE == this.state) { // Create a new job with a reference to mergedConf job = Job.getInstance(mergedConf); job.setNumReduceTasks(0); job.setJobName(makeClassName(mapper)); HBaseAuthHelper.setHBaseAuthToken(mergedConf, job); this.jobs.add(job); } else { job = this.jobs.get(this.jobs.size() - 1); job.setJobName(job.getJobName() + ARROW + makeClassName(mapper)); } if (State.MAPPER == this.state || State.NONE == this.state) { ChainMapper.addMapper(job, mapper, NullWritable.class, FaunusVertex.class, mapOutputKey, mapOutputValue, mergedConf); this.state = State.MAPPER; } else { ChainReducer.addMapper(job, mapper, NullWritable.class, FaunusVertex.class, mapOutputKey, mapOutputValue, mergedConf); this.state = State.REDUCER; } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } @Override public void completeSequence() { // noop } @Override public void composeJobs() throws IOException { if (this.jobs.size() == 0) { return; } if (getTitanConf().get(TitanHadoopConfiguration.PIPELINE_TRACK_PATHS)) logger.warn("Path tracking is enabled for this Titan/Hadoop job (space and time expensive)"); if (getTitanConf().get(TitanHadoopConfiguration.PIPELINE_TRACK_STATE)) logger.warn("State tracking is enabled for this Titan/Hadoop job (full deletes not possible)"); JobClasspathConfigurer cpConf = JobClasspathConfigurers.get(graph.getConf().get(MAPRED_JAR), JOB_JAR); // Create temporary job data directory on the filesystem Path tmpPath = graph.getJobDir(); final FileSystem fs = FileSystem.get(graph.getConf()); fs.mkdirs(tmpPath); logger.debug("Created " + tmpPath + " on filesystem " + fs); final String jobTmp = tmpPath.toString() + "/" + Tokens.JOB; logger.debug("Set jobDir=" + jobTmp); //////// CHAINING JOBS TOGETHER for (int i = 0; i < this.jobs.size(); i++) { final Job job = this.jobs.get(i); for (ConfigOption<Boolean> c : Arrays.asList(TitanHadoopConfiguration.PIPELINE_TRACK_PATHS, TitanHadoopConfiguration.PIPELINE_TRACK_STATE)) { ModifiableHadoopConfiguration jobFaunusConf = ModifiableHadoopConfiguration.of(job.getConfiguration()); jobFaunusConf.set(c, getTitanConf().get(c)); } SequenceFileOutputFormat.setOutputPath(job, new Path(jobTmp + "-" + i)); cpConf.configure(job); // configure job inputs if (i == 0) { job.setInputFormatClass(this.graph.getGraphInputFormat()); if (FileInputFormat.class.isAssignableFrom(this.graph.getGraphInputFormat())) { FileInputFormat.setInputPaths(job, this.graph.getInputLocation()); FileInputFormat.setInputPathFilter(job, NoSideEffectFilter.class); } } else { job.setInputFormatClass(INTERMEDIATE_INPUT_FORMAT); FileInputFormat.setInputPaths(job, new Path(jobTmp + "-" + (i - 1))); FileInputFormat.setInputPathFilter(job, NoSideEffectFilter.class); } // configure job outputs if (i == this.jobs.size() - 1) { LazyOutputFormat.setOutputFormatClass(job, this.graph.getGraphOutputFormat()); MultipleOutputs.addNamedOutput(job, Tokens.SIDEEFFECT, this.graph.getSideEffectOutputFormat(), job.getOutputKeyClass(), job.getOutputKeyClass()); MultipleOutputs.addNamedOutput(job, Tokens.GRAPH, this.graph.getGraphOutputFormat(), NullWritable.class, FaunusVertex.class); } else { LazyOutputFormat.setOutputFormatClass(job, INTERMEDIATE_OUTPUT_FORMAT); MultipleOutputs.addNamedOutput(job, Tokens.SIDEEFFECT, this.graph.getSideEffectOutputFormat(), job.getOutputKeyClass(), job.getOutputKeyClass()); MultipleOutputs.addNamedOutput(job, Tokens.GRAPH, INTERMEDIATE_OUTPUT_FORMAT, NullWritable.class, FaunusVertex.class); } } } @Override public int run(final String[] args) throws Exception { String script = null; boolean showHeader = true; if (args.length == 2) { script = args[0]; showHeader = Boolean.valueOf(args[1]); } final FileSystem hdfs = FileSystem.get(this.getConf()); if (null != graph.getJobDir() && graph.getJobDirOverwrite() && hdfs.exists(graph.getJobDir())) { hdfs.delete(graph.getJobDir(), true); } if (showHeader) { logger.info("Titan/Hadoop: Distributed Graph Processing with Hadoop"); logger.info(" ,"); logger.info(" , |\\ ,__"); logger.info(" |\\ \\/ `\\"); logger.info(" \\ `-.:. `\\"); logger.info(" `-.__ `\\/\\/\\|"); logger.info(" / `'/ () \\"); logger.info(" .' /\\ )"); logger.info(" .-' .'| \\ \\__"); logger.info(" .' __( \\ '`(()"); logger.info("/_.'` `. | )("); logger.info(" \\ |"); logger.info(" |/"); } if (null != script && !script.isEmpty()) logger.info("Generating job chain: " + script); this.composeJobs(); logger.info("Compiled to " + this.jobs.size() + " MapReduce job(s)"); final String jobTmp = graph.getJobDir().toString() + "/" + Tokens.JOB; for (int i = 0; i < this.jobs.size(); i++) { final Job job = this.jobs.get(i); try { ((JobConfigurationFormat) (FormatTools.getBaseOutputFormatClass(job).newInstance())).updateJob(job); } catch (final Exception e) { } logger.info("Executing job " + (i + 1) + " out of " + this.jobs.size() + ": " + job.getJobName()); boolean success = job.waitForCompletion(true); if (i > 0) { Preconditions.checkNotNull(jobTmp); logger.debug("Cleaninng job data location: " + jobTmp + "-" + i); final Path path = new Path(jobTmp + "-" + (i - 1)); // delete previous intermediate graph data for (final FileStatus temp : hdfs.globStatus(new Path(path.toString() + "/" + Tokens.GRAPH + "*"))) { hdfs.delete(temp.getPath(), true); } // delete previous intermediate graph data for (final FileStatus temp : hdfs.globStatus(new Path(path.toString() + "/" + Tokens.PART + "*"))) { hdfs.delete(temp.getPath(), true); } } if (!success) { logger.error("Titan/Hadoop job error -- remaining MapReduce jobs have been canceled"); return -1; } } return 0; } private static Configuration overlayConfiguration(Configuration base, Configuration overrides) { Configuration mergedConf = new Configuration(base); final Iterator<Entry<String,String>> it = overrides.iterator(); while (it.hasNext()) { Entry<String,String> ent = it.next(); mergedConf.set(ent.getKey(), ent.getValue()); } return mergedConf; } }
1no label
titan-hadoop-parent_titan-hadoop-2_src_main_java_com_thinkaurelius_titan_hadoop_compat_h2_Hadoop2Compiler.java
474
final OIndexManager indexManagerOne = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<OIndexManager>() { public OIndexManager call() { return databaseDocumentTxOne.getMetadata().getIndexManager(); } });
0true
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
171
Executors.newSingleThreadExecutor().submit(new Runnable() { public void run() { while (true) { try { Thread.sleep(STATS_SECONDS * 1000); System.out.println("cluster size:" + client.getCluster().getMembers().size()); Stats currentStats = stats.getAndReset(); System.out.println(currentStats); System.out.println("Operations per Second : " + currentStats.total() / STATS_SECONDS); } catch (Exception e) { e.printStackTrace(); } } } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_SimpleMapTestFromClient.java
345
Comparator<Node> idCompare = new Comparator<Node>() { public int compare(Node arg0, Node arg1) { Node id1 = arg0.getAttributes().getNamedItem(attribute); Node id2 = arg1.getAttributes().getNamedItem(attribute); String idVal1 = id1.getNodeValue(); String idVal2 = id2.getNodeValue(); return idVal1.compareTo(idVal2); } };
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_NonEmptyNodeReplaceInsert.java
1,108
SINGLE_VALUED_SPARSE_RANDOM { public int numValues() { return RANDOM.nextFloat() < 0.1f ? 1 : 0; } @Override public long nextValue() { return RANDOM.nextLong(); } },
0true
src_test_java_org_elasticsearch_benchmark_fielddata_LongFieldDataBenchmark.java
1,121
public class OSQLFunctionDecode extends OSQLFunctionAbstract { public static final String NAME = "decode"; /** * Get the date at construction to have the same date for all the iteration. */ public OSQLFunctionDecode() { super(NAME, 2, 2); } @Override public Object execute(OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters, OCommandContext iContext) { final String candidate = iParameters[0].toString(); final String format = iParameters[1].toString(); if(OSQLFunctionEncode.FORMAT_BASE64.equalsIgnoreCase(format)){ return OBase64Utils.decode(candidate); }else{ throw new OException("unknowned format :"+format); } } @Override public String getSyntax() { return "Syntax error: decode(<binaryfield>, <format>)"; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_functions_misc_OSQLFunctionDecode.java
2,019
public class LatestUpdateMapMergePolicy implements MapMergePolicy { public Object merge(String mapName, EntryView mergingEntry, EntryView existingEntry) { if (mergingEntry.getLastUpdateTime() > existingEntry.getLastUpdateTime()) return mergingEntry.getValue(); return existingEntry.getValue(); } @Override public void writeData(ObjectDataOutput out) throws IOException { } @Override public void readData(ObjectDataInput in) throws IOException { } }
1no label
hazelcast_src_main_java_com_hazelcast_map_merge_LatestUpdateMapMergePolicy.java
648
public final class OLocalHashTableIndexEngine<V> implements OIndexEngine<V> { public static final String METADATA_FILE_EXTENSION = ".him"; public static final String TREE_FILE_EXTENSION = ".hit"; public static final String BUCKET_FILE_EXTENSION = ".hib"; private final OLocalHashTable<Object, V> hashTable; private final OMurmurHash3HashFunction<Object> hashFunction; private volatile ORID identity; public OLocalHashTableIndexEngine() { hashFunction = new OMurmurHash3HashFunction<Object>(); hashTable = new OLocalHashTable<Object, V>(METADATA_FILE_EXTENSION, TREE_FILE_EXTENSION, BUCKET_FILE_EXTENSION, hashFunction); } @Override public void init() { } @Override public void create(String indexName, OIndexDefinition indexDefinition, String clusterIndexName, OStreamSerializer valueSerializer, boolean isAutomatic) { OBinarySerializer keySerializer; if (indexDefinition != null) { if (indexDefinition instanceof ORuntimeKeyIndexDefinition) { keySerializer = ((ORuntimeKeyIndexDefinition) indexDefinition).getSerializer(); } else { if (indexDefinition.getTypes().length > 1) { keySerializer = OCompositeKeySerializer.INSTANCE; } else { keySerializer = OBinarySerializerFactory.INSTANCE.getObjectSerializer(indexDefinition.getTypes()[0]); } } } else keySerializer = new OSimpleKeySerializer(); final ODatabaseRecord database = getDatabase(); final ORecordBytes identityRecord = new ORecordBytes(); final OStorageLocalAbstract storageLocalAbstract = (OStorageLocalAbstract) database.getStorage(); database.save(identityRecord, clusterIndexName); identity = identityRecord.getIdentity(); hashFunction.setValueSerializer(keySerializer); hashTable.create(indexName, keySerializer, (OBinarySerializer<V>) valueSerializer, indexDefinition != null ? indexDefinition.getTypes() : null, storageLocalAbstract); } @Override public void flush() { hashTable.flush(); } @Override public void deleteWithoutLoad(String indexName) { hashTable.deleteWithoutLoad(indexName, (OStorageLocalAbstract) getDatabase().getStorage().getUnderlying()); } @Override public void delete() { hashTable.delete(); } @Override public void load(ORID indexRid, String indexName, OIndexDefinition indexDefinition, boolean isAutomatic) { identity = indexRid; hashTable.load(indexName, indexDefinition != null ? indexDefinition.getTypes() : null, (OStorageLocalAbstract) getDatabase() .getStorage().getUnderlying()); hashFunction.setValueSerializer(hashTable.getKeySerializer()); } @Override public boolean contains(Object key) { return hashTable.get(key) != null; } @Override public boolean remove(Object key) { return hashTable.remove(key) != null; } @Override public void clear() { hashTable.clear(); } @Override public void unload() { } @Override public void closeDb() { } @Override public void close() { hashTable.close(); } @Override public V get(Object key) { return hashTable.get(key); } @Override public void put(Object key, V value) { hashTable.put(key, value); } @Override public long size(ValuesTransformer<V> transformer) { if (transformer == null) return hashTable.size(); else { OHashIndexBucket.Entry<Object, V> firstEntry = hashTable.firstEntry(); if (firstEntry == null) return 0; OHashIndexBucket.Entry<Object, V>[] entries = hashTable.ceilingEntries(firstEntry.key); long counter = 0; while (entries.length > 0) { for (OHashIndexBucket.Entry<Object, V> entry : entries) counter += transformer.transformFromValue(entry.value).size(); entries = hashTable.higherEntries(entries[entries.length - 1].key); } return counter; } } @Override public ORID getIdentity() { return identity; } @Override public boolean hasRangeQuerySupport() { return false; } @Override public Iterator<Map.Entry<Object, V>> iterator() { return new EntriesIterator(); } @Override public Iterable<Object> keys() { return new KeysIterable(); } @Override public void getValuesBetween(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener) { throw new UnsupportedOperationException("getValuesBetween"); } @Override public void getValuesMajor(Object fromKey, boolean isInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener) { throw new UnsupportedOperationException("getValuesMajor"); } @Override public void getValuesMinor(Object toKey, boolean isInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener) { throw new UnsupportedOperationException("getValuesMinor"); } @Override public void getEntriesMajor(Object fromKey, boolean isInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener) { throw new UnsupportedOperationException("getEntriesMajor"); } @Override public void getEntriesMinor(Object toKey, boolean isInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener) { throw new UnsupportedOperationException("getEntriesMinor"); } @Override public void getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener) { throw new UnsupportedOperationException("getEntriesBetween"); } @Override public long count(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive, int maxValuesToFetch, ValuesTransformer<V> transformer) { throw new UnsupportedOperationException("count"); } @Override public Iterator<V> valuesIterator() { throw new UnsupportedOperationException("valuesIterator"); } @Override public Iterator<V> inverseValuesIterator() { throw new UnsupportedOperationException("inverseValuesIterator"); } @Override public void startTransaction() { } @Override public void stopTransaction() { } @Override public void afterTxRollback() { } @Override public void afterTxCommit() { } @Override public void beforeTxBegin() { } @Override public Iterator<Map.Entry<Object, V>> inverseIterator() { throw new UnsupportedOperationException("inverseIterator"); } private ODatabaseRecord getDatabase() { return ODatabaseRecordThreadLocal.INSTANCE.get(); } private final class EntriesIterator implements Iterator<Map.Entry<Object, V>> { private int size = 0; private int nextEntriesIndex; private OHashIndexBucket.Entry<Object, V>[] entries; private EntriesIterator() { OHashIndexBucket.Entry<Object, V> firstEntry = hashTable.firstEntry(); if (firstEntry == null) entries = new OHashIndexBucket.Entry[0]; else entries = hashTable.ceilingEntries(firstEntry.key); size += entries.length; } @Override public boolean hasNext() { return entries.length > 0; } @Override public Map.Entry<Object, V> next() { if (entries.length == 0) throw new NoSuchElementException(); final OHashIndexBucket.Entry<Object, V> bucketEntry = entries[nextEntriesIndex]; nextEntriesIndex++; if (nextEntriesIndex >= entries.length) { entries = hashTable.higherEntries(entries[entries.length - 1].key); size += entries.length; nextEntriesIndex = 0; } return new Map.Entry<Object, V>() { @Override public Object getKey() { return bucketEntry.key; } @Override public V getValue() { return bucketEntry.value; } @Override public V setValue(V value) { throw new UnsupportedOperationException("setValue"); } }; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } } private final class KeysIterable implements Iterable<Object> { @Override public Iterator<Object> iterator() { final EntriesIterator entriesIterator = new EntriesIterator(); return new Iterator<Object>() { @Override public boolean hasNext() { return entriesIterator.hasNext(); } @Override public Object next() { return entriesIterator.next().getKey(); } @Override public void remove() { entriesIterator.remove(); } }; } } }
1no label
core_src_main_java_com_orientechnologies_orient_core_index_engine_OLocalHashTableIndexEngine.java
212
public class OConsoleDatabaseApp extends OrientConsole implements OCommandOutputListener, OProgressListener { protected ODatabaseDocument currentDatabase; protected String currentDatabaseName; protected ORecordInternal<?> currentRecord; protected List<OIdentifiable> currentResultSet; protected OServerAdmin serverAdmin; private int lastPercentStep; private String currentDatabaseUserName; private String currentDatabaseUserPassword; public OConsoleDatabaseApp(final String[] args) { super(args); } public static void main(final String[] args) { int result = 0; try { boolean tty = false; try { if (setTerminalToCBreak()) tty = true; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { stty("echo"); } catch (Exception e) { } } }); } catch (Exception e) { } final OConsoleDatabaseApp console = new OConsoleDatabaseApp(args); if (tty) console.setReader(new TTYConsoleReader()); result = console.run(); } finally { try { stty("echo"); } catch (Exception e) { } } System.exit(result); } @Override protected boolean isCollectingCommands(final String iLine) { return iLine.startsWith("js"); } @Override protected void onBefore() { super.onBefore(); currentResultSet = new ArrayList<OIdentifiable>(); OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false); // DISABLE THE NETWORK AND STORAGE TIMEOUTS OGlobalConfiguration.STORAGE_LOCK_TIMEOUT.setValue(0); OGlobalConfiguration.NETWORK_LOCK_TIMEOUT.setValue(0); OGlobalConfiguration.CLIENT_CHANNEL_MIN_POOL.setValue(1); OGlobalConfiguration.CLIENT_CHANNEL_MAX_POOL.setValue(2); properties.put("limit", "20"); properties.put("width", "132"); properties.put("debug", "false"); properties.put("maxBinaryDisplay", "160"); properties.put("verbose", "2"); OCommandManager.instance().registerExecutor(OCommandScript.class, OCommandExecutorScript.class); } @Override protected void onAfter() { super.onAfter(); Orient.instance().shutdown(); } @ConsoleCommand(aliases = { "use database" }, description = "Connect to a database or a remote Server instance") public void connect( @ConsoleParameter(name = "url", description = "The url of the remote server or the database to connect to in the format '<mode>:<path>'") String iURL, @ConsoleParameter(name = "user", description = "User name") String iUserName, @ConsoleParameter(name = "password", description = "User password", optional = true) String iUserPassword) throws IOException { disconnect(); if (iUserPassword == null) { message("Enter password: "); final BufferedReader br = new BufferedReader(new InputStreamReader(this.in)); iUserPassword = br.readLine(); message("\n"); } currentDatabaseUserName = iUserName; currentDatabaseUserPassword = iUserPassword; if (iURL.contains("/")) { // OPEN DB message("Connecting to database [" + iURL + "] with user '" + iUserName + "'..."); currentDatabase = new ODatabaseDocumentTx(iURL); if (currentDatabase == null) throw new OException("Database " + iURL + " not found"); currentDatabase.registerListener(new OConsoleDatabaseListener(this)); currentDatabase.open(iUserName, iUserPassword); currentDatabaseName = currentDatabase.getName(); // if (currentDatabase.getStorage() instanceof OStorageProxy) // serverAdmin = new OServerAdmin(currentDatabase.getStorage().getURL()); } else { // CONNECT TO REMOTE SERVER message("Connecting to remote Server instance [" + iURL + "] with user '" + iUserName + "'..."); serverAdmin = new OServerAdmin(iURL).connect(iUserName, iUserPassword); currentDatabase = null; currentDatabaseName = null; } message("OK"); } @ConsoleCommand(aliases = { "close database" }, description = "Disconnect from the current database") public void disconnect() { if (serverAdmin != null) { message("\nDisconnecting from remote server [" + serverAdmin.getURL() + "]..."); serverAdmin.close(true); serverAdmin = null; message("\nOK"); } if (currentDatabase != null) { message("\nDisconnecting from the database [" + currentDatabaseName + "]..."); final OStorage stg = Orient.instance().getStorage(currentDatabase.getURL()); currentDatabase.close(); // FORCE CLOSING OF STORAGE: THIS CLEAN UP REMOTE CONNECTIONS if (stg != null) stg.close(true); currentDatabase = null; currentDatabaseName = null; currentRecord = null; message("\nOK"); } } @ConsoleCommand(description = "Create a new database") public void createDatabase( @ConsoleParameter(name = "database-url", description = "The url of the database to create in the format '<mode>:<path>'") String iDatabaseURL, @ConsoleParameter(name = "user", description = "Server administrator name") String iUserName, @ConsoleParameter(name = "password", description = "Server administrator password") String iUserPassword, @ConsoleParameter(name = "storage-type", description = "The type of the storage. 'local' and 'plocal' for disk-based databases and 'memory' for in-memory database") String iStorageType, @ConsoleParameter(name = "db-type", optional = true, description = "The type of the database used between 'document' and 'graph'. By default is graph.") String iDatabaseType) throws IOException { if (iDatabaseType == null) iDatabaseType = "graph"; message("\nCreating database [" + iDatabaseURL + "] using the storage type [" + iStorageType + "]..."); currentDatabaseUserName = iUserName; currentDatabaseUserPassword = iUserPassword; if (iDatabaseURL.startsWith(OEngineRemote.NAME)) { // REMOTE CONNECTION final String dbURL = iDatabaseURL.substring(OEngineRemote.NAME.length() + 1); new OServerAdmin(dbURL).connect(iUserName, iUserPassword).createDatabase(iDatabaseType, iStorageType).close(); connect(iDatabaseURL, OUser.ADMIN, OUser.ADMIN); } else { // LOCAL CONNECTION if (iStorageType != null) { // CHECK STORAGE TYPE if (!iDatabaseURL.toLowerCase().startsWith(iStorageType.toLowerCase())) throw new IllegalArgumentException("Storage type '" + iStorageType + "' is different by storage type in URL"); } currentDatabase = Orient.instance().getDatabaseFactory().createDatabase(iDatabaseType, iDatabaseURL); currentDatabase.create(); currentDatabaseName = currentDatabase.getName(); } message("\nDatabase created successfully."); message("\n\nCurrent database is: " + iDatabaseURL); } @ConsoleCommand(description = "List all the databases available on the connected server") public void listDatabases() throws IOException { if (serverAdmin != null) { final Map<String, String> databases = serverAdmin.listDatabases(); message("\nFound %d databases:\n", databases.size()); for (Entry<String, String> database : databases.entrySet()) { message("\n* %s (%s)", database.getKey(), database.getValue().substring(0, database.getValue().indexOf(":"))); } } else { message("\nNot connected to the Server instance. You've to connect to the Server using server's credentials (look at orientdb-*server-config.xml file)"); } out.println(); } @ConsoleCommand(description = "Reload the database schema") public void reloadSchema() throws IOException { message("\nreloading database schema..."); updateDatabaseInfo(); message("\n\nDone."); } @ConsoleCommand(description = "Create a new data-segment in the current database.") public void createDatasegment( @ConsoleParameter(name = "datasegment-name", description = "The name of the data segment to create") final String iName, @ConsoleParameter(name = "datasegment-location", description = "The directory where to place the files", optional = true) final String iLocation) { checkForDatabase(); if (iLocation != null) message("\nCreating data-segment [" + iName + "] in database " + currentDatabaseName + " in path: " + iLocation + "..."); else message("\nCreating data-segment [" + iName + "] in database directory..."); currentDatabase.addDataSegment(iName, iLocation); updateDatabaseInfo(); } @ConsoleCommand(splitInWords = false, description = "Create a new cluster in the current database. The cluster can be physical or memory") public void createCluster( @ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("create", iCommandText, "\nCluster created correctly with id #%d\n", true); updateDatabaseInfo(); } @ConsoleCommand(description = "Remove a cluster in the current database. The cluster can be physical or memory") public void dropCluster( @ConsoleParameter(name = "cluster-name", description = "The name or the id of the cluster to remove") String iClusterName) { checkForDatabase(); message("\nDropping cluster [" + iClusterName + "] in database " + currentDatabaseName + "..."); boolean result = currentDatabase.dropCluster(iClusterName, true); if (!result) { // TRY TO GET AS CLUSTER ID try { int clusterId = Integer.parseInt(iClusterName); if (clusterId > -1) { result = currentDatabase.dropCluster(clusterId, true); } } catch (Exception e) { } } if (result) message("\nCluster correctly removed"); else message("\nCannot find the cluster to remove"); updateDatabaseInfo(); } @ConsoleCommand(splitInWords = false, description = "Alters a cluster in the current database. The cluster can be physical or memory") public void alterCluster(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("alter", iCommandText, "\nCluster updated successfully\n", false); updateDatabaseInfo(); } @ConsoleCommand(description = "Shows the holes in current storage") public void showHoles() throws IOException { checkForDatabase(); if (!(currentDatabase.getStorage() instanceof OStorageLocal)) { message("\nError: cannot show holes in databases different by local"); return; } final OStorageLocal storage = (OStorageLocal) currentDatabase.getStorage(); final List<ODataHoleInfo> result = storage.getHolesList(); message("\nFound " + result.size() + " holes in database " + currentDatabaseName + ":"); message("\n+----------------------+----------------------+"); message("\n| Position | Size (in bytes) |"); message("\n+----------------------+----------------------+"); long size = 0; for (ODataHoleInfo ppos : result) { message("\n| %20d | %20d |", ppos.dataOffset, ppos.size); size += ppos.size; } message("\n+----------------------+----------------------+"); message("\n| %20s | %20s |", "Total hole size", OFileUtils.getSizeAsString(size)); message("\n+----------------------+----------------------+"); } @ConsoleCommand(description = "Begins a transaction. All the changes will remain local") public void begin() throws IOException { checkForDatabase(); if (currentDatabase.getTransaction().isActive()) { message("\nError: an active transaction is currently open (id=" + currentDatabase.getTransaction().getId() + "). Commit or rollback before starting a new one."); return; } currentDatabase.begin(); message("\nTransaction " + currentDatabase.getTransaction().getId() + " is running"); } @ConsoleCommand(description = "Commits transaction changes to the database") public void commit() throws IOException { checkForDatabase(); if (!currentDatabase.getTransaction().isActive()) { message("\nError: no active transaction is currently open."); return; } final long begin = System.currentTimeMillis(); final int txId = currentDatabase.getTransaction().getId(); currentDatabase.commit(); message("\nTransaction " + txId + " has been committed in " + (System.currentTimeMillis() - begin) + "ms"); } @ConsoleCommand(description = "Rolls back transaction changes to the previous state") public void rollback() throws IOException { checkForDatabase(); if (!currentDatabase.getTransaction().isActive()) { message("\nError: no active transaction is running right now."); return; } final long begin = System.currentTimeMillis(); final int txId = currentDatabase.getTransaction().getId(); currentDatabase.rollback(); message("\nTransaction " + txId + " has been rollbacked in " + (System.currentTimeMillis() - begin) + "ms"); } @ConsoleCommand(splitInWords = false, description = "Truncate the class content in the current database") public void truncateClass(@ConsoleParameter(name = "text", description = "The name of the class to truncate") String iCommandText) { sqlCommand("truncate", iCommandText, "\nTruncated %d record(s) in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Truncate the cluster content in the current database") public void truncateCluster( @ConsoleParameter(name = "text", description = "The name of the class to truncate") String iCommandText) { sqlCommand("truncate", iCommandText, "\nTruncated %d record(s) in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Truncate a record deleting it at low level") public void truncateRecord(@ConsoleParameter(name = "text", description = "The record(s) to truncate") String iCommandText) { sqlCommand("truncate", iCommandText, "\nTruncated %d record(s) in %f sec(s).\n", true); } @ConsoleCommand(description = "Load a record in memory using passed fetch plan") public void loadRecord( @ConsoleParameter(name = "record-id", description = "The unique Record Id of the record to load. If you do not have the Record Id, execute a query first") String iRecordId, @ConsoleParameter(name = "fetch-plan", description = "The fetch plan to load the record with") String iFetchPlan) { loadRecordInternal(iRecordId, iFetchPlan); } @ConsoleCommand(description = "Load a record in memory and set it as the current") public void loadRecord( @ConsoleParameter(name = "record-id", description = "The unique Record Id of the record to load. If you do not have the Record Id, execute a query first") String iRecordId) { loadRecordInternal(iRecordId, null); } @ConsoleCommand(description = "Reloads a record using passed fetch plan") public void reloadRecord( @ConsoleParameter(name = "record-id", description = "The unique Record Id of the record to load. If you do not have the Record Id, execute a query first") String iRecordId, @ConsoleParameter(name = "fetch-plan", description = "The fetch plan to load the record with") String iFetchPlan) { reloadRecordInternal(iRecordId, iFetchPlan); } @ConsoleCommand(description = "Reload a record and set it as the current one") public void reloadRecord( @ConsoleParameter(name = "record-id", description = "The unique Record Id of the record to load. If you do not have the Record Id, execute a query first") String iRecordId) { reloadRecordInternal(iRecordId, null); } @ConsoleCommand(splitInWords = false, description = "Explain how a command is executed profiling it") public void explain(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { Object result = sqlCommand("explain", iCommandText, "\nProfiled command '%s' in %f sec(s):\n", true); if (result != null && result instanceof ODocument) { message(((ODocument) result).toJSON()); } } @ConsoleCommand(splitInWords = false, description = "Executes a command inside a transaction") public void transactional(@ConsoleParameter(name = "command-text", description = "The command to execute") String iCommandText) { sqlCommand("transactional", iCommandText, "\nResult: '%s'. Executed in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Insert a new record into the database") public void insert(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("insert", iCommandText, "\nInserted record '%s' in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Create a new vertex into the database") public void createVertex(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("create", iCommandText, "\nCreated vertex '%s' in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Create a new edge into the database") public void createEdge(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("create", iCommandText, "\nCreated edge '%s' in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Update records in the database") public void update(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("update", iCommandText, "\nUpdated %d record(s) in %f sec(s).\n", true); updateDatabaseInfo(); currentDatabase.getLevel1Cache().invalidate(); currentDatabase.getLevel2Cache().clear(); } @ConsoleCommand(splitInWords = false, description = "Delete records from the database") public void delete(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("delete", iCommandText, "\nDelete %d record(s) in %f sec(s).\n", true); updateDatabaseInfo(); currentDatabase.getLevel1Cache().invalidate(); currentDatabase.getLevel2Cache().clear(); } @ConsoleCommand(splitInWords = false, description = "Grant privileges to a role") public void grant(@ConsoleParameter(name = "text", description = "Grant command") String iCommandText) { sqlCommand("grant", iCommandText, "\nPrivilege granted to the role: %s\n", true); } @ConsoleCommand(splitInWords = false, description = "Revoke privileges to a role") public void revoke(@ConsoleParameter(name = "text", description = "Revoke command") String iCommandText) { sqlCommand("revoke", iCommandText, "\nPrivilege revoked to the role: %s\n", true); } @ConsoleCommand(splitInWords = false, description = "Create a link from a JOIN") public void createLink(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("create", iCommandText, "\nCreated %d link(s) in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Find all references the target record id @rid") public void findReferences( @ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("find", iCommandText, "\nFound %s in %f sec(s).\n", true); } @ConsoleCommand(splitInWords = false, description = "Alter a database property") public void alterDatabase( @ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("alter", iCommandText, "\nDatabase updated successfully\n", false); updateDatabaseInfo(); } @ConsoleCommand(description = "Freeze database and flush on the disk") public void freezeDatabase( @ConsoleParameter(name = "storage-type", description = "Storage type of server database", optional = true) String storageType) throws IOException { checkForDatabase(); final String dbName = currentDatabase.getName(); if (currentDatabase.getURL().startsWith(OEngineRemote.NAME)) { if (serverAdmin == null) { message("\n\nCannot freeze a remote database without connecting to the server with a valid server's user"); return; } if (storageType == null) storageType = "plocal"; new OServerAdmin(currentDatabase.getURL()).connect(currentDatabaseUserName, currentDatabaseUserPassword).freezeDatabase( storageType); } else { // LOCAL CONNECTION currentDatabase.freeze(); } message("\n\nDatabase '" + dbName + "' was frozen successfully"); } @ConsoleCommand(description = "Release database after freeze") public void releaseDatabase( @ConsoleParameter(name = "storage-type", description = "Storage type of server database", optional = true) String storageType) throws IOException { checkForDatabase(); final String dbName = currentDatabase.getName(); if (currentDatabase.getURL().startsWith(OEngineRemote.NAME)) { if (serverAdmin == null) { message("\n\nCannot release a remote database without connecting to the server with a valid server's user"); return; } if (storageType == null) storageType = "plocal"; new OServerAdmin(currentDatabase.getURL()).connect(currentDatabaseUserName, currentDatabaseUserPassword).releaseDatabase( storageType); } else { // LOCAL CONNECTION currentDatabase.release(); } message("\n\nDatabase '" + dbName + "' was released successfully"); } @ConsoleCommand(description = "Freeze clusters and flush on the disk") public void freezeCluster( @ConsoleParameter(name = "cluster-name", description = "The name of the cluster to freeze") String iClusterName, @ConsoleParameter(name = "storage-type", description = "Storage type of server database", optional = true) String storageType) throws IOException { checkForDatabase(); final int clusterId = currentDatabase.getClusterIdByName(iClusterName); if (currentDatabase.getURL().startsWith(OEngineRemote.NAME)) { if (serverAdmin == null) { message("\n\nCannot freeze a remote database without connecting to the server with a valid server's user"); return; } if (storageType == null) storageType = "plocal"; new OServerAdmin(currentDatabase.getURL()).connect(currentDatabaseUserName, currentDatabaseUserPassword).freezeCluster( clusterId, storageType); } else { // LOCAL CONNECTION currentDatabase.freezeCluster(clusterId); } message("\n\nCluster '" + iClusterName + "' was frozen successfully"); } @ConsoleCommand(description = "Release cluster after freeze") public void releaseCluster( @ConsoleParameter(name = "cluster-name", description = "The name of the cluster to unfreeze") String iClusterName, @ConsoleParameter(name = "storage-type", description = "Storage type of server database", optional = true) String storageType) throws IOException { checkForDatabase(); final int clusterId = currentDatabase.getClusterIdByName(iClusterName); if (currentDatabase.getURL().startsWith(OEngineRemote.NAME)) { if (serverAdmin == null) { message("\n\nCannot freeze a remote database without connecting to the server with a valid server's user"); return; } if (storageType == null) storageType = "plocal"; new OServerAdmin(currentDatabase.getURL()).connect(currentDatabaseUserName, currentDatabaseUserPassword).releaseCluster( clusterId, storageType); } else { // LOCAL CONNECTION currentDatabase.releaseCluster(clusterId); } message("\n\nCluster '" + iClusterName + "' was released successfully"); } @ConsoleCommand(splitInWords = false, description = "Alter a class in the database schema") public void alterClass(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("alter", iCommandText, "\nClass updated successfully\n", false); updateDatabaseInfo(); } @ConsoleCommand(splitInWords = false, description = "Create a class") public void createClass(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("create", iCommandText, "\nClass created successfully. Total classes in database now: %d\n", true); updateDatabaseInfo(); } @ConsoleCommand(splitInWords = false, description = "Alter a class property in the database schema") public void alterProperty( @ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("alter", iCommandText, "\nProperty updated successfully\n", false); updateDatabaseInfo(); } @ConsoleCommand(splitInWords = false, description = "Create a property") public void createProperty( @ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("create", iCommandText, "\nProperty created successfully with id=%d\n", true); updateDatabaseInfo(); } /*** * @author Claudio Tesoriero * @param iCommandText */ @ConsoleCommand(splitInWords = false, description = "Create a stored function") public void createFunction( @ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) { sqlCommand("create", iCommandText, "\nFunction created successfully with id=%s\n", true); updateDatabaseInfo(); } @ConsoleCommand(splitInWords = false, description = "Traverse records and display the results") public void traverse(@ConsoleParameter(name = "query-text", description = "The traverse to execute") String iQueryText) { final int limit; if (iQueryText.contains("limit")) { // RESET CONSOLE FLAG limit = -1; } else { limit = Integer.parseInt((String) properties.get("limit")); } long start = System.currentTimeMillis(); currentResultSet = currentDatabase.command(new OCommandSQL("traverse " + iQueryText)).execute(); float elapsedSeconds = getElapsedSecs(start); dumpResultSet(limit); message("\n\n" + currentResultSet.size() + " item(s) found. Traverse executed in " + elapsedSeconds + " sec(s)."); } @ConsoleCommand(splitInWords = false, description = "Execute a query against the database and display the results") public void select(@ConsoleParameter(name = "query-text", description = "The query to execute") String iQueryText) { checkForDatabase(); if (iQueryText == null) return; iQueryText = iQueryText.trim(); if (iQueryText.length() == 0 || iQueryText.equalsIgnoreCase("select")) return; iQueryText = "select " + iQueryText; final int limit; if (iQueryText.contains("limit")) { limit = -1; } else { limit = Integer.parseInt((String) properties.get("limit")); } final long start = System.currentTimeMillis(); currentResultSet = currentDatabase.query(new OSQLSynchQuery<ODocument>(iQueryText, limit).setFetchPlan("*:1")); float elapsedSeconds = getElapsedSecs(start); dumpResultSet(limit); message("\n\n" + currentResultSet.size() + " item(s) found. Query executed in " + elapsedSeconds + " sec(s)."); } @SuppressWarnings("unchecked") @ConsoleCommand(splitInWords = false, description = "Execute javascript commands in the console") public void js( @ConsoleParameter(name = "text", description = "The javascript to execute. Use 'db' to reference to a document database, 'gdb' for a graph database") final String iText) { if (iText == null) return; currentResultSet.clear(); final OCommandExecutorScript cmd = new OCommandExecutorScript(); cmd.parse(new OCommandScript("Javascript", iText)); long start = System.currentTimeMillis(); final Object result = cmd.execute(null); float elapsedSeconds = getElapsedSecs(start); if (OMultiValue.isMultiValue(result)) { if (result instanceof List<?>) currentResultSet = (List<OIdentifiable>) result; else if (result instanceof Collection<?>) { currentResultSet = new ArrayList<OIdentifiable>(); currentResultSet.addAll((Collection<? extends OIdentifiable>) result); } else if (result.getClass().isArray()) { currentResultSet = new ArrayList<OIdentifiable>(); for (OIdentifiable o : (OIdentifiable[]) result) currentResultSet.add(o); } dumpResultSet(-1); message("Client side script executed in %f sec(s). Returned %d records", elapsedSeconds, currentResultSet.size()); } else message("Client side script executed in %f sec(s). Value returned is: %s", elapsedSeconds, result); } @SuppressWarnings("unchecked") @ConsoleCommand(splitInWords = false, description = "Execute javascript commands against a remote server") public void jss( @ConsoleParameter(name = "text", description = "The javascript to execute. Use 'db' to reference to a document database, 'gdb' for a graph database") final String iText) { checkForRemoteServer(); if (iText == null) return; currentResultSet.clear(); long start = System.currentTimeMillis(); Object result = currentDatabase.command(new OCommandScript("Javascript", iText.toString())).execute(); float elapsedSeconds = getElapsedSecs(start); if (OMultiValue.isMultiValue(result)) { if (result instanceof List<?>) currentResultSet = (List<OIdentifiable>) result; else if (result instanceof Collection<?>) { currentResultSet = new ArrayList<OIdentifiable>(); currentResultSet.addAll((Collection<? extends OIdentifiable>) result); } else if (result.getClass().isArray()) { currentResultSet = new ArrayList<OIdentifiable>(); for (OIdentifiable o : (OIdentifiable[]) result) currentResultSet.add(o); } dumpResultSet(-1); message("Server side script executed in %f sec(s). Returned %d records", elapsedSeconds, currentResultSet.size()); } else message("Server side script executed in %f sec(s). Value returned is: %s", elapsedSeconds, result); } @ConsoleCommand(splitInWords = false, description = "Create an index against a property") public void createIndex(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) throws IOException { message("\n\nCreating index..."); sqlCommand("create", iCommandText, "\nCreated index successfully with %d entries in %f sec(s).\n", true); updateDatabaseInfo(); message("\n\nIndex created successfully"); } @ConsoleCommand(description = "Delete the current database") public void dropDatabase( @ConsoleParameter(name = "storage-type", description = "Storage type of server database", optional = true) String storageType) throws IOException { checkForDatabase(); final String dbName = currentDatabase.getName(); if (currentDatabase.getURL().startsWith(OEngineRemote.NAME)) { if (serverAdmin == null) { message("\n\nCannot drop a remote database without connecting to the server with a valid server's user"); return; } if (storageType == null) storageType = "plocal"; // REMOTE CONNECTION final String dbURL = currentDatabase.getURL().substring(OEngineRemote.NAME.length() + 1); new OServerAdmin(dbURL).connect(currentDatabaseUserName, currentDatabaseUserPassword).dropDatabase(storageType); } else { // LOCAL CONNECTION currentDatabase.drop(); currentDatabase = null; currentDatabaseName = null; } message("\n\nDatabase '" + dbName + "' deleted successfully"); } @ConsoleCommand(description = "Delete the specified database") public void dropDatabase( @ConsoleParameter(name = "database-url", description = "The url of the database to drop in the format '<mode>:<path>'") String iDatabaseURL, @ConsoleParameter(name = "user", description = "Server administrator name") String iUserName, @ConsoleParameter(name = "password", description = "Server administrator password") String iUserPassword, @ConsoleParameter(name = "storage-type", description = "Storage type of server database", optional = true) String storageType) throws IOException { if (iDatabaseURL.startsWith(OEngineRemote.NAME)) { // REMOTE CONNECTION final String dbURL = iDatabaseURL.substring(OEngineRemote.NAME.length() + 1); if (serverAdmin != null) serverAdmin.close(); serverAdmin = new OServerAdmin(dbURL).connect(iUserName, iUserPassword); serverAdmin.dropDatabase(storageType); disconnect(); } else { // LOCAL CONNECTION currentDatabase = new ODatabaseDocumentTx(iDatabaseURL); if (currentDatabase.exists()) { currentDatabase.open(iUserName, iUserPassword); currentDatabase.drop(); } else message("\n\nCannot drop database '" + iDatabaseURL + "' because was not found"); currentDatabase = null; currentDatabaseName = null; } message("\n\nDatabase '" + iDatabaseURL + "' deleted successfully"); } @ConsoleCommand(splitInWords = false, description = "Remove an index") public void dropIndex(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) throws IOException { message("\n\nRemoving index..."); sqlCommand("drop", iCommandText, "\nDropped index in %f sec(s).\n", false); updateDatabaseInfo(); message("\n\nIndex removed successfully"); } @ConsoleCommand(splitInWords = false, description = "Rebuild an index if it is automatic") public void rebuildIndex(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) throws IOException { message("\n\nRebuilding index(es)..."); sqlCommand("rebuild", iCommandText, "\nRebuilt index(es). Found %d link(s) in %f sec(s).\n", true); updateDatabaseInfo(); message("\n\nIndex(es) rebuilt successfully"); } @ConsoleCommand(splitInWords = false, description = "Remove a class from the schema") public void dropClass(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) throws IOException { sqlCommand("drop", iCommandText, "\nRemoved class in %f sec(s).\n", false); updateDatabaseInfo(); } @ConsoleCommand(splitInWords = false, description = "Remove a property from a class") public void dropProperty(@ConsoleParameter(name = "command-text", description = "The command text to execute") String iCommandText) throws IOException { sqlCommand("drop", iCommandText, "\nRemoved class property in %f sec(s).\n", false); updateDatabaseInfo(); } @ConsoleCommand(description = "Browse all records of a class") public void browseClass(@ConsoleParameter(name = "class-name", description = "The name of the class") final String iClassName) { checkForDatabase(); currentResultSet.clear(); final int limit = Integer.parseInt((String) properties.get("limit")); OIdentifiableIterator<?> it = currentDatabase.browseClass(iClassName); browseRecords(limit, it); } @ConsoleCommand(description = "Browse all records of a cluster") public void browseCluster( @ConsoleParameter(name = "cluster-name", description = "The name of the cluster") final String iClusterName) { checkForDatabase(); currentResultSet.clear(); final int limit = Integer.parseInt((String) properties.get("limit")); final ORecordIteratorCluster<?> it = currentDatabase.browseCluster(iClusterName); browseRecords(limit, it); } @ConsoleCommand(aliases = { "display" }, description = "Display current record attributes") public void displayRecord( @ConsoleParameter(name = "number", description = "The number of the record in the most recent result set") final String iRecordNumber) { checkForDatabase(); if (iRecordNumber == null) checkCurrentObject(); else { int recNumber = Integer.parseInt(iRecordNumber); if (currentResultSet.size() == 0) throw new OException("No result set where to find the requested record. Execute a query first."); if (currentResultSet.size() <= recNumber) throw new OException("The record requested is not part of current result set (0" + (currentResultSet.size() > 0 ? "-" + (currentResultSet.size() - 1) : "") + ")"); currentRecord = currentResultSet.get(recNumber).getRecord(); } dumpRecordDetails(); } @ConsoleCommand(description = "Display a record as raw bytes") public void displayRawRecord(@ConsoleParameter(name = "rid", description = "The record id to display") final String iRecordId) { checkForDatabase(); ORecordId rid = new ORecordId(iRecordId); final ORawBuffer buffer = currentDatabase.getStorage().readRecord(rid, null, false, null, false).getResult(); if (buffer == null) throw new OException("The record has been deleted"); String content; if (Integer.parseInt(properties.get("maxBinaryDisplay")) < buffer.buffer.length) content = new String(Arrays.copyOf(buffer.buffer, Integer.parseInt(properties.get("maxBinaryDisplay")))); else content = new String(buffer.buffer); message("\nRaw record content. The size is " + buffer.buffer.length + " bytes, while settings force to print first " + content.length() + " bytes:\n\n" + new String(content)); } @ConsoleCommand(aliases = { "status" }, description = "Display information about the database") public void info() { if (currentDatabaseName != null) { message("\nCurrent database: " + currentDatabaseName + " (url=" + currentDatabase.getURL() + ")"); final OStorage stg = currentDatabase.getStorage(); if (stg instanceof OStorageRemoteThread) { final ODocument clusterConfig = ((OStorageRemoteThread) stg).getClusterConfiguration(); if (clusterConfig != null) message("\n\nCluster configuration: " + clusterConfig.toJSON("prettyPrint")); else message("\n\nCluster configuration: none"); } else if (stg instanceof OStorageLocal) { final OStorageLocal localStorage = (OStorageLocal) stg; long holeSize = localStorage.getHoleSize(); message("\nFragmented at " + (float) (holeSize * 100f / localStorage.getSize()) + "%%"); message("\n (" + localStorage.getHoles() + " holes, total size of holes: " + OFileUtils.getSizeAsString(holeSize) + ")"); } listProperties(); listClusters(); listClasses(); listIndexes(); } } @ConsoleCommand(description = "Display the database properties") public void listProperties() { if (currentDatabase == null) return; final OStorage stg = currentDatabase.getStorage(); final OStorageConfiguration dbCfg = stg.getConfiguration(); message("\n\nDATABASE PROPERTIES:"); if (dbCfg.properties != null) { message("\n--------------------------------+----------------------------------------------------+"); message("\n NAME | VALUE |"); message("\n--------------------------------+----------------------------------------------------+"); message("\n %-30s | %-50s |", "Name", format(dbCfg.name, 50)); message("\n %-30s | %-50s |", "Version", format("" + dbCfg.version, 50)); message("\n %-30s | %-50s |", "Date format", format(dbCfg.dateFormat, 50)); message("\n %-30s | %-50s |", "Datetime format", format(dbCfg.dateTimeFormat, 50)); message("\n %-30s | %-50s |", "Schema RID", format(dbCfg.schemaRecordId, 50)); message("\n %-30s | %-50s |", "Index Manager RID", format(dbCfg.indexMgrRecordId, 50)); message("\n %-30s | %-50s |", "Dictionary RID", format(dbCfg.dictionaryRecordId, 50)); message("\n--------------------------------+----------------------------------------------------+"); if (dbCfg.properties != null && !dbCfg.properties.isEmpty()) { message("\n\nDATABASE CUSTOM PROPERTIES:"); message("\n +-------------------------------+--------------------------------------------------+"); message("\n | NAME | VALUE |"); message("\n +-------------------------------+--------------------------------------------------+"); for (OStorageEntryConfiguration cfg : dbCfg.properties) message("\n | %-29s | %-49s|", cfg.name, format(cfg.value, 49)); message("\n +-------------------------------+--------------------------------------------------+"); } } } @ConsoleCommand(aliases = { "desc" }, description = "Display the schema of a class") public void infoClass(@ConsoleParameter(name = "class-name", description = "The name of the class") final String iClassName) { if (currentDatabaseName == null) { message("\nNo database selected yet."); return; } final OClass cls = currentDatabase.getMetadata().getSchema().getClass(iClassName); if (cls == null) { message("\n! Class '" + iClassName + "' does not exist in the database '" + currentDatabaseName + "'"); return; } message("\nClass................: " + cls); if (cls.getShortName() != null) message("\nAlias................: " + cls.getShortName()); if (cls.getSuperClass() != null) message("\nSuper class..........: " + cls.getSuperClass()); message("\nDefault cluster......: " + currentDatabase.getClusterNameById(cls.getDefaultClusterId()) + " (id=" + cls.getDefaultClusterId() + ")"); message("\nSupported cluster ids: " + Arrays.toString(cls.getClusterIds())); if (cls.getBaseClasses().hasNext()) { message("Base classes.........: "); int i = 0; for (Iterator<OClass> it = cls.getBaseClasses(); it.hasNext();) { if (i > 0) message(", "); message(it.next().getName()); ++i; } out.println(); } if (cls.properties().size() > 0) { message("\nProperties:"); message("\n-------------------------------+-------------+-------------------------------+-----------+----------+----------+-----------+-----------+----------+"); message("\n NAME | TYPE | LINKED TYPE/CLASS | MANDATORY | READONLY | NOT NULL | MIN | MAX | COLLATE |"); message("\n-------------------------------+-------------+-------------------------------+-----------+----------+----------+-----------+-----------+----------+"); for (final OProperty p : cls.properties()) { try { message("\n %-30s| %-12s| %-30s| %-10s| %-9s| %-9s| %-10s| %-10s| %-9s|", p.getName(), p.getType(), p.getLinkedClass() != null ? p.getLinkedClass() : p.getLinkedType(), p.isMandatory(), p.isReadonly(), p.isNotNull(), p.getMin() != null ? p.getMin() : "", p.getMax() != null ? p.getMax() : "", p.getCollate() != null ? p.getCollate().getName() : ""); } catch (Exception e) { } } message("\n-------------------------------+-------------+-------------------------------+-----------+----------+----------+-----------+-----------+----------+"); } final Set<OIndex<?>> indexes = cls.getClassIndexes(); if (!indexes.isEmpty()) { message("\nIndexes (" + indexes.size() + " altogether):"); message("\n-------------------------------+----------------+"); message("\n NAME | PROPERTIES |"); message("\n-------------------------------+----------------+"); for (final OIndex<?> index : indexes) { final OIndexDefinition indexDefinition = index.getDefinition(); if (indexDefinition != null) { final List<String> fields = indexDefinition.getFields(); message("\n %-30s| %-15s|", index.getName(), fields.get(0) + (fields.size() > 1 ? " (+)" : "")); for (int i = 1; i < fields.size(); i++) { if (i < fields.size() - 1) message("\n %-30s| %-15s|", "", fields.get(i) + " (+)"); else message("\n %-30s| %-15s|", "", fields.get(i)); } } else { message("\n %-30s| %-15s|", index.getName(), ""); } } message("\n-------------------------------+----------------+"); } } @ConsoleCommand(description = "Display all indexes", aliases = { "indexes" }) public void listIndexes() { if (currentDatabaseName != null) { message("\n\nINDEXES:"); message("\n----------------------------------------------+------------+-----------------------+----------------+------------+"); message("\n NAME | TYPE | CLASS | FIELDS | RECORDS |"); message("\n----------------------------------------------+------------+-----------------------+----------------+------------+"); int totalIndexes = 0; long totalRecords = 0; final List<OIndex<?>> indexes = new ArrayList<OIndex<?>>(currentDatabase.getMetadata().getIndexManager().getIndexes()); Collections.sort(indexes, new Comparator<OIndex<?>>() { public int compare(OIndex<?> o1, OIndex<?> o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); for (final OIndex<?> index : indexes) { try { final OIndexDefinition indexDefinition = index.getDefinition(); if (indexDefinition == null || indexDefinition.getClassName() == null) { message("\n %-45s| %-10s | %-22s| %-15s|%11d |", format(index.getName(), 45), format(index.getType(), 10), "", "", index.getSize()); } else { final List<String> fields = indexDefinition.getFields(); if (fields.size() == 1) { message("\n %-45s| %-10s | %-22s| %-15s|%11d |", format(index.getName(), 45), format(index.getType(), 10), format(indexDefinition.getClassName(), 22), format(fields.get(0), 10), index.getSize()); } else { message("\n %-45s| %-10s | %-22s| %-15s|%11d |", format(index.getName(), 45), format(index.getType(), 10), format(indexDefinition.getClassName(), 22), format(fields.get(0), 10), index.getSize()); for (int i = 1; i < fields.size(); i++) { message("\n %-45s| %-10s | %-22s| %-15s|%11s |", "", "", "", fields.get(i), ""); } } } totalIndexes++; totalRecords += index.getSize(); } catch (Exception e) { } } message("\n----------------------------------------------+------------+-----------------------+----------------+------------+"); message("\n TOTAL = %-3d %15d |", totalIndexes, totalRecords); message("\n-----------------------------------------------------------------------------------------------------------------+"); } else message("\nNo database selected yet."); } @ConsoleCommand(description = "Display all the configured clusters", aliases = { "clusters" }) public void listClusters() { if (currentDatabaseName != null) { message("\n\nCLUSTERS:"); message("\n----------------------------------------------+-------+---------------------+---------+-----------------+"); message("\n NAME | ID | TYPE | DATASEG | RECORDS |"); message("\n----------------------------------------------+-------+---------------------+---------+-----------------+"); int clusterId; String clusterType = null; long totalElements = 0; long count; final List<String> clusters = new ArrayList<String>(currentDatabase.getClusterNames()); Collections.sort(clusters); for (String clusterName : clusters) { try { clusterId = currentDatabase.getClusterIdByName(clusterName); clusterType = currentDatabase.getClusterType(clusterName); final OCluster cluster = currentDatabase.getStorage().getClusterById(clusterId); count = currentDatabase.countClusterElements(clusterName); totalElements += count; message("\n %-45s| %5d | %-20s| %7d | %15d |", format(clusterName, 45), clusterId, clusterType, cluster.getDataSegmentId(), count); } catch (Exception e) { } } message("\n----------------------------------------------+-------+---------------------+---------+-----------------+"); message("\n TOTAL = %-3d | | %15s |", clusters.size(), totalElements); message("\n----------------------------------------------------------------------------+---------+-----------------+"); } else message("\nNo database selected yet."); } @ConsoleCommand(description = "Display all the configured classes", aliases = { "classes" }) public void listClasses() { if (currentDatabaseName != null) { message("\n\nCLASSES:"); message("\n----------------------------------------------+------------------------------------+------------+----------------+"); message("\n NAME | SUPERCLASS | CLUSTERS | RECORDS |"); message("\n----------------------------------------------+------------------------------------+------------+----------------+"); long totalElements = 0; long count; final List<OClass> classes = new ArrayList<OClass>(currentDatabase.getMetadata().getSchema().getClasses()); Collections.sort(classes, new Comparator<OClass>() { public int compare(OClass o1, OClass o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); for (OClass cls : classes) { try { final StringBuilder clusters = new StringBuilder(); if (cls.isAbstract()) clusters.append("-"); else for (int i = 0; i < cls.getClusterIds().length; ++i) { if (i > 0) clusters.append(", "); clusters.append(cls.getClusterIds()[i]); } count = currentDatabase.countClass(cls.getName()); totalElements += count; final String superClass = cls.getSuperClass() != null ? cls.getSuperClass().getName() : ""; message("\n %-45s| %-35s| %-11s|%15d |", format(cls.getName(), 45), format(superClass, 35), clusters.toString(), count); } catch (Exception e) { } } message("\n----------------------------------------------+------------------------------------+------------+----------------+"); message("\n TOTAL = %-3d %15d |", classes.size(), totalElements); message("\n----------------------------------------------+------------------------------------+------------+----------------+"); } else message("\nNo database selected yet."); } @ConsoleCommand(description = "Display all keys in the database dictionary") public void dictionaryKeys() { checkForDatabase(); Iterable<Object> keys = currentDatabase.getDictionary().keys(); int i = 0; for (Object k : keys) { message(String.format("\n#%d: %s", i++, k)); } message("\nFound " + i + " keys:"); } @ConsoleCommand(description = "Loook up a record using the dictionary. If found, set it as the current record") public void dictionaryGet(@ConsoleParameter(name = "key", description = "The key to search") final String iKey) { checkForDatabase(); currentRecord = currentDatabase.getDictionary().get(iKey); if (currentRecord == null) message("\nEntry not found in dictionary."); else { currentRecord = (ORecordInternal<?>) currentRecord.load(); displayRecord(null); } } @ConsoleCommand(description = "Insert or modify an entry in the database dictionary. The entry is comprised of key=String, value=record-id") public void dictionaryPut(@ConsoleParameter(name = "key", description = "The key to bind") final String iKey, @ConsoleParameter(name = "record-id", description = "The record-id of the record to bind to the key") final String iRecordId) { checkForDatabase(); currentRecord = currentDatabase.load(new ORecordId(iRecordId)); if (currentRecord == null) message("\nError: record with id '" + iRecordId + "' was not found in database"); else { currentDatabase.getDictionary().put(iKey, (ODocument) currentRecord); displayRecord(null); message("\nThe entry " + iKey + "=" + iRecordId + " has been inserted in the database dictionary"); } } @ConsoleCommand(description = "Remove the association in the dictionary") public void dictionaryRemove(@ConsoleParameter(name = "key", description = "The key to remove") final String iKey) { checkForDatabase(); boolean result = currentDatabase.getDictionary().remove(iKey); if (!result) message("\nEntry not found in dictionary."); else message("\nEntry removed from the dictionary."); } @ConsoleCommand(description = "Copy a database to a remote server") public void copyDatabase( @ConsoleParameter(name = "db-name", description = "Name of the database to share") final String iDatabaseName, @ConsoleParameter(name = "db-user", description = "Database user") final String iDatabaseUserName, @ConsoleParameter(name = "db-password", description = "Database password") String iDatabaseUserPassword, @ConsoleParameter(name = "server-name", description = "Remote server's name as <address>:<port>") final String iRemoteName, @ConsoleParameter(name = "engine-name", description = "Remote server's engine to use between 'local' or 'memory'") final String iRemoteEngine) throws IOException { try { if (serverAdmin == null) throw new IllegalStateException("You must be connected to a remote server to share a database"); message("\nCopying database '" + iDatabaseName + "' to the server '" + iRemoteName + "' via network streaming..."); serverAdmin.copyDatabase(iDatabaseName, iDatabaseUserName, iDatabaseUserPassword, iRemoteName, iRemoteEngine); message("\nDatabase '" + iDatabaseName + "' has been copied to the server '" + iRemoteName + "'"); } catch (Exception e) { printError(e); } } @ConsoleCommand(description = "Displays the status of the cluster nodes") public void clusterStatus() throws IOException { if (serverAdmin == null) throw new IllegalStateException("You must be connected to a remote server to get the cluster status"); checkForRemoteServer(); try { message("\nCluster status:"); out.println(serverAdmin.clusterStatus().toJSON("attribSameRow,alwaysFetchEmbedded,fetchPlan:*:0")); } catch (Exception e) { printError(e); } } @ConsoleCommand(description = "Check database integrity") public void checkDatabase(@ConsoleParameter(name = "options", description = "Options: -v", optional = true) final String iOptions) throws IOException { checkForDatabase(); if (!(currentDatabase.getStorage() instanceof OStorageLocalAbstract)) { message("\nCannot check integrity of non-local database. Connect to it using local mode."); return; } boolean verbose = iOptions != null && iOptions.indexOf("-v") > -1; try { ((OStorageLocalAbstract) currentDatabase.getStorage()).check(verbose, this); } catch (ODatabaseImportException e) { printError(e); } } @ConsoleCommand(description = "Compare two databases") public void compareDatabases( @ConsoleParameter(name = "db1-url", description = "URL of the first database") final String iDb1URL, @ConsoleParameter(name = "db2-url", description = "URL of the second database") final String iDb2URL, @ConsoleParameter(name = "user-name", description = "User name", optional = true) final String iUserName, @ConsoleParameter(name = "user-password", description = "User password", optional = true) final String iUserPassword, @ConsoleParameter(name = "detect-mapping-data", description = "Whether RID mapping data after DB import should be tried to found on the disk.", optional = true) Boolean autoDiscoveringMappingData) throws IOException { try { final ODatabaseCompare compare; if (iUserName == null) compare = new ODatabaseCompare(iDb1URL, iDb2URL, this); else compare = new ODatabaseCompare(iDb1URL, iDb1URL, iUserName, iUserPassword, this); compare.setAutoDetectExportImportMap(autoDiscoveringMappingData != null ? autoDiscoveringMappingData : true); compare.compare(); } catch (ODatabaseExportException e) { printError(e); } } @ConsoleCommand(description = "Import a database into the current one", splitInWords = false) public void importDatabase(@ConsoleParameter(name = "options", description = "Import options") final String text) throws IOException { checkForDatabase(); message("\nImporting " + text + "..."); final List<String> items = OStringSerializerHelper.smartSplit(text, ' '); final String fileName = items.size() <= 0 || (items.get(1)).charAt(0) == '-' ? null : items.get(1); final String options = fileName != null ? text.substring((items.get(0)).length() + (items.get(1)).length() + 1).trim() : text; try { ODatabaseImport databaseImport = new ODatabaseImport(currentDatabase, fileName, this); databaseImport.setOptions(options).importDatabase(); databaseImport.close(); } catch (ODatabaseImportException e) { printError(e); } } @ConsoleCommand(description = "Backup a database", splitInWords = false) public void backupDatabase(@ConsoleParameter(name = "options", description = "Backup options") final String iText) throws IOException { checkForDatabase(); out.println(new StringBuilder("Backuping current database to: ").append(iText).append("...")); final List<String> items = OStringSerializerHelper.smartSplit(iText, ' '); final String fileName = items.size() <= 0 || ((String) items.get(1)).charAt(0) == '-' ? null : (String) items.get(1); // final String options = fileName != null ? iText.substring( // ((String) items.get(0)).length() + ((String) items.get(1)).length() + 1).trim() : iText; final long startTime = System.currentTimeMillis(); try { currentDatabase.backup(new FileOutputStream(fileName), null, null); message("\nBackup executed in %.2f seconds", ((float) (System.currentTimeMillis() - startTime) / 1000)); } catch (ODatabaseExportException e) { printError(e); } } @ConsoleCommand(description = "Restore a database into the current one", splitInWords = false) public void restoreDatabase(@ConsoleParameter(name = "options", description = "Restore options") final String text) throws IOException { checkForDatabase(); message("\nRestoring database %s...", text); final List<String> items = OStringSerializerHelper.smartSplit(text, ' '); final String fileName = items.size() <= 0 || (items.get(1)).charAt(0) == '-' ? null : items.get(1); // final String options = fileName != null ? text.substring((items.get(0)).length() + (items.get(1)).length() + 1).trim() : // text; final long startTime = System.currentTimeMillis(); try { currentDatabase.restore(new FileInputStream(fileName), null, null); message("\nDatabase restored in %.2f seconds", ((float) (System.currentTimeMillis() - startTime) / 1000)); } catch (ODatabaseImportException e) { printError(e); } } @ConsoleCommand(description = "Export a database", splitInWords = false) public void exportDatabase(@ConsoleParameter(name = "options", description = "Export options") final String iText) throws IOException { checkForDatabase(); out.println(new StringBuilder("Exporting current database to: ").append(iText).append(" in GZipped JSON format ...")); final List<String> items = OStringSerializerHelper.smartSplit(iText, ' '); final String fileName = items.size() <= 0 || ((String) items.get(1)).charAt(0) == '-' ? null : (String) items.get(1); final String options = fileName != null ? iText.substring( ((String) items.get(0)).length() + ((String) items.get(1)).length() + 1).trim() : iText; try { new ODatabaseExport(currentDatabase, fileName, this).setOptions(options).exportDatabase().close(); } catch (ODatabaseExportException e) { printError(e); } } @ConsoleCommand(description = "Export a database schema") public void exportSchema(@ConsoleParameter(name = "output-file", description = "Output file path") final String iOutputFilePath) throws IOException { checkForDatabase(); message("\nExporting current database to: " + iOutputFilePath + "..."); try { ODatabaseExport exporter = new ODatabaseExport(currentDatabase, iOutputFilePath, this); exporter.setIncludeRecords(false); exporter.exportDatabase().close(); } catch (ODatabaseExportException e) { printError(e); } } @ConsoleCommand(description = "Export the current record in the requested format") public void exportRecord(@ConsoleParameter(name = "format", description = "Format, such as 'json'") final String iFormat, @ConsoleParameter(name = "options", description = "Options", optional = true) String iOptions) throws IOException { checkForDatabase(); checkCurrentObject(); final ORecordSerializer serializer = ORecordSerializerFactory.instance().getFormat(iFormat.toLowerCase()); if (serializer == null) { message("\nERROR: Format '" + iFormat + "' was not found."); printSupportedSerializerFormat(); return; } else if (!(serializer instanceof ORecordSerializerStringAbstract)) { message("\nERROR: Format '" + iFormat + "' does not export as text."); printSupportedSerializerFormat(); return; } if (iOptions == null || iOptions.length() <= 0) { iOptions = "rid,version,class,type,attribSameRow,keepTypes,alwaysFetchEmbedded,fetchPlan:*:0"; } try { out.println(((ORecordSerializerStringAbstract) serializer).toString(currentRecord, iOptions)); } catch (ODatabaseExportException e) { printError(e); } } @ConsoleCommand(description = "Return all configured properties") public void properties() { message("\nPROPERTIES:"); message("\n+---------------------+----------------------+"); message("\n| %-30s| %-30s |", "NAME", "VALUE"); message("\n+---------------------+----------------------+"); for (Entry<String, String> p : properties.entrySet()) { message("\n| %-30s= %-30s |", p.getKey(), p.getValue()); } message("\n+---------------------+----------------------+"); } @ConsoleCommand(description = "Return the value of a property") public void get(@ConsoleParameter(name = "property-name", description = "Name of the property") final String iPropertyName) { Object value = properties.get(iPropertyName); out.println(); if (value == null) message("\nProperty '" + iPropertyName + "' is not setted"); else out.println(iPropertyName + " = " + value); } @ConsoleCommand(description = "Change the value of a property") public void set(@ConsoleParameter(name = "property-name", description = "Name of the property") final String iPropertyName, @ConsoleParameter(name = "property-value", description = "Value to set") final String iPropertyValue) { Object prevValue = properties.get(iPropertyName); out.println(); if (iPropertyName.equalsIgnoreCase("limit") && (Integer.parseInt(iPropertyValue) == 0 || Integer.parseInt(iPropertyValue) < -1)) { message("\nERROR: Limit must be > 0 or = -1 (no limit)"); } else { if (prevValue != null) message("\nPrevious value was: " + prevValue); properties.put(iPropertyName, iPropertyValue); out.println(); out.println(iPropertyName + " = " + iPropertyValue); } } @ConsoleCommand(description = "Declare an intent") public void declareIntent( @ConsoleParameter(name = "Intent name", description = "name of the intent to execute") final String iIntentName) { checkForDatabase(); message("\nDeclaring intent '" + iIntentName + "'..."); if (iIntentName.equalsIgnoreCase("massiveinsert")) currentDatabase.declareIntent(new OIntentMassiveInsert()); else if (iIntentName.equalsIgnoreCase("massiveread")) currentDatabase.declareIntent(new OIntentMassiveRead()); else throw new IllegalArgumentException("Intent '" + iIntentName + "' not supported. Available ones are: massiveinsert, massiveread"); message("\nIntent '" + iIntentName + "' setted successfully"); } @ConsoleCommand(description = "Execute a command against the profiler") public void profiler( @ConsoleParameter(name = "profiler command", description = "command to execute against the profiler") final String iCommandName) { if (iCommandName.equalsIgnoreCase("on")) { Orient.instance().getProfiler().startRecording(); message("\nProfiler is ON now, use 'profiler off' to turn off."); } else if (iCommandName.equalsIgnoreCase("off")) { Orient.instance().getProfiler().stopRecording(); message("\nProfiler is OFF now, use 'profiler on' to turn on."); } else if (iCommandName.equalsIgnoreCase("dump")) { out.println(Orient.instance().getProfiler().dump()); } } @ConsoleCommand(description = "Return the value of a configuration value") public void configGet(@ConsoleParameter(name = "config-name", description = "Name of the configuration") final String iConfigName) throws IOException { final OGlobalConfiguration config = OGlobalConfiguration.findByKey(iConfigName); if (config == null) throw new IllegalArgumentException("Configuration variable '" + iConfigName + "' wasn't found"); final String value; if (serverAdmin != null) { value = serverAdmin.getGlobalConfiguration(config); message("\nRemote configuration: "); } else { value = config.getValueAsString(); message("\nLocal configuration: "); } out.println(iConfigName + " = " + value); } @ConsoleCommand(description = "Sleep X milliseconds") public void sleep(final String iTime) { try { Thread.sleep(Long.parseLong(iTime)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @ConsoleCommand(description = "Change the value of a configuration value") public void configSet( @ConsoleParameter(name = "config-name", description = "Name of the configuration") final String iConfigName, @ConsoleParameter(name = "config-value", description = "Value to set") final String iConfigValue) throws IOException { final OGlobalConfiguration config = OGlobalConfiguration.findByKey(iConfigName); if (config == null) throw new IllegalArgumentException("Configuration variable '" + iConfigName + "' not found"); if (serverAdmin != null) { serverAdmin.setGlobalConfiguration(config, iConfigValue); message("\n\nRemote configuration value changed correctly"); } else { config.setValue(iConfigValue); message("\n\nLocal configuration value changed correctly"); } out.println(); } @ConsoleCommand(description = "Return all the configuration values") public void config() throws IOException { if (serverAdmin != null) { // REMOTE STORAGE final Map<String, String> values = serverAdmin.getGlobalConfigurations(); message("\nREMOTE SERVER CONFIGURATION:"); message("\n+------------------------------------+--------------------------------+"); message("\n| %-35s| %-30s |", "NAME", "VALUE"); message("\n+------------------------------------+--------------------------------+"); for (Entry<String, String> p : values.entrySet()) { message("\n| %-35s= %-30s |", p.getKey(), p.getValue()); } } else { // LOCAL STORAGE message("\nLOCAL SERVER CONFIGURATION:"); message("\n+------------------------------------+--------------------------------+"); message("\n| %-35s| %-30s |", "NAME", "VALUE"); message("\n+------------------------------------+--------------------------------+"); for (OGlobalConfiguration cfg : OGlobalConfiguration.values()) { message("\n| %-35s= %-30s |", cfg.getKey(), cfg.getValue()); } } message("\n+------------------------------------+--------------------------------+"); } /** Should be used only by console commands */ public ODatabaseDocument getCurrentDatabase() { return currentDatabase; } /** Should be used only by console commands */ public String getCurrentDatabaseName() { return currentDatabaseName; } /** Should be used only by console commands */ public String getCurrentDatabaseUserName() { return currentDatabaseUserName; } /** Should be used only by console commands */ public String getCurrentDatabaseUserPassword() { return currentDatabaseUserPassword; } /** Should be used only by console commands */ public ORecordInternal<?> getCurrentRecord() { return currentRecord; } /** Should be used only by console commands */ public List<OIdentifiable> getCurrentResultSet() { return currentResultSet; } /** Should be used only by console commands */ public void loadRecordInternal(String iRecordId, String iFetchPlan) { checkForDatabase(); currentRecord = currentDatabase.load(new ORecordId(iRecordId), iFetchPlan); displayRecord(null); message("\nOK"); } /** Should be used only by console commands */ public void reloadRecordInternal(String iRecordId, String iFetchPlan) { checkForDatabase(); currentRecord = ((ODatabaseRecordAbstract) currentDatabase.getUnderlying()).executeReadRecord(new ORecordId(iRecordId), null, iFetchPlan, true, false); displayRecord(null); message("\nOK"); } /** Should be used only by console commands */ public void checkForRemoteServer() { if (serverAdmin == null && (currentDatabase == null || !(currentDatabase.getStorage() instanceof OStorageRemoteThread) || currentDatabase .isClosed())) throw new OException("Remote server is not connected. Use 'connect remote:<host>[:<port>][/<database-name>]' to connect"); } /** Should be used only by console commands */ public void checkForDatabase() { if (currentDatabase == null) throw new OException("Database not selected. Use 'connect <database-name>' to connect to a database."); if (currentDatabase.isClosed()) throw new ODatabaseException("Database '" + currentDatabaseName + "' is closed"); } /** Should be used only by console commands */ public void checkCurrentObject() { if (currentRecord == null) throw new OException("The is no current object selected: create a new one or load it"); } private void dumpRecordDetails() { if (currentRecord instanceof ODocument) { ODocument rec = (ODocument) currentRecord; message("\n--------------------------------------------------"); message("\nODocument - Class: %s id: %s v.%s", rec.getClassName(), rec.getIdentity().toString(), rec.getRecordVersion() .toString()); message("\n--------------------------------------------------"); Object value; for (String fieldName : rec.fieldNames()) { value = rec.field(fieldName); if (value instanceof byte[]) value = "byte[" + ((byte[]) value).length + "]"; else if (value instanceof Iterator<?>) { final List<Object> coll = new ArrayList<Object>(); while (((Iterator<?>) value).hasNext()) coll.add(((Iterator<?>) value).next()); value = coll; } message("\n%20s : %-20s", fieldName, value); } } else if (currentRecord instanceof ORecordFlat) { ORecordFlat rec = (ORecordFlat) currentRecord; message("\n--------------------------------------------------"); message("\nFlat - record id: %s v.%s", rec.getIdentity().toString(), rec.getRecordVersion().toString()); message("\n--------------------------------------------------"); message(rec.value()); } else if (currentRecord instanceof ORecordBytes) { ORecordBytes rec = (ORecordBytes) currentRecord; message("\n--------------------------------------------------"); message("\nBytes - record id: %s v.%s", rec.getIdentity().toString(), rec.getRecordVersion().toString()); message("\n--------------------------------------------------"); final byte[] value = rec.toStream(); final int max = Math.min(Integer.parseInt(properties.get("maxBinaryDisplay")), Array.getLength(value)); for (int i = 0; i < max; ++i) { message("%03d", Array.getByte(value, i)); } } else { message("\n--------------------------------------------------"); message("\n%s - record id: %s v.%s", currentRecord.getClass().getSimpleName(), currentRecord.getIdentity().toString(), currentRecord.getRecordVersion().toString()); } out.println(); } public String ask(final String iText) { out.print(iText); final Scanner scanner = new Scanner(in); final String answer = scanner.nextLine(); scanner.close(); return answer; } public void onMessage(final String iText) { message(iText); } private void printSupportedSerializerFormat() { message("\nSupported formats are:"); for (ORecordSerializer s : ORecordSerializerFactory.instance().getFormats()) { if (s instanceof ORecordSerializerStringAbstract) message("\n- " + s.toString()); } } private void browseRecords(final int limit, final OIdentifiableIterator<?> it) { final OTableFormatter tableFormatter = new OTableFormatter(this).setMaxWidthSize(Integer.parseInt(properties.get("width"))); currentResultSet.clear(); while (it.hasNext() && currentResultSet.size() <= limit) currentResultSet.add(it.next()); tableFormatter.writeRecords(currentResultSet, limit); } private Object sqlCommand(final String iExpectedCommand, String iReceivedCommand, final String iMessage, final boolean iIncludeResult) { checkForDatabase(); if (iReceivedCommand == null) return null; iReceivedCommand = iExpectedCommand + " " + iReceivedCommand.trim(); currentResultSet.clear(); final long start = System.currentTimeMillis(); final Object result = new OCommandSQL(iReceivedCommand).setProgressListener(this).execute(); float elapsedSeconds = getElapsedSecs(start); if (iIncludeResult) message(iMessage, result, elapsedSeconds); else message(iMessage, elapsedSeconds); return result; } public void onBegin(final Object iTask, final long iTotal) { lastPercentStep = 0; message("["); if (interactiveMode) { for (int i = 0; i < 10; ++i) message(" "); message("] 0%"); } } public boolean onProgress(final Object iTask, final long iCounter, final float iPercent) { final int completitionBar = (int) iPercent / 10; if (((int) (iPercent * 10)) == lastPercentStep) return true; final StringBuilder buffer = new StringBuilder(); if (interactiveMode) { buffer.append("\r["); for (int i = 0; i < completitionBar; ++i) buffer.append('='); for (int i = completitionBar; i < 10; ++i) buffer.append(' '); message("] %3.1f%% ", iPercent); } else { for (int i = lastPercentStep / 100; i < completitionBar; ++i) buffer.append('='); } message(buffer.toString()); lastPercentStep = (int) (iPercent * 10); return true; } @ConsoleCommand(description = "Display the current path") public void pwd() { message("\nCurrent path: " + new File("").getAbsolutePath()); } public void onCompletition(final Object iTask, final boolean iSucceed) { if (interactiveMode) if (iSucceed) message("\r[==========] 100% Done."); else message(" Error!"); else message(iSucceed ? "] Done." : " Error!"); } protected void printApplicationInfo() { message("\nOrientDB console v." + OConstants.getVersion() + " " + OConstants.ORIENT_URL); message("\nType 'help' to display all the commands supported."); } protected static boolean setTerminalToCBreak() throws IOException, InterruptedException { // set the console to be character-buffered instead of line-buffered int result = stty("-icanon min 1"); if (result != 0) { return false; } // disable character echoing stty("-echo"); return true; } protected void dumpResultSet(final int limit) { new OTableFormatter(this).setMaxWidthSize(Integer.parseInt(properties.get("width"))).writeRecords(currentResultSet, limit); } /** * Execute the stty command with the specified arguments against the current active terminal. */ protected static int stty(final String args) throws IOException, InterruptedException { String cmd = "stty " + args + " < /dev/tty"; return exec(new String[] { "sh", "-c", cmd }); } protected float getElapsedSecs(final long start) { return (float) (System.currentTimeMillis() - start) / 1000; } /** * Execute the specified command and return the output (both stdout and stderr). */ protected static int exec(final String[] cmd) throws IOException, InterruptedException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Process p = Runtime.getRuntime().exec(cmd); int c; InputStream in = p.getInputStream(); while ((c = in.read()) != -1) { bout.write(c); } in = p.getErrorStream(); while ((c = in.read()) != -1) { bout.write(c); } p.waitFor(); return p.exitValue(); } protected void printError(final Exception e) { if (properties.get("debug") != null && Boolean.parseBoolean(properties.get("debug").toString())) { message("\n\n!ERROR:"); e.printStackTrace(); } else { // SHORT FORM message("\n\n!ERROR: " + e.getMessage()); if (e.getCause() != null) { Throwable t = e.getCause(); while (t != null) { message("\n-> " + t.getMessage()); t = t.getCause(); } } } } protected void updateDatabaseInfo() { currentDatabase.getStorage().reload(); currentDatabase.getMetadata().getSchema().reload(); currentDatabase.getMetadata().getIndexManager().reload(); } }
1no label
tools_src_main_java_com_orientechnologies_orient_console_OConsoleDatabaseApp.java
77
public final class ClientDataSerializerHook implements DataSerializerHook { public static final int ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.CLIENT_DS_FACTORY, -3); public static final int CLIENT_RESPONSE = 1; @Override public int getFactoryId() { return ID; } @Override public DataSerializableFactory createFactory() { return new DataSerializableFactory() { @Override public IdentifiedDataSerializable create(int typeId) { switch (typeId) { case CLIENT_RESPONSE: return new ClientResponse(); default: return null; } } }; } }
0true
hazelcast_src_main_java_com_hazelcast_client_ClientDataSerializerHook.java
3,127
class FailEngineOnMergeFailure implements MergeSchedulerProvider.FailureListener { @Override public void onFailedMerge(MergePolicy.MergeException e) { failEngine(e); } }
1no label
src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java
86
IN { @Override public boolean evaluate(Object value, Object condition) { Preconditions.checkArgument(isValidCondition(condition), "Invalid condition provided: %s", condition); Collection col = (Collection) condition; return col.contains(value); } @Override public TitanPredicate negate() { return NOT_IN; } },
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Contain.java
285
public interface EncryptionModule { public String encrypt(String plainText); public String decrypt(String cipherText); }
0true
common_src_main_java_org_broadleafcommerce_common_encryption_EncryptionModule.java
2,351
private static class CollectingCombinerFactory<KeyIn, ValueIn> implements CombinerFactory<KeyIn, ValueIn, List<ValueIn>> { @Override public Combiner<KeyIn, ValueIn, List<ValueIn>> newCombiner(KeyIn key) { return new Combiner<KeyIn, ValueIn, List<ValueIn>>() { private final List<ValueIn> values = new ArrayList<ValueIn>(); @Override public void combine(KeyIn key, ValueIn value) { values.add(value); } @Override public List<ValueIn> finalizeChunk() { List<ValueIn> values = new ArrayList<ValueIn>(this.values); this.values.clear(); return values; } }; } }
1no label
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_task_DefaultContext.java
748
public class GetRequest extends SingleShardOperationRequest<GetRequest> { protected String type; protected String id; protected String routing; protected String preference; private String[] fields; private FetchSourceContext fetchSourceContext; private boolean refresh = false; Boolean realtime; private VersionType versionType = VersionType.INTERNAL; private long version = Versions.MATCH_ANY; GetRequest() { type = "_all"; } /** * Constructs a new get request against the specified index. The {@link #type(String)} and {@link #id(String)} * must be set. */ public GetRequest(String index) { super(index); this.type = "_all"; } /** * Constructs a new get request against the specified index with the type and id. * * @param index The index to get the document from * @param type The type of the document * @param id The id of the document */ public GetRequest(String index, String type, String id) { super(index); this.type = type; this.id = id; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (type == null) { validationException = ValidateActions.addValidationError("type is missing", validationException); } if (id == null) { validationException = ValidateActions.addValidationError("id is missing", validationException); } return validationException; } /** * Sets the type of the document to fetch. */ public GetRequest type(@Nullable String type) { if (type == null) { type = "_all"; } this.type = type; return this; } /** * Sets the id of the document to fetch. */ public GetRequest id(String id) { this.id = id; return this; } /** * Sets the parent id of this document. Will simply set the routing to this value, as it is only * used for routing with delete requests. */ public GetRequest parent(String parent) { if (routing == null) { routing = parent; } return this; } /** * Controls the shard routing of the request. Using this value to hash the shard * and not the id. */ public GetRequest routing(String routing) { this.routing = routing; return this; } /** * Sets the preference to execute the search. Defaults to randomize across shards. Can be set to * <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or * a custom value, which guarantees that the same order will be used across different requests. */ public GetRequest preference(String preference) { this.preference = preference; return this; } public String type() { return type; } public String id() { return id; } public String routing() { return this.routing; } public String preference() { return this.preference; } /** * Allows setting the {@link FetchSourceContext} for this request, controlling if and how _source should be returned. */ public GetRequest fetchSourceContext(FetchSourceContext context) { this.fetchSourceContext = context; return this; } public FetchSourceContext fetchSourceContext() { return fetchSourceContext; } /** * Explicitly specify the fields that will be returned. By default, the <tt>_source</tt> * field will be returned. */ public GetRequest fields(String... fields) { this.fields = fields; return this; } /** * Explicitly specify the fields that will be returned. By default, the <tt>_source</tt> * field will be returned. */ public String[] fields() { return this.fields; } /** * Should a refresh be executed before this get operation causing the operation to * return the latest value. Note, heavy get should not set this to <tt>true</tt>. Defaults * to <tt>false</tt>. */ public GetRequest refresh(boolean refresh) { this.refresh = refresh; return this; } public boolean refresh() { return this.refresh; } public boolean realtime() { return this.realtime == null ? true : this.realtime; } public GetRequest realtime(Boolean realtime) { this.realtime = realtime; return this; } /** * Sets the version, which will cause the get operation to only be performed if a matching * version exists and no changes happened on the doc since then. */ public long version() { return version; } public GetRequest version(long version) { this.version = version; return this; } /** * Sets the versioning type. Defaults to {@link org.elasticsearch.index.VersionType#INTERNAL}. */ public GetRequest versionType(VersionType versionType) { this.versionType = versionType; return this; } public VersionType versionType() { return this.versionType; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); type = in.readSharedString(); id = in.readString(); routing = in.readOptionalString(); preference = in.readOptionalString(); refresh = in.readBoolean(); int size = in.readInt(); if (size >= 0) { fields = new String[size]; for (int i = 0; i < size; i++) { fields[i] = in.readString(); } } byte realtime = in.readByte(); if (realtime == 0) { this.realtime = false; } else if (realtime == 1) { this.realtime = true; } this.versionType = VersionType.fromValue(in.readByte()); this.version = in.readVLong(); fetchSourceContext = FetchSourceContext.optionalReadFromStream(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeSharedString(type); out.writeString(id); out.writeOptionalString(routing); out.writeOptionalString(preference); out.writeBoolean(refresh); if (fields == null) { out.writeInt(-1); } else { out.writeInt(fields.length); for (String field : fields) { out.writeString(field); } } if (realtime == null) { out.writeByte((byte) -1); } else if (realtime == false) { out.writeByte((byte) 0); } else { out.writeByte((byte) 1); } out.writeByte(versionType.getValue()); out.writeVLong(version); FetchSourceContext.optionalWriteToStream(fetchSourceContext, out); } @Override public String toString() { return "[" + index + "][" + type + "][" + id + "]: routing [" + routing + "]"; } }
1no label
src_main_java_org_elasticsearch_action_get_GetRequest.java
1,384
public class MappingMetaData { public static class Id { public static final Id EMPTY = new Id(null); private final String path; private final String[] pathElements; public Id(String path) { this.path = path; if (path == null) { pathElements = Strings.EMPTY_ARRAY; } else { pathElements = Strings.delimitedListToStringArray(path, "."); } } public boolean hasPath() { return path != null; } public String path() { return this.path; } public String[] pathElements() { return this.pathElements; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Id id = (Id) o; if (path != null ? !path.equals(id.path) : id.path != null) return false; if (!Arrays.equals(pathElements, id.pathElements)) return false; return true; } @Override public int hashCode() { int result = path != null ? path.hashCode() : 0; result = 31 * result + (pathElements != null ? Arrays.hashCode(pathElements) : 0); return result; } } public static class Routing { public static final Routing EMPTY = new Routing(false, null); private final boolean required; private final String path; private final String[] pathElements; public Routing(boolean required, String path) { this.required = required; this.path = path; if (path == null) { pathElements = Strings.EMPTY_ARRAY; } else { pathElements = Strings.delimitedListToStringArray(path, "."); } } public boolean required() { return required; } public boolean hasPath() { return path != null; } public String path() { return this.path; } public String[] pathElements() { return this.pathElements; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Routing routing = (Routing) o; if (required != routing.required) return false; if (path != null ? !path.equals(routing.path) : routing.path != null) return false; if (!Arrays.equals(pathElements, routing.pathElements)) return false; return true; } @Override public int hashCode() { int result = (required ? 1 : 0); result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (pathElements != null ? Arrays.hashCode(pathElements) : 0); return result; } } public static class Timestamp { public static String parseStringTimestamp(String timestampAsString, FormatDateTimeFormatter dateTimeFormatter) throws TimestampParsingException { long ts; try { // if we manage to parse it, its a millisecond timestamp, just return the string as is ts = Long.parseLong(timestampAsString); return timestampAsString; } catch (NumberFormatException e) { try { ts = dateTimeFormatter.parser().parseMillis(timestampAsString); } catch (RuntimeException e1) { throw new TimestampParsingException(timestampAsString); } } return Long.toString(ts); } public static final Timestamp EMPTY = new Timestamp(false, null, TimestampFieldMapper.DEFAULT_DATE_TIME_FORMAT); private final boolean enabled; private final String path; private final String format; private final String[] pathElements; private final FormatDateTimeFormatter dateTimeFormatter; public Timestamp(boolean enabled, String path, String format) { this.enabled = enabled; this.path = path; if (path == null) { pathElements = Strings.EMPTY_ARRAY; } else { pathElements = Strings.delimitedListToStringArray(path, "."); } this.format = format; this.dateTimeFormatter = Joda.forPattern(format); } public boolean enabled() { return enabled; } public boolean hasPath() { return path != null; } public String path() { return this.path; } public String[] pathElements() { return this.pathElements; } public String format() { return this.format; } public FormatDateTimeFormatter dateTimeFormatter() { return this.dateTimeFormatter; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Timestamp timestamp = (Timestamp) o; if (enabled != timestamp.enabled) return false; if (dateTimeFormatter != null ? !dateTimeFormatter.equals(timestamp.dateTimeFormatter) : timestamp.dateTimeFormatter != null) return false; if (format != null ? !format.equals(timestamp.format) : timestamp.format != null) return false; if (path != null ? !path.equals(timestamp.path) : timestamp.path != null) return false; if (!Arrays.equals(pathElements, timestamp.pathElements)) return false; return true; } @Override public int hashCode() { int result = (enabled ? 1 : 0); result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (format != null ? format.hashCode() : 0); result = 31 * result + (pathElements != null ? Arrays.hashCode(pathElements) : 0); result = 31 * result + (dateTimeFormatter != null ? dateTimeFormatter.hashCode() : 0); return result; } } private final String type; private final CompressedString source; private Id id; private Routing routing; private Timestamp timestamp; private boolean hasParentField; public MappingMetaData(DocumentMapper docMapper) { this.type = docMapper.type(); this.source = docMapper.mappingSource(); this.id = new Id(docMapper.idFieldMapper().path()); this.routing = new Routing(docMapper.routingFieldMapper().required(), docMapper.routingFieldMapper().path()); this.timestamp = new Timestamp(docMapper.timestampFieldMapper().enabled(), docMapper.timestampFieldMapper().path(), docMapper.timestampFieldMapper().dateTimeFormatter().format()); this.hasParentField = docMapper.parentFieldMapper().active(); } public MappingMetaData(CompressedString mapping) throws IOException { this.source = mapping; Map<String, Object> mappingMap = XContentHelper.createParser(mapping.compressed(), 0, mapping.compressed().length).mapOrderedAndClose(); if (mappingMap.size() != 1) { throw new ElasticsearchIllegalStateException("Can't derive type from mapping, no root type: " + mapping.string()); } this.type = mappingMap.keySet().iterator().next(); initMappers((Map<String, Object>) mappingMap.get(this.type)); } public MappingMetaData(Map<String, Object> mapping) throws IOException { this(mapping.keySet().iterator().next(), mapping); } public MappingMetaData(String type, Map<String, Object> mapping) throws IOException { this.type = type; XContentBuilder mappingBuilder = XContentFactory.jsonBuilder().map(mapping); this.source = new CompressedString(mappingBuilder.bytes()); Map<String, Object> withoutType = mapping; if (mapping.size() == 1 && mapping.containsKey(type)) { withoutType = (Map<String, Object>) mapping.get(type); } initMappers(withoutType); } private void initMappers(Map<String, Object> withoutType) { if (withoutType.containsKey("_id")) { String path = null; Map<String, Object> routingNode = (Map<String, Object>) withoutType.get("_id"); for (Map.Entry<String, Object> entry : routingNode.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("path")) { path = fieldNode.toString(); } } this.id = new Id(path); } else { this.id = Id.EMPTY; } if (withoutType.containsKey("_routing")) { boolean required = false; String path = null; Map<String, Object> routingNode = (Map<String, Object>) withoutType.get("_routing"); for (Map.Entry<String, Object> entry : routingNode.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("required")) { required = nodeBooleanValue(fieldNode); } else if (fieldName.equals("path")) { path = fieldNode.toString(); } } this.routing = new Routing(required, path); } else { this.routing = Routing.EMPTY; } if (withoutType.containsKey("_timestamp")) { boolean enabled = false; String path = null; String format = TimestampFieldMapper.DEFAULT_DATE_TIME_FORMAT; Map<String, Object> timestampNode = (Map<String, Object>) withoutType.get("_timestamp"); for (Map.Entry<String, Object> entry : timestampNode.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { enabled = nodeBooleanValue(fieldNode); } else if (fieldName.equals("path")) { path = fieldNode.toString(); } else if (fieldName.equals("format")) { format = fieldNode.toString(); } } this.timestamp = new Timestamp(enabled, path, format); } else { this.timestamp = Timestamp.EMPTY; } if (withoutType.containsKey("_parent")) { this.hasParentField = true; } else { this.hasParentField = false; } } public MappingMetaData(String type, CompressedString source, Id id, Routing routing, Timestamp timestamp, boolean hasParentField) { this.type = type; this.source = source; this.id = id; this.routing = routing; this.timestamp = timestamp; this.hasParentField = hasParentField; } void updateDefaultMapping(MappingMetaData defaultMapping) { if (id == Id.EMPTY) { id = defaultMapping.id(); } if (routing == Routing.EMPTY) { routing = defaultMapping.routing(); } if (timestamp == Timestamp.EMPTY) { timestamp = defaultMapping.timestamp(); } } public String type() { return this.type; } public CompressedString source() { return this.source; } public boolean hasParentField() { return hasParentField; } /** * Converts the serialized compressed form of the mappings into a parsed map. */ public Map<String, Object> sourceAsMap() throws IOException { Map<String, Object> mapping = XContentHelper.convertToMap(source.compressed(), 0, source.compressed().length, true).v2(); if (mapping.size() == 1 && mapping.containsKey(type())) { // the type name is the root value, reduce it mapping = (Map<String, Object>) mapping.get(type()); } return mapping; } /** * Converts the serialized compressed form of the mappings into a parsed map. */ public Map<String, Object> getSourceAsMap() throws IOException { return sourceAsMap(); } public Id id() { return this.id; } public Routing routing() { return this.routing; } public Timestamp timestamp() { return this.timestamp; } public ParseContext createParseContext(@Nullable String id, @Nullable String routing, @Nullable String timestamp) { return new ParseContext( id == null && id().hasPath(), routing == null && routing().hasPath(), timestamp == null && timestamp().hasPath() ); } public void parse(XContentParser parser, ParseContext parseContext) throws IOException { innerParse(parser, parseContext); } private void innerParse(XContentParser parser, ParseContext context) throws IOException { if (!context.parsingStillNeeded()) { return; } XContentParser.Token t = parser.currentToken(); if (t == null) { t = parser.nextToken(); } if (t == XContentParser.Token.START_OBJECT) { t = parser.nextToken(); } String idPart = context.idParsingStillNeeded() ? id().pathElements()[context.locationId] : null; String routingPart = context.routingParsingStillNeeded() ? routing().pathElements()[context.locationRouting] : null; String timestampPart = context.timestampParsingStillNeeded() ? timestamp().pathElements()[context.locationTimestamp] : null; for (; t == XContentParser.Token.FIELD_NAME; t = parser.nextToken()) { // Must point to field name String fieldName = parser.currentName(); // And then the value... t = parser.nextToken(); boolean incLocationId = false; boolean incLocationRouting = false; boolean incLocationTimestamp = false; if (context.idParsingStillNeeded() && fieldName.equals(idPart)) { if (context.locationId + 1 == id.pathElements().length) { if (!t.isValue()) { throw new MapperParsingException("id field must be a value but was either an object or an array"); } context.id = parser.textOrNull(); context.idResolved = true; } else { incLocationId = true; } } if (context.routingParsingStillNeeded() && fieldName.equals(routingPart)) { if (context.locationRouting + 1 == routing.pathElements().length) { context.routing = parser.textOrNull(); context.routingResolved = true; } else { incLocationRouting = true; } } if (context.timestampParsingStillNeeded() && fieldName.equals(timestampPart)) { if (context.locationTimestamp + 1 == timestamp.pathElements().length) { context.timestamp = parser.textOrNull(); context.timestampResolved = true; } else { incLocationTimestamp = true; } } if (incLocationId || incLocationRouting || incLocationTimestamp) { if (t == XContentParser.Token.START_OBJECT) { context.locationId += incLocationId ? 1 : 0; context.locationRouting += incLocationRouting ? 1 : 0; context.locationTimestamp += incLocationTimestamp ? 1 : 0; innerParse(parser, context); context.locationId -= incLocationId ? 1 : 0; context.locationRouting -= incLocationRouting ? 1 : 0; context.locationTimestamp -= incLocationTimestamp ? 1 : 0; } } else { parser.skipChildren(); } if (!context.parsingStillNeeded()) { return; } } } public static void writeTo(MappingMetaData mappingMd, StreamOutput out) throws IOException { out.writeString(mappingMd.type()); mappingMd.source().writeTo(out); // id if (mappingMd.id().hasPath()) { out.writeBoolean(true); out.writeString(mappingMd.id().path()); } else { out.writeBoolean(false); } // routing out.writeBoolean(mappingMd.routing().required()); if (mappingMd.routing().hasPath()) { out.writeBoolean(true); out.writeString(mappingMd.routing().path()); } else { out.writeBoolean(false); } // timestamp out.writeBoolean(mappingMd.timestamp().enabled()); if (mappingMd.timestamp().hasPath()) { out.writeBoolean(true); out.writeString(mappingMd.timestamp().path()); } else { out.writeBoolean(false); } out.writeString(mappingMd.timestamp().format()); out.writeBoolean(mappingMd.hasParentField()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MappingMetaData that = (MappingMetaData) o; if (!id.equals(that.id)) return false; if (!routing.equals(that.routing)) return false; if (!source.equals(that.source)) return false; if (!timestamp.equals(that.timestamp)) return false; if (!type.equals(that.type)) return false; return true; } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + source.hashCode(); result = 31 * result + id.hashCode(); result = 31 * result + routing.hashCode(); result = 31 * result + timestamp.hashCode(); return result; } public static MappingMetaData readFrom(StreamInput in) throws IOException { String type = in.readString(); CompressedString source = CompressedString.readCompressedString(in); // id Id id = new Id(in.readBoolean() ? in.readString() : null); // routing Routing routing = new Routing(in.readBoolean(), in.readBoolean() ? in.readString() : null); // timestamp Timestamp timestamp = new Timestamp(in.readBoolean(), in.readBoolean() ? in.readString() : null, in.readString()); final boolean hasParentField = in.readBoolean(); return new MappingMetaData(type, source, id, routing, timestamp, hasParentField); } public static class ParseContext { final boolean shouldParseId; final boolean shouldParseRouting; final boolean shouldParseTimestamp; int locationId = 0; int locationRouting = 0; int locationTimestamp = 0; boolean idResolved; boolean routingResolved; boolean timestampResolved; String id; String routing; String timestamp; public ParseContext(boolean shouldParseId, boolean shouldParseRouting, boolean shouldParseTimestamp) { this.shouldParseId = shouldParseId; this.shouldParseRouting = shouldParseRouting; this.shouldParseTimestamp = shouldParseTimestamp; } /** * The id value parsed, <tt>null</tt> if does not require parsing, or not resolved. */ public String id() { return id; } /** * Does id parsing really needed at all? */ public boolean shouldParseId() { return shouldParseId; } /** * Has id been resolved during the parsing phase. */ public boolean idResolved() { return idResolved; } /** * Is id parsing still needed? */ public boolean idParsingStillNeeded() { return shouldParseId && !idResolved; } /** * The routing value parsed, <tt>null</tt> if does not require parsing, or not resolved. */ public String routing() { return routing; } /** * Does routing parsing really needed at all? */ public boolean shouldParseRouting() { return shouldParseRouting; } /** * Has routing been resolved during the parsing phase. */ public boolean routingResolved() { return routingResolved; } /** * Is routing parsing still needed? */ public boolean routingParsingStillNeeded() { return shouldParseRouting && !routingResolved; } /** * The timestamp value parsed, <tt>null</tt> if does not require parsing, or not resolved. */ public String timestamp() { return timestamp; } /** * Does timestamp parsing really needed at all? */ public boolean shouldParseTimestamp() { return shouldParseTimestamp; } /** * Has timestamp been resolved during the parsing phase. */ public boolean timestampResolved() { return timestampResolved; } /** * Is timestamp parsing still needed? */ public boolean timestampParsingStillNeeded() { return shouldParseTimestamp && !timestampResolved; } /** * Do we really need parsing? */ public boolean shouldParse() { return shouldParseId || shouldParseRouting || shouldParseTimestamp; } /** * Is parsing still needed? */ public boolean parsingStillNeeded() { return idParsingStillNeeded() || routingParsingStillNeeded() || timestampParsingStillNeeded(); } } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_MappingMetaData.java
4,678
final static class Match extends QueryCollector { final PercolateContext context; final HighlightPhase highlightPhase; final List<BytesRef> matches = new ArrayList<BytesRef>(); final List<Map<String, HighlightField>> hls = new ArrayList<Map<String, HighlightField>>(); final boolean limit; final int size; long counter = 0; Match(ESLogger logger, PercolateContext context, HighlightPhase highlightPhase) { super(logger, context); this.limit = context.limit; this.size = context.size; this.context = context; this.highlightPhase = highlightPhase; } @Override public void collect(int doc) throws IOException { final Query query = getQuery(doc); if (query == null) { // log??? return; } // run the query try { collector.reset(); if (context.highlight() != null) { context.parsedQuery(new ParsedQuery(query, ImmutableMap.<String, Filter>of())); context.hitContext().cache().clear(); } searcher.search(query, collector); if (collector.exists()) { if (!limit || counter < size) { matches.add(values.copyShared()); if (context.highlight() != null) { highlightPhase.hitExecute(context, context.hitContext()); hls.add(context.hitContext().hit().getHighlightFields()); } } counter++; if (facetAndAggregatorCollector != null) { facetAndAggregatorCollector.collect(doc); } } } catch (IOException e) { logger.warn("[" + spare.bytes.utf8ToString() + "] failed to execute query", e); } } long counter() { return counter; } List<BytesRef> matches() { return matches; } List<Map<String, HighlightField>> hls() { return hls; } }
1no label
src_main_java_org_elasticsearch_percolator_QueryCollector.java
73
class AssignToTryProposal extends LocalProposal { protected DocumentChange createChange(IDocument document, Node expanse, Integer stopIndex) { DocumentChange change = new DocumentChange("Assign to Try", document); change.setEdit(new MultiTextEdit()); change.addEdit(new InsertEdit(offset, "try (" + initialName + " = ")); String terminal = expanse.getEndToken().getText(); if (!terminal.equals(";")) { change.addEdit(new InsertEdit(stopIndex+1, ") {}")); exitPos = stopIndex+3; } else { change.addEdit(new ReplaceEdit(stopIndex, 1, ") {}")); exitPos = stopIndex+2; } return change; } public AssignToTryProposal(Tree.CompilationUnit cu, Node node, int currentOffset) { super(cu, node, currentOffset); } protected void addLinkedPositions(IDocument document, Unit unit) throws BadLocationException { // ProposalPosition typePosition = // new ProposalPosition(document, offset, 5, 1, // getSupertypeProposals(offset, unit, // type, true, "value")); ProposalPosition namePosition = new ProposalPosition(document, offset+5, initialName.length(), 0, getNameProposals(offset+5, 0, nameProposals)); // LinkedMode.addLinkedPosition(linkedModeModel, typePosition); LinkedMode.addLinkedPosition(linkedModeModel, namePosition); } @Override String[] computeNameProposals(Node expression) { return super.computeNameProposals(expression); } @Override public String getDisplayString() { return "Assign expression to 'try'"; } @Override boolean isEnabled(ProducedType resultType) { return resultType!=null && rootNode.getUnit().isUsableType(resultType); } static void addAssignToTryProposal(Tree.CompilationUnit cu, Collection<ICompletionProposal> proposals, Node node, int currentOffset) { AssignToTryProposal prop = new AssignToTryProposal(cu, node, currentOffset); if (prop.isEnabled()) { proposals.add(prop); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AssignToTryProposal.java
631
public static class MasterClaim extends AbstractOperation implements JoinOperation { private transient boolean approvedAsMaster = false; @Override public void run() { final NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine(); Node node = nodeEngine.getNode(); Joiner joiner = node.getJoiner(); final ILogger logger = node.getLogger(getClass().getName()); if (joiner instanceof TcpIpJoiner) { TcpIpJoiner tcpIpJoiner = (TcpIpJoiner) joiner; final Address endpoint = getCallerAddress(); final Address masterAddress = node.getMasterAddress(); approvedAsMaster = !tcpIpJoiner.claimingMaster && !node.isMaster() && (masterAddress == null || masterAddress.equals(endpoint)); } else { approvedAsMaster = false; logger.warning("This node requires MulticastJoin strategy!"); } if (logger.isFinestEnabled()) { logger.finest("Sending '" + approvedAsMaster + "' for master claim of node: " + getCallerAddress()); } } @Override public boolean returnsResponse() { return true; } @Override public Object getResponse() { return approvedAsMaster; } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_TcpIpJoiner.java
771
@Deprecated @Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_SKU_AVAILABILITY") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blInventoryElements") public class SkuAvailabilityImpl implements SkuAvailability { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The id. */ @Id @GeneratedValue(generator = "SkuAvailabilityId") @GenericGenerator( name="SkuAvailabilityId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="SkuAvailabilityImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.inventory.domain.SkuAvailabilityImpl") } ) @Column(name = "SKU_AVAILABILITY_ID") @AdminPresentation(friendlyName = "SkuAvailabilityImpl_Sku_Availability_ID", group = "SkuAvailabilityImpl_Primary_Key", visibility = VisibilityEnum.HIDDEN_ALL) protected Long id; /** The sale price. */ @Column(name = "SKU_ID") @Index(name="SKUAVAIL_SKU_INDEX", columnNames={"SKU_ID"}) @AdminPresentation(friendlyName = "SkuAvailabilityImpl_Sku_ID", visibility = VisibilityEnum.HIDDEN_ALL) protected Long skuId; /** The retail price. */ @Column(name = "LOCATION_ID") @Index(name="SKUAVAIL_LOCATION_INDEX", columnNames={"LOCATION_ID"}) @AdminPresentation(friendlyName = "SkuAvailabilityImpl_Location_ID", group = "SkuAvailabilityImpl_Description") protected Long locationId; /** The quantity on hand. */ @Column(name = "QTY_ON_HAND") @AdminPresentation(friendlyName = "SkuAvailabilityImpl_Quantity_On_Hand", group = "SkuAvailabilityImpl_Description") protected Integer quantityOnHand; /** The reserve quantity. */ @Column(name = "RESERVE_QTY") @AdminPresentation(friendlyName = "SkuAvailabilityImpl_Reserve_Quantity", group = "SkuAvailabilityImpl_Description") protected Integer reserveQuantity; /** The description. */ @Column(name = "AVAILABILITY_STATUS") @Index(name="SKUAVAIL_STATUS_INDEX", columnNames={"AVAILABILITY_STATUS"}) @AdminPresentation(friendlyName = "SkuAvailabilityImpl_Availability_Status", group = "SkuAvailabilityImpl_Description", fieldType= SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration="org.broadleafcommerce.core.inventory.service.type.AvailabilityStatusType") protected String availabilityStatus; /** The date this product will be available. */ @Column(name = "AVAILABILITY_DATE") @AdminPresentation(friendlyName = "SkuAvailabilityImpl_Available_Date", group = "SkuAvailabilityImpl_Description") protected Date availabilityDate; @Override public Long getId() { return id; } @Override public Long getLocationId() { return locationId; } @Override public Integer getQuantityOnHand() { return quantityOnHand; } @Override public Long getSkuId() { return skuId; } @Override public void setId(Long id) { this.id = id; } @Override public void setLocationId(Long locationId) { this.locationId = locationId; } @Override public void setQuantityOnHand(Integer qoh) { this.quantityOnHand = qoh; } @Override public void setSkuId(Long skuId) { this.skuId = skuId; } @Override public Date getAvailabilityDate() { return availabilityDate; } @Override public void setAvailabilityDate(Date availabilityDate) { this.availabilityDate = availabilityDate; } @Override public AvailabilityStatusType getAvailabilityStatus() { return AvailabilityStatusType.getInstance(availabilityStatus); } @Override public void setAvailabilityStatus(final AvailabilityStatusType availabilityStatus) { if (availabilityStatus != null) { this.availabilityStatus = availabilityStatus.getType(); } } /** * Returns the reserve quantity. Nulls will be treated the same as 0. * Implementations may want to manage a reserve quantity at each location so that the * available quantity for purchases is the quantityOnHand - reserveQuantity. */ @Override public Integer getReserveQuantity() { return reserveQuantity; } /** * Sets the reserve quantity. * Implementations may want to manage a reserve quantity at each location so that the * available quantity for purchases is the quantityOnHand - reserveQuantity. */ @Override public void setReserveQuantity(Integer reserveQuantity) { this.reserveQuantity = reserveQuantity; } /** * Returns the getQuantityOnHand() - getReserveQuantity(). * Preferred implementation is to return null if getQuantityOnHand() is null and to treat * a null in getReserveQuantity() as ZERO. */ @Override public Integer getAvailableQuantity() { if (getQuantityOnHand() == null || getReserveQuantity() == null) { return getQuantityOnHand(); } else { return getQuantityOnHand() - getReserveQuantity(); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((locationId == null) ? 0 : locationId.hashCode()); result = prime * result + ((skuId == null) ? 0 : skuId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SkuAvailabilityImpl other = (SkuAvailabilityImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (locationId == null) { if (other.locationId != null) return false; } else if (!locationId.equals(other.locationId)) return false; if (skuId == null) { if (other.skuId != null) return false; } else if (!skuId.equals(other.skuId)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_inventory_domain_SkuAvailabilityImpl.java
1,553
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, Text> { private Closure closure; private boolean isVertex; private SafeMapperOutputs outputs; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); try { this.closure = (Closure) engine.eval(context.getConfiguration().get(CLOSURE)); } catch (final ScriptException e) { throw new IOException(e.getMessage(), e); } this.outputs = new SafeMapperOutputs(context); } private final Text textWritable = new Text(); @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, Text>.Context context) throws IOException, InterruptedException { if (this.isVertex) { if (value.hasPaths()) { final Object result = this.closure.call(value); this.textWritable.set(null == result ? Tokens.NULL : result.toString()); for (int i = 0; i < value.pathCount(); i++) { this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), this.textWritable); } DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L); } } else { long edgesProcessed = 0; for (final Edge e : value.getEdges(Direction.OUT)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { final Object result = this.closure.call(edge); this.textWritable.set(null == result ? Tokens.NULL : result.toString()); for (int i = 0; i < edge.pathCount(); i++) { this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), this.textWritable); } edgesProcessed++; } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_PROCESSED, edgesProcessed); } this.outputs.write(Tokens.GRAPH, NullWritable.get(), value); } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, Text>.Context context) throws IOException, InterruptedException { this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_TransformMap.java
549
public abstract class OClusterPositionFactory { public static final OClusterPositionFactory INSTANCE; static { if (OGlobalConfiguration.USE_NODE_ID_CLUSTER_POSITION.getValueAsBoolean()) INSTANCE = new OClusterPositionFactoryNodeId(); else INSTANCE = new OClusterPositionFactoryLong(); } public abstract OClusterPosition generateUniqueClusterPosition(); public abstract OClusterPosition valueOf(long value); public abstract OClusterPosition valueOf(String value); public abstract OClusterPosition fromStream(byte[] content, int start); /** * @return Size of {@link OClusterPosition} instance in serialized form. * @see com.orientechnologies.orient.core.id.OClusterPosition#toStream() */ public abstract int getSerializedSize(); public OClusterPosition fromStream(byte[] content) { return fromStream(content, 0); } public OClusterPosition fromStream(InputStream in) throws IOException { int bytesToRead; int contentLength = 0; final int clusterSize = OClusterPositionFactory.INSTANCE.getSerializedSize(); final byte[] clusterContent = new byte[clusterSize]; do { bytesToRead = in.read(clusterContent, contentLength, clusterSize - contentLength); if (bytesToRead < 0) break; contentLength += bytesToRead; } while (contentLength < clusterSize); return fromStream(clusterContent); } public OClusterPosition fromStream(ObjectInput in) throws IOException { int bytesToRead; int contentLength = 0; final int clusterSize = OClusterPositionFactory.INSTANCE.getSerializedSize(); final byte[] clusterContent = new byte[clusterSize]; do { bytesToRead = in.read(clusterContent, contentLength, clusterSize - contentLength); if (bytesToRead < 0) break; contentLength += bytesToRead; } while (contentLength < clusterSize); return fromStream(clusterContent); } public OClusterPosition fromStream(DataInput in) throws IOException { final int clusterSize = OClusterPositionFactory.INSTANCE.getSerializedSize(); final byte[] clusterContent = new byte[clusterSize]; in.readFully(clusterContent); return fromStream(clusterContent); } public abstract OClusterPosition getMaxValue(); public static final class OClusterPositionFactoryLong extends OClusterPositionFactory { @Override public OClusterPosition generateUniqueClusterPosition() { throw new UnsupportedOperationException(); } @Override public OClusterPosition valueOf(long value) { return new OClusterPositionLong(value); } @Override public OClusterPosition valueOf(String value) { return new OClusterPositionLong(Long.valueOf(value)); } @Override public OClusterPosition fromStream(byte[] content, int start) { return new OClusterPositionLong(OLongSerializer.INSTANCE.deserialize(content, start)); } @Override public int getSerializedSize() { return OLongSerializer.LONG_SIZE; } @Override public OClusterPosition getMaxValue() { return new OClusterPositionLong(Long.MAX_VALUE); } } public static final class OClusterPositionFactoryNodeId extends OClusterPositionFactory { @Override public OClusterPosition generateUniqueClusterPosition() { return new OClusterPositionNodeId(ONodeId.generateUniqueId()); } @Override public OClusterPosition valueOf(long value) { return new OClusterPositionNodeId(ONodeId.valueOf(value)); } @Override public OClusterPosition valueOf(String value) { return new OClusterPositionNodeId(ONodeId.parseString(value)); } @Override public OClusterPosition fromStream(byte[] content, int start) { return new OClusterPositionNodeId(ONodeId.fromStream(content, start)); } @Override public int getSerializedSize() { return ONodeId.SERIALIZED_SIZE; } @Override public OClusterPosition getMaxValue() { return new OClusterPositionNodeId(ONodeId.MAX_VALUE); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_id_OClusterPositionFactory.java
18
@Component("blTargetItemRulesValidator") public class TargetItemRulesValidator implements PropertyValidator { @Override public PropertyValidationResult validate(Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration, BasicFieldMetadata propertyMetadata, String propertyName, String value) { Offer offer = (Offer)instance; if (OfferType.ORDER_ITEM.equals(offer.getType())) { return new PropertyValidationResult(CollectionUtils.isNotEmpty(offer.getTargetItemCriteria()), RequiredPropertyValidator.ERROR_MESSAGE); } else { return new PropertyValidationResult(true); } } }
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_persistence_validation_TargetItemRulesValidator.java
737
public class ShardDeleteByQueryRequest extends ShardReplicationOperationRequest<ShardDeleteByQueryRequest> { private int shardId; private BytesReference source; private String[] types = Strings.EMPTY_ARRAY; @Nullable private Set<String> routing; @Nullable private String[] filteringAliases; ShardDeleteByQueryRequest(IndexDeleteByQueryRequest request, int shardId) { super(request); this.index = request.index(); this.source = request.source(); this.types = request.types(); this.shardId = shardId; replicationType(request.replicationType()); consistencyLevel(request.consistencyLevel()); timeout = request.timeout(); this.routing = request.routing(); filteringAliases = request.filteringAliases(); } ShardDeleteByQueryRequest() { } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (source == null) { addValidationError("source is missing", validationException); } return validationException; } public int shardId() { return this.shardId; } BytesReference source() { return source; } public String[] types() { return this.types; } public Set<String> routing() { return this.routing; } public String[] filteringAliases() { return filteringAliases; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); source = in.readBytesReference(); shardId = in.readVInt(); types = in.readStringArray(); int routingSize = in.readVInt(); if (routingSize > 0) { routing = new HashSet<String>(routingSize); for (int i = 0; i < routingSize; i++) { routing.add(in.readString()); } } int aliasesSize = in.readVInt(); if (aliasesSize > 0) { filteringAliases = new String[aliasesSize]; for (int i = 0; i < aliasesSize; i++) { filteringAliases[i] = in.readString(); } } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBytesReference(source); out.writeVInt(shardId); out.writeStringArray(types); if (routing != null) { out.writeVInt(routing.size()); for (String r : routing) { out.writeString(r); } } else { out.writeVInt(0); } if (filteringAliases != null) { out.writeVInt(filteringAliases.length); for (String alias : filteringAliases) { out.writeString(alias); } } else { out.writeVInt(0); } } @Override public String toString() { String sSource = "_na_"; try { sSource = XContentHelper.convertToJson(source, false); } catch (Exception e) { // ignore } return "delete_by_query {[" + index + "]" + Arrays.toString(types) + ", query [" + sSource + "]}"; } }
0true
src_main_java_org_elasticsearch_action_deletebyquery_ShardDeleteByQueryRequest.java
1,221
bytePage = build(type, maxCount(limit, BigArrays.BYTE_PAGE_SIZE, bytesWeight, totalWeight), searchThreadPoolSize, availableProcessors, new Recycler.C<byte[]>() { @Override public byte[] newInstance(int sizing) { return new byte[BigArrays.BYTE_PAGE_SIZE]; } @Override public void clear(byte[] value) {} });
0true
src_main_java_org_elasticsearch_cache_recycler_PageCacheRecycler.java
107
class CreateInNewUnitProposal implements ICompletionProposal, ICompletionProposalExtension6 { private final IFile file; private final DefinitionGenerator dg; CreateInNewUnitProposal(IFile file, DefinitionGenerator dg) { this.file = file; this.dg = dg; } @Override public Point getSelection(IDocument doc) { return null; } @Override public Image getImage() { return dg.getImage(); } @Override public String getDisplayString() { return "Create toplevel " + dg.getDescription() + " in a new source file"; } @Override public IContextInformation getContextInformation() { return null; } @Override public String getAdditionalProposalInfo() { return null; } @Override public void apply(IDocument doc) { SelectNewUnitWizard w = new SelectNewUnitWizard("Create in New Source File", "Create a new Ceylon source file with the missing declaration.", dg.getBrokenName()); if (w.open(file)) { CreateUnitChange change = new CreateUnitChange(w.getFile(), w.includePreamble(), getText(doc), w.getProject(), "Create in New Source File"); try { performChange(getCurrentEditor(), doc, change, "Move to New Source File"); gotoLocation(w.getFile().getFullPath(), 0); } catch (CoreException e) { e.printStackTrace(); } } } private String getText(IDocument doc) { String delim = getDefaultLineDelimiter(doc); String definition = dg.generate("", delim); List<Declaration> imports = new ArrayList<Declaration>(); resolveImports(imports, dg.getReturnType()); if (dg.getParameters()!=null) { resolveImports(imports, dg.getParameters().values()); } String imps = imports(imports, doc); if (!imps.isEmpty()) { definition = imps + delim + delim + definition; } return definition; } static void addCreateInNewUnitProposal(Collection<ICompletionProposal> proposals, DefinitionGenerator dg, IFile file) { proposals.add(new CreateInNewUnitProposal(file, dg)); } private static void resolveImports(List<Declaration> imports, Collection<ProducedType> producedTypes) { if (producedTypes!=null) { for (ProducedType pt : producedTypes) { resolveImports(imports, pt); } } } private static void resolveImports(List<Declaration> imports, ProducedType pt) { if (pt != null) { if (pt.getDeclaration() instanceof UnionType) { resolveImports(imports, pt.getCaseTypes()); } else if (pt.getDeclaration() instanceof IntersectionType) { resolveImports(imports, pt.getSatisfiedTypes()); } else if (pt.getDeclaration() instanceof TypeParameter) { TypeParameter typeParam = (TypeParameter) pt.getDeclaration(); if (typeParam.isConstrained()) { resolveImports(imports, typeParam.getCaseTypes()); resolveImports(imports, typeParam.getSatisfiedTypes()); } if (typeParam.isDefaulted()) { resolveImports(imports, typeParam.getDefaultTypeArgument()); } } else { resolveImports(imports, pt.getTypeArgumentList()); Package p = pt.getDeclaration().getUnit().getPackage(); if (!p.getQualifiedNameString().isEmpty() && !p.getQualifiedNameString().equals(Module.LANGUAGE_MODULE_NAME)) { if (!imports.contains(pt.getDeclaration())) { imports.add(pt.getDeclaration()); } } } } } @Override public StyledString getStyledDisplayString() { return Highlights.styleProposal(getDisplayString(), false); } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CreateInNewUnitProposal.java
504
public class CreateIndexRequestBuilder extends AcknowledgedRequestBuilder<CreateIndexRequest, CreateIndexResponse, CreateIndexRequestBuilder> { public CreateIndexRequestBuilder(IndicesAdminClient indicesClient) { super((InternalIndicesAdminClient) indicesClient, new CreateIndexRequest()); } public CreateIndexRequestBuilder(IndicesAdminClient indicesClient, String index) { super((InternalIndicesAdminClient) indicesClient, new CreateIndexRequest(index)); } /** * Sets the name of the index to be created */ public CreateIndexRequestBuilder setIndex(String index) { request.index(index); return this; } /** * The settings to create the index with. */ public CreateIndexRequestBuilder setSettings(Settings settings) { request.settings(settings); return this; } /** * The settings to create the index with. */ public CreateIndexRequestBuilder setSettings(Settings.Builder settings) { request.settings(settings); return this; } /** * Allows to set the settings using a json builder. */ public CreateIndexRequestBuilder setSettings(XContentBuilder builder) { request.settings(builder); return this; } /** * The settings to create the index with (either json/yaml/properties format) */ public CreateIndexRequestBuilder setSettings(String source) { request.settings(source); return this; } /** * A simplified version of settings that takes key value pairs settings. */ public CreateIndexRequestBuilder setSettings(Object... settings) { request.settings(settings); return this; } /** * The settings to create the index with (either json/yaml/properties format) */ public CreateIndexRequestBuilder setSettings(Map<String, Object> source) { request.settings(source); return this; } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source */ public CreateIndexRequestBuilder addMapping(String type, String source) { request.mapping(type, source); return this; } /** * The cause for this index creation. */ public CreateIndexRequestBuilder setCause(String cause) { request.cause(cause); return this; } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source */ public CreateIndexRequestBuilder addMapping(String type, XContentBuilder source) { request.mapping(type, source); return this; } /** * Adds mapping that will be added when the index gets created. * * @param type The mapping type * @param source The mapping source */ public CreateIndexRequestBuilder addMapping(String type, Map<String, Object> source) { request.mapping(type, source); return this; } /** * A specialized simplified mapping source method, takes the form of simple properties definition: * ("field1", "type=string,store=true"). */ public CreateIndexRequestBuilder addMapping(String type, Object... source) { request.mapping(type, source); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequestBuilder setSource(String source) { request.source(source); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequestBuilder setSource(BytesReference source) { request.source(source); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequestBuilder setSource(byte[] source) { request.source(source); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequestBuilder setSource(byte[] source, int offset, int length) { request.source(source, offset, length); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequestBuilder setSource(Map<String, Object> source) { request.source(source); return this; } /** * Adds custom metadata to the index to be created. */ public CreateIndexRequestBuilder addCustom(IndexMetaData.Custom custom) { request.custom(custom); return this; } /** * Sets the settings and mappings as a single source. */ public CreateIndexRequestBuilder setSource(XContentBuilder source) { request.source(source); return this; } @Override protected void doExecute(ActionListener<CreateIndexResponse> listener) { ((IndicesAdminClient) client).create(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_create_CreateIndexRequestBuilder.java
519
public class TransportTypesExistsAction extends TransportMasterNodeReadOperationAction<TypesExistsRequest, TypesExistsResponse> { @Inject public TransportTypesExistsAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) { super(settings, transportService, clusterService, threadPool); } @Override protected String executor() { // lightweight check return ThreadPool.Names.SAME; } @Override protected String transportAction() { return TypesExistsAction.NAME; } @Override protected TypesExistsRequest newRequest() { return new TypesExistsRequest(); } @Override protected TypesExistsResponse newResponse() { return new TypesExistsResponse(); } @Override protected ClusterBlockException checkBlock(TypesExistsRequest request, ClusterState state) { return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, request.indices()); } @Override protected void masterOperation(final TypesExistsRequest request, final ClusterState state, final ActionListener<TypesExistsResponse> listener) throws ElasticsearchException { String[] concreteIndices = state.metaData().concreteIndices(request.indices(), request.indicesOptions()); if (concreteIndices.length == 0) { listener.onResponse(new TypesExistsResponse(false)); return; } for (String concreteIndex : concreteIndices) { if (!state.metaData().hasConcreteIndex(concreteIndex)) { listener.onResponse(new TypesExistsResponse(false)); return; } ImmutableOpenMap<String, MappingMetaData> mappings = state.metaData().getIndices().get(concreteIndex).mappings(); if (mappings.isEmpty()) { listener.onResponse(new TypesExistsResponse(false)); return; } for (String type : request.types()) { if (!mappings.containsKey(type)) { listener.onResponse(new TypesExistsResponse(false)); return; } } } listener.onResponse(new TypesExistsResponse(true)); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_exists_types_TransportTypesExistsAction.java
5,877
public class QueryParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { context.parsedQuery(context.queryParserService().parse(parser)); } }
1no label
src_main_java_org_elasticsearch_search_query_QueryParseElement.java
938
public class OfferType implements Serializable, BroadleafEnumerationType, Comparable<OfferType> { private static final long serialVersionUID = 1L; private static final Map<String, OfferType> TYPES = new LinkedHashMap<String, OfferType>(); public static final OfferType ORDER_ITEM = new OfferType("ORDER_ITEM", "Order Item", 1000); public static final OfferType ORDER = new OfferType("ORDER", "Order", 2000); public static final OfferType FULFILLMENT_GROUP = new OfferType("FULFILLMENT_GROUP", "Fulfillment Group", 3000); public static OfferType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; private int order; public OfferType() { //do nothing } public OfferType(final String type, final String friendlyType, int order) { this.friendlyType = friendlyType; setType(type); setOrder(order); } public void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OfferType other = (OfferType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } @Override public int compareTo(OfferType arg0) { return this.order - arg0.order; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_type_OfferType.java
132
public interface StructuredContent extends Serializable { /** * Gets the primary key. * * @return the primary key */ @Nullable public Long getId(); /** * Sets the primary key. * * @param id the new primary key */ public void setId(@Nullable Long id); /** * Gets the name. * * @return the name */ @Nonnull public String getContentName(); /** * Sets the name. * @param contentName */ public void setContentName(@Nonnull String contentName); /** * Gets the {@link Locale} associated with this content item. * * @return */ @Nonnull public Locale getLocale(); /** * Sets the locale associated with this content item. * @param locale */ public void setLocale(@Nonnull Locale locale); /** * Gets the Sandbox associated with the content item. SandBoxes * allow for segmentation of data. A result of null indicates * that this item is in "Production" in a single-site architecture. * <br> * The processing may differ depending on which type of SandBox is * returned. * * @return */ @Nullable public SandBox getSandbox(); /** * Sets the SandBox for this content item. This method is typically * only called by the BLC Content Management System during content-item * lifecycle operations like New, Promote, Approve, Deploy. * * @param sandbox */ public void setSandbox(@Nullable SandBox sandbox); /** * Gets the {@link StructuredContentType} associated with this content item. * * @return */ @Nonnull public StructuredContentType getStructuredContentType(); /** * Sets the {@link StructuredContentType} associated with this content item. * */ public void setStructuredContentType(@Nonnull StructuredContentType structuredContentType); /** * Gets a map with the custom fields associated with this content item.<br> * The map keys are based on the field types. For example, consider a content * item with a <code>StructuredContentType</code> of ad which defined a field * named targetUrl. The field could be accessed with * <code>structuredContentItem.getStructuredContentFields().get("targetUrl")</code> * @return */ @Nullable public Map<String, StructuredContentField> getStructuredContentFields(); /** * Sets the structured content fields for this item. Would not typically called * outside of the ContentManagementSystem. * * @param structuredContentFields */ public void setStructuredContentFields(@Nullable Map<String, StructuredContentField> structuredContentFields); /** * Gets the "deleted" indicator. Deleted means that the item has been * marked for deletion. If this method returns true, the item will not be returned * as part {@link org.broadleafcommerce.cms.structure.service.StructuredContentService#lookupStructuredContentItemsByType(org.broadleafcommerce.common.sandbox.domain.SandBox, StructuredContentType, org.broadleafcommerce.common.locale.domain.Locale, Integer, java.util.Map)}'s}. * * In a "production sandbox", an item that returns true for <code>getDeletedFlag</code> * should also return true for <code>getArchivedFlag</code> * * @return the deleted indicator or false if none found */ @Nonnull public Boolean getDeletedFlag(); /** * Sets the deleted flag for this item. Would not typically be called * outside of the Content Administration system. * * @param deletedFlag */ public void setDeletedFlag(@Nonnull Boolean deletedFlag); /** * Gets the archived indicator. The archivedFlag indicates that the item * is no longer of importance to the system. Items that have been * archived may be removed by a data cleanup process. * * @return true if this item has been archived. Returns false if not set. */ @Nonnull public Boolean getArchivedFlag(); /** * Sets the archived flag for this item. Would not typically be called * outside the Content Administration system. * * Content items with an archived flag of true will not be returned from * most APIs and can be deleted from the system. * * @param archivedFlag */ public void setArchivedFlag(@Nonnull Boolean archivedFlag); /** * Returns the offlineFlag. Indicates that the item should no longer appear on the site. * The item will still appear within the content administration program but no longer * be returned as part of the client facing APIs. * * @return true if this item is offline */ @Nullable public Boolean getOfflineFlag(); /** * Sets the offline flag. * * @param offlineFlag */ public void setOfflineFlag(@Nullable Boolean offlineFlag); /** * Gets the integer priority of this content item. Items with a lower priority should * be displayed before items with a higher priority. * * @return the priority as a numeric value */ @Nullable public Integer getPriority(); /** * Sets the display priority of this item. Lower priorities should be displayed first. * * @param priority */ public void setPriority(@Nullable Integer priority); /** * Gets the id of a related content item on which this item is based. This value is * used internally by the content management system. Generally, when an item is * promoted through a content workflow to production, the system will set mark the item * associated with the originalItemId as archived. * * @return the id of the originalItemId */ @Nullable public Long getOriginalItemId(); /** * The id of the item on which this content item is based. This property gets set by the * content management system when an item is edited. * * @param originalItemId */ public void setOriginalItemId(@Nullable Long originalItemId); /** * Builds a copy of this content item. Used by the content management system when an * item is edited. * * @return a copy of this item */ @Nonnull public StructuredContent cloneEntity(); /** * Returns audit information for this content item. * * @return */ @Nullable public AdminAuditable getAuditable(); /** * Sets audit information for this content item. Default implementations automatically * populate this data during persistence. * * @param auditable */ public void setAuditable(@Nullable AdminAuditable auditable); /** * Returns the locked flag. If an item is locked, it is being edited by another user. * * @return true if this item is locked for editing. */ @Nonnull public Boolean getLockedFlag(); /** * Sets the lockedFlag for this item. * * @param lockedFlag */ public void setLockedFlag(@Nullable Boolean lockedFlag); /** * Gets the <code>SandBox</code> which originally edited this item. Used by the * Content Management System to determine where to return an item that is being * rejected. * * @return */ @Nullable public SandBox getOriginalSandBox(); /** * Sets the originalSandBox for this item. The Content Management System will set this * value when an item is promoted from a user sandbox. * * @param originalSandBox */ public void setOriginalSandBox(@Nullable SandBox originalSandBox); /** * Returns a map of the targeting rules associated with this content item. * * Targeting rules are defined in the content mangagement system and used to * enforce which items are returned to the client. * * @return */ @Nullable public Map<String, StructuredContentRule> getStructuredContentMatchRules(); /** * Sets the targeting rules for this content item. * * @param structuredContentMatchRules */ public void setStructuredContentMatchRules(@Nullable Map<String, StructuredContentRule> structuredContentMatchRules); /** * Returns the item (or cart) based rules associated with this content item. * * @return */ @Nullable public Set<StructuredContentItemCriteria> getQualifyingItemCriteria(); /** * Sets the item (e.g. cart) based rules associated with this content item. * * @param qualifyingItemCriteria */ public void setQualifyingItemCriteria(@Nullable Set<StructuredContentItemCriteria> qualifyingItemCriteria); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContent.java
1,440
public class RestoreMetaData implements MetaData.Custom { public static final String TYPE = "restore"; public static final Factory FACTORY = new Factory(); private final ImmutableList<Entry> entries; /** * Constructs new restore metadata * * @param entries list of currently running restore processes */ public RestoreMetaData(ImmutableList<Entry> entries) { this.entries = entries; } /** * Constructs new restore metadata * * @param entries list of currently running restore processes */ public RestoreMetaData(Entry... entries) { this.entries = ImmutableList.copyOf(entries); } /** * Returns list of currently running restore processes * * @return list of currently running restore processes */ public ImmutableList<Entry> entries() { return this.entries; } /** * Returns currently running restore process with corresponding snapshot id or null if this snapshot is not being * restored * * @param snapshotId snapshot id * @return restore metadata or null */ public Entry snapshot(SnapshotId snapshotId) { for (Entry entry : entries) { if (snapshotId.equals(entry.snapshotId())) { return entry; } } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RestoreMetaData that = (RestoreMetaData) o; if (!entries.equals(that.entries)) return false; return true; } @Override public int hashCode() { return entries.hashCode(); } /** * Restore metadata */ public static class Entry { private final State state; private final SnapshotId snapshotId; private final ImmutableMap<ShardId, ShardRestoreStatus> shards; private final ImmutableList<String> indices; /** * Creates new restore metadata * * @param snapshotId snapshot id * @param state current state of the restore process * @param indices list of indices being restored * @param shards list of shards being restored and thier current restore status */ public Entry(SnapshotId snapshotId, State state, ImmutableList<String> indices, ImmutableMap<ShardId, ShardRestoreStatus> shards) { this.snapshotId = snapshotId; this.state = state; this.indices = indices; if (shards == null) { this.shards = ImmutableMap.of(); } else { this.shards = shards; } } /** * Returns snapshot id * * @return snapshot id */ public SnapshotId snapshotId() { return this.snapshotId; } /** * Returns list of shards that being restore and their status * * @return list of shards */ public ImmutableMap<ShardId, ShardRestoreStatus> shards() { return this.shards; } /** * Returns current restore state * * @return restore state */ public State state() { return state; } /** * Returns list of indices * * @return list of indices */ public ImmutableList<String> indices() { return indices; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; if (!indices.equals(entry.indices)) return false; if (!snapshotId.equals(entry.snapshotId)) return false; if (!shards.equals(entry.shards)) return false; if (state != entry.state) return false; return true; } @Override public int hashCode() { int result = state.hashCode(); result = 31 * result + snapshotId.hashCode(); result = 31 * result + shards.hashCode(); result = 31 * result + indices.hashCode(); return result; } } /** * Represents status of a restored shard */ public static class ShardRestoreStatus { private State state; private String nodeId; private String reason; private ShardRestoreStatus() { } /** * Constructs a new shard restore status in initializing state on the given node * * @param nodeId node id */ public ShardRestoreStatus(String nodeId) { this(nodeId, State.INIT); } /** * Constructs a new shard restore status in with specified state on the given node * * @param nodeId node id * @param state restore state */ public ShardRestoreStatus(String nodeId, State state) { this(nodeId, state, null); } /** * Constructs a new shard restore status in with specified state on the given node with specified failure reason * * @param nodeId node id * @param state restore state * @param reason failure reason */ public ShardRestoreStatus(String nodeId, State state, String reason) { this.nodeId = nodeId; this.state = state; this.reason = reason; } /** * Returns current state * * @return current state */ public State state() { return state; } /** * Returns node id of the node where shared is getting restored * * @return node id */ public String nodeId() { return nodeId; } /** * Returns failure reason * * @return failure reason */ public String reason() { return reason; } /** * Reads restore status from stream input * * @param in stream input * @return restore status * @throws IOException */ public static ShardRestoreStatus readShardRestoreStatus(StreamInput in) throws IOException { ShardRestoreStatus shardSnapshotStatus = new ShardRestoreStatus(); shardSnapshotStatus.readFrom(in); return shardSnapshotStatus; } /** * Reads restore status from stream input * * @param in stream input * @throws IOException */ public void readFrom(StreamInput in) throws IOException { nodeId = in.readOptionalString(); state = State.fromValue(in.readByte()); reason = in.readOptionalString(); } /** * Writes restore status to stream output * * @param out stream input * @throws IOException */ public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(nodeId); out.writeByte(state.value); out.writeOptionalString(reason); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShardRestoreStatus status = (ShardRestoreStatus) o; if (nodeId != null ? !nodeId.equals(status.nodeId) : status.nodeId != null) return false; if (reason != null ? !reason.equals(status.reason) : status.reason != null) return false; if (state != status.state) return false; return true; } @Override public int hashCode() { int result = state != null ? state.hashCode() : 0; result = 31 * result + (nodeId != null ? nodeId.hashCode() : 0); result = 31 * result + (reason != null ? reason.hashCode() : 0); return result; } } /** * Shard restore process state */ public static enum State { /** * Initializing state */ INIT((byte) 0), /** * Started state */ STARTED((byte) 1), /** * Restore finished successfully */ SUCCESS((byte) 2), /** * Restore failed */ FAILURE((byte) 3); private byte value; /** * Constructs new state * * @param value state code */ State(byte value) { this.value = value; } /** * Returns state code * * @return state code */ public byte value() { return value; } /** * Returns true if restore process completed (either successfully or with failure) * * @return true if restore process completed */ public boolean completed() { return this == SUCCESS || this == FAILURE; } /** * Returns state corresponding to state code * * @param value stat code * @return state */ public static State fromValue(byte value) { switch (value) { case 0: return INIT; case 1: return STARTED; case 2: return SUCCESS; case 3: return FAILURE; default: throw new ElasticsearchIllegalArgumentException("No snapshot state for value [" + value + "]"); } } } /** * Restore metadata factory */ public static class Factory implements MetaData.Custom.Factory<RestoreMetaData> { /** * {@inheritDoc} */ @Override public String type() { return TYPE; } /** * {@inheritDoc} */ @Override public RestoreMetaData readFrom(StreamInput in) throws IOException { Entry[] entries = new Entry[in.readVInt()]; for (int i = 0; i < entries.length; i++) { SnapshotId snapshotId = SnapshotId.readSnapshotId(in); State state = State.fromValue(in.readByte()); int indices = in.readVInt(); ImmutableList.Builder<String> indexBuilder = ImmutableList.builder(); for (int j = 0; j < indices; j++) { indexBuilder.add(in.readString()); } ImmutableMap.Builder<ShardId, ShardRestoreStatus> builder = ImmutableMap.<ShardId, ShardRestoreStatus>builder(); int shards = in.readVInt(); for (int j = 0; j < shards; j++) { ShardId shardId = ShardId.readShardId(in); ShardRestoreStatus shardState = ShardRestoreStatus.readShardRestoreStatus(in); builder.put(shardId, shardState); } entries[i] = new Entry(snapshotId, state, indexBuilder.build(), builder.build()); } return new RestoreMetaData(entries); } /** * {@inheritDoc} */ @Override public void writeTo(RestoreMetaData repositories, StreamOutput out) throws IOException { out.writeVInt(repositories.entries().size()); for (Entry entry : repositories.entries()) { entry.snapshotId().writeTo(out); out.writeByte(entry.state().value()); out.writeVInt(entry.indices().size()); for (String index : entry.indices()) { out.writeString(index); } out.writeVInt(entry.shards().size()); for (Map.Entry<ShardId, ShardRestoreStatus> shardEntry : entry.shards().entrySet()) { shardEntry.getKey().writeTo(out); shardEntry.getValue().writeTo(out); } } } /** * {@inheritDoc} */ @Override public RestoreMetaData fromXContent(XContentParser parser) throws IOException { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override public void toXContent(RestoreMetaData customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startArray("snapshots"); for (Entry entry : customIndexMetaData.entries()) { toXContent(entry, builder, params); } builder.endArray(); } /** * Serializes single restore operation * * @param entry restore operation metadata * @param builder XContent builder * @param params serialization parameters * @throws IOException */ public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field("snapshot", entry.snapshotId().getSnapshot()); builder.field("repository", entry.snapshotId().getRepository()); builder.field("state", entry.state()); builder.startArray("indices"); { for (String index : entry.indices()) { builder.value(index); } } builder.endArray(); builder.startArray("shards"); { for (Map.Entry<ShardId, ShardRestoreStatus> shardEntry : entry.shards.entrySet()) { ShardId shardId = shardEntry.getKey(); ShardRestoreStatus status = shardEntry.getValue(); builder.startObject(); { builder.field("index", shardId.getIndex()); builder.field("shard", shardId.getId()); builder.field("state", status.state()); } builder.endObject(); } } builder.endArray(); builder.endObject(); } /** * {@inheritDoc} */ @Override public boolean isPersistent() { return false; } } }
0true
src_main_java_org_elasticsearch_cluster_metadata_RestoreMetaData.java
345
public interface ODatabasePooled { /** * Reuses current instance. * * @param iOwner * @param iAdditionalArgs */ public void reuse(final Object iOwner, final Object[] iAdditionalArgs); /** * Tells if the underlying database is closed. */ public boolean isUnderlyingOpen(); /** * Force closing the current instance avoiding to being reused. */ public void forceClose(); }
0true
core_src_main_java_com_orientechnologies_orient_core_db_ODatabasePooled.java
1,464
public class IndexRoutingTable implements Iterable<IndexShardRoutingTable> { private final String index; // note, we assume that when the index routing is created, ShardRoutings are created for all possible number of // shards with state set to UNASSIGNED private final ImmutableOpenIntMap<IndexShardRoutingTable> shards; private final ImmutableList<ShardRouting> allShards; private final ImmutableList<ShardRouting> allActiveShards; private final AtomicInteger counter = new AtomicInteger(); IndexRoutingTable(String index, ImmutableOpenIntMap<IndexShardRoutingTable> shards) { this.index = index; this.shards = shards; ImmutableList.Builder<ShardRouting> allShards = ImmutableList.builder(); ImmutableList.Builder<ShardRouting> allActiveShards = ImmutableList.builder(); for (IntObjectCursor<IndexShardRoutingTable> cursor : shards) { for (ShardRouting shardRouting : cursor.value) { allShards.add(shardRouting); if (shardRouting.active()) { allActiveShards.add(shardRouting); } } } this.allShards = allShards.build(); this.allActiveShards = allActiveShards.build(); } /** * Return the index id * * @return id of the index */ public String index() { return this.index; } /** * Return the index id * * @return id of the index */ public String getIndex() { return index(); } /** * creates a new {@link IndexRoutingTable} with all shard versions normalized * * @return new {@link IndexRoutingTable} */ public IndexRoutingTable normalizeVersions() { IndexRoutingTable.Builder builder = new Builder(this.index); for (IntObjectCursor<IndexShardRoutingTable> cursor : shards) { builder.addIndexShard(cursor.value.normalizeVersions()); } return builder.build(); } public void validate(RoutingTableValidation validation, MetaData metaData) { if (!metaData.hasIndex(index())) { validation.addIndexFailure(index(), "Exists in routing does not exists in metadata"); return; } IndexMetaData indexMetaData = metaData.index(index()); for (String failure : validate(indexMetaData)) { validation.addIndexFailure(index, failure); } } /** * validate based on a meta data, returning failures found */ public List<String> validate(IndexMetaData indexMetaData) { ArrayList<String> failures = new ArrayList<String>(); // check the number of shards if (indexMetaData.numberOfShards() != shards().size()) { Set<Integer> expected = Sets.newHashSet(); for (int i = 0; i < indexMetaData.numberOfShards(); i++) { expected.add(i); } for (IndexShardRoutingTable indexShardRoutingTable : this) { expected.remove(indexShardRoutingTable.shardId().id()); } failures.add("Wrong number of shards in routing table, missing: " + expected); } // check the replicas for (IndexShardRoutingTable indexShardRoutingTable : this) { int routingNumberOfReplicas = indexShardRoutingTable.size() - 1; if (routingNumberOfReplicas != indexMetaData.numberOfReplicas()) { failures.add("Shard [" + indexShardRoutingTable.shardId().id() + "] routing table has wrong number of replicas, expected [" + indexMetaData.numberOfReplicas() + "], got [" + routingNumberOfReplicas + "]"); } for (ShardRouting shardRouting : indexShardRoutingTable) { if (!shardRouting.index().equals(index())) { failures.add("shard routing has an index [" + shardRouting.index() + "] that is different than the routing table"); } } } return failures; } @Override public UnmodifiableIterator<IndexShardRoutingTable> iterator() { return shards.valuesIt(); } /** * Calculates the number of nodes that hold one or more shards of this index * {@link IndexRoutingTable} excluding the nodes with the node ids give as * the <code>excludedNodes</code> parameter. * * @param excludedNodes id of nodes that will be excluded * @return number of distinct nodes this index has at least one shard allocated on */ public int numberOfNodesShardsAreAllocatedOn(String... excludedNodes) { Set<String> nodes = Sets.newHashSet(); for (IndexShardRoutingTable shardRoutingTable : this) { for (ShardRouting shardRouting : shardRoutingTable) { if (shardRouting.assignedToNode()) { String currentNodeId = shardRouting.currentNodeId(); boolean excluded = false; if (excludedNodes != null) { for (String excludedNode : excludedNodes) { if (currentNodeId.equals(excludedNode)) { excluded = true; break; } } } if (!excluded) { nodes.add(currentNodeId); } } } } return nodes.size(); } public ImmutableOpenIntMap<IndexShardRoutingTable> shards() { return shards; } public ImmutableOpenIntMap<IndexShardRoutingTable> getShards() { return shards(); } public IndexShardRoutingTable shard(int shardId) { return shards.get(shardId); } /** * Returns <code>true</code> if all shards are primary and active. Otherwise <code>false</code>. */ public boolean allPrimaryShardsActive() { return primaryShardsActive() == shards().size(); } /** * Calculates the number of primary shards in active state in routing table * * @return number of active primary shards */ public int primaryShardsActive() { int counter = 0; for (IndexShardRoutingTable shardRoutingTable : this) { if (shardRoutingTable.primaryShard().active()) { counter++; } } return counter; } /** * Returns <code>true</code> if all primary shards are in * {@link ShardRoutingState#UNASSIGNED} state. Otherwise <code>false</code>. */ public boolean allPrimaryShardsUnassigned() { return primaryShardsUnassigned() == shards.size(); } /** * Calculates the number of primary shards in the routing table the are in * {@link ShardRoutingState#UNASSIGNED} state. */ public int primaryShardsUnassigned() { int counter = 0; for (IndexShardRoutingTable shardRoutingTable : this) { if (shardRoutingTable.primaryShard().unassigned()) { counter++; } } return counter; } /** * Returns a {@link List} of shards that match one of the states listed in {@link ShardRoutingState states} * * @param states a set of {@link ShardRoutingState states} * @return a {@link List} of shards that match one of the given {@link ShardRoutingState states} */ public List<ShardRouting> shardsWithState(ShardRoutingState... states) { List<ShardRouting> shards = newArrayList(); for (IndexShardRoutingTable shardRoutingTable : this) { shards.addAll(shardRoutingTable.shardsWithState(states)); } return shards; } /** * Returns an unordered iterator over all shards (including replicas). */ public ShardsIterator randomAllShardsIt() { return new PlainShardsIterator(allShards, counter.incrementAndGet()); } /** * Returns an unordered iterator over all active shards (including replicas). */ public ShardsIterator randomAllActiveShardsIt() { return new PlainShardsIterator(allActiveShards, counter.incrementAndGet()); } /** * A group shards iterator where each group ({@link ShardIterator} * is an iterator across shard replication group. */ public GroupShardsIterator groupByShardsIt() { // use list here since we need to maintain identity across shards ArrayList<ShardIterator> set = new ArrayList<ShardIterator>(shards.size()); for (IndexShardRoutingTable indexShard : this) { set.add(indexShard.shardsIt()); } return new GroupShardsIterator(set); } /** * A groups shards iterator where each groups is a single {@link ShardRouting} and a group * is created for each shard routing. * <p/> * <p>This basically means that components that use the {@link GroupShardsIterator} will iterate * over *all* the shards (all the replicas) within the index.</p> */ public GroupShardsIterator groupByAllIt() { // use list here since we need to maintain identity across shards ArrayList<ShardIterator> set = new ArrayList<ShardIterator>(); for (IndexShardRoutingTable indexShard : this) { for (ShardRouting shardRouting : indexShard) { set.add(shardRouting.shardsIt()); } } return new GroupShardsIterator(set); } public void validate() throws RoutingValidationException { } public static Builder builder(String index) { return new Builder(index); } public static class Builder { private final String index; private final ImmutableOpenIntMap.Builder<IndexShardRoutingTable> shards = ImmutableOpenIntMap.builder(); public Builder(String index) { this.index = index; } /** * Reads an {@link IndexRoutingTable} from an {@link StreamInput} * * @param in {@link StreamInput} to read the {@link IndexRoutingTable} from * @return {@link IndexRoutingTable} read * @throws IOException if something happens during read */ public static IndexRoutingTable readFrom(StreamInput in) throws IOException { String index = in.readString(); Builder builder = new Builder(index); int size = in.readVInt(); for (int i = 0; i < size; i++) { builder.addIndexShard(IndexShardRoutingTable.Builder.readFromThin(in, index)); } return builder.build(); } /** * Writes an {@link IndexRoutingTable} to a {@link StreamOutput}. * * @param index {@link IndexRoutingTable} to write * @param out {@link StreamOutput} to write to * @throws IOException if something happens during write */ public static void writeTo(IndexRoutingTable index, StreamOutput out) throws IOException { out.writeString(index.index()); out.writeVInt(index.shards.size()); for (IndexShardRoutingTable indexShard : index) { IndexShardRoutingTable.Builder.writeToThin(indexShard, out); } } /** * Initializes a new empty index, as if it was created from an API. */ public Builder initializeAsNew(IndexMetaData indexMetaData) { return initializeEmpty(indexMetaData, true); } /** * Initializes a new empty index, as if it was created from an API. */ public Builder initializeAsRecovery(IndexMetaData indexMetaData) { return initializeEmpty(indexMetaData, false); } /** * Initializes a new empty index, to be restored from a snapshot */ public Builder initializeAsNewRestore(IndexMetaData indexMetaData, RestoreSource restoreSource) { return initializeAsRestore(indexMetaData, restoreSource, true); } /** * Initializes an existing index, to be restored from a snapshot */ public Builder initializeAsRestore(IndexMetaData indexMetaData, RestoreSource restoreSource) { return initializeAsRestore(indexMetaData, restoreSource, false); } /** * Initializes an index, to be restored from snapshot */ private Builder initializeAsRestore(IndexMetaData indexMetaData, RestoreSource restoreSource, boolean asNew) { if (!shards.isEmpty()) { throw new ElasticsearchIllegalStateException("trying to initialize an index with fresh shards, but already has shards created"); } for (int shardId = 0; shardId < indexMetaData.numberOfShards(); shardId++) { IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(new ShardId(indexMetaData.index(), shardId), asNew ? false : true); for (int i = 0; i <= indexMetaData.numberOfReplicas(); i++) { indexShardRoutingBuilder.addShard(new ImmutableShardRouting(index, shardId, null, null, i == 0 ? restoreSource : null, i == 0, ShardRoutingState.UNASSIGNED, 0)); } shards.put(shardId, indexShardRoutingBuilder.build()); } return this; } /** * Initializes a new empty index, with an option to control if its from an API or not. */ private Builder initializeEmpty(IndexMetaData indexMetaData, boolean asNew) { if (!shards.isEmpty()) { throw new ElasticsearchIllegalStateException("trying to initialize an index with fresh shards, but already has shards created"); } for (int shardId = 0; shardId < indexMetaData.numberOfShards(); shardId++) { IndexShardRoutingTable.Builder indexShardRoutingBuilder = new IndexShardRoutingTable.Builder(new ShardId(indexMetaData.index(), shardId), asNew ? false : true); for (int i = 0; i <= indexMetaData.numberOfReplicas(); i++) { indexShardRoutingBuilder.addShard(new ImmutableShardRouting(index, shardId, null, i == 0, ShardRoutingState.UNASSIGNED, 0)); } shards.put(shardId, indexShardRoutingBuilder.build()); } return this; } public Builder addReplica() { for (IntCursor cursor : shards.keys()) { int shardId = cursor.value; // version 0, will get updated when reroute will happen ImmutableShardRouting shard = new ImmutableShardRouting(index, shardId, null, false, ShardRoutingState.UNASSIGNED, 0); shards.put(shardId, new IndexShardRoutingTable.Builder(shards.get(shard.id())).addShard(shard).build() ); } return this; } public Builder removeReplica() { for (IntCursor cursor : shards.keys()) { int shardId = cursor.value; IndexShardRoutingTable indexShard = shards.get(shardId); if (indexShard.replicaShards().isEmpty()) { // nothing to do here! return this; } // re-add all the current ones IndexShardRoutingTable.Builder builder = new IndexShardRoutingTable.Builder(indexShard.shardId(), indexShard.primaryAllocatedPostApi()); for (ShardRouting shardRouting : indexShard) { builder.addShard(new ImmutableShardRouting(shardRouting)); } // first check if there is one that is not assigned to a node, and remove it boolean removed = false; for (ShardRouting shardRouting : indexShard) { if (!shardRouting.primary() && !shardRouting.assignedToNode()) { builder.removeShard(shardRouting); removed = true; break; } } if (!removed) { for (ShardRouting shardRouting : indexShard) { if (!shardRouting.primary()) { builder.removeShard(shardRouting); removed = true; break; } } } shards.put(shardId, builder.build()); } return this; } public Builder addIndexShard(IndexShardRoutingTable indexShard) { shards.put(indexShard.shardId().id(), indexShard); return this; } /** * Clears the post allocation flag for the specified shard */ public Builder clearPostAllocationFlag(ShardId shardId) { assert this.index.equals(shardId.index().name()); IndexShardRoutingTable indexShard = shards.get(shardId.id()); shards.put(indexShard.shardId().id(), new IndexShardRoutingTable(indexShard.shardId(), indexShard.shards(), false)); return this; } /** * Adds a new shard routing (makes a copy of it), with reference data used from the index shard routing table * if it needs to be created. */ public Builder addShard(IndexShardRoutingTable refData, ShardRouting shard) { IndexShardRoutingTable indexShard = shards.get(shard.id()); if (indexShard == null) { indexShard = new IndexShardRoutingTable.Builder(refData.shardId(), refData.primaryAllocatedPostApi()).addShard(new ImmutableShardRouting(shard)).build(); } else { indexShard = new IndexShardRoutingTable.Builder(indexShard).addShard(new ImmutableShardRouting(shard)).build(); } shards.put(indexShard.shardId().id(), indexShard); return this; } public IndexRoutingTable build() throws RoutingValidationException { IndexRoutingTable indexRoutingTable = new IndexRoutingTable(index, shards.build()); indexRoutingTable.validate(); return indexRoutingTable; } } public String prettyPrint() { StringBuilder sb = new StringBuilder("-- index [" + index + "]\n"); for (IndexShardRoutingTable indexShard : this) { sb.append("----shard_id [").append(indexShard.shardId().index().name()).append("][").append(indexShard.shardId().id()).append("]\n"); for (ShardRouting shard : indexShard) { sb.append("--------").append(shard.shortSummary()).append("\n"); } } return sb.toString(); } }
1no label
src_main_java_org_elasticsearch_cluster_routing_IndexRoutingTable.java
792
public class PercolateAction extends Action<PercolateRequest, PercolateResponse, PercolateRequestBuilder> { public static final PercolateAction INSTANCE = new PercolateAction(); public static final String NAME = "percolate"; private PercolateAction() { super(NAME); } @Override public PercolateResponse newResponse() { return new PercolateResponse(); } @Override public PercolateRequestBuilder newRequestBuilder(Client client) { return new PercolateRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_percolate_PercolateAction.java
1,765
public class GeoPoint { public static final String LATITUDE = GeoPointFieldMapper.Names.LAT; public static final String LONGITUDE = GeoPointFieldMapper.Names.LON; public static final String GEOHASH = GeoPointFieldMapper.Names.GEOHASH; private double lat; private double lon; public GeoPoint() { } public GeoPoint(double lat, double lon) { this.lat = lat; this.lon = lon; } public GeoPoint reset(double lat, double lon) { this.lat = lat; this.lon = lon; return this; } public GeoPoint resetLat(double lat) { this.lat = lat; return this; } public GeoPoint resetLon(double lon) { this.lon = lon; return this; } public GeoPoint resetFromString(String value) { int comma = value.indexOf(','); if (comma != -1) { lat = Double.parseDouble(value.substring(0, comma).trim()); lon = Double.parseDouble(value.substring(comma + 1).trim()); } else { resetFromGeoHash(value); } return this; } public GeoPoint resetFromGeoHash(String hash) { GeoHashUtils.decode(hash, this); return this; } void latlon(double lat, double lon) { this.lat = lat; this.lon = lon; } public final double lat() { return this.lat; } public final double getLat() { return this.lat; } public final double lon() { return this.lon; } public final double getLon() { return this.lon; } public final String geohash() { return GeoHashUtils.encode(lat, lon); } public final String getGeohash() { return GeoHashUtils.encode(lat, lon); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GeoPoint geoPoint = (GeoPoint) o; if (Double.compare(geoPoint.lat, lat) != 0) return false; if (Double.compare(geoPoint.lon, lon) != 0) return false; return true; } @Override public int hashCode() { int result; long temp; temp = lat != +0.0d ? Double.doubleToLongBits(lat) : 0L; result = (int) (temp ^ (temp >>> 32)); temp = lon != +0.0d ? Double.doubleToLongBits(lon) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public String toString() { return "[" + lat + ", " + lon + "]"; } public static GeoPoint parseFromLatLon(String latLon) { GeoPoint point = new GeoPoint(); point.resetFromString(latLon); return point; } /** * Parse a {@link GeoPoint} with a {@link XContentParser}: * * @param parser {@link XContentParser} to parse the value from * @return new {@link GeoPoint} parsed from the parse * * @throws IOException * @throws org.elasticsearch.ElasticsearchParseException */ public static GeoPoint parse(XContentParser parser) throws IOException, ElasticsearchParseException { return parse(parser, new GeoPoint()); } /** * Parse a {@link GeoPoint} with a {@link XContentParser}. A geopoint has one of the following forms: * * <ul> * <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li> * <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li> * <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li> * <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li> * </ul> * * @param parser {@link XContentParser} to parse the value from * @param point A {@link GeoPoint} that will be reset by the values parsed * @return new {@link GeoPoint} parsed from the parse * * @throws IOException * @throws org.elasticsearch.ElasticsearchParseException */ public static GeoPoint parse(XContentParser parser, GeoPoint point) throws IOException, ElasticsearchParseException { if(parser.currentToken() == Token.START_OBJECT) { while(parser.nextToken() != Token.END_OBJECT) { if(parser.currentToken() == Token.FIELD_NAME) { String field = parser.text(); if(LATITUDE.equals(field)) { if(parser.nextToken() == Token.VALUE_NUMBER) { point.resetLat(parser.doubleValue()); } else { throw new ElasticsearchParseException("latitude must be a number"); } } else if (LONGITUDE.equals(field)) { if(parser.nextToken() == Token.VALUE_NUMBER) { point.resetLon(parser.doubleValue()); } else { throw new ElasticsearchParseException("latitude must be a number"); } } else if (GEOHASH.equals(field)) { if(parser.nextToken() == Token.VALUE_STRING) { point.resetFromGeoHash(parser.text()); } else { throw new ElasticsearchParseException("geohash must be a string"); } } else { throw new ElasticsearchParseException("field must be either '" + LATITUDE + "', '" + LONGITUDE + "' or '" + GEOHASH + "'"); } } else { throw new ElasticsearchParseException("Token '"+parser.currentToken()+"' not allowed"); } } return point; } else if(parser.currentToken() == Token.START_ARRAY) { int element = 0; while(parser.nextToken() != Token.END_ARRAY) { if(parser.currentToken() == Token.VALUE_NUMBER) { element++; if(element == 1) { point.resetLon(parser.doubleValue()); } else if(element == 2) { point.resetLat(parser.doubleValue()); } else { throw new ElasticsearchParseException("only two values allowed"); } } else { throw new ElasticsearchParseException("Numeric value expected"); } } return point; } else if(parser.currentToken() == Token.VALUE_STRING) { String data = parser.text(); int comma = data.indexOf(','); if(comma > 0) { double lat = Double.parseDouble(data.substring(0, comma).trim()); double lon = Double.parseDouble(data.substring(comma + 1).trim()); return point.reset(lat, lon); } else { point.resetFromGeoHash(data); return point; } } else { throw new ElasticsearchParseException("geo_point expected"); } } }
1no label
src_main_java_org_elasticsearch_common_geo_GeoPoint.java
293
public interface DataDrivenEnumerationService { public DataDrivenEnumeration findEnumByKey(String enumKey); public DataDrivenEnumerationValue findEnumValueByKey(String enumKey, String enumValueKey); }
0true
common_src_main_java_org_broadleafcommerce_common_enumeration_service_DataDrivenEnumerationService.java
3,569
public class DateFieldMapper extends NumberFieldMapper<Long> { public static final String CONTENT_TYPE = "date"; public static class Defaults extends NumberFieldMapper.Defaults { public static final FormatDateTimeFormatter DATE_TIME_FORMATTER = Joda.forPattern("dateOptionalTime", Locale.ROOT); public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.freeze(); } public static final String NULL_VALUE = null; public static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS; public static final boolean ROUND_CEIL = true; } public static class Builder extends NumberFieldMapper.Builder<Builder, DateFieldMapper> { protected TimeUnit timeUnit = Defaults.TIME_UNIT; protected String nullValue = Defaults.NULL_VALUE; protected FormatDateTimeFormatter dateTimeFormatter = Defaults.DATE_TIME_FORMATTER; private Locale locale; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); builder = this; // do *NOT* rely on the default locale locale = Locale.ROOT; } public Builder timeUnit(TimeUnit timeUnit) { this.timeUnit = timeUnit; return this; } public Builder nullValue(String nullValue) { this.nullValue = nullValue; return this; } public Builder dateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) { this.dateTimeFormatter = dateTimeFormatter; return this; } @Override public DateFieldMapper build(BuilderContext context) { boolean roundCeil = Defaults.ROUND_CEIL; if (context.indexSettings() != null) { Settings settings = context.indexSettings(); roundCeil = settings.getAsBoolean("index.mapping.date.round_ceil", settings.getAsBoolean("index.mapping.date.parse_upper_inclusive", Defaults.ROUND_CEIL)); } fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f); if (!locale.equals(dateTimeFormatter.locale())) { dateTimeFormatter = new FormatDateTimeFormatter(dateTimeFormatter.format(), dateTimeFormatter.parser(), dateTimeFormatter.printer(), locale); } DateFieldMapper fieldMapper = new DateFieldMapper(buildNames(context), dateTimeFormatter, precisionStep, boost, fieldType, docValues, nullValue, timeUnit, roundCeil, ignoreMalformed(context), coerce(context), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); fieldMapper.includeInAll(includeInAll); return fieldMapper; } public Builder locale(Locale locale) { this.locale = locale; return this; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { DateFieldMapper.Builder builder = dateField(name); parseNumberField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(propNode.toString()); } else if (propName.equals("format")) { builder.dateTimeFormatter(parseDateTimeFormatter(propName, propNode)); } else if (propName.equals("numeric_resolution")) { builder.timeUnit(TimeUnit.valueOf(propNode.toString().toUpperCase(Locale.ROOT))); } else if (propName.equals("locale")) { builder.locale(parseLocale(propNode.toString())); } } return builder; } } // public for test public static Locale parseLocale(String locale) { final String[] parts = locale.split("_", -1); switch (parts.length) { case 3: // lang_country_variant return new Locale(parts[0], parts[1], parts[2]); case 2: // lang_country return new Locale(parts[0], parts[1]); case 1: if ("ROOT".equalsIgnoreCase(parts[0])) { return Locale.ROOT; } // lang return new Locale(parts[0]); default: throw new ElasticsearchIllegalArgumentException("Can't parse locale: [" + locale + "]"); } } protected FormatDateTimeFormatter dateTimeFormatter; // Triggers rounding up of the upper bound for range queries and filters if // set to true. // Rounding up a date here has the following meaning: If a date is not // defined with full precision, for example, no milliseconds given, the date // will be filled up to the next larger date with that precision. // Example: An upper bound given as "2000-01-01", will be converted to // "2000-01-01T23.59.59.999" private final boolean roundCeil; private final DateMathParser dateMathParser; private String nullValue; protected final TimeUnit timeUnit; protected DateFieldMapper(Names names, FormatDateTimeFormatter dateTimeFormatter, int precisionStep, float boost, FieldType fieldType, Boolean docValues, String nullValue, TimeUnit timeUnit, boolean roundCeil, Explicit<Boolean> ignoreMalformed,Explicit<Boolean> coerce, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(names, precisionStep, boost, fieldType, docValues, ignoreMalformed, coerce, new NamedAnalyzer("_date/" + precisionStep, new NumericDateAnalyzer(precisionStep, dateTimeFormatter.parser())), new NamedAnalyzer("_date/max", new NumericDateAnalyzer(Integer.MAX_VALUE, dateTimeFormatter.parser())), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo); this.dateTimeFormatter = dateTimeFormatter; this.nullValue = nullValue; this.timeUnit = timeUnit; this.roundCeil = roundCeil; this.dateMathParser = new DateMathParser(dateTimeFormatter, timeUnit); } public FormatDateTimeFormatter dateTimeFormatter() { return dateTimeFormatter; } public DateMathParser dateMathParser() { return dateMathParser; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("long"); } @Override protected int maxPrecisionStep() { return 64; } @Override public Long value(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return Numbers.bytesToLong((BytesRef) value); } return parseStringValue(value.toString()); } /** Dates should return as a string. */ @Override public Object valueForSearch(Object value) { if (value instanceof String) { // assume its the string that was indexed, just return it... (for example, with get) return value; } Long val = value(value); if (val == null) { return null; } return dateTimeFormatter.printer().print(val); } @Override public BytesRef indexedValueForSearch(Object value) { BytesRef bytesRef = new BytesRef(); NumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match return bytesRef; } private long parseValue(Object value) { if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return dateTimeFormatter.parser().parseMillis(((BytesRef) value).utf8ToString()); } return dateTimeFormatter.parser().parseMillis(value.toString()); } private String convertToString(Object value) { if (value instanceof BytesRef) { return ((BytesRef) value).utf8ToString(); } return value.toString(); } @Override public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) { long iValue = dateMathParser.parse(value, System.currentTimeMillis()); long iSim; try { iSim = fuzziness.asTimeValue().millis(); } catch (Exception e) { // not a time format iSim = fuzziness.asLong(); } return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, iValue - iSim, iValue + iSim, true, true); } @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { long lValue = parseToMilliseconds(value, context); return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, lValue, lValue, true, true); } public long parseToMilliseconds(Object value, @Nullable QueryParseContext context) { return parseToMilliseconds(value, context, false); } public long parseToMilliseconds(Object value, @Nullable QueryParseContext context, boolean includeUpper) { long now = context == null ? System.currentTimeMillis() : context.nowInMillis(); return includeUpper && roundCeil ? dateMathParser.parseRoundCeil(convertToString(value), now) : dateMathParser.parse(convertToString(value), now); } public long parseToMilliseconds(String value, @Nullable QueryParseContext context, boolean includeUpper) { long now = context == null ? System.currentTimeMillis() : context.nowInMillis(); return includeUpper && roundCeil ? dateMathParser.parseRoundCeil(value, now) : dateMathParser.parse(value, now); } @Override public Filter termFilter(Object value, @Nullable QueryParseContext context) { final long lValue = parseToMilliseconds(value, context); return NumericRangeFilter.newLongRange(names.indexName(), precisionStep, lValue, lValue, true, true); } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseToMilliseconds(lowerTerm, context), upperTerm == null ? null : parseToMilliseconds(upperTerm, context, includeUpper), includeLower, includeUpper); } @Override public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return rangeFilter(lowerTerm, upperTerm, includeLower, includeUpper, context, false); } public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context, boolean explicitCaching) { boolean cache = explicitCaching; Long lowerVal = null; Long upperVal = null; if (lowerTerm != null) { String value = convertToString(lowerTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); lowerVal = parseToMilliseconds(value, context, false); } if (upperTerm != null) { String value = convertToString(upperTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); upperVal = parseToMilliseconds(value, context, includeUpper); } Filter filter = NumericRangeFilter.newLongRange( names.indexName(), precisionStep, lowerVal, upperVal, includeLower, includeUpper ); if (!cache) { // We don't cache range filter if `now` date expression is used and also when a compound filter wraps // a range filter with a `now` date expressions. return NoCacheFilter.wrap(filter); } else { return filter; } } @Override public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return rangeFilter(fieldData, lowerTerm, upperTerm, includeLower, includeUpper, context, false); } public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context, boolean explicitCaching) { boolean cache = explicitCaching; Long lowerVal = null; Long upperVal = null; if (lowerTerm != null) { String value = convertToString(lowerTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); lowerVal = parseToMilliseconds(value, context, false); } if (upperTerm != null) { String value = convertToString(upperTerm); cache = explicitCaching || !hasNowExpressionWithNoRounding(value); upperVal = parseToMilliseconds(value, context, includeUpper); } Filter filter = NumericRangeFieldDataFilter.newLongRange( (IndexNumericFieldData<?>) fieldData.getForField(this), lowerVal,upperVal, includeLower, includeUpper ); if (!cache) { // We don't cache range filter if `now` date expression is used and also when a compound filter wraps // a range filter with a `now` date expressions. return NoCacheFilter.wrap(filter); } else { return filter; } } private boolean hasNowExpressionWithNoRounding(String value) { int index = value.indexOf("now"); if (index != -1) { if (value.length() == 3) { return true; } else { int indexOfPotentialRounding = index + 3; if (indexOfPotentialRounding >= value.length()) { return true; } else { char potentialRoundingChar; do { potentialRoundingChar = value.charAt(indexOfPotentialRounding++); if (potentialRoundingChar == '/') { return false; // We found the rounding char, so we shouldn't forcefully disable caching } else if (potentialRoundingChar == ' ') { return true; // Next token in the date math expression and no rounding found, so we should not cache. } } while (indexOfPotentialRounding < value.length()); return true; // Couldn't find rounding char, so we should not cache } } } else { return false; } } @Override public Filter nullValueFilter() { if (nullValue == null) { return null; } long value = parseStringValue(nullValue); return NumericRangeFilter.newLongRange(names.indexName(), precisionStep, value, value, true, true); } @Override protected boolean customBoost() { return true; } @Override protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException { String dateAsString = null; Long value = null; float boost = this.boost; if (context.externalValueSet()) { Object externalValue = context.externalValue(); if (externalValue instanceof Number) { value = ((Number) externalValue).longValue(); } else { dateAsString = (String) externalValue; if (dateAsString == null) { dateAsString = nullValue; } } } else { XContentParser parser = context.parser(); XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NULL) { dateAsString = nullValue; } else if (token == XContentParser.Token.VALUE_NUMBER) { value = parser.longValue(coerce.value()); } else if (token == XContentParser.Token.START_OBJECT) { String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) { if (token == XContentParser.Token.VALUE_NULL) { dateAsString = nullValue; } else if (token == XContentParser.Token.VALUE_NUMBER) { value = parser.longValue(coerce.value()); } else { dateAsString = parser.text(); } } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) { boost = parser.floatValue(); } else { throw new ElasticsearchIllegalArgumentException("unknown property [" + currentFieldName + "]"); } } } } else { dateAsString = parser.text(); } } if (dateAsString != null) { assert value == null; if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(names.fullName(), dateAsString, boost); } value = parseStringValue(dateAsString); } if (value != null) { if (fieldType.indexed() || fieldType.stored()) { CustomLongNumericField field = new CustomLongNumericField(this, value, fieldType); field.setBoost(boost); fields.add(field); } if (hasDocValues()) { addDocValue(context, value); } } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { super.merge(mergeWith, mergeContext); if (!this.getClass().equals(mergeWith.getClass())) { return; } if (!mergeContext.mergeFlags().simulate()) { this.nullValue = ((DateFieldMapper) mergeWith).nullValue; this.dateTimeFormatter = ((DateFieldMapper) mergeWith).dateTimeFormatter; } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || precisionStep != Defaults.PRECISION_STEP) { builder.field("precision_step", precisionStep); } builder.field("format", dateTimeFormatter.format()); if (includeDefaults || nullValue != null) { builder.field("null_value", nullValue); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } if (includeDefaults || timeUnit != Defaults.TIME_UNIT) { builder.field("numeric_resolution", timeUnit.name().toLowerCase(Locale.ROOT)); } // only serialize locale if needed, ROOT is the default, so no need to serialize that case as well... if (dateTimeFormatter.locale() != null && dateTimeFormatter.locale() != Locale.ROOT) { builder.field("locale", dateTimeFormatter.locale()); } else if (includeDefaults) { if (dateTimeFormatter.locale() == null) { builder.field("locale", Locale.ROOT); } else { builder.field("locale", dateTimeFormatter.locale()); } } } private long parseStringValue(String value) { try { return dateTimeFormatter.parser().parseMillis(value); } catch (RuntimeException e) { try { long time = Long.parseLong(value); return timeUnit.toMillis(time); } catch (NumberFormatException e1) { throw new MapperParsingException("failed to parse date field [" + value + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number with locale [" + dateTimeFormatter.locale() + "]", e); } } } }
1no label
src_main_java_org_elasticsearch_index_mapper_core_DateFieldMapper.java
102
CONTAINS { @Override public boolean evaluate(Object value, Object condition) { this.preevaluate(value,condition); if (value == null) return false; return evaluateRaw(value.toString(),(String)condition); } @Override public boolean evaluateRaw(String value, String terms) { Set<String> tokens = Sets.newHashSet(tokenize(value.toLowerCase())); terms = terms.trim(); List<String> tokenTerms = tokenize(terms.toLowerCase()); if (!terms.isEmpty() && tokenTerms.isEmpty()) return false; for (String term : tokenTerms) { if (!tokens.contains(term)) return false; } return true; } @Override public boolean isValidCondition(Object condition) { if (condition == null) return false; else if (condition instanceof String && StringUtils.isNotBlank((String) condition)) return true; else return false; } },
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Text.java
4,474
public class RecoverySettings extends AbstractComponent { public static final String INDICES_RECOVERY_FILE_CHUNK_SIZE = "indices.recovery.file_chunk_size"; public static final String INDICES_RECOVERY_TRANSLOG_OPS = "indices.recovery.translog_ops"; public static final String INDICES_RECOVERY_TRANSLOG_SIZE = "indices.recovery.translog_size"; public static final String INDICES_RECOVERY_COMPRESS = "indices.recovery.compress"; public static final String INDICES_RECOVERY_CONCURRENT_STREAMS = "indices.recovery.concurrent_streams"; public static final String INDICES_RECOVERY_CONCURRENT_SMALL_FILE_STREAMS = "indices.recovery.concurrent_small_file_streams"; public static final String INDICES_RECOVERY_MAX_BYTES_PER_SEC = "indices.recovery.max_bytes_per_sec"; public static final long SMALL_FILE_CUTOFF_BYTES = ByteSizeValue.parseBytesSizeValue("5mb").bytes(); /** * Use {@link #INDICES_RECOVERY_MAX_BYTES_PER_SEC} instead */ @Deprecated public static final String INDICES_RECOVERY_MAX_SIZE_PER_SEC = "indices.recovery.max_size_per_sec"; private volatile ByteSizeValue fileChunkSize; private volatile boolean compress; private volatile int translogOps; private volatile ByteSizeValue translogSize; private volatile int concurrentStreams; private volatile int concurrentSmallFileStreams; private final ThreadPoolExecutor concurrentStreamPool; private final ThreadPoolExecutor concurrentSmallFileStreamPool; private volatile ByteSizeValue maxBytesPerSec; private volatile SimpleRateLimiter rateLimiter; @Inject public RecoverySettings(Settings settings, NodeSettingsService nodeSettingsService) { super(settings); this.fileChunkSize = componentSettings.getAsBytesSize("file_chunk_size", settings.getAsBytesSize("index.shard.recovery.file_chunk_size", new ByteSizeValue(512, ByteSizeUnit.KB))); this.translogOps = componentSettings.getAsInt("translog_ops", settings.getAsInt("index.shard.recovery.translog_ops", 1000)); this.translogSize = componentSettings.getAsBytesSize("translog_size", settings.getAsBytesSize("index.shard.recovery.translog_size", new ByteSizeValue(512, ByteSizeUnit.KB))); this.compress = componentSettings.getAsBoolean("compress", true); this.concurrentStreams = componentSettings.getAsInt("concurrent_streams", settings.getAsInt("index.shard.recovery.concurrent_streams", 3)); this.concurrentStreamPool = EsExecutors.newScaling(0, concurrentStreams, 60, TimeUnit.SECONDS, EsExecutors.daemonThreadFactory(settings, "[recovery_stream]")); this.concurrentSmallFileStreams = componentSettings.getAsInt("concurrent_small_file_streams", settings.getAsInt("index.shard.recovery.concurrent_small_file_streams", 2)); this.concurrentSmallFileStreamPool = EsExecutors.newScaling(0, concurrentSmallFileStreams, 60, TimeUnit.SECONDS, EsExecutors.daemonThreadFactory(settings, "[small_file_recovery_stream]")); this.maxBytesPerSec = componentSettings.getAsBytesSize("max_bytes_per_sec", componentSettings.getAsBytesSize("max_size_per_sec", new ByteSizeValue(20, ByteSizeUnit.MB))); if (maxBytesPerSec.bytes() <= 0) { rateLimiter = null; } else { rateLimiter = new SimpleRateLimiter(maxBytesPerSec.mbFrac()); } logger.debug("using max_bytes_per_sec[{}], concurrent_streams [{}], file_chunk_size [{}], translog_size [{}], translog_ops [{}], and compress [{}]", maxBytesPerSec, concurrentStreams, fileChunkSize, translogSize, translogOps, compress); nodeSettingsService.addListener(new ApplySettings()); } public void close() { concurrentStreamPool.shutdown(); try { concurrentStreamPool.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { // that's fine... } concurrentStreamPool.shutdownNow(); } public ByteSizeValue fileChunkSize() { return fileChunkSize; } public boolean compress() { return compress; } public int translogOps() { return translogOps; } public ByteSizeValue translogSize() { return translogSize; } public int concurrentStreams() { return concurrentStreams; } public ThreadPoolExecutor concurrentStreamPool() { return concurrentStreamPool; } public ThreadPoolExecutor concurrentSmallFileStreamPool() { return concurrentSmallFileStreamPool; } public RateLimiter rateLimiter() { return rateLimiter; } class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { ByteSizeValue maxSizePerSec = settings.getAsBytesSize(INDICES_RECOVERY_MAX_BYTES_PER_SEC, settings.getAsBytesSize(INDICES_RECOVERY_MAX_SIZE_PER_SEC, RecoverySettings.this.maxBytesPerSec)); if (!Objects.equal(maxSizePerSec, RecoverySettings.this.maxBytesPerSec)) { logger.info("updating [{}] from [{}] to [{}]", INDICES_RECOVERY_MAX_BYTES_PER_SEC, RecoverySettings.this.maxBytesPerSec, maxSizePerSec); RecoverySettings.this.maxBytesPerSec = maxSizePerSec; if (maxSizePerSec.bytes() <= 0) { rateLimiter = null; } else if (rateLimiter != null) { rateLimiter.setMbPerSec(maxSizePerSec.mbFrac()); } else { rateLimiter = new SimpleRateLimiter(maxSizePerSec.mbFrac()); } } ByteSizeValue fileChunkSize = settings.getAsBytesSize(INDICES_RECOVERY_FILE_CHUNK_SIZE, RecoverySettings.this.fileChunkSize); if (!fileChunkSize.equals(RecoverySettings.this.fileChunkSize)) { logger.info("updating [indices.recovery.file_chunk_size] from [{}] to [{}]", RecoverySettings.this.fileChunkSize, fileChunkSize); RecoverySettings.this.fileChunkSize = fileChunkSize; } int translogOps = settings.getAsInt(INDICES_RECOVERY_TRANSLOG_OPS, RecoverySettings.this.translogOps); if (translogOps != RecoverySettings.this.translogOps) { logger.info("updating [indices.recovery.translog_ops] from [{}] to [{}]", RecoverySettings.this.translogOps, translogOps); RecoverySettings.this.translogOps = translogOps; } ByteSizeValue translogSize = settings.getAsBytesSize(INDICES_RECOVERY_TRANSLOG_SIZE, RecoverySettings.this.translogSize); if (!translogSize.equals(RecoverySettings.this.translogSize)) { logger.info("updating [indices.recovery.translog_size] from [{}] to [{}]", RecoverySettings.this.translogSize, translogSize); RecoverySettings.this.translogSize = translogSize; } boolean compress = settings.getAsBoolean(INDICES_RECOVERY_COMPRESS, RecoverySettings.this.compress); if (compress != RecoverySettings.this.compress) { logger.info("updating [indices.recovery.compress] from [{}] to [{}]", RecoverySettings.this.compress, compress); RecoverySettings.this.compress = compress; } int concurrentStreams = settings.getAsInt(INDICES_RECOVERY_CONCURRENT_STREAMS, RecoverySettings.this.concurrentStreams); if (concurrentStreams != RecoverySettings.this.concurrentStreams) { logger.info("updating [indices.recovery.concurrent_streams] from [{}] to [{}]", RecoverySettings.this.concurrentStreams, concurrentStreams); RecoverySettings.this.concurrentStreams = concurrentStreams; RecoverySettings.this.concurrentStreamPool.setMaximumPoolSize(concurrentStreams); } int concurrentSmallFileStreams = settings.getAsInt(INDICES_RECOVERY_CONCURRENT_SMALL_FILE_STREAMS, RecoverySettings.this.concurrentSmallFileStreams); if (concurrentSmallFileStreams != RecoverySettings.this.concurrentSmallFileStreams) { logger.info("updating [indices.recovery.concurrent_small_file_streams] from [{}] to [{}]", RecoverySettings.this.concurrentSmallFileStreams, concurrentSmallFileStreams); RecoverySettings.this.concurrentSmallFileStreams = concurrentSmallFileStreams; RecoverySettings.this.concurrentSmallFileStreamPool.setMaximumPoolSize(concurrentSmallFileStreams); } } } }
1no label
src_main_java_org_elasticsearch_indices_recovery_RecoverySettings.java
359
future.andThen(new ExecutionCallback<Integer>() { @Override public void onResponse(Integer response) { result[0] = response.intValue(); semaphore.release(); } @Override public void onFailure(Throwable t) { semaphore.release(); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
821
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_OFFER_INFO") public class OfferInfoImpl implements OfferInfo { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "OfferInfoId") @GenericGenerator( name="OfferInfoId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="OfferInfoImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OfferInfoImpl") } ) @Column(name = "OFFER_INFO_ID") protected Long id; @ElementCollection @MapKeyColumn(name="FIELD_NAME") @Column(name="FIELD_VALUE") @CollectionTable(name="BLC_OFFER_INFO_FIELDS", joinColumns=@JoinColumn(name="OFFER_INFO_FIELDS_ID")) @BatchSize(size = 50) protected Map<String, String> fieldValues = new HashMap<String, String>(); @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public Map<String, String> getFieldValues() { return fieldValues; } @Override public void setFieldValues(Map<String, String> fieldValues) { this.fieldValues = fieldValues; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fieldValues == null) ? 0 : fieldValues.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OfferInfoImpl other = (OfferInfoImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (fieldValues == null) { if (other.fieldValues != null) return false; } else if (!fieldValues.equals(other.fieldValues)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OfferInfoImpl.java
815
public class ClearScrollAction extends Action<ClearScrollRequest, ClearScrollResponse, ClearScrollRequestBuilder> { public static final ClearScrollAction INSTANCE = new ClearScrollAction(); public static final String NAME = "clear_sc"; private ClearScrollAction() { super(NAME); } @Override public ClearScrollResponse newResponse() { return new ClearScrollResponse(); } @Override public ClearScrollRequestBuilder newRequestBuilder(Client client) { return new ClearScrollRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_search_ClearScrollAction.java
144
static final class ThreadHashCode extends ThreadLocal<HashCode> { public HashCode initialValue() { return new HashCode(); } }
0true
src_main_java_jsr166e_Striped64.java
669
public class DeleteWarmerRequest extends AcknowledgedRequest<DeleteWarmerRequest> { private String[] names = Strings.EMPTY_ARRAY; private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, false); private String[] indices = Strings.EMPTY_ARRAY; DeleteWarmerRequest() { } /** * Constructs a new delete warmer request for the specified name. * * @param name: the name (or wildcard expression) of the warmer to match, null to delete all. */ public DeleteWarmerRequest(String... names) { names(names); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (CollectionUtils.isEmpty(names)) { validationException = addValidationError("warmer names are missing", validationException); } else { validationException = checkForEmptyString(validationException, names); } if (CollectionUtils.isEmpty(indices)) { validationException = addValidationError("indices are missing", validationException); } else { validationException = checkForEmptyString(validationException, indices); } return validationException; } private ActionRequestValidationException checkForEmptyString(ActionRequestValidationException validationException, String[] strings) { boolean containsEmptyString = false; for (String string : strings) { if (!Strings.hasText(string)) { containsEmptyString = true; } } if (containsEmptyString) { validationException = addValidationError("types must not contain empty strings", validationException); } return validationException; } /** * The name to delete. */ @Nullable String[] names() { return names; } /** * The name (or wildcard expression) of the index warmer to delete, or null * to delete all warmers. */ public DeleteWarmerRequest names(@Nullable String... names) { this.names = names; return this; } /** * Sets the indices this put mapping operation will execute on. */ public DeleteWarmerRequest indices(String... indices) { this.indices = indices; return this; } /** * The indices the mappings will be put. */ public String[] indices() { return indices; } public IndicesOptions indicesOptions() { return indicesOptions; } public DeleteWarmerRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); names = in.readStringArray(); indices = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); readTimeout(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArrayNullable(names); out.writeStringArrayNullable(indices); indicesOptions.writeIndicesOptions(out); writeTimeout(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_warmer_delete_DeleteWarmerRequest.java
216
public class ClientOutSelectorImpl extends ClientAbstractIOSelector { public ClientOutSelectorImpl(ThreadGroup threadGroup) { super(threadGroup, "OutSelector"); } @Override protected void handleSelectionKey(SelectionKey sk) { if (sk.isValid() && sk.isWritable()) { sk.interestOps(sk.interestOps() & ~SelectionKey.OP_WRITE); final SelectionHandler handler = (SelectionHandler) sk.attachment(); handler.handle(); } } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientOutSelectorImpl.java
546
refreshAction.execute(Requests.refreshRequest(request.indices()), new ActionListener<RefreshResponse>() { @Override public void onResponse(RefreshResponse refreshResponse) { removeMapping(); } @Override public void onFailure(Throwable e) { removeMapping(); } protected void removeMapping() { DeleteMappingClusterStateUpdateRequest clusterStateUpdateRequest = new DeleteMappingClusterStateUpdateRequest() .indices(request.indices()).types(request.types()) .ackTimeout(request.timeout()) .masterNodeTimeout(request.masterNodeTimeout()); metaDataMappingService.removeMapping(clusterStateUpdateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new DeleteMappingResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } }); } });
1no label
src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_TransportDeleteMappingAction.java
44
@Component("blPageTemplateCustomPersistenceHandler") public class PageTemplateCustomPersistenceHandler extends CustomPersistenceHandlerAdapter { private final Log LOG = LogFactory.getLog(PageTemplateCustomPersistenceHandler.class); @Resource(name="blPageService") protected PageService pageService; @Resource(name="blSandBoxService") protected SandBoxService sandBoxService; @Resource(name = "blDynamicFieldPersistenceHandlerHelper") protected DynamicFieldPersistenceHandlerHelper dynamicFieldUtil; @Override public Boolean canHandleFetch(PersistencePackage persistencePackage) { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); return PageTemplate.class.getName().equals(ceilingEntityFullyQualifiedClassname) && persistencePackage.getCustomCriteria() != null && persistencePackage.getCustomCriteria().length > 0 && persistencePackage.getCustomCriteria()[0].equals("constructForm"); } @Override public Boolean canHandleAdd(PersistencePackage persistencePackage) { return canHandleFetch(persistencePackage); } @Override public Boolean canHandleInspect(PersistencePackage persistencePackage) { return canHandleFetch(persistencePackage); } @Override public Boolean canHandleRemove(PersistencePackage persistencePackage) { return false; } @Override public Boolean canHandleUpdate(PersistencePackage persistencePackage) { return canHandleFetch(persistencePackage); } protected SandBox getSandBox() { return sandBoxService.retrieveSandboxById(SandBoxContext.getSandBoxContext().getSandBoxId()); } @Override public DynamicResultSet inspect(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, InspectHelper helper) throws ServiceException { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); try { String pageTemplateId = persistencePackage.getCustomCriteria()[3]; PageTemplate template = pageService.findPageTemplateById(Long.valueOf(pageTemplateId)); ClassMetadata metadata = new ClassMetadata(); metadata.setCeilingType(PageTemplate.class.getName()); ClassTree entities = new ClassTree(PageTemplateImpl.class.getName()); metadata.setPolymorphicEntities(entities); Property[] properties = dynamicFieldUtil.buildDynamicPropertyList(template.getFieldGroups(), PageTemplate.class); metadata.setProperties(properties); DynamicResultSet results = new DynamicResultSet(metadata); return results; } catch (Exception e) { throw new ServiceException("Unable to perform inspect for entity: "+ceilingEntityFullyQualifiedClassname, e); } } @Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); try { String pageId = persistencePackage.getCustomCriteria()[1]; Entity entity = fetchEntityBasedOnId(pageId); DynamicResultSet results = new DynamicResultSet(new Entity[]{entity}, 1); return results; } catch (Exception e) { throw new ServiceException("Unable to perform fetch for entity: "+ceilingEntityFullyQualifiedClassname, e); } } protected Entity fetchEntityBasedOnId(String pageId) throws Exception { Page page = pageService.findPageById(Long.valueOf(pageId)); Map<String, PageField> pageFieldMap = page.getPageFields(); Entity entity = new Entity(); entity.setType(new String[]{PageTemplateImpl.class.getName()}); List<Property> propertiesList = new ArrayList<Property>(); for (FieldGroup fieldGroup : page.getPageTemplate().getFieldGroups()) { for (FieldDefinition definition : fieldGroup.getFieldDefinitions()) { Property property = new Property(); propertiesList.add(property); property.setName(definition.getName()); String value = null; if (!MapUtils.isEmpty(pageFieldMap)) { PageField pageField = pageFieldMap.get(definition.getName()); if (pageField == null) { value = ""; } else { value = pageField.getValue(); } } property.setValue(value); } } Property property = new Property(); propertiesList.add(property); property.setName("id"); property.setValue(pageId); entity.setProperties(propertiesList.toArray(new Property[]{})); return entity; } @Override public Entity update(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { return addOrUpdate(persistencePackage, dynamicEntityDao, helper); } @Override public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { return addOrUpdate(persistencePackage, dynamicEntityDao, helper); } protected Entity addOrUpdate(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); try { String pageId = persistencePackage.getCustomCriteria()[1]; Page page = pageService.findPageById(Long.valueOf(pageId)); Property[] properties = dynamicFieldUtil.buildDynamicPropertyList(page.getPageTemplate().getFieldGroups(), PageTemplate.class); Map<String, FieldMetadata> md = new HashMap<String, FieldMetadata>(); for (Property property : properties) { md.put(property.getName(), property.getMetadata()); } boolean validated = helper.validate(persistencePackage.getEntity(), null, md); if (!validated) { throw new ValidationException(persistencePackage.getEntity(), "Page dynamic fields failed validation"); } List<String> templateFieldNames = new ArrayList<String>(20); for (FieldGroup group : page.getPageTemplate().getFieldGroups()) { for (FieldDefinition definition: group.getFieldDefinitions()) { templateFieldNames.add(definition.getName()); } } Map<String, PageField> pageFieldMap = page.getPageFields(); for (Property property : persistencePackage.getEntity().getProperties()) { if (templateFieldNames.contains(property.getName())) { PageField pageField = pageFieldMap.get(property.getName()); if (pageField != null) { pageField.setValue(property.getValue()); } else { pageField = new PageFieldImpl(); pageFieldMap.put(property.getName(), pageField); pageField.setFieldKey(property.getName()); pageField.setPage(page); pageField.setValue(property.getValue()); } } } List<String> removeItems = new ArrayList<String>(); for (String key : pageFieldMap.keySet()) { if (persistencePackage.getEntity().findProperty(key)==null) { removeItems.add(key); } } if (removeItems.size() > 0) { for (String removeKey : removeItems) { PageField pageField = pageFieldMap.remove(removeKey); pageField.setPage(null); } } pageService.updatePage(page, getSandBox()); return fetchEntityBasedOnId(pageId); } catch (ValidationException e) { throw e; } catch (Exception e) { throw new ServiceException("Unable to perform update for entity: "+ceilingEntityFullyQualifiedClassname, e); } } }
1no label
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_admin_server_handler_PageTemplateCustomPersistenceHandler.java
1,036
@SuppressWarnings("unchecked") public class OCommandExecutorSQLDropClass extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest { public static final String KEYWORD_DROP = "DROP"; public static final String KEYWORD_CLASS = "CLASS"; private String className; public OCommandExecutorSQLDropClass parse(final OCommandRequest iRequest) { init((OCommandRequestText) iRequest); final StringBuilder word = new StringBuilder(); int oldPos = 0; int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true); if (pos == -1 || !word.toString().equals(KEYWORD_DROP)) throw new OCommandSQLParsingException("Keyword " + KEYWORD_DROP + " not found. Use " + getSyntax(), parserText, oldPos); pos = nextWord(parserText, parserTextUpperCase, pos, word, true); if (pos == -1 || !word.toString().equals(KEYWORD_CLASS)) throw new OCommandSQLParsingException("Keyword " + KEYWORD_CLASS + " not found. Use " + getSyntax(), parserText, oldPos); pos = nextWord(parserText, parserTextUpperCase, pos, word, false); if (pos == -1) throw new OCommandSQLParsingException("Expected <class>. Use " + getSyntax(), parserText, pos); className = word.toString(); return this; } /** * Execute the DROP CLASS. */ public Object execute(final Map<Object, Object> iArgs) { if (className == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final ODatabaseRecord database = getDatabase(); final OClass oClass = database.getMetadata().getSchema().getClass(className); if (oClass == null) return null; for (final OIndex<?> oIndex : oClass.getClassIndexes()) { database.getMetadata().getIndexManager().dropIndex(oIndex.getName()); } final OClass superClass = oClass.getSuperClass(); final int[] clustersToIndex = oClass.getPolymorphicClusterIds(); final String[] clusterNames = new String[clustersToIndex.length]; for (int i = 0; i < clustersToIndex.length; i++) { clusterNames[i] = database.getClusterNameById(clustersToIndex[i]); } final int clusterId = oClass.getDefaultClusterId(); ((OSchemaProxy) database.getMetadata().getSchema()).dropClassInternal(className); ((OSchemaProxy) database.getMetadata().getSchema()).saveInternal(); database.getMetadata().getSchema().reload(); deleteDefaultCluster(clusterId); if (superClass == null) return true; for (final OIndex<?> oIndex : superClass.getIndexes()) { for (final String clusterName : clusterNames) oIndex.getInternal().removeCluster(clusterName); OLogManager.instance() .info(this, "Index %s is used in super class of %s and should be rebuilt.", oIndex.getName(), className); oIndex.rebuild(); } return true; } protected void deleteDefaultCluster(int clusterId) { final ODatabaseRecord database = getDatabase(); OCluster cluster = database.getStorage().getClusterById(clusterId); if (cluster.getName().equalsIgnoreCase(className)) { if (isClusterDeletable(clusterId)) { database.getStorage().dropCluster(clusterId, true); } } } protected boolean isClusterDeletable(int clusterId) { final ODatabaseRecord database = getDatabase(); for (OClass iClass : database.getMetadata().getSchema().getClasses()) { for (int i : iClass.getClusterIds()) { if (i == clusterId) return false; } } return true; } @Override public String getSyntax() { return "DROP CLASS <class>"; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLDropClass.java
181
@RunWith(Parameterized.class) public abstract class IDAuthorityTest { private static final Logger log = LoggerFactory.getLogger(IDAuthorityTest.class); public static final int CONCURRENCY = 8; public static final int MAX_NUM_PARTITIONS = 4; public static final String DB_NAME = "test"; public static final Duration GET_ID_BLOCK_TIMEOUT = new StandardDuration(300000L, TimeUnit.MILLISECONDS); @Parameterized.Parameters public static Collection<Object[]> configs() { List<Object[]> configurations = new ArrayList<Object[]>(); ModifiableConfiguration c = getBasicConfig(); configurations.add(new Object[]{c.getConfiguration()}); c = getBasicConfig(); c.set(IDAUTHORITY_CAV_BITS,9); c.set(IDAUTHORITY_CAV_TAG,511); configurations.add(new Object[]{c.getConfiguration()}); c = getBasicConfig(); c.set(IDAUTHORITY_CAV_RETRIES,10); c.set(IDAUTHORITY_WAIT, new StandardDuration(10L, TimeUnit.MILLISECONDS)); c.set(IDAUTHORITY_CAV_BITS,7); //c.set(IDAUTHORITY_RANDOMIZE_UNIQUEID,true); c.set(IDAUTHORITY_CONFLICT_AVOIDANCE, ConflictAvoidanceMode.GLOBAL_AUTO); configurations.add(new Object[]{c.getConfiguration()}); return configurations; } public static ModifiableConfiguration getBasicConfig() { ModifiableConfiguration c = GraphDatabaseConfiguration.buildConfiguration(); c.set(IDAUTHORITY_WAIT, new StandardDuration(100L, TimeUnit.MILLISECONDS)); c.set(IDS_BLOCK_SIZE,400); return c; } public KeyColumnValueStoreManager[] manager; public IDAuthority[] idAuthorities; public WriteConfiguration baseStoreConfiguration; public final int uidBitWidth; public final boolean hasFixedUid; public final boolean hasEmptyUid; public final long blockSize; public final long idUpperBoundBitWidth; public final long idUpperBound; public IDAuthorityTest(WriteConfiguration baseConfig) { Preconditions.checkNotNull(baseConfig); TestGraphConfigs.applyOverrides(baseConfig); this.baseStoreConfiguration = baseConfig; Configuration config = StorageSetup.getConfig(baseConfig); uidBitWidth = config.get(IDAUTHORITY_CAV_BITS); //hasFixedUid = !config.get(IDAUTHORITY_RANDOMIZE_UNIQUEID); hasFixedUid = !ConflictAvoidanceMode.GLOBAL_AUTO.equals(config.get(IDAUTHORITY_CONFLICT_AVOIDANCE)); hasEmptyUid = uidBitWidth==0; blockSize = config.get(IDS_BLOCK_SIZE); idUpperBoundBitWidth = 30; idUpperBound = 1l<<idUpperBoundBitWidth; } @Before public void setUp() throws Exception { StoreManager m = openStorageManager(); m.clearStorage(); m.close(); open(); } public abstract KeyColumnValueStoreManager openStorageManager() throws BackendException; public void open() throws BackendException { manager = new KeyColumnValueStoreManager[CONCURRENCY]; idAuthorities = new IDAuthority[CONCURRENCY]; for (int i = 0; i < CONCURRENCY; i++) { ModifiableConfiguration sc = StorageSetup.getConfig(baseStoreConfiguration.copy()); //sc.set(GraphDatabaseConfiguration.INSTANCE_RID_SHORT,(short)i); sc.set(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID_SUFFIX, (short)i); if (!sc.has(UNIQUE_INSTANCE_ID)) { String uniqueGraphId = getOrGenerateUniqueInstanceId(sc); log.debug("Setting unique instance id: {}", uniqueGraphId); sc.set(UNIQUE_INSTANCE_ID, uniqueGraphId); } sc.set(GraphDatabaseConfiguration.CLUSTER_PARTITION,true); sc.set(GraphDatabaseConfiguration.CLUSTER_MAX_PARTITIONS,MAX_NUM_PARTITIONS); manager[i] = openStorageManager(); StoreFeatures storeFeatures = manager[i].getFeatures(); KeyColumnValueStore idStore = manager[i].openDatabase("ids"); if (storeFeatures.isKeyConsistent()) idAuthorities[i] = new ConsistentKeyIDAuthority(idStore, manager[i], sc); else throw new IllegalArgumentException("Cannot open id store"); } } @After public void tearDown() throws Exception { close(); } public void close() throws BackendException { for (int i = 0; i < CONCURRENCY; i++) { idAuthorities[i].close(); manager[i].close(); } } private class InnerIDBlockSizer implements IDBlockSizer { @Override public long getBlockSize(int idNamespace) { return blockSize; } @Override public long getIdUpperBound(int idNamespace) { return idUpperBound; } } private void checkBlock(IDBlock block) { assertTrue(blockSize<10000); LongSet ids = new LongOpenHashSet((int)blockSize); checkBlock(block,ids); } private void checkBlock(IDBlock block, LongSet ids) { assertEquals(blockSize,block.numIds()); for (int i=0;i<blockSize;i++) { long id = block.getId(i); assertEquals(id,block.getId(i)); assertFalse(ids.contains(id)); assertTrue(id<idUpperBound); assertTrue(id>0); ids.add(id); } if (hasEmptyUid) { assertEquals(blockSize-1,block.getId(block.numIds()-1)-block.getId(0)); } try { block.getId(blockSize); fail(); } catch (ArrayIndexOutOfBoundsException e) {} } // private void checkIdList(List<Long> ids) { // Collections.sort(ids); // for (int i=1;i<ids.size();i++) { // long current = ids.get(i); // long previous = ids.get(i-1); // Assert.assertTrue(current>0); // Assert.assertTrue(previous>0); // Assert.assertTrue("ID block allocated twice: blockstart=" + current + ", indices=(" + i + ", " + (i-1) + ")", current!=previous); // Assert.assertTrue("ID blocks allocated in non-increasing order: " + previous + " then " + current, current>previous); // Assert.assertTrue(previous+blockSize<=current); // // if (hasFixedUid) { // Assert.assertTrue(current + " vs " + previous, 0 == (current - previous) % blockSize); // final long skipped = (current - previous) / blockSize; // Assert.assertTrue(0 <= skipped); // } // } // } @Test public void testAuthorityUniqueIDsAreDistinct() { /* Check that each IDAuthority was created with a unique id. Duplicate * values reflect a problem in either this test or the * implementation-under-test. */ Set<String> uids = new HashSet<String>(); String uidErrorMessage = "Uniqueness failure detected for config option " + UNIQUE_INSTANCE_ID.getName(); for (int i = 0; i < CONCURRENCY; i++) { String uid = idAuthorities[i].getUniqueID(); Assert.assertTrue(uidErrorMessage, !uids.contains(uid)); uids.add(uid); } assertEquals(uidErrorMessage, CONCURRENCY, uids.size()); } @Test public void testSimpleIDAcquisition() throws BackendException { final IDBlockSizer blockSizer = new InnerIDBlockSizer(); idAuthorities[0].setIDBlockSizer(blockSizer); int numTrials = 100; LongSet ids = new LongOpenHashSet((int)blockSize*numTrials); long previous = 0; for (int i=0;i<numTrials;i++) { IDBlock block = idAuthorities[0].getIDBlock(0, 0, GET_ID_BLOCK_TIMEOUT); checkBlock(block,ids); if (hasEmptyUid) { if (previous!=0) assertEquals(previous+1, block.getId(0)); previous=block.getId(block.numIds()-1); } } } @Test public void testIDExhaustion() throws BackendException { final int chunks = 30; final IDBlockSizer blockSizer = new IDBlockSizer() { @Override public long getBlockSize(int idNamespace) { return ((1l<<(idUpperBoundBitWidth-uidBitWidth))-1)/chunks; } @Override public long getIdUpperBound(int idNamespace) { return idUpperBound; } }; idAuthorities[0].setIDBlockSizer(blockSizer); if (hasFixedUid) { for (int i=0;i<chunks;i++) { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); } try { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); Assert.fail(); } catch (IDPoolExhaustedException e) {} } else { for (int i=0;i<(chunks*Math.max(1,(1<<uidBitWidth)/10));i++) { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); } try { for (int i=0;i<(chunks*Math.max(1,(1<<uidBitWidth)*9/10));i++) { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); } Assert.fail(); } catch (IDPoolExhaustedException e) {} } } @Test public void testLocalPartitionAcquisition() throws BackendException { for (int c = 0; c < CONCURRENCY; c++) { if (manager[c].getFeatures().hasLocalKeyPartition()) { try { List<KeyRange> partitions = idAuthorities[c].getLocalIDPartition(); for (KeyRange range : partitions) { assertEquals(range.getStart().length(), range.getEnd().length()); for (int i = 0; i < 2; i++) { Assert.assertTrue(range.getAt(i).length() >= 4); } } } catch (UnsupportedOperationException e) { Assert.fail(); } } } } @Test public void testManyThreadsOneIDAuthority() throws BackendException, InterruptedException, ExecutionException { ExecutorService es = Executors.newFixedThreadPool(CONCURRENCY); final IDAuthority targetAuthority = idAuthorities[0]; targetAuthority.setIDBlockSizer(new InnerIDBlockSizer()); final int targetPartition = 0; final int targetNamespace = 2; final ConcurrentLinkedQueue<IDBlock> blocks = new ConcurrentLinkedQueue<IDBlock>(); final int blocksPerThread = 40; Assert.assertTrue(0 < blocksPerThread); List <Future<Void>> futures = new ArrayList<Future<Void>>(CONCURRENCY); // Start some concurrent threads getting blocks the same ID authority and same partition in that authority for (int c = 0; c < CONCURRENCY; c++) { futures.add(es.submit(new Callable<Void>() { @Override public Void call() { try { getBlock(); } catch (BackendException e) { throw new RuntimeException(e); } return null; } private void getBlock() throws BackendException { for (int i = 0; i < blocksPerThread; i++) { IDBlock block = targetAuthority.getIDBlock(targetPartition,targetNamespace, GET_ID_BLOCK_TIMEOUT); Assert.assertNotNull(block); blocks.add(block); } } })); } for (Future<Void> f : futures) { try { f.get(); } catch (ExecutionException e) { throw e; } } es.shutdownNow(); assertEquals(blocksPerThread * CONCURRENCY, blocks.size()); LongSet ids = new LongOpenHashSet((int)blockSize*blocksPerThread*CONCURRENCY); for (IDBlock block : blocks) checkBlock(block,ids); } @Test public void testMultiIDAcquisition() throws Throwable { final int numPartitions = MAX_NUM_PARTITIONS; final int numAcquisitionsPerThreadPartition = 100; final IDBlockSizer blockSizer = new InnerIDBlockSizer(); for (int i = 0; i < CONCURRENCY; i++) idAuthorities[i].setIDBlockSizer(blockSizer); final List<ConcurrentLinkedQueue<IDBlock>> ids = new ArrayList<ConcurrentLinkedQueue<IDBlock>>(numPartitions); for (int i = 0; i < numPartitions; i++) { ids.add(new ConcurrentLinkedQueue<IDBlock>()); } final int maxIterations = numAcquisitionsPerThreadPartition * numPartitions * 2; final Collection<Future<?>> futures = new ArrayList<Future<?>>(CONCURRENCY); ExecutorService es = Executors.newFixedThreadPool(CONCURRENCY); Set<String> uids = new HashSet<String>(CONCURRENCY); for (int i = 0; i < CONCURRENCY; i++) { final IDAuthority idAuthority = idAuthorities[i]; final IDStressor stressRunnable = new IDStressor( numAcquisitionsPerThreadPartition, numPartitions, maxIterations, idAuthority, ids); uids.add(idAuthority.getUniqueID()); futures.add(es.submit(stressRunnable)); } // If this fails, it's likely to be a bug in the test rather than the // IDAuthority (the latter is technically possible, just less likely) assertEquals(CONCURRENCY, uids.size()); for (Future<?> f : futures) { try { f.get(); } catch (ExecutionException e) { throw e.getCause(); } } for (int i = 0; i < numPartitions; i++) { ConcurrentLinkedQueue<IDBlock> list = ids.get(i); assertEquals(numAcquisitionsPerThreadPartition * CONCURRENCY, list.size()); LongSet idset = new LongOpenHashSet((int)blockSize*list.size()); for (IDBlock block : list) checkBlock(block,idset); } es.shutdownNow(); } private class IDStressor implements Runnable { private final int numRounds; private final int numPartitions; private final int maxIterations; private final IDAuthority authority; private final List<ConcurrentLinkedQueue<IDBlock>> allocatedBlocks; private static final long sleepMS = 250L; private IDStressor(int numRounds, int numPartitions, int maxIterations, IDAuthority authority, List<ConcurrentLinkedQueue<IDBlock>> ids) { this.numRounds = numRounds; this.numPartitions = numPartitions; this.maxIterations = maxIterations; this.authority = authority; this.allocatedBlocks = ids; } @Override public void run() { try { runInterruptible(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private void runInterruptible() throws InterruptedException { int iterations = 0; long lastStart[] = new long[numPartitions]; for (int i = 0; i < numPartitions; i++) lastStart[i] = Long.MIN_VALUE; for (int j = 0; j < numRounds; j++) { for (int p = 0; p < numPartitions; p++) { if (maxIterations < ++iterations) { throwIterationsExceededException(); } final IDBlock block = allocate(p); if (null == block) { Thread.sleep(sleepMS); p--; } else { allocatedBlocks.get(p).add(block); if (hasEmptyUid) { long start = block.getId(0); Assert.assertTrue("Previous block start " + lastStart[p] + " exceeds next block start " + start, lastStart[p] <= start); lastStart[p] = start; } } } } } private IDBlock allocate(int partitionIndex) { IDBlock block; try { block = authority.getIDBlock(partitionIndex,partitionIndex,GET_ID_BLOCK_TIMEOUT); } catch (BackendException e) { log.error("Unexpected exception while getting ID block", e); return null; } /* * This is not guaranteed in the consistentkey implementation. * Writers of ID block claims in that implementation delete their * writes if they take too long. A peek can see this short-lived * block claim even though a subsequent getblock does not. */ // Assert.assertTrue(nextId <= block[0]); if (hasEmptyUid) assertEquals(block.getId(0)+ blockSize-1, block.getId(blockSize-1)); log.trace("Obtained ID block {}", block); return block; } private boolean throwIterationsExceededException() { throw new RuntimeException( "Exceeded maximum ID allocation iteration count (" + maxIterations + "); too many timeouts?"); } } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_IDAuthorityTest.java
171
public class BroadleafCmsSimpleUrlHandlerMapping extends SimpleUrlHandlerMapping { @Resource(name="blConfiguration") protected RuntimeEnvironmentPropertiesConfigurer configurer; @Override public void setMappings(Properties mappings) { Properties clone = new Properties(); for (Object propertyName: mappings.keySet()) { String newName = configurer.getStringValueResolver().resolveStringValue(propertyName.toString()); clone.put(newName, mappings.get(propertyName)); } super.setMappings(clone); } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_BroadleafCmsSimpleUrlHandlerMapping.java
2,550
private static final class ConstructorCache { private final ConcurrentMap<ClassLoader, ConcurrentMap<String, WeakReference<Constructor>>> cache; private ConstructorCache() { // Guess 16 classloaders to not waste to much memory (16 is default concurrency level) cache = new ConcurrentReferenceHashMap<ClassLoader, ConcurrentMap<String, WeakReference<Constructor>>>(16); } private <T> Constructor put(ClassLoader classLoader, String className, Constructor<T> constructor) { ClassLoader cl = classLoader == null ? ClassLoaderUtil.class.getClassLoader() : classLoader; ConcurrentMap<String, WeakReference<Constructor>> innerCache = cache.get(cl); if (innerCache == null) { // Let's guess a start of 100 classes per classloader innerCache = new ConcurrentHashMap<String, WeakReference<Constructor>>(100); ConcurrentMap<String, WeakReference<Constructor>> old = cache.putIfAbsent(cl, innerCache); if (old != null) { innerCache = old; } } innerCache.put(className, new WeakReference<Constructor>(constructor)); return constructor; } public <T> Constructor<T> get(ClassLoader classLoader, String className) { ConcurrentMap<String, WeakReference<Constructor>> innerCache = cache.get(classLoader); if (innerCache == null) { return null; } WeakReference<Constructor> reference = innerCache.get(className); Constructor constructor = reference == null ? null : reference.get(); if (reference != null && constructor == null) { innerCache.remove(className); } return (Constructor<T>) constructor; } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_ClassLoaderUtil.java
454
static class ClusterStatsNodeRequest extends NodeOperationRequest { ClusterStatsRequest request; ClusterStatsNodeRequest() { } ClusterStatsNodeRequest(String nodeId, ClusterStatsRequest request) { super(request, nodeId); this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); request = new ClusterStatsRequest(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); request.writeTo(out); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_stats_TransportClusterStatsAction.java
182
public class OClassLoaderHelper { /** * Switch to the OrientDb classloader before lookups on ServiceRegistry for * implementation of the given Class. Useful under OSGI and generally under * applications where jars are loaded by another class loader * * @param clazz * the class to lookup foor * @return an Iterator on the class implementation */ public static synchronized <T extends Object> Iterator<T> lookupProviderWithOrientClassLoader(Class<T> clazz) { return lookupProviderWithOrientClassLoader(clazz,OClassLoaderHelper.class.getClassLoader()); } public static synchronized <T extends Object> Iterator<T> lookupProviderWithOrientClassLoader(Class<T> clazz,ClassLoader orientClassLoader) { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(orientClassLoader); Iterator<T> lookupProviders = ServiceRegistry.lookupProviders(clazz); Thread.currentThread().setContextClassLoader(origClassLoader); return lookupProviders; } }
0true
commons_src_main_java_com_orientechnologies_common_util_OClassLoaderHelper.java
2,698
final class PortableSerializer implements StreamSerializer<Portable> { private final SerializationContext context; private final Map<Integer, PortableFactory> factories = new HashMap<Integer, PortableFactory>(); PortableSerializer(SerializationContext context, Map<Integer, ? extends PortableFactory> portableFactories) { this.context = context; factories.putAll(portableFactories); } public int getTypeId() { return SerializationConstants.CONSTANT_TYPE_PORTABLE; } public void write(ObjectDataOutput out, Portable p) throws IOException { if (p.getClassId() == 0) { throw new IllegalArgumentException("Portable class id cannot be zero!"); } if (!(out instanceof BufferObjectDataOutput)) { throw new IllegalArgumentException("ObjectDataOutput must be instance of BufferObjectDataOutput!"); } if (p.getClassId() == 0) { throw new IllegalArgumentException("Portable class id cannot be zero!"); } ClassDefinition cd = context.lookupOrRegisterClassDefinition(p); BufferObjectDataOutput bufferedOut = (BufferObjectDataOutput) out; DefaultPortableWriter writer = new DefaultPortableWriter(this, bufferedOut, cd); p.writePortable(writer); writer.end(); } public Portable read(ObjectDataInput in) throws IOException { if (!(in instanceof BufferObjectDataInput)) { throw new IllegalArgumentException("ObjectDataInput must be instance of BufferObjectDataInput!"); } if (!(in instanceof PortableContextAwareInputStream)) { throw new IllegalArgumentException("ObjectDataInput must be instance of PortableContextAwareInputStream!"); } final PortableContextAwareInputStream ctxIn = (PortableContextAwareInputStream) in; final int factoryId = ctxIn.getFactoryId(); final int dataClassId = ctxIn.getClassId(); final int dataVersion = ctxIn.getVersion(); final PortableFactory portableFactory = factories.get(factoryId); if (portableFactory == null) { throw new HazelcastSerializationException("Could not find PortableFactory for factory-id: " + factoryId); } final Portable portable = portableFactory.create(dataClassId); if (portable == null) { throw new HazelcastSerializationException("Could not create Portable for class-id: " + dataClassId); } final DefaultPortableReader reader; final ClassDefinition cd; final BufferObjectDataInput bufferedIn = (BufferObjectDataInput) in; if (context.getVersion() == dataVersion) { cd = context.lookup(factoryId, dataClassId); // using context.version if (cd == null) { throw new HazelcastSerializationException("Could not find class-definition for " + "factory-id: " + factoryId + ", class-id: " + dataClassId + ", version: " + dataVersion); } reader = new DefaultPortableReader(this, bufferedIn, cd); } else { cd = context.lookup(factoryId, dataClassId, dataVersion); // registered during read if (cd == null) { throw new HazelcastSerializationException("Could not find class-definition for " + "factory-id: " + factoryId + ", class-id: " + dataClassId + ", version: " + dataVersion); } reader = new MorphingPortableReader(this, bufferedIn, cd); } portable.readPortable(reader); reader.end(); return portable; } Portable readAndInitialize(BufferObjectDataInput in) throws IOException { Portable p = read(in); final ManagedContext managedContext = context.getManagedContext(); return managedContext != null ? (Portable) managedContext.initialize(p) : p; } public void destroy() { factories.clear(); } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_serialization_PortableSerializer.java
205
public class ExistsFieldQueryExtension implements FieldQueryExtension { public static final String NAME = "_exists_"; @Override public Query query(QueryParseContext parseContext, String queryText) { String fieldName = queryText; Filter filter = null; MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); if (smartNameFieldMappers != null) { if (smartNameFieldMappers.hasMapper()) { filter = smartNameFieldMappers.mapper().rangeFilter(null, null, true, true, parseContext); } } if (filter == null) { filter = new TermRangeFilter(fieldName, null, null, true, true); } // we always cache this one, really does not change... filter = parseContext.cacheFilter(filter, null); filter = wrapSmartNameFilter(filter, smartNameFieldMappers, parseContext); return new XConstantScoreQuery(filter); } }
1no label
src_main_java_org_apache_lucene_queryparser_classic_ExistsFieldQueryExtension.java
1,454
public static enum OpType { AND, OR }
0true
src_main_java_org_elasticsearch_cluster_node_DiscoveryNodeFilters.java
3,425
public static class PostJoinProxyOperation extends AbstractOperation { private Collection<ProxyInfo> proxies; public PostJoinProxyOperation() { } public PostJoinProxyOperation(Collection<ProxyInfo> proxies) { this.proxies = proxies; } @Override public void run() throws Exception { if (proxies != null && proxies.size() > 0) { NodeEngine nodeEngine = getNodeEngine(); ProxyServiceImpl proxyService = getService(); for (ProxyInfo proxy : proxies) { final ProxyRegistry registry = getOrPutIfAbsent(proxyService.registries, proxy.serviceName, proxyService.registryConstructor); DistributedObjectFuture future = registry.createProxy(proxy.objectName, false, false); if (future != null) { final DistributedObject object = future.get(); if (object instanceof InitializingObject) { nodeEngine.getExecutionService().execute(ExecutionService.SYSTEM_EXECUTOR, new Runnable() { public void run() { try { ((InitializingObject) object).initialize(); } catch (Exception e) { getLogger().warning("Error while initializing proxy: " + object, e); } } }); } } } } } @Override public String getServiceName() { return ProxyServiceImpl.SERVICE_NAME; } @Override public boolean returnsResponse() { return false; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); int len = proxies != null ? proxies.size() : 0; out.writeInt(len); if (len > 0) { for (ProxyInfo proxy : proxies) { out.writeUTF(proxy.serviceName); out.writeObject(proxy.objectName); // writing as object for backward-compatibility } } } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); int len = in.readInt(); if (len > 0) { proxies = new ArrayList<ProxyInfo>(len); for (int i = 0; i < len; i++) { ProxyInfo proxy = new ProxyInfo(in.readUTF(), (String) in.readObject()); proxies.add(proxy); } } } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_ProxyServiceImpl.java
4,478
pool.execute(new Runnable() { @Override public void run() { IndexInput indexInput = null; try { final int BUFFER_SIZE = (int) recoverySettings.fileChunkSize().bytes(); byte[] buf = new byte[BUFFER_SIZE]; StoreFileMetaData md = shard.store().metaData(name); // TODO: maybe use IOContext.READONCE? indexInput = shard.store().openInputRaw(name, IOContext.READ); boolean shouldCompressRequest = recoverySettings.compress(); if (CompressorFactory.isCompressed(indexInput)) { shouldCompressRequest = false; } long len = indexInput.length(); long readCount = 0; while (readCount < len) { if (shard.state() == IndexShardState.CLOSED) { // check if the shard got closed on us throw new IndexShardClosedException(shard.shardId()); } int toRead = readCount + BUFFER_SIZE > len ? (int) (len - readCount) : BUFFER_SIZE; long position = indexInput.getFilePointer(); if (recoverySettings.rateLimiter() != null) { recoverySettings.rateLimiter().pause(toRead); } indexInput.readBytes(buf, 0, toRead, false); BytesArray content = new BytesArray(buf, 0, toRead); transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.FILE_CHUNK, new RecoveryFileChunkRequest(request.recoveryId(), request.shardId(), name, position, len, md.checksum(), content), TransportRequestOptions.options().withCompress(shouldCompressRequest).withType(TransportRequestOptions.Type.RECOVERY).withTimeout(internalActionTimeout), EmptyTransportResponseHandler.INSTANCE_SAME).txGet(); readCount += toRead; } } catch (Throwable e) { lastException.set(e); } finally { IOUtils.closeWhileHandlingException(indexInput); latch.countDown(); } } });
1no label
src_main_java_org_elasticsearch_indices_recovery_RecoverySource.java
2,662
public class PublishClusterStateAction extends AbstractComponent { public static interface NewClusterStateListener { static interface NewStateProcessed { void onNewClusterStateProcessed(); void onNewClusterStateFailed(Throwable t); } void onNewClusterState(ClusterState clusterState, NewStateProcessed newStateProcessed); } private final TransportService transportService; private final DiscoveryNodesProvider nodesProvider; private final NewClusterStateListener listener; private final TimeValue publishTimeout; public PublishClusterStateAction(Settings settings, TransportService transportService, DiscoveryNodesProvider nodesProvider, NewClusterStateListener listener) { super(settings); this.transportService = transportService; this.nodesProvider = nodesProvider; this.listener = listener; this.publishTimeout = settings.getAsTime("discovery.zen.publish_timeout", Discovery.DEFAULT_PUBLISH_TIMEOUT); transportService.registerHandler(PublishClusterStateRequestHandler.ACTION, new PublishClusterStateRequestHandler()); } public void close() { transportService.removeHandler(PublishClusterStateRequestHandler.ACTION); } public void publish(ClusterState clusterState, final Discovery.AckListener ackListener) { publish(clusterState, new AckClusterStatePublishResponseHandler(clusterState.nodes().size() - 1, ackListener)); } private void publish(ClusterState clusterState, final ClusterStatePublishResponseHandler publishResponseHandler) { DiscoveryNode localNode = nodesProvider.nodes().localNode(); Map<Version, BytesReference> serializedStates = Maps.newHashMap(); for (final DiscoveryNode node : clusterState.nodes()) { if (node.equals(localNode)) { continue; } // try and serialize the cluster state once (or per version), so we don't serialize it // per node when we send it over the wire, compress it while we are at it... BytesReference bytes = serializedStates.get(node.version()); if (bytes == null) { try { BytesStreamOutput bStream = new BytesStreamOutput(); StreamOutput stream = new HandlesStreamOutput(CompressorFactory.defaultCompressor().streamOutput(bStream)); stream.setVersion(node.version()); ClusterState.Builder.writeTo(clusterState, stream); stream.close(); bytes = bStream.bytes(); serializedStates.put(node.version(), bytes); } catch (Throwable e) { logger.warn("failed to serialize cluster_state before publishing it to node {}", e, node); publishResponseHandler.onFailure(node, e); continue; } } try { TransportRequestOptions options = TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withCompress(false); // no need to put a timeout on the options here, because we want the response to eventually be received // and not log an error if it arrives after the timeout transportService.sendRequest(node, PublishClusterStateRequestHandler.ACTION, new BytesTransportRequest(bytes, node.version()), options, // no need to compress, we already compressed the bytes new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty response) { publishResponseHandler.onResponse(node); } @Override public void handleException(TransportException exp) { logger.debug("failed to send cluster state to [{}]", exp, node); publishResponseHandler.onFailure(node, exp); } }); } catch (Throwable t) { logger.debug("error sending cluster state to [{}]", t, node); publishResponseHandler.onFailure(node, t); } } if (publishTimeout.millis() > 0) { // only wait if the publish timeout is configured... try { boolean awaited = publishResponseHandler.awaitAllNodes(publishTimeout); if (!awaited) { logger.debug("awaiting all nodes to process published state {} timed out, timeout {}", clusterState.version(), publishTimeout); } } catch (InterruptedException e) { // ignore & restore interrupt Thread.currentThread().interrupt(); } } } private class PublishClusterStateRequestHandler extends BaseTransportRequestHandler<BytesTransportRequest> { static final String ACTION = "discovery/zen/publish"; @Override public BytesTransportRequest newInstance() { return new BytesTransportRequest(); } @Override public void messageReceived(BytesTransportRequest request, final TransportChannel channel) throws Exception { Compressor compressor = CompressorFactory.compressor(request.bytes()); StreamInput in; if (compressor != null) { in = CachedStreamInput.cachedHandlesCompressed(compressor, request.bytes().streamInput()); } else { in = CachedStreamInput.cachedHandles(request.bytes().streamInput()); } in.setVersion(request.version()); ClusterState clusterState = ClusterState.Builder.readFrom(in, nodesProvider.nodes().localNode()); logger.debug("received cluster state version {}", clusterState.version()); listener.onNewClusterState(clusterState, new NewClusterStateListener.NewStateProcessed() { @Override public void onNewClusterStateProcessed() { try { channel.sendResponse(TransportResponse.Empty.INSTANCE); } catch (Throwable e) { logger.debug("failed to send response on cluster state processed", e); } } @Override public void onNewClusterStateFailed(Throwable t) { try { channel.sendResponse(t); } catch (Throwable e) { logger.debug("failed to send response on cluster state processed", e); } } }); } @Override public String executor() { return ThreadPool.Names.SAME; } } }
1no label
src_main_java_org_elasticsearch_discovery_zen_publish_PublishClusterStateAction.java
522
public class TypesExistsRequestBuilder extends MasterNodeReadOperationRequestBuilder<TypesExistsRequest, TypesExistsResponse, TypesExistsRequestBuilder> { /** * @param indices What indices to check for types */ public TypesExistsRequestBuilder(IndicesAdminClient indicesClient, String... indices) { super((InternalIndicesAdminClient) indicesClient, new TypesExistsRequest(indices, Strings.EMPTY_ARRAY)); } TypesExistsRequestBuilder(IndicesAdminClient client) { super((InternalIndicesAdminClient) client, new TypesExistsRequest()); } /** * @param indices What indices to check for types */ public TypesExistsRequestBuilder setIndices(String[] indices) { request.indices(indices); return this; } /** * @param types The types to check if they exist */ public TypesExistsRequestBuilder setTypes(String... types) { request.types(types); return this; } /** * @param indicesOptions Specifies how to resolve indices that aren't active / ready and indices wildcard expressions */ public TypesExistsRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) { request.indicesOptions(indicesOptions); return this; } protected void doExecute(ActionListener<TypesExistsResponse> listener) { ((IndicesAdminClient) client).typesExists(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_exists_types_TypesExistsRequestBuilder.java
65
public static class KeySetView<K,V> extends CollectionView<K,V,K> implements Set<K>, java.io.Serializable { private static final long serialVersionUID = 7249069246763182397L; private final V value; KeySetView(ConcurrentHashMapV8<K,V> map, V value) { // non-public super(map); this.value = value; } /** * Returns the default mapped value for additions, * or {@code null} if additions are not supported. * * @return the default mapped value for additions, or {@code null} * if not supported */ public V getMappedValue() { return value; } /** * {@inheritDoc} * @throws NullPointerException if the specified key is null */ public boolean contains(Object o) { return map.containsKey(o); } /** * Removes the key from this map view, by removing the key (and its * corresponding value) from the backing map. This method does * nothing if the key is not in the map. * * @param o the key to be removed from the backing map * @return {@code true} if the backing map contained the specified key * @throws NullPointerException if the specified key is null */ public boolean remove(Object o) { return map.remove(o) != null; } /** * @return an iterator over the keys of the backing map */ public Iterator<K> iterator() { Node<K,V>[] t; ConcurrentHashMapV8<K,V> m = map; int f = (t = m.table) == null ? 0 : t.length; return new KeyIterator<K,V>(t, f, 0, f, m); } /** * Adds the specified key to this set view by mapping the key to * the default mapped value in the backing map, if defined. * * @param e key to be added * @return {@code true} if this set changed as a result of the call * @throws NullPointerException if the specified key is null * @throws UnsupportedOperationException if no default mapped value * for additions was provided */ public boolean add(K e) { V v; if ((v = value) == null) throw new UnsupportedOperationException(); return map.putVal(e, v, true) == null; } /** * Adds all of the elements in the specified collection to this set, * as if by calling {@link #add} on each one. * * @param c the elements to be inserted into this set * @return {@code true} if this set changed as a result of the call * @throws NullPointerException if the collection or any of its * elements are {@code null} * @throws UnsupportedOperationException if no default mapped value * for additions was provided */ public boolean addAll(Collection<? extends K> c) { boolean added = false; V v; if ((v = value) == null) throw new UnsupportedOperationException(); for (K e : c) { if (map.putVal(e, v, true) == null) added = true; } return added; } public int hashCode() { int h = 0; for (K e : this) h += e.hashCode(); return h; } public boolean equals(Object o) { Set<?> c; return ((o instanceof Set) && ((c = (Set<?>)o) == this || (containsAll(c) && c.containsAll(this)))); } public ConcurrentHashMapSpliterator<K> spliteratorJSR166() { Node<K,V>[] t; ConcurrentHashMapV8<K,V> m = map; long n = m.sumCount(); int f = (t = m.table) == null ? 0 : t.length; return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n); } public void forEach(Action<? super K> action) { if (action == null) throw new NullPointerException(); Node<K,V>[] t; if ((t = map.table) != null) { Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length); for (Node<K,V> p; (p = it.advance()) != null; ) action.apply(p.key); } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
126
@Service("blPageService") public class PageServiceImpl extends AbstractContentService implements PageService, SandBoxItemListener { protected static final Log LOG = LogFactory.getLog(PageServiceImpl.class); protected static String AND = " && "; @Resource(name="blPageDao") protected PageDao pageDao; @Resource(name="blSandBoxItemDao") protected SandBoxItemDao sandBoxItemDao; @Resource(name="blSandBoxDao") protected SandBoxDao sandBoxDao; @Resource(name="blPageRuleProcessors") protected List<PageRuleProcessor> pageRuleProcessors; @Resource(name="blLocaleService") protected LocaleService localeService; @Resource(name="blStaticAssetService") protected StaticAssetService staticAssetService; @Value("${automatically.approve.pages}") protected boolean automaticallyApproveAndPromotePages=true; protected Cache pageCache; protected List<ArchivedPagePublisher> archivedPageListeners; protected final PageDTO NULL_PAGE = new NullPageDTO(); protected final List<PageDTO> EMPTY_PAGE_DTO = new ArrayList<PageDTO>(); /** * Returns the page with the passed in id. * * @param pageId - The id of the page. * @return The associated page. */ @Override public Page findPageById(Long pageId) { return pageDao.readPageById(pageId); } @Override public PageTemplate findPageTemplateById(Long id) { return pageDao.readPageTemplateById(id); } @Override @Transactional("blTransactionManager") public PageTemplate savePageTemplate(PageTemplate template) { return pageDao.savePageTemplate(template); } /** * Returns the page-fields associated with the passed in page-id. * This is preferred over the direct access from Page so that the * two items can be cached distinctly * * @param pageId - The id of the page. * @return The associated page. */ @Override public Map<String, PageField> findPageFieldsByPageId(Long pageId) { Page page = findPageById(pageId); return pageDao.readPageFieldsByPage(page); } /** * This method is intended to be called from within the CMS * admin only. * <p/> * Adds the passed in page to the DB. * <p/> */ @Override public Page addPage(Page page, SandBox destinationSandbox) { if (automaticallyApproveAndPromotePages) { if (destinationSandbox != null && destinationSandbox.getSite() != null) { destinationSandbox = destinationSandbox.getSite().getProductionSandbox(); } else { // Null means production for single-site installations. destinationSandbox = null; } } page.setSandbox(destinationSandbox); page.setArchivedFlag(false); page.setDeletedFlag(false); Page newPage = pageDao.addPage(page); if (! isProductionSandBox(destinationSandbox)) { sandBoxItemDao.addSandBoxItem(destinationSandbox.getId(), SandBoxOperationType.ADD, SandBoxItemType.PAGE, newPage.getFullUrl(), newPage.getId(), null); } return newPage; } /** * This method is intended to be called from within the CMS * admin only. * <p/> * Updates the page according to the following rules: * <p/> * 1. If sandbox has changed from null to a value * This means that the user is editing an item in production and * the edit is taking place in a sandbox. * <p/> * Clone the page and add it to the new sandbox and set the cloned * page's originalPageId to the id of the page being updated. * <p/> * 2. If the sandbox has changed from one value to another * This means that the user is moving the item from one sandbox * to another. * <p/> * Update the siteId for the page to the one associated with the * new sandbox * <p/> * 3. If the sandbox has changed from a value to null * This means that the item is moving from the sandbox to production. * <p/> * If the page has an originalPageId, then update that page by * setting it's archived flag to true. * <p/> * Then, update the siteId of the page being updated to be the * siteId of the original page. * <p/> * 4. If the sandbox is the same then just update the page. */ @Override public Page updatePage(Page page, SandBox destSandbox) { if (page.getLockedFlag()) { throw new IllegalArgumentException("Unable to update a locked record"); } if (automaticallyApproveAndPromotePages) { if (destSandbox != null && destSandbox.getSite() != null) { destSandbox = destSandbox.getSite().getProductionSandbox(); } else { // Null means production for single-site installations. destSandbox = null; } } if (checkForSandboxMatch(page.getSandbox(), destSandbox)) { if (page.getDeletedFlag()) { SandBoxItem item = page.getSandbox()==null?null:sandBoxItemDao.retrieveBySandboxAndTemporaryItemId(page.getSandbox().getId(), SandBoxItemType.PAGE, page.getId()); if (page.getOriginalPageId() == null && item != null) { // This page was added in this sandbox and now needs to be deleted. item.setArchivedFlag(true); page.setArchivedFlag(true); } else if (item != null) { // This page was being updated but now is being deleted - so change the // sandbox operation type to deleted item.setSandBoxOperationType(SandBoxOperationType.DELETE); sandBoxItemDao.updateSandBoxItem(item); } else if (automaticallyApproveAndPromotePages) { page.setArchivedFlag(true); } } return pageDao.updatePage(page); } else if (isProductionSandBox(page.getSandbox())) { // The passed in page is an existing page with updated values. // Instead, we want to create a clone of this page for the destSandbox Page clonedPage = page.cloneEntity(); clonedPage.setOriginalPageId(page.getId()); clonedPage.setSandbox(destSandbox); // Detach the old page from the session so it is not updated. pageDao.detachPage(page); // Save the cloned page Page returnPage = pageDao.addPage(clonedPage); // Lookup the original page and mark it as locked Page prod = findPageById(page.getId()); prod.setLockedFlag(true); pageDao.updatePage(prod); SandBoxOperationType type = SandBoxOperationType.UPDATE; if (clonedPage.getDeletedFlag()) { type = SandBoxOperationType.DELETE; } // Add this item to the sandbox. sandBoxItemDao.addSandBoxItem(destSandbox.getId(), type, SandBoxItemType.PAGE, clonedPage.getFullUrl(), returnPage.getId(), returnPage.getOriginalPageId()); return returnPage; } else { // This should happen via a promote, revert, or reject in the sandbox service throw new IllegalArgumentException("Update called when promote or reject was expected."); } } // Returns true if the src and dest sandbox are the same. protected boolean checkForSandboxMatch(SandBox src, SandBox dest) { if (src != null) { if (dest != null) { return src.getId().equals(dest.getId()); } } return (src == null && dest == null); } // Returns true if the dest sandbox is production. protected boolean isProductionSandBox(SandBox dest) { if (dest == null) { return true; } else { return SandBoxType.PRODUCTION.equals(dest.getSandBoxType()); } } /** * If deleting and item where page.originalPageId != null * then the item is deleted from the database. * <p/> * If the originalPageId is null, then this method marks * the items as deleted within the passed in sandbox. * * @param page * @param destinationSandbox * @return */ @Override public void deletePage(Page page, SandBox destinationSandbox) { page.setDeletedFlag(true); updatePage(page, destinationSandbox); } /** * Converts a list of pages to a list of pageDTOs.<br> * Internally calls buildPageDTO(...). * * @param pageList * @param secure * @return */ protected List<PageDTO> buildPageDTOList(List<Page> pageList, boolean secure) { List<PageDTO> dtoList = new ArrayList<PageDTO>(); if (pageList != null) { for(Page page : pageList) { dtoList.add(buildPageDTOInternal(page, secure)); } } return dtoList; } protected PageDTO buildPageDTOInternal(Page page, boolean secure) { PageDTO pageDTO = new PageDTO(); pageDTO.setId(page.getId()); pageDTO.setDescription(page.getDescription()); pageDTO.setUrl(page.getFullUrl()); pageDTO.setPriority(page.getPriority()); if (page.getSandbox() != null) { pageDTO.setSandboxId(page.getSandbox().getId()); } if (page.getPageTemplate() != null) { pageDTO.setTemplatePath(page.getPageTemplate().getTemplatePath()); if (page.getPageTemplate().getLocale() != null) { pageDTO.setLocaleCode(page.getPageTemplate().getLocale().getLocaleCode()); } } String envPrefix = staticAssetService.getStaticAssetEnvironmentUrlPrefix(); if (envPrefix != null && secure) { envPrefix = staticAssetService.getStaticAssetEnvironmentSecureUrlPrefix(); } String cmsPrefix = staticAssetService.getStaticAssetUrlPrefix(); for (String fieldKey : page.getPageFields().keySet()) { PageField pf = page.getPageFields().get(fieldKey); String originalValue = pf.getValue(); if (StringUtils.isNotBlank(envPrefix) && StringUtils.isNotBlank(originalValue) && StringUtils.isNotBlank(cmsPrefix) && originalValue.contains(cmsPrefix)) { String fldValue = originalValue.replaceAll(cmsPrefix, envPrefix+cmsPrefix); pageDTO.getPageFields().put(fieldKey, fldValue); } else { pageDTO.getPageFields().put(fieldKey, originalValue); } } pageDTO.setRuleExpression(buildRuleExpression(page)); if (page.getQualifyingItemCriteria() != null && page.getQualifyingItemCriteria().size() > 0) { pageDTO.setItemCriteriaDTOList(buildItemCriteriaDTOList(page)); } return pageDTO; } protected String buildRuleExpression(Page page) { StringBuffer ruleExpression = null; Map<String, PageRule> ruleMap = page.getPageMatchRules(); if (ruleMap != null) { for (String ruleKey : ruleMap.keySet()) { if (ruleExpression == null) { ruleExpression = new StringBuffer(ruleMap.get(ruleKey).getMatchRule()); } else { ruleExpression.append(AND); ruleExpression.append(ruleMap.get(ruleKey).getMatchRule()); } } } if (ruleExpression != null) { return ruleExpression.toString(); } else { return null; } } protected List<ItemCriteriaDTO> buildItemCriteriaDTOList(Page page) { List<ItemCriteriaDTO> itemCriteriaDTOList = new ArrayList<ItemCriteriaDTO>(); for(PageItemCriteria criteria : page.getQualifyingItemCriteria()) { ItemCriteriaDTO criteriaDTO = new ItemCriteriaDTO(); criteriaDTO.setMatchRule(criteria.getMatchRule()); criteriaDTO.setQty(criteria.getQuantity()); itemCriteriaDTOList.add(criteriaDTO); } return itemCriteriaDTOList; } protected List<PageDTO> mergePages(List<PageDTO> productionPageList, List<Page> sandboxPageList, boolean secure) { if (sandboxPageList == null || sandboxPageList.size() == 0) { return productionPageList; } Map<Long, PageDTO> pageMap = new LinkedHashMap<Long, PageDTO>(); if (productionPageList != null) { for(PageDTO page : productionPageList) { pageMap.put(page.getId(), page); } } for (Page page : sandboxPageList) { if (page.getOriginalPageId() != null) { pageMap.remove(page.getOriginalPageId()); } if (! page.getDeletedFlag() && page.getOfflineFlag() != null && ! page.getOfflineFlag()) { PageDTO convertedPage = buildPageDTOInternal(page, secure); pageMap.put(page.getId(), convertedPage); } } ArrayList<PageDTO> returnList = new ArrayList<PageDTO>(pageMap.values()); if (returnList.size() > 1) { Collections.sort(returnList, new BeanComparator("priority")); } return returnList; } protected PageDTO evaluatePageRules(List<PageDTO> pageDTOList, Locale locale, Map<String, Object> ruleDTOs) { if (pageDTOList == null) { return NULL_PAGE; } // First check to see if we have a page that matches on the full locale. for(PageDTO page : pageDTOList) { if (locale != null && locale.getLocaleCode() != null) { if (page.getLocaleCode().equals(locale.getLocaleCode())) { if (passesPageRules(page, ruleDTOs)) { return page; } } } } // Otherwise, we look for a match using just the language. for(PageDTO page : pageDTOList) { if (passesPageRules(page, ruleDTOs)) { return page; } } return NULL_PAGE; } protected boolean passesPageRules(PageDTO page, Map<String, Object> ruleDTOs) { if (pageRuleProcessors != null) { for (PageRuleProcessor processor : pageRuleProcessors) { boolean matchFound = processor.checkForMatch(page, ruleDTOs); if (! matchFound) { return false; } } } return true; } protected Locale findLanguageOnlyLocale(Locale locale) { if (locale != null ) { Locale languageOnlyLocale = localeService.findLocaleByCode(LocaleUtil.findLanguageCode(locale)); if (languageOnlyLocale != null) { return languageOnlyLocale; } } return locale; } /** * Retrieve the page if one is available for the passed in uri. */ @Override public PageDTO findPageByURI(SandBox currentSandbox, Locale locale, String uri, Map<String,Object> ruleDTOs, boolean secure) { List<PageDTO> returnList = null; if (uri != null) { SandBox productionSandbox = null; if (currentSandbox != null && currentSandbox.getSite() != null) { productionSandbox = currentSandbox.getSite().getProductionSandbox(); } Locale languageOnlyLocale = findLanguageOnlyLocale(locale); String key = buildKey(productionSandbox, locale, uri); key = key + "-" + secure; returnList = getPageListFromCache(key); if (returnList == null) { if (LOG.isTraceEnabled()) { LOG.trace("Page not found in cache, searching DB for key: " + key); } List<Page> productionPages = pageDao.findPageByURI(productionSandbox, locale, languageOnlyLocale, uri); if (productionPages != null) { if (LOG.isTraceEnabled()) { LOG.trace("Pages found, adding pages to cache with key: " + key); } returnList = buildPageDTOList(productionPages, secure); Collections.sort(returnList, new BeanComparator("priority")); addPageListToCache(returnList, key); } else { if (LOG.isTraceEnabled()) { LOG.trace("No match found for passed in URI, locale, and sandbox. Key = " + key); } addPageListToCache(EMPTY_PAGE_DTO, key); } } // If the request is from a non-production SandBox, we need to check to see if the SandBox has an override // for this page before returning. No caching is used for Sandbox pages. if (currentSandbox != null && ! currentSandbox.getSandBoxType().equals(SandBoxType.PRODUCTION)) { List<Page> sandboxPages = pageDao.findPageByURI(currentSandbox, locale, languageOnlyLocale, uri); if (sandboxPages != null && sandboxPages.size() > 0) { returnList = mergePages(returnList, sandboxPages, secure); } } } return evaluatePageRules(returnList, locale, ruleDTOs); } @Override public List<Page> findPages(SandBox sandbox, Criteria c) { return findItems(sandbox, c, Page.class, PageImpl.class, "originalPageId"); } @Override public List<Page> readAllPages() { return pageDao.readAllPages(); } @Override public List<PageTemplate> readAllPageTemplates() { return pageDao.readAllPageTemplates(); } @Override public Long countPages(SandBox sandbox, Criteria c) { return countItems(sandbox, c, PageImpl.class, "originalPageId"); } protected void productionItemArchived(Page page) { // Immediately remove the page from this VM. removePageFromCache(page); if (archivedPageListeners != null) { for (ArchivedPagePublisher listener : archivedPageListeners) { listener.processPageArchive(page, buildKey(page)); } } } @Override public void itemPromoted(SandBoxItem sandBoxItem, SandBox destinationSandBox) { if (! SandBoxItemType.PAGE.equals(sandBoxItem.getSandBoxItemType())) { return; } Page page = pageDao.readPageById(sandBoxItem.getTemporaryItemId()); if (page == null) { if (LOG.isDebugEnabled()) { LOG.debug("Page not found " + sandBoxItem.getTemporaryItemId()); } } else { boolean productionSandBox = isProductionSandBox(destinationSandBox); if (productionSandBox) { page.setLockedFlag(false); } else { page.setLockedFlag(true); } if (productionSandBox && page.getOriginalPageId() != null) { if (LOG.isDebugEnabled()) { LOG.debug("Page promoted to production. " + page.getId() + ". Archiving original page " + page.getOriginalPageId()); } Page originalPage = pageDao.readPageById(page.getOriginalPageId()); originalPage.setArchivedFlag(Boolean.TRUE); pageDao.updatePage(originalPage); productionItemArchived(originalPage); // We are archiving the old page and making this the new "production page", so // null out the original page id before saving. page.setOriginalPageId(null); if (page.getDeletedFlag()) { // If this page is being deleted, set it as archived. page.setArchivedFlag(true); } } } if (page.getOriginalSandBox() == null) { page.setOriginalSandBox(page.getSandbox()); } page.setSandbox(destinationSandBox); pageDao.updatePage(page); } @Override public void itemRejected(SandBoxItem sandBoxItem, SandBox destinationSandBox) { if (! SandBoxItemType.PAGE.equals(sandBoxItem.getSandBoxItemType())) { return; } Page page = pageDao.readPageById(sandBoxItem.getTemporaryItemId()); if (page != null) { page.setSandbox(destinationSandBox); page.setOriginalSandBox(null); page.setLockedFlag(false); pageDao.updatePage(page); } } @Override public void itemReverted(SandBoxItem sandBoxItem) { if (! SandBoxItemType.PAGE.equals(sandBoxItem.getSandBoxItemType())) { return; } Page page = pageDao.readPageById(sandBoxItem.getTemporaryItemId()); if (page != null) { page.setArchivedFlag(Boolean.TRUE); page.setLockedFlag(false); pageDao.updatePage(page); if (page.getOriginalPageId() != null) { Page originalPage = pageDao.readPageById(page.getOriginalPageId()); originalPage.setLockedFlag(false); pageDao.updatePage(originalPage); } } } protected Cache getPageCache() { if (pageCache == null) { pageCache = CacheManager.getInstance().getCache("cmsPageCache"); } return pageCache; } protected String buildKey(SandBox currentSandbox, Locale locale, String uri) { StringBuffer key = new StringBuffer(uri); if (locale != null) { key.append("-").append(locale.getLocaleCode()); } if (currentSandbox != null) { key.append("-").append(currentSandbox.getId()); } return key.toString(); } protected String buildKey(Page page) { return buildKey(page.getSandbox(), page.getPageTemplate().getLocale(), page.getFullUrl()); } protected void addPageListToCache(List<PageDTO> pageList, String key) { getPageCache().put(new Element(key, pageList)); } @SuppressWarnings("unchecked") protected List<PageDTO> getPageListFromCache(String key) { Element cacheElement = getPageCache().get(key); if (cacheElement != null && cacheElement.getValue() != null) { return (List<PageDTO>) cacheElement.getValue(); } return null; } /** * Call to evict an item from the cache. * @param p */ public void removePageFromCache(Page p) { // Remove secure and non-secure instances of the page. // Typically the page will be in one or the other if at all. removePageFromCache(buildKey(p)); } /** * Call to evict both secure and non-secure pages matching * the passed in key. * * @param baseKey */ @Override public void removePageFromCache(String baseKey) { // Remove secure and non-secure instances of the page. // Typically the page will be in one or the other if at all. getPageCache().remove(baseKey+"-"+true); getPageCache().remove(baseKey+"-"+false); } @Override public List<ArchivedPagePublisher> getArchivedPageListeners() { return archivedPageListeners; } @Override public void setArchivedPageListeners(List<ArchivedPagePublisher> archivedPageListeners) { this.archivedPageListeners = archivedPageListeners; } @Override public boolean isAutomaticallyApproveAndPromotePages() { return automaticallyApproveAndPromotePages; } @Override public void setAutomaticallyApproveAndPromotePages(boolean automaticallyApproveAndPromotePages) { this.automaticallyApproveAndPromotePages = automaticallyApproveAndPromotePages; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_service_PageServiceImpl.java
1,189
public class BroadcastActionsTests extends ElasticsearchIntegrationTest { @Test public void testBroadcastOperations() throws IOException { prepareCreate("test", 1).execute().actionGet(5000); logger.info("Running Cluster Health"); ClusterHealthResponse clusterHealth = client().admin().cluster().health(clusterHealthRequest().waitForYellowStatus()).actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW)); client().index(indexRequest("test").type("type1").id("1").source(source("1", "test"))).actionGet(); flush(); client().index(indexRequest("test").type("type1").id("2").source(source("2", "test"))).actionGet(); refresh(); logger.info("Count"); // check count for (int i = 0; i < 5; i++) { // test successful CountResponse countResponse = client().prepareCount("test") .setQuery(termQuery("_type", "type1")) .setOperationThreading(BroadcastOperationThreading.NO_THREADS).get(); assertThat(countResponse.getCount(), equalTo(2l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(5)); assertThat(countResponse.getFailedShards(), equalTo(0)); } for (int i = 0; i < 5; i++) { CountResponse countResponse = client().prepareCount("test") .setQuery(termQuery("_type", "type1")) .setOperationThreading(BroadcastOperationThreading.SINGLE_THREAD).get(); assertThat(countResponse.getCount(), equalTo(2l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(5)); assertThat(countResponse.getFailedShards(), equalTo(0)); } for (int i = 0; i < 5; i++) { CountResponse countResponse = client().prepareCount("test") .setQuery(termQuery("_type", "type1")) .setOperationThreading(BroadcastOperationThreading.THREAD_PER_SHARD).get(); assertThat(countResponse.getCount(), equalTo(2l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(5)); assertThat(countResponse.getFailedShards(), equalTo(0)); } for (int i = 0; i < 5; i++) { // test failed (simply query that can't be parsed) CountResponse countResponse = client().count(countRequest("test").source("{ term : { _type : \"type1 } }".getBytes(Charsets.UTF_8))).actionGet(); assertThat(countResponse.getCount(), equalTo(0l)); assertThat(countResponse.getTotalShards(), equalTo(5)); assertThat(countResponse.getSuccessfulShards(), equalTo(0)); assertThat(countResponse.getFailedShards(), equalTo(5)); for (ShardOperationFailedException exp : countResponse.getShardFailures()) { assertThat(exp.reason(), containsString("QueryParsingException")); } } } private XContentBuilder source(String id, String nameValue) throws IOException { return XContentFactory.jsonBuilder().startObject().field("id", id).field("name", nameValue).endObject(); } }
0true
src_test_java_org_elasticsearch_broadcast_BroadcastActionsTests.java
4,267
public class FsChannelSnapshot implements Translog.Snapshot { private final long id; private final int totalOperations; private final RafReference raf; private final FileChannel channel; private final long length; private Translog.Operation lastOperationRead = null; private int position = 0; private ByteBuffer cacheBuffer; public FsChannelSnapshot(long id, RafReference raf, long length, int totalOperations) throws FileNotFoundException { this.id = id; this.raf = raf; this.channel = raf.raf().getChannel(); this.length = length; this.totalOperations = totalOperations; } @Override public long translogId() { return this.id; } @Override public long position() { return this.position; } @Override public long length() { return this.length; } @Override public int estimatedTotalOperations() { return this.totalOperations; } @Override public InputStream stream() throws IOException { return new FileChannelInputStream(channel, position, lengthInBytes()); } @Override public long lengthInBytes() { return length - position; } @Override public boolean hasNext() { try { if (position > length) { return false; } if (cacheBuffer == null) { cacheBuffer = ByteBuffer.allocate(1024); } cacheBuffer.limit(4); int bytesRead = channel.read(cacheBuffer, position); if (bytesRead < 4) { return false; } cacheBuffer.flip(); int opSize = cacheBuffer.getInt(); position += 4; if ((position + opSize) > length) { // restore the position to before we read the opSize position -= 4; return false; } if (cacheBuffer.capacity() < opSize) { cacheBuffer = ByteBuffer.allocate(opSize); } cacheBuffer.clear(); cacheBuffer.limit(opSize); channel.read(cacheBuffer, position); cacheBuffer.flip(); position += opSize; lastOperationRead = TranslogStreams.readTranslogOperation(new BytesStreamInput(cacheBuffer.array(), 0, opSize, true)); return true; } catch (Exception e) { return false; } } @Override public Translog.Operation next() { return this.lastOperationRead; } @Override public void seekForward(long length) { this.position += length; } @Override public boolean release() throws ElasticsearchException { raf.decreaseRefCount(true); return true; } }
1no label
src_main_java_org_elasticsearch_index_translog_fs_FsChannelSnapshot.java
299
public class UnavailableShardsException extends ElasticsearchException { public UnavailableShardsException(@Nullable ShardId shardId, String message) { super(buildMessage(shardId, message)); } private static String buildMessage(ShardId shardId, String message) { if (shardId == null) { return message; } return "[" + shardId.index().name() + "][" + shardId.id() + "] " + message; } @Override public RestStatus status() { return RestStatus.SERVICE_UNAVAILABLE; } }
0true
src_main_java_org_elasticsearch_action_UnavailableShardsException.java
1,501
NodeSettingsService service = new NodeSettingsService(settingsBuilder().build()) { @Override public void addListener(Listener listener) { assertNull("addListener was called twice while only one time was expected", listeners[0]); listeners[0] = listener; } };
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_BalanceConfigurationTests.java
339
public interface ODatabaseListener { public void onCreate(final ODatabase iDatabase); public void onDelete(final ODatabase iDatabase); public void onOpen(final ODatabase iDatabase); public void onBeforeTxBegin(final ODatabase iDatabase); public void onBeforeTxRollback(final ODatabase iDatabase); public void onAfterTxRollback(final ODatabase iDatabase); public void onBeforeTxCommit(final ODatabase iDatabase); public void onAfterTxCommit(final ODatabase iDatabase); public void onClose(final ODatabase iDatabase); /** * Callback to decide if repair the database upon corruption. * * @param iDatabase * Target database * @param iReason * Reason of corruption * @param iWhatWillbeFixed TODO * @return true if repair must be done, otherwise false */ public boolean onCorruptionRepairDatabase(final ODatabase iDatabase, final String iReason, String iWhatWillbeFixed); }
0true
core_src_main_java_com_orientechnologies_orient_core_db_ODatabaseListener.java
14
ScheduledFuture future = exe.scheduleWithFixedDelay(new Runnable() { AtomicInteger atomicInt = new AtomicInteger(0); @Override public void run() { try { for (int i=0;i<10;i++) { exe.submit(new Runnable() { private final int number = atomicInt.incrementAndGet(); @Override public void run() { try { Thread.sleep(150); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(number); } }); System.out.println("Submitted: "+i); // doSomethingExpensive(20); } } catch (Exception e) { e.printStackTrace(); } } },0,1, TimeUnit.SECONDS);
0true
titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java
1,451
public class TimestampsRegionCache extends LocalRegionCache implements RegionCache { public TimestampsRegionCache(final String name, final HazelcastInstance hazelcastInstance) { super(name, hazelcastInstance, null); } @Override public boolean put(Object key, Object value, Object currentVersion) { return update(key, value, currentVersion, null, null); } @Override protected MessageListener<Object> createMessageListener() { return new MessageListener<Object>() { public void onMessage(final Message<Object> message) { final Timestamp ts = (Timestamp) message.getMessageObject(); final Object key = ts.getKey(); for (;;) { final Value value = cache.get(key); final Long current = value != null ? (Long) value.getValue() : null; if (current != null) { if (ts.getTimestamp() > current) { if (cache.replace(key, value, new Value(value.getVersion(), ts.getTimestamp(), Clock.currentTimeMillis()))) { return; } } else { return; } } else { if (cache.putIfAbsent(key, new Value(null, ts.getTimestamp(), Clock.currentTimeMillis())) == null) { return; } } } } }; } @Override protected Object createMessage(final Object key, final Object value, final Object currentVersion) { return new Timestamp(key, (Long) value); } final void cleanup() { } }
1no label
hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_local_TimestampsRegionCache.java
115
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_PAGE_TMPLT") @Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements") @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "PageTemplateImpl_basePageTemplate") public class PageTemplateImpl implements PageTemplate, AdminMainEntity { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "PageTemplateId") @GenericGenerator( name="PageTemplateId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="PageTemplateImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.page.domain.PageTemplateImpl") } ) @Column(name = "PAGE_TMPLT_ID") @AdminPresentation(friendlyName = "PageTemplateImpl_Template_Id", visibility = VisibilityEnum.HIDDEN_ALL, readOnly = true) protected Long id; @Column (name = "TMPLT_NAME") @AdminPresentation(friendlyName = "PageTemplateImpl_Template_Name", prominent = true, gridOrder = 1) protected String templateName; @Column (name = "TMPLT_DESCR") protected String templateDescription; @Column (name = "TMPLT_PATH") @AdminPresentation(friendlyName = "PageTemplateImpl_Template_Path", visibility = VisibilityEnum.HIDDEN_ALL, readOnly = true) protected String templatePath; @ManyToOne(targetEntity = LocaleImpl.class) @JoinColumn(name = "LOCALE_CODE") @AdminPresentation(excluded = true) protected Locale locale; @ManyToMany(targetEntity = FieldGroupImpl.class, cascade = {CascadeType.ALL}) @JoinTable(name = "BLC_PGTMPLT_FLDGRP_XREF", joinColumns = @JoinColumn(name = "PAGE_TMPLT_ID", referencedColumnName = "PAGE_TMPLT_ID"), inverseJoinColumns = @JoinColumn(name = "FLD_GROUP_ID", referencedColumnName = "FLD_GROUP_ID")) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blCMSElements") @OrderColumn(name = "GROUP_ORDER") @BatchSize(size = 20) protected List<FieldGroup> fieldGroups; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getTemplateName() { return templateName; } @Override public void setTemplateName(String templateName) { this.templateName = templateName; } @Override public String getTemplateDescription() { return templateDescription; } @Override public void setTemplateDescription(String templateDescription) { this.templateDescription = templateDescription; } @Override public String getTemplatePath() { return templatePath; } @Override public void setTemplatePath(String templatePath) { this.templatePath = templatePath; } @Override public Locale getLocale() { return locale; } @Override public void setLocale(Locale locale) { this.locale = locale; } @Override public List<FieldGroup> getFieldGroups() { return fieldGroups; } @Override public void setFieldGroups(List<FieldGroup> fieldGroups) { this.fieldGroups = fieldGroups; } @Override public String getMainEntityName() { return getTemplateName(); } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageTemplateImpl.java
1,179
public static class EchoServerHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { e.getChannel().write(e.getMessage()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. e.getCause().printStackTrace(); e.getChannel().close(); } }
0true
src_test_java_org_elasticsearch_benchmark_transport_netty_NettyEchoBenchmark.java
1,106
MULTI_VALUED_DATE { public int numValues() { return RANDOM.nextInt(3); } @Override public long nextValue() { // somewhere in-between 2010 and 2012 return 1000L * (40L * SECONDS_PER_YEAR + RANDOM.nextInt(2 * SECONDS_PER_YEAR)); } },
0true
src_test_java_org_elasticsearch_benchmark_fielddata_LongFieldDataBenchmark.java
3,421
public class ProxyServiceImpl implements ProxyService, PostJoinAwareService, EventPublishingService<DistributedObjectEventPacket, Object> { static final String SERVICE_NAME = "hz:core:proxyService"; private final NodeEngineImpl nodeEngine; private final ConcurrentMap<String, ProxyRegistry> registries = new ConcurrentHashMap<String, ProxyRegistry>(); private final ConcurrentMap<String, DistributedObjectListener> listeners = new ConcurrentHashMap<String, DistributedObjectListener>(); private final ILogger logger; ProxyServiceImpl(NodeEngineImpl nodeEngine) { this.nodeEngine = nodeEngine; this.logger = nodeEngine.getLogger(ProxyService.class.getName()); } void init() { nodeEngine.getEventService().registerListener(SERVICE_NAME, SERVICE_NAME, new Object()); } private final ConstructorFunction<String, ProxyRegistry> registryConstructor = new ConstructorFunction<String, ProxyRegistry>() { public ProxyRegistry createNew(String serviceName) { return new ProxyRegistry(serviceName); } }; @Override public int getProxyCount() { int count = 0; for (ProxyRegistry registry : registries.values()) { count += registry.getProxyCount(); } return count; } @Override public void initializeDistributedObject(String serviceName, String name) { if (serviceName == null) { throw new NullPointerException("Service name is required!"); } if (name == null) { throw new NullPointerException("Object name is required!"); } ProxyRegistry registry = getOrPutIfAbsent(registries, serviceName, registryConstructor); registry.createProxy(name, true, true); } @Override public DistributedObject getDistributedObject(String serviceName, String name) { if (serviceName == null) { throw new NullPointerException("Service name is required!"); } if (name == null) { throw new NullPointerException("Object name is required!"); } ProxyRegistry registry = getOrPutIfAbsent(registries, serviceName, registryConstructor); return registry.getOrCreateProxy(name, true, true); } @Override public void destroyDistributedObject(String serviceName, String name) { if (serviceName == null) { throw new NullPointerException("Service name is required!"); } if (name == null) { throw new NullPointerException("Object name is required!"); } Collection<MemberImpl> members = nodeEngine.getClusterService().getMemberList(); Collection<Future> calls = new ArrayList<Future>(members.size()); for (MemberImpl member : members) { if (member.localMember()) { continue; } Future f = nodeEngine.getOperationService() .createInvocationBuilder(SERVICE_NAME, new DistributedObjectDestroyOperation(serviceName, name), member.getAddress()).setTryCount(10).invoke(); calls.add(f); } destroyLocalDistributedObject(serviceName, name, true); for (Future f : calls) { try { f.get(3, TimeUnit.SECONDS); } catch (Exception e) { logger.finest(e); } } } private void destroyLocalDistributedObject(String serviceName, String name, boolean fireEvent) { ProxyRegistry registry = registries.get(serviceName); if (registry != null) { registry.destroyProxy(name, fireEvent); } final RemoteService service = nodeEngine.getService(serviceName); if (service != null) { service.destroyDistributedObject(name); } Throwable cause = new DistributedObjectDestroyedException(serviceName, name); nodeEngine.waitNotifyService.cancelWaitingOps(serviceName, name, cause); } @Override public Collection<DistributedObject> getDistributedObjects(String serviceName) { if (serviceName == null) { throw new NullPointerException("Service name is required!"); } Collection<DistributedObject> objects = new LinkedList<DistributedObject>(); ProxyRegistry registry = registries.get(serviceName); if (registry != null) { Collection<DistributedObjectFuture> futures = registry.proxies.values(); for (DistributedObjectFuture future : futures) { objects.add(future.get()); } } return objects; } @Override public Collection<DistributedObject> getAllDistributedObjects() { Collection<DistributedObject> objects = new LinkedList<DistributedObject>(); for (ProxyRegistry registry : registries.values()) { Collection<DistributedObjectFuture> futures = registry.proxies.values(); for (DistributedObjectFuture future : futures) { objects.add(future.get()); } } return objects; } @Override public String addProxyListener(DistributedObjectListener distributedObjectListener) { final String id = UuidUtil.buildRandomUuidString(); listeners.put(id, distributedObjectListener); return id; } @Override public boolean removeProxyListener(String registrationId) { return listeners.remove(registrationId) != null; } @Override public void dispatchEvent(final DistributedObjectEventPacket eventPacket, Object ignore) { final String serviceName = eventPacket.getServiceName(); if (eventPacket.getEventType() == CREATED) { try { final ProxyRegistry registry = getOrPutIfAbsent(registries, serviceName, registryConstructor); if (!registry.contains(eventPacket.getName())) { registry.createProxy(eventPacket.getName(), false, true); // listeners will be called if proxy is created here. } } catch (HazelcastInstanceNotActiveException ignored) { } } else { final ProxyRegistry registry = registries.get(serviceName); if (registry != null) { registry.destroyProxy(eventPacket.getName(), false); } } } @Override public Operation getPostJoinOperation() { Collection<ProxyInfo> proxies = new LinkedList<ProxyInfo>(); for (ProxyRegistry registry : registries.values()) { for (DistributedObjectFuture future : registry.proxies.values()) { DistributedObject distributedObject = future.get(); if (distributedObject instanceof InitializingObject) { proxies.add(new ProxyInfo(registry.serviceName, distributedObject.getName())); } } } return proxies.isEmpty() ? null : new PostJoinProxyOperation(proxies); } private class ProxyRegistry { final String serviceName; final RemoteService service; final ConcurrentMap<String, DistributedObjectFuture> proxies = new ConcurrentHashMap<String, DistributedObjectFuture>(); private ProxyRegistry(String serviceName) { this.serviceName = serviceName; this.service = nodeEngine.getService(serviceName); if (service == null) { if (nodeEngine.isActive()) { throw new IllegalArgumentException("Unknown service: " + serviceName); } else { throw new HazelcastInstanceNotActiveException(); } } } /** * Retrieves a DistributedObject proxy or creates it if it's not available * * @param name name of the proxy object * @param publishEvent true if a DistributedObjectEvent should be fired * @param initialize true if proxy object should be initialized * @return a DistributedObject instance */ DistributedObject getOrCreateProxy(final String name, boolean publishEvent, boolean initialize) { DistributedObjectFuture proxyFuture = proxies.get(name); if (proxyFuture == null) { if (!nodeEngine.isActive()) { throw new HazelcastInstanceNotActiveException(); } proxyFuture = createProxy(name, publishEvent, initialize); if (proxyFuture == null) { // warning; recursive call! I (@mdogan) do not think this will ever cause a stack overflow.. return getOrCreateProxy(name, publishEvent, initialize); } } return proxyFuture.get(); } /** * Creates a DistributedObject proxy if it's not created yet * * @param name name of the proxy object * @param publishEvent true if a DistributedObjectEvent should be fired * @param initialize true if proxy object should be initialized * @return a DistributedObject instance if it's created by this method, null otherwise */ DistributedObjectFuture createProxy(final String name, boolean publishEvent, boolean initialize) { if (!proxies.containsKey(name)) { if (!nodeEngine.isActive()) { throw new HazelcastInstanceNotActiveException(); } DistributedObjectFuture proxyFuture = new DistributedObjectFuture(); if (proxies.putIfAbsent(name, proxyFuture) == null) { DistributedObject proxy = service.createDistributedObject(name); if (initialize && proxy instanceof InitializingObject) { try { ((InitializingObject) proxy).initialize(); } catch (Exception e) { logger.warning("Error while initializing proxy: " + proxy, e); } } nodeEngine.eventService.executeEvent(new ProxyEventProcessor(CREATED, serviceName, proxy)); if (publishEvent) { publish(new DistributedObjectEventPacket(CREATED, serviceName, name)); } proxyFuture.set(proxy); return proxyFuture; } } return null; } void destroyProxy(String name, boolean publishEvent) { final DistributedObjectFuture proxyFuture = proxies.remove(name); if (proxyFuture != null) { DistributedObject proxy = proxyFuture.get(); nodeEngine.eventService.executeEvent(new ProxyEventProcessor(DESTROYED, serviceName, proxy)); if (publishEvent) { publish(new DistributedObjectEventPacket(DESTROYED, serviceName, name)); } } } private void publish(DistributedObjectEventPacket event) { final EventService eventService = nodeEngine.getEventService(); final Collection<EventRegistration> registrations = eventService.getRegistrations(SERVICE_NAME, SERVICE_NAME); eventService.publishEvent(SERVICE_NAME, registrations, event, event.getName().hashCode()); } private boolean contains(String name) { return proxies.containsKey(name); } void destroy() { for (DistributedObjectFuture future : proxies.values()) { DistributedObject distributedObject = future.get(); if (distributedObject instanceof AbstractDistributedObject) { ((AbstractDistributedObject) distributedObject).invalidate(); } } proxies.clear(); } public int getProxyCount() { return proxies.size(); } } private static class DistributedObjectFuture { volatile DistributedObject proxy; DistributedObject get() { if (proxy == null) { boolean interrupted = false; synchronized (this) { while (proxy == null) { try { wait(); } catch (InterruptedException e) { interrupted = true; } } } if (interrupted) { Thread.currentThread().interrupt(); } } return proxy; } void set(DistributedObject o) { if (o == null) { throw new IllegalArgumentException(); } synchronized (this) { proxy = o; notifyAll(); } } } private class ProxyEventProcessor implements StripedRunnable { final EventType type; final String serviceName; final DistributedObject object; private ProxyEventProcessor(EventType eventType, String serviceName, DistributedObject object) { this.type = eventType; this.serviceName = serviceName; this.object = object; } @Override public void run() { DistributedObjectEvent event = new DistributedObjectEvent(type, serviceName, object); for (DistributedObjectListener listener : listeners.values()) { if (EventType.CREATED.equals(type)) { listener.distributedObjectCreated(event); } else if (EventType.DESTROYED.equals(type)) { listener.distributedObjectDestroyed(event); } } } @Override public int getKey() { return object.getId().hashCode(); } } public static class DistributedObjectDestroyOperation extends AbstractOperation { private String serviceName; private String name; public DistributedObjectDestroyOperation() { } public DistributedObjectDestroyOperation(String serviceName, String name) { this.serviceName = serviceName; this.name = name; } @Override public void run() throws Exception { ProxyServiceImpl proxyService = getService(); proxyService.destroyLocalDistributedObject(serviceName, name, false); } @Override public boolean returnsResponse() { return true; } @Override public Object getResponse() { return Boolean.TRUE; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeUTF(serviceName); out.writeObject(name); // writing as object for backward-compatibility } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); serviceName = in.readUTF(); name = in.readObject(); } } public static class PostJoinProxyOperation extends AbstractOperation { private Collection<ProxyInfo> proxies; public PostJoinProxyOperation() { } public PostJoinProxyOperation(Collection<ProxyInfo> proxies) { this.proxies = proxies; } @Override public void run() throws Exception { if (proxies != null && proxies.size() > 0) { NodeEngine nodeEngine = getNodeEngine(); ProxyServiceImpl proxyService = getService(); for (ProxyInfo proxy : proxies) { final ProxyRegistry registry = getOrPutIfAbsent(proxyService.registries, proxy.serviceName, proxyService.registryConstructor); DistributedObjectFuture future = registry.createProxy(proxy.objectName, false, false); if (future != null) { final DistributedObject object = future.get(); if (object instanceof InitializingObject) { nodeEngine.getExecutionService().execute(ExecutionService.SYSTEM_EXECUTOR, new Runnable() { public void run() { try { ((InitializingObject) object).initialize(); } catch (Exception e) { getLogger().warning("Error while initializing proxy: " + object, e); } } }); } } } } } @Override public String getServiceName() { return ProxyServiceImpl.SERVICE_NAME; } @Override public boolean returnsResponse() { return false; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); int len = proxies != null ? proxies.size() : 0; out.writeInt(len); if (len > 0) { for (ProxyInfo proxy : proxies) { out.writeUTF(proxy.serviceName); out.writeObject(proxy.objectName); // writing as object for backward-compatibility } } } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); int len = in.readInt(); if (len > 0) { proxies = new ArrayList<ProxyInfo>(len); for (int i = 0; i < len; i++) { ProxyInfo proxy = new ProxyInfo(in.readUTF(), (String) in.readObject()); proxies.add(proxy); } } } } private static class ProxyInfo { final String serviceName; final String objectName; private ProxyInfo(String serviceName, String objectName) { this.serviceName = serviceName; this.objectName = objectName; } @Override public String toString() { final StringBuilder sb = new StringBuilder("ProxyInfo{"); sb.append("serviceName='").append(serviceName).append('\''); sb.append(", objectName='").append(objectName).append('\''); sb.append('}'); return sb.toString(); } } void shutdown() { for (ProxyRegistry registry : registries.values()) { registry.destroy(); } registries.clear(); listeners.clear(); } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_ProxyServiceImpl.java
1,922
EntryListener<Object, Object> listener = new EntryListener<Object, Object>() { private void handleEvent(EntryEvent<Object, Object> event) { if (endpoint.live()) { Data key = clientEngine.toData(event.getKey()); Data value = clientEngine.toData(event.getValue()); Data oldValue = clientEngine.toData(event.getOldValue()); PortableEntryEvent portableEntryEvent = new PortableEntryEvent(key, value, oldValue, event.getEventType(), event.getMember().getUuid()); endpoint.sendEvent(portableEntryEvent, getCallId()); } } public void entryAdded(EntryEvent<Object, Object> event) { handleEvent(event); } public void entryRemoved(EntryEvent<Object, Object> event) { handleEvent(event); } public void entryUpdated(EntryEvent<Object, Object> event) { handleEvent(event); } public void entryEvicted(EntryEvent<Object, Object> event) { handleEvent(event); } };
1no label
hazelcast_src_main_java_com_hazelcast_map_client_AbstractMapAddEntryListenerRequest.java
563
public class PutMappingRequest extends AcknowledgedRequest<PutMappingRequest> { private static ObjectOpenHashSet<String> RESERVED_FIELDS = ObjectOpenHashSet.from( "_uid", "_id", "_type", "_source", "_all", "_analyzer", "_boost", "_parent", "_routing", "_index", "_size", "_timestamp", "_ttl" ); private String[] indices; private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, true); private String type; private String source; private boolean ignoreConflicts = false; PutMappingRequest() { } /** * Constructs a new put mapping request against one or more indices. If nothing is set then * it will be executed against all indices. */ public PutMappingRequest(String... indices) { this.indices = indices; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (type == null) { validationException = addValidationError("mapping type is missing", validationException); } if (source == null) { validationException = addValidationError("mapping source is missing", validationException); } return validationException; } /** * Sets the indices this put mapping operation will execute on. */ public PutMappingRequest indices(String[] indices) { this.indices = indices; return this; } /** * The indices the mappings will be put. */ public String[] indices() { return indices; } public IndicesOptions indicesOptions() { return indicesOptions; } public PutMappingRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } /** * The mapping type. */ public String type() { return type; } /** * The type of the mappings. */ public PutMappingRequest type(String type) { this.type = type; return this; } /** * The mapping source definition. */ public String source() { return source; } /** * A specialized simplified mapping source method, takes the form of simple properties definition: * ("field1", "type=string,store=true"). * * Also supports metadata mapping fields such as `_all` and `_parent` as property definition, these metadata * mapping fields will automatically be put on the top level mapping object. */ public PutMappingRequest source(Object... source) { return source(buildFromSimplifiedDef(type, source)); } public static XContentBuilder buildFromSimplifiedDef(String type, Object... source) { try { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); if (type != null) { builder.startObject(type); } for (int i = 0; i < source.length; i++) { String fieldName = source[i++].toString(); if (RESERVED_FIELDS.contains(fieldName)) { builder.startObject(fieldName); String[] s1 = Strings.splitStringByCommaToArray(source[i].toString()); for (String s : s1) { String[] s2 = Strings.split(s, "="); if (s2.length != 2) { throw new ElasticsearchIllegalArgumentException("malformed " + s); } builder.field(s2[0], s2[1]); } builder.endObject(); } } builder.startObject("properties"); for (int i = 0; i < source.length; i++) { String fieldName = source[i++].toString(); if (RESERVED_FIELDS.contains(fieldName)) { continue; } builder.startObject(fieldName); String[] s1 = Strings.splitStringByCommaToArray(source[i].toString()); for (String s : s1) { String[] s2 = Strings.split(s, "="); if (s2.length != 2) { throw new ElasticsearchIllegalArgumentException("malformed " + s); } builder.field(s2[0], s2[1]); } builder.endObject(); } builder.endObject(); if (type != null) { builder.endObject(); } builder.endObject(); return builder; } catch (Exception e) { throw new ElasticsearchIllegalArgumentException("failed to generate simplified mapping definition", e); } } /** * The mapping source definition. */ public PutMappingRequest source(XContentBuilder mappingBuilder) { try { return source(mappingBuilder.string()); } catch (IOException e) { throw new ElasticsearchIllegalArgumentException("Failed to build json for mapping request", e); } } /** * The mapping source definition. */ @SuppressWarnings("unchecked") public PutMappingRequest source(Map mappingSource) { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(mappingSource); return source(builder.string()); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + mappingSource + "]", e); } } /** * The mapping source definition. */ public PutMappingRequest source(String mappingSource) { this.source = mappingSource; return this; } /** * If there is already a mapping definition registered against the type, then it will be merged. If there are * elements that can't be merged are detected, the request will be rejected unless the * {@link #ignoreConflicts(boolean)} is set. In such a case, the duplicate mappings will be rejected. */ public boolean ignoreConflicts() { return ignoreConflicts; } /** * If there is already a mapping definition registered against the type, then it will be merged. If there are * elements that can't be merged are detected, the request will be rejected unless the * {@link #ignoreConflicts(boolean)} is set. In such a case, the duplicate mappings will be rejected. */ public PutMappingRequest ignoreConflicts(boolean ignoreDuplicates) { this.ignoreConflicts = ignoreDuplicates; return this; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); indices = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); type = in.readOptionalString(); source = in.readString(); readTimeout(in); ignoreConflicts = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArrayNullable(indices); indicesOptions.writeIndicesOptions(out); out.writeOptionalString(type); out.writeString(source); writeTimeout(out); out.writeBoolean(ignoreConflicts); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_put_PutMappingRequest.java
425
restoreService.addListener(new RestoreService.RestoreCompletionListener() { SnapshotId snapshotId = new SnapshotId(request.repository(), request.snapshot()); @Override public void onRestoreCompletion(SnapshotId snapshotId, RestoreInfo snapshot) { if (this.snapshotId.equals(snapshotId)) { listener.onResponse(new RestoreSnapshotResponse(snapshot)); restoreService.removeListener(this); } } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_TransportRestoreSnapshotAction.java
271
public class ElasticsearchParseException extends ElasticsearchException { public ElasticsearchParseException(String msg) { super(msg); } public ElasticsearchParseException(String msg, Throwable cause) { super(msg, cause); } @Override public RestStatus status() { return RestStatus.BAD_REQUEST; } }
0true
src_main_java_org_elasticsearch_ElasticsearchParseException.java
1,212
QUEUE { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) { return concurrentDeque(c, limit); } },
0true
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java
704
constructors[COLLECTION_CONTAINS] = new ConstructorFunction<Integer, Portable>() { public Portable createNew(Integer arg) { return new CollectionContainsRequest(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
5,346
public abstract class ValuesSourceMetricsAggregatorParser<S extends MetricsAggregation> implements Aggregator.Parser { protected boolean requiresSortedValues() { return false; } @Override public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException { ValuesSourceConfig<NumericValuesSource> config = new ValuesSourceConfig<NumericValuesSource>(NumericValuesSource.class); String field = null; String script = null; String scriptLang = null; Map<String, Object> scriptParams = null; boolean assumeSorted = false; XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { if ("field".equals(currentFieldName)) { field = parser.text(); } else if ("script".equals(currentFieldName)) { script = parser.text(); } else if ("lang".equals(currentFieldName)) { scriptLang = parser.text(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.START_OBJECT) { if ("params".equals(currentFieldName)) { scriptParams = parser.map(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.VALUE_BOOLEAN) { if ("script_values_sorted".equals(currentFieldName)) { assumeSorted = parser.booleanValue(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else { throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "]."); } } if (script != null) { config.script(context.scriptService().search(context.lookup(), scriptLang, script, scriptParams)); } if (!assumeSorted && requiresSortedValues()) { config.ensureSorted(true); } if (field == null) { return createFactory(aggregationName, config); } FieldMapper<?> mapper = context.smartNameFieldMapper(field); if (mapper == null) { config.unmapped(true); return createFactory(aggregationName, config); } IndexFieldData<?> indexFieldData = context.fieldData().getForField(mapper); config.fieldContext(new FieldContext(field, indexFieldData)); return createFactory(aggregationName, config); } protected abstract AggregatorFactory createFactory(String aggregationName, ValuesSourceConfig<NumericValuesSource> config); }
1no label
src_main_java_org_elasticsearch_search_aggregations_metrics_ValuesSourceMetricsAggregatorParser.java
632
public class TcpIpJoinerOverAWS extends TcpIpJoiner { final AWSClient aws; final ILogger logger; public TcpIpJoinerOverAWS(Node node) { super(node); logger = node.getLogger(getClass()); AwsConfig awsConfig = node.getConfig().getNetworkConfig().getJoin().getAwsConfig(); aws = new AWSClient(awsConfig); if (awsConfig.getRegion() != null && awsConfig.getRegion().length() > 0) { aws.setEndpoint("ec2." + awsConfig.getRegion() + ".amazonaws.com"); } } @Override protected Collection<String> getMembers() { try { List<String> list = aws.getPrivateIpAddresses(); if(list.isEmpty()){ logger.warning("No EC2 instances found!"); }else{ if(logger.isFinestEnabled()){ StringBuilder sb = new StringBuilder("Found the following EC2 instances:\n"); for(String ip: list){ sb.append(" ").append(ip).append("\n"); } logger.finest(sb.toString()); } } return list; } catch (Exception e) { logger.warning(e); throw ExceptionUtil.rethrow(e); } } @Override protected int getConnTimeoutSeconds() { AwsConfig awsConfig = node.getConfig().getNetworkConfig().getJoin().getAwsConfig(); return awsConfig.getConnectionTimeoutSeconds(); } @Override public String getType() { return "aws"; } }
0true
hazelcast-cloud_src_main_java_com_hazelcast_cluster_TcpIpJoinerOverAWS.java
1,201
hashSet = build(type, limit, smartSize, availableProcessors, new Recycler.C<ObjectOpenHashSet>() { @Override public ObjectOpenHashSet newInstance(int sizing) { return new ObjectOpenHashSet(size(sizing), 0.5f); } @Override public void clear(ObjectOpenHashSet value) { value.clear(); } });
0true
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java
230
assertTrueEventually(new AssertTask() { public void run() throws Exception { assertTrue(map.containsKey(targetUuid)); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java
2,578
clusterService.submitStateUpdateTask("zen-disco-receive(from master [" + newState.nodes().masterNode() + "])", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { // we don't need to do this, since we ping the master, and get notified when it has moved from being a master // because it doesn't have enough master nodes... //if (!electMaster.hasEnoughMasterNodes(newState.nodes())) { // return disconnectFromCluster(newState, "not enough master nodes on new cluster state received from [" + newState.nodes().masterNode() + "]"); //} latestDiscoNodes = newState.nodes(); // check to see that we monitor the correct master of the cluster if (masterFD.masterNode() == null || !masterFD.masterNode().equals(latestDiscoNodes.masterNode())) { masterFD.restart(latestDiscoNodes.masterNode(), "new cluster state received and we are monitoring the wrong master [" + masterFD.masterNode() + "]"); } ClusterState.Builder builder = ClusterState.builder(newState); // if the routing table did not change, use the original one if (newState.routingTable().version() == currentState.routingTable().version()) { builder.routingTable(currentState.routingTable()); } // same for metadata if (newState.metaData().version() == currentState.metaData().version()) { builder.metaData(currentState.metaData()); } else { // if its not the same version, only copy over new indices or ones that changed the version MetaData.Builder metaDataBuilder = MetaData.builder(newState.metaData()).removeAllIndices(); for (IndexMetaData indexMetaData : newState.metaData()) { IndexMetaData currentIndexMetaData = currentState.metaData().index(indexMetaData.index()); if (currentIndexMetaData == null || currentIndexMetaData.version() != indexMetaData.version()) { metaDataBuilder.put(indexMetaData, false); } else { metaDataBuilder.put(currentIndexMetaData, false); } } builder.metaData(metaDataBuilder); } return builder.build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); newStateProcessed.onNewClusterStateFailed(t); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); newStateProcessed.onNewClusterStateProcessed(); } });
1no label
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
5,195
public class InternalGeoHashGrid extends InternalAggregation implements GeoHashGrid { public static final Type TYPE = new Type("geohash_grid", "ghcells"); public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() { @Override public InternalGeoHashGrid readResult(StreamInput in) throws IOException { InternalGeoHashGrid buckets = new InternalGeoHashGrid(); buckets.readFrom(in); return buckets; } }; public static void registerStreams() { AggregationStreams.registerStream(STREAM, TYPE.stream()); } static class Bucket implements GeoHashGrid.Bucket, Comparable<Bucket> { protected long geohashAsLong; protected long docCount; protected InternalAggregations aggregations; public Bucket(long geohashAsLong, long docCount, InternalAggregations aggregations) { this.docCount = docCount; this.aggregations = aggregations; this.geohashAsLong = geohashAsLong; } public String getKey() { return GeoHashUtils.toString(geohashAsLong); } @Override public Text getKeyAsText() { return new StringText(getKey()); } public GeoPoint getKeyAsGeoPoint() { return GeoHashUtils.decode(geohashAsLong); } @Override public long getDocCount() { return docCount; } @Override public Aggregations getAggregations() { return aggregations; } @Override public int compareTo(Bucket other) { if (this.geohashAsLong > other.geohashAsLong) { return 1; } if (this.geohashAsLong < other.geohashAsLong) { return -1; } return 0; } public Bucket reduce(List<? extends Bucket> buckets, CacheRecycler cacheRecycler) { if (buckets.size() == 1) { // we still need to reduce the sub aggs Bucket bucket = buckets.get(0); bucket.aggregations.reduce(cacheRecycler); return bucket; } Bucket reduced = null; List<InternalAggregations> aggregationsList = new ArrayList<InternalAggregations>(buckets.size()); for (Bucket bucket : buckets) { if (reduced == null) { reduced = bucket; } else { reduced.docCount += bucket.docCount; } aggregationsList.add(bucket.aggregations); } reduced.aggregations = InternalAggregations.reduce(aggregationsList, cacheRecycler); return reduced; } @Override public Number getKeyAsNumber() { return geohashAsLong; } } private int requiredSize; private Collection<Bucket> buckets; protected Map<String, Bucket> bucketMap; InternalGeoHashGrid() { } // for serialization public InternalGeoHashGrid(String name, int requiredSize, Collection<Bucket> buckets) { super(name); this.requiredSize = requiredSize; this.buckets = buckets; } @Override public Type type() { return TYPE; } @Override public Collection<GeoHashGrid.Bucket> getBuckets() { Object o = buckets; return (Collection<GeoHashGrid.Bucket>) o; } @Override public GeoHashGrid.Bucket getBucketByKey(String geohash) { if (bucketMap == null) { bucketMap = new HashMap<String, Bucket>(buckets.size()); for (Bucket bucket : buckets) { bucketMap.put(bucket.getKey(), bucket); } } return bucketMap.get(geohash); } @Override public GeoHashGrid.Bucket getBucketByKey(Number key) { return getBucketByKey(GeoHashUtils.toString(key.longValue())); } @Override public GeoHashGrid.Bucket getBucketByKey(GeoPoint key) { return getBucketByKey(key.geohash()); } @Override public InternalGeoHashGrid reduce(ReduceContext reduceContext) { List<InternalAggregation> aggregations = reduceContext.aggregations(); if (aggregations.size() == 1) { InternalGeoHashGrid grid = (InternalGeoHashGrid) aggregations.get(0); grid.reduceAndTrimBuckets(reduceContext.cacheRecycler()); return grid; } InternalGeoHashGrid reduced = null; Recycler.V<LongObjectOpenHashMap<List<Bucket>>> buckets = null; for (InternalAggregation aggregation : aggregations) { InternalGeoHashGrid grid = (InternalGeoHashGrid) aggregation; if (reduced == null) { reduced = grid; } if (buckets == null) { buckets = reduceContext.cacheRecycler().longObjectMap(grid.buckets.size()); } for (Bucket bucket : grid.buckets) { List<Bucket> existingBuckets = buckets.v().get(bucket.geohashAsLong); if (existingBuckets == null) { existingBuckets = new ArrayList<Bucket>(aggregations.size()); buckets.v().put(bucket.geohashAsLong, existingBuckets); } existingBuckets.add(bucket); } } if (reduced == null) { // there are only unmapped terms, so we just return the first one (no need to reduce) return (InternalGeoHashGrid) aggregations.get(0); } // TODO: would it be better to sort the backing array buffer of the hppc map directly instead of using a PQ? final int size = Math.min(requiredSize, buckets.v().size()); BucketPriorityQueue ordered = new BucketPriorityQueue(size); Object[] internalBuckets = buckets.v().values; boolean[] states = buckets.v().allocated; for (int i = 0; i < states.length; i++) { if (states[i]) { List<Bucket> sameCellBuckets = (List<Bucket>) internalBuckets[i]; ordered.insertWithOverflow(sameCellBuckets.get(0).reduce(sameCellBuckets, reduceContext.cacheRecycler())); } } buckets.release(); Bucket[] list = new Bucket[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = ordered.pop(); } reduced.buckets = Arrays.asList(list); return reduced; } protected void reduceAndTrimBuckets(CacheRecycler cacheRecycler) { if (requiredSize > buckets.size()) { // nothing to trim for (Bucket bucket : buckets) { bucket.aggregations.reduce(cacheRecycler); } return; } List<Bucket> trimmedBuckets = new ArrayList<Bucket>(requiredSize); for (Bucket bucket : buckets) { if (trimmedBuckets.size() >= requiredSize) { break; } bucket.aggregations.reduce(cacheRecycler); trimmedBuckets.add(bucket); } buckets = trimmedBuckets; } @Override public void readFrom(StreamInput in) throws IOException { this.name = in.readString(); this.requiredSize = in.readVInt(); int size = in.readVInt(); List<Bucket> buckets = new ArrayList<Bucket>(size); for (int i = 0; i < size; i++) { buckets.add(new Bucket(in.readLong(), in.readVLong(), InternalAggregations.readAggregations(in))); } this.buckets = buckets; this.bucketMap = null; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); out.writeVInt(requiredSize); out.writeVInt(buckets.size()); for (Bucket bucket : buckets) { out.writeLong(bucket.geohashAsLong); out.writeVLong(bucket.getDocCount()); ((InternalAggregations) bucket.getAggregations()).writeTo(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name); builder.startArray(CommonFields.BUCKETS); for (Bucket bucket : buckets) { builder.startObject(); builder.field(CommonFields.KEY, bucket.getKeyAsText()); builder.field(CommonFields.DOC_COUNT, bucket.getDocCount()); ((InternalAggregations) bucket.getAggregations()).toXContentInternal(builder, params); builder.endObject(); } builder.endArray(); builder.endObject(); return builder; } static class BucketPriorityQueue extends PriorityQueue<Bucket> { public BucketPriorityQueue(int size) { super(size); } @Override protected boolean lessThan(Bucket o1, Bucket o2) { long i = o2.getDocCount() - o1.getDocCount(); if (i == 0) { i = o2.compareTo(o1); if (i == 0) { i = System.identityHashCode(o2) - System.identityHashCode(o1); } } return i > 0; } } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_geogrid_InternalGeoHashGrid.java
1,538
public static class Map extends Mapper<NullWritable, FaunusVertex, WritableComparable, Text> { private String key; private boolean isVertex; private WritableHandler handler; private String elementKey; private SafeMapperOutputs outputs; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); this.key = context.getConfiguration().get(KEY); this.handler = new WritableHandler(context.getConfiguration().getClass(TYPE, Text.class, WritableComparable.class)); this.elementKey = context.getConfiguration().get(ELEMENT_KEY); this.outputs = new SafeMapperOutputs(context); } private Text text = new Text(); private WritableComparable writable; @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, WritableComparable, Text>.Context context) throws IOException, InterruptedException { if (this.isVertex) { if (value.hasPaths()) { this.text.set(ElementPicker.getPropertyAsString(value, this.elementKey)); final Object temp = ElementPicker.getProperty(value, this.key); if (this.key.equals(Tokens._COUNT)) { this.writable = this.handler.set(temp); context.write(this.writable, this.text); } else if (temp instanceof Number) { this.writable = this.handler.set(multiplyPathCount((Number) temp, value.pathCount())); context.write(this.writable, this.text); } else { this.writable = this.handler.set(temp); for (int i = 0; i < value.pathCount(); i++) { context.write(this.writable, this.text); } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L); } } else { long edgesProcessed = 0; for (final Edge e : value.getEdges(Direction.OUT)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { this.text.set(ElementPicker.getPropertyAsString(edge, this.elementKey)); final Object temp = ElementPicker.getProperty(edge, this.key); if (this.key.equals(Tokens._COUNT)) { this.writable = this.handler.set(temp); context.write(this.writable, this.text); } else if (temp instanceof Number) { this.writable = this.handler.set(multiplyPathCount((Number) temp, edge.pathCount())); context.write(this.writable, this.text); } else { this.writable = this.handler.set(temp); for (int i = 0; i < edge.pathCount(); i++) { context.write(this.writable, this.text); } } edgesProcessed++; } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed); } this.outputs.write(Tokens.GRAPH, NullWritable.get(), value); } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, WritableComparable, Text>.Context context) throws IOException, InterruptedException { this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_OrderMapReduce.java
2,587
clusterService.submitStateUpdateTask("received a request to rejoin the cluster from [" + request.fromNodeId + "]", Priority.URGENT, new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { try { channel.sendResponse(TransportResponse.Empty.INSTANCE); } catch (Exception e) { logger.warn("failed to send response on rejoin cluster request handling", e); } return rejoin(currentState, "received a request to rejoin the cluster from [" + request.fromNodeId + "]"); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } });
1no label
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
769
public static enum OpType { /** * Index the source. If there an existing document with the id, it will * be replaced. */ INDEX((byte) 0), /** * Creates the resource. Simply adds it to the index, if there is an existing * document with the id, then it won't be removed. */ CREATE((byte) 1); private final byte id; private final String lowercase; OpType(byte id) { this.id = id; this.lowercase = this.toString().toLowerCase(Locale.ENGLISH); } /** * The internal representation of the operation type. */ public byte id() { return id; } public String lowercase() { return this.lowercase; } /** * Constructs the operation type from its internal representation. */ public static OpType fromId(byte id) { if (id == 0) { return INDEX; } else if (id == 1) { return CREATE; } else { throw new ElasticsearchIllegalArgumentException("No type match for [" + id + "]"); } } }
0true
src_main_java_org_elasticsearch_action_index_IndexRequest.java
1,464
public class BroadleafLoginController extends BroadleafAbstractController { @Resource(name="blCustomerService") protected CustomerService customerService; @Resource(name="blResetPasswordValidator") protected ResetPasswordValidator resetPasswordValidator; @Resource(name="blLoginService") protected LoginService loginService; protected static String loginView = "authentication/login"; protected static String forgotPasswordView = "authentication/forgotPassword"; protected static String forgotUsernameView = "authentication/forgotUsername"; protected static String forgotPasswordSuccessView = "authentication/forgotPasswordSuccess"; protected static String resetPasswordView = "authentication/resetPassword"; protected static String resetPasswordErrorView = "authentication/resetPasswordError"; protected static String resetPasswordSuccessView = "redirect:/"; protected static String resetPasswordFormView = "authentication/resetPasswordForm"; /** * Redirects to the login view. * * @param request * @param response * @param model * @return the return view */ public String login(HttpServletRequest request, HttpServletResponse response, Model model) { if (StringUtils.isNotBlank(request.getParameter("successUrl"))) { model.addAttribute("successUrl", request.getParameter("successUrl")); } return getLoginView(); } /** * Redirects to te forgot password view. * * @param request * @param response * @param model * @return the return view */ public String forgotPassword(HttpServletRequest request, HttpServletResponse response, Model model) { return getForgotPasswordView(); } /** * Looks up the passed in username and sends an email to the address on file with a * reset password token. * * Returns error codes for invalid username. * * @param username * @param request * @param model * @return the return view */ public String processForgotPassword(String username, HttpServletRequest request, Model model) { GenericResponse errorResponse = customerService.sendForgotPasswordNotification(username, getResetPasswordUrl(request)); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); model.addAttribute("errorCode", errorCode); return getForgotPasswordView(); } else { request.getSession(true).setAttribute("forgot_password_username", username); return getForgotPasswordSuccessView(); } } /** * Returns the forgot username view. * * @param request * @param response * @param model * @return the return view */ public String forgotUsername(HttpServletRequest request, HttpServletResponse response, Model model) { return getForgotUsernameView(); } /** * Looks up an account by email address and if found, sends an email with the * associated username. * * @param email * @param request * @param response * @param model * @return the return view */ public String processForgotUsername(String email, HttpServletRequest request, HttpServletResponse response, Model model) { GenericResponse errorResponse = customerService.sendForgotUsernameNotification(email); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); request.setAttribute("errorCode", errorCode); return getForgotUsernameView(); } else { return buildRedirectToLoginWithMessage("usernameSent"); } } /** * Displays the reset password view. Expects a valid resetPasswordToken to exist * that was generated by {@link processForgotPassword} or similar. Returns an error * view if the token is invalid or expired. * * @param request * @param response * @param model * @return the return view */ public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model) { ResetPasswordForm resetPasswordForm = initResetPasswordForm(request); model.addAttribute("resetPasswordForm", resetPasswordForm); GenericResponse errorResponse = customerService.checkPasswordResetToken(resetPasswordForm.getToken()); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); request.setAttribute("errorCode", errorCode); return getResetPasswordErrorView(); } else { return getResetPasswordView(); } } /** * Processes the reset password token and allows the user to change their password. * Ensures that the password and confirm password match, that the token is valid, * and that the token matches the provided email address. * * @param resetPasswordForm * @param request * @param response * @param model * @param errors * @return the return view * @throws ServiceException */ public String processResetPassword(ResetPasswordForm resetPasswordForm, HttpServletRequest request, HttpServletResponse response, Model model, BindingResult errors) throws ServiceException { GenericResponse errorResponse = new GenericResponse(); resetPasswordValidator.validate(resetPasswordForm.getUsername(), resetPasswordForm.getPassword(), resetPasswordForm.getPasswordConfirm(), errors); if (errorResponse.getHasErrors()) { return getResetPasswordView(); } errorResponse = customerService.resetPasswordUsingToken( resetPasswordForm.getUsername(), resetPasswordForm.getToken(), resetPasswordForm.getPassword(), resetPasswordForm.getPasswordConfirm()); if (errorResponse.getHasErrors()) { String errorCode = errorResponse.getErrorCodesList().get(0); request.setAttribute("errorCode", errorCode); return getResetPasswordView(); } else { // The reset password was successful, so log this customer in. loginService.loginCustomer(resetPasswordForm.getUsername(), resetPasswordForm.getPassword()); return getResetPasswordSuccessView(); } } /** * By default, redirects to the login page with a message. * * @param message * @return the return view */ protected String buildRedirectToLoginWithMessage(String message) { StringBuffer url = new StringBuffer("redirect:").append(getLoginView()).append("?messageCode=").append(message); return url.toString(); } /** * Initializes the reset password by ensuring that the passed in token URL * parameter initializes the hidden form field. * * Also, if the reset password request is in the same session as the * forgotPassword request, the username will auto-populate * * @param request * @return the return view */ public ResetPasswordForm initResetPasswordForm(HttpServletRequest request) { ResetPasswordForm resetPasswordForm = new ResetPasswordForm(); String username = (String) request.getSession(true).getAttribute("forgot_password_username"); String token = request.getParameter("token"); resetPasswordForm.setToken(token); resetPasswordForm.setUsername(username); return resetPasswordForm; } /** * @return the view representing the login page. */ public String getLoginView() { return loginView; } /** * @return the view displayed for the forgot username form. */ public String getForgotUsernameView() { return forgotUsernameView; } /** * @return the view displayed for the forgot password form. */ public String getForgotPasswordView() { return forgotPasswordView; } /** * @return the view displayed for the reset password form. */ public String getResetPasswordView() { return resetPasswordView; } /** * @return the view returned after a successful forgotPassword email has been sent. */ public String getForgotPasswordSuccessView() { return forgotPasswordSuccessView; } /** * @return the view name to use for the reset password model.. */ public String getResetPasswordFormView() { return resetPasswordFormView; } public String getResetPasswordScheme(HttpServletRequest request) { return request.getScheme(); } public String getResetPasswordPort(HttpServletRequest request, String scheme) { if ("http".equalsIgnoreCase(scheme) && request.getServerPort() != 80) { return ":" + request.getServerPort(); } else if ("https".equalsIgnoreCase(scheme) && request.getServerPort() != 443) { return ":" + request.getServerPort(); } return ""; // no port required } public String getResetPasswordUrl(HttpServletRequest request) { String url = request.getScheme() + "://" + request.getServerName() + getResetPasswordPort(request, request.getScheme() + "/"); if (request.getContextPath() != null && ! "".equals(request.getContextPath())) { url = url + request.getContextPath() + getResetPasswordView(); } else { url = url + getResetPasswordView(); } return url; } /** * View user is directed to if they try to access the resetPasswordForm with an * invalid token. * * @return the error view */ public String getResetPasswordErrorView() { return resetPasswordErrorView; } /** * View that a user is sent to after a successful reset password operations. * Should be a redirect (e.g. start with "redirect:" since * this will cause the entire SpringSecurity pipeline to be fulfilled. */ public String getResetPasswordSuccessView() { return resetPasswordSuccessView; } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_BroadleafLoginController.java
675
public class GetWarmersRequest extends ClusterInfoRequest<GetWarmersRequest> { private String[] warmers = Strings.EMPTY_ARRAY; public GetWarmersRequest warmers(String[] warmers) { this.warmers = warmers; return this; } public String[] warmers() { return warmers; } @Override public ActionRequestValidationException validate() { return null; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); warmers = in.readStringArray(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArray(warmers); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_warmer_get_GetWarmersRequest.java
511
public class HourOfDayType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, HourOfDayType> TYPES = new LinkedHashMap<String, HourOfDayType>(); public static final HourOfDayType ZERO = new HourOfDayType("0", "00"); public static final HourOfDayType ONE = new HourOfDayType("1", "01"); public static final HourOfDayType TWO = new HourOfDayType("2", "02"); public static final HourOfDayType THREE = new HourOfDayType("3", "03"); public static final HourOfDayType FOUR = new HourOfDayType("4", "04"); public static final HourOfDayType FIVE = new HourOfDayType("5", "05"); public static final HourOfDayType SIX = new HourOfDayType("6", "06"); public static final HourOfDayType SEVEN = new HourOfDayType("7", "07"); public static final HourOfDayType EIGHT = new HourOfDayType("8", "08"); public static final HourOfDayType NINE = new HourOfDayType("9", "09"); public static final HourOfDayType TEN = new HourOfDayType("10", "10"); public static final HourOfDayType ELEVEN = new HourOfDayType("11", "11"); public static final HourOfDayType TWELVE = new HourOfDayType("12", "12"); public static final HourOfDayType THIRTEEN = new HourOfDayType("13", "13"); public static final HourOfDayType FOURTEEN = new HourOfDayType("14", "14"); public static final HourOfDayType FIFTEEN = new HourOfDayType("15", "15"); public static final HourOfDayType SIXTEEN = new HourOfDayType("16", "16"); public static final HourOfDayType SEVENTEEN = new HourOfDayType("17", "17"); public static final HourOfDayType EIGHTEEN = new HourOfDayType("18", "18"); public static final HourOfDayType NINETEEN = new HourOfDayType("19", "19"); public static final HourOfDayType TWENTY = new HourOfDayType("20", "20"); public static final HourOfDayType TWENTYONE = new HourOfDayType("21", "21"); public static final HourOfDayType TWNETYTWO = new HourOfDayType("22", "22"); public static final HourOfDayType TWENTYTHREE = new HourOfDayType("23", "23"); public static HourOfDayType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public HourOfDayType() { //do nothing } public HourOfDayType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } else { throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HourOfDayType other = (HourOfDayType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
common_src_main_java_org_broadleafcommerce_common_time_HourOfDayType.java
1,972
@Entity @EntityListeners(value = { TemporalTimestampListener.class }) @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_CUSTOMER_ADDRESS", uniqueConstraints = @UniqueConstraint(name = "CSTMR_ADDR_UNIQUE_CNSTRNT", columnNames = { "CUSTOMER_ID", "ADDRESS_NAME" })) @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = "address.firstName", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED, booleanOverrideValue = true)), @AdminPresentationMergeOverride(name = "address.lastName", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED, booleanOverrideValue = true)), @AdminPresentationMergeOverride(name = "address.addressLine1", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.PROMINENT, booleanOverrideValue = true)) } ) @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE) public class CustomerAddressImpl implements CustomerAddress { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "CustomerAddressId") @GenericGenerator( name="CustomerAddressId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="CustomerAddressImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.profile.core.domain.CustomerAddressImpl") } ) @Column(name = "CUSTOMER_ADDRESS_ID") protected Long id; @Column(name = "ADDRESS_NAME") @AdminPresentation(friendlyName = "CustomerAddressImpl_Address_Name", order=1, group = "CustomerAddressImpl_Identification", groupOrder = 1, prominent = true, gridOrder = 1) protected String addressName; @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, targetEntity = CustomerImpl.class, optional=false) @JoinColumn(name = "CUSTOMER_ID") @AdminPresentation(excluded = true, visibility = VisibilityEnum.HIDDEN_ALL) protected Customer customer; @ManyToOne(cascade = CascadeType.ALL, targetEntity = AddressImpl.class, optional=false) @JoinColumn(name = "ADDRESS_ID") @Index(name="CUSTOMERADDRESS_ADDRESS_INDEX", columnNames={"ADDRESS_ID"}) protected Address address; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getAddressName() { return addressName; } @Override public void setAddressName(String addressName) { this.addressName = addressName; } @Override public Customer getCustomer() { return customer; } @Override public void setCustomer(Customer customer) { this.customer = customer; } @Override public Address getAddress() { return address; } @Override public void setAddress(Address address) { this.address = address; } @Override public String toString() { return (addressName == null) ? address.getFirstName() + " - " + address.getAddressLine1() : addressName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((addressName == null) ? 0 : addressName.hashCode()); result = prime * result + ((customer == null) ? 0 : customer.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CustomerAddressImpl other = (CustomerAddressImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (address == null) { if (other.address != null) { return false; } } else if (!address.equals(other.address)) { return false; } if (addressName == null) { if (other.addressName != null) { return false; } } else if (!addressName.equals(other.addressName)) { return false; } if (customer == null) { if (other.customer != null) { return false; } } else if (!customer.equals(other.customer)) { return false; } return true; } }
1no label
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_CustomerAddressImpl.java
680
public class PutWarmerRequest extends AcknowledgedRequest<PutWarmerRequest> { private String name; private SearchRequest searchRequest; PutWarmerRequest() { } /** * Constructs a new warmer. * * @param name The name of the warmer. */ public PutWarmerRequest(String name) { this.name = name; } /** * Sets the name of the warmer. */ public PutWarmerRequest name(String name) { this.name = name; return this; } String name() { return this.name; } /** * Sets the search request to warm. */ public PutWarmerRequest searchRequest(SearchRequest searchRequest) { this.searchRequest = searchRequest; return this; } /** * Sets the search request to warm. */ public PutWarmerRequest searchRequest(SearchRequestBuilder searchRequest) { this.searchRequest = searchRequest.request(); return this; } SearchRequest searchRequest() { return this.searchRequest; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (searchRequest == null) { validationException = addValidationError("search request is missing", validationException); } else { validationException = searchRequest.validate(); } if (name == null) { validationException = addValidationError("name is missing", validationException); } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); name = in.readString(); if (in.readBoolean()) { searchRequest = new SearchRequest(); searchRequest.readFrom(in); } readTimeout(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(name); if (searchRequest == null) { out.writeBoolean(false); } else { out.writeBoolean(true); searchRequest.writeTo(out); } writeTimeout(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_warmer_put_PutWarmerRequest.java
1,402
final NodeIndexDeletedAction.Listener nodeIndexDeleteListener = new NodeIndexDeletedAction.Listener() { @Override public void onNodeIndexDeleted(String index, String nodeId) { if (index.equals(request.index)) { if (counter.decrementAndGet() == 0) { listener.onResponse(new Response(true)); nodeIndexDeletedAction.remove(this); } } } @Override public void onNodeIndexStoreDeleted(String index, String nodeId) { if (index.equals(request.index)) { if (counter.decrementAndGet() == 0) { listener.onResponse(new Response(true)); nodeIndexDeletedAction.remove(this); } } } };
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java