Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
1,925
public enum TxnMapRequestType { CONTAINS_KEY(1), GET(2), SIZE(3), PUT(4), PUT_IF_ABSENT(5), REPLACE(6), REPLACE_IF_SAME(7), SET(8), REMOVE(9), DELETE(10), REMOVE_IF_SAME(11), KEYSET(12), KEYSET_BY_PREDICATE(13), VALUES(14), VALUES_BY_PREDICATE(15), GET_FOR_UPDATE(16), PUT_WITH_TTL(17); int type; TxnMapRequestType(int i) { type = i; } public static TxnMapRequestType getByType(int type) { for (TxnMapRequestType requestType : values()) { if (requestType.type == type) { return requestType; } } return null; } }
0true
hazelcast_src_main_java_com_hazelcast_map_client_AbstractTxnMapRequest.java
1,716
runnable = new Runnable() { public void run() { map.putAll(mapWithNullKey); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
225
public class TestCommandMode { @Test public void shouldInferCorrectModes() throws Exception { assertThat( fromRecordState( /* create */true, /* inUse */true ), equalTo(Command.Mode.CREATE)); assertThat( fromRecordState( /* create */false, /* inUse */true ), equalTo(Command.Mode.UPDATE)); assertThat( fromRecordState( /* create */false, /* inUse */false ), equalTo(Command.Mode.DELETE)); assertThat( fromRecordState( /* create */true, /* inUse */false ), equalTo(Command.Mode.DELETE)); } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_TestCommandMode.java
2,728
static class DanglingIndex { public final String index; public final ScheduledFuture future; DanglingIndex(String index, ScheduledFuture future) { this.index = index; this.future = future; } }
0true
src_main_java_org_elasticsearch_gateway_local_state_meta_LocalGatewayMetaState.java
1,114
public class RequiredAttributeNotProvidedException extends RuntimeException { private static final long serialVersionUID = 1L; public RequiredAttributeNotProvidedException() { super(); } public RequiredAttributeNotProvidedException(String message, Throwable cause) { super(message, cause); } public RequiredAttributeNotProvidedException(String message) { super(message); } public RequiredAttributeNotProvidedException(Throwable cause) { super(cause); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_exception_RequiredAttributeNotProvidedException.java
1,532
@Service("blHeadProcessorExtensionManager") public class HeadProcessorExtensionManager implements HeadProcessorExtensionListener { protected List<HeadProcessorExtensionListener> listeners; @Override public void processAttributeValues(Arguments arguments, Element element) { if(listeners == null) { listeners = new ArrayList<HeadProcessorExtensionListener>(); } for(HeadProcessorExtensionListener listener : listeners){ listener.processAttributeValues(arguments, element); } } public List<HeadProcessorExtensionListener> getListeners() { return listeners; } public void setListeners(List<HeadProcessorExtensionListener> listeners) { this.listeners = listeners; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_extension_HeadProcessorExtensionManager.java
2,938
public class SnowballTokenFilterFactory extends AbstractTokenFilterFactory { private String language; @Inject public SnowballTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); this.language = Strings.capitalize(settings.get("language", settings.get("name", "English"))); } @Override public TokenStream create(TokenStream tokenStream) { return new SnowballFilter(tokenStream, language); } }
0true
src_main_java_org_elasticsearch_index_analysis_SnowballTokenFilterFactory.java
432
return new EventHandler<ReplicatedMapPortableEntryEvent>() { public void handle(ReplicatedMapPortableEntryEvent event) { V value = (V) event.getValue(); V oldValue = (V) event.getOldValue(); K key = (K) event.getKey(); Member member = getContext().getClusterService().getMember(event.getUuid()); EntryEvent<K, V> entryEvent = new EntryEvent<K, V>(getName(), member, event.getEventType().getType(), key, oldValue, value); switch (event.getEventType()) { case ADDED: listener.entryAdded(entryEvent); break; case REMOVED: listener.entryRemoved(entryEvent); break; case UPDATED: listener.entryUpdated(entryEvent); break; case EVICTED: listener.entryEvicted(entryEvent); break; default: throw new IllegalArgumentException("Not a known event type " + event.getEventType()); } } @Override public void onListenerRegister() { } };
0true
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientReplicatedMapProxy.java
1,585
public interface LoggerFactory { ILogger getLogger(String name); }
0true
hazelcast_src_main_java_com_hazelcast_logging_LoggerFactory.java
3,448
public class FsSnapshotLock implements SnapshotLock { private final Lock lock; public FsSnapshotLock(Lock lock) { this.lock = lock; } @Override public void release() { try { lock.release(); } catch (IOException e) { logger.warn("failed to release snapshot lock [{}]", e, lock); } } }
1no label
src_main_java_org_elasticsearch_index_gateway_fs_FsIndexShardGateway.java
959
public interface OrderItemDao { OrderItem readOrderItemById(Long orderItemId); OrderItem save(OrderItem orderItem); void delete(OrderItem orderItem); OrderItem create(OrderItemType orderItemType); OrderItem saveOrderItem(OrderItem orderItem); PersonalMessage createPersonalMessage(); OrderItemPriceDetail createOrderItemPriceDetail(); OrderItemQualifier createOrderItemQualifier(); /** * Sets the initial orderItemPriceDetail for the item. */ OrderItemPriceDetail initializeOrderItemPriceDetails(OrderItem item); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_dao_OrderItemDao.java
45
@Component("blPendingSandBoxItemCustomPersistenceHandler") public class PendingSandBoxItemCustomPersistenceHandler extends SandBoxItemCustomPersistenceHandler { private final Log LOG = LogFactory.getLog(PendingSandBoxItemCustomPersistenceHandler.class); @Override public Boolean canHandleFetch(PersistencePackage persistencePackage) { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); boolean isSandboxItem = SandBoxItem.class.getName().equals(ceilingEntityFullyQualifiedClassname); if (isSandboxItem) { return persistencePackage.getCustomCriteria()[4].equals("pending"); } return false; } @Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); String[] customCriteria = persistencePackage.getCustomCriteria(); if (ArrayUtils.isEmpty(customCriteria) || customCriteria.length != 5) { ServiceException e = new ServiceException("Invalid request for entity: " + ceilingEntityFullyQualifiedClassname); LOG.error("Invalid request for entity: " + ceilingEntityFullyQualifiedClassname, e); throw e; } AdminUser adminUser = adminRemoteSecurityService.getPersistentAdminUser(); if (adminUser == null) { ServiceException e = new ServiceException("Unable to determine current user logged in status"); throw e; } try { String operation = customCriteria[1]; List<Long> targets = new ArrayList<Long>(); if (!StringUtils.isEmpty(customCriteria[2])) { String[] parts = customCriteria[2].split(","); for (String part : parts) { try { targets.add(Long.valueOf(part)); } catch (NumberFormatException e) { //do nothing } } } String requiredPermission = "PERMISSION_ALL_USER_SANDBOX"; boolean allowOperation = false; for (AdminRole role : adminUser.getAllRoles()) { for (AdminPermission permission : role.getAllPermissions()) { if (permission.getName().equals(requiredPermission)) { allowOperation = true; break; } } } if (!allowOperation) { ServiceException e = new ServiceException("Current user does not have permission to perform operation"); LOG.error("Current user does not have permission to perform operation", e); throw e; } SandBox mySandBox = sandBoxService.retrieveUserSandBox(null, adminUser); SandBox approvalSandBox = sandBoxService.retrieveApprovalSandBox(mySandBox); if (operation.equals("releaseAll")) { sandBoxService.revertAllSandBoxItems(mySandBox, approvalSandBox); } else if (operation.equals("releaseSelected")) { List<SandBoxItem> items = retrieveSandBoxItems(targets, dynamicEntityDao, mySandBox); sandBoxService.revertSelectedSandBoxItems(approvalSandBox, items); } else if (operation.equals("reclaimAll")) { sandBoxService.rejectAllSandBoxItems(mySandBox, approvalSandBox, "reclaiming sandbox items"); } else if (operation.equals("reclaimSelected")) { List<SandBoxItem> items = retrieveSandBoxItems(targets, dynamicEntityDao, mySandBox); sandBoxService.rejectSelectedSandBoxItems(approvalSandBox, "reclaiming sandbox item", items); } PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(SandBoxItem.class.getName(), persistencePerspective); cto.get("originalSandBoxId").setFilterValue(mySandBox.getId().toString()); cto.get("archivedFlag").setFilterValue(Boolean.FALSE.toString()); List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto, SandBoxItem.class.getName(), originalProps); List<Serializable> records = helper.getPersistentRecords(SandBoxItem.class.getName(), filterMappings, cto.getFirstResult(), cto.getMaxResults()); Entity[] results = helper.getRecords(originalProps, records); int totalRecords = helper.getTotalRecords(StringUtils.isEmpty(persistencePackage.getFetchTypeFullyQualifiedClassname())? persistencePackage.getCeilingEntityFullyQualifiedClassname():persistencePackage.getFetchTypeFullyQualifiedClassname(), filterMappings); DynamicResultSet response = new DynamicResultSet(results, totalRecords); return response; } catch (Exception e) { throw new ServiceException("Unable to execute persistence activity for entity: "+ceilingEntityFullyQualifiedClassname, e); } } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_admin_server_handler_PendingSandBoxItemCustomPersistenceHandler.java
3,440
public abstract class BlobStoreIndexGateway extends AbstractIndexComponent implements IndexGateway { private final BlobStoreGateway gateway; private final BlobStore blobStore; private final BlobPath indexPath; protected ByteSizeValue chunkSize; protected BlobStoreIndexGateway(Index index, @IndexSettings Settings indexSettings, Gateway gateway) { super(index, indexSettings); if (gateway.type().equals(NoneGateway.TYPE)) { logger.warn("index gateway is configured, but no cluster level gateway configured, cluster level metadata will be lost on full shutdown"); } this.gateway = (BlobStoreGateway) gateway; this.blobStore = this.gateway.blobStore(); this.chunkSize = componentSettings.getAsBytesSize("chunk_size", this.gateway.chunkSize()); this.indexPath = this.gateway.basePath().add("indices").add(index.name()); } @Override public String toString() { return type() + "://" + blobStore + "/" + indexPath; } public BlobStore blobStore() { return blobStore; } public ByteSizeValue chunkSize() { return this.chunkSize; } public BlobPath shardPath(int shardId) { return indexPath.add(Integer.toString(shardId)); } public static BlobPath shardPath(BlobPath basePath, String index, int shardId) { return basePath.add("indices").add(index).add(Integer.toString(shardId)); } @Override public void close() throws ElasticsearchException { } }
0true
src_main_java_org_elasticsearch_index_gateway_blobstore_BlobStoreIndexGateway.java
907
new Thread(new Runnable() { public void run() { try { lock.lock(); if (lock.isLockedByCurrentThread()) { count.incrementAndGet(); } awaitLatch.countDown(); condition.await(); if (lock.isLockedByCurrentThread()) { count.incrementAndGet(); } } catch (InterruptedException ignored) { } finally { lock.unlock(); finalLatch.countDown(); } } }).start();
0true
hazelcast_src_test_java_com_hazelcast_concurrent_lock_ConditionTest.java
1,206
floatIntMap = build(type, limit, smartSize, availableProcessors, new Recycler.C<FloatIntOpenHashMap>() { @Override public FloatIntOpenHashMap newInstance(int sizing) { return new FloatIntOpenHashMap(size(sizing)); } @Override public void clear(FloatIntOpenHashMap value) { value.clear(); } });
0true
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java
189
public class ClientConfig { /** * To pass properties */ private Properties properties = new Properties(); /** * The Group Configuration properties like: * Name and Password that is used to connect to the cluster. */ private GroupConfig groupConfig = new GroupConfig(); /** * The Security Configuration for custom Credentials: * Name and Password that is used to connect to the cluster. */ private ClientSecurityConfig securityConfig = new ClientSecurityConfig(); /** * The Network Configuration properties like: * addresses to connect, smart-routing, socket-options... */ private ClientNetworkConfig networkConfig = new ClientNetworkConfig(); /** * Used to distribute the operations to multiple Endpoints. */ private LoadBalancer loadBalancer; /** * List of listeners that Hazelcast will automatically add as a part of initialization process. * Currently only supports {@link com.hazelcast.core.LifecycleListener}. */ private List<ListenerConfig> listenerConfigs = new LinkedList<ListenerConfig>(); /** * pool-size for internal ExecutorService which handles responses etc. */ private int executorPoolSize = -1; private SerializationConfig serializationConfig = new SerializationConfig(); private List<ProxyFactoryConfig> proxyFactoryConfigs = new LinkedList<ProxyFactoryConfig>(); private ManagedContext managedContext; private ClassLoader classLoader; public String getProperty(String name) { String value = properties.getProperty(name); return value != null ? value : System.getProperty(name); } public ClientConfig setProperty(String name, String value) { properties.put(name, value); return this; } public Properties getProperties() { return properties; } private Map<String, NearCacheConfig> nearCacheConfigMap = new HashMap<String, NearCacheConfig>(); public ClientConfig setProperties(final Properties properties) { this.properties = properties; return this; } public ClientSecurityConfig getSecurityConfig() { return securityConfig; } public void setSecurityConfig(ClientSecurityConfig securityConfig) { this.securityConfig = securityConfig; } public ClientNetworkConfig getNetworkConfig() { return networkConfig; } public void setNetworkConfig(ClientNetworkConfig networkConfig) { this.networkConfig = networkConfig; } /** * please use {@link ClientConfig#addNearCacheConfig(NearCacheConfig)} * * @param mapName * @param nearCacheConfig * @return */ @Deprecated public ClientConfig addNearCacheConfig(String mapName, NearCacheConfig nearCacheConfig) { nearCacheConfig.setName(mapName); return addNearCacheConfig(nearCacheConfig); } public ClientConfig addNearCacheConfig(NearCacheConfig nearCacheConfig) { nearCacheConfigMap.put(nearCacheConfig.getName(), nearCacheConfig); return this; } public ClientConfig addListenerConfig(ListenerConfig listenerConfig) { getListenerConfigs().add(listenerConfig); return this; } public ClientConfig addProxyFactoryConfig(ProxyFactoryConfig proxyFactoryConfig) { this.proxyFactoryConfigs.add(proxyFactoryConfig); return this; } public NearCacheConfig getNearCacheConfig(String mapName) { return lookupByPattern(nearCacheConfigMap, mapName); } public Map<String, NearCacheConfig> getNearCacheConfigMap() { return nearCacheConfigMap; } public ClientConfig setNearCacheConfigMap(Map<String, NearCacheConfig> nearCacheConfigMap) { this.nearCacheConfigMap = nearCacheConfigMap; return this; } /** * Use {@link ClientNetworkConfig#isSmartRouting} instead */ @Deprecated public boolean isSmartRouting() { return networkConfig.isSmartRouting(); } /** * Use {@link ClientNetworkConfig#setSmartRouting} instead */ @Deprecated public ClientConfig setSmartRouting(boolean smartRouting) { networkConfig.setSmartRouting(smartRouting); return this; } /** * Use {@link ClientNetworkConfig#getSocketInterceptorConfig} instead */ @Deprecated public SocketInterceptorConfig getSocketInterceptorConfig() { return networkConfig.getSocketInterceptorConfig(); } /** * Use {@link ClientNetworkConfig#setSocketInterceptorConfig} instead */ @Deprecated public ClientConfig setSocketInterceptorConfig(SocketInterceptorConfig socketInterceptorConfig) { networkConfig.setSocketInterceptorConfig(socketInterceptorConfig); return this; } /** * Use {@link ClientNetworkConfig#getConnectionAttemptPeriod} instead */ @Deprecated public int getConnectionAttemptPeriod() { return networkConfig.getConnectionAttemptPeriod(); } /** * Use {@link ClientNetworkConfig#setConnectionAttemptPeriod} instead */ @Deprecated public ClientConfig setConnectionAttemptPeriod(int connectionAttemptPeriod) { networkConfig.setConnectionAttemptPeriod(connectionAttemptPeriod); return this; } /** * Use {@link ClientNetworkConfig#getConnectionAttemptLimit} instead */ @Deprecated public int getConnectionAttemptLimit() { return networkConfig.getConnectionAttemptLimit(); } /** * Use {@link ClientNetworkConfig#setConnectionAttemptLimit} instead */ @Deprecated public ClientConfig setConnectionAttemptLimit(int connectionAttemptLimit) { networkConfig.setConnectionAttemptLimit(connectionAttemptLimit); return this; } /** * Use {@link ClientNetworkConfig#getConnectionTimeout} instead */ @Deprecated public int getConnectionTimeout() { return networkConfig.getConnectionTimeout(); } /** * Use {@link ClientNetworkConfig#setConnectionTimeout} instead */ @Deprecated public ClientConfig setConnectionTimeout(int connectionTimeout) { networkConfig.setConnectionTimeout(connectionTimeout); return this; } public Credentials getCredentials() { return securityConfig.getCredentials(); } public ClientConfig setCredentials(Credentials credentials) { securityConfig.setCredentials(credentials); return this; } /** * Use {@link ClientNetworkConfig#addAddress} instead */ @Deprecated public ClientConfig addAddress(String... addresses) { networkConfig.addAddress(addresses); return this; } /** * Use {@link ClientNetworkConfig#setAddresses} instead */ @Deprecated public ClientConfig setAddresses(List<String> addresses) { networkConfig.setAddresses(addresses); return this; } /** * Use {@link ClientNetworkConfig#getAddresses} instead */ @Deprecated public List<String> getAddresses() { return networkConfig.getAddresses(); } public GroupConfig getGroupConfig() { return groupConfig; } public ClientConfig setGroupConfig(GroupConfig groupConfig) { this.groupConfig = groupConfig; return this; } public List<ListenerConfig> getListenerConfigs() { return listenerConfigs; } public ClientConfig setListenerConfigs(List<ListenerConfig> listenerConfigs) { this.listenerConfigs = listenerConfigs; return this; } public LoadBalancer getLoadBalancer() { return loadBalancer; } public ClientConfig setLoadBalancer(LoadBalancer loadBalancer) { this.loadBalancer = loadBalancer; return this; } /** * Use {@link ClientNetworkConfig#isRedoOperation} instead */ @Deprecated public boolean isRedoOperation() { return networkConfig.isRedoOperation(); } /** * Use {@link ClientNetworkConfig#setRedoOperation} instead */ @Deprecated public ClientConfig setRedoOperation(boolean redoOperation) { networkConfig.setRedoOperation(redoOperation); return this; } /** * Use {@link ClientNetworkConfig#getSocketOptions} instead */ @Deprecated public SocketOptions getSocketOptions() { return networkConfig.getSocketOptions(); } /** * Use {@link ClientNetworkConfig#setSocketOptions} instead */ @Deprecated public ClientConfig setSocketOptions(SocketOptions socketOptions) { networkConfig.setSocketOptions(socketOptions); return this; } public ClassLoader getClassLoader() { return classLoader; } public ClientConfig setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } public ManagedContext getManagedContext() { return managedContext; } public ClientConfig setManagedContext(ManagedContext managedContext) { this.managedContext = managedContext; return this; } public int getExecutorPoolSize() { return executorPoolSize; } public ClientConfig setExecutorPoolSize(int executorPoolSize) { this.executorPoolSize = executorPoolSize; return this; } public List<ProxyFactoryConfig> getProxyFactoryConfigs() { return proxyFactoryConfigs; } public ClientConfig setProxyFactoryConfigs(List<ProxyFactoryConfig> proxyFactoryConfigs) { this.proxyFactoryConfigs = proxyFactoryConfigs; return this; } public SerializationConfig getSerializationConfig() { return serializationConfig; } public ClientConfig setSerializationConfig(SerializationConfig serializationConfig) { this.serializationConfig = serializationConfig; return this; } private static <T> T lookupByPattern(Map<String, T> map, String name) { T t = map.get(name); if (t == null) { int lastMatchingPoint = -1; for (Map.Entry<String, T> entry : map.entrySet()) { String pattern = entry.getKey(); T value = entry.getValue(); final int matchingPoint = getMatchingPoint(name, pattern); if (matchingPoint > lastMatchingPoint) { lastMatchingPoint = matchingPoint; t = value; } } } return t; } /** * higher values means more specific matching * * @param name * @param pattern * @return -1 if name does not match at all, zero or positive otherwise */ private static int getMatchingPoint(final String name, final String pattern) { final int index = pattern.indexOf('*'); if (index == -1) { return -1; } final String firstPart = pattern.substring(0, index); final int indexFirstPart = name.indexOf(firstPart, 0); if (indexFirstPart == -1) { return -1; } final String secondPart = pattern.substring(index + 1); final int indexSecondPart = name.indexOf(secondPart, index + 1); if (indexSecondPart == -1) { return -1; } return firstPart.length() + secondPart.length(); } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_config_ClientConfig.java
1,395
@SuppressWarnings("serial") public class OMVRBTreeStorage<K, V> extends OMVRBTreePersistent<K, V> { public OMVRBTreeStorage(OMVRBTreeProvider<K, V> iProvider) { super(iProvider); } public OMVRBTreeStorage(final OStorageLocalAbstract iStorage, final String iClusterName, final ORID iRID) { super(new OMVRBTreeMapProvider<K, V>(iStorage, iClusterName, iRID)); } public OMVRBTreeStorage(final OStorageLocalAbstract iStorage, String iClusterName, final OBinarySerializer<K> iKeySerializer, final OStreamSerializer iValueSerializer) { super(new OMVRBTreeMapProvider<K, V>(iStorage, iClusterName, iKeySerializer, iValueSerializer)); } }
0true
core_src_main_java_com_orientechnologies_orient_core_type_tree_OMVRBTreeStorage.java
1,556
public interface Processor { public boolean supports(Activity<? extends ProcessContext> activity); public ProcessContext doActivities() throws WorkflowException; public ProcessContext doActivities(Object seedData) throws WorkflowException; public void setActivities(List<Activity<ProcessContext>> activities); public void setDefaultErrorHandler(ErrorHandler defaultErrorHandler); public void setProcessContextFactory(ProcessContextFactory processContextFactory); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_workflow_Processor.java
998
public static class Name { public static final String Pricing = "FulfillmentGroupImpl_Pricing"; }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_FulfillmentGroupImpl.java
2,189
public final class MatchNoDocsQuery extends Query { /** * Weight implementation that matches no documents. */ private class MatchNoDocsWeight extends Weight { @Override public String toString() { return "weight(" + MatchNoDocsQuery.this + ")"; } @Override public Query getQuery() { return MatchNoDocsQuery.this; } @Override public float getValueForNormalization() throws IOException { return 0; } @Override public void normalize(float norm, float topLevelBoost) { } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { return null; } @Override public Explanation explain(final AtomicReaderContext context, final int doc) { return new ComplexExplanation(false, 0, "MatchNoDocs matches nothing"); } } @Override public Weight createWeight(IndexSearcher searcher) throws IOException { return new MatchNoDocsWeight(); } @Override public void extractTerms(final Set<Term> terms) { } @Override public String toString(final String field) { return "MatchNoDocsQuery"; } @Override public boolean equals(final Object o) { if (o instanceof MatchNoDocsQuery) { return getBoost() == ((MatchNoDocsQuery) o).getBoost(); } return false; } @Override public int hashCode() { return getClass().hashCode() ^ Float.floatToIntBits(getBoost()); } }
0true
src_main_java_org_elasticsearch_common_lucene_search_MatchNoDocsQuery.java
1,578
public class BatchDynamicResultSet implements Serializable { protected DynamicResultSet[] dynamicResultSets; public DynamicResultSet[] getDynamicResultSets() { return dynamicResultSets; } public void setDynamicResultSets(DynamicResultSet[] dynamicResultSets) { this.dynamicResultSets = dynamicResultSets; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_BatchDynamicResultSet.java
121
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }});
0true
src_main_java_jsr166e_ForkJoinTask.java
5,572
public class GeoDistanceFacetParser extends AbstractComponent implements FacetParser { @Inject public GeoDistanceFacetParser(Settings settings) { super(settings); InternalGeoDistanceFacet.registerStreams(); } @Override public String[] types() { return new String[]{GeoDistanceFacet.TYPE, "geoDistance"}; } @Override public FacetExecutor.Mode defaultMainMode() { return FacetExecutor.Mode.COLLECTOR; } @Override public FacetExecutor.Mode defaultGlobalMode() { return FacetExecutor.Mode.COLLECTOR; } @Override public FacetExecutor parse(String facetName, XContentParser parser, SearchContext context) throws IOException { String fieldName = null; String valueFieldName = null; String valueScript = null; String scriptLang = null; Map<String, Object> params = null; GeoPoint point = new GeoPoint(); DistanceUnit unit = DistanceUnit.DEFAULT; GeoDistance geoDistance = GeoDistance.DEFAULT; List<GeoDistanceFacet.Entry> entries = Lists.newArrayList(); boolean normalizeLon = true; boolean normalizeLat = true; XContentParser.Token token; String currentName = parser.currentName(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if ("ranges".equals(currentName) || "entries".equals(currentName)) { // "ranges" : [ // { "from" : 0, "to" : 12.5 } // { "from" : 12.5 } // ] while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { double from = Double.NEGATIVE_INFINITY; double to = Double.POSITIVE_INFINITY; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentName = parser.currentName(); } else if (token.isValue()) { if ("from".equals(currentName)) { from = parser.doubleValue(); } else if ("to".equals(currentName)) { to = parser.doubleValue(); } } } entries.add(new GeoDistanceFacet.Entry(from, to, 0, 0, 0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)); } } else { GeoPoint.parse(parser, point); fieldName = currentName; } } else if (token == XContentParser.Token.START_OBJECT) { if ("params".equals(currentName)) { params = parser.map(); } else { // the json in the format of -> field : { lat : 30, lon : 12 } fieldName = currentName; GeoPoint.parse(parser, point); } } else if (token.isValue()) { if (currentName.equals("unit")) { unit = DistanceUnit.fromString(parser.text()); } else if (currentName.equals("distance_type") || currentName.equals("distanceType")) { geoDistance = GeoDistance.fromString(parser.text()); } else if ("value_field".equals(currentName) || "valueField".equals(currentName)) { valueFieldName = parser.text(); } else if ("value_script".equals(currentName) || "valueScript".equals(currentName)) { valueScript = parser.text(); } else if ("lang".equals(currentName)) { scriptLang = parser.text(); } else if ("normalize".equals(currentName)) { normalizeLat = parser.booleanValue(); normalizeLon = parser.booleanValue(); } else { // assume the value is the actual value point.resetFromString(parser.text()); fieldName = currentName; } } } if (entries.isEmpty()) { throw new FacetPhaseExecutionException(facetName, "no ranges defined for geo_distance facet"); } if (normalizeLat || normalizeLon) { GeoUtils.normalizePoint(point, normalizeLat, normalizeLon); } FieldMapper keyFieldMapper = context.smartNameFieldMapper(fieldName); if (keyFieldMapper == null) { throw new FacetPhaseExecutionException(facetName, "failed to find mapping for [" + fieldName + "]"); } IndexGeoPointFieldData keyIndexFieldData = context.fieldData().getForField(keyFieldMapper); if (valueFieldName != null) { FieldMapper valueFieldMapper = context.smartNameFieldMapper(valueFieldName); if (valueFieldMapper == null) { throw new FacetPhaseExecutionException(facetName, "failed to find mapping for [" + valueFieldName + "]"); } IndexNumericFieldData valueIndexFieldData = context.fieldData().getForField(valueFieldMapper); return new ValueGeoDistanceFacetExecutor(keyIndexFieldData, point.lat(), point.lon(), unit, geoDistance, entries.toArray(new GeoDistanceFacet.Entry[entries.size()]), context, valueIndexFieldData); } if (valueScript != null) { return new ScriptGeoDistanceFacetExecutor(keyIndexFieldData, point.lat(), point.lon(), unit, geoDistance, entries.toArray(new GeoDistanceFacet.Entry[entries.size()]), context, scriptLang, valueScript, params); } return new GeoDistanceFacetExecutor(keyIndexFieldData, point.lat(), point.lon(), unit, geoDistance, entries.toArray(new GeoDistanceFacet.Entry[entries.size()]), context); } }
1no label
src_main_java_org_elasticsearch_search_facet_geodistance_GeoDistanceFacetParser.java
4,431
private class PeerRecoveryListener implements RecoveryTarget.RecoveryListener { private final StartRecoveryRequest request; private final ShardRouting shardRouting; private final IndexService indexService; private final IndexMetaData indexMetaData; private PeerRecoveryListener(StartRecoveryRequest request, ShardRouting shardRouting, IndexService indexService, IndexMetaData indexMetaData) { this.request = request; this.shardRouting = shardRouting; this.indexService = indexService; this.indexMetaData = indexMetaData; } @Override public void onRecoveryDone() { shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(), "after recovery (replica) from node [" + request.sourceNode() + "]"); } @Override public void onRetryRecovery(TimeValue retryAfter, RecoveryStatus recoveryStatus) { recoveryTarget.retryRecovery(request, recoveryStatus, PeerRecoveryListener.this); } @Override public void onIgnoreRecovery(boolean removeShard, String reason) { if (!removeShard) { return; } synchronized (mutex) { if (indexService.hasShard(shardRouting.shardId().id())) { if (logger.isDebugEnabled()) { logger.debug("[{}][{}] removing shard on ignored recovery, reason [{}]", shardRouting.index(), shardRouting.shardId().id(), reason); } try { indexService.removeShard(shardRouting.shardId().id(), "ignore recovery: " + reason); } catch (IndexShardMissingException e) { // the node got closed on us, ignore it } catch (Throwable e1) { logger.warn("[{}][{}] failed to delete shard after ignore recovery", e1, indexService.index().name(), shardRouting.shardId().id()); } } } } @Override public void onRecoveryFailure(RecoveryFailedException e, boolean sendShardFailure) { handleRecoveryFailure(indexService, indexMetaData, shardRouting, sendShardFailure, e); } }
1no label
src_main_java_org_elasticsearch_indices_cluster_IndicesClusterStateService.java
171
static final class Submitter { int seed; Submitter(int s) { seed = s; } }
0true
src_main_java_jsr166y_ForkJoinPool.java
224
public class CeylonSourceViewer extends ProjectionViewer { /** * Text operation code for requesting the outline for the current input. */ public static final int SHOW_OUTLINE= 51; /** * Text operation code for requesting the outline for the element at the current position. */ public static final int OPEN_STRUCTURE= 52; /** * Text operation code for requesting the hierarchy for the current input. */ public static final int SHOW_HIERARCHY= 53; /** * Text operation code for requesting the code for the current input. */ public static final int SHOW_DEFINITION= 56; /** * Text operation code for requesting the references for the current input. */ public static final int SHOW_REFERENCES= 59; /** * Text operation code for toggling the commenting of a selected range of text, or the current line. */ public static final int TOGGLE_COMMENT= 54; public static final int ADD_BLOCK_COMMENT= 57; public static final int REMOVE_BLOCK_COMMENT= 58; /** * Text operation code for toggling the display of "occurrences" of the * current selection, whatever that means to the current language. */ public static final int MARK_OCCURRENCES= 55; /** * Text operation code for correcting the indentation of the currently selected text. */ public static final int CORRECT_INDENTATION= 60; /** * Text operation code for requesting the hierarchy for the current input. */ public static final int SHOW_IN_HIERARCHY_VIEW= 70; private IInformationPresenter outlinePresenter; private IInformationPresenter structurePresenter; private IInformationPresenter hierarchyPresenter; private IInformationPresenter definitionPresenter; private IInformationPresenter referencesPresenter; private IAutoEditStrategy autoEditStrategy; private CeylonEditor editor; public CeylonSourceViewer(CeylonEditor ceylonEditor, Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) { super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles); this.editor = ceylonEditor; } public CeylonSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) { this(null, parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles); } public boolean canDoOperation(int operation) { switch(operation) { case SHOW_OUTLINE: return outlinePresenter!=null; case OPEN_STRUCTURE: return structurePresenter!=null; case SHOW_HIERARCHY: return hierarchyPresenter!=null; case SHOW_DEFINITION: return definitionPresenter!=null; case SHOW_REFERENCES: return referencesPresenter!=null; case SHOW_IN_HIERARCHY_VIEW: return true; case ADD_BLOCK_COMMENT: //TODO: check if something is selected! case REMOVE_BLOCK_COMMENT: //TODO: check if there is a block comment in the selection! case TOGGLE_COMMENT: return true; case CORRECT_INDENTATION: return autoEditStrategy!=null; } return super.canDoOperation(operation); } public void doOperation(int operation) { try { if (getTextWidget() == null) { super.doOperation(operation); return; } String selectedText = editor.getSelectionText(); Map<Declaration,String> imports = null; switch (operation) { case SHOW_OUTLINE: if (outlinePresenter!=null) outlinePresenter.showInformation(); return; case OPEN_STRUCTURE: if (structurePresenter!=null) structurePresenter.showInformation(); return; case SHOW_HIERARCHY: if (hierarchyPresenter!=null) hierarchyPresenter.showInformation(); return; case SHOW_DEFINITION: if (definitionPresenter!=null) definitionPresenter.showInformation(); return; case SHOW_REFERENCES: if (referencesPresenter!=null) referencesPresenter.showInformation(); return; case SHOW_IN_HIERARCHY_VIEW: showHierarchy(); return; case TOGGLE_COMMENT: doToggleComment(); return; case ADD_BLOCK_COMMENT: addBlockComment(); return; case REMOVE_BLOCK_COMMENT: removeBlockComment(); return; case CORRECT_INDENTATION: Point selectedRange = getSelectedRange(); doCorrectIndentation(selectedRange.x, selectedRange.y); return; case PASTE: if (localPaste()) return; break; case CUT: case COPY: imports = copyImports(); break; } super.doOperation(operation); switch (operation) { case CUT: case COPY: afterCopyCut(selectedText, imports); break; /*case PASTE: afterPaste(textWidget); break;*/ } } catch (Exception e) { //never propagate exceptions e.printStackTrace(); } } public void showHierarchy() throws PartInitException { showHierarchyView().focusOnSelection(editor); } private void afterCopyCut(String selection, Map<Declaration,String> imports) { if (imports!=null && !editor.isBlockSelectionModeEnabled()) { char c = editor.getSelectedNode() instanceof Tree.Literal ? '"' : '{'; Clipboard clipboard = new Clipboard(getTextWidget().getDisplay()); try { Object text = clipboard.getContents(TextTransfer.getInstance()); Object rtf = clipboard.getContents(RTFTransfer.getInstance()); try { Object[] data; Transfer[] dataTypes; if (rtf==null) { data = new Object[] { text, imports, c + selection }; dataTypes = new Transfer[] { TextTransfer.getInstance(), ImportsTransfer.INSTANCE, SourceTransfer.INSTANCE }; } else { data = new Object[] { text, rtf, imports, c + selection }; dataTypes = new Transfer[] { TextTransfer.getInstance(), RTFTransfer.getInstance(), ImportsTransfer.INSTANCE, SourceTransfer.INSTANCE }; } clipboard.setContents(data, dataTypes); } catch (SWTError e) { if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) { throw e; } e.printStackTrace(); } } finally { clipboard.dispose(); } } } private boolean localPaste() { if (!editor.isBlockSelectionModeEnabled()) { Clipboard clipboard = new Clipboard(getTextWidget().getDisplay()); try { String text = (String) clipboard.getContents(SourceTransfer.INSTANCE); boolean fromStringLiteral; if (text==null) { fromStringLiteral = false; text = (String) clipboard.getContents(TextTransfer.getInstance()); } else { fromStringLiteral = text.charAt(0)=='"'; text = text.substring(1); } if (text==null) { return false; } else { @SuppressWarnings({"unchecked", "rawtypes"}) Map<Declaration,String> imports = (Map) clipboard.getContents(ImportsTransfer.INSTANCE); IRegion selection = editor.getSelection(); int offset = selection.getOffset(); int length = selection.getLength(); int endOffset = offset+length; IDocument doc = this.getDocument(); DocumentRewriteSession rewriteSession= null; if (doc instanceof IDocumentExtension4) { rewriteSession = ((IDocumentExtension4) doc).startRewriteSession(SEQUENTIAL); } ANTLRStringStream stream = new NewlineFixingStringStream(doc.get()); CeylonLexer lexer = new CeylonLexer(stream); CommonTokenStream tokens = new CommonTokenStream(lexer); tokens.fill(); CommonToken token = getTokenStrictlyContainingOffset(offset, tokens.getTokens()); boolean quoted; boolean verbatim; if (token == null) { quoted = false; verbatim = false; } else { int tt = token.getType(); quoted = tt==CeylonLexer.STRING_LITERAL || tt==CeylonLexer.STRING_END || tt==CeylonLexer.STRING_END || tt==CeylonLexer.STRING_MID; verbatim = token.getText().startsWith("\"\"\""); } try { boolean startOfLine = false; try { int lineStart = doc.getLineInformationOfOffset(offset).getOffset(); startOfLine = doc.get(lineStart, offset-lineStart).trim().isEmpty(); } catch (BadLocationException e) { e.printStackTrace(); } try { MultiTextEdit edit = new MultiTextEdit(); if (!quoted && imports!=null) { pasteImports(imports, edit, text, doc); } if (quoted && !verbatim && !fromStringLiteral) { text = text .replace("\\", "\\\\") .replace("\t", "\\t") .replace("\"", "\\\"") .replace("`", "\\`"); } edit.addChild(new ReplaceEdit(offset, length, text)); edit.apply(doc); endOffset = edit.getRegion().getOffset()+edit.getRegion().getLength(); } catch (Exception e) { e.printStackTrace(); return false; } try { if (startOfLine && EditorsUI.getPreferenceStore().getBoolean(PASTE_CORRECT_INDENTATION)) { endOffset = correctSourceIndentation(endOffset-text.length(), text.length(), doc)+1; } return true; } catch (Exception e) { e.printStackTrace(); return true; } } finally { if (doc instanceof IDocumentExtension4) { ((IDocumentExtension4) doc).stopRewriteSession(rewriteSession); } setSelectedRange(endOffset, 0); } } } finally { clipboard.dispose(); } } else { return false; } } /*private void afterPaste(StyledText textWidget) { Clipboard clipboard= new Clipboard(textWidget.getDisplay()); try { List<Declaration> imports = (List<Declaration>) clipboard.getContents(ImportsTransfer.INSTANCE); if (imports!=null) { MultiTextEdit edit = new MultiTextEdit(); pasteImports(imports, edit); if (edit.hasChildren()) { try { edit.apply(getDocument()); } catch (Exception e) { e.printStackTrace(); } } } } finally { clipboard.dispose(); } }*/ private void addBlockComment() { IDocument doc = this.getDocument(); DocumentRewriteSession rewriteSession = null; Point p = this.getSelectedRange(); if (doc instanceof IDocumentExtension4) { rewriteSession= ((IDocumentExtension4) doc).startRewriteSession(SEQUENTIAL); } try { final int selStart = p.x; final int selLen = p.y; final int selEnd = selStart+selLen; doc.replace(selStart, 0, "/*"); doc.replace(selEnd+2, 0, "*/"); } catch (BadLocationException e) { e.printStackTrace(); } finally { if (doc instanceof IDocumentExtension4) { ((IDocumentExtension4) doc).stopRewriteSession(rewriteSession); } restoreSelection(); } } private void removeBlockComment() { IDocument doc = this.getDocument(); DocumentRewriteSession rewriteSession = null; Point p = this.getSelectedRange(); if (doc instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) doc; rewriteSession= extension.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL); } try { final int selStart = p.x; final int selLen = p.y; final int selEnd = selStart+selLen; String text = doc.get(); int open = text.indexOf("/*", selStart); if (open>selEnd) open = -1; if (open<0) { open = text.lastIndexOf("/*", selStart); } int close = -1; if (open>=0) { close = text.indexOf("*/", open); } if (close+2<selStart) close = -1; if (open>=0&&close>=0) { doc.replace(open, 2, ""); doc.replace(close-2, 2, ""); } } catch (BadLocationException e) { e.printStackTrace(); } finally { if (doc instanceof IDocumentExtension4) { ((IDocumentExtension4) doc).stopRewriteSession(rewriteSession); } restoreSelection(); } } private void doToggleComment() { IDocument doc = this.getDocument(); DocumentRewriteSession rewriteSession = null; Point p = this.getSelectedRange(); final String lineCommentPrefix = "//"; if (doc instanceof IDocumentExtension4) { rewriteSession= ((IDocumentExtension4) doc).startRewriteSession(SEQUENTIAL); } try { final int selStart = p.x; final int selLen = p.y; final int selEnd = selStart+selLen; final int startLine= doc.getLineOfOffset(selStart); int endLine= doc.getLineOfOffset(selEnd); if (selLen>0 && lookingAtLineEnd(doc, selEnd)) endLine--; boolean linesAllHaveCommentPrefix = linesHaveCommentPrefix(doc, lineCommentPrefix, startLine, endLine); boolean useCommonLeadingSpace = true; // take from a preference? int leadingSpaceToUse = useCommonLeadingSpace ? calculateLeadingSpace(doc, startLine, endLine) : 0; for(int line = startLine; line<=endLine; line++) { int lineStart = doc.getLineOffset(line); int lineEnd = lineStart+doc.getLineLength(line)-1; if (linesAllHaveCommentPrefix) { // remove the comment prefix from each line, wherever it occurs in the line int offset = lineStart; while (Character.isWhitespace(doc.getChar(offset)) && offset<lineEnd) { offset++; } // The first non-whitespace characters *must* be the single-line comment prefix doc.replace(offset, lineCommentPrefix.length(), ""); } else { // add the comment prefix to each line, after however many spaces leadingSpaceToAdd indicates int offset = lineStart+leadingSpaceToUse; doc.replace(offset, 0, lineCommentPrefix); } } } catch (BadLocationException e) { e.printStackTrace(); } finally { if (doc instanceof IDocumentExtension4) { ((IDocumentExtension4) doc).stopRewriteSession(rewriteSession); } restoreSelection(); } } private int calculateLeadingSpace(IDocument doc, int startLine, int endLine) { try { int result = Integer.MAX_VALUE; for(int line = startLine; line <= endLine; line++) { int lineStart = doc.getLineOffset(line); int lineEnd = lineStart + doc.getLineLength(line) - 1; int offset = lineStart; while (Character.isWhitespace(doc.getChar(offset)) && offset < lineEnd) { offset++; } int leadingSpaces = offset - lineStart; result = Math.min(result, leadingSpaces); } return result; } catch (BadLocationException e) { return 0; } } /** * @return true, if the given inclusive range of lines all start with the single-line comment prefix, * even if they have different amounts of leading whitespace */ private boolean linesHaveCommentPrefix(IDocument doc, String lineCommentPrefix, int startLine, int endLine) { try { int docLen= doc.getLength(); for(int line= startLine; line <= endLine; line++) { int lineStart= doc.getLineOffset(line); int lineEnd= lineStart + doc.getLineLength(line) - 1; int offset= lineStart; while (Character.isWhitespace(doc.getChar(offset)) && offset < lineEnd) { offset++; } if (docLen - offset > lineCommentPrefix.length() && doc.get(offset, lineCommentPrefix.length()).equals(lineCommentPrefix)) { // this line starts with the single-line comment prefix } else { return false; } } } catch (BadLocationException e) { return false; } return true; } private void doCorrectIndentation(int offset, int len) { IDocument doc = getDocument(); DocumentRewriteSession rewriteSession= null; if (doc instanceof IDocumentExtension4) { rewriteSession = ((IDocumentExtension4) doc).startRewriteSession(SEQUENTIAL); } Point selectedRange = getSelectedRange(); boolean emptySelection = selectedRange==null || selectedRange.y==0; try { correctSourceIndentation(offset, len, doc); } catch (BadLocationException e) { e.printStackTrace(); } finally { if (doc instanceof IDocumentExtension4) { ((IDocumentExtension4) doc).stopRewriteSession(rewriteSession); } restoreSelection(); if (emptySelection) { selectedRange = getSelectedRange(); setSelectedRange(selectedRange.x/*+selectedRange.y*/, 0); } } } public int correctSourceIndentation(int selStart, int selLen, IDocument doc) throws BadLocationException { int selEnd = selStart + selLen; int startLine = doc.getLineOfOffset(selStart); int endLine = doc.getLineOfOffset(selEnd); // If the selection extends just to the beginning of the next line, don't indent that one too if (selLen > 0 && lookingAtLineEnd(doc, selEnd)) { endLine--; } int endOffset = selStart+selLen-1; // Indent each line using the AutoEditStrategy for (int line=startLine; line<=endLine; line++) { int lineStartOffset = doc.getLineOffset(line); // Replace the existing indentation with the desired indentation. // Use the language-specific AutoEditStrategy, which requires a DocumentCommand. DocumentCommand cmd = new DocumentCommand() { }; cmd.offset = lineStartOffset; cmd.length = 0; cmd.text = Character.toString('\t'); cmd.doit = true; cmd.shiftsCaret = false; autoEditStrategy.customizeDocumentCommand(doc, cmd); if (cmd.text!=null) { doc.replace(cmd.offset, cmd.length, cmd.text); endOffset += cmd.text.length()-cmd.length; } } return endOffset; } private boolean lookingAtLineEnd(IDocument doc, int pos) { String[] legalLineTerms = doc.getLegalLineDelimiters(); try { for(String lineTerm: legalLineTerms) { int len = lineTerm.length(); if (pos>len && doc.get(pos-len,len).equals(lineTerm)) { return true; } } } catch (BadLocationException e) { e.printStackTrace(); } return false; } public void configure(SourceViewerConfiguration configuration) { /* * Prevent access to colors disposed in unconfigure(), see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=53641 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=86177 */ // StyledText textWidget = getTextWidget(); // if (textWidget != null && !textWidget.isDisposed()) { // Color foregroundColor = textWidget.getForeground(); // if (foregroundColor != null && foregroundColor.isDisposed()) { // textWidget.setForeground(null); // } // Color backgroundColor = textWidget.getBackground(); // if (backgroundColor != null && backgroundColor.isDisposed()) { // textWidget.setBackground(null); // } // } super.configure(configuration); AbstractInformationControlManager hoverController = getTextHoveringController(); if (hoverController!=null) { //null in a merge viewer hoverController.setSizeConstraints(80, 30, false, true); } if (configuration instanceof CeylonSourceViewerConfiguration) { CeylonSourceViewerConfiguration svc = (CeylonSourceViewerConfiguration) configuration; outlinePresenter = svc.getOutlinePresenter(this); if (outlinePresenter!=null) { outlinePresenter.install(this); } structurePresenter = svc.getOutlinePresenter(this); if (structurePresenter!=null) { structurePresenter.install(this); } hierarchyPresenter = svc.getHierarchyPresenter(this); if (hierarchyPresenter!=null) { hierarchyPresenter.install(this); } definitionPresenter = svc.getDefinitionPresenter(this); if (definitionPresenter!=null) { definitionPresenter.install(this); } referencesPresenter = svc.getReferencesPresenter(this); if (referencesPresenter!=null) { referencesPresenter.install(this); } autoEditStrategy = new CeylonAutoEditStrategy(); } // if (fPreferenceStore != null) { // fPreferenceStore.addPropertyChangeListener(this); // initializeViewerColors(); // } ITextHover textHover = configuration.getTextHover(this, DEFAULT_CONTENT_TYPE); if (textHover!=null) { setTextHover(textHover, DEFAULT_CONTENT_TYPE); } } public void unconfigure() { if (outlinePresenter != null) { outlinePresenter.uninstall(); outlinePresenter= null; } if (structurePresenter != null) { structurePresenter.uninstall(); structurePresenter= null; } if (hierarchyPresenter != null) { hierarchyPresenter.uninstall(); hierarchyPresenter= null; } // if (fForegroundColor != null) { // fForegroundColor.dispose(); // fForegroundColor= null; // } // if (fBackgroundColor != null) { // fBackgroundColor.dispose(); // fBackgroundColor= null; // } // if (fPreferenceStore != null) // fPreferenceStore.removePropertyChangeListener(this); super.unconfigure(); } Map<Declaration,String> copyImports() { try { CeylonParseController pc = editor.getParseController(); if (pc==null || pc.getRootNode()==null) return null; Tree.CompilationUnit cu = pc.getRootNode(); final IRegion selection = editor.getSelection(); class SelectedImportsVisitor extends Visitor { Map<Declaration,String> results = new HashMap<Declaration,String>(); boolean inSelection(Node node) { return node.getStartIndex()>=selection.getOffset() && node.getStopIndex()<selection.getOffset()+selection.getLength(); } void addDeclaration(Declaration d, Tree.Identifier id) { if (d!=null && id!=null && d.isToplevel()) { String pname = d.getUnit().getPackage().getNameAsString(); if (!pname.isEmpty() && !pname.equals(Module.LANGUAGE_MODULE_NAME)) { results.put(d, id.getText()); } } } @Override public void visit(Tree.BaseMemberOrTypeExpression that) { if (inSelection(that)) { addDeclaration(that.getDeclaration(), that.getIdentifier()); } super.visit(that); } @Override public void visit(Tree.BaseType that) { if (inSelection(that)) { addDeclaration(that.getDeclarationModel(), that.getIdentifier()); } super.visit(that); } @Override public void visit(Tree.MemberLiteral that) { if (inSelection(that) && that.getType()==null) { addDeclaration(that.getDeclaration(), that.getIdentifier()); } super.visit(that); } } SelectedImportsVisitor v = new SelectedImportsVisitor(); cu.visit(v); return v.results; } catch (Exception e) { e.printStackTrace(); return null; } } void pasteImports(Map<Declaration,String> map, MultiTextEdit edit, String pastedText, IDocument doc) { if (!map.isEmpty()) { CeylonParseController pc = editor.getParseController(); if (pc==null || pc.getRootNode()==null) return; Tree.CompilationUnit cu = pc.getRootNode(); Unit unit = cu.getUnit(); //copy them, so as to not affect the clipboard Map<Declaration,String> imports = new LinkedHashMap<Declaration,String>(); imports.putAll(map); for (Iterator<Map.Entry<Declaration,String>> i=imports.entrySet().iterator(); i.hasNext();) { Map.Entry<Declaration,String> e = i.next(); Declaration declaration = e.getKey(); Package declarationPackage = declaration.getUnit().getPackage(); Pattern pattern = Pattern.compile("\\bimport\\s+" + declarationPackage.getNameAsString().replace(".", "\\.") + "\\b[^.]"); if (unit.getPackage().equals(declarationPackage)) { //the declaration belongs to this package i.remove(); } else if (pattern.matcher(pastedText).find()) { //i.e. the pasted text probably already contains the import i.remove(); } else { for (Import ip: unit.getImports()) { //compare qualified names, treating //overloaded versions as identical if (ip.getDeclaration().getQualifiedNameString() .equals(declaration.getQualifiedNameString())) { i.remove(); break; } } } } if (!imports.isEmpty()) { List<InsertEdit> edits = importEdits(cu, imports.keySet(), imports.values(), null, doc); for (InsertEdit importEdit: edits) { edit.addChild(importEdit); } } } } public IPresentationReconciler getPresentationReconciler() { return fPresentationReconciler; } public ContentAssistant getContentAssistant() { return (ContentAssistant) fContentAssistant; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonSourceViewer.java
160
public interface StructuredContentService extends SandBoxItemListener { /** * Returns the StructuredContent item associated with the passed in id. * * @param contentId - The id of the content item. * @return The associated structured content item. */ public StructuredContent findStructuredContentById(Long contentId); /** * Returns the <code>StructuredContentType</code> associated with the passed in id. * * @param id - The id of the content type. * @return The associated <code>StructuredContentType</code>. */ public StructuredContentType findStructuredContentTypeById(Long id); /** * Returns the <code>StructuredContentType</code> associated with the passed in * String value. * * @param name - The name of the content type. * @return The associated <code>StructuredContentType</code>. */ public StructuredContentType findStructuredContentTypeByName(String name); /** * * @return a list of all <code>StructuredContentType</code>s */ public List<StructuredContentType> retrieveAllStructuredContentTypes(); /** * Returns the fields associated with the passed in contentId. * This is preferred over the direct access from the ContentItem so that the * two items can be cached distinctly * * @param contentId - The id of the content. * @return Map of fields for this content id */ public Map<String,StructuredContentField> findFieldsByContentId(Long contentId); /** * This method is intended to be called solely from the CMS admin. Similar methods * exist that are intended for other clients (e.g. lookupStructuredContentItemsBy.... * <br> * Returns content items for the passed in sandbox that match the passed in criteria. * The criteria acts as a where clause to be used in the search for content items. * Implementations should automatically add criteria such that no archived items * are returned from this method. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * * @param sandbox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param criteria - the criteria used to search for content * @return */ public List<StructuredContent> findContentItems(SandBox sandbox, Criteria criteria); /** * Finds all content items regardless of the {@link Sandbox} they are a member of * @return */ public List<StructuredContent> findAllContentItems(); /** * Follows the same rules as {@link #findContentItems(org.broadleafcommerce.common.sandbox.domain.SandBox, org.hibernate.Criteria) findContentItems}. * * @return the count of items in this sandbox that match the passed in Criteria */ public Long countContentItems(SandBox sandBox, Criteria c); /** * This method is intended to be called from within the CMS * admin only. * * Adds the passed in contentItem to the DB. * * Creates a sandbox/site if one doesn't already exist. */ public StructuredContent addStructuredContent(StructuredContent content, SandBox destinationSandbox); /** * This method is intended to be called from within the CMS * admin only. * * Updates the structuredContent according to the following rules: * * 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. * * Clone the item and add it to the new sandbox and set the cloned * item's originalItemId to the id of the item being updated. * * 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. * * Update the siteId for the item to the one associated with the * new sandbox * * 3. If the sandbox has changed from a value to null * This means that the item is moving from the sandbox to production. * * If the item has an originalItemId, then update that item by * setting it's archived flag to true. * * Then, update the siteId of the item being updated to be the * siteId of the original item. * * 4. If the sandbox is the same then just update the item. */ public StructuredContent updateStructuredContent(StructuredContent content, SandBox sandbox); /** * Saves the given <b>type</b> and returns the merged instance */ public StructuredContentType saveStructuredContentType(StructuredContentType type); /** * If deleting and item where content.originalItemId != null * then the item is deleted from the database. * * If the originalItemId is null, then this method marks * the items as deleted within the passed in sandbox. * * @param content * @param destinationSandbox * @return */ public void deleteStructuredContent(StructuredContent content, SandBox destinationSandbox); /** * This method returns content * <br> * Returns active content items for the passed in sandbox that match the passed in type. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * <br> * The secure item is used in cases where the structured content item contains an image path that needs * to be rewritten to use https. * * @param sandBox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param contentType - the type of content to return * @param count - the max number of content items to return * @param ruleDTOs - a Map of objects that will be used in MVEL processing. * @param secure - set to true if the request is being served over https * @return - The matching items * @see org.broadleafcommerce.cms.web.structure.DisplayContentTag */ public List<StructuredContentDTO> lookupStructuredContentItemsByType(SandBox sandBox, StructuredContentType contentType, Locale locale, Integer count, Map<String,Object> ruleDTOs, boolean secure); /** * This method returns content by name only. * <br> * Returns active content items for the passed in sandbox that match the passed in type. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * * @param sandBox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param contentName - the name of content to return * @param count - the max number of content items to return * @param ruleDTOs - a Map of objects that will be used in MVEL processing. * @param secure - set to true if the request is being served over https * @return - The matching items * @see org.broadleafcommerce.cms.web.structure.DisplayContentTag */ public List<StructuredContentDTO> lookupStructuredContentItemsByName(SandBox sandBox, String contentName, Locale locale, Integer count, Map<String,Object> ruleDTOs, boolean secure); /** * This method returns content by name and type. * <br> * Returns active content items for the passed in sandbox that match the passed in type. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * * @param sandBox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param contentType - the type of content to return * @param contentName - the name of content to return * @param count - the max number of content items to return * @param ruleDTOs - a Map of objects that will be used in MVEL processing. * @param secure - set to true if the request is being served over https * @return - The matching items * @see org.broadleafcommerce.cms.web.structure.DisplayContentTag */ public List<StructuredContentDTO> lookupStructuredContentItemsByName(SandBox sandBox, StructuredContentType contentType, String contentName, Locale locale, Integer count, Map<String,Object> ruleDTOs, boolean secure); /** * Removes the items from cache that match the passed in name and page keys. * @param nameKey - key for a specific content item * @param typeKey - key for a type of content item */ public void removeItemFromCache(String nameKey, String typeKey); public boolean isAutomaticallyApproveAndPromoteStructuredContent(); public void setAutomaticallyApproveAndPromoteStructuredContent(boolean automaticallyApproveAndPromoteStructuredContent); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_service_StructuredContentService.java
1,476
public abstract class OSQLFunctionMove extends OSQLFunctionConfigurableAbstract { public static final String NAME = "move"; public OSQLFunctionMove() { super(NAME, 1, 2); } public OSQLFunctionMove(final String iName, final int iMin, final int iMax) { super(iName, iMin, iMax); } protected abstract Object move(final OrientBaseGraph graph, final OIdentifiable iRecord, final String[] iLabels); public String getSyntax() { return "Syntax error: " + name + "([<labels>])"; } public Object execute(OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters, final OCommandContext iContext) { final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); final String[] labels; if (iParameters != null && iParameters.length > 0 && iParameters[0] != null) labels = OMultiValue.array(iParameters, String.class, new OCallable<Object, Object>() { @Override public Object call(final Object iArgument) { return OStringSerializerHelper.getStringContent(iArgument); } }); else labels = null; if (iCurrentRecord == null) { return OSQLEngine.foreachRecord(new OCallable<Object, OIdentifiable>() { @Override public Object call(final OIdentifiable iArgument) { return move(graph, iArgument, labels); } }, iCurrentResult, iContext); } else return move(graph, iCurrentRecord.getRecord(), labels); } protected Object v2v(final OrientBaseGraph graph, final OIdentifiable iRecord, final Direction iDirection, final String[] iLabels) { final ODocument rec = iRecord.getRecord(); if (rec.getSchemaClass() != null) if (rec.getSchemaClass().isSubClassOf(OrientVertex.CLASS_NAME)) { // VERTEX final OrientVertex vertex = graph.getVertex(rec); if (vertex != null) return vertex.getVertices(iDirection, iLabels); } return null; } protected Object v2e(final OrientBaseGraph graph, final OIdentifiable iRecord, final Direction iDirection, final String[] iLabels) { final ODocument rec = iRecord.getRecord(); if (rec.getSchemaClass() != null) if (rec.getSchemaClass().isSubClassOf(OrientVertex.CLASS_NAME)) { // VERTEX final OrientVertex vertex = graph.getVertex(rec); if (vertex != null) return vertex.getEdges(iDirection, iLabels); } return null; } protected Object e2v(final OrientBaseGraph graph, final OIdentifiable iRecord, final Direction iDirection, final String[] iLabels) { final ODocument rec = iRecord.getRecord(); if (rec.getSchemaClass() != null) if (rec.getSchemaClass().isSubClassOf(OrientEdge.CLASS_NAME)) { // EDGE final OrientEdge edge = graph.getEdge(rec); if (edge != null) { final OrientVertex out = (OrientVertex) edge.getVertex(iDirection); return out; } } return null; } }
1no label
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionMove.java
828
@Entity @Table(name = "BLC_ORDER_ADJUSTMENT") @Inheritance(strategy=InheritanceType.JOINED) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = "", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY, booleanOverrideValue = true)) } ) @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "OrderAdjustmentImpl_baseOrderAdjustment") public class OrderAdjustmentImpl implements OrderAdjustment, CurrencyCodeIdentifiable { public static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "OrderAdjustmentId") @GenericGenerator( name="OrderAdjustmentId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="OrderAdjustmentImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OrderAdjustmentImpl") } ) @Column(name = "ORDER_ADJUSTMENT_ID") protected Long id; @ManyToOne(targetEntity = OrderImpl.class) @JoinColumn(name = "ORDER_ID") @Index(name="ORDERADJUST_ORDER_INDEX", columnNames={"ORDER_ID"}) @AdminPresentation(excluded = true) protected Order order; @ManyToOne(targetEntity = OfferImpl.class, optional=false) @JoinColumn(name = "OFFER_ID") @Index(name="ORDERADJUST_OFFER_INDEX", columnNames={"OFFER_ID"}) @AdminPresentation(friendlyName = "OrderAdjustmentImpl_Offer", order=1000, prominent = true, gridOrder = 1000) @AdminPresentationToOneLookup() protected Offer offer; @Column(name = "ADJUSTMENT_REASON", nullable=false) @AdminPresentation(friendlyName = "OrderAdjustmentImpl_Order_Adjustment_Reason", order=2000) protected String reason; @Column(name = "ADJUSTMENT_VALUE", nullable=false, precision=19, scale=5) @AdminPresentation(friendlyName = "OrderAdjustmentImpl_Order_Adjustment_Value", order=3000, fieldType = SupportedFieldType.MONEY, prominent = true, gridOrder = 2000) protected BigDecimal value = Money.ZERO.getAmount(); @Override public void init(Order order, Offer offer, String reason){ this.order = order; this.offer = offer; this.reason = reason; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public Order getOrder() { return order; } @Override public void setOrder(Order order) { this.order = order; } @Override public Offer getOffer() { return offer; } public void setOffer(Offer offer) { this.offer = offer; } @Override public String getReason() { return reason; } @Override public void setReason(String reason) { this.reason = reason; } @Override public Money getValue() { return value == null ? null : BroadleafCurrencyUtils.getMoney(value, getOrder().getCurrency()); } @Override public void setValue(Money value) { this.value = value.getAmount(); } @Override public String getCurrencyCode() { if (order.getCurrency() != null) { return order.getCurrency().getCurrencyCode(); } return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((offer == null) ? 0 : offer.hashCode()); result = prime * result + ((order == null) ? 0 : order.hashCode()); result = prime * result + ((reason == null) ? 0 : reason.hashCode()); result = prime * result + ((value == null) ? 0 : value.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; } OrderAdjustmentImpl other = (OrderAdjustmentImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (offer == null) { if (other.offer != null) { return false; } } else if (!offer.equals(other.offer)) { return false; } if (order == null) { if (other.order != null) { return false; } } else if (!order.equals(other.order)) { return false; } if (reason == null) { if (other.reason != null) { return false; } } else if (!reason.equals(other.reason)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OrderAdjustmentImpl.java
320
public class NodesHotThreadsResponse extends NodesOperationResponse<NodeHotThreads> { NodesHotThreadsResponse() { } public NodesHotThreadsResponse(ClusterName clusterName, NodeHotThreads[] nodes) { super(clusterName, nodes); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); nodes = new NodeHotThreads[in.readVInt()]; for (int i = 0; i < nodes.length; i++) { nodes[i] = NodeHotThreads.readNodeHotThreads(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(nodes.length); for (NodeHotThreads node : nodes) { node.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_hotthreads_NodesHotThreadsResponse.java
335
public class NodesRestartRequest extends NodesOperationRequest<NodesRestartRequest> { TimeValue delay = TimeValue.timeValueSeconds(1); protected NodesRestartRequest() { } /** * Restarts down nodes based on the nodes ids specified. If none are passed, <b>all</b> * nodes will be shutdown. */ public NodesRestartRequest(String... nodesIds) { super(nodesIds); } /** * The delay for the restart to occur. Defaults to <tt>1s</tt>. */ public NodesRestartRequest delay(TimeValue delay) { this.delay = delay; return this; } /** * The delay for the restart to occur. Defaults to <tt>1s</tt>. */ public NodesRestartRequest delay(String delay) { return delay(TimeValue.parseTimeValue(delay, null)); } public TimeValue delay() { return this.delay; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); delay = readTimeValue(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); delay.writeTo(out); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_restart_NodesRestartRequest.java
1,471
public class PlainShardIterator extends PlainShardsIterator implements ShardIterator { private final ShardId shardId; /** * Creates a {@link PlainShardIterator} instance that iterates over a subset of the given shards * this the a given <code>shardId</code>. * * @param shardId shard id of the group * @param shards shards to iterate */ public PlainShardIterator(ShardId shardId, List<ShardRouting> shards) { super(shards); this.shardId = shardId; } /** * Creates a {@link PlainShardIterator} instance that iterates over a subset of the given shards * this the a given <code>shardId</code>. * * @param shardId shard id of the group * @param shards shards to iterate * @param index the offset in the shards list to start the iteration from */ public PlainShardIterator(ShardId shardId, List<ShardRouting> shards, int index) { super(shards, index); this.shardId = shardId; } @Override public ShardId shardId() { return this.shardId; } @Override public boolean equals(Object o) { if (this == o) return true; ShardIterator that = (ShardIterator) o; return shardId.equals(that.shardId()); } @Override public int hashCode() { return shardId.hashCode(); } }
1no label
src_main_java_org_elasticsearch_cluster_routing_PlainShardIterator.java
1,155
iMethodParams = OMultiValue.array(iMethodParams, Object.class, new OCallable<Object, Object>() { @Override public Object call(final Object iArgument) { if (iArgument instanceof String && ((String) iArgument).startsWith("$")) return iContext.getVariable((String) iArgument); return iArgument; } });
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodRemoveAll.java
771
public class CollectionPrepareBackupOperation extends CollectionOperation implements BackupOperation { long itemId; boolean removeOperation; String transactionId; public CollectionPrepareBackupOperation() { } public CollectionPrepareBackupOperation(String name, long itemId, String transactionId, boolean removeOperation) { super(name); this.itemId = itemId; this.removeOperation = removeOperation; this.transactionId = transactionId; } @Override public int getId() { return CollectionDataSerializerHook.COLLECTION_PREPARE_BACKUP; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { if (removeOperation) { getOrCreateContainer().reserveRemoveBackup(itemId, transactionId); } else { getOrCreateContainer().reserveAddBackup(itemId, transactionId); } } @Override public void afterRun() throws Exception { } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(itemId); out.writeBoolean(removeOperation); out.writeUTF(transactionId); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); itemId = in.readLong(); removeOperation = in.readBoolean(); transactionId = in.readUTF(); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_txn_CollectionPrepareBackupOperation.java
33
public class ThriftBlueprintsTest extends AbstractCassandraBlueprintsTest { @Override public void beforeSuite() { CassandraStorageSetup.startCleanEmbedded(); } @Override protected WriteConfiguration getGraphConfig() { return CassandraStorageSetup.getCassandraGraphConfiguration(getClass().getSimpleName()); } @Override public void extraCleanUp(String uid) throws BackendException { ModifiableConfiguration mc = new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS, getGraphConfig(), Restriction.NONE); StoreManager m = new CassandraThriftStoreManager(mc); m.clearStorage(); m.close(); } }
0true
titan-cassandra_src_test_java_com_thinkaurelius_titan_blueprints_ThriftBlueprintsTest.java
570
public class BigDecimalRoundingAdapter extends XmlAdapter<String, BigDecimal> { @Override public BigDecimal unmarshal(String s) throws Exception { return new BigDecimal(s); } @Override public String marshal(BigDecimal bigDecimal) throws Exception { return bigDecimal.setScale(2, RoundingMode.UP).toString(); } }
0true
common_src_main_java_org_broadleafcommerce_common_util_xml_BigDecimalRoundingAdapter.java
659
constructors[LIST_SUB] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ListSubOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
1,224
addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.add(new byte[100]); } }, 10);
0true
hazelcast_src_main_java_com_hazelcast_examples_AllTest.java
619
public class OIndexNotUnique extends OIndexMultiValues { public OIndexNotUnique(String typeId, String algorithm, OIndexEngine<Set<OIdentifiable>> engine, String valueContainerAlgorithm) { super(typeId, algorithm, engine, valueContainerAlgorithm); } public boolean canBeUsedInEqualityOperators() { return true; } @Override public boolean supportsOrderedIterations() { return indexEngine.hasRangeQuerySupport(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexNotUnique.java
1,552
@ManagedDescription("IList") public class ListMBean extends HazelcastMBean<IList<?>> { private AtomicLong totalAddedItemCount = new AtomicLong(); private AtomicLong totalRemovedItemCount = new AtomicLong(); private final String registrationId; protected ListMBean(IList<?> managedObject, ManagementService service) { super(managedObject, service); objectName = service.createObjectName("IList", managedObject.getName()); //todo: using the event system to register number of adds/remove is an very expensive price to pay. ItemListener itemListener = new ItemListener() { @Override public void itemAdded(ItemEvent item) { totalAddedItemCount.incrementAndGet(); } @Override public void itemRemoved(ItemEvent item) { totalRemovedItemCount.incrementAndGet(); } }; registrationId = managedObject.addItemListener(itemListener, false); } @ManagedAnnotation(value = "clear", operation = true) @ManagedDescription("Clear List") public void clear() { managedObject.clear(); } @ManagedAnnotation("name") @ManagedDescription("Name of the DistributedObject") public String getName() { return managedObject.getName(); } @ManagedAnnotation("totalAddedItemCount") public long getTotalAddedItemCount() { return totalAddedItemCount.get(); } @ManagedAnnotation("totalRemovedItemCount") public long getTotalRemovedItemCount() { return totalRemovedItemCount.get(); } public void preDeregister() throws Exception { super.preDeregister(); try { managedObject.removeItemListener(registrationId); } catch (Exception ignored) { } } }
0true
hazelcast_src_main_java_com_hazelcast_jmx_ListMBean.java
668
sbTree.loadEntriesMajor(fromKey, isInclusive, new OTreeInternal.RangeResultListener<Object, V>() { @Override public boolean addResult(Map.Entry<Object, V> entry) { final Object key = entry.getKey(); final V value = entry.getValue(); return addToEntriesResult(transformer, entriesResultListener, key, value); } });
0true
core_src_main_java_com_orientechnologies_orient_core_index_engine_OSBTreeIndexEngine.java
237
@Category({StandaloneTests.class}) public class UUIDTest { public static final String z = "00000000-0000-1000-0000-000000000000"; public static final String v = "9451e273-7753-11e0-92df-e700f669bcfc"; @Test public void timeUUIDComparison() { TimeUUIDType ti = TimeUUIDType.instance; UUID zu = UUID.fromString(z); UUID vu = UUID.fromString(v); ByteBuffer zb = ti.decompose(zu); ByteBuffer vb = ti.decompose(vu); assertEquals(-1, ti.compare(zb, vb)); assertEquals(1, zu.compareTo(vu)); assertEquals(1, ti.compare(vb, zb)); assertEquals(-1, vu.compareTo(zu)); } }
0true
titan-cassandra_src_test_java_com_thinkaurelius_titan_diskstorage_cassandra_UUIDTest.java
665
@Repository("blSkuDao") public class SkuDaoImpl implements SkuDao { @PersistenceContext(unitName="blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; @Override public Sku save(Sku sku) { return em.merge(sku); } @Override public SkuFee saveSkuFee(SkuFee fee) { return em.merge(fee); } @Override public Sku readSkuById(Long skuId) { return (Sku) em.find(SkuImpl.class, skuId); } @Override public Sku readFirstSku() { TypedQuery<Sku> query = em.createNamedQuery("BC_READ_FIRST_SKU", Sku.class); return query.getSingleResult(); } @Override public List<Sku> readAllSkus() { TypedQuery<Sku> query = em.createNamedQuery("BC_READ_ALL_SKUS", Sku.class); return query.getResultList(); } @Override public List<Sku> readSkusById(List<Long> ids) { TypedQuery<Sku> query = em.createNamedQuery("BC_READ_SKUS_BY_ID", Sku.class); query.setParameter("skuIds", ids); return query.getResultList(); } @Override public void delete(Sku sku){ if (!em.contains(sku)) { sku = readSkuById(sku.getId()); } em.remove(sku); } @Override public Sku create() { return (Sku) entityConfiguration.createEntityInstance(Sku.class.getName()); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_dao_SkuDaoImpl.java
44
{ @Override public void notify( ClusterMemberListener listener ) { for ( MemberIsAvailable memberIsAvailable : clusterMembersSnapshot.getCurrentAvailable( member ) ) { listener.memberIsUnavailable( memberIsAvailable.getRole(), member ); } } } );
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_member_paxos_PaxosClusterMemberEvents.java
3,675
public static class Defaults extends AbstractFieldMapper.Defaults { public static final String NAME = ParentFieldMapper.NAME; public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexed(true); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setStored(true); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY); FIELD_TYPE.freeze(); } }
0true
src_main_java_org_elasticsearch_index_mapper_internal_ParentFieldMapper.java
1,923
abstract class AbstractMapQueryRequest extends InvocationClientRequest implements Portable, RetryableRequest, SecureRequest { private String name; private IterationType iterationType; public AbstractMapQueryRequest() { } public AbstractMapQueryRequest(String name, IterationType iterationType) { this.name = name; this.iterationType = iterationType; } @Override protected final void invoke() { Collection<MemberImpl> members = getClientEngine().getClusterService().getMemberList(); int partitionCount = getClientEngine().getPartitionService().getPartitionCount(); Set<Integer> plist = new HashSet<Integer>(partitionCount); final ClientEndpoint endpoint = getEndpoint(); QueryResultSet result = new QueryResultSet(null, iterationType, true); try { List<Future> flist = new ArrayList<Future>(); final Predicate predicate = getPredicate(); for (MemberImpl member : members) { Future future = createInvocationBuilder(SERVICE_NAME, new QueryOperation(name, predicate), member.getAddress()).invoke(); flist.add(future); } for (Future future : flist) { QueryResult queryResult = (QueryResult) future.get(); if (queryResult != null) { final List<Integer> partitionIds = queryResult.getPartitionIds(); if (partitionIds != null) { plist.addAll(partitionIds); result.addAll(queryResult.getResult()); } } } if (plist.size() != partitionCount) { List<Integer> missingList = new ArrayList<Integer>(); for (int i = 0; i < partitionCount; i++) { if (!plist.contains(i)) { missingList.add(i); } } List<Future> futures = new ArrayList<Future>(missingList.size()); for (Integer pid : missingList) { QueryPartitionOperation queryPartitionOperation = new QueryPartitionOperation(name, predicate); queryPartitionOperation.setPartitionId(pid); try { Future f = createInvocationBuilder(SERVICE_NAME, queryPartitionOperation, pid).invoke(); futures.add(f); } catch (Throwable t) { throw ExceptionUtil.rethrow(t); } } for (Future future : futures) { QueryResult queryResult = (QueryResult) future.get(); result.addAll(queryResult.getResult()); } } } catch (Throwable t) { throw ExceptionUtil.rethrow(t); } endpoint.sendResponse(result, getCallId()); } protected abstract Predicate getPredicate(); public final String getServiceName() { return MapService.SERVICE_NAME; } public final int getFactoryId() { return MapPortableHook.F_ID; } public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); writer.writeUTF("t", iterationType.toString()); writePortableInner(writer); } protected abstract void writePortableInner(PortableWriter writer) throws IOException; public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); iterationType = IterationType.valueOf(reader.readUTF("t")); readPortableInner(reader); } protected abstract void readPortableInner(PortableReader reader) throws IOException; public Permission getRequiredPermission() { return new MapPermission(name, ActionConstants.ACTION_READ); } }
0true
hazelcast_src_main_java_com_hazelcast_map_client_AbstractMapQueryRequest.java
1,441
public class RemoteGremlinTest { /** * */ private static final String URL = "remote:localhost/tinkerpop"; private final OServer server; private OGraphDatabase graphDatabase; public RemoteGremlinTest() throws Exception { if (System.getProperty("ORIENTDB_HOME") == null) { System.setProperty("ORIENTDB_HOME", "target"); } OGremlinHelper.global().create(); server = OServerMain.create(); } @BeforeClass public void setUp() throws Exception { server.startup(new File(getClass().getResource("db-config.xml").getFile())); server.activate(); } @AfterClass public void tearDown() throws Exception { if (server != null) server.shutdown(); } @BeforeMethod public void beforeMethod() { for (OStorage stg : Orient.instance().getStorages()) { System.out.println("Closing storage: " + stg); stg.close(true); } graphDatabase = new OGraphDatabase(URL); graphDatabase.open("admin", "admin"); } @AfterMethod public void afterMethod() { graphDatabase.close(); } @Test public void function() throws IOException { ODocument vertex1 = (ODocument) graphDatabase.createVertex().field("label", "car").save(); ODocument vertex2 = (ODocument) graphDatabase.createVertex().field("label", "pilot").save(); ODocument edge = (ODocument) graphDatabase.createEdge(vertex1, vertex2).field("label", "drives").save(); List<?> result = graphDatabase.query(new OSQLSynchQuery<Object>( "select gremlin('current.out.in') as value from V where out.size() > 0 limit 3")); System.out.println("Query result: " + result); result = graphDatabase.query(new OSQLSynchQuery<Object>("select gremlin('current.out') as value from V")); System.out.println("Query result: " + result); int clusterId = graphDatabase.getVertexBaseClass().getDefaultClusterId(); result = graphDatabase.query(new OSQLSynchQuery<Object>("select gremlin('current.out.in') as value from " + clusterId + ":1")); System.out.println("Query result: " + result); result = graphDatabase.query(new OSQLSynchQuery<Object>("select gremlin('current.out(\"drives\").count()') as value from V")); System.out.println("Query result: " + result); } @Test public void command() throws IOException { List<OIdentifiable> result = graphDatabase.command(new OCommandGremlin("g.V[0..10]")).execute(); if (result != null) { for (OIdentifiable doc : result) { System.out.println(doc.getRecord().toJSON()); } } Map<String, Object> params = new HashMap<String, Object>(); params.put("par1", 100); result = graphDatabase.command(new OCommandSQL("select gremlin('current.out.filter{ it.performances > par1 }') from V")) .execute(params); System.out.println("Command result: " + result); } @Test public void testGremlinAgainstBlueprints() { OGremlinHelper.global().create(); OrientGraph graph = new OrientGraph(URL); final int NUM_ITERS = 1000; long start = System.currentTimeMillis(); try { for (int i = NUM_ITERS; i > 0; i--) { List<Vertex> r = graph.getRawGraph().command(new OCommandGremlin("g.V[1].out.out.in")).execute(); System.out.println(r.size()); } System.out.println("Total: " + (System.currentTimeMillis() - start) + " ms AVG: " + ((System.currentTimeMillis() - start) / (float) NUM_ITERS)); } catch (Exception x) { x.printStackTrace(); System.out.println(graph.getRawGraph().isClosed()); } } @Test public void testRemoteDB() { OrientGraphNoTx graph = new OrientGraphNoTx("remote:localhost/temp", "admin", "admin"); OrientVertex v1 = graph.addVertex("class:V"); OrientVertex v2 = graph.addVertex("class:V"); OrientVertex v3 = graph.addVertex("class:V"); v1.addEdge("rel", v2); v2.addEdge("rel", v3); graph.commit(); graph = new OrientGraphNoTx("remote:localhost/temp"); Assert.assertEquals(graph.countVertices(), 3); Assert.assertEquals(graph.countEdges(), 2); graph.shutdown(); } }
0true
graphdb_src_test_java_com_orientechnologies_orient_graph_blueprints_RemoteGremlinTest.java
97
public class ODirectMemoryPointer { private final boolean SAFE_MODE = !Boolean.valueOf(System.getProperty("memory.directMemory.unsafeMode")); private final ODirectMemory directMemory = ODirectMemoryFactory.INSTANCE.directMemory(); private final long pageSize; private final long dataPointer; public ODirectMemoryPointer(long pageSize) { if (pageSize <= 0) throw new ODirectMemoryViolationException("Size of allocated area should be more than zero but " + pageSize + " was provided."); this.dataPointer = directMemory.allocate(pageSize); this.pageSize = pageSize; } public ODirectMemoryPointer(byte[] data) { if (data.length == 0) throw new ODirectMemoryViolationException("Size of allocated area should be more than zero but 0 was provided."); this.dataPointer = directMemory.allocate(data); this.pageSize = data.length; } public byte[] get(long offset, int length) { if (SAFE_MODE) rangeCheck(offset, length); return directMemory.get(dataPointer + offset, length); } public void get(long offset, byte[] array, int arrayOffset, int length) { if (SAFE_MODE) rangeCheck(offset, length); directMemory.get(dataPointer + offset, array, arrayOffset, length); } public void set(long offset, byte[] content, int arrayOffset, int length) { if (SAFE_MODE) rangeCheck(offset, length); directMemory.set(dataPointer + offset, content, arrayOffset, length); } public int getInt(long offset) { if (SAFE_MODE) rangeCheck(offset, OIntegerSerializer.INT_SIZE); return directMemory.getInt(dataPointer + offset); } public void setInt(long offset, int value) { if (SAFE_MODE) rangeCheck(offset, OIntegerSerializer.INT_SIZE); directMemory.setInt(dataPointer + offset, value); } public void setShort(long offset, short value) { if (SAFE_MODE) rangeCheck(offset, OShortSerializer.SHORT_SIZE); directMemory.setShort(dataPointer + offset, value); } public short getShort(long offset) { if (SAFE_MODE) rangeCheck(offset, OShortSerializer.SHORT_SIZE); return directMemory.getShort(dataPointer + offset); } public long getLong(long offset) { if (SAFE_MODE) rangeCheck(offset, OLongSerializer.LONG_SIZE); return directMemory.getLong(dataPointer + offset); } public void setLong(long offset, long value) { if (SAFE_MODE) rangeCheck(offset, OLongSerializer.LONG_SIZE); directMemory.setLong(dataPointer + offset, value); } public byte getByte(long offset) { if (SAFE_MODE) rangeCheck(offset, OByteSerializer.BYTE_SIZE); return directMemory.getByte(dataPointer + offset); } public void setByte(long offset, byte value) { if (SAFE_MODE) rangeCheck(offset, OByteSerializer.BYTE_SIZE); directMemory.setByte(dataPointer + offset, value); } public void setChar(long offset, char value) { if (SAFE_MODE) rangeCheck(offset, OCharSerializer.CHAR_SIZE); directMemory.setChar(dataPointer + offset, value); } public char getChar(long offset) { if (SAFE_MODE) rangeCheck(offset, OCharSerializer.CHAR_SIZE); return directMemory.getChar(dataPointer + offset); } public void moveData(long srcOffset, ODirectMemoryPointer destPointer, long destOffset, long len) { if (SAFE_MODE) { rangeCheck(srcOffset, len); rangeCheck(destOffset, len); } directMemory.moveData(dataPointer + srcOffset, destPointer.getDataPointer() + destOffset, len); } private void rangeCheck(long offset, long size) { if (offset < 0) throw new ODirectMemoryViolationException("Negative offset was provided"); if (size < 0) throw new ODirectMemoryViolationException("Negative size was provided"); if (offset > pageSize) throw new ODirectMemoryViolationException("Provided offset [" + offset + "] is more than size of allocated area [" + pageSize + "]"); if (offset + size > pageSize) throw new ODirectMemoryViolationException("Last position of provided data interval [" + (offset + size) + "] is more than size of allocated area [" + pageSize + "]"); } public long getDataPointer() { return dataPointer; } public void free() { directMemory.free(dataPointer); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ODirectMemoryPointer that = (ODirectMemoryPointer) o; if (dataPointer != that.dataPointer) return false; if (pageSize != that.pageSize) return false; return true; } @Override public int hashCode() { int result = (int) (pageSize ^ (pageSize >>> 32)); result = 31 * result + (int) (dataPointer ^ (dataPointer >>> 32)); return result; } }
0true
commons_src_main_java_com_orientechnologies_common_directmemory_ODirectMemoryPointer.java
620
public class IndicesStatsResponse extends BroadcastOperationResponse implements ToXContent { private ShardStats[] shards; private ImmutableMap<ShardRouting, CommonStats> shardStatsMap; IndicesStatsResponse() { } IndicesStatsResponse(ShardStats[] shards, ClusterState clusterState, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) { super(totalShards, successfulShards, failedShards, shardFailures); this.shards = shards; } public ImmutableMap<ShardRouting, CommonStats> asMap() { if (shardStatsMap == null) { ImmutableMap.Builder<ShardRouting, CommonStats> mb = ImmutableMap.builder(); for (ShardStats ss : shards) { mb.put(ss.getShardRouting(), ss.getStats()); } shardStatsMap = mb.build(); } return shardStatsMap; } public ShardStats[] getShards() { return this.shards; } public ShardStats getAt(int position) { return shards[position]; } public IndexStats getIndex(String index) { return getIndices().get(index); } private Map<String, IndexStats> indicesStats; public Map<String, IndexStats> getIndices() { if (indicesStats != null) { return indicesStats; } Map<String, IndexStats> indicesStats = Maps.newHashMap(); Set<String> indices = Sets.newHashSet(); for (ShardStats shard : shards) { indices.add(shard.getIndex()); } for (String index : indices) { List<ShardStats> shards = Lists.newArrayList(); for (ShardStats shard : this.shards) { if (shard.getShardRouting().index().equals(index)) { shards.add(shard); } } indicesStats.put(index, new IndexStats(index, shards.toArray(new ShardStats[shards.size()]))); } this.indicesStats = indicesStats; return indicesStats; } private CommonStats total = null; public CommonStats getTotal() { if (total != null) { return total; } CommonStats stats = new CommonStats(); for (ShardStats shard : shards) { stats.add(shard.getStats()); } total = stats; return stats; } private CommonStats primary = null; public CommonStats getPrimaries() { if (primary != null) { return primary; } CommonStats stats = new CommonStats(); for (ShardStats shard : shards) { if (shard.getShardRouting().primary()) { stats.add(shard.getStats()); } } primary = stats; return stats; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); shards = new ShardStats[in.readVInt()]; for (int i = 0; i < shards.length; i++) { shards[i] = ShardStats.readShardStats(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(shards.length); for (ShardStats shard : shards) { shard.writeTo(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { String level = params.param("level", "indices"); boolean isLevelValid = "indices".equalsIgnoreCase(level) || "shards".equalsIgnoreCase(level) || "cluster".equalsIgnoreCase(level); if (!isLevelValid) { return builder; } builder.startObject("_all"); builder.startObject("primaries"); getPrimaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); getTotal().toXContent(builder, params); builder.endObject(); builder.endObject(); if ("indices".equalsIgnoreCase(level) || "shards".equalsIgnoreCase(level)) { builder.startObject(Fields.INDICES); for (IndexStats indexStats : getIndices().values()) { builder.startObject(indexStats.getIndex(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("primaries"); indexStats.getPrimaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); indexStats.getTotal().toXContent(builder, params); builder.endObject(); if ("shards".equalsIgnoreCase(level)) { builder.startObject(Fields.SHARDS); for (IndexShardStats indexShardStats : indexStats) { builder.startArray(Integer.toString(indexShardStats.getShardId().id())); for (ShardStats shardStats : indexShardStats) { builder.startObject(); shardStats.toXContent(builder, params); builder.endObject(); } builder.endArray(); } builder.endObject(); } builder.endObject(); } builder.endObject(); } return builder; } static final class Fields { static final XContentBuilderString INDICES = new XContentBuilderString("indices"); static final XContentBuilderString SHARDS = new XContentBuilderString("shards"); } @Override public String toString() { try { XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint(); builder.startObject(); toXContent(builder, EMPTY_PARAMS); builder.endObject(); return builder.string(); } catch (IOException e) { return "{ \"error\" : \"" + e.getMessage() + "\"}"; } } }
0true
src_main_java_org_elasticsearch_action_admin_indices_stats_IndicesStatsResponse.java
21
class FindScopeVisitor extends Visitor { Scope scope; public void visit(Tree.Declaration that) { super.visit(that); AnnotationList al = that.getAnnotationList(); if (al!=null) { for (Tree.Annotation a: al.getAnnotations()) { Integer i = a.getPrimary().getStartIndex(); Integer j = node.getStartIndex(); if (i.intValue()==j.intValue()) { scope = that.getDeclarationModel().getScope(); } } } } public void visit(Tree.DocLink that) { super.visit(that); scope = ((Tree.DocLink)node).getPkg(); } };
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionUtil.java
1,428
static class MappingTask { final String index; final String indexUUID; MappingTask(String index, final String indexUUID) { this.index = index; this.indexUUID = indexUUID; } }
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataMappingService.java
1,284
public final class SimpleFunctionalMapTest { private static final int ENTRY_COUNT = 1000; private static final int KB = 10240; private static final int STATS_SECONDS = 10; private static final Random RANDOM = new Random(); private SimpleFunctionalMapTest() { } /** * This test runs continuously until an exception is thrown. * No args */ public static void main(String[] args) { int threadCount = 40; final Stats stats = new Stats(); final HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(null); ExecutorService es = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { es.submit(new Runnable() { public void run() { IMap map = hazelcast.getMap("default"); while (true) { int keyInt = (int) (RANDOM.nextFloat() * ENTRY_COUNT); int operation = ((int) (RANDOM.nextFloat() * 1000)) % 20; Object key = String.valueOf(keyInt); if (operation < 1) { map.size(); stats.increment("size"); } else if (operation < 2) { map.get(key); stats.increment("get"); } else if (operation < 3) { map.remove(key); stats.increment("remove"); } else if (operation < 4) { map.containsKey(key); stats.increment("containsKey"); } else if (operation < 5) { Object value = String.valueOf(key); map.containsValue(value); stats.increment("containsValue"); } else if (operation < 6) { map.putIfAbsent(key, createValue()); stats.increment("putIfAbsent"); } else if (operation < 7) { Collection col = map.values(); for (Object o : col) { int i = 0; } stats.increment("values"); } else if (operation < 8) { Collection col = map.keySet(); for (Object o : col) { int i = 0; } stats.increment("keySet"); } else if (operation < 9) { Collection col = map.entrySet(); for (Object o : col) { int i = 0; } stats.increment("entrySet"); } else { map.put(key, createValue()); stats.increment("put"); } } } }); } Executors.newSingleThreadExecutor().submit(new Runnable() { public void run() { while (true) { try { //noinspection BusyWait Thread.sleep(STATS_SECONDS * 1000); System.out.println("cluster size:" + hazelcast.getCluster().getMembers().size()); Stats currentStats = stats.getAndReset(); System.out.println(currentStats); } catch (Exception e) { e.printStackTrace(); } } } }); } public static Object createValue() { int numberOfK = (((int) (RANDOM.nextFloat() * 1000)) % 40) + 1; return new byte[numberOfK * KB]; } /** * Map statistics class */ public static class Stats { Map<String, AtomicLong> mapStats = new ConcurrentHashMap<String, AtomicLong>(10); public Stats() { mapStats.put("put", new AtomicLong(0)); mapStats.put("get", new AtomicLong(0)); mapStats.put("remove", new AtomicLong(0)); mapStats.put("size", new AtomicLong(0)); mapStats.put("containsKey", new AtomicLong(0)); mapStats.put("containsValue", new AtomicLong(0)); mapStats.put("clear", new AtomicLong(0)); mapStats.put("keySet", new AtomicLong(0)); mapStats.put("values", new AtomicLong(0)); mapStats.put("entrySet", new AtomicLong(0)); mapStats.put("putIfAbsent", new AtomicLong(0)); } public Stats getAndReset() { Stats newOne = new Stats(); Set<Map.Entry<String, AtomicLong>> entries = newOne.mapStats.entrySet(); for (Map.Entry<String, AtomicLong> entry : entries) { String key = entry.getKey(); AtomicLong value = entry.getValue(); value.set(mapStats.get(key).getAndSet(0)); } return newOne; } @Override public String toString() { StringBuilder sb = new StringBuilder(); long total = 0; Set<Map.Entry<String, AtomicLong>> entries = mapStats.entrySet(); for (Map.Entry<String, AtomicLong> entry : entries) { String key = entry.getKey(); AtomicLong value = entry.getValue(); sb.append(key + ":" + value.get()); sb.append("\n"); total += value.get(); } sb.append("Operations per Second : " + total / STATS_SECONDS + " \n"); return sb.toString(); } public void increment(String operation) { mapStats.get(operation).incrementAndGet(); } } }
0true
hazelcast_src_main_java_com_hazelcast_examples_SimpleFunctionalMapTest.java
738
public class SkuActiveDateConsiderationContext { private static final ThreadLocal<SkuActiveDateConsiderationContext> skuActiveDatesConsiderationContext = ThreadLocalManager.createThreadLocal(SkuActiveDateConsiderationContext.class); public static HashMap getSkuActiveDateConsiderationContext() { return SkuActiveDateConsiderationContext.skuActiveDatesConsiderationContext.get().considerations; } public static void setSkuActiveDateConsiderationContext(HashMap skuPricingConsiderations) { SkuActiveDateConsiderationContext.skuActiveDatesConsiderationContext.get().considerations = skuPricingConsiderations; } public static DynamicSkuActiveDatesService getSkuActiveDatesService() { return SkuActiveDateConsiderationContext.skuActiveDatesConsiderationContext.get().service; } public static void setSkuActiveDatesService(DynamicSkuActiveDatesService skuPricingService) { SkuActiveDateConsiderationContext.skuActiveDatesConsiderationContext.get().service = skuPricingService; } public static boolean hasDynamicActiveDates() { return (getSkuActiveDatesService() != null); } protected DynamicSkuActiveDatesService service; protected HashMap considerations; }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_service_dynamic_SkuActiveDateConsiderationContext.java
985
public abstract class TransportIndicesReplicationOperationAction<Request extends IndicesReplicationOperationRequest, Response extends ActionResponse, IndexRequest extends IndexReplicationOperationRequest, IndexResponse extends ActionResponse, ShardRequest extends ShardReplicationOperationRequest, ShardReplicaRequest extends ActionRequest, ShardResponse extends ActionResponse> extends TransportAction<Request, Response> { protected final ClusterService clusterService; protected final TransportIndexReplicationOperationAction<IndexRequest, IndexResponse, ShardRequest, ShardReplicaRequest, ShardResponse> indexAction; final String transportAction; @Inject public TransportIndicesReplicationOperationAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, TransportIndexReplicationOperationAction<IndexRequest, IndexResponse, ShardRequest, ShardReplicaRequest, ShardResponse> indexAction) { super(settings, threadPool); this.clusterService = clusterService; this.indexAction = indexAction; this.transportAction = transportAction(); transportService.registerHandler(transportAction, new TransportHandler()); } protected abstract Map<String, Set<String>> resolveRouting(ClusterState clusterState, Request request) throws ElasticsearchException; @Override protected void doExecute(final Request request, final ActionListener<Response> listener) { ClusterState clusterState = clusterService.state(); ClusterBlockException blockException = checkGlobalBlock(clusterState, request); if (blockException != null) { throw blockException; } // get actual indices String[] concreteIndices = clusterState.metaData().concreteIndices(request.indices(), request.indicesOptions()); blockException = checkRequestBlock(clusterState, request, concreteIndices); if (blockException != null) { throw blockException; } final AtomicInteger indexCounter = new AtomicInteger(); final AtomicInteger completionCounter = new AtomicInteger(concreteIndices.length); final AtomicReferenceArray<Object> indexResponses = new AtomicReferenceArray<Object>(concreteIndices.length); Map<String, Set<String>> routingMap = resolveRouting(clusterState, request); if (concreteIndices == null || concreteIndices.length == 0) { listener.onResponse(newResponseInstance(request, indexResponses)); } else { for (final String index : concreteIndices) { Set<String> routing = null; if (routingMap != null) { routing = routingMap.get(index); } IndexRequest indexRequest = newIndexRequestInstance(request, index, routing); // no threading needed, all is done on the index replication one indexRequest.listenerThreaded(false); indexAction.execute(indexRequest, new ActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse result) { indexResponses.set(indexCounter.getAndIncrement(), result); if (completionCounter.decrementAndGet() == 0) { listener.onResponse(newResponseInstance(request, indexResponses)); } } @Override public void onFailure(Throwable e) { int index = indexCounter.getAndIncrement(); if (accumulateExceptions()) { indexResponses.set(index, e); } if (completionCounter.decrementAndGet() == 0) { listener.onResponse(newResponseInstance(request, indexResponses)); } } }); } } } protected abstract Request newRequestInstance(); protected abstract Response newResponseInstance(Request request, AtomicReferenceArray indexResponses); protected abstract String transportAction(); protected abstract IndexRequest newIndexRequestInstance(Request request, String index, Set<String> routing); protected abstract boolean accumulateExceptions(); protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request); protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request, String[] concreteIndices); private class TransportHandler extends BaseTransportRequestHandler<Request> { @Override public Request newInstance() { return newRequestInstance(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void messageReceived(final Request request, final TransportChannel channel) throws Exception { // no need for a threaded listener, since we just send a response request.listenerThreaded(false); execute(request, new ActionListener<Response>() { @Override public void onResponse(Response result) { try { channel.sendResponse(result); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Exception e1) { logger.warn("Failed to send error response for action [" + transportAction + "] and request [" + request + "]", e1); } } }); } } }
1no label
src_main_java_org_elasticsearch_action_support_replication_TransportIndicesReplicationOperationAction.java
1,345
Future future = es.submit("default", new Callable<String>() { @Override public String call() { try { latch1.await(30, TimeUnit.SECONDS); return "success"; } catch (Exception e) { throw new RuntimeException(e); } } });
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
1,484
public class BroadleafCategoryController extends BroadleafAbstractController implements Controller { protected static String defaultCategoryView = "catalog/category"; protected static String CATEGORY_ATTRIBUTE_NAME = "category"; protected static String PRODUCTS_ATTRIBUTE_NAME = "products"; protected static String FACETS_ATTRIBUTE_NAME = "facets"; protected static String PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME = "result"; protected static String ACTIVE_FACETS_ATTRIBUTE_NAME = "activeFacets"; @Resource(name = "blSearchService") protected SearchService searchService; @Resource(name = "blSearchFacetDTOService") protected SearchFacetDTOService facetService; @Override @SuppressWarnings("unchecked") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); if (request.getParameterMap().containsKey("facetField")) { // If we receive a facetField parameter, we need to convert the field to the // product search criteria expected format. This is used in multi-facet selection. We // will send a redirect to the appropriate URL to maintain canonical URLs String fieldName = request.getParameter("facetField"); List<String> activeFieldFilters = new ArrayList<String>(); Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap()); for (Iterator<Entry<String,String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();){ Map.Entry<String, String[]> entry = iter.next(); String key = entry.getKey(); if (key.startsWith(fieldName + "-")) { activeFieldFilters.add(key.substring(key.indexOf('-') + 1)); iter.remove(); } } parameters.remove(ProductSearchCriteria.PAGE_NUMBER); parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()])); parameters.remove("facetField"); String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters); model.setViewName("redirect:" + newUrl); } else { // Else, if we received a GET to the category URL (either the user clicked this link or we redirected // from the POST method, we can actually process the results Category category = (Category) request.getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME); assert(category != null); List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category); ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets); String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING); ProductSearchResult result; if (StringUtils.isNotBlank(searchTerm)) { result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria); } else { result = searchService.findProductsByCategory(category, searchCriteria); } facetService.setActiveFacetResults(result.getFacets(), request); model.addObject(CATEGORY_ATTRIBUTE_NAME, category); model.addObject(PRODUCTS_ATTRIBUTE_NAME, result.getProducts()); model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets()); model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result); if (StringUtils.isNotEmpty(category.getDisplayTemplate())) { model.setViewName(category.getDisplayTemplate()); } else { model.setViewName(getDefaultCategoryView()); } } return model; } public String getDefaultCategoryView() { return defaultCategoryView; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_catalog_BroadleafCategoryController.java
756
public class CommitTaxActivity extends BaseActivity<CheckoutContext> { @Resource(name = "blTaxService") protected TaxService taxService; public CommitTaxActivity() { super(); //We can automatically register a rollback handler because the state will be in the process context. super.setAutomaticallyRegisterRollbackHandler(true); } @Override public CheckoutContext execute(CheckoutContext context) throws Exception { Order order = context.getSeedData().getOrder(); order = taxService.commitTaxForOrder(order); context.getSeedData().setOrder(order); return context; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_checkout_service_workflow_CommitTaxActivity.java
1,164
public interface GiftCardPaymentInfo extends Referenced { /** * @return the id */ public Long getId(); /** * @param id the id to set */ public void setId(Long id); /** * @return the pan */ public String getPan(); /** * @param pan the pan to set */ public void setPan(String pan); /** * @return the pin */ public String getPin(); /** * @param pin the pin to set */ public void setPin(String pin); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_GiftCardPaymentInfo.java
1,923
class Parameter { private final Type type; private final boolean isAssisted; private final Annotation bindingAnnotation; private final boolean isProvider; public Parameter(Type type, Annotation[] annotations) { this.type = type; this.bindingAnnotation = getBindingAnnotation(annotations); this.isAssisted = hasAssistedAnnotation(annotations); this.isProvider = isProvider(type); } public boolean isProvidedByFactory() { return isAssisted; } public Type getType() { return type; } @Override public String toString() { StringBuilder result = new StringBuilder(); if (isAssisted) { result.append("@Assisted"); result.append(" "); } if (bindingAnnotation != null) { result.append(bindingAnnotation.toString()); result.append(" "); } result.append(type.toString()); return result.toString(); } private boolean hasAssistedAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { if (annotation.annotationType().equals(Assisted.class)) { return true; } } return false; } /** * Returns the Guice {@link Key} for this parameter. */ public Object getValue(Injector injector) { return isProvider ? injector.getProvider(getBindingForType(getProvidedType(type))) : injector.getInstance(getPrimaryBindingKey()); } public boolean isBound(Injector injector) { return isBound(injector, getPrimaryBindingKey()) || isBound(injector, fixAnnotations(getPrimaryBindingKey())); } private boolean isBound(Injector injector, Key<?> key) { // This method is particularly lame - we really need an API that can test // for any binding, implicit or explicit try { return injector.getBinding(key) != null; } catch (ConfigurationException e) { return false; } } /** * Replace annotation instances with annotation types, this is only * appropriate for testing if a key is bound and not for injecting. * <p/> * See Guice bug 125, * http://code.google.com/p/google-guice/issues/detail?id=125 */ public Key<?> fixAnnotations(Key<?> key) { return key.getAnnotation() == null ? key : Key.get(key.getTypeLiteral(), key.getAnnotation().annotationType()); } Key<?> getPrimaryBindingKey() { return isProvider ? getBindingForType(getProvidedType(type)) : getBindingForType(type); } private Type getProvidedType(Type type) { return ((ParameterizedType) type).getActualTypeArguments()[0]; } private boolean isProvider(Type type) { return type instanceof ParameterizedType && ((ParameterizedType) type).getRawType() == Provider.class; } private Key<?> getBindingForType(Type type) { return bindingAnnotation != null ? Key.get(type, bindingAnnotation) : Key.get(type); } /** * Returns the unique binding annotation from the specified list, or * {@code null} if there are none. * * @throws IllegalStateException if multiple binding annotations exist. */ private Annotation getBindingAnnotation(Annotation[] annotations) { Annotation bindingAnnotation = null; for (Annotation a : annotations) { if (a.annotationType().getAnnotation(BindingAnnotation.class) != null) { checkArgument(bindingAnnotation == null, "Parameter has multiple binding annotations: %s and %s", bindingAnnotation, a); bindingAnnotation = a; } } return bindingAnnotation; } }
0true
src_main_java_org_elasticsearch_common_inject_assistedinject_Parameter.java
110
public interface ChangeState { /** * Returns all added, removed, or modified vertices when the change argument is {@link Change#ADDED}, * {@link Change#REMOVED}, or {@link Change#ANY} respectively. * * @param change * @return */ public Set<TitanVertex> getVertices(Change change); /** * Returns all relations that match the change state and any of the provided relation types. If no relation types * are specified all relations matching the state are returned. * * @param change * @param types * @return */ public Iterable<TitanRelation> getRelations(Change change, RelationType... types); /** * Returns all edges incident on the given vertex in the given direction that match the provided change state and edge labels. * * @param vertex * @param change * @param dir * @param labels * @return */ public Iterable<TitanEdge> getEdges(TitanVertex vertex, Change change, Direction dir, String... labels); /** * Returns all edges incident on the given vertex in the given direction that match the provided change state and edge labels. * * @param vertex * @param change * @param dir * @param labels * @return */ public Iterable<TitanEdge> getTitanEdges(TitanVertex vertex, Change change, Direction dir, EdgeLabel... labels); /** * Returns all properties incident for the given vertex that match the provided change state and property keys. * * @param vertex * @param change * @param keys * @return */ public Iterable<TitanProperty> getProperties(TitanVertex vertex, Change change, String... keys); /** * Returns all properties incident for the given vertex that match the provided change state and property keys. * * @param vertex * @param change * @param keys * @return */ public Iterable<TitanProperty> getTitanProperties(TitanVertex vertex, Change change, PropertyKey... keys); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_log_ChangeState.java
1,226
@Test public class StorageModificationLockTest { private final static int THREAD_COUNT = 100; private final static int CYCLES_COUNT = 20; private final AtomicLong counter = new AtomicLong(); private final OModificationLock modificationLock = new OModificationLock(); private final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT + 1); private final List<Future<Void>> futures = new ArrayList<Future<Void>>(THREAD_COUNT); private final CountDownLatch countDownLatch = new CountDownLatch(1); @Test public void testLock() throws Exception { for (int i = 0; i < THREAD_COUNT; i++) { futures.add(executorService.submit(new Counter())); } Future<Void> prohibiter = executorService.submit(new Prohibiter()); countDownLatch.countDown(); prohibiter.get(); for (Future<Void> future : futures) future.get(); } private final class Counter implements Callable<Void> { private final Random random = new Random(); public Void call() throws Exception { countDownLatch.await(); for (int n = 0; n < CYCLES_COUNT; n++) { final int modificationsCount = random.nextInt(255); modificationLock.requestModificationLock(); try { for (int i = 0; i < modificationsCount; i++) { counter.incrementAndGet(); Thread.sleep(random.nextInt(5)); } } finally { modificationLock.releaseModificationLock(); } } return null; } } private final class Prohibiter implements Callable<Void> { public Void call() throws Exception { countDownLatch.await(); for (int n = 0; n < CYCLES_COUNT; n++) { modificationLock.prohibitModifications(); long beforeModification = counter.get(); Thread.sleep(50); if (n % 10 == 0) System.out .println("After prohibit modifications " + beforeModification + " before allow modifications " + counter.get()); Assert.assertEquals(counter.get(), beforeModification); modificationLock.allowModifications(); Thread.sleep(50); } return null; } } }
0true
core_src_test_java_com_orientechnologies_orient_core_storage_StorageModificationLockTest.java
522
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientTxnMapTest { static HazelcastInstance client; static HazelcastInstance server; @BeforeClass public static void init() { server = Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(); } @AfterClass public static void destroy() { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testUnlockAfterRollback() { final String mapName = randomString(); final String key ="key"; final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> map = context.getMap(mapName); map.put(key, "value"); context.rollbackTransaction(); assertFalse(client.getMap(mapName).isLocked(key)); } @Test public void testDeadLockFromClientInstance() throws InterruptedException { final String mapName = randomString(); final String key = "key"; final AtomicBoolean running = new AtomicBoolean(true); Thread t = new Thread() { public void run() { while (running.get()) { client.getMap(mapName).get(key); } } }; t.start(); CBAuthorisation cb = new CBAuthorisation(); cb.setAmount(15000); try { TransactionContext context = client.newTransactionContext(); context.beginTransaction(); TransactionalMap mapTransaction = context.getMap(mapName); // init data mapTransaction.put(key, cb); // start test deadlock, 3 set and concurrent, get deadlock cb.setAmount(12000); mapTransaction.set(key, cb); cb.setAmount(10000); mapTransaction.set(key, cb); cb.setAmount(900); mapTransaction.set(key, cb); cb.setAmount(800); mapTransaction.set(key, cb); cb.setAmount(700); mapTransaction.set(key, cb); context.commitTransaction(); } catch (TransactionException e) { e.printStackTrace(); fail(); } running.set(false); t.join(); } public static class CBAuthorisation implements Serializable { private int amount; public void setAmount(int amount) { this.amount = amount; } public int getAmount() { return amount; } } @Test public void testTxnMapPut() throws Exception { final String mapName = randomString(); final String key = "key"; final String value = "Value"; final IMap map = client.getMap(mapName); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> txnMap = context.getMap(mapName); txnMap.put(key, value); context.commitTransaction(); assertEquals(value, map.get(key)); } @Test public void testTxnMapPut_BeforeCommit() throws Exception { final String mapName = randomString(); final String key = "key"; final String value = "Value"; final IMap map = client.getMap(mapName); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> txnMap = context.getMap(mapName); assertNull(txnMap.put(key, value)); context.commitTransaction(); } @Test public void testTxnMapGet_BeforeCommit() throws Exception { final String mapName = randomString(); final String key = "key"; final String value = "Value"; final IMap map = client.getMap(mapName); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> txnMap = context.getMap(mapName); txnMap.put(key, value); assertEquals(value, txnMap.get(key)); assertNull(map.get(key)); context.commitTransaction(); } @Test public void testPutWithTTL() { final String mapName = randomString(); final int ttlSeconds = 1; final String key = "key"; final String value = "Value"; final IMap map = client.getMap(mapName); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> txnMap = context.getMap(mapName); txnMap.put(key, value, ttlSeconds, TimeUnit.SECONDS); Object resultFromClientWhileTxnInProgress = map.get(key); context.commitTransaction(); assertNull(resultFromClientWhileTxnInProgress); assertEquals(value, map.get(key)); //waite for ttl to expire sleepSeconds(ttlSeconds + 1); assertNull(map.get(key)); } @Test public void testGetForUpdate() throws TransactionException { final String mapName = randomString(); final String key = "key"; final int initialValue = 111; final int value = 888; final CountDownLatch getKeyForUpdateLatch = new CountDownLatch(1); final CountDownLatch afterTryPutResult = new CountDownLatch(1); final IMap<String, Integer> map = client.getMap(mapName); map.put(key, initialValue); final AtomicBoolean tryPutResult = new AtomicBoolean(true); Runnable incrementor = new Runnable() { public void run() { try { getKeyForUpdateLatch.await(30, TimeUnit.SECONDS); boolean result = map.tryPut(key, value, 0, TimeUnit.SECONDS); tryPutResult.set(result); afterTryPutResult.countDown(); } catch (Exception e) { } } }; new Thread(incrementor).start(); client.executeTransaction(new TransactionalTask<Boolean>() { public Boolean execute(TransactionalTaskContext context) throws TransactionException { try { final TransactionalMap<String, Integer> txMap = context.getMap(mapName); txMap.getForUpdate(key); getKeyForUpdateLatch.countDown(); afterTryPutResult.await(30, TimeUnit.SECONDS); } catch (Exception e) { } return true; } }); assertFalse(tryPutResult.get()); } @Test public void testKeySetValues() throws Exception { final String mapName = randomString(); IMap map = client.getMap(mapName); map.put("key1", "value1"); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> txMap = context.getMap(mapName); assertNull(txMap.put("key2", "value2")); assertEquals(2, txMap.size()); assertEquals(2, txMap.keySet().size()); assertEquals(2, txMap.values().size()); context.commitTransaction(); assertEquals(2, map.size()); assertEquals(2, map.keySet().size()); assertEquals(2, map.values().size()); } @Test public void testKeysetAndValuesWithPredicates() throws Exception { final String mapName = randomString(); IMap map = client.getMap(mapName); final SampleObjects.Employee emp1 = new SampleObjects.Employee("abc-123-xvz", 34, true, 10D); final SampleObjects.Employee emp2 = new SampleObjects.Employee("abc-123-xvz", 20, true, 10D); map.put(emp1, emp1); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); assertNull(txMap.put(emp2, emp2)); assertEquals(2, txMap.size()); assertEquals(2, txMap.keySet().size()); assertEquals(0, txMap.keySet(new SqlPredicate("age = 10")).size()); assertEquals(0, txMap.values(new SqlPredicate("age = 10")).size()); assertEquals(2, txMap.keySet(new SqlPredicate("age >= 10")).size()); assertEquals(2, txMap.values(new SqlPredicate("age >= 10")).size()); context.commitTransaction(); assertEquals(2, map.size()); assertEquals(2, map.values().size()); } @Test public void testPutAndRoleBack() throws Exception { final String mapName = randomString(); final String key = "key"; final String value = "value"; final IMap map = client.getMap(mapName); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> mapTxn = context.getMap(mapName); mapTxn.put(key, value); context.rollbackTransaction(); assertNull(map.get(key)); } @Test public void testTnxMapContainsKey() throws Exception { final String mapName = randomString(); IMap map = client.getMap(mapName); map.put("key1", "value1"); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); txMap.put("key2", "value2"); assertTrue(txMap.containsKey("key1")); assertTrue(txMap.containsKey("key2")); assertFalse(txMap.containsKey("key3")); context.commitTransaction(); } @Test public void testTnxMapIsEmpty() throws Exception { final String mapName = randomString(); IMap map = client.getMap(mapName); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); assertTrue(txMap.isEmpty()); context.commitTransaction(); } @Test public void testTnxMapPutIfAbsent() throws Exception { final String mapName = randomString(); IMap map = client.getMap(mapName); final String keyValue1 = "keyValue1"; final String keyValue2 = "keyValue2"; map.put(keyValue1, keyValue1); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); txMap.putIfAbsent(keyValue1, "NOT_THIS"); txMap.putIfAbsent(keyValue2, keyValue2); context.commitTransaction(); assertEquals(keyValue1, map.get(keyValue1)); assertEquals(keyValue2, map.get(keyValue2)); } @Test public void testTnxMapReplace() throws Exception { final String mapName = randomString(); IMap map = client.getMap(mapName); final String key1 = "key1"; final String key2 = "key2"; final String replaceValue = "replaceValue"; map.put(key1, "OLD_VALUE"); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); txMap.replace(key1, replaceValue); txMap.replace(key2, "NOT_POSSIBLE"); context.commitTransaction(); assertEquals(replaceValue, map.get(key1)); assertNull(map.get(key2)); } @Test public void testTnxMapReplaceKeyValue() throws Exception { final String mapName = randomString(); final String key1 = "key1"; final String oldValue1 = "old1"; final String newValue1 = "new1"; final String key2 = "key2"; final String oldValue2 = "old2"; IMap map = client.getMap(mapName); map.put(key1, oldValue1); map.put(key2, oldValue2); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); txMap.replace(key1, oldValue1, newValue1); txMap.replace(key2, "NOT_OLD_VALUE", "NEW_VALUE_CANT_BE_THIS"); context.commitTransaction(); assertEquals(newValue1, map.get(key1)); assertEquals(oldValue2, map.get(key2)); } @Test public void testTnxMapRemove() throws Exception { final String mapName = randomString(); final String key = "key1"; final String value = "old1"; IMap map = client.getMap(mapName); map.put(key, value); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); txMap.remove(key); context.commitTransaction(); assertNull(map.get(key)); } @Test public void testTnxMapRemoveKeyValue() throws Exception { final String mapName = randomString(); final String key1 = "key1"; final String oldValue1 = "old1"; final String key2 = "key2"; final String oldValue2 = "old2"; IMap map = client.getMap(mapName); map.put(key1, oldValue1); map.put(key2, oldValue2); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); txMap.remove(key1, oldValue1); txMap.remove(key2, "NO_REMOVE_AS_NOT_VALUE"); context.commitTransaction(); assertNull(map.get(key1)); assertEquals(oldValue2, map.get(key2)); } @Test public void testTnxMapDelete() throws Exception { final String mapName = randomString(); final String key = "key1"; final String value = "old1"; IMap map = client.getMap(mapName); map.put(key, value); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap txMap = context.getMap(mapName); txMap.delete(key); context.commitTransaction(); assertNull(map.get(key)); } @Test(expected = NullPointerException.class) public void testKeySetPredicateNull() throws Exception { final String mapName = randomString(); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> txMap = context.getMap(mapName); txMap.keySet(null); } @Test(expected = NullPointerException.class) public void testKeyValuesPredicateNull() throws Exception { final String mapName = randomString(); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalMap<Object, Object> txMap = context.getMap(mapName); txMap.values(null); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnMapTest.java
362
public class HBaseDistributedStoreManagerTest extends DistributedStoreManagerTest<HBaseStoreManager> { @BeforeClass public static void startHBase() throws IOException { HBaseStorageSetup.startHBase(); } @AfterClass public static void stopHBase() { // Workaround for https://issues.apache.org/jira/browse/HBASE-10312 if (VersionInfo.getVersion().startsWith("0.96")) HBaseStorageSetup.killIfRunning(); } @Before public void setUp() throws BackendException { manager = new HBaseStoreManager(HBaseStorageSetup.getHBaseConfiguration()); store = manager.openDatabase("distributedStoreTest"); } @After public void tearDown() throws BackendException { store.close(); manager.close(); } }
0true
titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_diskstorage_hbase_HBaseDistributedStoreManagerTest.java
702
public class OCachePointer { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final AtomicInteger referrersCount = new AtomicInteger(); private final AtomicInteger usagesCounter = new AtomicInteger(); private volatile OLogSequenceNumber lastFlushedLsn; private final ODirectMemoryPointer dataPointer; public OCachePointer(ODirectMemoryPointer dataPointer, OLogSequenceNumber lastFlushedLsn) { this.lastFlushedLsn = lastFlushedLsn; this.dataPointer = dataPointer; } public OCachePointer(byte[] data, OLogSequenceNumber lastFlushedLsn) { this.lastFlushedLsn = lastFlushedLsn; dataPointer = new ODirectMemoryPointer(data); } OLogSequenceNumber getLastFlushedLsn() { return lastFlushedLsn; } void setLastFlushedLsn(OLogSequenceNumber lastFlushedLsn) { this.lastFlushedLsn = lastFlushedLsn; } void incrementReferrer() { referrersCount.incrementAndGet(); } void decrementReferrer() { if (referrersCount.decrementAndGet() == 0) { dataPointer.free(); } } public ODirectMemoryPointer getDataPointer() { return dataPointer; } public void acquireExclusiveLock() { readWriteLock.writeLock().lock(); } public boolean tryAcquireExclusiveLock() { return readWriteLock.writeLock().tryLock(); } public void releaseExclusiveLock() { readWriteLock.writeLock().unlock(); } @Override protected void finalize() throws Throwable { super.finalize(); if (referrersCount.get() > 0) dataPointer.free(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OCachePointer that = (OCachePointer) o; if (dataPointer != null ? !dataPointer.equals(that.dataPointer) : that.dataPointer != null) return false; return true; } @Override public int hashCode() { return dataPointer != null ? dataPointer.hashCode() : 0; } @Override public String toString() { return "OCachePointer{" + "referrersCount=" + referrersCount + ", usagesCount=" + usagesCounter + ", dataPointer=" + dataPointer + '}'; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_cache_OCachePointer.java
1,528
@ApplicationException(rollback = true) public class CustomRuntimeException extends RuntimeException { public CustomRuntimeException(String s) { super(s); } }
0true
hazelcast-ra_hazelcast-jca_src_test_java_com_hazelcast_jca_CustomRuntimeException.java
1,650
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class AsyncTest extends HazelcastTestSupport { private final String key = "key"; private final String value1 = "value1"; private final String value2 = "value2"; @Test public void testGetAsync() throws Exception { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); IMap<String, String> map = factory.newHazelcastInstance().getMap("testGetAsync"); map.put(key, value1); Future<String> f1 = map.getAsync(key); TestCase.assertEquals(value1, f1.get()); } @Test public void testPutAsync() throws Exception { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); IMap<String, String> map = factory.newHazelcastInstance().getMap("map:test:putAsync"); Future<String> f1 = map.putAsync(key, value1); String f1Val = f1.get(); TestCase.assertNull(f1Val); Future<String> f2 = map.putAsync(key, value2); String f2Val = f2.get(); TestCase.assertEquals(value1, f2Val); } @Test public void testPutAsyncWithTtl() throws Exception { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); IMap<String, String> map = factory.newHazelcastInstance().getMap("map:test:putAsyncWithTtl"); final CountDownLatch latch = new CountDownLatch(1); map.addEntryListener(new EntryAdapter<String, String>() { public void entryEvicted(EntryEvent<String, String> event) { latch.countDown(); } }, true); Future<String> f1 = map.putAsync(key, value1, 3, TimeUnit.SECONDS); String f1Val = f1.get(); TestCase.assertNull(f1Val); assertEquals(value1, map.get(key)); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNull(map.get(key)); } @Test public void testRemoveAsync() throws Exception { IMap<String, String> map = createHazelcastInstance().getMap("map:test:removeAsync"); // populate map map.put(key, value1); Future<String> f1 = map.removeAsync(key); TestCase.assertEquals(value1, f1.get()); } @Test public void testRemoveAsyncWithImmediateTimeout() throws Exception { final IMap<String, String> map = createHazelcastInstance().getMap("map:test:removeAsync:timeout"); // populate map map.put(key, value1); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { public void run() { map.lock(key); latch.countDown(); } }).start(); assertTrue(latch.await(20, TimeUnit.SECONDS)); Future<String> f1 = map.removeAsync(key); try { assertEquals(value1, f1.get(0L, TimeUnit.SECONDS)); } catch (TimeoutException e) { // expected return; } TestCase.fail("Failed to throw TimeoutException with zero timeout"); } @Test public void testRemoveAsyncWithNonExistentKey() throws Exception { IMap<String, String> map = createHazelcastInstance().getMap("map:test:removeAsync:nonexistant"); Future<String> f1 = map.removeAsync(key); TestCase.assertNull(f1.get()); } }
0true
hazelcast_src_test_java_com_hazelcast_map_AsyncTest.java
593
static final class Fields { static final XContentBuilderString INDICES = new XContentBuilderString("indices"); static final XContentBuilderString SHARDS = new XContentBuilderString("shards"); static final XContentBuilderString ROUTING = new XContentBuilderString("routing"); static final XContentBuilderString STATE = new XContentBuilderString("state"); static final XContentBuilderString PRIMARY = new XContentBuilderString("primary"); static final XContentBuilderString NODE = new XContentBuilderString("node"); static final XContentBuilderString RELOCATING_NODE = new XContentBuilderString("relocating_node"); static final XContentBuilderString SEGMENTS = new XContentBuilderString("segments"); static final XContentBuilderString GENERATION = new XContentBuilderString("generation"); static final XContentBuilderString NUM_COMMITTED_SEGMENTS = new XContentBuilderString("num_committed_segments"); static final XContentBuilderString NUM_SEARCH_SEGMENTS = new XContentBuilderString("num_search_segments"); static final XContentBuilderString NUM_DOCS = new XContentBuilderString("num_docs"); static final XContentBuilderString DELETED_DOCS = new XContentBuilderString("deleted_docs"); static final XContentBuilderString SIZE = new XContentBuilderString("size"); static final XContentBuilderString SIZE_IN_BYTES = new XContentBuilderString("size_in_bytes"); static final XContentBuilderString COMMITTED = new XContentBuilderString("committed"); static final XContentBuilderString SEARCH = new XContentBuilderString("search"); static final XContentBuilderString VERSION = new XContentBuilderString("version"); static final XContentBuilderString COMPOUND = new XContentBuilderString("compound"); static final XContentBuilderString MERGE_ID = new XContentBuilderString("merge_id"); static final XContentBuilderString MEMORY = new XContentBuilderString("memory"); static final XContentBuilderString MEMORY_IN_BYTES = new XContentBuilderString("memory_in_bytes"); }
0true
src_main_java_org_elasticsearch_action_admin_indices_segments_IndicesSegmentResponse.java
2,232
public class FunctionScoreQuery extends Query { Query subQuery; final ScoreFunction function; float maxBoost = Float.MAX_VALUE; CombineFunction combineFunction; public FunctionScoreQuery(Query subQuery, ScoreFunction function) { this.subQuery = subQuery; this.function = function; this.combineFunction = function.getDefaultScoreCombiner(); } public void setCombineFunction(CombineFunction combineFunction) { this.combineFunction = combineFunction; } public void setMaxBoost(float maxBoost) { this.maxBoost = maxBoost; } public float getMaxBoost() { return this.maxBoost; } public Query getSubQuery() { return subQuery; } public ScoreFunction getFunction() { return function; } @Override public Query rewrite(IndexReader reader) throws IOException { Query newQ = subQuery.rewrite(reader); if (newQ == subQuery) { return this; } FunctionScoreQuery bq = (FunctionScoreQuery) this.clone(); bq.subQuery = newQ; return bq; } @Override public void extractTerms(Set<Term> terms) { subQuery.extractTerms(terms); } @Override public Weight createWeight(IndexSearcher searcher) throws IOException { Weight subQueryWeight = subQuery.createWeight(searcher); return new CustomBoostFactorWeight(subQueryWeight); } class CustomBoostFactorWeight extends Weight { final Weight subQueryWeight; public CustomBoostFactorWeight(Weight subQueryWeight) throws IOException { this.subQueryWeight = subQueryWeight; } public Query getQuery() { return FunctionScoreQuery.this; } @Override public float getValueForNormalization() throws IOException { float sum = subQueryWeight.getValueForNormalization(); sum *= getBoost() * getBoost(); return sum; } @Override public void normalize(float norm, float topLevelBoost) { subQueryWeight.normalize(norm, topLevelBoost * getBoost()); } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { // we ignore scoreDocsInOrder parameter, because we need to score in // order if documents are scored with a script. The // ShardLookup depends on in order scoring. Scorer subQueryScorer = subQueryWeight.scorer(context, true, false, acceptDocs); if (subQueryScorer == null) { return null; } function.setNextReader(context); return new CustomBoostFactorScorer(this, subQueryScorer, function, maxBoost, combineFunction); } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException { Explanation subQueryExpl = subQueryWeight.explain(context, doc); if (!subQueryExpl.isMatch()) { return subQueryExpl; } function.setNextReader(context); Explanation functionExplanation = function.explainScore(doc, subQueryExpl); return combineFunction.explain(getBoost(), subQueryExpl, functionExplanation, maxBoost); } } static class CustomBoostFactorScorer extends Scorer { private final float subQueryBoost; private final Scorer scorer; private final ScoreFunction function; private final float maxBoost; private final CombineFunction scoreCombiner; private CustomBoostFactorScorer(CustomBoostFactorWeight w, Scorer scorer, ScoreFunction function, float maxBoost, CombineFunction scoreCombiner) throws IOException { super(w); this.subQueryBoost = w.getQuery().getBoost(); this.scorer = scorer; this.function = function; this.maxBoost = maxBoost; this.scoreCombiner = scoreCombiner; } @Override public int docID() { return scorer.docID(); } @Override public int advance(int target) throws IOException { return scorer.advance(target); } @Override public int nextDoc() throws IOException { return scorer.nextDoc(); } @Override public float score() throws IOException { float score = scorer.score(); return scoreCombiner.combine(subQueryBoost, score, function.score(scorer.docID(), score), maxBoost); } @Override public int freq() throws IOException { return scorer.freq(); } @Override public long cost() { return scorer.cost(); } } public String toString(String field) { StringBuilder sb = new StringBuilder(); sb.append("function score (").append(subQuery.toString(field)).append(",function=").append(function).append(')'); sb.append(ToStringUtils.boost(getBoost())); return sb.toString(); } public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; FunctionScoreQuery other = (FunctionScoreQuery) o; return this.getBoost() == other.getBoost() && this.subQuery.equals(other.subQuery) && this.function.equals(other.function) && this.maxBoost == other.maxBoost; } public int hashCode() { return subQuery.hashCode() + 31 * function.hashCode() ^ Float.floatToIntBits(getBoost()); } }
1no label
src_main_java_org_elasticsearch_common_lucene_search_function_FunctionScoreQuery.java
682
public class PutWarmerRequestTests extends ElasticsearchTestCase { @Test // issue 4196 public void testThatValidationWithoutSpecifyingSearchRequestFails() { PutWarmerRequest putWarmerRequest = new PutWarmerRequest("foo"); ActionRequestValidationException validationException = putWarmerRequest.validate(); assertThat(validationException.validationErrors(), hasSize(1)); assertThat(validationException.getMessage(), containsString("search request is missing")); } }
0true
src_test_java_org_elasticsearch_action_admin_indices_warmer_put_PutWarmerRequestTests.java
300
public class SiteNotFoundException extends RuntimeException { public SiteNotFoundException() { //do nothing } public SiteNotFoundException(Throwable cause) { super(cause); } public SiteNotFoundException(String message) { super(message); } public SiteNotFoundException(String message, Throwable cause) { super(message, cause); } }
0true
common_src_main_java_org_broadleafcommerce_common_exception_SiteNotFoundException.java
189
public interface OSizeable { public int size(); }
0true
commons_src_main_java_com_orientechnologies_common_util_OSizeable.java
858
public class AlterAndGetOperation extends AbstractAlterOperation { public AlterAndGetOperation() { } public AlterAndGetOperation(String name, Data function) { super(name, function); } @Override public void run() throws Exception { NodeEngine nodeEngine = getNodeEngine(); IFunction f = nodeEngine.toObject(function); ReferenceWrapper reference = getReference(); Object input = nodeEngine.toObject(reference.get()); //noinspection unchecked Object output = f.apply(input); shouldBackup = !isEquals(input, output); if (shouldBackup) { backup = nodeEngine.toData(output); reference.set(backup); } response = output; } @Override public int getId() { return AtomicReferenceDataSerializerHook.ALTER_AND_GET; } }
1no label
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_AlterAndGetOperation.java
177
public class MersenneTwisterFast implements Serializable, Cloneable { // Serialization private static final long serialVersionUID = -8219700664442619525L; // locked as of Version 15 // Period parameters private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; // private static final * constant vector a private static final int UPPER_MASK = 0x80000000; // most significant w-r bits private static final int LOWER_MASK = 0x7fffffff; // least significant r bits // Tempering parameters private static final int TEMPERING_MASK_B = 0x9d2c5680; private static final int TEMPERING_MASK_C = 0xefc60000; private int mt[]; // the array for the state vector private int mti; // mti==N+1 means mt[N] is not initialized private int mag01[]; // a good initial seed (of int size, though stored in a long) //private static final long GOOD_SEED = 4357; private double __nextNextGaussian; private boolean __haveNextNextGaussian; /* We're overriding all internal data, to my knowledge, so this should be okay */ public Object clone() { try { MersenneTwisterFast f = (MersenneTwisterFast)(super.clone()); f.mt = (int[])(mt.clone()); f.mag01 = (int[])(mag01.clone()); return f; } catch (CloneNotSupportedException e) { throw new InternalError(); } // should never happen } public boolean stateEquals(Object o) { if (o==this) return true; if (o == null || !(o instanceof MersenneTwisterFast)) return false; MersenneTwisterFast other = (MersenneTwisterFast) o; if (mti != other.mti) return false; for(int x=0;x<mag01.length;x++) if (mag01[x] != other.mag01[x]) return false; for(int x=0;x<mt.length;x++) if (mt[x] != other.mt[x]) return false; return true; } /** Reads the entire state of the MersenneTwister RNG from the stream */ public void readState(DataInputStream stream) throws IOException { int len = mt.length; for(int x=0;x<len;x++) mt[x] = stream.readInt(); len = mag01.length; for(int x=0;x<len;x++) mag01[x] = stream.readInt(); mti = stream.readInt(); __nextNextGaussian = stream.readDouble(); __haveNextNextGaussian = stream.readBoolean(); } /** Writes the entire state of the MersenneTwister RNG to the stream */ public void writeState(DataOutputStream stream) throws IOException { int len = mt.length; for(int x=0;x<len;x++) stream.writeInt(mt[x]); len = mag01.length; for(int x=0;x<len;x++) stream.writeInt(mag01[x]); stream.writeInt(mti); stream.writeDouble(__nextNextGaussian); stream.writeBoolean(__haveNextNextGaussian); } /** * Constructor using the default seed. */ public MersenneTwisterFast() { this(System.currentTimeMillis()); } /** * Constructor using a given seed. Though you pass this seed in * as a long, it's best to make sure it's actually an integer. * */ public MersenneTwisterFast(final long seed) { setSeed(seed); } /** * Constructor using an array of integers as seed. * Your array must have a non-zero length. Only the first 624 integers * in the array are used; if the array is shorter than this then * integers are repeatedly used in a wrap-around fashion. */ public MersenneTwisterFast(final int[] array) { setSeed(array); } /** * Initalize the pseudo random number generator. Don't * pass in a long that's bigger than an int (Mersenne Twister * only uses the first 32 bits for its seed). */ synchronized public void setSeed(final long seed) { // Due to a bug in java.util.Random clear up to 1.2, we're // doing our own Gaussian variable. __haveNextNextGaussian = false; mt = new int[N]; mag01 = new int[2]; mag01[0] = 0x0; mag01[1] = MATRIX_A; mt[0]= (int)(seed & 0xffffffff); for (mti=1; mti<N; mti++) { mt[mti] = (1812433253 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffff; /* for >32 bit machines */ } } /** * Sets the seed of the MersenneTwister using an array of integers. * Your array must have a non-zero length. Only the first 624 integers * in the array are used; if the array is shorter than this then * integers are repeatedly used in a wrap-around fashion. */ synchronized public void setSeed(final int[] array) { if (array.length == 0) throw new IllegalArgumentException("Array length must be greater than zero"); int i, j, k; setSeed(19650218); i=1; j=0; k = (N>array.length ? N : array.length); for (; k!=0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1664525)) + array[j] + j; /* non linear */ mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=array.length) j=0; } for (k=N-1; k!=0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1566083941)) - i; /* non linear */ mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ } public final int nextInt() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return y; } public final short nextShort() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (short)(y >>> 16); } public final char nextChar() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (char)(y >>> 16); } public final boolean nextBoolean() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (boolean)((y >>> 31) != 0); } /** This generates a coin flip with a probability <tt>probability</tt> of returning true, else returning false. <tt>probability</tt> must be between 0.0 and 1.0, inclusive. Not as precise a random real event as nextBoolean(double), but twice as fast. To explicitly use this, remember you may need to cast to float first. */ public final boolean nextBoolean(final float probability) { int y; if (probability < 0.0f || probability > 1.0f) throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive."); if (probability==0.0f) return false; // fix half-open issues else if (probability==1.0f) return true; // fix half-open issues if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (y >>> 8) / ((float)(1 << 24)) < probability; } /** This generates a coin flip with a probability <tt>probability</tt> of returning true, else returning false. <tt>probability</tt> must be between 0.0 and 1.0, inclusive. */ public final boolean nextBoolean(final double probability) { int y; int z; if (probability < 0.0 || probability > 1.0) throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive."); if (probability==0.0) return false; // fix half-open issues else if (probability==1.0) return true; // fix half-open issues if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) /* derived from nextDouble documentation in jdk 1.2 docs, see top */ return ((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53) < probability; } public final byte nextByte() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (byte)(y >>> 24); } public final void nextBytes(byte[] bytes) { int y; for (int x=0;x<bytes.length;x++) { if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) bytes[x] = (byte)(y >>> 24); } } public final long nextLong() { int y; int z; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) return (((long)y) << 32) + (long)z; } /** Returns a long drawn uniformly from 0 to n-1. Suffice it to say, n must be > 0, or an IllegalArgumentException is raised. */ public final long nextLong(final long n) { if (n<=0) throw new IllegalArgumentException("n must be positive, got: " + n); long bits, val; do { int y; int z; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) bits = (((((long)y) << 32) + (long)z) >>> 1); val = bits % n; } while (bits - val + (n-1) < 0); return val; } /** Returns a random double in the half-open range from [0.0,1.0). Thus 0.0 is a valid result but 1.0 is not. */ public final double nextDouble() { int y; int z; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) /* derived from nextDouble documentation in jdk 1.2 docs, see top */ return ((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53); } /** Returns a double in the range from 0.0 to 1.0, possibly inclusive of 0.0 and 1.0 themselves. Thus: <p><table border=0> <th><td>Expression<td>Interval <tr><td>nextDouble(false, false)<td>(0.0, 1.0) <tr><td>nextDouble(true, false)<td>[0.0, 1.0) <tr><td>nextDouble(false, true)<td>(0.0, 1.0] <tr><td>nextDouble(true, true)<td>[0.0, 1.0] </table> <p>This version preserves all possible random values in the double range. */ public double nextDouble(boolean includeZero, boolean includeOne) { double d = 0.0; do { d = nextDouble(); // grab a value, initially from half-open [0.0, 1.0) if (includeOne && nextBoolean()) d += 1.0; // if includeOne, with 1/2 probability, push to [1.0, 2.0) } while ( (d > 1.0) || // everything above 1.0 is always invalid (!includeZero && d == 0.0)); // if we're not including zero, 0.0 is invalid return d; } public final double nextGaussian() { if (__haveNextNextGaussian) { __haveNextNextGaussian = false; return __nextNextGaussian; } else { double v1, v2, s; do { int y; int z; int a; int b; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { a = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (a >>> 1) ^ mag01[a & 0x1]; } for (; kk < N-1; kk++) { a = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (a >>> 1) ^ mag01[a & 0x1]; } a = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (a >>> 1) ^ mag01[a & 0x1]; mti = 0; } a = mt[mti++]; a ^= a >>> 11; // TEMPERING_SHIFT_U(a) a ^= (a << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(a) a ^= (a << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(a) a ^= (a >>> 18); // TEMPERING_SHIFT_L(a) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { b = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (b >>> 1) ^ mag01[b & 0x1]; } for (; kk < N-1; kk++) { b = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (b >>> 1) ^ mag01[b & 0x1]; } b = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (b >>> 1) ^ mag01[b & 0x1]; mti = 0; } b = mt[mti++]; b ^= b >>> 11; // TEMPERING_SHIFT_U(b) b ^= (b << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(b) b ^= (b << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(b) b ^= (b >>> 18); // TEMPERING_SHIFT_L(b) /* derived from nextDouble documentation in jdk 1.2 docs, see top */ v1 = 2 * (((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53)) - 1; v2 = 2 * (((((long)(a >>> 6)) << 27) + (b >>> 5)) / (double)(1L << 53)) - 1; s = v1 * v1 + v2 * v2; } while (s >= 1 || s==0); double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); __nextNextGaussian = v2 * multiplier; __haveNextNextGaussian = true; return v1 * multiplier; } } /** Returns a random float in the half-open range from [0.0f,1.0f). Thus 0.0f is a valid result but 1.0f is not. */ public final float nextFloat() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (y >>> 8) / ((float)(1 << 24)); } /** Returns a float in the range from 0.0f to 1.0f, possibly inclusive of 0.0f and 1.0f themselves. Thus: <p><table border=0> <th><td>Expression<td>Interval <tr><td>nextFloat(false, false)<td>(0.0f, 1.0f) <tr><td>nextFloat(true, false)<td>[0.0f, 1.0f) <tr><td>nextFloat(false, true)<td>(0.0f, 1.0f] <tr><td>nextFloat(true, true)<td>[0.0f, 1.0f] </table> <p>This version preserves all possible random values in the float range. */ public double nextFloat(boolean includeZero, boolean includeOne) { float d = 0.0f; do { d = nextFloat(); // grab a value, initially from half-open [0.0f, 1.0f) if (includeOne && nextBoolean()) d += 1.0f; // if includeOne, with 1/2 probability, push to [1.0f, 2.0f) } while ( (d > 1.0f) || // everything above 1.0f is always invalid (!includeZero && d == 0.0f)); // if we're not including zero, 0.0f is invalid return d; } /** Returns an integer drawn uniformly from 0 to n-1. Suffice it to say, n must be > 0, or an IllegalArgumentException is raised. */ public final int nextInt(final int n) { if (n<=0) throw new IllegalArgumentException("n must be positive, got: " + n); if ((n & -n) == n) // i.e., n is a power of 2 { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (int)((n * (long) (y >>> 1) ) >> 31); } int bits, val; do { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) bits = (y >>> 1); val = bits % n; } while(bits - val + (n-1) < 0); return val; } }
0true
commons_src_main_java_com_orientechnologies_common_util_MersenneTwisterFast.java
2,233
static class CustomBoostFactorScorer extends Scorer { private final float subQueryBoost; private final Scorer scorer; private final ScoreFunction function; private final float maxBoost; private final CombineFunction scoreCombiner; private CustomBoostFactorScorer(CustomBoostFactorWeight w, Scorer scorer, ScoreFunction function, float maxBoost, CombineFunction scoreCombiner) throws IOException { super(w); this.subQueryBoost = w.getQuery().getBoost(); this.scorer = scorer; this.function = function; this.maxBoost = maxBoost; this.scoreCombiner = scoreCombiner; } @Override public int docID() { return scorer.docID(); } @Override public int advance(int target) throws IOException { return scorer.advance(target); } @Override public int nextDoc() throws IOException { return scorer.nextDoc(); } @Override public float score() throws IOException { float score = scorer.score(); return scoreCombiner.combine(subQueryBoost, score, function.score(scorer.docID(), score), maxBoost); } @Override public int freq() throws IOException { return scorer.freq(); } @Override public long cost() { return scorer.cost(); } }
0true
src_main_java_org_elasticsearch_common_lucene_search_function_FunctionScoreQuery.java
2,012
public static class WaitingOnFirstTestMapStore extends TestMapStore { private AtomicInteger count; public WaitingOnFirstTestMapStore() { super(); this.count = new AtomicInteger(0); } @Override public void storeAll(Map map) { if (count.get() == 0) { count.incrementAndGet(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } super.storeAll(map); } }
0true
hazelcast_src_test_java_com_hazelcast_map_mapstore_MapStoreTest.java
1,609
updateTasksExecutor.execute(task, threadPool.scheduler(), timeoutUpdateTask.timeout(), new Runnable() { @Override public void run() { threadPool.generic().execute(new Runnable() { @Override public void run() { timeoutUpdateTask.onFailure(task.source, new ProcessClusterEventTimeoutException(timeoutUpdateTask.timeout(), task.source)); } }); } });
0true
src_main_java_org_elasticsearch_cluster_service_InternalClusterService.java
972
public class LinkSerializerTest { private static final int FIELD_SIZE = OShortSerializer.SHORT_SIZE + OLongSerializer.LONG_SIZE; private ORecordId OBJECT; private static final int clusterId = 5; private static final OClusterPosition position = OClusterPositionFactory.INSTANCE.valueOf(100500L); private OLinkSerializer linkSerializer; byte[] stream = new byte[FIELD_SIZE]; @BeforeClass public void beforeClass() { OBJECT = new ORecordId(clusterId, position); linkSerializer = new OLinkSerializer(); } @Test public void testFieldSize() { Assert.assertEquals(linkSerializer.getObjectSize(null), FIELD_SIZE); } @Test public void testSerialize() { linkSerializer.serialize(OBJECT, stream, 0); Assert.assertEquals(linkSerializer.deserialize(stream, 0), OBJECT); } }
0true
core_src_test_java_com_orientechnologies_orient_core_serialization_serializer_binary_impl_LinkSerializerTest.java
140
@Test public class DateTimeSerializerTest { private final static int FIELD_SIZE = 8; private static final Date OBJECT = new Date(); private ODateTimeSerializer dateTimeSerializer; private static final byte[] stream = new byte[FIELD_SIZE]; @BeforeClass public void beforeClass() { dateTimeSerializer = new ODateTimeSerializer(); } public void testFieldSize() { Assert.assertEquals(dateTimeSerializer.getObjectSize(OBJECT), FIELD_SIZE); } public void testSerialize() { dateTimeSerializer.serialize(OBJECT, stream, 0); Assert.assertEquals(dateTimeSerializer.deserialize(stream, 0), OBJECT); } public void testSerializeNative() { dateTimeSerializer.serializeNative(OBJECT, stream, 0); Assert.assertEquals(dateTimeSerializer.deserializeNative(stream, 0), OBJECT); } public void testNativeDirectMemoryCompatibility() { dateTimeSerializer.serializeNative(OBJECT, stream, 0); ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream); try { Assert.assertEquals(dateTimeSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT); } finally { pointer.free(); } } }
0true
commons_src_test_java_com_orientechnologies_common_serialization_types_DateTimeSerializerTest.java
4,207
public class Store extends AbstractIndexShardComponent implements CloseableIndexComponent { static final String CHECKSUMS_PREFIX = "_checksums-"; public static final boolean isChecksum(String name) { return name.startsWith(CHECKSUMS_PREFIX); } private final IndexStore indexStore; final CodecService codecService; private final DirectoryService directoryService; private final StoreDirectory directory; private volatile ImmutableOpenMap<String, StoreFileMetaData> filesMetadata = ImmutableOpenMap.of(); private volatile String[] files = Strings.EMPTY_ARRAY; private final Object mutex = new Object(); private final boolean sync; @Inject public Store(ShardId shardId, @IndexSettings Settings indexSettings, IndexStore indexStore, CodecService codecService, DirectoryService directoryService, Distributor distributor) throws IOException { super(shardId, indexSettings); this.indexStore = indexStore; this.codecService = codecService; this.directoryService = directoryService; this.sync = componentSettings.getAsBoolean("sync", true); // TODO we don't really need to fsync when using shared gateway... this.directory = new StoreDirectory(distributor); } public IndexStore indexStore() { return this.indexStore; } public Directory directory() { return directory; } public ImmutableMap<String, StoreFileMetaData> list() throws IOException { ImmutableMap.Builder<String, StoreFileMetaData> builder = ImmutableMap.builder(); for (String name : files) { StoreFileMetaData md = metaData(name); if (md != null) { builder.put(md.name(), md); } } return builder.build(); } public StoreFileMetaData metaData(String name) throws IOException { StoreFileMetaData md = filesMetadata.get(name); if (md == null) { return null; } // IndexOutput not closed, does not exists if (md.length() == -1) { return null; } return md; } /** * Deletes the content of a shard store. Be careful calling this!. */ public void deleteContent() throws IOException { String[] files = directory.listAll(); IOException lastException = null; for (String file : files) { if (isChecksum(file)) { try { directory.deleteFileChecksum(file); } catch (IOException e) { lastException = e; } } else { try { directory.deleteFile(file); } catch (FileNotFoundException e) { // ignore } catch (IOException e) { lastException = e; } } } if (lastException != null) { throw lastException; } } public StoreStats stats() throws IOException { return new StoreStats(Directories.estimateSize(directory), directoryService.throttleTimeInNanos()); } public ByteSizeValue estimateSize() throws IOException { return new ByteSizeValue(Directories.estimateSize(directory)); } public void renameFile(String from, String to) throws IOException { synchronized (mutex) { StoreFileMetaData fromMetaData = filesMetadata.get(from); // we should always find this one if (fromMetaData == null) { throw new FileNotFoundException(from); } directoryService.renameFile(fromMetaData.directory(), from, to); StoreFileMetaData toMetaData = new StoreFileMetaData(to, fromMetaData.length(), fromMetaData.checksum(), fromMetaData.directory()); filesMetadata = ImmutableOpenMap.builder(filesMetadata).fRemove(from).fPut(to, toMetaData).build(); files = filesMetadata.keys().toArray(String.class); } } public static Map<String, String> readChecksums(File[] locations) throws IOException { Directory[] dirs = new Directory[locations.length]; try { for (int i = 0; i < locations.length; i++) { dirs[i] = new SimpleFSDirectory(locations[i]); } return readChecksums(dirs, null); } finally { for (Directory dir : dirs) { if (dir != null) { try { dir.close(); } catch (IOException e) { // ignore } } } } } static Map<String, String> readChecksums(Directory[] dirs, Map<String, String> defaultValue) throws IOException { long lastFound = -1; Directory lastDir = null; for (Directory dir : dirs) { for (String name : dir.listAll()) { if (!isChecksum(name)) { continue; } long current = Long.parseLong(name.substring(CHECKSUMS_PREFIX.length())); if (current > lastFound) { lastFound = current; lastDir = dir; } } } if (lastFound == -1) { return defaultValue; } IndexInput indexInput = lastDir.openInput(CHECKSUMS_PREFIX + lastFound, IOContext.READONCE); try { indexInput.readInt(); // version return indexInput.readStringStringMap(); } catch (Throwable e) { // failed to load checksums, ignore and return an empty map return defaultValue; } finally { indexInput.close(); } } public void writeChecksums() throws IOException { ImmutableMap<String, StoreFileMetaData> files = list(); String checksumName = CHECKSUMS_PREFIX + System.currentTimeMillis(); synchronized (mutex) { Map<String, String> checksums = new HashMap<String, String>(); for (StoreFileMetaData metaData : files.values()) { if (metaData.checksum() != null) { checksums.put(metaData.name(), metaData.checksum()); } } while (directory.fileExists(checksumName)) { checksumName = CHECKSUMS_PREFIX + System.currentTimeMillis(); } IndexOutput output = directory.createOutput(checksumName, IOContext.DEFAULT, true); try { output.writeInt(0); // version output.writeStringStringMap(checksums); } finally { output.close(); } } for (StoreFileMetaData metaData : files.values()) { if (metaData.name().startsWith(CHECKSUMS_PREFIX) && !checksumName.equals(metaData.name())) { try { directory.deleteFileChecksum(metaData.name()); } catch (Throwable e) { // ignore } } } } /** * Returns <tt>true</tt> by default. */ public boolean suggestUseCompoundFile() { return false; } public void close() { try { directory.close(); } catch (IOException e) { logger.debug("failed to close directory", e); } } /** * Creates a raw output, no checksum is computed, and no compression if enabled. */ public IndexOutput createOutputRaw(String name) throws IOException { return directory.createOutput(name, IOContext.DEFAULT, true); } /** * Opened an index input in raw form, no decompression for example. */ public IndexInput openInputRaw(String name, IOContext context) throws IOException { StoreFileMetaData metaData = filesMetadata.get(name); if (metaData == null) { throw new FileNotFoundException(name); } return metaData.directory().openInput(name, context); } public void writeChecksum(String name, String checksum) throws IOException { // update the metadata to include the checksum and write a new checksums file synchronized (mutex) { StoreFileMetaData metaData = filesMetadata.get(name); metaData = new StoreFileMetaData(metaData.name(), metaData.length(), checksum, metaData.directory()); filesMetadata = ImmutableOpenMap.builder(filesMetadata).fPut(name, metaData).build(); writeChecksums(); } } public void writeChecksums(Map<String, String> checksums) throws IOException { // update the metadata to include the checksum and write a new checksums file synchronized (mutex) { for (Map.Entry<String, String> entry : checksums.entrySet()) { StoreFileMetaData metaData = filesMetadata.get(entry.getKey()); metaData = new StoreFileMetaData(metaData.name(), metaData.length(), entry.getValue(), metaData.directory()); filesMetadata = ImmutableOpenMap.builder(filesMetadata).fPut(entry.getKey(), metaData).build(); } writeChecksums(); } } /** * The idea of the store directory is to cache file level meta data, as well as md5 of it */ public class StoreDirectory extends BaseDirectory implements ForceSyncDirectory { private final Distributor distributor; StoreDirectory(Distributor distributor) throws IOException { this.distributor = distributor; synchronized (mutex) { ImmutableOpenMap.Builder<String, StoreFileMetaData> builder = ImmutableOpenMap.builder(); Map<String, String> checksums = readChecksums(distributor.all(), new HashMap<String, String>()); for (Directory delegate : distributor.all()) { for (String file : delegate.listAll()) { String checksum = checksums.get(file); builder.put(file, new StoreFileMetaData(file, delegate.fileLength(file), checksum, delegate)); } } filesMetadata = builder.build(); files = filesMetadata.keys().toArray(String.class); } } public ShardId shardId() { return Store.this.shardId(); } public Settings settings() { return Store.this.indexSettings(); } @Nullable public CodecService codecService() { return Store.this.codecService; } public Directory[] delegates() { return distributor.all(); } @Override public void copy(Directory to, String src, String dest, IOContext context) throws IOException { ensureOpen(); // lets the default implementation happen, so we properly open an input and create an output super.copy(to, src, dest, context); } @Override public String[] listAll() throws IOException { ensureOpen(); return files; } @Override public boolean fileExists(String name) throws IOException { ensureOpen(); return filesMetadata.containsKey(name); } public void deleteFileChecksum(String name) throws IOException { ensureOpen(); StoreFileMetaData metaData = filesMetadata.get(name); if (metaData != null) { try { metaData.directory().deleteFile(name); } catch (IOException e) { if (metaData.directory().fileExists(name)) { throw e; } } } synchronized (mutex) { filesMetadata = ImmutableOpenMap.builder(filesMetadata).fRemove(name).build(); files = filesMetadata.keys().toArray(String.class); } } @Override public void deleteFile(String name) throws IOException { ensureOpen(); // we don't allow to delete the checksums files, only using the deleteChecksum method if (isChecksum(name)) { return; } StoreFileMetaData metaData = filesMetadata.get(name); if (metaData != null) { try { metaData.directory().deleteFile(name); } catch (IOException e) { if (metaData.directory().fileExists(name)) { throw e; } } } synchronized (mutex) { filesMetadata = ImmutableOpenMap.builder(filesMetadata).fRemove(name).build(); files = filesMetadata.keys().toArray(String.class); } } /** * Returns the *actual* file length, not the uncompressed one if compression is enabled, this * messes things up when using compound file format, but it shouldn't be used in any case... */ @Override public long fileLength(String name) throws IOException { ensureOpen(); StoreFileMetaData metaData = filesMetadata.get(name); if (metaData == null) { throw new FileNotFoundException(name); } // not set yet (IndexOutput not closed) if (metaData.length() != -1) { return metaData.length(); } return metaData.directory().fileLength(name); } @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { return createOutput(name, context, false); } public IndexOutput createOutput(String name, IOContext context, boolean raw) throws IOException { ensureOpen(); Directory directory; // we want to write the segments gen file to the same directory *all* the time // to make sure we don't create multiple copies of it if (isChecksum(name) || IndexFileNames.SEGMENTS_GEN.equals(name)) { directory = distributor.primary(); } else { directory = distributor.any(); } IndexOutput out = directory.createOutput(name, context); boolean success = false; try { synchronized (mutex) { StoreFileMetaData metaData = new StoreFileMetaData(name, -1, null, directory); filesMetadata = ImmutableOpenMap.builder(filesMetadata).fPut(name, metaData).build(); files = filesMetadata.keys().toArray(String.class); boolean computeChecksum = !raw; if (computeChecksum) { // don't compute checksum for segment based files if (IndexFileNames.SEGMENTS_GEN.equals(name) || name.startsWith(IndexFileNames.SEGMENTS)) { computeChecksum = false; } } if (computeChecksum) { out = new BufferedChecksumIndexOutput(out, new Adler32()); } final StoreIndexOutput storeIndexOutput = new StoreIndexOutput(metaData, out, name); success = true; return storeIndexOutput; } } finally { if (!success) { IOUtils.closeWhileHandlingException(out); } } } @Override public IndexInput openInput(String name, IOContext context) throws IOException { ensureOpen(); StoreFileMetaData metaData = filesMetadata.get(name); if (metaData == null) { throw new FileNotFoundException(name); } IndexInput in = metaData.directory().openInput(name, context); boolean success = false; try { // Only for backward comp. since we now use Lucene codec compression if (name.endsWith(".fdt") || name.endsWith(".tvf")) { Compressor compressor = CompressorFactory.compressor(in); if (compressor != null) { in = compressor.indexInput(in); } } success = true; } finally { if (!success) { IOUtils.closeWhileHandlingException(in); } } return in; } @Override public IndexInputSlicer createSlicer(String name, IOContext context) throws IOException { ensureOpen(); StoreFileMetaData metaData = filesMetadata.get(name); if (metaData == null) { throw new FileNotFoundException(name); } // Only for backward comp. since we now use Lucene codec compression if (name.endsWith(".fdt") || name.endsWith(".tvf")) { // rely on the slicer from the base class that uses an input, since they might be compressed... // note, it seems like slicers are only used in compound file format..., so not relevant for now return super.createSlicer(name, context); } return metaData.directory().createSlicer(name, context); } @Override public synchronized void close() throws IOException { isOpen = false; for (Directory delegate : distributor.all()) { delegate.close(); } synchronized (mutex) { filesMetadata = ImmutableOpenMap.of(); files = Strings.EMPTY_ARRAY; } } @Override public Lock makeLock(String name) { return distributor.primary().makeLock(name); } @Override public void clearLock(String name) throws IOException { distributor.primary().clearLock(name); } @Override public void setLockFactory(LockFactory lockFactory) throws IOException { distributor.primary().setLockFactory(lockFactory); } @Override public LockFactory getLockFactory() { return distributor.primary().getLockFactory(); } @Override public String getLockID() { return distributor.primary().getLockID(); } @Override public void sync(Collection<String> names) throws IOException { ensureOpen(); if (sync) { Map<Directory, Collection<String>> map = Maps.newHashMap(); for (String name : names) { StoreFileMetaData metaData = filesMetadata.get(name); if (metaData == null) { throw new FileNotFoundException(name); } Collection<String> dirNames = map.get(metaData.directory()); if (dirNames == null) { dirNames = new ArrayList<String>(); map.put(metaData.directory(), dirNames); } dirNames.add(name); } for (Map.Entry<Directory, Collection<String>> entry : map.entrySet()) { entry.getKey().sync(entry.getValue()); } } for (String name : names) { // write the checksums file when we sync on the segments file (committed) if (!name.equals(IndexFileNames.SEGMENTS_GEN) && name.startsWith(IndexFileNames.SEGMENTS)) { writeChecksums(); break; } } } @Override public void forceSync(String name) throws IOException { sync(ImmutableList.of(name)); } @Override public String toString() { return "store(" + distributor.toString() + ")"; } } class StoreIndexOutput extends IndexOutput { private final StoreFileMetaData metaData; private final IndexOutput out; private final String name; StoreIndexOutput(StoreFileMetaData metaData, IndexOutput delegate, String name) { this.metaData = metaData; this.out = delegate; this.name = name; } @Override public void close() throws IOException { out.close(); String checksum = null; IndexOutput underlying = out; if (underlying instanceof BufferedChecksumIndexOutput) { checksum = Long.toString(((BufferedChecksumIndexOutput) underlying).digest().getValue(), Character.MAX_RADIX); } else if (underlying instanceof ChecksumIndexOutput) { checksum = Long.toString(((ChecksumIndexOutput) underlying).digest().getValue(), Character.MAX_RADIX); } synchronized (mutex) { StoreFileMetaData md = new StoreFileMetaData(name, metaData.directory().fileLength(name), checksum, metaData.directory()); filesMetadata = ImmutableOpenMap.builder(filesMetadata).fPut(name, md).build(); files = filesMetadata.keys().toArray(String.class); } } @Override public void copyBytes(DataInput input, long numBytes) throws IOException { out.copyBytes(input, numBytes); } @Override public long getFilePointer() { return out.getFilePointer(); } @Override public void writeByte(byte b) throws IOException { out.writeByte(b); } @Override public void writeBytes(byte[] b, int offset, int length) throws IOException { out.writeBytes(b, offset, length); } @Override public void flush() throws IOException { out.flush(); } @Override public void seek(long pos) throws IOException { out.seek(pos); } @Override public long length() throws IOException { return out.length(); } @Override public void setLength(long length) throws IOException { out.setLength(length); } @Override public String toString() { return out.toString(); } } }
1no label
src_main_java_org_elasticsearch_index_store_Store.java
789
static final class Fields { static final XContentBuilderString RESPONSES = new XContentBuilderString("responses"); static final XContentBuilderString ERROR = new XContentBuilderString("error"); }
0true
src_main_java_org_elasticsearch_action_percolate_MultiPercolateResponse.java
313
{ @Override protected Update read( NodeRecord node ) { long[] labels = parseLabelsField( node ).get( nodeStore ); Update update = new Update( node.getId(), labels ); if ( !containsAnyLabel( labelIds, labels ) ) { return update; } properties: for ( PropertyBlock property : properties( node ) ) { int propertyKeyId = property.getKeyIndexId(); for ( int sought : propertyKeyIds ) { if ( propertyKeyId == sought ) { update.add( NodePropertyUpdate .add( node.getId(), propertyKeyId, valueOf( property ), labels ) ); continue properties; } } } return update; } @Override protected void process( Update update ) throws FAILURE { labelUpdateVisitor.visit( update.labels ); for ( NodePropertyUpdate propertyUpdate : update ) { propertyUpdateVisitor.visit( propertyUpdate ); } } };
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreIndexStoreView.java
2,495
public interface XContentParser extends Closeable { enum Token { START_OBJECT { @Override public boolean isValue() { return false; } }, END_OBJECT { @Override public boolean isValue() { return false; } }, START_ARRAY { @Override public boolean isValue() { return false; } }, END_ARRAY { @Override public boolean isValue() { return false; } }, FIELD_NAME { @Override public boolean isValue() { return false; } }, VALUE_STRING { @Override public boolean isValue() { return true; } }, VALUE_NUMBER { @Override public boolean isValue() { return true; } }, VALUE_BOOLEAN { @Override public boolean isValue() { return true; } }, // usually a binary value VALUE_EMBEDDED_OBJECT { @Override public boolean isValue() { return true; } }, VALUE_NULL { @Override public boolean isValue() { return false; } }; public abstract boolean isValue(); } enum NumberType { INT, LONG, FLOAT, DOUBLE } XContentType contentType(); Token nextToken() throws IOException; void skipChildren() throws IOException; Token currentToken(); String currentName() throws IOException; Map<String, Object> map() throws IOException; Map<String, Object> mapOrdered() throws IOException; Map<String, Object> mapAndClose() throws IOException; Map<String, Object> mapOrderedAndClose() throws IOException; String text() throws IOException; String textOrNull() throws IOException; BytesRef bytesOrNull() throws IOException; BytesRef bytes() throws IOException; Object objectText() throws IOException; Object objectBytes() throws IOException; boolean hasTextCharacters(); char[] textCharacters() throws IOException; int textLength() throws IOException; int textOffset() throws IOException; Number numberValue() throws IOException; NumberType numberType() throws IOException; /** * Is the number type estimated or not (i.e. an int might actually be a long, its just low enough * to be an int). */ boolean estimatedNumberType(); short shortValue(boolean coerce) throws IOException; int intValue(boolean coerce) throws IOException; long longValue(boolean coerce) throws IOException; float floatValue(boolean coerce) throws IOException; double doubleValue(boolean coerce) throws IOException; short shortValue() throws IOException; int intValue() throws IOException; long longValue() throws IOException; float floatValue() throws IOException; double doubleValue() throws IOException; /** * returns true if the current value is boolean in nature. * values that are considered booleans: * - boolean value (true/false) * - numeric integers (=0 is considered as false, !=0 is true) * - one of the following strings: "true","false","on","off","yes","no","1","0" */ boolean isBooleanValue() throws IOException; boolean booleanValue() throws IOException; byte[] binaryValue() throws IOException; void close(); }
0true
src_main_java_org_elasticsearch_common_xcontent_XContentParser.java
2,213
private class Empty extends DocIdSet { @Override public DocIdSetIterator iterator() throws IOException { return null; } }
0true
src_test_java_org_elasticsearch_common_lucene_search_XBooleanFilterTests.java
1,013
public class OStringSerializerAnyStreamable implements OStringSerializer { public static final OStringSerializerAnyStreamable INSTANCE = new OStringSerializerAnyStreamable(); public static final String NAME = "st"; /** * Re-Create any object if the class has a public constructor that accepts a String as unique parameter. */ public Object fromStream(final String iStream) { if (iStream == null || iStream.length() == 0) // NULL VALUE return null; OSerializableStream instance = null; int propertyPos = iStream.indexOf(':'); int pos = iStream.indexOf(OStreamSerializerHelper.SEPARATOR); if (pos < 0 || propertyPos > -1 && pos > propertyPos) { instance = new ODocument(); pos = -1; } else { final String className = iStream.substring(0, pos); try { final Class<?> clazz = Class.forName(className); instance = (OSerializableStream) clazz.newInstance(); } catch (Exception e) { OLogManager.instance().error(this, "Error on unmarshalling content. Class: " + className, e, OSerializationException.class); } } instance.fromStream(OBase64Utils.decode(iStream.substring(pos + 1))); return instance; } /** * Serialize the class name size + class name + object content * * @param iValue */ public StringBuilder toStream(final StringBuilder iOutput, Object iValue) { if (iValue != null) { if (!(iValue instanceof OSerializableStream)) throw new OSerializationException("Cannot serialize the object since it's not implements the OSerializableStream interface"); OSerializableStream stream = (OSerializableStream) iValue; iOutput.append(iValue.getClass().getName()); iOutput.append(OStreamSerializerHelper.SEPARATOR); iOutput.append(OBase64Utils.encodeBytes(stream.toStream())); } return iOutput; } public String getName() { return NAME; } }
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_string_OStringSerializerAnyStreamable.java
3,688
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { SourceFieldMapper.Builder builder = source(); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { builder.enabled(nodeBooleanValue(fieldNode)); } else if (fieldName.equals("compress") && fieldNode != null) { builder.compress(nodeBooleanValue(fieldNode)); } else if (fieldName.equals("compress_threshold") && fieldNode != null) { if (fieldNode instanceof Number) { builder.compressThreshold(((Number) fieldNode).longValue()); builder.compress(true); } else { builder.compressThreshold(ByteSizeValue.parseBytesSizeValue(fieldNode.toString()).bytes()); builder.compress(true); } } else if ("format".equals(fieldName)) { builder.format(nodeStringValue(fieldNode, null)); } else if (fieldName.equals("includes")) { List<Object> values = (List<Object>) fieldNode; String[] includes = new String[values.size()]; for (int i = 0; i < includes.length; i++) { includes[i] = values.get(i).toString(); } builder.includes(includes); } else if (fieldName.equals("excludes")) { List<Object> values = (List<Object>) fieldNode; String[] excludes = new String[values.size()]; for (int i = 0; i < excludes.length; i++) { excludes[i] = values.get(i).toString(); } builder.excludes(excludes); } } return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_internal_SourceFieldMapper.java
2,046
public final class Message implements Serializable, Element { private final String message; private final Throwable cause; private final List<Object> sources; /** * @since 2.0 */ public Message(List<Object> sources, String message, Throwable cause) { this.sources = ImmutableList.copyOf(sources); this.message = checkNotNull(message, "message"); this.cause = cause; } public Message(Object source, String message) { this(ImmutableList.of(source), message, null); } public Message(String message) { this(ImmutableList.of(), message, null); } public String getSource() { return sources.isEmpty() ? SourceProvider.UNKNOWN_SOURCE.toString() : Errors.convert(sources.get(sources.size() - 1)).toString(); } /** * @since 2.0 */ public List<Object> getSources() { return sources; } /** * Gets the error message text. */ public String getMessage() { return message; } /** * @since 2.0 */ public <T> T acceptVisitor(ElementVisitor<T> visitor) { return visitor.visit(this); } /** * Returns the throwable that caused this message, or {@code null} if this * message was not caused by a throwable. * * @since 2.0 */ public Throwable getCause() { return cause; } @Override public String toString() { return message; } @Override public int hashCode() { return message.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Message)) { return false; } Message e = (Message) o; return message.equals(e.message) && Objects.equal(cause, e.cause) && sources.equals(e.sources); } /** * @since 2.0 */ public void applyTo(Binder binder) { binder.withSource(getSource()).addError(this); } /** * When serialized, we eagerly convert sources to strings. This hurts our formatting, but it * guarantees that the receiving end will be able to read the message. */ private Object writeReplace() throws ObjectStreamException { Object[] sourcesAsStrings = sources.toArray(); for (int i = 0; i < sourcesAsStrings.length; i++) { sourcesAsStrings[i] = Errors.convert(sourcesAsStrings[i]).toString(); } return new Message(ImmutableList.copyOf(sourcesAsStrings), message, cause); } private static final long serialVersionUID = 0; }
0true
src_main_java_org_elasticsearch_common_inject_spi_Message.java
54
public class OAdaptiveLock extends OAbstractLock { private final ReentrantLock lock = new ReentrantLock(); private final boolean concurrent; private final int timeout; private final boolean ignoreThreadInterruption; public OAdaptiveLock() { this.concurrent = true; this.timeout = 0; this.ignoreThreadInterruption = false; } public OAdaptiveLock(final int iTimeout) { this.concurrent = true; this.timeout = iTimeout; this.ignoreThreadInterruption = false; } public OAdaptiveLock(final boolean iConcurrent) { this.concurrent = iConcurrent; this.timeout = 0; this.ignoreThreadInterruption = false; } public OAdaptiveLock(final boolean iConcurrent, final int iTimeout, boolean ignoreThreadInterruption) { this.concurrent = iConcurrent; this.timeout = iTimeout; this.ignoreThreadInterruption = ignoreThreadInterruption; } public void lock() { if (concurrent) if (timeout > 0) { try { if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { if (ignoreThreadInterruption) { // IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN try { if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { // OK, RESET THE INTERRUPTED STATE Thread.currentThread().interrupt(); return; } } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } throw new OTimeoutException("Timeout on acquiring lock against resource of class: " + getClass() + " with timeout=" + timeout); } else lock.lock(); } public boolean tryAcquireLock() { return tryAcquireLock(timeout, TimeUnit.MILLISECONDS); } public boolean tryAcquireLock(final long iTimeout, final TimeUnit iUnit) { if (concurrent) if (timeout > 0) try { return lock.tryLock(iTimeout, iUnit); } catch (InterruptedException e) { throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } else return lock.tryLock(); return true; } public void unlock() { if (concurrent) lock.unlock(); } public boolean isConcurrent() { return concurrent; } public ReentrantLock getUnderlying() { return lock; } }
1no label
commons_src_main_java_com_orientechnologies_common_concur_lock_OAdaptiveLock.java
574
indexStateService.openIndex(updateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new OpenIndexResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to open indices [{}]", t, request.indices()); listener.onFailure(t); } });
1no label
src_main_java_org_elasticsearch_action_admin_indices_open_TransportOpenIndexAction.java
1,615
public class OFixTxTask extends OAbstractRemoteTask { private static final long serialVersionUID = 1L; private List<OAbstractRecordReplicatedTask> tasks = new ArrayList<OAbstractRecordReplicatedTask>(); public OFixTxTask() { } public void add(final OAbstractRecordReplicatedTask iTask) { tasks.add(iTask); } @Override public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) throws Exception { ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "fixing conflicts found during committing transaction against db=%s...", database.getName()); ODatabaseRecordThreadLocal.INSTANCE.set(database); try { for (OAbstractRecordReplicatedTask task : tasks) { task.execute(iServer, iManager, database); } } catch (Exception e) { return Boolean.FALSE; } return Boolean.TRUE; } @Override public QUORUM_TYPE getQuorumType() { return QUORUM_TYPE.NONE; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeInt(tasks.size()); for (OAbstractRecordReplicatedTask task : tasks) out.writeObject(task); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { final int size = in.readInt(); for (int i = 0; i < size; ++i) tasks.add((OAbstractRecordReplicatedTask) in.readObject()); } @Override public String getName() { return "fix_tx"; } }
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_task_OFixTxTask.java
922
static final class ThreadedActionListener<Response> implements ActionListener<Response> { private final ThreadPool threadPool; private final ActionListener<Response> listener; private final ESLogger logger; ThreadedActionListener(ThreadPool threadPool, ActionListener<Response> listener, ESLogger logger) { this.threadPool = threadPool; this.listener = listener; this.logger = logger; } @Override public void onResponse(final Response response) { try { threadPool.generic().execute(new Runnable() { @Override public void run() { try { listener.onResponse(response); } catch (Throwable e) { listener.onFailure(e); } } }); } catch (EsRejectedExecutionException ex) { logger.debug("Can not run threaded action, exectuion rejected [{}] running on current thread", listener); /* we don't care if that takes long since we are shutting down. But if we not respond somebody could wait * for the response on the listener side which could be a remote machine so make sure we push it out there.*/ try { listener.onResponse(response); } catch (Throwable e) { listener.onFailure(e); } } } @Override public void onFailure(final Throwable e) { try { threadPool.generic().execute(new Runnable() { @Override public void run() { listener.onFailure(e); } }); } catch (EsRejectedExecutionException ex) { logger.debug("Can not run threaded action, exectuion rejected for listener [{}] running on current thread", listener); /* we don't care if that takes long since we are shutting down. But if we not respond somebody could wait * for the response on the listener side which could be a remote machine so make sure we push it out there.*/ listener.onFailure(e); } } }
0true
src_main_java_org_elasticsearch_action_support_TransportAction.java
2,025
public abstract class DefaultElementVisitor<V> implements ElementVisitor<V> { /** * Default visit implementation. Returns {@code null}. */ protected V visitOther(Element element) { return null; } public V visit(Message message) { return visitOther(message); } public <T> V visit(Binding<T> binding) { return visitOther(binding); } public V visit(ScopeBinding scopeBinding) { return visitOther(scopeBinding); } public V visit(TypeConverterBinding typeConverterBinding) { return visitOther(typeConverterBinding); } public <T> V visit(ProviderLookup<T> providerLookup) { return visitOther(providerLookup); } public V visit(InjectionRequest injectionRequest) { return visitOther(injectionRequest); } public V visit(StaticInjectionRequest staticInjectionRequest) { return visitOther(staticInjectionRequest); } public V visit(PrivateElements privateElements) { return visitOther(privateElements); } public <T> V visit(MembersInjectorLookup<T> lookup) { return visitOther(lookup); } public V visit(TypeListenerBinding binding) { return visitOther(binding); } }
0true
src_main_java_org_elasticsearch_common_inject_spi_DefaultElementVisitor.java
851
execute(request, new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse result) { try { channel.sendResponse(result); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Exception e1) { logger.warn("Failed to send response for search", e1); } } });
0true
src_main_java_org_elasticsearch_action_search_TransportSearchAction.java
971
public class OBinarySerializerFactory { private final Map<Byte, OBinarySerializer<?>> serializerIdMap = new HashMap<Byte, OBinarySerializer<?>>(); private final Map<Byte, Class<? extends OBinarySerializer<?>>> serializerClassesIdMap = new HashMap<Byte, Class<? extends OBinarySerializer<?>>>(); private final Map<OType, OBinarySerializer<?>> serializerTypeMap = new HashMap<OType, OBinarySerializer<?>>(); /** * Instance of the factory */ public static final OBinarySerializerFactory INSTANCE = new OBinarySerializerFactory(); /** * Size of the type identifier block size */ public static final int TYPE_IDENTIFIER_SIZE = 1; private OBinarySerializerFactory() { // STATELESS SERIALIER registerSerializer(new ONullSerializer(), null); registerSerializer(OBooleanSerializer.INSTANCE, OType.BOOLEAN); registerSerializer(OIntegerSerializer.INSTANCE, OType.INTEGER); registerSerializer(OShortSerializer.INSTANCE, OType.SHORT); registerSerializer(OLongSerializer.INSTANCE, OType.LONG); registerSerializer(OFloatSerializer.INSTANCE, OType.FLOAT); registerSerializer(ODoubleSerializer.INSTANCE, OType.DOUBLE); registerSerializer(ODateTimeSerializer.INSTANCE, OType.DATETIME); registerSerializer(OCharSerializer.INSTANCE, null); registerSerializer(OStringSerializer.INSTANCE, OType.STRING); registerSerializer(OByteSerializer.INSTANCE, OType.BYTE); registerSerializer(ODateSerializer.INSTANCE, OType.DATE); registerSerializer(OLinkSerializer.INSTANCE, OType.LINK); registerSerializer(OCompositeKeySerializer.INSTANCE, null); registerSerializer(OStreamSerializerRID.INSTANCE, null); registerSerializer(OBinaryTypeSerializer.INSTANCE, OType.BINARY); registerSerializer(ODecimalSerializer.INSTANCE, OType.DECIMAL); registerSerializer(OStreamSerializerListRID.INSTANCE, null); registerSerializer(OStreamSerializerOldRIDContainer.INSTANCE, null); registerSerializer(OStreamSerializerSBTreeIndexRIDContainer.INSTANCE, null); registerSerializer(OPhysicalPositionSerializer.INSTANCE, null); registerSerializer(OClusterPositionSerializer.INSTANCE, null); // STATEFUL SERIALIER registerSerializer(OSimpleKeySerializer.ID, OSimpleKeySerializer.class); } public void registerSerializer(final OBinarySerializer<?> iInstance, final OType iType) { if (serializerIdMap.containsKey(iInstance.getId())) throw new IllegalArgumentException("Binary serializer with id " + iInstance.getId() + " has been already registered."); serializerIdMap.put(iInstance.getId(), iInstance); if (iType != null) serializerTypeMap.put(iType, iInstance); } @SuppressWarnings({ "unchecked", "rawtypes" }) public void registerSerializer(final byte iId, final Class<? extends OBinarySerializer> iClass) { if (serializerClassesIdMap.containsKey(iId)) throw new IllegalStateException("Serializer with id " + iId + " has been already registered."); serializerClassesIdMap.put(iId, (Class<? extends OBinarySerializer<?>>) iClass); } /** * Obtain OBinarySerializer instance by it's id. * * @param identifier * is serializes identifier. * @return OBinarySerializer instance. */ public OBinarySerializer<?> getObjectSerializer(final byte identifier) { OBinarySerializer<?> impl = serializerIdMap.get(identifier); if (impl == null) { final Class<? extends OBinarySerializer<?>> cls = serializerClassesIdMap.get(identifier); if (cls != null) try { impl = cls.newInstance(); } catch (Exception e) { OLogManager.instance().error(this, "Cannot create an instance of class %s invoking the empty constructor", cls); } } return impl; } /** * Obtain OBinarySerializer realization for the OType * * @param type * is the OType to obtain serializer algorithm for * @return OBinarySerializer instance */ public OBinarySerializer<?> getObjectSerializer(final OType type) { return serializerTypeMap.get(type); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_binary_OBinarySerializerFactory.java
947
@Repository("blFulfillmentGroupDao") public class FulfillmentGroupDaoImpl implements FulfillmentGroupDao { @PersistenceContext(unitName = "blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; @Override public FulfillmentGroup save(final FulfillmentGroup fulfillmentGroup) { return em.merge(fulfillmentGroup); } @Override public FulfillmentGroup readFulfillmentGroupById(final Long fulfillmentGroupId) { return em.find(FulfillmentGroupImpl.class, fulfillmentGroupId); } @Override public FulfillmentGroupImpl readDefaultFulfillmentGroupForOrder(final Order order) { final Query query = em.createNamedQuery("BC_READ_DEFAULT_FULFILLMENT_GROUP_BY_ORDER_ID"); query.setParameter("orderId", order.getId()); @SuppressWarnings("unchecked") List<FulfillmentGroupImpl> fulfillmentGroups = query.getResultList(); return fulfillmentGroups == null || fulfillmentGroups.isEmpty() ? null : fulfillmentGroups.get(0); } @Override public void delete(FulfillmentGroup fulfillmentGroup) { if (!em.contains(fulfillmentGroup)) { fulfillmentGroup = readFulfillmentGroupById(fulfillmentGroup.getId()); } em.remove(fulfillmentGroup); } @Override public FulfillmentGroup createDefault() { final FulfillmentGroup fg = ((FulfillmentGroup) entityConfiguration.createEntityInstance("org.broadleafcommerce.core.order.domain.FulfillmentGroup")); fg.setPrimary(true); return fg; } @Override public FulfillmentGroup create() { final FulfillmentGroup fg = ((FulfillmentGroup) entityConfiguration.createEntityInstance("org.broadleafcommerce.core.order.domain.FulfillmentGroup")); return fg; } @Override public FulfillmentGroupFee createFulfillmentGroupFee() { return ((FulfillmentGroupFee) entityConfiguration.createEntityInstance("org.broadleafcommerce.core.order.domain.FulfillmentGroupFee")); } @SuppressWarnings("unchecked") @Override public List<FulfillmentGroup> readUnfulfilledFulfillmentGroups(int start, int maxResults) { Query query = em.createNamedQuery("BC_READ_UNFULFILLED_FULFILLMENT_GROUP_ASC"); query.setFirstResult(start); query.setMaxResults(maxResults); return query.getResultList(); } @SuppressWarnings("unchecked") @Override public List<FulfillmentGroup> readPartiallyFulfilledFulfillmentGroups(int start, int maxResults) { Query query = em.createNamedQuery("BC_READ_PARTIALLY_FULFILLED_FULFILLMENT_GROUP_ASC"); query.setFirstResult(start); query.setMaxResults(maxResults); return query.getResultList(); } @SuppressWarnings("unchecked") @Override public List<FulfillmentGroup> readUnprocessedFulfillmentGroups(int start, int maxResults) { Query query = em.createNamedQuery("BC_READ_UNPROCESSED_FULFILLMENT_GROUP_ASC"); query.setFirstResult(start); query.setMaxResults(maxResults); return query.getResultList(); } @SuppressWarnings("unchecked") @Override public List<FulfillmentGroup> readFulfillmentGroupsByStatus( FulfillmentGroupStatusType status, int start, int maxResults, boolean ascending) { Query query = null; if (ascending) { query = em.createNamedQuery("BC_READ_FULFILLMENT_GROUP_BY_STATUS_ASC"); } else { query = em.createNamedQuery("BC_READ_FULFILLMENT_GROUP_BY_STATUS_DESC"); } query.setParameter("status", status.getType()); query.setFirstResult(start); query.setMaxResults(maxResults); return query.getResultList(); } @Override public List<FulfillmentGroup> readFulfillmentGroupsByStatus( FulfillmentGroupStatusType status, int start, int maxResults) { return readFulfillmentGroupsByStatus(status, start, maxResults, true); } @SuppressWarnings("unchecked") @Override public Integer readNextFulfillmentGroupSequnceForOrder(Order order) { Query query = em.createNamedQuery("BC_READ_MAX_FULFILLMENT_GROUP_SEQUENCE"); query.setParameter("orderId", order.getId()); List<Integer> max = query.getResultList(); if (max != null && !max.isEmpty()) { Integer maxNumber = max.get(0); if (maxNumber == null) { return 1; } return maxNumber + 1; } return 1; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_dao_FulfillmentGroupDaoImpl.java
168
public abstract class SpeedTestMonoThread extends SpeedTestAbstract { protected SpeedTestMonoThread() { } protected SpeedTestMonoThread(final long iCycles) { super(iCycles); } }
0true
commons_src_test_java_com_orientechnologies_common_test_SpeedTestMonoThread.java
833
static final class Fields { static final XContentBuilderString _SCROLL_ID = new XContentBuilderString("_scroll_id"); static final XContentBuilderString _SHARDS = new XContentBuilderString("_shards"); static final XContentBuilderString TOTAL = new XContentBuilderString("total"); static final XContentBuilderString SUCCESSFUL = new XContentBuilderString("successful"); static final XContentBuilderString FAILED = new XContentBuilderString("failed"); static final XContentBuilderString FAILURES = new XContentBuilderString("failures"); static final XContentBuilderString STATUS = new XContentBuilderString("status"); static final XContentBuilderString INDEX = new XContentBuilderString("index"); static final XContentBuilderString SHARD = new XContentBuilderString("shard"); static final XContentBuilderString REASON = new XContentBuilderString("reason"); static final XContentBuilderString TOOK = new XContentBuilderString("took"); static final XContentBuilderString TIMED_OUT = new XContentBuilderString("timed_out"); }
0true
src_main_java_org_elasticsearch_action_search_SearchResponse.java
2,121
public class JdkESLoggerFactory extends ESLoggerFactory { @Override protected ESLogger rootLogger() { return getLogger(""); } @Override protected ESLogger newInstance(String prefix, String name) { final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name); return new JdkESLogger(prefix, name, logger); } }
0true
src_main_java_org_elasticsearch_common_logging_jdk_JdkESLoggerFactory.java
1,564
public class VerticesMap { public static final String PROCESS_EDGES = Tokens.makeNamespace(VerticesMap.class) + ".processEdges"; public enum Counters { VERTICES_PROCESSED, EDGES_PROCESSED } public static Configuration createConfiguration(final boolean processEdges) { final Configuration configuration = new EmptyConfiguration(); configuration.setBoolean(PROCESS_EDGES, processEdges); return configuration; } public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> { private boolean processEdges; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.processEdges = context.getConfiguration().getBoolean(PROCESS_EDGES, true); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { value.startPath(); long edgesProcessed = 0; if (this.processEdges) { for (final Edge edge : value.getEdges(Direction.BOTH)) { ((StandardFaunusEdge) edge).clearPaths(); edgesProcessed++; } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_PROCESSED, edgesProcessed); DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L); context.write(NullWritable.get(), value); } } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_VerticesMap.java
37
public class MemberNameCompletions { static void addMemberNameProposals(final int offset, final CeylonParseController cpc, final Node node, final List<ICompletionProposal> result) { final Integer startIndex2 = node.getStartIndex(); new Visitor() { @Override public void visit(Tree.StaticMemberOrTypeExpression that) { Tree.TypeArguments tal = that.getTypeArguments(); Integer startIndex = tal==null ? null : tal.getStartIndex(); if (startIndex!=null && startIndex2!=null && startIndex.intValue()==startIndex2.intValue()) { addMemberNameProposal(offset, "", that, result); } super.visit(that); } public void visit(Tree.SimpleType that) { Tree.TypeArgumentList tal = that.getTypeArgumentList(); Integer startIndex = tal==null ? null : tal.getStartIndex(); if (startIndex!=null && startIndex2!=null && startIndex.intValue()==startIndex2.intValue()) { addMemberNameProposal(offset, "", that, result); } super.visit(that); } }.visit(cpc.getRootNode()); } static void addMemberNameProposal(int offset, String prefix, Node node, List<ICompletionProposal> result) { Set<String> proposals = new LinkedHashSet<String>(); if (node instanceof Tree.TypeDeclaration) { //TODO: dictionary completions? return; } else if (node instanceof Tree.TypedDeclaration) { Tree.TypedDeclaration td = (Tree.TypedDeclaration) node; Tree.Type type = td.getType(); Tree.Identifier id = td.getIdentifier(); if (id==null || offset>=id.getStartIndex() && offset<=id.getStopIndex()+1) { node = type; } else { node = null; } } if (node instanceof Tree.SimpleType) { Tree.SimpleType simpleType = (Tree.SimpleType) node; addProposals(proposals, simpleType.getIdentifier(), simpleType.getTypeModel()); } else if (node instanceof Tree.BaseTypeExpression) { Tree.BaseTypeExpression typeExpression = (Tree.BaseTypeExpression) node; addProposals(proposals, typeExpression.getIdentifier(), getLiteralType(node, typeExpression)); } else if (node instanceof Tree.QualifiedTypeExpression) { Tree.QualifiedTypeExpression typeExpression = (Tree.QualifiedTypeExpression) node; addProposals(proposals, typeExpression.getIdentifier(), getLiteralType(node, typeExpression)); } else if (node instanceof Tree.OptionalType) { Tree.StaticType et = ((Tree.OptionalType) node).getDefiniteType(); if (et instanceof Tree.SimpleType) { addProposals(proposals, ((Tree.SimpleType) et).getIdentifier(), ((Tree.OptionalType) node).getTypeModel()); } } else if (node instanceof Tree.SequenceType) { Tree.StaticType et = ((Tree.SequenceType) node).getElementType(); if (et instanceof Tree.SimpleType) { addPluralProposals(proposals, ((Tree.SimpleType) et).getIdentifier(), ((Tree.SequenceType) node).getTypeModel()); } proposals.add("sequence"); } else if (node instanceof Tree.IterableType) { Tree.Type et = ((Tree.IterableType) node).getElementType(); if (et instanceof Tree.SequencedType) { et = ((Tree.SequencedType) et).getType(); } if (et instanceof Tree.SimpleType) { addPluralProposals(proposals, ((Tree.SimpleType) et).getIdentifier(), ((Tree.IterableType) node).getTypeModel()); } proposals.add("iterable"); } else if (node instanceof Tree.TupleType) { List<Type> ets = ((Tree.TupleType) node).getElementTypes(); if (ets.size()==1) { Tree.Type et = ets.get(0); if (et instanceof Tree.SequencedType) { et = ((Tree.SequencedType) et).getType(); } if (et instanceof Tree.SimpleType) { addPluralProposals(proposals, ((Tree.SimpleType) et).getIdentifier(), ((Tree.TupleType) node).getTypeModel()); } proposals.add("sequence"); } } /*if (suggestedName!=null) { suggestedName = lower(suggestedName); String unquoted = prefix.startsWith("\\i")||prefix.startsWith("\\I") ? prefix.substring(2) : prefix; if (!suggestedName.startsWith(unquoted)) { suggestedName = prefix + upper(suggestedName); } result.add(new CompletionProposal(offset, prefix, LOCAL_NAME, suggestedName, escape(suggestedName))); }*/ /*if (proposals.isEmpty()) { proposals.add("it"); }*/ for (String name: proposals) { String unquotedPrefix = prefix.startsWith("\\i") ? prefix.substring(2) : prefix; if (name.startsWith(unquotedPrefix)) { String unquotedName = name.startsWith("\\i") ? name.substring(2) : name; result.add(new CompletionProposal(offset, prefix, LOCAL_NAME, unquotedName, name)); } } } private static ProducedType getLiteralType(Node node, Tree.StaticMemberOrTypeExpression typeExpression) { Unit unit = node.getUnit(); ProducedType pt = typeExpression.getTypeModel(); return unit.isCallableType(pt) ? unit.getCallableReturnType(pt) : pt; } private static void addProposals(Set<String> proposals, Tree.Identifier identifier, ProducedType type) { Nodes.addNameProposals(proposals, false, identifier.getText()); if (!isTypeUnknown(type) && identifier.getUnit().isIterableType(type)) { addPluralProposals(proposals, identifier, type); } } private static void addPluralProposals(Set<String> proposals, Tree.Identifier identifier, ProducedType type) { Nodes.addNameProposals(proposals, true, identifier.getUnit().getIteratedType(type) .getDeclaration().getName()); } /*private static String lower(String suggestedName) { return Character.toLowerCase(suggestedName.charAt(0)) + suggestedName.substring(1); } private static String upper(String suggestedName) { return Character.toUpperCase(suggestedName.charAt(0)) + suggestedName.substring(1); }*/ }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_MemberNameCompletions.java
116
public class OStringForwardReader implements CharSequence { private final BufferedReader input; private char[] buffer = new char[DEFAULT_SIZE]; private long start = -1; private long end = -1; private long current = 0; private long size = 0; private static final int DEFAULT_SIZE = 1000; public OStringForwardReader(final InputStream iInput) { this.input = new BufferedReader(new InputStreamReader(iInput)); } public OStringForwardReader(final Reader iReader) { this.input = new BufferedReader(iReader); } public OStringForwardReader(final File file) throws FileNotFoundException { this(new FileInputStream(file)); size = file.length(); } public char charAt(final int iIndex) { if (iIndex < start) throw new IllegalStateException("Cannot read backward"); if (iIndex >= end) read(iIndex); if (iIndex > current) current = iIndex; return buffer[(int) (iIndex - start)]; } private void read(final int iIndex) { try { // JUMP CHARACTERS for (long i = end; i < iIndex - 1; ++i) input.read(); start = iIndex; final int byteRead = input.read(buffer); end = start + byteRead; current = start; } catch (IOException e) { throw new OIOException("Error in read", e); } } public void close() throws IOException { if (input != null) input.close(); start = end = -1; current = size = 0; } public boolean ready() { try { return current < end || input.ready(); } catch (IOException e) { throw new OIOException("Error in ready", e); } } public int length() { return (int) size; } public CharSequence subSequence(final int start, final int end) { throw new UnsupportedOperationException(); } public long getPosition() { return current; } @Override public String toString() { return (start > 0 ? "..." : "") + new String(buffer) + (ready() ? "..." : ""); } public int indexOf(final char iToFind) { for (int i = (int) current; i < size; ++i) { if (charAt(i) == iToFind) return i; } return -1; } public String subString(int iOffset, final char iToFind, boolean iIncluded) { StringBuilder buffer = new StringBuilder(); char c; for (int i = iOffset; i < size; ++i) { c = charAt(i); if (c == iToFind) { if (iIncluded) buffer.append(c); return buffer.toString(); } buffer.append(c); } buffer.setLength(0); return null; } }
0true
commons_src_main_java_com_orientechnologies_common_parser_OStringForwardReader.java