Unnamed: 0
int64
0
6.45k
func
stringlengths
37
143k
target
class label
2 classes
project
stringlengths
33
157
2,352
return new Combiner<KeyIn, ValueIn, List<ValueIn>>() { private final List<ValueIn> values = new ArrayList<ValueIn>(); @Override public void combine(KeyIn key, ValueIn value) { values.add(value); } @Override public List<ValueIn> finalizeChunk() { List<ValueIn> values = new ArrayList<ValueIn>(this.values); this.values.clear(); return values; } };
1no label
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_task_DefaultContext.java
513
public class MonthType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, MonthType> TYPES = new LinkedHashMap<String, MonthType>(); public static final MonthType JANUARY = new MonthType("1", "January"); public static final MonthType FEBRUARY = new MonthType("2", "February"); public static final MonthType MARCH = new MonthType("3", "March"); public static final MonthType APRIL = new MonthType("4", "April"); public static final MonthType MAY = new MonthType("5", "May"); public static final MonthType JUNE = new MonthType("6", "June"); public static final MonthType JULY = new MonthType("7", "July"); public static final MonthType AUGUST = new MonthType("8", "August"); public static final MonthType SEPTEMBER = new MonthType("9", "September"); public static final MonthType OCTOBER = new MonthType("10", "October"); public static final MonthType NOVEMBER = new MonthType("11", "November"); public static final MonthType DECEMBER = new MonthType("12", "December"); public static MonthType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public MonthType() { //do nothing } public MonthType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } else { throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MonthType other = (MonthType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
common_src_main_java_org_broadleafcommerce_common_time_MonthType.java
554
public class GetMappingsRequest extends ClusterInfoRequest<GetMappingsRequest> { @Override public ActionRequestValidationException validate() { return null; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetMappingsRequest.java
2,109
public class DateMathParser { private final FormatDateTimeFormatter dateTimeFormatter; private final TimeUnit timeUnit; public DateMathParser(FormatDateTimeFormatter dateTimeFormatter, TimeUnit timeUnit) { this.dateTimeFormatter = dateTimeFormatter; this.timeUnit = timeUnit; } public long parse(String text, long now) { return parse(text, now, false); } public long parseRoundCeil(String text, long now) { return parse(text, now, true); } public long parse(String text, long now, boolean roundCeil) { long time; String mathString; if (text.startsWith("now")) { time = now; mathString = text.substring("now".length()); } else { int index = text.indexOf("||"); String parseString; if (index == -1) { parseString = text; mathString = ""; // nothing else } else { parseString = text.substring(0, index); mathString = text.substring(index + 2); } if (roundCeil) { time = parseRoundCeilStringValue(parseString); } else { time = parseStringValue(parseString); } } if (mathString.isEmpty()) { return time; } return parseMath(mathString, time, roundCeil); } private long parseMath(String mathString, long time, boolean roundUp) throws ElasticsearchParseException { MutableDateTime dateTime = new MutableDateTime(time, DateTimeZone.UTC); try { for (int i = 0; i < mathString.length(); ) { char c = mathString.charAt(i++); int type; if (c == '/') { type = 0; } else if (c == '+') { type = 1; } else if (c == '-') { type = 2; } else { throw new ElasticsearchParseException("operator not supported for date math [" + mathString + "]"); } int num; if (!Character.isDigit(mathString.charAt(i))) { num = 1; } else { int numFrom = i; while (Character.isDigit(mathString.charAt(i))) { i++; } num = Integer.parseInt(mathString.substring(numFrom, i)); } if (type == 0) { // rounding is only allowed on whole numbers if (num != 1) { throw new ElasticsearchParseException("rounding `/` can only be used on single unit types [" + mathString + "]"); } } char unit = mathString.charAt(i++); switch (unit) { case 'y': if (type == 0) { if (roundUp) { dateTime.yearOfCentury().roundCeiling(); } else { dateTime.yearOfCentury().roundFloor(); } } else if (type == 1) { dateTime.addYears(num); } else if (type == 2) { dateTime.addYears(-num); } break; case 'M': if (type == 0) { if (roundUp) { dateTime.monthOfYear().roundCeiling(); } else { dateTime.monthOfYear().roundFloor(); } } else if (type == 1) { dateTime.addMonths(num); } else if (type == 2) { dateTime.addMonths(-num); } break; case 'w': if (type == 0) { if (roundUp) { dateTime.weekOfWeekyear().roundCeiling(); } else { dateTime.weekOfWeekyear().roundFloor(); } } else if (type == 1) { dateTime.addWeeks(num); } else if (type == 2) { dateTime.addWeeks(-num); } break; case 'd': if (type == 0) { if (roundUp) { dateTime.dayOfMonth().roundCeiling(); } else { dateTime.dayOfMonth().roundFloor(); } } else if (type == 1) { dateTime.addDays(num); } else if (type == 2) { dateTime.addDays(-num); } break; case 'h': case 'H': if (type == 0) { if (roundUp) { dateTime.hourOfDay().roundCeiling(); } else { dateTime.hourOfDay().roundFloor(); } } else if (type == 1) { dateTime.addHours(num); } else if (type == 2) { dateTime.addHours(-num); } break; case 'm': if (type == 0) { if (roundUp) { dateTime.minuteOfHour().roundCeiling(); } else { dateTime.minuteOfHour().roundFloor(); } } else if (type == 1) { dateTime.addMinutes(num); } else if (type == 2) { dateTime.addMinutes(-num); } break; case 's': if (type == 0) { if (roundUp) { dateTime.secondOfMinute().roundCeiling(); } else { dateTime.secondOfMinute().roundFloor(); } } else if (type == 1) { dateTime.addSeconds(num); } else if (type == 2) { dateTime.addSeconds(-num); } break; default: throw new ElasticsearchParseException("unit [" + unit + "] not supported for date math [" + mathString + "]"); } } } catch (Exception e) { if (e instanceof ElasticsearchParseException) { throw (ElasticsearchParseException) e; } throw new ElasticsearchParseException("failed to parse date math [" + mathString + "]"); } return dateTime.getMillis(); } private long parseStringValue(String value) { try { return dateTimeFormatter.parser().parseMillis(value); } catch (RuntimeException e) { try { long time = Long.parseLong(value); return timeUnit.toMillis(time); } catch (NumberFormatException e1) { throw new ElasticsearchParseException("failed to parse date field [" + value + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number", e); } } } private long parseRoundCeilStringValue(String value) { try { // we create a date time for inclusive upper range, we "include" by default the day level data // so something like 2011-01-01 will include the full first day of 2011. // we also use 1970-01-01 as the base for it so we can handle searches like 10:12:55 (just time) // since when we index those, the base is 1970-01-01 MutableDateTime dateTime = new MutableDateTime(1970, 1, 1, 23, 59, 59, 999, DateTimeZone.UTC); int location = dateTimeFormatter.parser().parseInto(dateTime, value, 0); // if we parsed all the string value, we are good if (location == value.length()) { return dateTime.getMillis(); } // if we did not manage to parse, or the year is really high year which is unreasonable // see if its a number if (location <= 0 || dateTime.getYear() > 5000) { try { long time = Long.parseLong(value); return timeUnit.toMillis(time); } catch (NumberFormatException e1) { throw new ElasticsearchParseException("failed to parse date field [" + value + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number"); } } return dateTime.getMillis(); } catch (RuntimeException e) { try { long time = Long.parseLong(value); return timeUnit.toMillis(time); } catch (NumberFormatException e1) { throw new ElasticsearchParseException("failed to parse date field [" + value + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number", e); } } } }
1no label
src_main_java_org_elasticsearch_common_joda_DateMathParser.java
1,165
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_GIFT_CARD_PAYMENT") public class GiftCardPaymentInfoImpl implements GiftCardPaymentInfo { private static final long serialVersionUID = 1L; protected GiftCardPaymentInfoImpl() { // do not allow direct instantiation -- must at least be package private // for bytecode instrumentation // this complies with JPA specification requirements for entity // construction } @Transient protected EncryptionModule encryptionModule; @Id @GeneratedValue(generator = "GiftCardPaymentId") @GenericGenerator( name="GiftCardPaymentId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="GiftCardPaymentInfoImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.GiftCardPaymentInfoImpl") } ) @Column(name = "PAYMENT_ID") protected Long id; @Column(name = "REFERENCE_NUMBER", nullable = false) @Index(name="GIFTCARD_INDEX", columnNames={"REFERENCE_NUMBER"}) protected String referenceNumber; @Column(name = "PAN", nullable = false) protected String pan; @Column(name = "PIN") protected String pin; @Override public Long getId() { return id; } @Override public String getPan() { return encryptionModule.decrypt(pan); } @Override public String getPin() { return encryptionModule.decrypt(pin); } @Override public void setId(Long id) { this.id = id; } @Override public void setPan(String pan) { this.pan = encryptionModule.encrypt(pan); } @Override public void setPin(String pin) { this.pin = encryptionModule.encrypt(pin); } @Override public String getReferenceNumber() { return referenceNumber; } @Override public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } @Override public EncryptionModule getEncryptionModule() { return encryptionModule; } @Override public void setEncryptionModule(EncryptionModule encryptionModule) { this.encryptionModule = encryptionModule; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((pan == null) ? 0 : pan.hashCode()); result = prime * result + ((pin == null) ? 0 : pin.hashCode()); result = prime * result + ((referenceNumber == null) ? 0 : referenceNumber.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; GiftCardPaymentInfoImpl other = (GiftCardPaymentInfoImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (pan == null) { if (other.pan != null) return false; } else if (!pan.equals(other.pan)) return false; if (pin == null) { if (other.pin != null) return false; } else if (!pin.equals(other.pin)) return false; if (referenceNumber == null) { if (other.referenceNumber != null) return false; } else if (!referenceNumber.equals(other.referenceNumber)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_GiftCardPaymentInfoImpl.java
290
public class ORubyScriptFormatter implements OScriptFormatter { public String getFunctionDefinition(final OFunction f) { final StringBuilder fCode = new StringBuilder(); fCode.append("def "); fCode.append(f.getName()); fCode.append('('); int i = 0; if (f.getParameters() != null) for (String p : f.getParameters()) { if (i++ > 0) fCode.append(','); fCode.append(p); } fCode.append(")\n"); final Scanner scanner = new Scanner(f.getCode()); try { scanner.useDelimiter("\n").skip("\r"); while (scanner.hasNext()) { fCode.append('\t'); fCode.append(scanner.next()); } } finally { scanner.close(); } fCode.append("\nend\n"); return fCode.toString(); } @Override public String getFunctionInvoke(final OFunction iFunction, final Object[] iArgs) { final StringBuilder code = new StringBuilder(); code.append(iFunction.getName()); code.append('('); if (iArgs != null) { int i = 0; for (Object a : iArgs) { if (i++ > 0) code.append(','); code.append(a); } } code.append(");"); return code.toString(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_command_script_formatter_ORubyScriptFormatter.java
4,520
class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { TimeValue interval = settings.getAsTime(INDICES_TTL_INTERVAL, IndicesTTLService.this.interval); if (!interval.equals(IndicesTTLService.this.interval)) { logger.info("updating indices.ttl.interval from [{}] to [{}]", IndicesTTLService.this.interval, interval); IndicesTTLService.this.interval = interval; } } }
1no label
src_main_java_org_elasticsearch_indices_ttl_IndicesTTLService.java
32
public class StateMachines implements MessageProcessor, MessageSource { private final Logger logger = LoggerFactory.getLogger( StateMachines.class ); private final MessageSender sender; private DelayedDirectExecutor executor; private Executor stateMachineExecutor; private Timeouts timeouts; private final Map<Class<? extends MessageType>, StateMachine> stateMachines = new LinkedHashMap<Class<? extends MessageType>, StateMachine>(); private final List<MessageProcessor> outgoingProcessors = new ArrayList<MessageProcessor>(); private final OutgoingMessageHolder outgoing; // This is used to ensure fairness of message delivery private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock( true ); private final String instanceIdHeaderValue; public StateMachines( MessageSource source, final MessageSender sender, Timeouts timeouts, DelayedDirectExecutor executor, Executor stateMachineExecutor, InstanceId instanceId ) { this.sender = sender; this.executor = executor; this.stateMachineExecutor = stateMachineExecutor; this.timeouts = timeouts; this.instanceIdHeaderValue = instanceId.toString(); outgoing = new OutgoingMessageHolder(); timeouts.addMessageProcessor( this ); source.addMessageProcessor( this ); } public Timeouts getTimeouts() { return timeouts; } public synchronized void addStateMachine( StateMachine stateMachine ) { stateMachines.put( stateMachine.getMessageType(), stateMachine ); } public synchronized void removeStateMachine( StateMachine stateMachine ) { stateMachines.remove( stateMachine.getMessageType() ); } public Iterable<StateMachine> getStateMachines() { return stateMachines.values(); } @Override public void addMessageProcessor( MessageProcessor messageProcessor ) { outgoingProcessors.add( messageProcessor ); } public OutgoingMessageHolder getOutgoing() { return outgoing; } @Override public boolean process( final Message<? extends MessageType> message ) { stateMachineExecutor.execute( new Runnable() { OutgoingMessageHolder temporaryOutgoing = new OutgoingMessageHolder(); @Override public void run() { lock.writeLock().lock(); try { // Lock timeouts while we are processing the message synchronized ( timeouts ) { StateMachine stateMachine = stateMachines.get( message.getMessageType().getClass() ); if ( stateMachine == null ) { return; // No StateMachine registered for this MessageType type - Ignore this } stateMachine.handle( message, temporaryOutgoing ); Message<? extends MessageType> tempMessage; while ((tempMessage = temporaryOutgoing.nextOutgoingMessage()) != null) { outgoing.offer( tempMessage ); } // Process and send messages // Allow state machines to send messages to each other as well in this loop Message<? extends MessageType> outgoingMessage; List<Message<? extends MessageType>> toSend = new LinkedList<Message<? extends MessageType>>(); try { while ( ( outgoingMessage = outgoing.nextOutgoingMessage() ) != null ) { message.copyHeadersTo( outgoingMessage, CONVERSATION_ID, CREATED_BY ); for ( MessageProcessor outgoingProcessor : outgoingProcessors ) { try { if ( !outgoingProcessor.process( outgoingMessage ) ) { break; } } catch ( Throwable e ) { logger.warn( "Outgoing message processor threw exception", e ); } } if ( outgoingMessage.hasHeader( Message.TO ) ) { outgoingMessage.setHeader( Message.INSTANCE_ID, instanceIdHeaderValue ); toSend.add( outgoingMessage ); } else { // Deliver internally if possible StateMachine internalStatemachine = stateMachines.get( outgoingMessage.getMessageType() .getClass() ); if ( internalStatemachine != null ) { internalStatemachine.handle( (Message) outgoingMessage, temporaryOutgoing ); while ((tempMessage = temporaryOutgoing.nextOutgoingMessage()) != null) { outgoing.offer( tempMessage ); } } } } if ( !toSend.isEmpty() ) // the check is necessary, sender may not have started yet { sender.process( toSend ); } } catch ( Exception e ) { logger.warn( "Error processing message " + message, e ); } } } finally { lock.writeLock().unlock(); } // Before returning, process delayed executions so that they are done before returning // This will effectively trigger all notifications created by contexts executor.drain(); } } ); return true; } public void addStateTransitionListener( StateTransitionListener stateTransitionListener ) { for ( StateMachine stateMachine : stateMachines.values() ) { stateMachine.addStateTransitionListener( stateTransitionListener ); } } public void removeStateTransitionListener( StateTransitionListener stateTransitionListener ) { for ( StateMachine stateMachine : stateMachines.values() ) { stateMachine.removeStateTransitionListener( stateTransitionListener ); } } @Override public String toString() { List<String> states = new ArrayList<String>(); for ( StateMachine stateMachine : stateMachines.values() ) { states.add( stateMachine.getState().getClass().getSuperclass().getSimpleName() + ":" + stateMachine .getState().toString() ); } return states.toString(); } public StateMachine getStateMachine( Class<? extends MessageType> messageType ) { return stateMachines.get( messageType ); } private class OutgoingMessageHolder implements MessageHolder { private Deque<Message<? extends MessageType>> outgoingMessages = new ArrayDeque<Message<? extends MessageType>>(); @Override public synchronized void offer( Message<? extends MessageType> message ) { outgoingMessages.addFirst( message ); } public synchronized Message<? extends MessageType> nextOutgoingMessage() { return outgoingMessages.pollFirst(); } } }
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_StateMachines.java
153
public interface ArchivedStructuredContentPublisher { void processStructuredContentArchive(StructuredContent sc, String baseTypeKey, String baseNameKey); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_message_ArchivedStructuredContentPublisher.java
144
public final class HazelcastClient implements HazelcastInstance { static { OutOfMemoryErrorDispatcher.setClientHandler(new ClientOutOfMemoryHandler()); } private static final AtomicInteger CLIENT_ID = new AtomicInteger(); private static final ConcurrentMap<Integer, HazelcastClientProxy> CLIENTS = new ConcurrentHashMap<Integer, HazelcastClientProxy>(5); private final int id = CLIENT_ID.getAndIncrement(); private final String instanceName; private final ClientConfig config; private final ThreadGroup threadGroup; private final LifecycleServiceImpl lifecycleService; private final SerializationServiceImpl serializationService; private final ClientConnectionManager connectionManager; private final ClientClusterServiceImpl clusterService; private final ClientPartitionServiceImpl partitionService; private final ClientInvocationServiceImpl invocationService; private final ClientExecutionServiceImpl executionService; private final ClientTransactionManager transactionManager; private final ProxyManager proxyManager; private final ConcurrentMap<String, Object> userContext; private final LoadBalancer loadBalancer; public final ClientProperties clientProperties; private HazelcastClient(ClientConfig config) { this.config = config; final GroupConfig groupConfig = config.getGroupConfig(); instanceName = "hz.client_" + id + (groupConfig != null ? "_" + groupConfig.getName() : ""); threadGroup = new ThreadGroup(instanceName); lifecycleService = new LifecycleServiceImpl(this); clientProperties = new ClientProperties(config); SerializationService ss; try { String partitioningStrategyClassName = System.getProperty(GroupProperties.PROP_PARTITIONING_STRATEGY_CLASS); final PartitioningStrategy partitioningStrategy; if (partitioningStrategyClassName != null && partitioningStrategyClassName.length() > 0) { partitioningStrategy = ClassLoaderUtil.newInstance(config.getClassLoader(), partitioningStrategyClassName); } else { partitioningStrategy = new DefaultPartitioningStrategy(); } ss = new SerializationServiceBuilder() .setManagedContext(new HazelcastClientManagedContext(this, config.getManagedContext())) .setClassLoader(config.getClassLoader()) .setConfig(config.getSerializationConfig()) .setPartitioningStrategy(partitioningStrategy) .build(); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } serializationService = (SerializationServiceImpl) ss; proxyManager = new ProxyManager(this); executionService = new ClientExecutionServiceImpl(instanceName, threadGroup, Thread.currentThread().getContextClassLoader(), config.getExecutorPoolSize()); transactionManager = new ClientTransactionManager(this); LoadBalancer lb = config.getLoadBalancer(); if (lb == null) { lb = new RoundRobinLB(); } loadBalancer = lb; connectionManager = new ClientConnectionManagerImpl(this, loadBalancer); clusterService = new ClientClusterServiceImpl(this); invocationService = new ClientInvocationServiceImpl(this); userContext = new ConcurrentHashMap<String, Object>(); proxyManager.init(config); partitionService = new ClientPartitionServiceImpl(this); } public static HazelcastInstance newHazelcastClient() { return newHazelcastClient(new XmlClientConfigBuilder().build()); } public static HazelcastInstance newHazelcastClient(ClientConfig config) { if (config == null) { config = new XmlClientConfigBuilder().build(); } final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); HazelcastClientProxy proxy; try { Thread.currentThread().setContextClassLoader(HazelcastClient.class.getClassLoader()); final HazelcastClient client = new HazelcastClient(config); client.start(); OutOfMemoryErrorDispatcher.register(client); proxy = new HazelcastClientProxy(client); CLIENTS.put(client.id, proxy); } finally { Thread.currentThread().setContextClassLoader(tccl); } return proxy; } public static Collection<HazelcastInstance> getAllHazelcastClients() { return Collections.<HazelcastInstance>unmodifiableCollection(CLIENTS.values()); } public static void shutdownAll() { for (HazelcastClientProxy proxy : CLIENTS.values()) { try { proxy.client.getLifecycleService().shutdown(); } catch (Exception ignored) { } proxy.client = null; } CLIENTS.clear(); } private void start() { lifecycleService.setStarted(); connectionManager.start(); try { clusterService.start(); } catch (IllegalStateException e) { //there was an authentication failure (todo: perhaps use an AuthenticationException // ??) lifecycleService.shutdown(); throw e; } loadBalancer.init(getCluster(), config); partitionService.start(); } public Config getConfig() { throw new UnsupportedOperationException("Client cannot access cluster config!"); } @Override public String getName() { return instanceName; } @Override public <E> IQueue<E> getQueue(String name) { return getDistributedObject(QueueService.SERVICE_NAME, name); } @Override public <E> ITopic<E> getTopic(String name) { return getDistributedObject(TopicService.SERVICE_NAME, name); } @Override public <E> ISet<E> getSet(String name) { return getDistributedObject(SetService.SERVICE_NAME, name); } @Override public <E> IList<E> getList(String name) { return getDistributedObject(ListService.SERVICE_NAME, name); } @Override public <K, V> IMap<K, V> getMap(String name) { return getDistributedObject(MapService.SERVICE_NAME, name); } @Override public <K, V> MultiMap<K, V> getMultiMap(String name) { return getDistributedObject(MultiMapService.SERVICE_NAME, name); } @Override public <K, V> ReplicatedMap<K, V> getReplicatedMap(String name) { return getDistributedObject(ReplicatedMapService.SERVICE_NAME, name); } @Override public JobTracker getJobTracker(String name) { return getDistributedObject(MapReduceService.SERVICE_NAME, name); } @Override public ILock getLock(String key) { return getDistributedObject(LockServiceImpl.SERVICE_NAME, key); } @Override @Deprecated public ILock getLock(Object key) { //this method will be deleted in the near future. String name = LockProxy.convertToStringKey(key, serializationService); return getDistributedObject(LockServiceImpl.SERVICE_NAME, name); } @Override public Cluster getCluster() { return new ClientClusterProxy(clusterService); } @Override public Client getLocalEndpoint() { return clusterService.getLocalClient(); } @Override public IExecutorService getExecutorService(String name) { return getDistributedObject(DistributedExecutorService.SERVICE_NAME, name); } public <T> T executeTransaction(TransactionalTask<T> task) throws TransactionException { return transactionManager.executeTransaction(task); } @Override public <T> T executeTransaction(TransactionOptions options, TransactionalTask<T> task) throws TransactionException { return transactionManager.executeTransaction(options, task); } @Override public TransactionContext newTransactionContext() { return transactionManager.newTransactionContext(); } @Override public TransactionContext newTransactionContext(TransactionOptions options) { return transactionManager.newTransactionContext(options); } @Override public IdGenerator getIdGenerator(String name) { return getDistributedObject(IdGeneratorService.SERVICE_NAME, name); } @Override public IAtomicLong getAtomicLong(String name) { return getDistributedObject(AtomicLongService.SERVICE_NAME, name); } @Override public <E> IAtomicReference<E> getAtomicReference(String name) { return getDistributedObject(AtomicReferenceService.SERVICE_NAME, name); } @Override public ICountDownLatch getCountDownLatch(String name) { return getDistributedObject(CountDownLatchService.SERVICE_NAME, name); } @Override public ISemaphore getSemaphore(String name) { return getDistributedObject(SemaphoreService.SERVICE_NAME, name); } @Override public Collection<DistributedObject> getDistributedObjects() { try { GetDistributedObjectsRequest request = new GetDistributedObjectsRequest(); final Future<SerializableCollection> future = invocationService.invokeOnRandomTarget(request); final SerializableCollection serializableCollection = serializationService.toObject(future.get()); for (Data data : serializableCollection) { final DistributedObjectInfo o = serializationService.toObject(data); getDistributedObject(o.getServiceName(), o.getName()); } return (Collection<DistributedObject>) proxyManager.getDistributedObjects(); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } @Override public String addDistributedObjectListener(DistributedObjectListener distributedObjectListener) { return proxyManager.addDistributedObjectListener(distributedObjectListener); } @Override public boolean removeDistributedObjectListener(String registrationId) { return proxyManager.removeDistributedObjectListener(registrationId); } @Override public PartitionService getPartitionService() { return new PartitionServiceProxy(partitionService); } @Override public ClientService getClientService() { throw new UnsupportedOperationException(); } @Override public LoggingService getLoggingService() { throw new UnsupportedOperationException(); } @Override public LifecycleService getLifecycleService() { return lifecycleService; } @Override @Deprecated public <T extends DistributedObject> T getDistributedObject(String serviceName, Object id) { if (id instanceof String) { return (T) proxyManager.getProxy(serviceName, (String) id); } throw new IllegalArgumentException("'id' must be type of String!"); } @Override public <T extends DistributedObject> T getDistributedObject(String serviceName, String name) { return (T) proxyManager.getProxy(serviceName, name); } @Override public ConcurrentMap<String, Object> getUserContext() { return userContext; } public ClientConfig getClientConfig() { return config; } public SerializationService getSerializationService() { return serializationService; } public ClientConnectionManager getConnectionManager() { return connectionManager; } public ClientClusterService getClientClusterService() { return clusterService; } public ClientExecutionService getClientExecutionService() { return executionService; } public ClientPartitionService getClientPartitionService() { return partitionService; } public ClientInvocationService getInvocationService() { return invocationService; } public ThreadGroup getThreadGroup() { return threadGroup; } @Override public void shutdown() { getLifecycleService().shutdown(); } void doShutdown() { CLIENTS.remove(id); executionService.shutdown(); partitionService.stop(); clusterService.stop(); transactionManager.shutdown(); connectionManager.shutdown(); proxyManager.destroy(); serializationService.destroy(); } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_HazelcastClient.java
3,610
final class TransactionImpl implements Transaction, TransactionSupport { private static final ThreadLocal<Boolean> THREAD_FLAG = new ThreadLocal<Boolean>(); private static final int ROLLBACK_TIMEOUT_MINUTES = 5; private static final int COMMIT_TIMEOUT_MINUTES = 5; private final TransactionManagerServiceImpl transactionManagerService; private final NodeEngine nodeEngine; private final List<TransactionLog> txLogs = new LinkedList<TransactionLog>(); private final Map<Object, TransactionLog> txLogMap = new HashMap<Object, TransactionLog>(); private final String txnId; private Long threadId; private final long timeoutMillis; private final int durability; private final TransactionType transactionType; private final String txOwnerUuid; private final boolean checkThreadAccess; private State state = NO_TXN; private long startTime; private Address[] backupAddresses; private SerializableXID xid; public TransactionImpl(TransactionManagerServiceImpl transactionManagerService, NodeEngine nodeEngine, TransactionOptions options, String txOwnerUuid) { this.transactionManagerService = transactionManagerService; this.nodeEngine = nodeEngine; this.txnId = UuidUtil.buildRandomUuidString(); this.timeoutMillis = options.getTimeoutMillis(); this.durability = options.getDurability(); this.transactionType = options.getTransactionType(); this.txOwnerUuid = txOwnerUuid == null ? nodeEngine.getLocalMember().getUuid() : txOwnerUuid; this.checkThreadAccess = txOwnerUuid != null; } // used by tx backups TransactionImpl(TransactionManagerServiceImpl transactionManagerService, NodeEngine nodeEngine, String txnId, List<TransactionLog> txLogs, long timeoutMillis, long startTime, String txOwnerUuid) { this.transactionManagerService = transactionManagerService; this.nodeEngine = nodeEngine; this.txnId = txnId; this.timeoutMillis = timeoutMillis; this.startTime = startTime; this.durability = 0; this.transactionType = TransactionType.TWO_PHASE; this.txLogs.addAll(txLogs); this.state = PREPARED; this.txOwnerUuid = txOwnerUuid; this.checkThreadAccess = false; } public void setXid(SerializableXID xid) { this.xid = xid; } public SerializableXID getXid() { return xid; } @Override public String getTxnId() { return txnId; } public TransactionType getTransactionType() { return transactionType; } @Override public void addTransactionLog(TransactionLog transactionLog) { if (state != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("Transaction is not active!"); } checkThread(); // there should be just one tx log for the same key. so if there is older we are removing it if (transactionLog instanceof KeyAwareTransactionLog) { KeyAwareTransactionLog keyAwareTransactionLog = (KeyAwareTransactionLog) transactionLog; TransactionLog removed = txLogMap.remove(keyAwareTransactionLog.getKey()); if (removed != null) { txLogs.remove(removed); } } txLogs.add(transactionLog); if (transactionLog instanceof KeyAwareTransactionLog) { KeyAwareTransactionLog keyAwareTransactionLog = (KeyAwareTransactionLog) transactionLog; txLogMap.put(keyAwareTransactionLog.getKey(), keyAwareTransactionLog); } } public TransactionLog getTransactionLog(Object key) { return txLogMap.get(key); } public List<TransactionLog> getTxLogs() { return txLogs; } public void removeTransactionLog(Object key) { TransactionLog removed = txLogMap.remove(key); if (removed != null) { txLogs.remove(removed); } } private void checkThread() { if (!checkThreadAccess && threadId != null && threadId.longValue() != Thread.currentThread().getId()) { throw new IllegalStateException("Transaction cannot span multiple threads!"); } } public void begin() throws IllegalStateException { if (state == ACTIVE) { throw new IllegalStateException("Transaction is already active"); } if (THREAD_FLAG.get() != null) { throw new IllegalStateException("Nested transactions are not allowed!"); } //init caller thread if(threadId == null){ threadId = Thread.currentThread().getId(); setThreadFlag(Boolean.TRUE); } startTime = Clock.currentTimeMillis(); backupAddresses = transactionManagerService.pickBackupAddresses(durability); if (durability > 0 && backupAddresses != null && transactionType == TransactionType.TWO_PHASE) { List<Future> futures = startTxBackup(); awaitTxBackupCompletion(futures); } state = ACTIVE; } private void awaitTxBackupCompletion(List<Future> futures) { for (Future future : futures) { try { future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (MemberLeftException e) { nodeEngine.getLogger(Transaction.class).warning("Member left while replicating tx begin: " + e); } catch (Throwable e) { if (e instanceof ExecutionException) { e = e.getCause() != null ? e.getCause() : e; } if (e instanceof TargetNotMemberException) { nodeEngine.getLogger(Transaction.class).warning("Member left while replicating tx begin: " + e); } else { throw ExceptionUtil.rethrow(e); } } } } private List<Future> startTxBackup() { final OperationService operationService = nodeEngine.getOperationService(); List<Future> futures = new ArrayList<Future>(backupAddresses.length); for (Address backupAddress : backupAddresses) { if (nodeEngine.getClusterService().getMember(backupAddress) != null) { final Future f = operationService.invokeOnTarget(TransactionManagerServiceImpl.SERVICE_NAME, new BeginTxBackupOperation(txOwnerUuid, txnId, xid), backupAddress); futures.add(f); } } return futures; } private void setThreadFlag(Boolean flag) { if (!checkThreadAccess) { THREAD_FLAG.set(flag); } } public void prepare() throws TransactionException { if (state != ACTIVE) { throw new TransactionNotActiveException("Transaction is not active"); } checkThread(); checkTimeout(); try { final List<Future> futures = new ArrayList<Future>(txLogs.size()); state = PREPARING; for (TransactionLog txLog : txLogs) { futures.add(txLog.prepare(nodeEngine)); } for (Future future : futures) { future.get(timeoutMillis, TimeUnit.MILLISECONDS); } futures.clear(); state = PREPARED; if (durability > 0) { replicateTxnLog(); } } catch (Throwable e) { throw ExceptionUtil.rethrow(e, TransactionException.class); } } private void replicateTxnLog() throws InterruptedException, ExecutionException, java.util.concurrent.TimeoutException { final List<Future> futures = new ArrayList<Future>(txLogs.size()); final OperationService operationService = nodeEngine.getOperationService(); for (Address backupAddress : backupAddresses) { if (nodeEngine.getClusterService().getMember(backupAddress) != null) { final Future f = operationService.invokeOnTarget(TransactionManagerServiceImpl.SERVICE_NAME, new ReplicateTxOperation(txLogs, txOwnerUuid, txnId, timeoutMillis, startTime), backupAddress); futures.add(f); } } for (Future future : futures) { future.get(timeoutMillis, TimeUnit.MILLISECONDS); } futures.clear(); } public void commit() throws TransactionException, IllegalStateException { try { if (transactionType.equals(TransactionType.TWO_PHASE) && state != PREPARED) { throw new IllegalStateException("Transaction is not prepared"); } if (transactionType.equals(TransactionType.LOCAL) && state != ACTIVE) { throw new IllegalStateException("Transaction is not active"); } checkThread(); checkTimeout(); try { final List<Future> futures = new ArrayList<Future>(txLogs.size()); state = COMMITTING; for (TransactionLog txLog : txLogs) { futures.add(txLog.commit(nodeEngine)); } for (Future future : futures) { try { future.get(COMMIT_TIMEOUT_MINUTES, TimeUnit.MINUTES); } catch (Throwable e) { nodeEngine.getLogger(getClass()).warning("Error during commit!", e); } } state = COMMITTED; // purge tx backup purgeTxBackups(); } catch (Throwable e) { state = COMMIT_FAILED; throw ExceptionUtil.rethrow(e, TransactionException.class); } } finally { setThreadFlag(null); } } private void checkTimeout() throws TransactionException { if (startTime + timeoutMillis < Clock.currentTimeMillis()) { throw new TransactionException("Transaction is timed-out!"); } } public void rollback() throws IllegalStateException { try { if (state == NO_TXN || state == ROLLED_BACK) { throw new IllegalStateException("Transaction is not active"); } checkThread(); state = ROLLING_BACK; try { rollbackTxBackup(); final List<Future> futures = new ArrayList<Future>(txLogs.size()); final ListIterator<TransactionLog> iter = txLogs.listIterator(txLogs.size()); while (iter.hasPrevious()) { final TransactionLog txLog = iter.previous(); futures.add(txLog.rollback(nodeEngine)); } for (Future future : futures) { try { future.get(ROLLBACK_TIMEOUT_MINUTES, TimeUnit.MINUTES); } catch (Throwable e) { nodeEngine.getLogger(getClass()).warning("Error during rollback!", e); } } // purge tx backup purgeTxBackups(); } catch (Throwable e) { throw ExceptionUtil.rethrow(e); } finally { state = ROLLED_BACK; } } finally { setThreadFlag(null); } } private void rollbackTxBackup() { final OperationService operationService = nodeEngine.getOperationService(); final List<Future> futures = new ArrayList<Future>(txLogs.size()); // rollback tx backup if (durability > 0 && transactionType.equals(TransactionType.TWO_PHASE)) { for (Address backupAddress : backupAddresses) { if (nodeEngine.getClusterService().getMember(backupAddress) != null) { final Future f = operationService.invokeOnTarget(TransactionManagerServiceImpl.SERVICE_NAME, new RollbackTxBackupOperation(txnId), backupAddress); futures.add(f); } } for (Future future : futures) { try { future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (Throwable e) { nodeEngine.getLogger(getClass()).warning("Error during tx rollback backup!", e); } } futures.clear(); } } public void setRollbackOnly() { state = ROLLING_BACK; } private void purgeTxBackups() { if (durability > 0 && transactionType.equals(TransactionType.TWO_PHASE)) { final OperationService operationService = nodeEngine.getOperationService(); for (Address backupAddress : backupAddresses) { if (nodeEngine.getClusterService().getMember(backupAddress) != null) { try { operationService.invokeOnTarget(TransactionManagerServiceImpl.SERVICE_NAME, new PurgeTxBackupOperation(txnId), backupAddress); } catch (Throwable e) { nodeEngine.getLogger(getClass()).warning("Error during purging backups!", e); } } } } } public long getStartTime() { return startTime; } public String getOwnerUuid() { return txOwnerUuid; } public State getState() { return state; } public long getTimeoutMillis() { return timeoutMillis; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Transaction"); sb.append("{txnId='").append(txnId).append('\''); sb.append(", state=").append(state); sb.append(", txType=").append(transactionType); sb.append(", timeoutMillis=").append(timeoutMillis); sb.append('}'); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_transaction_impl_TransactionImpl.java
164
public interface SpeedTest { public void cycle() throws Exception; public void init() throws Exception; public void deinit() throws Exception; public void beforeCycle() throws Exception; public void afterCycle() throws Exception; }
0true
commons_src_test_java_com_orientechnologies_common_test_SpeedTest.java
174
public class BroadleafProcessURLFilterTest extends TestCase { public void testShouldProcessURL() throws Exception { BroadleafProcessURLFilter cf = new BroadleafProcessURLFilter(); // Should fail assertFalse("Image resource should not be processed by content filter.", cf.shouldProcessURL(null, "/path/subpath/test.jpg")); assertFalse("URLs containing org.broadleafcommerce.admin should not be processed.", cf.shouldProcessURL(null, "/path/org.broadleafcommerce.admin/admintest")); assertTrue("/about_us should be processed by the content filter", cf.shouldProcessURL(null, "/about_us")); assertTrue("*.htm resources should be processed by the content filter", cf.shouldProcessURL(null, "/test.htm")); } }
0true
admin_broadleaf-contentmanagement-module_src_test_java_org_broadleafcommerce_cms_web_BroadleafProcessURLFilterTest.java
519
public class TransportTypesExistsAction extends TransportMasterNodeReadOperationAction<TypesExistsRequest, TypesExistsResponse> { @Inject public TransportTypesExistsAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) { super(settings, transportService, clusterService, threadPool); } @Override protected String executor() { // lightweight check return ThreadPool.Names.SAME; } @Override protected String transportAction() { return TypesExistsAction.NAME; } @Override protected TypesExistsRequest newRequest() { return new TypesExistsRequest(); } @Override protected TypesExistsResponse newResponse() { return new TypesExistsResponse(); } @Override protected ClusterBlockException checkBlock(TypesExistsRequest request, ClusterState state) { return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, request.indices()); } @Override protected void masterOperation(final TypesExistsRequest request, final ClusterState state, final ActionListener<TypesExistsResponse> listener) throws ElasticsearchException { String[] concreteIndices = state.metaData().concreteIndices(request.indices(), request.indicesOptions()); if (concreteIndices.length == 0) { listener.onResponse(new TypesExistsResponse(false)); return; } for (String concreteIndex : concreteIndices) { if (!state.metaData().hasConcreteIndex(concreteIndex)) { listener.onResponse(new TypesExistsResponse(false)); return; } ImmutableOpenMap<String, MappingMetaData> mappings = state.metaData().getIndices().get(concreteIndex).mappings(); if (mappings.isEmpty()) { listener.onResponse(new TypesExistsResponse(false)); return; } for (String type : request.types()) { if (!mappings.containsKey(type)) { listener.onResponse(new TypesExistsResponse(false)); return; } } } listener.onResponse(new TypesExistsResponse(true)); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_exists_types_TransportTypesExistsAction.java
926
public abstract class BroadcastOperationRequest<T extends BroadcastOperationRequest> extends ActionRequest<T> { protected String[] indices; private BroadcastOperationThreading operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD; private IndicesOptions indicesOptions = IndicesOptions.strict(); protected BroadcastOperationRequest() { } protected BroadcastOperationRequest(String[] indices) { this.indices = indices; } public String[] indices() { return indices; } @SuppressWarnings("unchecked") public final T indices(String... indices) { this.indices = indices; return (T) this; } @Override public ActionRequestValidationException validate() { return null; } /** * Controls the operation threading model. */ public BroadcastOperationThreading operationThreading() { return operationThreading; } /** * Controls the operation threading model. */ @SuppressWarnings("unchecked") public final T operationThreading(BroadcastOperationThreading operationThreading) { this.operationThreading = operationThreading; return (T) this; } /** * Controls the operation threading model. */ public T operationThreading(String operationThreading) { return operationThreading(BroadcastOperationThreading.fromString(operationThreading, this.operationThreading)); } public IndicesOptions indicesOptions() { return indicesOptions; } @SuppressWarnings("unchecked") public final T indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return (T) this; } protected void beforeStart() { } protected void beforeLocalFork() { } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArrayNullable(indices); out.writeByte(operationThreading.id()); indicesOptions.writeIndicesOptions(out); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); indices = in.readStringArray(); operationThreading = BroadcastOperationThreading.fromId(in.readByte()); indicesOptions = IndicesOptions.readIndicesOptions(in); } }
1no label
src_main_java_org_elasticsearch_action_support_broadcast_BroadcastOperationRequest.java
110
public interface PageItemCriteria extends QuantityBasedRule { /** * Returns the parent <code>Page</code> to which this * field belongs. * * @return */ @Nonnull public Page getPage(); /** * Sets the parent <code>Page</code>. * @param page */ public void setPage(@Nonnull Page page); /** * Builds a copy of this item. Used by the content management system when an * item is edited. * * @return a copy of this item */ @Nonnull public PageItemCriteria cloneEntity(); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageItemCriteria.java
237
public interface ModuleProvider { /** * Indicates if, given the configuration, this module can respond to the particular request. * * @param config * @return */ public boolean canRespond(ModuleConfiguration config); }
0true
common_src_main_java_org_broadleafcommerce_common_config_service_ModuleProvider.java
25
private class HAMClusterListener extends ClusterListener.Adapter { @Override public void enteredCluster( ClusterConfiguration configuration ) { Map<InstanceId, ClusterMember> newMembers = new HashMap<InstanceId, ClusterMember>(); for ( InstanceId memberClusterUri : configuration.getMembers().keySet() ) newMembers.put( memberClusterUri, new ClusterMember( memberClusterUri ) ); members.clear(); members.putAll( newMembers ); } @Override public void leftCluster() { members.clear(); } @Override public void joinedCluster( InstanceId member, URI memberUri ) { members.put( member, new ClusterMember( member ) ); } @Override public void leftCluster( InstanceId member ) { members.remove( member ); } }
1no label
enterprise_ha_src_main_java_org_neo4j_kernel_ha_cluster_member_ClusterMembers.java
138
public static class Presentation { public static class Tab { public static class Name { public static final String Rules = "StructuredContentImpl_Rules_Tab"; } public static class Order { public static final int Rules = 1000; } } public static class Group { public static class Name { public static final String Description = "StructuredContentImpl_Description"; public static final String Internal = "StructuredContentImpl_Internal"; public static final String Rules = "StructuredContentImpl_Rules"; } public static class Order { public static final int Description = 1000; public static final int Internal = 2000; public static final int Rules = 1000; } } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
1,600
public class PersistencePerspective implements Serializable { private static final long serialVersionUID = 1L; protected String[] additionalNonPersistentProperties = new String[]{}; protected ForeignKey[] additionalForeignKeys = new ForeignKey[]{}; protected Map<PersistencePerspectiveItemType, PersistencePerspectiveItem> persistencePerspectiveItems = new HashMap<PersistencePerspectiveItemType, PersistencePerspectiveItem>(); protected OperationTypes operationTypes = new OperationTypes(); protected Boolean populateToOneFields = false; protected String[] excludeFields = new String[]{}; protected String[] includeFields = new String[]{}; protected String configurationKey; protected Boolean showArchivedFields = false; protected Boolean useServerSideInspectionCache = true; public PersistencePerspective() { } public PersistencePerspective(OperationTypes operationTypes, String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignKeys) { setAdditionalNonPersistentProperties(additionalNonPersistentProperties); setAdditionalForeignKeys(additionalForeignKeys); this.operationTypes = operationTypes; } public String[] getAdditionalNonPersistentProperties() { return additionalNonPersistentProperties; } public void setAdditionalNonPersistentProperties(String[] additionalNonPersistentProperties) { this.additionalNonPersistentProperties = additionalNonPersistentProperties; Arrays.sort(this.additionalNonPersistentProperties); } public ForeignKey[] getAdditionalForeignKeys() { return additionalForeignKeys; } public void setAdditionalForeignKeys(ForeignKey[] additionalForeignKeys) { this.additionalForeignKeys = additionalForeignKeys; Arrays.sort(this.additionalForeignKeys, new Comparator<ForeignKey>() { public int compare(ForeignKey o1, ForeignKey o2) { return o1.getManyToField().compareTo(o2.getManyToField()); } }); } public OperationTypes getOperationTypes() { return operationTypes; } public void setOperationTypes(OperationTypes operationTypes) { this.operationTypes = operationTypes; } public void addPersistencePerspectiveItem(PersistencePerspectiveItemType type, PersistencePerspectiveItem item) { persistencePerspectiveItems.put(type, item); } public Map<PersistencePerspectiveItemType, PersistencePerspectiveItem> getPersistencePerspectiveItems() { return persistencePerspectiveItems; } public void setPersistencePerspectiveItems(Map<PersistencePerspectiveItemType, PersistencePerspectiveItem> persistencePerspectiveItems) { this.persistencePerspectiveItems = persistencePerspectiveItems; } /** * Retrieves whether or not ManyToOne and OneToOne field boundaries * will be traversed when retrieving and populating entity fields. * Implementation should use the @AdminPresentationClass annotation * instead. * * @return Whether or not ManyToOne and OneToOne field boundaries will be crossed. */ @Deprecated public Boolean getPopulateToOneFields() { return populateToOneFields; } /** * Sets whether or not ManyToOne and OneToOne field boundaries * will be traversed when retrieving and populating entity fields. * Implementation should use the @AdminPresentationClass annotation * instead. * * @return Whether or not ManyToOne and OneToOne field boundaries will be crossed. */ @Deprecated public void setPopulateToOneFields(Boolean populateToOneFields) { this.populateToOneFields = populateToOneFields; } /** * Retrieve the list of fields to exclude from the admin presentation. * Implementations should use the excluded property of the AdminPresentation * annotation instead, or use an AdminPresentationOverride if re-enabling a * Broadleaf field is desired. If multiple datasources point to the same * entity, but different exclusion behavior is required, a custom persistence * handler may be employed with different inspect method implementations to * account for the variations. * * @return list of fields to exclude from the admin */ @Deprecated public String[] getExcludeFields() { return excludeFields; } /** * Set the list of fields to exclude from the admin presentation. * Implementations should use the excluded property of the AdminPresentation * annotation instead, or use an AdminPresentationOverride if re-enabling a * Broadleaf field is desired. If multiple datasources point to the same * entity, but different exclusion behavior is required, a custom persistence * handler may be employed with different inspect method implementations to * account for the variations. * * @param excludeManyToOneFields */ @Deprecated public void setExcludeFields(String[] excludeManyToOneFields) { this.excludeFields = excludeManyToOneFields; Arrays.sort(this.excludeFields); } /** * Get the list of fields to include in the admin presentation. * Implementations should use excludeFields instead. * * @return list of fields to include in the admin */ @Deprecated public String[] getIncludeFields() { return includeFields; } /** * Set the list of fields to include in the admin presentation. * Implementations should use excludeFields instead. * * @param includeManyToOneFields */ @Deprecated public void setIncludeFields(String[] includeManyToOneFields) { this.includeFields = includeManyToOneFields; Arrays.sort(this.includeFields); } public String getConfigurationKey() { return configurationKey; } public void setConfigurationKey(String configurationKey) { this.configurationKey = configurationKey; } public Boolean getShowArchivedFields() { return showArchivedFields; } public void setShowArchivedFields(Boolean showArchivedFields) { this.showArchivedFields = showArchivedFields; } public Boolean getUseServerSideInspectionCache() { return useServerSideInspectionCache; } public void setUseServerSideInspectionCache(Boolean useServerSideInspectionCache) { this.useServerSideInspectionCache = useServerSideInspectionCache; } public PersistencePerspective clonePersistencePerspective() { PersistencePerspective persistencePerspective = new PersistencePerspective(); persistencePerspective.operationTypes = operationTypes.cloneOperationTypes(); if (additionalNonPersistentProperties != null) { persistencePerspective.additionalNonPersistentProperties = new String[additionalNonPersistentProperties.length]; System.arraycopy(additionalNonPersistentProperties, 0, persistencePerspective.additionalNonPersistentProperties, 0, additionalNonPersistentProperties.length); } if (additionalForeignKeys != null) { persistencePerspective.additionalForeignKeys = new ForeignKey[additionalForeignKeys.length]; for (int j=0; j<additionalForeignKeys.length;j++){ persistencePerspective.additionalForeignKeys[j] = additionalForeignKeys[j].cloneForeignKey(); } } if (this.persistencePerspectiveItems != null) { Map<PersistencePerspectiveItemType, PersistencePerspectiveItem> persistencePerspectiveItems = new HashMap<PersistencePerspectiveItemType, PersistencePerspectiveItem>(this.persistencePerspectiveItems.size()); for (Map.Entry<PersistencePerspectiveItemType, PersistencePerspectiveItem> entry : this.persistencePerspectiveItems.entrySet()) { persistencePerspectiveItems.put(entry.getKey(), entry.getValue().clonePersistencePerspectiveItem()); } persistencePerspective.persistencePerspectiveItems = persistencePerspectiveItems; } persistencePerspective.populateToOneFields = populateToOneFields; persistencePerspective.configurationKey = configurationKey; persistencePerspective.showArchivedFields = showArchivedFields; persistencePerspective.useServerSideInspectionCache = useServerSideInspectionCache; if (excludeFields != null) { persistencePerspective.excludeFields = new String[excludeFields.length]; System.arraycopy(excludeFields, 0, persistencePerspective.excludeFields, 0, excludeFields.length); } if (includeFields != null) { persistencePerspective.includeFields = new String[includeFields.length]; System.arraycopy(includeFields, 0, persistencePerspective.includeFields, 0, includeFields.length); } return persistencePerspective; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PersistencePerspective)) return false; PersistencePerspective that = (PersistencePerspective) o; if (!Arrays.equals(additionalForeignKeys, that.additionalForeignKeys)) return false; if (!Arrays.equals(additionalNonPersistentProperties, that.additionalNonPersistentProperties)) return false; if (configurationKey != null ? !configurationKey.equals(that.configurationKey) : that.configurationKey != null) return false; if (!Arrays.equals(excludeFields, that.excludeFields)) return false; if (!Arrays.equals(includeFields, that.includeFields)) return false; if (operationTypes != null ? !operationTypes.equals(that.operationTypes) : that.operationTypes != null) return false; if (persistencePerspectiveItems != null ? !persistencePerspectiveItems.equals(that.persistencePerspectiveItems) : that.persistencePerspectiveItems != null) return false; if (populateToOneFields != null ? !populateToOneFields.equals(that.populateToOneFields) : that.populateToOneFields != null) return false; if (showArchivedFields != null ? !showArchivedFields.equals(that.showArchivedFields) : that.showArchivedFields != null) return false; if (useServerSideInspectionCache != null ? !useServerSideInspectionCache.equals(that.useServerSideInspectionCache) : that.useServerSideInspectionCache != null) return false; return true; } @Override public int hashCode() { int result = additionalNonPersistentProperties != null ? Arrays.hashCode(additionalNonPersistentProperties) : 0; result = 31 * result + (additionalForeignKeys != null ? Arrays.hashCode(additionalForeignKeys) : 0); result = 31 * result + (persistencePerspectiveItems != null ? persistencePerspectiveItems.hashCode() : 0); result = 31 * result + (operationTypes != null ? operationTypes.hashCode() : 0); result = 31 * result + (populateToOneFields != null ? populateToOneFields.hashCode() : 0); result = 31 * result + (excludeFields != null ? Arrays.hashCode(excludeFields) : 0); result = 31 * result + (includeFields != null ? Arrays.hashCode(includeFields) : 0); result = 31 * result + (configurationKey != null ? configurationKey.hashCode() : 0); result = 31 * result + (showArchivedFields != null ? showArchivedFields.hashCode() : 0); result = 31 * result + (useServerSideInspectionCache != null ? useServerSideInspectionCache.hashCode() : 0); return result; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_PersistencePerspective.java
1,100
public class GiftWrapOrderItemRequest extends DiscreteOrderItemRequest { private List<OrderItem> wrappedItems = new ArrayList<OrderItem>(); public List<OrderItem> getWrappedItems() { return wrappedItems; } public void setWrappedItems(List<OrderItem> wrappedItems) { this.wrappedItems = wrappedItems; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((wrappedItems == null) ? 0 : wrappedItems.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; GiftWrapOrderItemRequest other = (GiftWrapOrderItemRequest) obj; if (wrappedItems == null) { if (other.wrappedItems != null) return false; } else if (!wrappedItems.equals(other.wrappedItems)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_call_GiftWrapOrderItemRequest.java
684
@Entity @Polymorphism(type = PolymorphismType.EXPLICIT) @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_CATEGORY_PRODUCT_XREF") @AdminPresentationClass(excludeFromPolymorphism = false) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") public class CategoryProductXrefImpl implements CategoryProductXref { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; @EmbeddedId CategoryProductXrefPK categoryProductXref = new CategoryProductXrefPK(); public CategoryProductXrefPK getCategoryProductXref() { return categoryProductXref; } public void setCategoryProductXref(CategoryProductXrefPK categoryProductXref) { this.categoryProductXref = categoryProductXref; } /** The display order. */ @Column(name = "DISPLAY_ORDER") @AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL) protected Long displayOrder; /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXref#getDisplayOrder() */ public Long getDisplayOrder() { return displayOrder; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXref#setDisplayOrder(java.lang.Integer) */ public void setDisplayOrder(Long displayOrder) { this.displayOrder = displayOrder; } /** * @return * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#getCategory() */ public Category getCategory() { return categoryProductXref.getCategory(); } /** * @param category * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#setCategory(org.broadleafcommerce.core.catalog.domain.Category) */ public void setCategory(Category category) { categoryProductXref.setCategory(category); } /** * @return * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#getProduct() */ public Product getProduct() { return categoryProductXref.getProduct(); } /** * @param product * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#setProduct(org.broadleafcommerce.core.catalog.domain.Product) */ public void setProduct(Product product) { categoryProductXref.setProduct(product); } @Override public boolean equals(Object o) { if (o instanceof CategoryProductXrefImpl) { CategoryProductXrefImpl that = (CategoryProductXrefImpl) o; return new EqualsBuilder() .append(categoryProductXref, that.categoryProductXref) .build(); } return false; } @Override public int hashCode() { int result = categoryProductXref != null ? categoryProductXref.hashCode() : 0; return result; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryProductXrefImpl.java
1,485
@SuppressWarnings("unchecked") public abstract class ODatabasePojoAbstract<T extends Object> extends ODatabaseWrapperAbstract<ODatabaseDocumentTx> implements ODatabaseSchemaAware<T> { protected IdentityHashMap<Object, ODocument> objects2Records = new IdentityHashMap<Object, ODocument>(); protected IdentityHashMap<ODocument, T> records2Objects = new IdentityHashMap<ODocument, T>(); protected HashMap<ORID, ODocument> rid2Records = new HashMap<ORID, ODocument>(); protected boolean retainObjects = true; public ODatabasePojoAbstract(final ODatabaseDocumentTx iDatabase) { super(iDatabase); iDatabase.setDatabaseOwner(this); } public abstract ODocument pojo2Stream(final T iPojo, final ODocument record); public abstract Object stream2pojo(final ODocument record, final Object iPojo, final String iFetchPlan); @Override public void close() { objects2Records.clear(); records2Objects.clear(); rid2Records.clear(); super.close(); } public OTransaction getTransaction() { return underlying.getTransaction(); } public ODatabaseComplex<T> begin() { return (ODatabaseComplex<T>) underlying.begin(); } public ODatabaseComplex<T> begin(final TXTYPE iType) { return (ODatabaseComplex<T>) underlying.begin(iType); } public ODatabaseComplex<T> begin(final OTransaction iTx) { return (ODatabaseComplex<T>) underlying.begin(iTx); } public ODatabaseComplex<T> commit() { clearNewEntriesFromCache(); underlying.commit(); return this; } public ODatabaseComplex<T> rollback() { clearNewEntriesFromCache(); underlying.rollback(); final Set<ORID> rids = new HashSet<ORID>(rid2Records.keySet()); ORecord<?> record; Object object; for (ORID rid : rids) { if (rid.isTemporary()) { record = rid2Records.remove(rid); if (record != null) { object = records2Objects.remove(record); if (object != null) { objects2Records.remove(object); } } } } return this; } /** * Sets as dirty a POJO. This is useful when you change the object and need to tell to the engine to treat as dirty. * * @param iPojo * User object */ public void setDirty(final Object iPojo) { if (iPojo == null) return; final ODocument record = getRecordByUserObject(iPojo, false); if (record == null) throw new OObjectNotManagedException("The object " + iPojo + " is not managed by current database"); record.setDirty(); } /** * Sets as not dirty a POJO. This is useful when you change some other object and need to tell to the engine to treat this one as * not dirty. * * @param iPojo * User object */ public void unsetDirty(final Object iPojo) { if (iPojo == null) return; final ODocument record = getRecordByUserObject(iPojo, false); if (record == null) return; record.unsetDirty(); } public void setInternal(final ATTRIBUTES attribute, final Object iValue) { underlying.setInternal(attribute, iValue); } /** * Returns the version number of the object. * * @param iPojo * User object */ public ORecordVersion getVersion(final Object iPojo) { final ODocument record = getRecordByUserObject(iPojo, false); if (record == null) throw new OObjectNotManagedException("The object " + iPojo + " is not managed by current database"); return record.getRecordVersion(); } /** * Returns the object unique identity. * * @param iPojo * User object */ public ORID getIdentity(final Object iPojo) { final ODocument record = getRecordByUserObject(iPojo, false); if (record == null) throw new OObjectNotManagedException("The object " + iPojo + " is not managed by current database"); return record.getIdentity(); } public OUser getUser() { return underlying.getUser(); } public void setUser(OUser user) { underlying.setUser(user); } public OMetadata getMetadata() { return underlying.getMetadata(); } /** * Returns a wrapped OCommandRequest instance to catch the result-set by converting it before to return to the user application. */ public <RET extends OCommandRequest> RET command(final OCommandRequest iCommand) { return (RET) new OCommandSQLPojoWrapper(this, underlying.command(iCommand)); } public <RET extends List<?>> RET query(final OQuery<?> iCommand, final Object... iArgs) { checkOpeness(); convertParameters(iArgs); final List<ODocument> result = underlying.query(iCommand, iArgs); if (result == null) return null; final List<Object> resultPojo = new ArrayList<Object>(); Object obj; for (OIdentifiable doc : result) { if (doc instanceof ODocument) { // GET THE ASSOCIATED DOCUMENT if (((ODocument) doc).getClassName() == null) obj = doc; else obj = getUserObjectByRecord(((ODocument) doc), iCommand.getFetchPlan(), true); resultPojo.add(obj); } else { resultPojo.add(doc); } } return (RET) resultPojo; } public ODatabaseComplex<T> delete(final ORecordInternal<?> iRecord) { underlying.delete(iRecord); return this; } public ODatabaseComplex<T> delete(final ORID iRID) { underlying.delete(iRID); return this; } public ODatabaseComplex<T> delete(final ORID iRID, final ORecordVersion iVersion) { underlying.delete(iRID, iVersion); return this; } public ODatabaseComplex<T> cleanOutRecord(final ORID iRID, final ORecordVersion iVersion) { underlying.cleanOutRecord(iRID, iVersion); return this; } public <DBTYPE extends ODatabaseComplex<?>> DBTYPE registerHook(final ORecordHook iHookImpl) { underlying.registerHook(iHookImpl); return (DBTYPE) this; } public <DBTYPE extends ODatabaseComplex<?>> DBTYPE registerHook(final ORecordHook iHookImpl, ORecordHook.HOOK_POSITION iPosition) { underlying.registerHook(iHookImpl, iPosition); return (DBTYPE) this; } public RESULT callbackHooks(final TYPE iType, final OIdentifiable iObject) { return underlying.callbackHooks(iType, iObject); } public Set<ORecordHook> getHooks() { return underlying.getHooks(); } public <DBTYPE extends ODatabaseComplex<?>> DBTYPE unregisterHook(final ORecordHook iHookImpl) { underlying.unregisterHook(iHookImpl); return (DBTYPE) this; } public boolean isMVCC() { return underlying.isMVCC(); } public <DBTYPE extends ODatabaseComplex<?>> DBTYPE setMVCC(final boolean iMvcc) { underlying.setMVCC(iMvcc); return (DBTYPE) this; } /** * Specifies if retain handled objects in memory or not. Setting it to false can improve performance on large inserts. Default is * enabled. * * @param iValue * True to enable, false to disable it. * @see #isRetainObjects() */ public ODatabasePojoAbstract<T> setRetainObjects(final boolean iValue) { retainObjects = iValue; return this; } /** * Returns true if current configuration retains objects, otherwise false * * @see #setRetainObjects(boolean) */ public boolean isRetainObjects() { return retainObjects; } public ODocument getRecordByUserObject(final Object iPojo, final boolean iCreateIfNotAvailable) { if (iPojo instanceof ODocument) return (ODocument) iPojo; else if (iPojo instanceof Proxy) return ((OObjectProxyMethodHandler) ((ProxyObject) iPojo).getHandler()).getDoc(); ODocument record = objects2Records.get(iPojo); if (record == null) { // SEARCH BY RID final ORID rid = OObjectSerializerHelper.getObjectID(this, iPojo); if (rid != null && rid.isValid()) { record = rid2Records.get(rid); if (record == null) // LOAD IT record = underlying.load(rid); } else if (iCreateIfNotAvailable) { record = underlying.newInstance(iPojo.getClass().getSimpleName()); } else { return null; } registerUserObject(iPojo, record); } return record; } public boolean existsUserObjectByRID(ORID iRID) { return rid2Records.containsKey(iRID); } public ODocument getRecordById(final ORID iRecordId) { return iRecordId.isValid() ? rid2Records.get(iRecordId) : null; } public boolean isManaged(final Object iEntity) { return objects2Records.containsKey(iEntity); } public T getUserObjectByRecord(final OIdentifiable iRecord, final String iFetchPlan) { return getUserObjectByRecord(iRecord, iFetchPlan, true); } public T getUserObjectByRecord(final OIdentifiable iRecord, final String iFetchPlan, final boolean iCreate) { if (!(iRecord instanceof ODocument)) return null; // PASS FOR rid2Records MAP BECAUSE IDENTITY COULD BE CHANGED IF WAS NEW AND IN TX ODocument record = rid2Records.get(iRecord.getIdentity()); if (record == null) record = (ODocument) iRecord; Object pojo = records2Objects.get(record); if (pojo == null && iCreate) { checkOpeness(); try { if (iRecord.getRecord().getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) record = (ODocument) record.load(); pojo = newInstance(record.getClassName()); registerUserObject(pojo, record); stream2pojo(record, pojo, iFetchPlan); } catch (Exception e) { throw new OConfigurationException("Cannot retrieve pojo from record " + record, e); } } return (T) pojo; } public void attach(final Object iPojo) { checkOpeness(); final ODocument record = objects2Records.get(iPojo); if (record != null) return; if (OObjectSerializerHelper.hasObjectID(iPojo)) { } else { throw new OObjectNotDetachedException("Cannot attach a non-detached object"); } } public <RET> RET detach(final Object iPojo) { checkOpeness(); for (Field field : iPojo.getClass().getDeclaredFields()) { final Object value = OObjectSerializerHelper.getFieldValue(iPojo, field.getName()); if (value instanceof OObjectLazyMultivalueElement) ((OObjectLazyMultivalueElement<?>) value).detach(false); } return (RET) iPojo; } /** * Register a new POJO */ public void registerUserObject(final Object iObject, final ORecordInternal<?> iRecord) { if (!(iRecord instanceof ODocument)) return; final ODocument doc = (ODocument) iRecord; final boolean isTombstone = doc.getRecordVersion().isTombstone(); if (retainObjects) { if (iObject != null) { if (!isTombstone) { objects2Records.put(iObject, doc); records2Objects.put(doc, (T) iObject); } OObjectSerializerHelper.setObjectID(iRecord.getIdentity(), iObject); OObjectSerializerHelper.setObjectVersion(iRecord.getRecordVersion().copy(), iObject); } final ORID rid = iRecord.getIdentity(); if (rid.isValid() && !isTombstone) rid2Records.put(rid, doc); } } public void unregisterPojo(final T iObject, final ODocument iRecord) { if (iObject != null) objects2Records.remove(iObject); if (iRecord != null) { records2Objects.remove(iRecord); final ORID rid = iRecord.getIdentity(); if (rid.isValid()) rid2Records.remove(rid); } } protected void clearNewEntriesFromCache() { for (Iterator<Entry<ORID, ODocument>> it = rid2Records.entrySet().iterator(); it.hasNext();) { Entry<ORID, ODocument> entry = it.next(); if (entry.getKey().isNew()) { it.remove(); } } for (Iterator<Entry<Object, ODocument>> it = objects2Records.entrySet().iterator(); it.hasNext();) { Entry<Object, ODocument> entry = it.next(); if (entry.getValue().getIdentity().isNew()) { it.remove(); } } for (Iterator<Entry<ODocument, T>> it = records2Objects.entrySet().iterator(); it.hasNext();) { Entry<ODocument, T> entry = it.next(); if (entry.getKey().getIdentity().isNew()) { it.remove(); } } } /** * Converts an array of parameters: if a POJO is used, then replace it with its record id. * * @param iArgs * Array of parameters as Object * @see #convertParameter(Object) */ protected void convertParameters(final Object... iArgs) { if (iArgs == null) return; // FILTER PARAMETERS for (int i = 0; i < iArgs.length; ++i) iArgs[i] = convertParameter(iArgs[i]); } /** * Convert a parameter: if a POJO is used, then replace it with its record id. * * @param iParameter * Parameter to convert, if applicable * @see #convertParameters(Object...) */ protected Object convertParameter(final Object iParameter) { if (iParameter != null) // FILTER PARAMETERS if (iParameter instanceof Map<?, ?>) { Map<String, Object> map = (Map<String, Object>) iParameter; for (Entry<String, Object> e : map.entrySet()) { map.put(e.getKey(), convertParameter(e.getValue())); } return map; } else if (iParameter instanceof Collection<?>) { List<Object> result = new ArrayList<Object>(); for (Object object : (Collection<Object>) iParameter) { result.add(convertParameter(object)); } return result; } else if (iParameter.getClass().isEnum()) { return ((Enum<?>) iParameter).name(); } else if (!OType.isSimpleType(iParameter)) { final ORID rid = getIdentity(iParameter); if (rid != null && rid.isValid()) // REPLACE OBJECT INSTANCE WITH ITS RECORD ID return rid; } return iParameter; } }
1no label
object_src_main_java_com_orientechnologies_orient_object_db_ODatabasePojoAbstract.java
47
public static class Builder { private final File root; private final Provider provider = clusterOfSize( 3 ); private final Map<String, String> commonConfig = emptyMap(); private final Map<Integer, Map<String,String>> instanceConfig = new HashMap<>(); private HighlyAvailableGraphDatabaseFactory factory = new HighlyAvailableGraphDatabaseFactory(); private StoreDirInitializer initializer; public Builder( File root ) { this.root = root; } public Builder withSeedDir( final File seedDir ) { return withStoreDirInitializer( new StoreDirInitializer() { @Override public void initializeStoreDir( int serverId, File storeDir ) throws IOException { copyRecursively( seedDir, storeDir ); } } ); } public Builder withStoreDirInitializer( StoreDirInitializer initializer ) { this.initializer = initializer; return this; } public Builder withDbFactory( HighlyAvailableGraphDatabaseFactory dbFactory ) { this.factory = dbFactory; return this; } public ClusterManager build() { return new ClusterManager( this ); } }
1no label
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
13
final class AscendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
59
@SuppressWarnings("serial") protected static class CountableLock extends ReentrantReadWriteLock { protected int countLocks = 0; public CountableLock() { super(false); } }
0true
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockManager.java
50
public abstract class HttpCommandProcessor<T> extends AbstractTextCommandProcessor<T> { public static final String URI_MAPS = "/hazelcast/rest/maps/"; public static final String URI_QUEUES = "/hazelcast/rest/queues/"; public static final String URI_CLUSTER = "/hazelcast/rest/cluster"; public static final String URI_STATE_DUMP = "/hazelcast/rest/dump"; public static final String URI_MANCENTER_CHANGE_URL = "/hazelcast/rest/mancenter/changeurl"; protected HttpCommandProcessor(TextCommandService textCommandService) { super(textCommandService); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpCommandProcessor.java
545
public class TransactionContextProxy implements TransactionContext { final ClientTransactionManager transactionManager; final HazelcastClient client; final TransactionProxy transaction; final ClientConnection connection; private final Map<TransactionalObjectKey, TransactionalObject> txnObjectMap = new HashMap<TransactionalObjectKey, TransactionalObject>(2); private XAResourceProxy xaResource; public TransactionContextProxy(ClientTransactionManager transactionManager, TransactionOptions options) { this.transactionManager = transactionManager; this.client = transactionManager.getClient(); try { this.connection = client.getConnectionManager().tryToConnect(null); } catch (Exception e) { throw new HazelcastException("Could not obtain Connection!!!", e); } this.transaction = new TransactionProxy(client, options, connection); } public String getTxnId() { return transaction.getTxnId(); } public void beginTransaction() { transaction.begin(); } public void commitTransaction() throws TransactionException { transaction.commit(true); } public void rollbackTransaction() { transaction.rollback(); } public <K, V> TransactionalMap<K, V> getMap(String name) { return getTransactionalObject(MapService.SERVICE_NAME, name); } public <E> TransactionalQueue<E> getQueue(String name) { return getTransactionalObject(QueueService.SERVICE_NAME, name); } public <K, V> TransactionalMultiMap<K, V> getMultiMap(String name) { return getTransactionalObject(MultiMapService.SERVICE_NAME, name); } public <E> TransactionalList<E> getList(String name) { return getTransactionalObject(ListService.SERVICE_NAME, name); } public <E> TransactionalSet<E> getSet(String name) { return getTransactionalObject(SetService.SERVICE_NAME, name); } public <T extends TransactionalObject> T getTransactionalObject(String serviceName, String name) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + name + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, name); TransactionalObject obj = txnObjectMap.get(key); if (obj == null) { if (serviceName.equals(QueueService.SERVICE_NAME)) { obj = new ClientTxnQueueProxy(name, this); } else if (serviceName.equals(MapService.SERVICE_NAME)) { obj = new ClientTxnMapProxy(name, this); } else if (serviceName.equals(MultiMapService.SERVICE_NAME)) { obj = new ClientTxnMultiMapProxy(name, this); } else if (serviceName.equals(ListService.SERVICE_NAME)) { obj = new ClientTxnListProxy(name, this); } else if (serviceName.equals(SetService.SERVICE_NAME)) { obj = new ClientTxnSetProxy(name, this); } if (obj == null) { throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } txnObjectMap.put(key, obj); } return (T) obj; } public ClientConnection getConnection() { return connection; } public HazelcastClient getClient() { return client; } public ClientTransactionManager getTransactionManager() { return transactionManager; } public XAResource getXaResource() { if (xaResource == null) { xaResource = new XAResourceProxy(this); } return xaResource; } public boolean isXAManaged() { return transaction.getXid() != null; } private static class TransactionalObjectKey { private final String serviceName; private final String name; TransactionalObjectKey(String serviceName, String name) { this.serviceName = serviceName; this.name = name; } public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TransactionalObjectKey)) { return false; } TransactionalObjectKey that = (TransactionalObjectKey) o; if (!name.equals(that.name)) { return false; } if (!serviceName.equals(that.serviceName)) { return false; } return true; } public int hashCode() { int result = serviceName.hashCode(); result = 31 * result + name.hashCode(); return result; } } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_txn_TransactionContextProxy.java
522
public class TypesExistsRequestBuilder extends MasterNodeReadOperationRequestBuilder<TypesExistsRequest, TypesExistsResponse, TypesExistsRequestBuilder> { /** * @param indices What indices to check for types */ public TypesExistsRequestBuilder(IndicesAdminClient indicesClient, String... indices) { super((InternalIndicesAdminClient) indicesClient, new TypesExistsRequest(indices, Strings.EMPTY_ARRAY)); } TypesExistsRequestBuilder(IndicesAdminClient client) { super((InternalIndicesAdminClient) client, new TypesExistsRequest()); } /** * @param indices What indices to check for types */ public TypesExistsRequestBuilder setIndices(String[] indices) { request.indices(indices); return this; } /** * @param types The types to check if they exist */ public TypesExistsRequestBuilder setTypes(String... types) { request.types(types); return this; } /** * @param indicesOptions Specifies how to resolve indices that aren't active / ready and indices wildcard expressions */ public TypesExistsRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) { request.indicesOptions(indicesOptions); return this; } protected void doExecute(ActionListener<TypesExistsResponse> listener) { ((IndicesAdminClient) client).typesExists(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_exists_types_TypesExistsRequestBuilder.java
353
private class NodeShutdownRequestHandler extends BaseTransportRequestHandler<NodeShutdownRequest> { static final String ACTION = "/cluster/nodes/shutdown/node"; @Override public NodeShutdownRequest newInstance() { return new NodeShutdownRequest(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void messageReceived(final NodeShutdownRequest request, TransportChannel channel) throws Exception { if (disabled) { throw new ElasticsearchIllegalStateException("Shutdown is disabled"); } logger.info("shutting down in [{}]", delay); Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(delay.millis()); } catch (InterruptedException e) { // ignore } if (!request.exit) { logger.info("initiating requested shutdown (no exit)..."); try { node.close(); } catch (Exception e) { logger.warn("Failed to shutdown", e); } return; } boolean shutdownWithWrapper = false; if (System.getProperty("elasticsearch-service") != null) { try { Class wrapperManager = settings.getClassLoader().loadClass("org.tanukisoftware.wrapper.WrapperManager"); logger.info("initiating requested shutdown (using service)"); wrapperManager.getMethod("stopAndReturn", int.class).invoke(null, 0); shutdownWithWrapper = true; } catch (Throwable e) { logger.error("failed to initial shutdown on service wrapper", e); } } if (!shutdownWithWrapper) { logger.info("initiating requested shutdown..."); try { node.close(); } catch (Exception e) { logger.warn("Failed to shutdown", e); } finally { // make sure we initiate the shutdown hooks, so the Bootstrap#main thread will exit System.exit(0); } } } }); t.start(); channel.sendResponse(TransportResponse.Empty.INSTANCE); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
2,097
public class QueryPartitionOperation extends AbstractMapOperation implements PartitionAwareOperation { private Predicate predicate; private QueryResult result; public QueryPartitionOperation(String mapName, Predicate predicate) { super(mapName); this.predicate = predicate; } public QueryPartitionOperation() { } public void run() { result = mapService.queryOnPartition(name, predicate, getPartitionId()); } @Override public Object getResponse() { return result; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(predicate); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); predicate = in.readObject(); } }
1no label
hazelcast_src_main_java_com_hazelcast_map_operation_QueryPartitionOperation.java
240
public class OCacheLevelOneLocatorImpl implements OCacheLevelOneLocator { @Override public OCache threadLocalCache() { return new OUnboundedWeakCache(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_cache_OCacheLevelOneLocatorImpl.java
310
public enum ClusterHealthStatus { GREEN((byte) 0), YELLOW((byte) 1), RED((byte) 2); private byte value; ClusterHealthStatus(byte value) { this.value = value; } public byte value() { return value; } public static ClusterHealthStatus fromValue(byte value) { switch (value) { case 0: return GREEN; case 1: return YELLOW; case 2: return RED; default: throw new ElasticsearchIllegalArgumentException("No cluster health status for value [" + value + "]"); } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_health_ClusterHealthStatus.java
126
public enum METRIC_TYPE { CHRONO, COUNTER, STAT, SIZE, ENABLED, TEXT }
0true
commons_src_main_java_com_orientechnologies_common_profiler_OProfilerMBean.java
132
assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(1, service.getConnectedClients().size()); } }, 5);
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientServiceTest.java
188
public abstract class RecursiveTask<V> extends ForkJoinTask<V> { private static final long serialVersionUID = 5232453952276485270L; /** * The result of the computation. */ V result; /** * The main computation performed by this task. */ protected abstract V compute(); public final V getRawResult() { return result; } protected final void setRawResult(V value) { result = value; } /** * Implements execution conventions for RecursiveTask. */ protected final boolean exec() { result = compute(); return true; } }
0true
src_main_java_jsr166y_RecursiveTask.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
217
public class ThreadLocalManager { private static final Log LOG = LogFactory.getLog(ThreadLocalManager.class); private static final ThreadLocal<ThreadLocalManager> THREAD_LOCAL_MANAGER = new ThreadLocal<ThreadLocalManager>() { @Override protected ThreadLocalManager initialValue() { return new ThreadLocalManager(); } }; protected Map<Long, ThreadLocal> threadLocals = new LinkedHashMap<Long, ThreadLocal>(); public static void addThreadLocal(ThreadLocal threadLocal) { Long position; synchronized (threadLock) { count++; position = count; } THREAD_LOCAL_MANAGER.get().threadLocals.put(position, threadLocal); } public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type) { return createThreadLocal(type, true); } public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type, final boolean createInitialValue) { ThreadLocal<T> response = new ThreadLocal<T>() { @Override protected T initialValue() { addThreadLocal(this); if (!createInitialValue) { return null; } try { return type.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void set(T value) { super.get(); super.set(value); } }; return response; } public static void remove() { for (Map.Entry<Long, ThreadLocal> entry : THREAD_LOCAL_MANAGER.get().threadLocals.entrySet()) { if (LOG.isDebugEnabled()) { LOG.debug("Removing ThreadLocal #" + entry.getKey() + " from request thread."); } entry.getValue().remove(); } THREAD_LOCAL_MANAGER.get().threadLocals.clear(); THREAD_LOCAL_MANAGER.remove(); } private static Long count = 0L; private static final Object threadLock = new Object(); }
0true
common_src_main_java_org_broadleafcommerce_common_classloader_release_ThreadLocalManager.java
19
private class NetworkMessageSender extends SimpleChannelHandler { @Override public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception { Channel ctxChannel = ctx.getChannel(); openedChannel( getURI( (InetSocketAddress) ctxChannel.getRemoteAddress() ), ctxChannel ); channels.add( ctxChannel ); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent event ) throws Exception { final Message message = (Message) event.getMessage(); msgLog.debug( "Received: " + message ); receiver.receive( message ); } @Override public void channelClosed( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception { closedChannel( ctx.getChannel() ); channels.remove( ctx.getChannel() ); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e ) throws Exception { Throwable cause = e.getCause(); if ( ! ( cause instanceof ConnectException || cause instanceof RejectedExecutionException ) ) { msgLog.error( "Receive exception:", cause ); } } }
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkSender.java
302
static class DumEntryListener implements EntryListener { public void entryAdded(EntryEvent event) { } public void entryRemoved(EntryEvent event) { } public void entryUpdated(EntryEvent event) { } public void entryEvicted(EntryEvent event) { } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapBasicTest.java
295
public enum ThreadingModel { NONE((byte) 0), OPERATION((byte) 1), LISTENER((byte) 2), OPERATION_LISTENER((byte) 3); private byte id; ThreadingModel(byte id) { this.id = id; } public byte id() { return this.id; } /** * <tt>true</tt> if the actual operation the action represents will be executed * on a different thread than the calling thread (assuming it will be executed * on the same node). */ public boolean threadedOperation() { return this == OPERATION || this == OPERATION_LISTENER; } /** * <tt>true</tt> if the invocation of the action result listener will be executed * on a different thread (than the calling thread or an "expensive" thread, like the * IO thread). */ public boolean threadedListener() { return this == LISTENER || this == OPERATION_LISTENER; } public ThreadingModel addListener() { if (this == NONE) { return LISTENER; } if (this == OPERATION) { return OPERATION_LISTENER; } return this; } public ThreadingModel removeListener() { if (this == LISTENER) { return NONE; } if (this == OPERATION_LISTENER) { return OPERATION; } return this; } public ThreadingModel addOperation() { if (this == NONE) { return OPERATION; } if (this == LISTENER) { return OPERATION_LISTENER; } return this; } public ThreadingModel removeOperation() { if (this == OPERATION) { return NONE; } if (this == OPERATION_LISTENER) { return LISTENER; } return this; } public static ThreadingModel fromId(byte id) { if (id == 0) { return NONE; } else if (id == 1) { return OPERATION; } else if (id == 2) { return LISTENER; } else if (id == 3) { return OPERATION_LISTENER; } else { throw new ElasticsearchIllegalArgumentException("No threading model for [" + id + "]"); } } }
0true
src_main_java_org_elasticsearch_action_ThreadingModel.java
19
abstract static class Completion extends AtomicInteger implements Runnable { }
0true
src_main_java_jsr166e_CompletableFuture.java
5,831
public static class Field { // Fields that default to null or -1 are often set to their real default in HighlighterParseElement#parse private final String field; private int fragmentCharSize = -1; private int numberOfFragments = -1; private int fragmentOffset = -1; private String encoder; private String[] preTags; private String[] postTags; private Boolean scoreOrdered; private Boolean highlightFilter; private Boolean requireFieldMatch; private String highlighterType; private Boolean forceSource; private String fragmenter; private int boundaryMaxScan = -1; private Character[] boundaryChars = null; private Query highlightQuery; private int noMatchSize = -1; private Set<String> matchedFields; private Map<String, Object> options; private int phraseLimit = -1; public Field(String field) { this.field = field; } public String field() { return field; } public int fragmentCharSize() { return fragmentCharSize; } public void fragmentCharSize(int fragmentCharSize) { this.fragmentCharSize = fragmentCharSize; } public int numberOfFragments() { return numberOfFragments; } public void numberOfFragments(int numberOfFragments) { this.numberOfFragments = numberOfFragments; } public int fragmentOffset() { return fragmentOffset; } public void fragmentOffset(int fragmentOffset) { this.fragmentOffset = fragmentOffset; } public String encoder() { return encoder; } public void encoder(String encoder) { this.encoder = encoder; } public String[] preTags() { return preTags; } public void preTags(String[] preTags) { this.preTags = preTags; } public String[] postTags() { return postTags; } public void postTags(String[] postTags) { this.postTags = postTags; } public Boolean scoreOrdered() { return scoreOrdered; } public void scoreOrdered(boolean scoreOrdered) { this.scoreOrdered = scoreOrdered; } public Boolean highlightFilter() { return highlightFilter; } public void highlightFilter(boolean highlightFilter) { this.highlightFilter = highlightFilter; } public Boolean requireFieldMatch() { return requireFieldMatch; } public void requireFieldMatch(boolean requireFieldMatch) { this.requireFieldMatch = requireFieldMatch; } public String highlighterType() { return highlighterType; } public void highlighterType(String type) { this.highlighterType = type; } public Boolean forceSource() { return forceSource; } public void forceSource(boolean forceSource) { this.forceSource = forceSource; } public String fragmenter() { return fragmenter; } public void fragmenter(String fragmenter) { this.fragmenter = fragmenter; } public int boundaryMaxScan() { return boundaryMaxScan; } public void boundaryMaxScan(int boundaryMaxScan) { this.boundaryMaxScan = boundaryMaxScan; } public Character[] boundaryChars() { return boundaryChars; } public void boundaryChars(Character[] boundaryChars) { this.boundaryChars = boundaryChars; } public Query highlightQuery() { return highlightQuery; } public void highlightQuery(Query highlightQuery) { this.highlightQuery = highlightQuery; } public int noMatchSize() { return noMatchSize; } public void noMatchSize(int noMatchSize) { this.noMatchSize = noMatchSize; } public int phraseLimit() { return phraseLimit; } public void phraseLimit(int phraseLimit) { this.phraseLimit = phraseLimit; } public Set<String> matchedFields() { return matchedFields; } public void matchedFields(Set<String> matchedFields) { this.matchedFields = matchedFields; } public Map<String, Object> options() { return options; } public void options(Map<String, Object> options) { this.options = options; } }
1no label
src_main_java_org_elasticsearch_search_highlight_SearchContextHighlight.java
4,257
public class TranslogService extends AbstractIndexShardComponent { private final ThreadPool threadPool; private final IndexSettingsService indexSettingsService; private final IndexShard indexShard; private final Translog translog; private volatile TimeValue interval; private volatile int flushThresholdOperations; private volatile ByteSizeValue flushThresholdSize; private volatile TimeValue flushThresholdPeriod; private volatile boolean disableFlush; private volatile ScheduledFuture future; private final ApplySettings applySettings = new ApplySettings(); @Inject public TranslogService(ShardId shardId, @IndexSettings Settings indexSettings, IndexSettingsService indexSettingsService, ThreadPool threadPool, IndexShard indexShard, Translog translog) { super(shardId, indexSettings); this.threadPool = threadPool; this.indexSettingsService = indexSettingsService; this.indexShard = indexShard; this.translog = translog; this.flushThresholdOperations = componentSettings.getAsInt("flush_threshold_ops", componentSettings.getAsInt("flush_threshold", 5000)); this.flushThresholdSize = componentSettings.getAsBytesSize("flush_threshold_size", new ByteSizeValue(200, ByteSizeUnit.MB)); this.flushThresholdPeriod = componentSettings.getAsTime("flush_threshold_period", TimeValue.timeValueMinutes(30)); this.interval = componentSettings.getAsTime("interval", timeValueMillis(5000)); this.disableFlush = componentSettings.getAsBoolean("disable_flush", false); logger.debug("interval [{}], flush_threshold_ops [{}], flush_threshold_size [{}], flush_threshold_period [{}]", interval, flushThresholdOperations, flushThresholdSize, flushThresholdPeriod); this.future = threadPool.schedule(interval, ThreadPool.Names.SAME, new TranslogBasedFlush()); indexSettingsService.addListener(applySettings); } public void close() { indexSettingsService.removeListener(applySettings); this.future.cancel(true); } public static final String INDEX_TRANSLOG_FLUSH_INTERVAL = "index.translog.interval"; public static final String INDEX_TRANSLOG_FLUSH_THRESHOLD_OPS = "index.translog.flush_threshold_ops"; public static final String INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE = "index.translog.flush_threshold_size"; public static final String INDEX_TRANSLOG_FLUSH_THRESHOLD_PERIOD = "index.translog.flush_threshold_period"; public static final String INDEX_TRANSLOG_DISABLE_FLUSH = "index.translog.disable_flush"; class ApplySettings implements IndexSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { int flushThresholdOperations = settings.getAsInt(INDEX_TRANSLOG_FLUSH_THRESHOLD_OPS, TranslogService.this.flushThresholdOperations); if (flushThresholdOperations != TranslogService.this.flushThresholdOperations) { logger.info("updating flush_threshold_ops from [{}] to [{}]", TranslogService.this.flushThresholdOperations, flushThresholdOperations); TranslogService.this.flushThresholdOperations = flushThresholdOperations; } ByteSizeValue flushThresholdSize = settings.getAsBytesSize(INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE, TranslogService.this.flushThresholdSize); if (!flushThresholdSize.equals(TranslogService.this.flushThresholdSize)) { logger.info("updating flush_threshold_size from [{}] to [{}]", TranslogService.this.flushThresholdSize, flushThresholdSize); TranslogService.this.flushThresholdSize = flushThresholdSize; } TimeValue flushThresholdPeriod = settings.getAsTime(INDEX_TRANSLOG_FLUSH_THRESHOLD_PERIOD, TranslogService.this.flushThresholdPeriod); if (!flushThresholdPeriod.equals(TranslogService.this.flushThresholdPeriod)) { logger.info("updating flush_threshold_period from [{}] to [{}]", TranslogService.this.flushThresholdPeriod, flushThresholdPeriod); TranslogService.this.flushThresholdPeriod = flushThresholdPeriod; } TimeValue interval = settings.getAsTime(INDEX_TRANSLOG_FLUSH_INTERVAL, TranslogService.this.interval); if (!interval.equals(TranslogService.this.interval)) { logger.info("updating interval from [{}] to [{}]", TranslogService.this.interval, interval); TranslogService.this.interval = interval; } boolean disableFlush = settings.getAsBoolean(INDEX_TRANSLOG_DISABLE_FLUSH, TranslogService.this.disableFlush); if (disableFlush != TranslogService.this.disableFlush) { logger.info("updating disable_flush from [{}] to [{}]", TranslogService.this.disableFlush, disableFlush); TranslogService.this.disableFlush = disableFlush; } } } private TimeValue computeNextInterval() { return new TimeValue(interval.millis() + (ThreadLocalRandom.current().nextLong(interval.millis()))); } private class TranslogBasedFlush implements Runnable { private volatile long lastFlushTime = System.currentTimeMillis(); @Override public void run() { if (indexShard.state() == IndexShardState.CLOSED) { return; } // flush is disabled, but still reschedule if (disableFlush) { reschedule(); return; } if (indexShard.state() == IndexShardState.CREATED) { reschedule(); return; } int currentNumberOfOperations = translog.estimatedNumberOfOperations(); if (currentNumberOfOperations == 0) { reschedule(); return; } if (flushThresholdOperations > 0) { if (currentNumberOfOperations > flushThresholdOperations) { logger.trace("flushing translog, operations [{}], breached [{}]", currentNumberOfOperations, flushThresholdOperations); asyncFlushAndReschedule(); return; } } if (flushThresholdSize.bytes() > 0) { long sizeInBytes = translog.translogSizeInBytes(); if (sizeInBytes > flushThresholdSize.bytes()) { logger.trace("flushing translog, size [{}], breached [{}]", new ByteSizeValue(sizeInBytes), flushThresholdSize); asyncFlushAndReschedule(); return; } } if (flushThresholdPeriod.millis() > 0) { if ((threadPool.estimatedTimeInMillis() - lastFlushTime) > flushThresholdPeriod.millis()) { logger.trace("flushing translog, last_flush_time [{}], breached [{}]", lastFlushTime, flushThresholdPeriod); asyncFlushAndReschedule(); return; } } reschedule(); } private void reschedule() { future = threadPool.schedule(computeNextInterval(), ThreadPool.Names.SAME, this); } private void asyncFlushAndReschedule() { threadPool.executor(ThreadPool.Names.FLUSH).execute(new Runnable() { @Override public void run() { try { indexShard.flush(new Engine.Flush()); } catch (IllegalIndexShardStateException e) { // we are being closed, or in created state, ignore } catch (FlushNotAllowedEngineException e) { // ignore this exception, we are not allowed to perform flush } catch (Throwable e) { logger.warn("failed to flush shard on translog threshold", e); } lastFlushTime = threadPool.estimatedTimeInMillis(); if (indexShard.state() != IndexShardState.CLOSED) { future = threadPool.schedule(computeNextInterval(), ThreadPool.Names.SAME, TranslogBasedFlush.this); } } }); } } }
1no label
src_main_java_org_elasticsearch_index_translog_TranslogService.java
4,853
public class RestIndicesStatsAction extends BaseRestHandler { @Inject public RestIndicesStatsAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(GET, "/_stats", this); controller.registerHandler(GET, "/_stats/{metric}", this); controller.registerHandler(GET, "/_stats/{metric}/{indexMetric}", this); controller.registerHandler(GET, "/{index}/_stats", this); controller.registerHandler(GET, "/{index}/_stats/{metric}", this); } @Override public void handleRequest(final RestRequest request, final RestChannel channel) { IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest(); indicesStatsRequest.listenerThreaded(false); indicesStatsRequest.indicesOptions(IndicesOptions.fromRequest(request, indicesStatsRequest.indicesOptions())); indicesStatsRequest.indices(Strings.splitStringByCommaToArray(request.param("index"))); indicesStatsRequest.types(Strings.splitStringByCommaToArray(request.param("types"))); if (request.hasParam("groups")) { indicesStatsRequest.groups(Strings.splitStringByCommaToArray(request.param("groups"))); } if (request.hasParam("types")) { indicesStatsRequest.types(Strings.splitStringByCommaToArray(request.param("types"))); } Set<String> metrics = Strings.splitStringByCommaToSet(request.param("metric", "_all")); // short cut, if no metrics have been specified in URI if (metrics.size() == 1 && metrics.contains("_all")) { indicesStatsRequest.all(); } else { indicesStatsRequest.clear(); indicesStatsRequest.docs(metrics.contains("docs")); indicesStatsRequest.store(metrics.contains("store")); indicesStatsRequest.indexing(metrics.contains("indexing")); indicesStatsRequest.search(metrics.contains("search")); indicesStatsRequest.get(metrics.contains("get")); indicesStatsRequest.merge(metrics.contains("merge")); indicesStatsRequest.refresh(metrics.contains("refresh")); indicesStatsRequest.flush(metrics.contains("flush")); indicesStatsRequest.warmer(metrics.contains("warmer")); indicesStatsRequest.filterCache(metrics.contains("filter_cache")); indicesStatsRequest.idCache(metrics.contains("id_cache")); indicesStatsRequest.percolate(metrics.contains("percolate")); indicesStatsRequest.segments(metrics.contains("segments")); indicesStatsRequest.fieldData(metrics.contains("fielddata")); indicesStatsRequest.completion(metrics.contains("completion")); } if (indicesStatsRequest.completion() && (request.hasParam("fields") || request.hasParam("completion_fields"))) { indicesStatsRequest.completionFields(request.paramAsStringArray("completion_fields", request.paramAsStringArray("fields", Strings.EMPTY_ARRAY))); } if (indicesStatsRequest.fieldData() && (request.hasParam("fields") || request.hasParam("fielddata_fields"))) { indicesStatsRequest.fieldDataFields(request.paramAsStringArray("fielddata_fields", request.paramAsStringArray("fields", Strings.EMPTY_ARRAY))); } client.admin().indices().stats(indicesStatsRequest, new ActionListener<IndicesStatsResponse>() { @Override public void onResponse(IndicesStatsResponse response) { try { XContentBuilder builder = RestXContentBuilder.restContentBuilder(request); builder.startObject(); buildBroadcastShardsHeader(builder, response); response.toXContent(builder, request); builder.endObject(); channel.sendResponse(new XContentRestResponse(request, OK, builder)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } }
1no label
src_main_java_org_elasticsearch_rest_action_admin_indices_stats_RestIndicesStatsAction.java
1,494
public class CommitEdgesMap { public static final String ACTION = Tokens.makeNamespace(CommitEdgesMap.class) + ".action"; public enum Counters { OUT_EDGES_DROPPED, OUT_EDGES_KEPT, IN_EDGES_DROPPED, IN_EDGES_KEPT } public static Configuration createConfiguration(final Tokens.Action action) { final Configuration configuration = new EmptyConfiguration(); configuration.set(ACTION, action.name()); return configuration; } public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> { private boolean drop; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.drop = Tokens.Action.valueOf(context.getConfiguration().get(ACTION)).equals(Tokens.Action.DROP); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { Iterator<Edge> itty = value.getEdges(Direction.IN).iterator(); long edgesKept = 0; long edgesDropped = 0; while (itty.hasNext()) { if (this.drop) { if ((((StandardFaunusEdge) itty.next()).hasPaths())) { itty.remove(); edgesDropped++; } else edgesKept++; } else { if (!(((StandardFaunusEdge) itty.next()).hasPaths())) { itty.remove(); edgesDropped++; } else edgesKept++; } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.IN_EDGES_DROPPED, edgesDropped); DEFAULT_COMPAT.incrementContextCounter(context, Counters.IN_EDGES_KEPT, edgesKept); /////////////////// itty = value.getEdges(Direction.OUT).iterator(); edgesKept = 0; edgesDropped = 0; while (itty.hasNext()) { if (this.drop) { if ((((StandardFaunusEdge) itty.next()).hasPaths())) { itty.remove(); edgesDropped++; } else edgesKept++; } else { if (!(((StandardFaunusEdge) itty.next()).hasPaths())) { itty.remove(); edgesDropped++; } else edgesKept++; } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_DROPPED, edgesDropped); DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_KEPT, edgesKept); context.write(NullWritable.get(), value); } } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_CommitEdgesMap.java
565
public class AuthenticationFailureOperation extends AbstractClusterOperation implements JoinOperation { @Override public void run() { final NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine(); final Node node = nodeEngine.getNode(); final ILogger logger = nodeEngine.getLogger("com.hazelcast.security"); logger.severe("Authentication failed on master node! Node is going to shutdown now!"); node.shutdown(true); } }
1no label
hazelcast_src_main_java_com_hazelcast_cluster_AuthenticationFailureOperation.java
2,235
public class RandomScoreFunction extends ScoreFunction { private final PRNG prng; private int docBase; public RandomScoreFunction(long seed) { super(CombineFunction.MULT); this.prng = new PRNG(seed); } @Override public void setNextReader(AtomicReaderContext context) { this.docBase = context.docBase; } @Override public double score(int docId, float subQueryScore) { return prng.random(docBase + docId); } @Override public Explanation explainScore(int docId, Explanation subQueryExpl) { Explanation exp = new Explanation(); exp.setDescription("random score function (seed: " + prng.originalSeed + ")"); exp.addDetail(subQueryExpl); return exp; } /** * Algorithm largely based on {@link java.util.Random} except this one is not * thread safe and it incorporates the doc id on next(); */ static class PRNG { private static final long multiplier = 0x5DEECE66DL; private static final long addend = 0xBL; private static final long mask = (1L << 48) - 1; final long originalSeed; long seed; PRNG(long seed) { this.originalSeed = seed; this.seed = (seed ^ multiplier) & mask; } public float random(int doc) { if (doc == 0) { doc = 0xCAFEBAB; } long rand = doc; rand |= rand << 32; rand ^= rand; return nextFloat(rand); } public float nextFloat(long rand) { seed = (seed * multiplier + addend) & mask; rand ^= seed; double result = rand / (double)(1L << 54); return (float) result; } } }
1no label
src_main_java_org_elasticsearch_common_lucene_search_function_RandomScoreFunction.java
55
public class TitanConfigurationException extends TitanException { private static final long serialVersionUID = 4056436257763972423L; /** * @param msg Exception message */ public TitanConfigurationException(String msg) { super(msg); } /** * @param msg Exception message * @param cause Cause of the exception */ public TitanConfigurationException(String msg, Throwable cause) { super(msg, cause); } /** * Constructs an exception with a generic message * * @param cause Cause of the exception */ public TitanConfigurationException(Throwable cause) { this("Exception in graph database configuration", cause); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanConfigurationException.java
643
public class BroadleafResourceHttpRequestHandler extends ResourceHttpRequestHandler { private static final Log LOG = LogFactory.getLog(BroadleafResourceHttpRequestHandler.class); // XML Configured generated resource handlers protected List<AbstractGeneratedResourceHandler> handlers; @javax.annotation.Resource(name = "blResourceBundlingService") protected ResourceBundlingService bundlingService; /** * Checks to see if the requested path corresponds to a registered bundle. If so, returns the generated bundle. * Otherwise, checks to see if any of the configured GeneratedResourceHandlers can handle the given request. * If neither of those cases match, delegates to the normal ResourceHttpRequestHandler */ @Override protected Resource getResource(HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (bundlingService.hasBundle(path)) { return bundlingService.getBundle(path); } if (handlers != null) { for (AbstractGeneratedResourceHandler handler : handlers) { if (handler.canHandle(path)) { return handler.getResource(path, getLocations()); } } } return super.getResource(request); } public boolean isBundleRequest(HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); return bundlingService.hasBundle(path); } /** * @return a clone of the locations list that is in {@link ResourceHttpRequestHandler}. Note that we must use * reflection to access this field as it is marked private. */ @SuppressWarnings("unchecked") public List<Resource> getLocations() { try { List<Resource> locations = (List<Resource>) FieldUtils.readField(this, "locations", true); return new ArrayList<Resource>(locations); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /* *********** */ /* BOILERPLATE */ /* *********** */ public List<AbstractGeneratedResourceHandler> getHandlers() { return handlers; } public void setHandlers(List<AbstractGeneratedResourceHandler> handlers) { this.handlers = handlers; } }
1no label
common_src_main_java_org_broadleafcommerce_common_web_resource_BroadleafResourceHttpRequestHandler.java
484
public class ClientCallFuture<V> implements ICompletableFuture<V>, Callback { private Object response; private final ClientRequest request; private final ClientExecutionServiceImpl executionService; private final ClientInvocationServiceImpl invocationService; private final SerializationService serializationService; private final EventHandler handler; public final int heartBeatInterval; public final int retryCount; public final int retryWaitTime; private AtomicInteger reSendCount = new AtomicInteger(); private volatile ClientConnection connection; private List<ExecutionCallbackNode> callbackNodeList = new LinkedList<ExecutionCallbackNode>(); public ClientCallFuture(HazelcastClient client, ClientRequest request, EventHandler handler) { int interval = client.clientProperties.HEARTBEAT_INTERVAL.getInteger(); this.heartBeatInterval = interval > 0 ? interval : Integer.parseInt(PROP_HEARTBEAT_INTERVAL_DEFAULT); int retry = client.clientProperties.RETRY_COUNT.getInteger(); this.retryCount = retry > 0 ? retry : Integer.parseInt(PROP_RETRY_COUNT_DEFAULT); int waitTime = client.clientProperties.RETRY_WAIT_TIME.getInteger(); this.retryWaitTime = waitTime > 0 ? waitTime : Integer.parseInt(PROP_RETRY_WAIT_TIME_DEFAULT); this.invocationService = (ClientInvocationServiceImpl) client.getInvocationService(); this.executionService = (ClientExecutionServiceImpl) client.getClientExecutionService(); this.serializationService = client.getSerializationService(); this.request = request; this.handler = handler; } public boolean cancel(boolean mayInterruptIfRunning) { return false; } public boolean isCancelled() { return false; } public boolean isDone() { return response != null; } public V get() throws InterruptedException, ExecutionException { try { return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (TimeoutException ignored) { return null; } } public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (response == null) { long waitMillis = unit.toMillis(timeout); if (waitMillis > 0) { synchronized (this) { while (waitMillis > 0 && response == null) { long start = Clock.currentTimeMillis(); this.wait(Math.min(heartBeatInterval, waitMillis)); long elapsed = Clock.currentTimeMillis() - start; waitMillis -= elapsed; if (!isConnectionHealthy(elapsed)) { break; } } } } } return resolveResponse(); } private boolean isConnectionHealthy(long elapsed) { if (elapsed >= heartBeatInterval) { return connection.isHeartBeating(); } return true; } public void notify(Object response) { if (response == null) { throw new IllegalArgumentException("response can't be null"); } if (response instanceof TargetNotMemberException) { if (resend()) { return; } } if (response instanceof TargetDisconnectedException || response instanceof HazelcastInstanceNotActiveException) { if (request instanceof RetryableRequest || invocationService.isRedoOperation()) { if (resend()) { return; } } } setResponse(response); } private void setResponse(Object response) { synchronized (this) { if (this.response != null && handler == null) { throw new IllegalArgumentException("The Future.set method can only be called once"); } if (handler != null && !(response instanceof Throwable)) { handler.onListenerRegister(); } if (this.response != null && !(response instanceof Throwable)) { String uuid = serializationService.toObject(this.response); String alias = serializationService.toObject(response); invocationService.reRegisterListener(uuid, alias, request.getCallId()); return; } this.response = response; this.notifyAll(); } for (ExecutionCallbackNode node : callbackNodeList) { runAsynchronous(node.callback, node.executor); } callbackNodeList.clear(); } private V resolveResponse() throws ExecutionException, TimeoutException, InterruptedException { if (response instanceof Throwable) { ExceptionUtil.fixRemoteStackTrace((Throwable) response, Thread.currentThread().getStackTrace()); if (response instanceof ExecutionException) { throw (ExecutionException) response; } if (response instanceof TimeoutException) { throw (TimeoutException) response; } if (response instanceof Error) { throw (Error) response; } if (response instanceof InterruptedException) { throw (InterruptedException) response; } throw new ExecutionException((Throwable) response); } if (response == null) { throw new TimeoutException(); } return (V) response; } public void andThen(ExecutionCallback<V> callback) { andThen(callback, executionService.getAsyncExecutor()); } public void andThen(ExecutionCallback<V> callback, Executor executor) { synchronized (this) { if (response != null) { runAsynchronous(callback, executor); return; } callbackNodeList.add(new ExecutionCallbackNode(callback, executor)); } } public ClientRequest getRequest() { return request; } public EventHandler getHandler() { return handler; } public ClientConnection getConnection() { return connection; } public boolean resend() { if (request.isSingleConnection()) { return false; } if (handler == null && reSendCount.incrementAndGet() > retryCount) { return false; } executionService.execute(new ReSendTask()); return true; } private void runAsynchronous(final ExecutionCallback callback, Executor executor) { executor.execute(new Runnable() { public void run() { try { callback.onResponse(serializationService.toObject(resolveResponse())); } catch (Throwable t) { callback.onFailure(t); } } }); } public void setConnection(ClientConnection connection) { this.connection = connection; } class ReSendTask implements Runnable { public void run() { try { sleep(); invocationService.reSend(ClientCallFuture.this); } catch (Exception e) { if (handler != null) { invocationService.registerFailedListener(ClientCallFuture.this); } else { setResponse(e); } } } private void sleep(){ try { Thread.sleep(250); } catch (InterruptedException ignored) { } } } class ExecutionCallbackNode { final ExecutionCallback callback; final Executor executor; ExecutionCallbackNode(ExecutionCallback callback, Executor executor) { this.callback = callback; this.executor = executor; } } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientCallFuture.java
4,754
public class RestController extends AbstractLifecycleComponent<RestController> { private final PathTrie<RestHandler> getHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> postHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> putHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> deleteHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> headHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final PathTrie<RestHandler> optionsHandlers = new PathTrie<RestHandler>(RestUtils.REST_DECODER); private final RestHandlerFilter handlerFilter = new RestHandlerFilter(); // non volatile since the assumption is that pre processors are registered on startup private RestFilter[] filters = new RestFilter[0]; @Inject public RestController(Settings settings) { super(settings); } @Override protected void doStart() throws ElasticsearchException { } @Override protected void doStop() throws ElasticsearchException { } @Override protected void doClose() throws ElasticsearchException { for (RestFilter filter : filters) { filter.close(); } } /** * Registers a pre processor to be executed before the rest request is actually handled. */ public synchronized void registerFilter(RestFilter preProcessor) { RestFilter[] copy = new RestFilter[filters.length + 1]; System.arraycopy(filters, 0, copy, 0, filters.length); copy[filters.length] = preProcessor; Arrays.sort(copy, new Comparator<RestFilter>() { @Override public int compare(RestFilter o1, RestFilter o2) { return o2.order() - o1.order(); } }); filters = copy; } /** * Registers a rest handler to be execute when the provided method and path match the request. */ public void registerHandler(RestRequest.Method method, String path, RestHandler handler) { switch (method) { case GET: getHandlers.insert(path, handler); break; case DELETE: deleteHandlers.insert(path, handler); break; case POST: postHandlers.insert(path, handler); break; case PUT: putHandlers.insert(path, handler); break; case OPTIONS: optionsHandlers.insert(path, handler); break; case HEAD: headHandlers.insert(path, handler); break; default: throw new ElasticsearchIllegalArgumentException("Can't handle [" + method + "] for path [" + path + "]"); } } /** * Returns a filter chain (if needed) to execute. If this method returns null, simply execute * as usual. */ @Nullable public RestFilterChain filterChainOrNull(RestFilter executionFilter) { if (filters.length == 0) { return null; } return new ControllerFilterChain(executionFilter); } /** * Returns a filter chain with the final filter being the provided filter. */ public RestFilterChain filterChain(RestFilter executionFilter) { return new ControllerFilterChain(executionFilter); } public void dispatchRequest(final RestRequest request, final RestChannel channel) { if (filters.length == 0) { try { executeHandler(request, channel); } catch (Exception e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1); } } } else { ControllerFilterChain filterChain = new ControllerFilterChain(handlerFilter); filterChain.continueProcessing(request, channel); } } void executeHandler(RestRequest request, RestChannel channel) { final RestHandler handler = getHandler(request); if (handler != null) { handler.handleRequest(request, channel); } else { if (request.method() == RestRequest.Method.OPTIONS) { // when we have OPTIONS request, simply send OK by default (with the Access Control Origin header which gets automatically added) StringRestResponse response = new StringRestResponse(OK); channel.sendResponse(response); } else { channel.sendResponse(new StringRestResponse(BAD_REQUEST, "No handler found for uri [" + request.uri() + "] and method [" + request.method() + "]")); } } } private RestHandler getHandler(RestRequest request) { String path = getPath(request); RestRequest.Method method = request.method(); if (method == RestRequest.Method.GET) { return getHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.POST) { return postHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.PUT) { return putHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.DELETE) { return deleteHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.HEAD) { return headHandlers.retrieve(path, request.params()); } else if (method == RestRequest.Method.OPTIONS) { return optionsHandlers.retrieve(path, request.params()); } else { return null; } } private String getPath(RestRequest request) { // we use rawPath since we don't want to decode it while processing the path resolution // so we can handle things like: // my_index/my_type/http%3A%2F%2Fwww.google.com return request.rawPath(); } class ControllerFilterChain implements RestFilterChain { private final RestFilter executionFilter; private volatile int index; ControllerFilterChain(RestFilter executionFilter) { this.executionFilter = executionFilter; } @Override public void continueProcessing(RestRequest request, RestChannel channel) { try { int loc = index; index++; if (loc > filters.length) { throw new ElasticsearchIllegalStateException("filter continueProcessing was called more than expected"); } else if (loc == filters.length) { executionFilter.process(request, channel, this); } else { RestFilter preProcessor = filters[loc]; preProcessor.process(request, channel, this); } } catch (Exception e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response for uri [" + request.uri() + "]", e1); } } } } class RestHandlerFilter extends RestFilter { @Override public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) { executeHandler(request, channel); } } }
1no label
src_main_java_org_elasticsearch_rest_RestController.java
118
public interface ArchivedPagePublisher { void processPageArchive(Page page, String basePageKey); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_message_ArchivedPagePublisher.java
797
public class OFunction { public static final String CLASS_NAME = "OFunction"; protected ODocument document; /** * Creates a new function. */ public OFunction() { document = new ODocument(CLASS_NAME); setLanguage("SQL"); } /** * Creates a new function wrapping the saved document. * * @param iDocument * Document to assign */ public OFunction(final ODocument iDocument) { document = iDocument; } /** * Loads a function. * * @param iRid * RID of the function to load */ public OFunction(final ORecordId iRid) { document = ODatabaseRecordThreadLocal.INSTANCE.get().load(iRid); } public String getName() { return document.field("name"); } public OFunction setName(final String iName) { document.field("name", iName); return this; } public String getCode() { return document.field("code"); } public OFunction setCode(final String iCode) { document.field("code", iCode); saveChanges(); return this; } public String getLanguage() { return document.field("language"); } public OFunction setLanguage(final String iLanguage) { document.field("language", iLanguage); return this; } public List<String> getParameters() { return document.field("parameters"); } public OFunction setParameters(final List<String> iParameters) { document.field("parameters", iParameters); return this; } public boolean isIdempotent() { final Boolean idempotent = document.field("idempotent"); return idempotent != null && idempotent; } public OFunction setIdempotent(final boolean iIdempotent) { document.field("idempotent", iIdempotent); saveChanges(); return this; } public Object execute(final Object... iArgs) { return executeInContext(null, iArgs); } public Object executeInContext(final OCommandContext iContext, final Object... iArgs) { final OCommandExecutorFunction command = new OCommandExecutorFunction(); command.parse(new OCommandFunction(getName())); final List<String> params = getParameters(); // CONVERT PARAMETERS IN A MAP Map<Object, Object> args = null; if (iArgs.length > 0) { args = new LinkedHashMap<Object, Object>(); for (int i = 0; i < iArgs.length; ++i) { // final Object argValue = ORecordSerializerStringAbstract.getTypeValue(iArgs[i].toString()); final Object argValue = iArgs[i]; if (params != null && i < params.size()) args.put(params.get(i), argValue); else args.put("param" + i, argValue); } } return command.executeInContext(iContext, args); } public Object execute(final Map<Object, Object> iArgs) { final long start = Orient.instance().getProfiler().startChrono(); final OCommandExecutorScript command = new OCommandExecutorScript(); command.parse(new OCommandScript(getLanguage(), getCode())); final Object result = command.execute(iArgs); if (Orient.instance().getProfiler().isRecording()) Orient .instance() .getProfiler() .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".function.execute", "Time to execute a function", start, "db.*.function.execute"); return result; } public ORID getId() { return document.getIdentity(); } @Override public String toString() { return getName(); } /** * Save pending changes if any. */ private void saveChanges() { document.save(); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_metadata_function_OFunction.java
3,123
Arrays.sort(segmentsArr, new Comparator<Segment>() { @Override public int compare(Segment o1, Segment o2) { return (int) (o1.getGeneration() - o2.getGeneration()); } });
1no label
src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java
227
public interface ModuleConfigurationDao { public ModuleConfiguration readById(Long id); public ModuleConfiguration save(ModuleConfiguration config); public void delete(ModuleConfiguration config); public List<ModuleConfiguration> readAllByType(ModuleConfigurationType type); public List<ModuleConfiguration> readActiveByType(ModuleConfigurationType type); public List<ModuleConfiguration> readByType(Class<? extends ModuleConfiguration> type); /** * Returns the number of milliseconds that the current date/time will be cached for queries before refreshing. * This aids in query caching, otherwise every query that utilized current date would be different and caching * would be ineffective. * * @return the milliseconds to cache the current date/time */ public Long getCurrentDateResolution(); /** * Sets the number of milliseconds that the current date/time will be cached for queries before refreshing. * This aids in query caching, otherwise every query that utilized current date would be different and caching * would be ineffective. * * @param currentDateResolution the milliseconds to cache the current date/time */ public void setCurrentDateResolution(Long currentDateResolution); }
0true
common_src_main_java_org_broadleafcommerce_common_config_dao_ModuleConfigurationDao.java
122
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientReconnectTest extends HazelcastTestSupport { @After @Before public void cleanup() throws Exception { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testClientReconnectOnClusterDown() throws Exception { final HazelcastInstance h1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(); final CountDownLatch connectedLatch = new CountDownLatch(2); client.getLifecycleService().addLifecycleListener(new LifecycleListener() { @Override public void stateChanged(LifecycleEvent event) { connectedLatch.countDown(); } }); IMap<String, String> m = client.getMap("default"); h1.shutdown(); Hazelcast.newHazelcastInstance(); assertOpenEventually(connectedLatch, 10); assertNull(m.put("test", "test")); assertEquals("test", m.get("test")); } @Test public void testClientReconnectOnClusterDownWithEntryListeners() throws Exception { HazelcastInstance h1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(); final CountDownLatch connectedLatch = new CountDownLatch(2); client.getLifecycleService().addLifecycleListener(new LifecycleListener() { @Override public void stateChanged(LifecycleEvent event) { connectedLatch.countDown(); } }); final IMap<String, String> m = client.getMap("default"); final CountDownLatch latch = new CountDownLatch(1); final EntryAdapter<String, String> listener = new EntryAdapter<String, String>() { public void onEntryEvent(EntryEvent<String, String> event) { latch.countDown(); } }; m.addEntryListener(listener, true); h1.shutdown(); Hazelcast.newHazelcastInstance(); assertOpenEventually(connectedLatch, 10); m.put("key", "value"); assertOpenEventually(latch, 10); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientReconnectTest.java
73
public abstract class TransactionManagerProvider extends Service { public TransactionManagerProvider( String name ) { super( name ); } public abstract AbstractTransactionManager loadTransactionManager( String txLogDir, XaDataSourceManager xaDataSourceManager, KernelPanicEventGenerator kpe, RemoteTxHook rollbackHook, StringLogger msgLog, FileSystemAbstraction fileSystem, TransactionStateFactory stateFactory ); }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TransactionManagerProvider.java
488
public final class ClientClusterServiceImpl implements ClientClusterService { private static final ILogger LOGGER = Logger.getLogger(ClientClusterService.class); private static final int SLEEP_TIME = 1000; private final HazelcastClient client; private final ClientConnectionManagerImpl connectionManager; private final ClusterListenerThread clusterThread; private final AtomicReference<Map<Address, MemberImpl>> membersRef = new AtomicReference<Map<Address, MemberImpl>>(); private final ConcurrentMap<String, MembershipListener> listeners = new ConcurrentHashMap<String, MembershipListener>(); public ClientClusterServiceImpl(HazelcastClient client) { this.client = client; this.connectionManager = (ClientConnectionManagerImpl) client.getConnectionManager(); clusterThread = new ClusterListenerThread(client.getThreadGroup(), client.getName() + ".cluster-listener"); final ClientConfig clientConfig = getClientConfig(); final List<ListenerConfig> listenerConfigs = client.getClientConfig().getListenerConfigs(); if (listenerConfigs != null && !listenerConfigs.isEmpty()) { for (ListenerConfig listenerConfig : listenerConfigs) { EventListener listener = listenerConfig.getImplementation(); if (listener == null) { try { listener = ClassLoaderUtil.newInstance(clientConfig.getClassLoader(), listenerConfig.getClassName()); } catch (Exception e) { LOGGER.severe(e); } } if (listener instanceof MembershipListener) { addMembershipListenerWithoutInit((MembershipListener) listener); } } } } public MemberImpl getMember(Address address) { final Map<Address, MemberImpl> members = membersRef.get(); return members != null ? members.get(address) : null; } public MemberImpl getMember(String uuid) { final Collection<MemberImpl> memberList = getMemberList(); for (MemberImpl member : memberList) { if (uuid.equals(member.getUuid())) { return member; } } return null; } public Collection<MemberImpl> getMemberList() { final Map<Address, MemberImpl> members = membersRef.get(); return members != null ? members.values() : Collections.<MemberImpl>emptySet(); } public Address getMasterAddress() { final Collection<MemberImpl> memberList = getMemberList(); return !memberList.isEmpty() ? memberList.iterator().next().getAddress() : null; } public int getSize() { return getMemberList().size(); } public long getClusterTime() { return Clock.currentTimeMillis(); } public Client getLocalClient() { ClientPrincipal cp = connectionManager.getPrincipal(); ClientConnection conn = clusterThread.conn; return new ClientImpl(cp != null ? cp.getUuid() : null, conn != null ? conn.getLocalSocketAddress() : null); } private SerializationService getSerializationService() { return client.getSerializationService(); } public String addMembershipListenerWithInit(MembershipListener listener) { final String id = UuidUtil.buildRandomUuidString(); listeners.put(id, listener); if (listener instanceof InitialMembershipListener) { // TODO: needs sync with membership events... final Cluster cluster = client.getCluster(); ((InitialMembershipListener) listener).init(new InitialMembershipEvent(cluster, cluster.getMembers())); } return id; } public String addMembershipListenerWithoutInit(MembershipListener listener) { final String id = UUID.randomUUID().toString(); listeners.put(id, listener); return id; } private void initMembershipListener() { for (MembershipListener membershipListener : listeners.values()) { if (membershipListener instanceof InitialMembershipListener) { // TODO: needs sync with membership events... final Cluster cluster = client.getCluster(); ((InitialMembershipListener) membershipListener).init(new InitialMembershipEvent(cluster, cluster.getMembers())); } } } public boolean removeMembershipListener(String registrationId) { return listeners.remove(registrationId) != null; } public void start() { clusterThread.start(); try { clusterThread.await(); } catch (InterruptedException e) { throw new HazelcastException(e); } initMembershipListener(); // started } public void stop() { clusterThread.shutdown(); } private final class ClusterListenerThread extends Thread { private volatile ClientConnection conn; private final List<MemberImpl> members = new LinkedList<MemberImpl>(); private final CountDownLatch latch = new CountDownLatch(1); private ClusterListenerThread(ThreadGroup group, String name) { super(group, name); } public void await() throws InterruptedException { latch.await(); } public void run() { while (!Thread.currentThread().isInterrupted()) { try { if (conn == null) { try { conn = pickConnection(); } catch (Exception e) { LOGGER.severe("Error while connecting to cluster!", e); client.getLifecycleService().shutdown(); latch.countDown(); return; } } getInvocationService().triggerFailedListeners(); loadInitialMemberList(); listenMembershipEvents(); } catch (Exception e) { if (client.getLifecycleService().isRunning()) { if (LOGGER.isFinestEnabled()) { LOGGER.warning("Error while listening cluster events! -> " + conn, e); } else { LOGGER.warning("Error while listening cluster events! -> " + conn + ", Error: " + e.toString()); } } connectionManager.markOwnerConnectionAsClosed(); IOUtil.closeResource(conn); conn = null; fireConnectionEvent(true); } try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { latch.countDown(); break; } } } private ClientInvocationServiceImpl getInvocationService() { return (ClientInvocationServiceImpl) client.getInvocationService(); } private ClientConnection pickConnection() throws Exception { final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>(); if (!members.isEmpty()) { for (MemberImpl member : members) { socketAddresses.add(member.getInetSocketAddress()); } Collections.shuffle(socketAddresses); } socketAddresses.addAll(getConfigAddresses()); return connectToOne(socketAddresses); } private void loadInitialMemberList() throws Exception { final SerializationService serializationService = getSerializationService(); final AddMembershipListenerRequest request = new AddMembershipListenerRequest(); final SerializableCollection coll = (SerializableCollection) connectionManager.sendAndReceive(request, conn); Map<String, MemberImpl> prevMembers = Collections.emptyMap(); if (!members.isEmpty()) { prevMembers = new HashMap<String, MemberImpl>(members.size()); for (MemberImpl member : members) { prevMembers.put(member.getUuid(), member); } members.clear(); } for (Data data : coll) { members.add((MemberImpl) serializationService.toObject(data)); } updateMembersRef(); LOGGER.info(membersString()); final List<MembershipEvent> events = new LinkedList<MembershipEvent>(); final Set<Member> eventMembers = Collections.unmodifiableSet(new LinkedHashSet<Member>(members)); for (MemberImpl member : members) { final MemberImpl former = prevMembers.remove(member.getUuid()); if (former == null) { events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_ADDED, eventMembers)); } } for (MemberImpl member : prevMembers.values()) { events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, eventMembers)); } for (MembershipEvent event : events) { fireMembershipEvent(event); } latch.countDown(); } private void listenMembershipEvents() throws IOException { final SerializationService serializationService = getSerializationService(); while (!Thread.currentThread().isInterrupted()) { final Data clientResponseData = conn.read(); final ClientResponse clientResponse = serializationService.toObject(clientResponseData); final Object eventObject = serializationService.toObject(clientResponse.getResponse()); final ClientMembershipEvent event = (ClientMembershipEvent) eventObject; final MemberImpl member = (MemberImpl) event.getMember(); boolean membersUpdated = false; if (event.getEventType() == MembershipEvent.MEMBER_ADDED) { members.add(member); membersUpdated = true; } else if (event.getEventType() == ClientMembershipEvent.MEMBER_REMOVED) { members.remove(member); membersUpdated = true; // getConnectionManager().removeConnectionPool(member.getAddress()); //TODO } else if (event.getEventType() == ClientMembershipEvent.MEMBER_ATTRIBUTE_CHANGED) { MemberAttributeChange memberAttributeChange = event.getMemberAttributeChange(); Map<Address, MemberImpl> memberMap = membersRef.get(); if (memberMap != null) { for (MemberImpl target : memberMap.values()) { if (target.getUuid().equals(memberAttributeChange.getUuid())) { final MemberAttributeOperationType operationType = memberAttributeChange.getOperationType(); final String key = memberAttributeChange.getKey(); final Object value = memberAttributeChange.getValue(); target.updateAttribute(operationType, key, value); MemberAttributeEvent memberAttributeEvent = new MemberAttributeEvent( client.getCluster(), target, operationType, key, value); fireMemberAttributeEvent(memberAttributeEvent); break; } } } } if (membersUpdated) { ((ClientPartitionServiceImpl) client.getClientPartitionService()).refreshPartitions(); updateMembersRef(); LOGGER.info(membersString()); fireMembershipEvent(new MembershipEvent(client.getCluster(), member, event.getEventType(), Collections.unmodifiableSet(new LinkedHashSet<Member>(members)))); } } } private void fireMembershipEvent(final MembershipEvent event) { client.getClientExecutionService().executeInternal(new Runnable() { public void run() { for (MembershipListener listener : listeners.values()) { if (event.getEventType() == MembershipEvent.MEMBER_ADDED) { listener.memberAdded(event); } else { listener.memberRemoved(event); } } } }); } private void fireMemberAttributeEvent(final MemberAttributeEvent event) { client.getClientExecutionService().executeInternal(new Runnable() { @Override public void run() { for (MembershipListener listener : listeners.values()) { listener.memberAttributeChanged(event); } } }); } private void updateMembersRef() { final Map<Address, MemberImpl> map = new LinkedHashMap<Address, MemberImpl>(members.size()); for (MemberImpl member : members) { map.put(member.getAddress(), member); } membersRef.set(Collections.unmodifiableMap(map)); } void shutdown() { interrupt(); final ClientConnection c = conn; if (c != null) { c.close(); } } } private ClientConnection connectToOne(final Collection<InetSocketAddress> socketAddresses) throws Exception { final ClientNetworkConfig networkConfig = getClientConfig().getNetworkConfig(); final int connectionAttemptLimit = networkConfig.getConnectionAttemptLimit(); final int connectionAttemptPeriod = networkConfig.getConnectionAttemptPeriod(); int attempt = 0; Throwable lastError = null; while (true) { final long nextTry = Clock.currentTimeMillis() + connectionAttemptPeriod; for (InetSocketAddress isa : socketAddresses) { Address address = new Address(isa); try { final ClientConnection connection = connectionManager.ownerConnection(address); fireConnectionEvent(false); return connection; } catch (IOException e) { lastError = e; LOGGER.finest("IO error during initial connection...", e); } catch (AuthenticationException e) { lastError = e; LOGGER.warning("Authentication error on " + address, e); } } if (attempt++ >= connectionAttemptLimit) { break; } final long remainingTime = nextTry - Clock.currentTimeMillis(); LOGGER.warning( String.format("Unable to get alive cluster connection," + " try in %d ms later, attempt %d of %d.", Math.max(0, remainingTime), attempt, connectionAttemptLimit)); if (remainingTime > 0) { try { Thread.sleep(remainingTime); } catch (InterruptedException e) { break; } } } throw new IllegalStateException("Unable to connect to any address in the config!", lastError); } private void fireConnectionEvent(boolean disconnected) { final LifecycleServiceImpl lifecycleService = (LifecycleServiceImpl) client.getLifecycleService(); final LifecycleState state = disconnected ? LifecycleState.CLIENT_DISCONNECTED : LifecycleState.CLIENT_CONNECTED; lifecycleService.fireLifecycleEvent(state); } private Collection<InetSocketAddress> getConfigAddresses() { final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>(); final List<String> addresses = getClientConfig().getAddresses(); Collections.shuffle(addresses); for (String address : addresses) { socketAddresses.addAll(AddressHelper.getSocketAddresses(address)); } return socketAddresses; } private ClientConfig getClientConfig() { return client.getClientConfig(); } private String membersString() { StringBuilder sb = new StringBuilder("\n\nMembers ["); final Collection<MemberImpl> members = getMemberList(); sb.append(members != null ? members.size() : 0); sb.append("] {"); if (members != null) { for (Member member : members) { sb.append("\n\t").append(member); } } sb.append("\n}\n"); return sb.toString(); } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientClusterServiceImpl.java
3,923
public class QueryParseContext { private static ThreadLocal<String[]> typesContext = new ThreadLocal<String[]>(); public static void setTypes(String[] types) { typesContext.set(types); } public static String[] getTypes() { return typesContext.get(); } public static String[] setTypesWithPrevious(String[] types) { String[] old = typesContext.get(); setTypes(types); return old; } public static void removeTypes() { typesContext.remove(); } private final Index index; private boolean propagateNoCache = false; IndexQueryParserService indexQueryParser; private final Map<String, Filter> namedFilters = Maps.newHashMap(); private final MapperQueryParser queryParser = new MapperQueryParser(this); private XContentParser parser; private EnumSet<ParseField.Flag> parseFlags = ParseField.EMPTY_FLAGS; public QueryParseContext(Index index, IndexQueryParserService indexQueryParser) { this.index = index; this.indexQueryParser = indexQueryParser; } public void parseFlags(EnumSet<ParseField.Flag> parseFlags) { this.parseFlags = parseFlags == null ? ParseField.EMPTY_FLAGS : parseFlags; } public EnumSet<ParseField.Flag> parseFlags() { return parseFlags; } public void reset(XContentParser jp) { this.parseFlags = ParseField.EMPTY_FLAGS; this.lookup = null; this.parser = jp; this.namedFilters.clear(); } public Index index() { return this.index; } public XContentParser parser() { return parser; } public AnalysisService analysisService() { return indexQueryParser.analysisService; } public CacheRecycler cacheRecycler() { return indexQueryParser.cacheRecycler; } public ScriptService scriptService() { return indexQueryParser.scriptService; } public MapperService mapperService() { return indexQueryParser.mapperService; } public IndexEngine indexEngine() { return indexQueryParser.indexEngine; } @Nullable public SimilarityService similarityService() { return indexQueryParser.similarityService; } public Similarity searchSimilarity() { return indexQueryParser.similarityService != null ? indexQueryParser.similarityService.similarity() : null; } public IndexCache indexCache() { return indexQueryParser.indexCache; } public IndexFieldDataService fieldData() { return indexQueryParser.fieldDataService; } public String defaultField() { return indexQueryParser.defaultField(); } public boolean queryStringLenient() { return indexQueryParser.queryStringLenient(); } public MapperQueryParser queryParser(QueryParserSettings settings) { queryParser.reset(settings); return queryParser; } public Filter cacheFilter(Filter filter, @Nullable CacheKeyFilter.Key cacheKey) { if (filter == null) { return null; } if (this.propagateNoCache || filter instanceof NoCacheFilter) { return filter; } if (cacheKey != null) { filter = new CacheKeyFilter.Wrapper(filter, cacheKey); } return indexQueryParser.indexCache.filter().cache(filter); } public void addNamedFilter(String name, Filter filter) { namedFilters.put(name, filter); } public void addNamedQuery(String name, Query query) { namedFilters.put(name, new QueryWrapperFilter(query)); } public ImmutableMap<String, Filter> copyNamedFilters() { if (namedFilters.isEmpty()) { return ImmutableMap.of(); } return ImmutableMap.copyOf(namedFilters); } @Nullable public Query parseInnerQuery() throws IOException, QueryParsingException { // move to START object XContentParser.Token token; if (parser.currentToken() != XContentParser.Token.START_OBJECT) { token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT) { throw new QueryParsingException(index, "[_na] query malformed, must start with start_object"); } } token = parser.nextToken(); if (token != XContentParser.Token.FIELD_NAME) { throw new QueryParsingException(index, "[_na] query malformed, no field after start_object"); } String queryName = parser.currentName(); // move to the next START_OBJECT token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT && token != XContentParser.Token.START_ARRAY) { throw new QueryParsingException(index, "[_na] query malformed, no field after start_object"); } QueryParser queryParser = indexQueryParser.queryParser(queryName); if (queryParser == null) { throw new QueryParsingException(index, "No query registered for [" + queryName + "]"); } Query result = queryParser.parse(this); if (parser.currentToken() == XContentParser.Token.END_OBJECT || parser.currentToken() == XContentParser.Token.END_ARRAY) { // if we are at END_OBJECT, move to the next one... parser.nextToken(); } return result; } @Nullable public Filter parseInnerFilter() throws IOException, QueryParsingException { // move to START object XContentParser.Token token; if (parser.currentToken() != XContentParser.Token.START_OBJECT) { token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT) { throw new QueryParsingException(index, "[_na] filter malformed, must start with start_object"); } } token = parser.nextToken(); if (token != XContentParser.Token.FIELD_NAME) { // empty filter if (token == XContentParser.Token.END_OBJECT || token == XContentParser.Token.VALUE_NULL) { return null; } throw new QueryParsingException(index, "[_na] filter malformed, no field after start_object"); } String filterName = parser.currentName(); // move to the next START_OBJECT or START_ARRAY token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT && token != XContentParser.Token.START_ARRAY) { throw new QueryParsingException(index, "[_na] filter malformed, no field after start_object"); } FilterParser filterParser = indexQueryParser.filterParser(filterName); if (filterParser == null) { throw new QueryParsingException(index, "No filter registered for [" + filterName + "]"); } Filter result = executeFilterParser(filterParser); if (parser.currentToken() == XContentParser.Token.END_OBJECT || parser.currentToken() == XContentParser.Token.END_ARRAY) { // if we are at END_OBJECT, move to the next one... parser.nextToken(); } return result; } public Filter parseInnerFilter(String filterName) throws IOException, QueryParsingException { FilterParser filterParser = indexQueryParser.filterParser(filterName); if (filterParser == null) { throw new QueryParsingException(index, "No filter registered for [" + filterName + "]"); } return executeFilterParser(filterParser); } private Filter executeFilterParser(FilterParser filterParser) throws IOException { final boolean propagateNoCache = this.propagateNoCache; // first safe the state that we need to restore this.propagateNoCache = false; // parse the subfilter with caching, that's fine Filter result = filterParser.parse(this); // now make sure we set propagateNoCache to true if it is true already or if the result is // an instance of NoCacheFilter or if we used to be true! all filters above will // be not cached ie. wrappers of this filter! this.propagateNoCache |= (result instanceof NoCacheFilter) || propagateNoCache; return result; } public FieldMapper fieldMapper(String name) { FieldMappers fieldMappers = indexQueryParser.mapperService.smartNameFieldMappers(name, getTypes()); if (fieldMappers == null) { return null; } return fieldMappers.mapper(); } public String indexName(String name) { FieldMapper smartMapper = fieldMapper(name); if (smartMapper == null) { return name; } return smartMapper.names().indexName(); } public Set<String> simpleMatchToIndexNames(String pattern) { return indexQueryParser.mapperService.simpleMatchToIndexNames(pattern, getTypes()); } public MapperService.SmartNameFieldMappers smartFieldMappers(String name) { return indexQueryParser.mapperService.smartName(name, getTypes()); } public FieldMapper smartNameFieldMapper(String name) { return indexQueryParser.mapperService.smartNameFieldMapper(name, getTypes()); } public MapperService.SmartNameObjectMapper smartObjectMapper(String name) { return indexQueryParser.mapperService.smartNameObjectMapper(name, getTypes()); } /** * Returns the narrowed down explicit types, or, if not set, all types. */ public Collection<String> queryTypes() { String[] types = getTypes(); if (types == null || types.length == 0) { return mapperService().types(); } if (types.length == 1 && types[0].equals("_all")) { return mapperService().types(); } return Arrays.asList(types); } private SearchLookup lookup = null; public SearchLookup lookup() { SearchContext current = SearchContext.current(); if (current != null) { return current.lookup(); } if (lookup == null) { lookup = new SearchLookup(mapperService(), fieldData(), null); } return lookup; } public long nowInMillis() { SearchContext current = SearchContext.current(); if (current != null) { return current.nowInMillis(); } return System.currentTimeMillis(); } }
1no label
src_main_java_org_elasticsearch_index_query_QueryParseContext.java
71
public interface StaticAssetStorageDao { StaticAssetStorage create(); StaticAssetStorage readStaticAssetStorageById(Long id); public StaticAssetStorage readStaticAssetStorageByStaticAssetId(Long id); StaticAssetStorage save(StaticAssetStorage assetStorage); void delete(StaticAssetStorage assetStorage); public Blob createBlob(MultipartFile uploadedFile) throws IOException; }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_dao_StaticAssetStorageDao.java
3,721
final class SecondsBasedEntryTaskScheduler<K, V> implements EntryTaskScheduler<K, V> { public static final int INITIAL_CAPACITY = 10; public static final double FACTOR = 1000d; private static final long INITIAL_TIME_MILLIS = Clock.currentTimeMillis(); private static final Comparator<ScheduledEntry> SCHEDULED_ENTRIES_COMPARATOR = new Comparator<ScheduledEntry>() { @Override public int compare(ScheduledEntry o1, ScheduledEntry o2) { if (o1.getScheduleStartTimeInNanos() > o2.getScheduleStartTimeInNanos()) { return 1; } else if (o1.getScheduleStartTimeInNanos() < o2.getScheduleStartTimeInNanos()) { return -1; } return 0; } }; private final ConcurrentMap<Object, Integer> secondsOfKeys = new ConcurrentHashMap<Object, Integer>(1000); private final ConcurrentMap<Integer, ConcurrentMap<Object, ScheduledEntry<K, V>>> scheduledEntries = new ConcurrentHashMap<Integer, ConcurrentMap<Object, ScheduledEntry<K, V>>>(1000); private final ScheduledExecutorService scheduledExecutorService; private final ScheduledEntryProcessor entryProcessor; private final ScheduleType scheduleType; private final ConcurrentMap<Integer, ScheduledFuture> scheduledTaskMap = new ConcurrentHashMap<Integer, ScheduledFuture>(1000); SecondsBasedEntryTaskScheduler(ScheduledExecutorService scheduledExecutorService, ScheduledEntryProcessor entryProcessor, ScheduleType scheduleType) { this.scheduledExecutorService = scheduledExecutorService; this.entryProcessor = entryProcessor; this.scheduleType = scheduleType; } @Override public boolean schedule(long delayMillis, K key, V value) { if (scheduleType.equals(ScheduleType.POSTPONE)) { return schedulePostponeEntry(delayMillis, key, value); } else if (scheduleType.equals(ScheduleType.SCHEDULE_IF_NEW)) { return scheduleIfNew(delayMillis, key, value); } else if (scheduleType.equals(ScheduleType.FOR_EACH)) { return scheduleEntry(delayMillis, key, value); } else { throw new RuntimeException("Undefined schedule type."); } } @Override public Set<K> flush(Set<K> keys) { if (scheduleType.equals(ScheduleType.FOR_EACH)) { return flushComparingTimeKeys(keys); } Set<ScheduledEntry<K, V>> res = new HashSet<ScheduledEntry<K, V>>(keys.size()); Set<K> processedKeys = new HashSet<K>(); for (K key : keys) { final Integer second = secondsOfKeys.remove(key); if (second != null) { final ConcurrentMap<Object, ScheduledEntry<K, V>> entries = scheduledEntries.get(second); if (entries != null) { processedKeys.add(key); res.add(entries.remove(key)); } } } entryProcessor.process(this, sortForEntryProcessing(res)); return processedKeys; } private Set flushComparingTimeKeys(Set keys) { Set<ScheduledEntry<K, V>> res = new HashSet<ScheduledEntry<K, V>>(keys.size()); Set<TimeKey> candidateKeys = new HashSet<TimeKey>(); Set processedKeys = new HashSet(); for (Object key : keys) { for (Object skey : secondsOfKeys.keySet()) { TimeKey timeKey = (TimeKey) skey; if (key.equals(timeKey.getKey())) { candidateKeys.add(timeKey); } } } for (TimeKey timeKey : candidateKeys) { final Integer second = secondsOfKeys.remove(timeKey); if (second != null) { final ConcurrentMap<Object, ScheduledEntry<K, V>> entries = scheduledEntries.get(second); if (entries != null) { res.add(entries.remove(timeKey)); processedKeys.add(timeKey.getKey()); } } } entryProcessor.process(this, sortForEntryProcessing(res)); return processedKeys; } @Override public ScheduledEntry<K, V> cancel(K key) { ScheduledEntry<K, V> result = null; if (scheduleType.equals(ScheduleType.FOR_EACH)) { return cancelComparingTimeKey(key); } final Integer second = secondsOfKeys.remove(key); if (second != null) { final ConcurrentMap<Object, ScheduledEntry<K, V>> entries = scheduledEntries.get(second); if (entries != null) { result = entries.remove(key); if (entries.isEmpty()) { ScheduledFuture removed = scheduledTaskMap.remove(second); if (removed != null) { removed.cancel(false); } } } } return result; } @Override public ScheduledEntry<K, V> get(K key) { if (scheduleType.equals(ScheduleType.FOR_EACH)) { return getComparingTimeKey(key); } final Integer second = secondsOfKeys.get(key); if (second != null) { final ConcurrentMap<Object, ScheduledEntry<K, V>> entries = scheduledEntries.get(second); if (entries != null) { return entries.get(key); } } return null; } public ScheduledEntry<K, V> cancelComparingTimeKey(K key) { Set<TimeKey> candidateKeys = new HashSet<TimeKey>(); for (Object tkey : secondsOfKeys.keySet()) { TimeKey timeKey = (TimeKey) tkey; if (timeKey.getKey().equals(key)) { candidateKeys.add(timeKey); } } ScheduledEntry<K, V> result = null; for (TimeKey timeKey : candidateKeys) { final Integer second = secondsOfKeys.remove(timeKey); if (second != null) { final ConcurrentMap<Object, ScheduledEntry<K, V>> entries = scheduledEntries.get(second); if (entries != null) { result = entries.remove(timeKey); if (entries.isEmpty()) { ScheduledFuture removed = scheduledTaskMap.remove(second); if (removed != null) { removed.cancel(false); } } } } } return result; } public ScheduledEntry<K, V> getComparingTimeKey(K key) { Set<TimeKey> candidateKeys = new HashSet<TimeKey>(); for (Object tkey : secondsOfKeys.keySet()) { TimeKey timeKey = (TimeKey) tkey; if (timeKey.getKey().equals(key)) { candidateKeys.add(timeKey); } } ScheduledEntry<K, V> result = null; for (TimeKey timeKey : candidateKeys) { final Integer second = secondsOfKeys.get(timeKey); if (second != null) { final ConcurrentMap<Object, ScheduledEntry<K, V>> entries = scheduledEntries.get(second); if (entries != null) { result = entries.get(timeKey); } } } return result; } private boolean schedulePostponeEntry(long delayMillis, K key, V value) { final int delaySeconds = ceilToSecond(delayMillis); final Integer newSecond = findRelativeSecond(delayMillis); final Integer existingSecond = secondsOfKeys.put(key, newSecond); if (existingSecond != null) { if (existingSecond.equals(newSecond)) { return false; } removeKeyFromSecond(key, existingSecond); } doSchedule(key, new ScheduledEntry<K, V>(key, value, delayMillis, delaySeconds), newSecond); return true; } private boolean scheduleEntry(long delayMillis, K key, V value) { final int delaySeconds = ceilToSecond(delayMillis); final Integer newSecond = findRelativeSecond(delayMillis); long time = System.nanoTime(); TimeKey timeKey = new TimeKey(key, time); secondsOfKeys.put(timeKey, newSecond); doSchedule(timeKey, new ScheduledEntry<K, V>(key, value, delayMillis, delaySeconds, time), newSecond); return true; } private boolean scheduleIfNew(long delayMillis, K key, V value) { final int delaySeconds = ceilToSecond(delayMillis); final Integer newSecond = findRelativeSecond(delayMillis); if (secondsOfKeys.putIfAbsent(key, newSecond) != null) { return false; } doSchedule(key, new ScheduledEntry<K, V>(key, value, delayMillis, delaySeconds), newSecond); return true; } private int findRelativeSecond(long delayMillis) { long now = Clock.currentTimeMillis(); long d = (now + delayMillis - INITIAL_TIME_MILLIS); return ceilToSecond(d); } private int ceilToSecond(long delayMillis) { return (int) Math.ceil(delayMillis / FACTOR); } private void doSchedule(Object mapKey, ScheduledEntry<K, V> entry, Integer second) { ConcurrentMap<Object, ScheduledEntry<K, V>> entries = scheduledEntries.get(second); boolean shouldSchedule = false; if (entries == null) { entries = new ConcurrentHashMap<Object, ScheduledEntry<K, V>>(INITIAL_CAPACITY); ConcurrentMap<Object, ScheduledEntry<K, V>> existingScheduleKeys = scheduledEntries.putIfAbsent(second, entries); if (existingScheduleKeys != null) { entries = existingScheduleKeys; } else { // we created the second // so we will schedule its execution shouldSchedule = true; } } entries.put(mapKey, entry); if (shouldSchedule) { schedule(second, entry.getActualDelaySeconds()); } } private void removeKeyFromSecond(Object key, Integer existingSecond) { ConcurrentMap<Object, ScheduledEntry<K, V>> scheduledKeys = scheduledEntries.get(existingSecond); if (scheduledKeys != null) { scheduledKeys.remove(key); if (scheduledKeys.isEmpty()) { ScheduledFuture removed = scheduledTaskMap.remove(existingSecond); if (removed != null) { removed.cancel(false); } } } } private void schedule(final Integer second, final int delaySeconds) { EntryProcessorExecutor command = new EntryProcessorExecutor(second); ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(command, delaySeconds, TimeUnit.SECONDS); scheduledTaskMap.put(second, scheduledFuture); } private final class EntryProcessorExecutor implements Runnable { private final Integer second; private EntryProcessorExecutor(Integer second) { this.second = second; } @Override public void run() { scheduledTaskMap.remove(second); final Map<Object, ScheduledEntry<K, V>> entries = scheduledEntries.remove(second); if (entries == null || entries.isEmpty()) { return; } Set<ScheduledEntry<K, V>> values = new HashSet<ScheduledEntry<K, V>>(entries.size()); for (Map.Entry<Object, ScheduledEntry<K, V>> entry : entries.entrySet()) { Integer removed = secondsOfKeys.remove(entry.getKey()); if (removed != null) { values.add(entry.getValue()); } } //sort entries asc by schedule times and send to processor. entryProcessor.process(SecondsBasedEntryTaskScheduler.this, sortForEntryProcessing(values)); } } private List<ScheduledEntry<K, V>> sortForEntryProcessing(Set<ScheduledEntry<K, V>> coll) { if (coll == null || coll.isEmpty()) { return Collections.EMPTY_LIST; } final List<ScheduledEntry<K, V>> sortedEntries = new ArrayList<ScheduledEntry<K, V>>(coll); Collections.sort(sortedEntries, SCHEDULED_ENTRIES_COMPARATOR); return sortedEntries; } @Override public int size() { return secondsOfKeys.size(); } public void cancelAll() { secondsOfKeys.clear(); scheduledEntries.clear(); for (ScheduledFuture task : scheduledTaskMap.values()) { task.cancel(false); } scheduledTaskMap.clear(); } @Override public String toString() { return "EntryTaskScheduler{" + "secondsOfKeys=" + secondsOfKeys.size() + ", scheduledEntries [" + scheduledEntries.size() + "] =" + scheduledEntries.keySet() + '}'; } }
1no label
hazelcast_src_main_java_com_hazelcast_util_scheduler_SecondsBasedEntryTaskScheduler.java
166
public interface URLHandler extends Serializable{ public abstract Long getId(); public abstract void setId(Long id); public abstract String getIncomingURL(); public abstract void setIncomingURL(String incomingURL); public abstract String getNewURL(); public abstract void setNewURL(String newURL); public abstract URLRedirectType getUrlRedirectType(); public void setUrlRedirectType(URLRedirectType redirectType); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_url_domain_URLHandler.java
61
public class OModificationLock { private volatile boolean veto = false; private volatile boolean throwException = false; private final ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<Thread>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); /** * Tells the lock that thread is going to perform data modifications in storage. This method allows to perform several data * modifications in parallel. */ public void requestModificationLock() { lock.readLock().lock(); if (!veto) return; if (throwException) { lock.readLock().unlock(); throw new OModificationOperationProhibitedException("Modification requests are prohibited"); } boolean wasInterrupted = false; Thread thread = Thread.currentThread(); waiters.add(thread); while (veto) { LockSupport.park(this); if (Thread.interrupted()) wasInterrupted = true; } waiters.remove(thread); if (wasInterrupted) thread.interrupt(); } /** * Tells the lock that thread is finished to perform to perform modifications in storage. */ public void releaseModificationLock() { lock.readLock().unlock(); } /** * After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till * {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished. */ public void prohibitModifications() { lock.writeLock().lock(); try { throwException = false; veto = true; } finally { lock.writeLock().unlock(); } } /** * After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till * {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished. * * @param throwException * If <code>true</code> {@link OModificationOperationProhibitedException} exception will be thrown on * {@link #requestModificationLock()} call. */ public void prohibitModifications(boolean throwException) { lock.writeLock().lock(); try { this.throwException = throwException; veto = true; } finally { lock.writeLock().unlock(); } } /** * After this method finished execution all threads that are waiting to perform data modifications in storage will be awaken and * will be allowed to continue their execution. */ public void allowModifications() { veto = false; for (Thread thread : waiters) LockSupport.unpark(thread); } }
0true
commons_src_main_java_com_orientechnologies_common_concur_lock_OModificationLock.java
273
public class SelectNoMembers implements MemberSelector { @Override public boolean select(Member member) { return false; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_tasks_SelectNoMembers.java
703
createIndexAction.execute(new CreateIndexRequest(index).cause("auto(bulk api)"), new ActionListener<CreateIndexResponse>() { @Override public void onResponse(CreateIndexResponse result) { if (counter.decrementAndGet() == 0) { executeBulk(bulkRequest, startTime, listener); } } @Override public void onFailure(Throwable e) { if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) { // we have the index, do it if (counter.decrementAndGet() == 0) { executeBulk(bulkRequest, startTime, listener); } } else if (failed.compareAndSet(false, true)) { listener.onFailure(e); } } });
1no label
src_main_java_org_elasticsearch_action_bulk_TransportBulkAction.java
354
Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(delay.millis()); } catch (InterruptedException e) { // ignore } if (!request.exit) { logger.info("initiating requested shutdown (no exit)..."); try { node.close(); } catch (Exception e) { logger.warn("Failed to shutdown", e); } return; } boolean shutdownWithWrapper = false; if (System.getProperty("elasticsearch-service") != null) { try { Class wrapperManager = settings.getClassLoader().loadClass("org.tanukisoftware.wrapper.WrapperManager"); logger.info("initiating requested shutdown (using service)"); wrapperManager.getMethod("stopAndReturn", int.class).invoke(null, 0); shutdownWithWrapper = true; } catch (Throwable e) { logger.error("failed to initial shutdown on service wrapper", e); } } if (!shutdownWithWrapper) { logger.info("initiating requested shutdown..."); try { node.close(); } catch (Exception e) { logger.warn("Failed to shutdown", e); } finally { // make sure we initiate the shutdown hooks, so the Bootstrap#main thread will exit System.exit(0); } } } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
1,161
final class NewModuleWizardPage extends NewUnitWizardPage { private String version="1.0.0"; NewModuleWizardPage() { super("New Ceylon Module", "Create a runnable Ceylon module with module and package descriptors.", CEYLON_NEW_MODULE); setUnitName("run"); } String getVersion() { return version; } @Override String getCompilationUnitLabel() { return "Runnable compilation unit: "; } @Override String getPackageLabel() { return "Module name: "; } @Override String getSharedPackageLabel() { return "Create module with shared root package"; // (visible to other modules) } @Override void createControls(Composite composite) { Text name = createPackageField(composite); createVersionField(composite); createSharedField(composite); createNameField(composite); createSeparator(composite); createFolderField(composite); name.forceFocus(); } @Override boolean isComplete() { return super.isComplete() && !getPackageFragment().isDefaultPackage(); } @Override boolean packageNameIsLegal(String packageName) { return !packageName.isEmpty() && super.packageNameIsLegal(packageName); } @Override String getIllegalPackageNameMessage() { return "Please enter a legal module name (a period-separated list of all-lowercase identifiers)."; } @Override String[] getFileNames() { return new String[] { "module", "package", getUnitName() }; } void createVersionField(Composite composite) { Label versionLabel = new Label(composite, SWT.LEFT | SWT.WRAP); versionLabel.setText("Module version:"); GridData lgd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); lgd.horizontalSpan = 1; versionLabel.setLayoutData(lgd); final Text versionName = new Text(composite, SWT.SINGLE | SWT.BORDER); GridData ngd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); ngd.horizontalSpan = 2; ngd.grabExcessHorizontalSpace = true; versionName.setLayoutData(ngd); versionName.setText(version); versionName.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { version = versionName.getText(); setPageComplete(isComplete()); } }); new Label(composite, SWT.NONE); } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_wizard_NewModuleWizardPage.java
647
public class TransportDeleteIndexTemplateAction extends TransportMasterNodeOperationAction<DeleteIndexTemplateRequest, DeleteIndexTemplateResponse> { private final MetaDataIndexTemplateService indexTemplateService; @Inject public TransportDeleteIndexTemplateAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, MetaDataIndexTemplateService indexTemplateService) { super(settings, transportService, clusterService, threadPool); this.indexTemplateService = indexTemplateService; } @Override protected String executor() { // we go async right away return ThreadPool.Names.SAME; } @Override protected String transportAction() { return DeleteIndexTemplateAction.NAME; } @Override protected DeleteIndexTemplateRequest newRequest() { return new DeleteIndexTemplateRequest(); } @Override protected DeleteIndexTemplateResponse newResponse() { return new DeleteIndexTemplateResponse(); } @Override protected ClusterBlockException checkBlock(DeleteIndexTemplateRequest request, ClusterState state) { return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, ""); } @Override protected void masterOperation(final DeleteIndexTemplateRequest request, final ClusterState state, final ActionListener<DeleteIndexTemplateResponse> listener) throws ElasticsearchException { indexTemplateService.removeTemplates(new MetaDataIndexTemplateService.RemoveRequest(request.name()).masterTimeout(request.masterNodeTimeout()), new MetaDataIndexTemplateService.RemoveListener() { @Override public void onResponse(MetaDataIndexTemplateService.RemoveResponse response) { listener.onResponse(new DeleteIndexTemplateResponse(response.acknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to delete templates [{}]", t, request.name()); listener.onFailure(t); } }); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_template_delete_TransportDeleteIndexTemplateAction.java
185
(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_jsr166y_Phaser.java
136
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientTimeoutTest { @Test(timeout = 20000, expected = IllegalStateException.class) public void testTimeoutToOutsideNetwork() throws Exception { ClientConfig clientConfig = new ClientConfig(); clientConfig.getGroupConfig().setName( "dev" ).setPassword( "dev-pass" ); clientConfig.getNetworkConfig().addAddress( "8.8.8.8:5701" ); HazelcastInstance client = HazelcastClient.newHazelcastClient( clientConfig ); IList<Object> list = client.getList( "test" ); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientTimeoutTest.java
3,427
private class ProxyEventProcessor implements StripedRunnable { final EventType type; final String serviceName; final DistributedObject object; private ProxyEventProcessor(EventType eventType, String serviceName, DistributedObject object) { this.type = eventType; this.serviceName = serviceName; this.object = object; } @Override public void run() { DistributedObjectEvent event = new DistributedObjectEvent(type, serviceName, object); for (DistributedObjectListener listener : listeners.values()) { if (EventType.CREATED.equals(type)) { listener.distributedObjectCreated(event); } else if (EventType.DESTROYED.equals(type)) { listener.distributedObjectDestroyed(event); } } } @Override public int getKey() { return object.getId().hashCode(); } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_ProxyServiceImpl.java
1,286
public class RatingSortType implements Serializable { private static final long serialVersionUID = 1L; private static final Map<String, RatingSortType> TYPES = new HashMap<String, RatingSortType>(); public static final RatingSortType MOST_HELPFUL = new RatingSortType("MOST_HELPFUL"); public static final RatingSortType MOST_RECENT = new RatingSortType("MOST_RECENT"); public static final RatingSortType DEFAULT = new RatingSortType("DEFAULT"); public static RatingSortType getInstance(final String type) { return TYPES.get(type); } private String type; public RatingSortType() { } public RatingSortType(final String type) { setType(type); } public String getType() { return type; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RatingSortType other = (RatingSortType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_rating_service_type_RatingSortType.java
5,470
public static Comparator<AtomicArray.Entry<? extends QuerySearchResultProvider>> QUERY_RESULT_ORDERING = new Comparator<AtomicArray.Entry<? extends QuerySearchResultProvider>>() { @Override public int compare(AtomicArray.Entry<? extends QuerySearchResultProvider> o1, AtomicArray.Entry<? extends QuerySearchResultProvider> o2) { int i = o1.value.shardTarget().index().compareTo(o2.value.shardTarget().index()); if (i == 0) { i = o1.value.shardTarget().shardId() - o2.value.shardTarget().shardId(); } return i; } };
1no label
src_main_java_org_elasticsearch_search_controller_SearchPhaseController.java
32
static final class ThenCompose<T,U> extends Completion { final CompletableFuture<? extends T> src; final Fun<? super T, CompletableFuture<U>> fn; final CompletableFuture<U> dst; final Executor executor; ThenCompose(CompletableFuture<? extends T> src, Fun<? super T, CompletableFuture<U>> fn, CompletableFuture<U> dst, Executor executor) { this.src = src; this.fn = fn; this.dst = dst; this.executor = executor; } public final void run() { final CompletableFuture<? extends T> a; final Fun<? super T, CompletableFuture<U>> fn; final CompletableFuture<U> dst; Object r; T t; Throwable ex; Executor e; if ((dst = this.dst) != null && (fn = this.fn) != null && (a = this.src) != null && (r = a.result) != null && compareAndSet(0, 1)) { if (r instanceof AltResult) { ex = ((AltResult)r).ex; t = null; } else { ex = null; @SuppressWarnings("unchecked") T tr = (T) r; t = tr; } CompletableFuture<U> c = null; U u = null; boolean complete = false; if (ex == null) { if ((e = executor) != null) e.execute(new AsyncCompose<T,U>(t, fn, dst)); else { try { if ((c = fn.apply(t)) == null) ex = new NullPointerException(); } catch (Throwable rex) { ex = rex; } } } if (c != null) { ThenCopy<U> d = null; Object s; if ((s = c.result) == null) { CompletionNode p = new CompletionNode (d = new ThenCopy<U>(c, dst)); while ((s = c.result) == null) { if (UNSAFE.compareAndSwapObject (c, COMPLETIONS, p.next = c.completions, p)) break; } } if (s != null && (d == null || d.compareAndSet(0, 1))) { complete = true; if (s instanceof AltResult) { ex = ((AltResult)s).ex; // no rewrap u = null; } else { @SuppressWarnings("unchecked") U us = (U) s; u = us; } } } if (complete || ex != null) dst.internalComplete(u, ex); if (c != null) c.helpPostComplete(); } } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
1,271
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Response>>() { @Override public ActionFuture<Response> doWithNode(DiscoveryNode node) throws ElasticsearchException { return proxy.execute(node, request); } });
1no label
src_main_java_org_elasticsearch_client_transport_support_InternalTransportClusterAdminClient.java
97
private static class TxLockElement { private final Transaction tx; // access to these is guarded by synchronized blocks private int readCount; private int writeCount; private boolean movedOn; TxLockElement( Transaction tx ) { this.tx = tx; } boolean isFree() { return readCount == 0 && writeCount == 0; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_RWLock.java
50
public interface SubQuery { /** * Whether this query is fitted, i.e. whether the returned results must be filtered in-memory. * @return */ public boolean isFitted(); /** * Whether this query respects the sort order of parent query or requires sorting in-memory. * @return */ public boolean isSorted(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_QueryDescription.java
604
public class TransportGetSettingsAction extends TransportMasterNodeReadOperationAction<GetSettingsRequest, GetSettingsResponse> { private final SettingsFilter settingsFilter; @Inject public TransportGetSettingsAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, SettingsFilter settingsFilter) { super(settings, transportService, clusterService, threadPool); this.settingsFilter = settingsFilter; } @Override protected String transportAction() { return GetSettingsAction.NAME; } @Override protected String executor() { // Very lightweight operation return ThreadPool.Names.SAME; } @Override protected GetSettingsRequest newRequest() { return new GetSettingsRequest(); } @Override protected GetSettingsResponse newResponse() { return new GetSettingsResponse(); } @Override protected void masterOperation(GetSettingsRequest request, ClusterState state, ActionListener<GetSettingsResponse> listener) throws ElasticsearchException { request.indices(state.metaData().concreteIndices(request.indices(), request.indicesOptions())); ImmutableOpenMap.Builder<String, Settings> indexToSettingsBuilder = ImmutableOpenMap.builder(); for (String concreteIndex : request.indices()) { IndexMetaData indexMetaData = state.getMetaData().index(concreteIndex); if (indexMetaData == null) { continue; } Settings settings = settingsFilter.filterSettings(indexMetaData.settings()); if (!CollectionUtils.isEmpty(request.names())) { ImmutableSettings.Builder settingsBuilder = ImmutableSettings.builder(); for (Map.Entry<String, String> entry : settings.getAsMap().entrySet()) { if (Regex.simpleMatch(request.names(), entry.getKey())) { settingsBuilder.put(entry.getKey(), entry.getValue()); } } settings = settingsBuilder.build(); } indexToSettingsBuilder.put(concreteIndex, settings); } listener.onResponse(new GetSettingsResponse(indexToSettingsBuilder.build())); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_settings_get_TransportGetSettingsAction.java
212
public final class CustomPostingsHighlighter extends XPostingsHighlighter { private static final Snippet[] EMPTY_SNIPPET = new Snippet[0]; private static final Passage[] EMPTY_PASSAGE = new Passage[0]; private final CustomPassageFormatter passageFormatter; private final int noMatchSize; private final int totalContentLength; private final String[] fieldValues; private final int[] fieldValuesOffsets; private int currentValueIndex = 0; private BreakIterator breakIterator; public CustomPostingsHighlighter(CustomPassageFormatter passageFormatter, List<Object> fieldValues, boolean mergeValues, int maxLength, int noMatchSize) { super(maxLength); this.passageFormatter = passageFormatter; this.noMatchSize = noMatchSize; if (mergeValues) { String rawValue = Strings.collectionToDelimitedString(fieldValues, String.valueOf(getMultiValuedSeparator(""))); String fieldValue = rawValue.substring(0, Math.min(rawValue.length(), maxLength)); this.fieldValues = new String[]{fieldValue}; this.fieldValuesOffsets = new int[]{0}; this.totalContentLength = fieldValue.length(); } else { this.fieldValues = new String[fieldValues.size()]; this.fieldValuesOffsets = new int[fieldValues.size()]; int contentLength = 0; int offset = 0; int previousLength = -1; for (int i = 0; i < fieldValues.size(); i++) { String rawValue = fieldValues.get(i).toString(); String fieldValue = rawValue.substring(0, Math.min(rawValue.length(), maxLength)); this.fieldValues[i] = fieldValue; contentLength += fieldValue.length(); offset += previousLength + 1; this.fieldValuesOffsets[i] = offset; previousLength = fieldValue.length(); } this.totalContentLength = contentLength; } } /* Our own api to highlight a single document field, passing in the query terms, and get back our own Snippet object */ public Snippet[] highlightDoc(String field, BytesRef[] terms, IndexSearcher searcher, int docId, int maxPassages) throws IOException { IndexReader reader = searcher.getIndexReader(); IndexReaderContext readerContext = reader.getContext(); List<AtomicReaderContext> leaves = readerContext.leaves(); String[] contents = new String[]{loadCurrentFieldValue()}; Map<Integer, Object> snippetsMap = highlightField(field, contents, getBreakIterator(field), terms, new int[]{docId}, leaves, maxPassages); //increment the current value index so that next time we'll highlight the next value if available currentValueIndex++; Object snippetObject = snippetsMap.get(docId); if (snippetObject != null && snippetObject instanceof Snippet[]) { return (Snippet[]) snippetObject; } return EMPTY_SNIPPET; } /* Method provided through our own fork: allows to do proper scoring when doing per value discrete highlighting. Used to provide the total length of the field (all values) for proper scoring. */ @Override protected int getContentLength(String field, int docId) { return totalContentLength; } /* Method provided through our own fork: allows to perform proper per value discrete highlighting. Used to provide the offset for the current value. */ @Override protected int getOffsetForCurrentValue(String field, int docId) { if (currentValueIndex < fieldValuesOffsets.length) { return fieldValuesOffsets[currentValueIndex]; } throw new IllegalArgumentException("No more values offsets to return"); } public void setBreakIterator(BreakIterator breakIterator) { this.breakIterator = breakIterator; } @Override protected PassageFormatter getFormatter(String field) { return passageFormatter; } @Override protected BreakIterator getBreakIterator(String field) { if (breakIterator == null) { return super.getBreakIterator(field); } return breakIterator; } @Override protected char getMultiValuedSeparator(String field) { //U+2029 PARAGRAPH SEPARATOR (PS): each value holds a discrete passage for highlighting return HighlightUtils.PARAGRAPH_SEPARATOR; } /* By default the postings highlighter returns non highlighted snippet when there are no matches. We want to return no snippets by default, unless no_match_size is greater than 0 */ @Override protected Passage[] getEmptyHighlight(String fieldName, BreakIterator bi, int maxPassages) { if (noMatchSize > 0) { //we want to return the first sentence of the first snippet only return super.getEmptyHighlight(fieldName, bi, 1); } return EMPTY_PASSAGE; } /* Not needed since we call our own loadCurrentFieldValue explicitly, but we override it anyway for consistency. */ @Override protected String[][] loadFieldValues(IndexSearcher searcher, String[] fields, int[] docids, int maxLength) throws IOException { return new String[][]{new String[]{loadCurrentFieldValue()}}; } /* Our own method that returns the field values, which relies on the content that was provided when creating the highlighter. Supports per value discrete highlighting calling the highlightDoc method multiple times, one per value. */ protected String loadCurrentFieldValue() { if (currentValueIndex < fieldValues.length) { return fieldValues[currentValueIndex]; } throw new IllegalArgumentException("No more values to return"); } }
0true
src_main_java_org_apache_lucene_search_postingshighlight_CustomPostingsHighlighter.java
369
public class GetRepositoriesRequest extends MasterNodeReadOperationRequest<GetRepositoriesRequest> { private String[] repositories = Strings.EMPTY_ARRAY; GetRepositoriesRequest() { } /** * Constructs a new get repositories request with a list of repositories. * <p/> * If the list of repositories is empty or it contains a single element "_all", all registered repositories * are returned. * * @param repositories list of repositories */ public GetRepositoriesRequest(String[] repositories) { this.repositories = repositories; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (repositories == null) { validationException = addValidationError("repositories is null", validationException); } return validationException; } /** * The names of the repositories. * * @return list of repositories */ public String[] repositories() { return this.repositories; } /** * Sets the list or repositories. * <p/> * If the list of repositories is empty or it contains a single element "_all", all registered repositories * are returned. * * @param repositories list of repositories * @return this request */ public GetRepositoriesRequest repositories(String[] repositories) { this.repositories = repositories; return this; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); repositories = in.readStringArray(); readLocal(in, Version.V_1_0_0_RC2); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArray(repositories); writeLocal(out, Version.V_1_0_0_RC2); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_repositories_get_GetRepositoriesRequest.java
89
public interface ObjectToDouble<A> { double apply(A a); }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
5,222
public class InternalDateHistogram extends InternalHistogram<InternalDateHistogram.Bucket> implements DateHistogram { final static Type TYPE = new Type("date_histogram", "dhisto"); final static Factory FACTORY = new Factory(); private final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() { @Override public InternalDateHistogram readResult(StreamInput in) throws IOException { InternalDateHistogram histogram = new InternalDateHistogram(); histogram.readFrom(in); return histogram; } }; public static void registerStream() { AggregationStreams.registerStream(STREAM, TYPE.stream()); } static class Bucket extends InternalHistogram.Bucket implements DateHistogram.Bucket { private final ValueFormatter formatter; Bucket(long key, long docCount, InternalAggregations aggregations, ValueFormatter formatter) { super(key, docCount, aggregations); this.formatter = formatter; } @Override public String getKey() { return formatter != null ? formatter.format(key) : DateFieldMapper.Defaults.DATE_TIME_FORMATTER.printer().print(key); } @Override public DateTime getKeyAsDate() { return new DateTime(key); } } static class Factory extends InternalHistogram.Factory<InternalDateHistogram.Bucket> { private Factory() { } @Override public String type() { return TYPE.name(); } @Override public InternalDateHistogram create(String name, List<InternalDateHistogram.Bucket> buckets, InternalOrder order, long minDocCount, EmptyBucketInfo emptyBucketInfo, ValueFormatter formatter, boolean keyed) { return new InternalDateHistogram(name, buckets, order, minDocCount, emptyBucketInfo, formatter, keyed); } @Override public InternalDateHistogram.Bucket createBucket(long key, long docCount, InternalAggregations aggregations, ValueFormatter formatter) { return new Bucket(key, docCount, aggregations, formatter); } } InternalDateHistogram() {} // for serialization InternalDateHistogram(String name, List<InternalDateHistogram.Bucket> buckets, InternalOrder order, long minDocCount, EmptyBucketInfo emptyBucketInfo, ValueFormatter formatter, boolean keyed) { super(name, buckets, order, minDocCount, emptyBucketInfo, formatter, keyed); } @Override public Type type() { return TYPE; } @Override public DateHistogram.Bucket getBucketByKey(DateTime key) { return getBucketByKey(key.getMillis()); } @Override protected InternalDateHistogram.Bucket createBucket(long key, long docCount, InternalAggregations aggregations, ValueFormatter formatter) { return new Bucket(key, docCount, aggregations, formatter); } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_histogram_InternalDateHistogram.java
34
static final class ThenPropagate extends Completion { final CompletableFuture<?> src; final CompletableFuture<Void> dst; ThenPropagate(CompletableFuture<?> src, CompletableFuture<Void> dst) { this.src = src; this.dst = dst; } public final void run() { final CompletableFuture<?> a; final CompletableFuture<Void> dst; Object r; Throwable ex; if ((dst = this.dst) != null && (a = this.src) != null && (r = a.result) != null && compareAndSet(0, 1)) { if (r instanceof AltResult) ex = ((AltResult)r).ex; else ex = null; dst.internalComplete(null, ex); } } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
399
public class CreateSnapshotRequest extends MasterNodeOperationRequest<CreateSnapshotRequest> { private String snapshot; private String repository; private String[] indices = EMPTY_ARRAY; private IndicesOptions indicesOptions = IndicesOptions.strict(); private boolean partial = false; private Settings settings = EMPTY_SETTINGS; private boolean includeGlobalState = true; private boolean waitForCompletion; CreateSnapshotRequest() { } /** * Constructs a new put repository request with the provided snapshot and repository names * * @param repository repository name * @param snapshot snapshot name */ public CreateSnapshotRequest(String repository, String snapshot) { this.snapshot = snapshot; this.repository = repository; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (snapshot == null) { validationException = addValidationError("snapshot is missing", validationException); } if (repository == null) { validationException = addValidationError("repository is missing", validationException); } if (indices == null) { validationException = addValidationError("indices is null", validationException); } for (String index : indices) { if (index == null) { validationException = addValidationError("index is null", validationException); break; } } if (indicesOptions == null) { validationException = addValidationError("indicesOptions is null", validationException); } if (settings == null) { validationException = addValidationError("settings is null", validationException); } return validationException; } /** * Sets the snapshot name * * @param snapshot snapshot name */ public CreateSnapshotRequest snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * The snapshot name * * @return snapshot name */ public String snapshot() { return this.snapshot; } /** * Sets repository name * * @param repository name * @return this request */ public CreateSnapshotRequest repository(String repository) { this.repository = repository; return this; } /** * Returns repository name * * @return repository name */ public String repository() { return this.repository; } /** * Sets a list of indices that should be included into the snapshot * <p/> * The list of indices supports multi-index syntax. For example: "+test*" ,"-test42" will index all indices with * prefix "test" except index "test42". Aliases are supported. An empty list or {"_all"} will snapshot all open * indices in the cluster. * * @param indices * @return this request */ public CreateSnapshotRequest indices(String... indices) { this.indices = indices; return this; } /** * Sets a list of indices that should be included into the snapshot * <p/> * The list of indices supports multi-index syntax. For example: "+test*" ,"-test42" will index all indices with * prefix "test" except index "test42". Aliases are supported. An empty list or {"_all"} will snapshot all open * indices in the cluster. * * @param indices * @return this request */ public CreateSnapshotRequest indices(List<String> indices) { this.indices = indices.toArray(new String[indices.size()]); return this; } /** * Returns a list of indices that should be included into the snapshot * * @return list of indices */ public String[] indices() { return indices; } /** * Specifies the indices options. Like what type of requested indices to ignore. For example indices that don't exist. * * @return the desired behaviour regarding indices options */ public IndicesOptions indicesOptions() { return indicesOptions; } /** * Specifies the indices options. Like what type of requested indices to ignore. For example indices that don't exist. * * @param indicesOptions the desired behaviour regarding indices options * @return this request */ public CreateSnapshotRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } /** * Returns true if indices with unavailable shards should be be partially snapshotted. * * @return the desired behaviour regarding indices options */ public boolean partial() { return partial; } /** * Set to true to allow indices with unavailable shards to be partially snapshotted. * * @param partial true if indices with unavailable shards should be be partially snapshotted. * @return this request */ public CreateSnapshotRequest partial(boolean partial) { this.partial = partial; return this; } /** * If set to true the request should wait for the snapshot completion before returning. * * @param waitForCompletion true if * @return this request */ public CreateSnapshotRequest waitForCompletion(boolean waitForCompletion) { this.waitForCompletion = waitForCompletion; return this; } /** * Returns true if the request should wait for the snapshot completion before returning * * @return true if the request should wait for completion */ public boolean waitForCompletion() { return waitForCompletion; } /** * Sets repository-specific snapshot settings. * <p/> * See repository documentation for more information. * * @param settings repository-specific snapshot settings * @return this request */ public CreateSnapshotRequest settings(Settings settings) { this.settings = settings; return this; } /** * Sets repository-specific snapshot settings. * <p/> * See repository documentation for more information. * * @param settings repository-specific snapshot settings * @return this request */ public CreateSnapshotRequest settings(Settings.Builder settings) { this.settings = settings.build(); return this; } /** * Sets repository-specific snapshot settings in JSON, YAML or properties format * <p/> * See repository documentation for more information. * * @param source repository-specific snapshot settings * @return this request */ public CreateSnapshotRequest settings(String source) { this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build(); return this; } /** * Sets repository-specific snapshot settings. * <p/> * See repository documentation for more information. * * @param source repository-specific snapshot settings * @return this request */ public CreateSnapshotRequest settings(Map<String, Object> source) { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(source); settings(builder.string()); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } return this; } /** * Returns repository-specific snapshot settings * * @return repository-specific snapshot settings */ public Settings settings() { return this.settings; } /** * Set to true if global state should be stored as part of the snapshot * * @param includeGlobalState true if global state should be stored * @return this request */ public CreateSnapshotRequest includeGlobalState(boolean includeGlobalState) { this.includeGlobalState = includeGlobalState; return this; } /** * Returns true if global state should be stored as part of the snapshot * * @return true if global state should be stored as part of the snapshot */ public boolean includeGlobalState() { return includeGlobalState; } /** * Parses snapshot definition. * * @param source snapshot definition * @return this request */ public CreateSnapshotRequest source(XContentBuilder source) { return source(source.bytes()); } /** * Parses snapshot definition. * * @param source snapshot definition * @return this request */ public CreateSnapshotRequest source(Map source) { boolean ignoreUnavailable = IndicesOptions.lenient().ignoreUnavailable(); boolean allowNoIndices = IndicesOptions.lenient().allowNoIndices(); boolean expandWildcardsOpen = IndicesOptions.lenient().expandWildcardsOpen(); boolean expandWildcardsClosed = IndicesOptions.lenient().expandWildcardsClosed(); for (Map.Entry<String, Object> entry : ((Map<String, Object>) source).entrySet()) { String name = entry.getKey(); if (name.equals("indices")) { if (entry.getValue() instanceof String) { indices(Strings.splitStringByCommaToArray((String) entry.getValue())); } else if (entry.getValue() instanceof ArrayList) { indices((ArrayList<String>) entry.getValue()); } else { throw new ElasticsearchIllegalArgumentException("malformed indices section, should be an array of strings"); } } else if (name.equals("ignore_unavailable") || name.equals("ignoreUnavailable")) { ignoreUnavailable = nodeBooleanValue(entry.getValue()); } else if (name.equals("allow_no_indices") || name.equals("allowNoIndices")) { allowNoIndices = nodeBooleanValue(entry.getValue()); } else if (name.equals("expand_wildcards_open") || name.equals("expandWildcardsOpen")) { expandWildcardsOpen = nodeBooleanValue(entry.getValue()); } else if (name.equals("expand_wildcards_closed") || name.equals("expandWildcardsClosed")) { expandWildcardsClosed = nodeBooleanValue(entry.getValue()); } else if (name.equals("partial")) { partial(nodeBooleanValue(entry.getValue())); } else if (name.equals("settings")) { if (!(entry.getValue() instanceof Map)) { throw new ElasticsearchIllegalArgumentException("malformed settings section, should indices an inner object"); } settings((Map<String, Object>) entry.getValue()); } else if (name.equals("include_global_state")) { includeGlobalState = nodeBooleanValue(entry.getValue()); } } indicesOptions(IndicesOptions.fromOptions(ignoreUnavailable, allowNoIndices, expandWildcardsOpen, expandWildcardsClosed)); return this; } /** * Parses snapshot definition. JSON, YAML and properties formats are supported * * @param source snapshot definition * @return this request */ public CreateSnapshotRequest source(String source) { if (hasLength(source)) { try { return source(XContentFactory.xContent(source).createParser(source).mapOrderedAndClose()); } catch (Exception e) { throw new ElasticsearchIllegalArgumentException("failed to parse repository source [" + source + "]", e); } } return this; } /** * Parses snapshot definition. JSON, YAML and properties formats are supported * * @param source snapshot definition * @return this request */ public CreateSnapshotRequest source(byte[] source) { return source(source, 0, source.length); } /** * Parses snapshot definition. JSON, YAML and properties formats are supported * * @param source snapshot definition * @param offset offset * @param length length * @return this request */ public CreateSnapshotRequest source(byte[] source, int offset, int length) { if (length > 0) { try { return source(XContentFactory.xContent(source, offset, length).createParser(source, offset, length).mapOrderedAndClose()); } catch (IOException e) { throw new ElasticsearchIllegalArgumentException("failed to parse repository source", e); } } return this; } /** * Parses snapshot definition. JSON, YAML and properties formats are supported * * @param source snapshot definition * @return this request */ public CreateSnapshotRequest source(BytesReference source) { try { return source(XContentFactory.xContent(source).createParser(source).mapOrderedAndClose()); } catch (IOException e) { throw new ElasticsearchIllegalArgumentException("failed to parse snapshot source", e); } } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); snapshot = in.readString(); repository = in.readString(); indices = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); settings = readSettingsFromStream(in); includeGlobalState = in.readBoolean(); waitForCompletion = in.readBoolean(); partial = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(snapshot); out.writeString(repository); out.writeStringArray(indices); indicesOptions.writeIndicesOptions(out); writeSettingsToStream(settings, out); out.writeBoolean(includeGlobalState); out.writeBoolean(waitForCompletion); out.writeBoolean(partial); } }
1no label
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_create_CreateSnapshotRequest.java
308
public class ClusterHealthResponse extends ActionResponse implements Iterable<ClusterIndexHealth>, ToXContent { private String clusterName; int numberOfNodes = 0; int numberOfDataNodes = 0; int activeShards = 0; int relocatingShards = 0; int activePrimaryShards = 0; int initializingShards = 0; int unassignedShards = 0; boolean timedOut = false; ClusterHealthStatus status = ClusterHealthStatus.RED; private List<String> validationFailures; Map<String, ClusterIndexHealth> indices = Maps.newHashMap(); ClusterHealthResponse() { } public ClusterHealthResponse(String clusterName, List<String> validationFailures) { this.clusterName = clusterName; this.validationFailures = validationFailures; } public ClusterHealthResponse(String clusterName, String[] concreteIndices, ClusterState clusterState) { this.clusterName = clusterName; RoutingTableValidation validation = clusterState.routingTable().validate(clusterState.metaData()); validationFailures = validation.failures(); numberOfNodes = clusterState.nodes().size(); numberOfDataNodes = clusterState.nodes().dataNodes().size(); for (String index : concreteIndices) { IndexRoutingTable indexRoutingTable = clusterState.routingTable().index(index); IndexMetaData indexMetaData = clusterState.metaData().index(index); if (indexRoutingTable == null) { continue; } ClusterIndexHealth indexHealth = new ClusterIndexHealth(indexMetaData, indexRoutingTable); indices.put(indexHealth.getIndex(), indexHealth); } status = ClusterHealthStatus.GREEN; for (ClusterIndexHealth indexHealth : indices.values()) { activePrimaryShards += indexHealth.activePrimaryShards; activeShards += indexHealth.activeShards; relocatingShards += indexHealth.relocatingShards; initializingShards += indexHealth.initializingShards; unassignedShards += indexHealth.unassignedShards; if (indexHealth.getStatus() == ClusterHealthStatus.RED) { status = ClusterHealthStatus.RED; } else if (indexHealth.getStatus() == ClusterHealthStatus.YELLOW && status != ClusterHealthStatus.RED) { status = ClusterHealthStatus.YELLOW; } } if (!validationFailures.isEmpty()) { status = ClusterHealthStatus.RED; } else if (clusterState.blocks().hasGlobalBlock(RestStatus.SERVICE_UNAVAILABLE)) { status = ClusterHealthStatus.RED; } } public String getClusterName() { return clusterName; } /** * The validation failures on the cluster level (without index validation failures). */ public List<String> getValidationFailures() { return this.validationFailures; } /** * All the validation failures, including index level validation failures. */ public List<String> getAllValidationFailures() { List<String> allFailures = newArrayList(getValidationFailures()); for (ClusterIndexHealth indexHealth : indices.values()) { allFailures.addAll(indexHealth.getValidationFailures()); } return allFailures; } public int getActiveShards() { return activeShards; } public int getRelocatingShards() { return relocatingShards; } public int getActivePrimaryShards() { return activePrimaryShards; } public int getInitializingShards() { return initializingShards; } public int getUnassignedShards() { return unassignedShards; } public int getNumberOfNodes() { return this.numberOfNodes; } public int getNumberOfDataNodes() { return this.numberOfDataNodes; } /** * <tt>true</tt> if the waitForXXX has timeout out and did not match. */ public boolean isTimedOut() { return this.timedOut; } public ClusterHealthStatus getStatus() { return status; } public Map<String, ClusterIndexHealth> getIndices() { return indices; } @Override public Iterator<ClusterIndexHealth> iterator() { return indices.values().iterator(); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); clusterName = in.readString(); activePrimaryShards = in.readVInt(); activeShards = in.readVInt(); relocatingShards = in.readVInt(); initializingShards = in.readVInt(); unassignedShards = in.readVInt(); numberOfNodes = in.readVInt(); numberOfDataNodes = in.readVInt(); status = ClusterHealthStatus.fromValue(in.readByte()); int size = in.readVInt(); for (int i = 0; i < size; i++) { ClusterIndexHealth indexHealth = readClusterIndexHealth(in); indices.put(indexHealth.getIndex(), indexHealth); } timedOut = in.readBoolean(); size = in.readVInt(); if (size == 0) { validationFailures = ImmutableList.of(); } else { for (int i = 0; i < size; i++) { validationFailures.add(in.readString()); } } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(clusterName); out.writeVInt(activePrimaryShards); out.writeVInt(activeShards); out.writeVInt(relocatingShards); out.writeVInt(initializingShards); out.writeVInt(unassignedShards); out.writeVInt(numberOfNodes); out.writeVInt(numberOfDataNodes); out.writeByte(status.value()); out.writeVInt(indices.size()); for (ClusterIndexHealth indexHealth : this) { indexHealth.writeTo(out); } out.writeBoolean(timedOut); out.writeVInt(validationFailures.size()); for (String failure : validationFailures) { out.writeString(failure); } } @Override public String toString() { StringBuilder builder = new StringBuilder("ClusterHealthResponse - status [").append(status).append("]") .append("\ntimedOut [").append(timedOut).append("]") .append("\nclustername [").append(clusterName).append("]") .append("\nnumberOfNodes [").append(numberOfNodes).append("]") .append("\nnumberOfDataNodes [").append(numberOfDataNodes).append("]") .append("\nactiveShards [").append(activeShards).append("]") .append("\nrelocatingShards [").append(relocatingShards).append("]") .append("\nactivePrimaryShards [").append(activePrimaryShards).append("]") .append("\ninitializingShards [").append(initializingShards).append("]") .append("\nvalidationFailures ").append(validationFailures) .append("\nindices:"); for (Map.Entry<String, ClusterIndexHealth> indexEntry : indices.entrySet()) { builder.append(" [").append(indexEntry.getKey()).append("][").append(indexEntry.getValue().status).append("]"); } return builder.toString(); } static final class Fields { static final XContentBuilderString CLUSTER_NAME = new XContentBuilderString("cluster_name"); static final XContentBuilderString STATUS = new XContentBuilderString("status"); static final XContentBuilderString TIMED_OUT = new XContentBuilderString("timed_out"); static final XContentBuilderString NUMBER_OF_NODES = new XContentBuilderString("number_of_nodes"); static final XContentBuilderString NUMBER_OF_DATA_NODES = new XContentBuilderString("number_of_data_nodes"); static final XContentBuilderString ACTIVE_PRIMARY_SHARDS = new XContentBuilderString("active_primary_shards"); static final XContentBuilderString ACTIVE_SHARDS = new XContentBuilderString("active_shards"); static final XContentBuilderString RELOCATING_SHARDS = new XContentBuilderString("relocating_shards"); static final XContentBuilderString INITIALIZING_SHARDS = new XContentBuilderString("initializing_shards"); static final XContentBuilderString UNASSIGNED_SHARDS = new XContentBuilderString("unassigned_shards"); static final XContentBuilderString VALIDATION_FAILURES = new XContentBuilderString("validation_failures"); static final XContentBuilderString INDICES = new XContentBuilderString("indices"); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field(Fields.CLUSTER_NAME, getClusterName()); builder.field(Fields.STATUS, getStatus().name().toLowerCase(Locale.ROOT)); builder.field(Fields.TIMED_OUT, isTimedOut()); builder.field(Fields.NUMBER_OF_NODES, getNumberOfNodes()); builder.field(Fields.NUMBER_OF_DATA_NODES, getNumberOfDataNodes()); builder.field(Fields.ACTIVE_PRIMARY_SHARDS, getActivePrimaryShards()); builder.field(Fields.ACTIVE_SHARDS, getActiveShards()); builder.field(Fields.RELOCATING_SHARDS, getRelocatingShards()); builder.field(Fields.INITIALIZING_SHARDS, getInitializingShards()); builder.field(Fields.UNASSIGNED_SHARDS, getUnassignedShards()); String level = params.param("level", "cluster"); boolean outputIndices = "indices".equals(level) || "shards".equals(level); if (!getValidationFailures().isEmpty()) { builder.startArray(Fields.VALIDATION_FAILURES); for (String validationFailure : getValidationFailures()) { builder.value(validationFailure); } // if we don't print index level information, still print the index validation failures // so we know why the status is red if (!outputIndices) { for (ClusterIndexHealth indexHealth : indices.values()) { builder.startObject(indexHealth.getIndex()); if (!indexHealth.getValidationFailures().isEmpty()) { builder.startArray(Fields.VALIDATION_FAILURES); for (String validationFailure : indexHealth.getValidationFailures()) { builder.value(validationFailure); } builder.endArray(); } builder.endObject(); } } builder.endArray(); } if (outputIndices) { builder.startObject(Fields.INDICES); for (ClusterIndexHealth indexHealth : indices.values()) { builder.startObject(indexHealth.getIndex(), XContentBuilder.FieldCaseConversion.NONE); indexHealth.toXContent(builder, params); builder.endObject(); } builder.endObject(); } return builder; } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_health_ClusterHealthResponse.java
1,162
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_CREDIT_CARD_PAYMENT") public class CreditCardPaymentInfoImpl implements CreditCardPaymentInfo { private static final long serialVersionUID = 1L; protected CreditCardPaymentInfoImpl() { //do not allow direct instantiation -- must at least be package private for bytecode instrumentation //this complies with JPA specification requirements for entity construction } @Transient protected EncryptionModule encryptionModule; @Id @GeneratedValue(generator = "CreditCardPaymentId") @GenericGenerator( name="CreditCardPaymentId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="CreditCardPaymentInfoImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.CreditCardPaymentInfoImpl") } ) @Column(name = "PAYMENT_ID") protected Long id; @Column(name = "REFERENCE_NUMBER", nullable=false) @Index(name="CREDITCARD_INDEX", columnNames={"REFERENCE_NUMBER"}) protected String referenceNumber; @Column(name = "PAN", nullable=false) protected String pan; @Column(name = "EXPIRATION_MONTH", nullable=false) protected Integer expirationMonth; @Column(name = "EXPIRATION_YEAR", nullable=false) protected Integer expirationYear; @Column(name = "NAME_ON_CARD", nullable=false) protected String nameOnCard; @Transient protected String cvvCode; /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getId() */ @Override public Long getId() { return id; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setId(long) */ @Override public void setId(Long id) { this.id = id; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getReferenceNumber() */ @Override public String getReferenceNumber() { return referenceNumber; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setReferenceNumber(java.lang.String) */ @Override public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getPan() */ @Override public String getPan() { return encryptionModule.decrypt(pan); } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setPan(java.lang.Long) */ @Override public void setPan(String pan) { this.pan = encryptionModule.encrypt(pan); } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getExpirationMonth() */ @Override public Integer getExpirationMonth() { return expirationMonth; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setExpirationMonth(java.lang.Integer) */ @Override public void setExpirationMonth(Integer expirationMonth) { this.expirationMonth = expirationMonth; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getExpirationYear() */ @Override public Integer getExpirationYear() { return expirationYear; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setExpirationYear(java.lang.Integer) */ @Override public void setExpirationYear(Integer expirationYear) { this.expirationYear = expirationYear; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getNameOnCard() */ @Override public String getNameOnCard() { return nameOnCard; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setNameOnCard(java.lang.String) */ @Override public void setNameOnCard(String nameOnCard) { this.nameOnCard = nameOnCard; } @Override public String getCvvCode() { return cvvCode; } @Override public void setCvvCode(String cvvCode) { this.cvvCode = cvvCode; } @Override public EncryptionModule getEncryptionModule() { return encryptionModule; } @Override public void setEncryptionModule(EncryptionModule encryptionModule) { this.encryptionModule = encryptionModule; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expirationMonth == null) ? 0 : expirationMonth.hashCode()); result = prime * result + ((expirationYear == null) ? 0 : expirationYear.hashCode()); result = prime * result + ((pan == null) ? 0 : pan.hashCode()); result = prime * result + ((referenceNumber == null) ? 0 : referenceNumber.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; CreditCardPaymentInfoImpl other = (CreditCardPaymentInfoImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (expirationMonth == null) { if (other.expirationMonth != null) return false; } else if (!expirationMonth.equals(other.expirationMonth)) return false; if (expirationYear == null) { if (other.expirationYear != null) return false; } else if (!expirationYear.equals(other.expirationYear)) return false; if (pan == null) { if (other.pan != null) return false; } else if (!pan.equals(other.pan)) return false; if (referenceNumber == null) { if (other.referenceNumber != null) return false; } else if (!referenceNumber.equals(other.referenceNumber)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_CreditCardPaymentInfoImpl.java
4,486
threadPool.generic().execute(new Runnable() { @Override public void run() { doRecovery(request, status, listener); } });
1no label
src_main_java_org_elasticsearch_indices_recovery_RecoveryTarget.java
0
public abstract class AbstractEntryIterator<K, V, T> implements OLazyIterator<T>, OResettable { OMVRBTree<K, V> tree; OMVRBTreeEntry<K, V> begin; OMVRBTreeEntry<K, V> next; OMVRBTreeEntry<K, V> lastReturned; int expectedModCount; int pageIndex; AbstractEntryIterator(final OMVRBTreeEntry<K, V> start) { begin = start; init(); } private void init() { if (begin == null) // IN CASE OF ABSTRACTMAP.HASHCODE() return; tree = begin.getTree(); next = begin; expectedModCount = tree.modCount; lastReturned = null; pageIndex = begin.getTree().getPageIndex() > -1 ? begin.getTree().getPageIndex() - 1 : -1; } @Override public void reset() { init(); } public boolean hasNext() { if (tree != null && expectedModCount != tree.modCount) { // CONCURRENT CHANGE: TRY TO REUSE LAST POSITION pageIndex--; expectedModCount = tree.modCount; } return next != null && (pageIndex < next.getSize() - 1 || OMVRBTree.successor(next) != null); } public final boolean hasPrevious() { if (tree != null && expectedModCount != tree.modCount) { // CONCURRENT CHANGE: TRY TO REUSE LAST POSITION pageIndex = -1; expectedModCount = tree.modCount; } return next != null && (pageIndex > 0 || OMVRBTree.predecessor(next) != null); } final K nextKey() { return nextEntry().getKey(pageIndex); } final V nextValue() { return nextEntry().getValue(pageIndex); } final V prevValue() { return prevEntry().getValue(pageIndex); } final OMVRBTreeEntry<K, V> nextEntry() { if (next == null) throw new NoSuchElementException(); if (pageIndex < next.getSize() - 1) { // ITERATE INSIDE THE NODE pageIndex++; } else { // GET THE NEXT NODE if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); next = OMVRBTree.successor(next); pageIndex = 0; } lastReturned = next; tree.pageIndex = pageIndex; return next; } final OMVRBTreeEntry<K, V> prevEntry() { if (next == null) throw new NoSuchElementException(); if (pageIndex > 0) { // ITERATE INSIDE THE NODE pageIndex--; } else { if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); next = OMVRBTree.predecessor(next); pageIndex = next != null ? next.getSize() - 1 : -1; } lastReturned = next; return next; } @SuppressWarnings("unchecked") public T update(final T iValue) { if (lastReturned == null) throw new IllegalStateException(); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); tree.pageIndex = pageIndex; return (T) next.setValue((V) iValue); } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.getLeft() != null && lastReturned.getRight() != null) next = lastReturned; tree.pageIndex = pageIndex; next = tree.deleteEntry(lastReturned); pageIndex--; expectedModCount = tree.modCount; lastReturned = null; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_AbstractEntryIterator.java
106
{ @Override public Void doWork( State state ) { state.tx.success(); state.tx.finish(); return null; } } );
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.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
75
public interface VertexList extends Iterable<TitanVertex> { /** * Returns the number of vertices in this list. * * @return Number of vertices in the list. */ public int size(); /** * Returns the vertex at a given position in the list. * * @param pos Position for which to retrieve the vertex. * @return TitanVertex at the given position */ public TitanVertex get(int pos); /** * Sorts this list according to vertex ids in increasing order. * If the list is already sorted, invoking this method incurs no cost. * * @throws UnsupportedOperationException If not all vertices in this list have an id */ public void sort(); /** * Whether this list of vertices is sorted by id in increasing order. * * @return */ public boolean isSorted(); /** * Returns a sub list of this list of vertices from the given position with the given number of vertices. * * @param fromPosition * @param length * @return */ public VertexList subList(int fromPosition, int length); /** * Returns a list of ids of all vertices in this list of vertices in the same order of the original vertex list. * <p/> * Uses an efficient primitive variable-sized array. * * @return A list of idAuthorities of all vertices in this list of vertices in the same order of the original vertex list. * @see AbstractLongList */ public LongArrayList getIDs(); /** * Returns the id of the vertex at the specified position * * @param pos The position of the vertex in the list * @return The id of that vertex */ public long getID(int pos); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_VertexList.java
5,312
public static class Bucket extends InternalTerms.Bucket { final BytesRef termBytes; public Bucket(BytesRef term, long docCount, InternalAggregations aggregations) { super(docCount, aggregations); this.termBytes = term; } @Override public String getKey() { return termBytes.utf8ToString(); } @Override public Text getKeyAsText() { return new BytesText(new BytesArray(termBytes)); } @Override public Number getKeyAsNumber() { // this method is needed for scripted numeric faceting return Double.parseDouble(termBytes.utf8ToString()); } @Override int compareTerm(Terms.Bucket other) { return BytesRef.getUTF8SortedAsUnicodeComparator().compare(termBytes, ((Bucket) other).termBytes); } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_terms_StringTerms.java
17
@Scope("prototype") @Component("blSkuPricingPersistenceProvider") public class SkuPricingPersistenceProvider extends AbstractMoneyFieldPersistenceProvider { public static int ORDER = FieldPersistenceProvider.MONEY - 1000; @Override public int getOrder() { return ORDER; } @Override public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException { if (!canHandleExtraction(extractValueRequest, property)) { return FieldProviderResponse.NOT_HANDLED; } Object displayValue = extractValueRequest.getRequestedValue(); if (displayValue == null) { try { displayValue = PropertyUtils.getProperty(extractValueRequest.getEntity(), property.getName()); ((BasicFieldMetadata)property.getMetadata()).setDerived(true); } catch (Exception e) { //swallow all exceptions because null is fine for the display value } } Object actualValue = extractValueRequest.getRequestedValue(); property.setValue(formatValue(actualValue, extractValueRequest, property)); property.setDisplayValue(formatDisplayValue(displayValue, extractValueRequest, property)); return FieldProviderResponse.HANDLED_BREAK; } protected String formatValue(Object value, ExtractValueRequest extractValueRequest, Property property) { if (value == null) { return null; } BigDecimal decimalValue = (value instanceof Money) ? ((Money)value).getAmount() : (BigDecimal) value; return super.formatValue(decimalValue, extractValueRequest, property); } protected String formatDisplayValue(Object value, ExtractValueRequest extractValueRequest, Property property) { if (value == null) { return null; } BigDecimal decimalValue = (value instanceof Money) ? ((Money)value).getAmount() : (BigDecimal) value; return super.formatDisplayValue(decimalValue, extractValueRequest, property); } /** * Handle all fields that have declared themselves to be apart of a Sku and have a field type of Money * * @param extractValueRequest * @param property * @return whether or not we can handle extraction */ @Override protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) { return ( extractValueRequest.getMetadata().getTargetClass().equals(SkuImpl.class.getName()) || extractValueRequest.getMetadata().getTargetClass().equals(Sku.class.getName()) ) && !property.getName().contains(FieldManager.MAPFIELDSEPARATOR) && SupportedFieldType.MONEY.equals(extractValueRequest.getMetadata().getFieldType()); } protected boolean isDefaultSkuProperty(ExtractValueRequest extractValueRequest, Property property) { return property.getName().startsWith("defaultSku"); } @Override protected Locale getLocale(ExtractValueRequest extractValueRequest, Property property) { BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext(); return brc.getJavaLocale(); } @Override protected Currency getCurrency(ExtractValueRequest extractValueRequest, Property property) { BroadleafCurrency bc = null; if (extractValueRequest.getEntity() instanceof Product && isDefaultSkuProperty(extractValueRequest, property)) { Product p = (Product) extractValueRequest.getEntity(); bc = p.getDefaultSku().getCurrency(); } else if (extractValueRequest.getEntity() instanceof Sku) { Sku s = (Sku) extractValueRequest.getEntity(); bc = s.getCurrency(); } if (bc == null) { BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext(); return brc.getJavaCurrency(); } else { return Currency.getInstance(bc.getCurrencyCode()); } } }
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_persistence_module_provider_SkuPricingPersistenceProvider.java
285
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientConcurrentLockTest { private static HazelcastInstance server; private static HazelcastInstance client; @BeforeClass public static void init() { server = Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(); } @AfterClass public static void destroy() { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void concurrent_TryLockTest() throws InterruptedException { concurrent_LockTest(false); } @Test public void concurrent_TryLock_WithTimeOutTest() throws InterruptedException { concurrent_LockTest(true); } private void concurrent_LockTest(boolean tryLockWithTimeOut) throws InterruptedException { final ILock lock = client.getLock(randomString()); final AtomicInteger upTotal = new AtomicInteger(0); final AtomicInteger downTotal = new AtomicInteger(0); LockTestThread threads[] = new LockTestThread[8]; for ( int i=0; i<threads.length; i++ ) { LockTestThread t; if (tryLockWithTimeOut){ t = new TryLockWithTimeOutThread(lock, upTotal, downTotal); }else{ t = new TryLockThread(lock, upTotal, downTotal); } t.start(); threads[i] = t; } assertJoinable(threads); assertEquals("concurrent access to locked code caused wrong total", 0, upTotal.get() + downTotal.get()); } static class TryLockThread extends LockTestThread { public TryLockThread(ILock lock, AtomicInteger upTotal, AtomicInteger downTotal){ super(lock, upTotal, downTotal); } public void doRun() throws Exception{ if ( lock.tryLock() ) { work(); lock.unlock(); } } } static class TryLockWithTimeOutThread extends LockTestThread { public TryLockWithTimeOutThread(ILock lock, AtomicInteger upTotal, AtomicInteger downTotal){ super(lock, upTotal, downTotal); } public void doRun() throws Exception{ if ( lock.tryLock(1, TimeUnit.MILLISECONDS) ) { work(); lock.unlock(); } } } static abstract class LockTestThread extends Thread{ private static final int ITERATIONS = 1000*10; private final Random random = new Random(); protected final ILock lock; protected final AtomicInteger upTotal; protected final AtomicInteger downTotal; public LockTestThread(ILock lock, AtomicInteger upTotal, AtomicInteger downTotal){ this.lock = lock; this.upTotal = upTotal; this.downTotal = downTotal; } public void run() { try{ for ( int i=0; i<ITERATIONS; i++ ) { doRun(); } }catch (Exception e){ throw new RuntimeException("LockTestThread throws: ", e); } } abstract void doRun() throws Exception; protected void work(){ int delta = random.nextInt(1000); upTotal.addAndGet(delta); downTotal.addAndGet(-delta); } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientConcurrentLockTest.java
1,609
public class OCopyDatabaseChunkTask extends OAbstractReplicatedTask { private static final long serialVersionUID = 1L; private String databaseName; private boolean lastChunk = false; private byte[] chunkContent; public OCopyDatabaseChunkTask() { } public OCopyDatabaseChunkTask(final byte[] chunk) { chunkContent = chunk; } @Override public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) throws Exception { ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT, "writing database %s in chunk to disk size=%d...", database.getName(), chunkContent.length); final File f = new File("importDatabase/" + database.getName()); final FileOutputStream out = new FileOutputStream(f, true); try { final ByteArrayInputStream in = new ByteArrayInputStream(chunkContent); try { OIOUtils.copyStream(in, out, chunkContent.length); } finally { in.close(); } } finally { out.close(); } if (lastChunk) try { ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT, "importing database %s...", database.getName()); final ODatabaseImport importDb = new ODatabaseImport(database, f.getAbsolutePath(), null); try { importDb.importDatabase(); } finally { ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT, "database %s imported correctly", database.getName()); importDb.close(); } } finally { OFileUtils.deleteRecursively(new File("importDatabase")); } return Boolean.TRUE; } public QUORUM_TYPE getQuorumType() { return QUORUM_TYPE.NONE; } @Override public String getPayload() { return null; } @Override public OFixUpdateRecordTask getFixTask(ODistributedRequest iRequest, ODistributedResponse iBadResponse, ODistributedResponse iGoodResponse) { return null; } @Override public String getName() { return "deploy_db"; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeUTF(databaseName); out.write(chunkContent); out.writeBoolean(lastChunk); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { databaseName = in.readUTF(); in.read(chunkContent); lastChunk = in.readBoolean(); } }
1no label
server_src_main_java_com_orientechnologies_orient_server_distributed_task_OCopyDatabaseChunkTask.java
38
public class TransactionalTitanGraphTestSuite extends TransactionalGraphTestSuite { public TransactionalTitanGraphTestSuite(final GraphTest graphTest) { super(graphTest); } @Override public void testCompetingThreads() { TitanBlueprintsGraph graph = (TitanBlueprintsGraph) graphTest.generateGraph(); //Need to define types before hand to avoid deadlock in transactions TitanManagement mgmt = graph.getManagementSystem(); mgmt.makeEdgeLabel("friend").make(); mgmt.makePropertyKey("test").dataType(Long.class).make(); mgmt.makePropertyKey("blah").dataType(Float.class).make(); mgmt.makePropertyKey("bloop").dataType(Integer.class).make(); mgmt.commit(); graph.shutdown(); super.testCompetingThreads(); } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TransactionalTitanGraphTestSuite.java
3,756
private static class ResponseWrapper extends HttpServletResponseWrapper { public ResponseWrapper(final HttpServletResponse original) { super(original); } }
1no label
hazelcast-wm_src_main_java_com_hazelcast_web_WebFilter.java
1,101
public class OSQLFunctionIntersect extends OSQLFunctionMultiValueAbstract<Set<Object>> { public static final String NAME = "intersect"; public OSQLFunctionIntersect() { super(NAME, 1, -1); } public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters, OCommandContext iContext) { Object value = iParameters[0]; if (value instanceof OSQLFilterItemVariable) value = ((OSQLFilterItemVariable) value).getValue(iCurrentRecord, iContext); if (value == null) return Collections.emptySet(); if (!(value instanceof Collection<?>)) value = Arrays.asList(value); final Collection<?> coll = (Collection<?>) value; if (iParameters.length == 1) { // AGGREGATION MODE (STATEFULL) if (context == null) { // ADD ALL THE ITEMS OF THE FIRST COLLECTION context = new HashSet<Object>(coll); } else { // INTERSECT IT AGAINST THE CURRENT COLLECTION context.retainAll(coll); } return null; } else { // IN-LINE MODE (STATELESS) final HashSet<Object> result = new HashSet<Object>(coll); for (int i = 1; i < iParameters.length; ++i) { value = iParameters[i]; if (value instanceof OSQLFilterItemVariable) value = ((OSQLFilterItemVariable) value).getValue(iCurrentRecord, iContext); if (value != null) { if (!(value instanceof Collection<?>)) // CONVERT IT INTO A COLLECTION value = Arrays.asList(value); result.retainAll((Collection<?>) value); } else result.clear(); } return result; } } public String getSyntax() { return "Syntax error: intersect(<field>*)"; } @SuppressWarnings("unchecked") @Override public Object mergeDistributedResult(List<Object> resultsToMerge) { final Collection<Object> result = new HashSet<Object>(); if (!resultsToMerge.isEmpty()) { final Collection<Object> items = (Collection<Object>) resultsToMerge.get(0); if (items != null) { result.addAll(items); } } for (int i = 1; i < resultsToMerge.size(); i++) { final Collection<Object> items = (Collection<Object>) resultsToMerge.get(i); if (items != null) { result.retainAll(items); } } return result; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_functions_coll_OSQLFunctionIntersect.java
108
public static class Name { public static final String Rules = "PageImpl_Rules_Tab"; }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageImpl.java