Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
7 | class ClusterInstance
{
private final Executor stateMachineExecutor;
private final Logging logging;
private final MultiPaxosServerFactory factory;
private final ProtocolServer server;
private final MultiPaxosContext ctx;
private final InMemoryAcceptorInstanceStore acceptorInstanceStore;
private final ProverTimeouts timeouts;
private final ClusterInstanceInput input;
private final ClusterInstanceOutput output;
private final URI uri;
public static final Executor DIRECT_EXECUTOR = new Executor()
{
@Override
public void execute( Runnable command )
{
command.run();
}
};
private boolean online = true;
public static ClusterInstance newClusterInstance( InstanceId id, URI uri, ClusterConfiguration configuration, Logging logging )
{
MultiPaxosServerFactory factory = new MultiPaxosServerFactory( configuration, logging);
ClusterInstanceInput input = new ClusterInstanceInput();
ClusterInstanceOutput output = new ClusterInstanceOutput(uri);
ObjectStreamFactory objStreamFactory = new ObjectStreamFactory();
ProverTimeouts timeouts = new ProverTimeouts(uri);
InMemoryAcceptorInstanceStore acceptorInstances = new InMemoryAcceptorInstanceStore();
DelayedDirectExecutor executor = new DelayedDirectExecutor();
final MultiPaxosContext context = new MultiPaxosContext( id,
Iterables.<ElectionRole,ElectionRole>iterable( new ElectionRole( ClusterConfiguration.COORDINATOR ) ),
new ClusterConfiguration( configuration.getName(), logging.getMessagesLog( ClusterConfiguration.class ),
configuration.getMemberURIs() ),
executor, logging, objStreamFactory, objStreamFactory, acceptorInstances, timeouts,
new DefaultElectionCredentialsProvider( id.toIntegerIndex(), new StateVerifierLastTxIdGetter(),
new MemberInfoProvider() ));
context.getClusterContext().setBoundAt( uri );
SnapshotContext snapshotContext = new SnapshotContext( context.getClusterContext(),context.getLearnerContext());
ProtocolServer ps = factory.newProtocolServer( id,
input, output, DIRECT_EXECUTOR, new DelayedDirectExecutor(), timeouts, context, snapshotContext);
return new ClusterInstance( DIRECT_EXECUTOR, logging, factory, ps, context, acceptorInstances, timeouts, input, output, uri );
}
public ClusterInstance( Executor stateMachineExecutor, Logging logging, MultiPaxosServerFactory factory,
ProtocolServer server,
MultiPaxosContext ctx, InMemoryAcceptorInstanceStore acceptorInstanceStore,
ProverTimeouts timeouts, ClusterInstanceInput input, ClusterInstanceOutput output,
URI uri )
{
this.stateMachineExecutor = stateMachineExecutor;
this.logging = logging;
this.factory = factory;
this.server = server;
this.ctx = ctx;
this.acceptorInstanceStore = acceptorInstanceStore;
this.timeouts = timeouts;
this.input = input;
this.output = output;
this.uri = uri;
}
public InstanceId id()
{
return server.getServerId();
}
/** Process a message, returns all messages generated as output. */
public Iterable<Message<? extends MessageType>> process( Message<? extends MessageType> message )
{
if(online)
{
input.process( message );
return output.messages();
}
else
{
return Iterables.empty();
}
}
@Override
public String toString()
{
return "[" + id() + ":" + Iterables.toString( stateMachineStates(), "," ) + "]";
}
private Iterable<String> stateMachineStates()
{
return Iterables.map( new Function<StateMachine, String>()
{
@Override
public String apply( StateMachine stateMachine )
{
return stateMachine.getState().toString();
}
}, server.getStateMachines().getStateMachines() );
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
ClusterInstance that = (ClusterInstance) o;
if ( !toString().equals( that.toString() ) )
{
return false;
}
if ( !uri.equals( that.uri ) )
{
return false;
}
// TODO: For now, we only look at the states of the underlying state machines,
// and ignore, at our peril, the MultiPaxosContext as part of this equality checks.
// This means the prover ignores lots of possible paths it could generate, as it considers two
// machines with different multi paxos state potentially equal and will ignore exploring both.
// This should be undone as soon as possible. It's here because we need a better mechanism than
// .equals() to compare that two contexts are the same, which is not yet implemented.
return true;
}
@Override
public int hashCode()
{
return toString().hashCode();
}
private StateMachine snapshotStateMachine( Logging logging, MultiPaxosContext snapshotCtx, StateMachine
stateMachine )
{
// This is done this way because all the state machines are sharing one piece of global state
// (MultiPaxosContext), which is snapshotted as one coherent component. This means the state machines
// cannot snapshot themselves, an external service needs to snapshot the full shared state and then create
// new state machines sharing that state.
Object ctx;
Class<? extends MessageType> msgType = stateMachine.getMessageType();
if(msgType == AtomicBroadcastMessage.class)
{
ctx = snapshotCtx.getAtomicBroadcastContext();
}
else if(msgType == AcceptorMessage.class)
{
ctx = snapshotCtx.getAcceptorContext();
}
else if(msgType == ProposerMessage.class)
{
ctx = snapshotCtx.getProposerContext();
}
else if(msgType == LearnerMessage.class)
{
ctx = snapshotCtx.getLearnerContext();
}
else if(msgType == HeartbeatMessage.class)
{
ctx = snapshotCtx.getHeartbeatContext();
}
else if(msgType == ElectionMessage.class)
{
ctx = snapshotCtx.getElectionContext();
}
else if(msgType == SnapshotMessage.class)
{
ctx = new SnapshotContext( snapshotCtx.getClusterContext(), snapshotCtx.getLearnerContext() );
}
else if(msgType == ClusterMessage.class)
{
ctx = snapshotCtx.getClusterContext();
}
else
{
throw new IllegalArgumentException( "I don't know how to snapshot this state machine: " + stateMachine );
}
return new StateMachine( ctx, stateMachine.getMessageType(), stateMachine.getState(), logging );
}
public ClusterInstance newCopy()
{
// A very invasive method of cloning a protocol server. Nonetheless, since this is mostly an experiment at this
// point, it seems we can refactor later on to have a cleaner clone mechanism.
// Because state machines share state, and are simultaneously conceptually unaware of each other, implementing
// a clean snapshot mechanism is very hard. I've opted for having a dirty one here in the test code rather
// than introducing a hack into the runtime code.
ProverTimeouts timeoutsSnapshot = timeouts.snapshot();
InMemoryAcceptorInstanceStore snapshotAcceptorInstances = acceptorInstanceStore.snapshot();
ClusterInstanceOutput output = new ClusterInstanceOutput(uri);
ClusterInstanceInput input = new ClusterInstanceInput();
DelayedDirectExecutor executor = new DelayedDirectExecutor();
ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory();
MultiPaxosContext snapshotCtx = ctx.snapshot( logging, timeoutsSnapshot, executor, snapshotAcceptorInstances,
objectStreamFactory, objectStreamFactory,
new DefaultElectionCredentialsProvider( server.getServerId().toIntegerIndex(),
new StateVerifierLastTxIdGetter(),
new MemberInfoProvider() ) );
List<StateMachine> snapshotMachines = new ArrayList<>();
for ( StateMachine stateMachine : server.getStateMachines().getStateMachines() )
{
snapshotMachines.add( snapshotStateMachine( logging, snapshotCtx, stateMachine ) );
}
ProtocolServer snapshotProtocolServer = factory.constructSupportingInfrastructureFor( server.getServerId(),
input, output, executor, timeoutsSnapshot, stateMachineExecutor,
snapshotCtx, snapshotMachines.toArray( new StateMachine[snapshotMachines.size()] ) );
return new ClusterInstance( stateMachineExecutor, logging, factory, snapshotProtocolServer, snapshotCtx,
snapshotAcceptorInstances, timeoutsSnapshot, input, output, uri );
}
public URI uri()
{
return uri;
}
public boolean hasPendingTimeouts()
{
return timeouts.hasTimeouts();
}
public ClusterAction popTimeout()
{
return timeouts.pop();
}
/** Make this instance stop responding to calls, and cancel all pending timeouts. */
public void crash()
{
timeouts.cancelAllTimeouts();
this.online = false;
}
private static class ClusterInstanceInput implements MessageSource, MessageProcessor
{
private final List<MessageProcessor> processors = new ArrayList<>();
@Override
public boolean process( Message<? extends MessageType> message )
{
for ( MessageProcessor processor : processors )
{
if(!processor.process( message ))
{
return false;
}
}
return true;
}
@Override
public void addMessageProcessor( MessageProcessor messageProcessor )
{
processors.add( messageProcessor );
}
}
private static class ClusterInstanceOutput implements MessageSender
{
private final List<Message<? extends MessageType>> messages = new ArrayList<>();
private final URI uri;
public ClusterInstanceOutput( URI uri )
{
this.uri = uri;
}
@Override
public boolean process( Message<? extends MessageType> message )
{
messages.add( message.setHeader( Message.FROM, uri.toASCIIString() ) );
return true;
}
@Override
public void process( List<Message<? extends MessageType>> msgList )
{
for ( Message<? extends MessageType> msg : msgList )
{
process( msg );
}
}
public Iterable<Message<? extends MessageType>> messages()
{
return messages;
}
}
static class MemberInfoProvider implements HighAvailabilityMemberInfoProvider
{
@Override
public HighAvailabilityMemberState getHighAvailabilityMemberState()
{
throw new UnsupportedOperationException( "TODO" );
}
}
// TODO: Make this emulate commits happening
static class StateVerifierLastTxIdGetter implements LastTxIdGetter
{
@Override
public long getLastTxId()
{
return 0;
}
}
} | 1no label
| enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterInstance.java |
599 | interface ValuesTransformer<V> {
Collection<OIdentifiable> transformFromValue(V value);
V transformToValue(Collection<OIdentifiable> collection);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexEngine.java |
1,067 | public class MapIndexConfigReadOnly extends MapIndexConfig {
public MapIndexConfigReadOnly(MapIndexConfig config) {
super(config);
}
public MapIndexConfig setAttribute(String attribute) {
throw new UnsupportedOperationException("This config is read-only");
}
public MapIndexConfig setOrdered(boolean ordered) {
throw new UnsupportedOperationException("This config is read-only");
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_MapIndexConfigReadOnly.java |
47 | static final class PackageProposal extends CompletionProposal {
private final boolean withBody;
private final int len;
private final Package p;
private final String completed;
private final CeylonParseController cpc;
PackageProposal(int offset, String prefix, boolean withBody,
int len, Package p, String completed,
CeylonParseController cpc) {
super(offset, prefix, PACKAGE, completed,
completed.substring(len));
this.withBody = withBody;
this.len = len;
this.p = p;
this.completed = completed;
this.cpc = cpc;
}
@Override
public Point getSelection(IDocument document) {
if (withBody) {
return new Point(offset+completed.length()-prefix.length()-len-5, 3);
}
else {
return new Point(offset+completed.length()-prefix.length()-len, 0);
}
}
@Override
public void apply(IDocument document) {
super.apply(document);
if (withBody &&
EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
final LinkedModeModel linkedModeModel = new LinkedModeModel();
final Point selection = getSelection(document);
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
for (final Declaration d: p.getMembers()) {
if (Util.isResolvable(d) && d.isShared() &&
!isOverloadedVersion(d)) {
proposals.add(new ICompletionProposal() {
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public Image getImage() {
return getImageForDeclaration(d);
}
@Override
public String getDisplayString() {
return d.getName();
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public void apply(IDocument document) {
try {
document.replace(selection.x, selection.y,
d.getName());
}
catch (BadLocationException e) {
e.printStackTrace();
}
linkedModeModel.exit(ILinkedModeListener.UPDATE_CARET);
}
});
}
}
if (!proposals.isEmpty()) {
ProposalPosition linkedPosition =
new ProposalPosition(document, selection.x, selection.y, 0,
proposals.toArray(NO_COMPLETIONS));
try {
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
-1, 0);
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
}
@Override
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, p);
}
@Override
protected boolean qualifiedNameIsPath() {
return true;
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_PackageCompletions.java |
849 | return new IAnswer<OrderItem>() {
@Override
public OrderItem answer() throws Throwable {
Order order = (Order) EasyMock.getCurrentArguments()[0];
order.getOrderItems().add((OrderItem) EasyMock.getCurrentArguments()[1]);
if (((OrderItem) EasyMock.getCurrentArguments()[1]).getId() == null) {
((OrderItem) EasyMock.getCurrentArguments()[1]).setId(OfferDataItemProvider.getOrderItemId());
}
return (OrderItem) EasyMock.getCurrentArguments()[1];
}
}; | 0true
| core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_OfferDataItemProvider.java |
900 | public interface ORecordPositional<T> extends ORecordInternal<T>, Iterator<T> {
public <E> E field(int iIndex);
public ORecordPositional<T> field(int iIndex, Object iValue);
public int size();
public ORecordPositional<T> add(Object iValue);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_ORecordPositional.java |
609 | public class UpdateSettingsRequest extends AcknowledgedRequest<UpdateSettingsRequest> {
private String[] indices;
private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, true);
private Settings settings = EMPTY_SETTINGS;
UpdateSettingsRequest() {
}
/**
* Constructs a new request to update settings for one or more indices
*/
public UpdateSettingsRequest(String... indices) {
this.indices = indices;
}
/**
* Constructs a new request to update settings for one or more indices
*/
public UpdateSettingsRequest(Settings settings, String... indices) {
this.indices = indices;
this.settings = settings;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (settings.getAsMap().isEmpty()) {
validationException = addValidationError("no settings to update", validationException);
}
return validationException;
}
String[] indices() {
return indices;
}
Settings settings() {
return settings;
}
/**
* Sets the indices to apply to settings update to
*/
public UpdateSettingsRequest indices(String... indices) {
this.indices = indices;
return this;
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public UpdateSettingsRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
/**
* Sets the settings to be updated
*/
public UpdateSettingsRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* Sets the settings to be updated
*/
public UpdateSettingsRequest settings(Settings.Builder settings) {
this.settings = settings.build();
return this;
}
/**
* Sets the settings to be updated (either json/yaml/properties format)
*/
public UpdateSettingsRequest settings(String source) {
this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
/**
* Sets the settings to be updated (either json/yaml/properties format)
*/
@SuppressWarnings("unchecked")
public UpdateSettingsRequest settings(Map 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;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = in.readStringArray();
indicesOptions = IndicesOptions.readIndicesOptions(in);
settings = readSettingsFromStream(in);
readTimeout(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArrayNullable(indices);
indicesOptions.writeIndicesOptions(out);
writeSettingsToStream(settings, out);
writeTimeout(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_settings_put_UpdateSettingsRequest.java |
956 | public abstract class TransportMasterNodeReadOperationAction<Request extends MasterNodeReadOperationRequest, Response extends ActionResponse> extends TransportMasterNodeOperationAction<Request, Response> {
public static final String FORCE_LOCAL_SETTING = "action.master.force_local";
private Boolean forceLocal;
protected TransportMasterNodeReadOperationAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) {
super(settings, transportService, clusterService, threadPool);
this.forceLocal = settings.getAsBoolean(FORCE_LOCAL_SETTING, null);
}
protected final boolean localExecute(Request request) {
if (forceLocal != null) {
return forceLocal;
}
return request.local();
}
} | 0true
| src_main_java_org_elasticsearch_action_support_master_TransportMasterNodeReadOperationAction.java |
1,455 | public class Value {
private final Object version;
private final Object value;
private final SoftLock lock;
private final long creationTime;
public Value(final Object version, final Object value, final long creationTime) {
this.version = version;
this.value = value;
this.creationTime = creationTime;
this.lock = null;
}
public Value(final Object version, final Object value, final SoftLock lock, final long creationTime) {
this.version = version;
this.value = value;
this.lock = lock;
this.creationTime = creationTime;
}
public Object getValue() {
return value;
}
public Object getVersion() {
return version;
}
public SoftLock getLock() {
return lock;
}
public long getCreationTime() {
return creationTime;
}
public Value createLockedValue(SoftLock lock) {
return new Value(version, value, lock, creationTime);
}
public Value createUnlockedValue() {
return new Value(version, value, null, creationTime);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Value value1 = (Value) o;
if (value != null ? !value.equals(value1.value) : value1.value != null) return false;
if (version != null ? !version.equals(value1.version) : value1.version != null) return false;
return true;
}
@Override
public int hashCode() {
int result = version != null ? version.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Value");
sb.append("{value=").append(value);
sb.append(", version=").append(version);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_local_Value.java |
3,148 | return new BytesValues(values.isMultiValued()) {
@Override
public int setDocument(int docId) {
this.docId = docId;
return values.setDocument(docId);
}
@Override
public BytesRef nextValue() {
scratch.copyChars(Double.toString(values.nextValue()));
return scratch;
}
@Override
public Order getOrder() {
return values.getOrder();
}
}; | 0true
| src_main_java_org_elasticsearch_index_fielddata_AbstractAtomicNumericFieldData.java |
6,451 | class TribeClusterStateListener implements ClusterStateListener {
private final InternalNode tribeNode;
private final String tribeName;
TribeClusterStateListener(InternalNode tribeNode) {
this.tribeNode = tribeNode;
this.tribeName = tribeNode.settings().get(TRIBE_NAME);
}
@Override
public void clusterChanged(final ClusterChangedEvent event) {
logger.debug("[{}] received cluster event, [{}]", tribeName, event.source());
clusterService.submitStateUpdateTask("cluster event from " + tribeName + ", " + event.source(), new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
ClusterState tribeState = event.state();
DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(currentState.nodes());
// -- merge nodes
// go over existing nodes, and see if they need to be removed
for (DiscoveryNode discoNode : currentState.nodes()) {
String markedTribeName = discoNode.attributes().get(TRIBE_NAME);
if (markedTribeName != null && markedTribeName.equals(tribeName)) {
if (tribeState.nodes().get(discoNode.id()) == null) {
logger.info("[{}] removing node [{}]", tribeName, discoNode);
nodes.remove(discoNode.id());
}
}
}
// go over tribe nodes, and see if they need to be added
for (DiscoveryNode tribe : tribeState.nodes()) {
if (currentState.nodes().get(tribe.id()) == null) {
// a new node, add it, but also add the tribe name to the attributes
ImmutableMap<String, String> tribeAttr = MapBuilder.newMapBuilder(tribe.attributes()).put(TRIBE_NAME, tribeName).immutableMap();
DiscoveryNode discoNode = new DiscoveryNode(tribe.name(), tribe.id(), tribe.getHostName(), tribe.getHostAddress(), tribe.address(), tribeAttr, tribe.version());
logger.info("[{}] adding node [{}]", tribeName, discoNode);
nodes.put(discoNode);
}
}
// -- merge metadata
MetaData.Builder metaData = MetaData.builder(currentState.metaData());
RoutingTable.Builder routingTable = RoutingTable.builder(currentState.routingTable());
// go over existing indices, and see if they need to be removed
for (IndexMetaData index : currentState.metaData()) {
String markedTribeName = index.settings().get(TRIBE_NAME);
if (markedTribeName != null && markedTribeName.equals(tribeName)) {
IndexMetaData tribeIndex = tribeState.metaData().index(index.index());
if (tribeIndex == null) {
logger.info("[{}] removing index [{}]", tribeName, index.index());
metaData.remove(index.index());
routingTable.remove(index.index());
} else {
// always make sure to update the metadata and routing table, in case
// there are changes in them (new mapping, shards moving from initializing to started)
routingTable.add(tribeState.routingTable().index(index.index()));
Settings tribeSettings = ImmutableSettings.builder().put(tribeIndex.settings()).put(TRIBE_NAME, tribeName).build();
metaData.put(IndexMetaData.builder(tribeIndex).settings(tribeSettings));
}
}
}
// go over tribe one, and see if they need to be added
for (IndexMetaData tribeIndex : tribeState.metaData()) {
if (!currentState.metaData().hasIndex(tribeIndex.index())) {
// a new index, add it, and add the tribe name as a setting
logger.info("[{}] adding index [{}]", tribeName, tribeIndex.index());
Settings tribeSettings = ImmutableSettings.builder().put(tribeIndex.settings()).put(TRIBE_NAME, tribeName).build();
metaData.put(IndexMetaData.builder(tribeIndex).settings(tribeSettings));
routingTable.add(tribeState.routingTable().index(tribeIndex.index()));
}
}
return ClusterState.builder(currentState).nodes(nodes).metaData(metaData).routingTable(routingTable).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.warn("failed to process [{}]", t, source);
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_tribe_TribeService.java |
678 | public class TransportGetWarmersAction extends TransportClusterInfoAction<GetWarmersRequest, GetWarmersResponse> {
@Inject
public TransportGetWarmersAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) {
super(settings, transportService, clusterService, threadPool);
}
@Override
protected String transportAction() {
return GetWarmersAction.NAME;
}
@Override
protected GetWarmersRequest newRequest() {
return new GetWarmersRequest();
}
@Override
protected GetWarmersResponse newResponse() {
return new GetWarmersResponse();
}
@Override
protected void doMasterOperation(final GetWarmersRequest request, final ClusterState state, final ActionListener<GetWarmersResponse> listener) throws ElasticsearchException {
ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> result = state.metaData().findWarmers(
request.indices(), request.types(), request.warmers()
);
listener.onResponse(new GetWarmersResponse(result));
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_warmer_get_TransportGetWarmersAction.java |
1,361 | @Deprecated
public interface CodeType extends Serializable {
public void setId(Long id);
public Long getId();
public void setCodeType(String type);
public String getCodeType();
public void setKey(String key);
public String getKey();
public void setDescription(String description);
public String getDescription();
public void setModifiable(Boolean modifiable);
public Boolean getModifiable();
public Boolean isModifiable();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_util_domain_CodeType.java |
494 | new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
String message = "Internal executor rejected task: " + r + ", because client is shutting down...";
LOGGER.finest(message);
throw new RejectedExecutionException(message);
}
}); | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientExecutionServiceImpl.java |
851 | DOUBLE("Double", 5, new Class<?>[] { Double.class, Double.TYPE }, new Class<?>[] { Double.class, Number.class }) {
}, | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java |
515 | public class SystemTimeTest extends TestCase {
private TimeSource mockTimeSource;
protected void setUp() throws Exception {
super.setUp();
mockTimeSource = createMock(TimeSource.class);
}
protected void tearDown() throws Exception {
SystemTime.reset();
super.tearDown();
}
/**
* Test method for {@link SystemTime#setGlobalTimeSource(TimeSource)}.
*/
public void testSetGlobalTimeSource() {
expect(mockTimeSource.timeInMillis()).andReturn(100L).atLeastOnce();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
assertEquals(100L, SystemTime.asMillis());
verify();
}
/**
* Test method for {@link SystemTime#resetGlobalTimeSource()}.
*/
public void testResetGlobalTimeSource() {
expect(mockTimeSource.timeInMillis()).andReturn(200L).anyTimes();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
SystemTime.resetGlobalTimeSource();
assertTrue(200L != SystemTime.asMillis());
verify();
}
/**
* Test method for {@link SystemTime#setLocalTimeSource(TimeSource)}.
*/
public void testSetLocalTimeSource() {
expect(mockTimeSource.timeInMillis()).andReturn(300L).atLeastOnce();
replay(mockTimeSource);
SystemTime.setLocalTimeSource(mockTimeSource);
assertEquals(300L, SystemTime.asMillis());
verify();
}
/**
* Test method for {@link SystemTime#resetLocalTimeSource()}.
*/
public void testResetLocalTimeSource() {
expect(mockTimeSource.timeInMillis()).andReturn(400L).anyTimes();
replay(mockTimeSource);
SystemTime.setLocalTimeSource(mockTimeSource);
SystemTime.resetLocalTimeSource();
assertTrue(400L != SystemTime.asMillis());
verify();
}
/**
* Test method for {@link SystemTime#resetLocalTimeSource()}.
*/
public void testLocalOverridesGlobal() {
TimeSource mockLocalTimeSource = createMock(TimeSource.class);
expect(mockTimeSource.timeInMillis()).andReturn(500L).anyTimes();
expect(mockLocalTimeSource.timeInMillis()).andReturn(600L).atLeastOnce();
replay(mockTimeSource, mockLocalTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
SystemTime.setLocalTimeSource(mockLocalTimeSource);
assertEquals(600L, SystemTime.asMillis());
SystemTime.resetLocalTimeSource();
assertEquals(500L, SystemTime.asMillis());
verify();
}
/**
* Test method for {@link SystemTime#reset()}.
*/
public void testReset() {
TimeSource mockLocalTimeSource = createMock(TimeSource.class);
expect(mockTimeSource.timeInMillis()).andReturn(700L).anyTimes();
expect(mockLocalTimeSource.timeInMillis()).andReturn(800L).anyTimes();
replay(mockTimeSource, mockLocalTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
SystemTime.setLocalTimeSource(mockLocalTimeSource);
SystemTime.reset();
assertTrue(SystemTime.asMillis() > 800L);
verify();
}
/**
* Test method for {@link SystemTime#asMillis()}.
*/
public void testAsMillis() {
expect(mockTimeSource.timeInMillis()).andReturn(1000L).atLeastOnce();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
assertEquals(1000L, SystemTime.asMillis());
verify();
}
/**
* Test method for {@link SystemTime#asDate()}.
*/
public void testAsDate() {
expect(mockTimeSource.timeInMillis()).andReturn(1100L).atLeastOnce();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
assertEquals(1100L, SystemTime.asDate().getTime());
verify();
}
/**
* Test method for {@link SystemTime#asCalendar()}.
*/
public void testAsCalendar() {
expect(mockTimeSource.timeInMillis()).andReturn(1200L).atLeastOnce();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
assertEquals(1200L, SystemTime.asCalendar().getTimeInMillis());
verify();
}
/**
* Test method for {@link SystemTime#asMillis(boolean)}.
*/
public void testAsMillisBoolean() {
Calendar cal = new GregorianCalendar(2010, 1, 2, 3, 4, 5);
long timeInMillis = cal.getTimeInMillis() + 3; // Add a few milliseconds for good measure
expect(mockTimeSource.timeInMillis()).andReturn(timeInMillis).atLeastOnce();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
Calendar calMidnight = new GregorianCalendar(2010, 1, 2, 0, 0, 0);
calMidnight.set(Calendar.MILLISECOND, 0);
assertEquals(calMidnight.getTimeInMillis(), SystemTime.asMillis(false));
assertEquals(timeInMillis, SystemTime.asMillis(true));
verify();
}
/**
* Test method for {@link SystemTime#asCalendar(boolean)}.
*/
public void testAsCalendarBoolean() {
Calendar cal = new GregorianCalendar(2010, 1, 2, 3, 4, 5);
cal.set(Calendar.MILLISECOND, 3); // Add a few milliseconds for good measure
expect(mockTimeSource.timeInMillis()).andReturn(cal.getTimeInMillis()).atLeastOnce();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
Calendar calMidnight = new GregorianCalendar(2010, 1, 2, 0, 0, 0);
calMidnight.set(Calendar.MILLISECOND, 0);
assertEquals(calMidnight, SystemTime.asCalendar(false));
assertEquals(cal, SystemTime.asCalendar(true));
verify();
}
/**
* Test method for {@link SystemTime#asDate(boolean)}.
*/
public void testAsDateBoolean() {
Calendar cal = new GregorianCalendar(2010, 1, 2, 3, 4, 5);
cal.set(Calendar.MILLISECOND, 3); // Add a few milliseconds for good measure
expect(mockTimeSource.timeInMillis()).andReturn(cal.getTimeInMillis()).atLeastOnce();
replay(mockTimeSource);
SystemTime.setGlobalTimeSource(mockTimeSource);
Calendar calMidnight = new GregorianCalendar(2010, 1, 2, 0, 0, 0);
calMidnight.set(Calendar.MILLISECOND, 0);
assertEquals(calMidnight.getTimeInMillis(), SystemTime.asDate(false).getTime());
assertEquals(cal.getTimeInMillis(), SystemTime.asDate(true).getTime());
verify();
}
} | 0true
| common_src_test_java_org_broadleafcommerce_common_time_SystemTimeTest.java |
1,965 | @Entity
@EntityListeners(value = { TemporalTimestampListener.class })
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_ADDRESS")
@AdminPresentationMergeOverrides(
{
@AdminPresentationMergeOverride(name = "phonePrimary", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = true)),
@AdminPresentationMergeOverride(name = "phoneSecondary", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = true)),
@AdminPresentationMergeOverride(name = "phoneFax", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = true)),
@AdminPresentationMergeOverride(name = "phonePrimary.phoneNumber", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = false),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.ORDER,
intOverrideValue = 1300),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE,
overrideValue = "NOT_REQUIRED"),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.FRIENDLYNAME,
overrideValue = "PhoneImpl_Primary_Phone")}),
@AdminPresentationMergeOverride(name = "phoneSecondary.phoneNumber", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = false),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.ORDER,
intOverrideValue = 1400),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE,
overrideValue = "NOT_REQUIRED"),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.FRIENDLYNAME,
overrideValue = "PhoneImpl_Secondary_Phone")}),
@AdminPresentationMergeOverride(name = "phoneFax.phoneNumber", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = false),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.ORDER,
intOverrideValue = 1500),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE,
overrideValue = "NOT_REQUIRED"),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.FRIENDLYNAME,
overrideValue = "PhoneImpl_Fax_Phone")})
}
)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "AddressImpl_baseAddress")
public class AddressImpl implements Address {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "AddressId")
@GenericGenerator(
name="AddressId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="AddressImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.profile.core.domain.AddressImpl")
}
)
@Column(name = "ADDRESS_ID")
protected Long id;
@Column(name = "FIRST_NAME")
@AdminPresentation(friendlyName = "AddressImpl_First_Name", order=10, group = "AddressImpl_Address")
protected String firstName;
@Column(name = "LAST_NAME")
@AdminPresentation(friendlyName = "AddressImpl_Last_Name", order=20, group = "AddressImpl_Address")
protected String lastName;
@Column(name = "EMAIL_ADDRESS")
@AdminPresentation(friendlyName = "AddressImpl_Email_Address", order=30, group = "AddressImpl_Address")
protected String emailAddress;
@Column(name = "COMPANY_NAME")
@AdminPresentation(friendlyName = "AddressImpl_Company_Name", order=40, group = "AddressImpl_Address")
protected String companyName;
@Column(name = "ADDRESS_LINE1", nullable = false)
@AdminPresentation(friendlyName = "AddressImpl_Address_1", order=50, group = "AddressImpl_Address")
protected String addressLine1;
@Column(name = "ADDRESS_LINE2")
@AdminPresentation(friendlyName = "AddressImpl_Address_2", order=60, group = "AddressImpl_Address")
protected String addressLine2;
@Column(name = "ADDRESS_LINE3")
@AdminPresentation(friendlyName = "AddressImpl_Address_3", order = 60, group = "AddressImpl_Address")
protected String addressLine3;
@Column(name = "CITY", nullable = false)
@AdminPresentation(friendlyName = "AddressImpl_City", order=70, group = "AddressImpl_Address")
protected String city;
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = StateImpl.class)
@JoinColumn(name = "STATE_PROV_REGION")
@Index(name="ADDRESS_STATE_INDEX", columnNames={"STATE_PROV_REGION"})
@AdminPresentation(friendlyName = "AddressImpl_State", order=80, group = "AddressImpl_Address")
@AdminPresentationToOneLookup()
protected State state;
@Column(name = "COUNTY")
@AdminPresentation(friendlyName = "AddressImpl_County", order=90, group = "AddressImpl_Address")
protected String county;
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = CountryImpl.class, optional = false)
@JoinColumn(name = "COUNTRY")
@Index(name="ADDRESS_COUNTRY_INDEX", columnNames={"COUNTRY"})
@AdminPresentation(friendlyName = "AddressImpl_Country", order=100, group = "AddressImpl_Address")
@AdminPresentationToOneLookup()
protected Country country;
@Column(name = "POSTAL_CODE", nullable = false)
@AdminPresentation(friendlyName = "AddressImpl_Postal_Code", order=110, group = "AddressImpl_Address")
protected String postalCode;
@Column(name = "ZIP_FOUR")
@AdminPresentation(friendlyName = "AddressImpl_Four_Digit_Zip", order=120, group = "AddressImpl_Address")
protected String zipFour;
@ManyToOne(targetEntity = PhoneImpl.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "PHONE_PRIMARY_ID")
@Index(name="ADDRESS_PHONE_PRI_IDX", columnNames={"PHONE_PRIMARY_ID"})
protected Phone phonePrimary;
@ManyToOne(targetEntity = PhoneImpl.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "PHONE_SECONDARY_ID")
@Index(name="ADDRESS_PHONE_SEC_IDX", columnNames={"PHONE_SECONDARY_ID"})
protected Phone phoneSecondary;
@ManyToOne(targetEntity = PhoneImpl.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "PHONE_FAX_ID")
@Index(name="ADDRESS_PHONE_FAX_IDX", columnNames={"PHONE_FAX_ID"})
protected Phone phoneFax;
@Column(name = "IS_DEFAULT")
@AdminPresentation(friendlyName = "AddressImpl_Default_Address", order=160, group = "AddressImpl_Address")
protected boolean isDefault = false;
@Column(name = "IS_ACTIVE")
@AdminPresentation(friendlyName = "AddressImpl_Active_Address", order=170, group = "AddressImpl_Address")
protected boolean isActive = true;
@Column(name = "IS_BUSINESS")
@AdminPresentation(friendlyName = "AddressImpl_Business_Address", order=180, group = "AddressImpl_Address")
protected boolean isBusiness = false;
/**
* This is intented to be used for address verification integrations and should not be modifiable in the admin
*/
@Column(name = "TOKENIZED_ADDRESS")
@AdminPresentation(friendlyName = "AddressImpl_Tokenized_Address", order=190, group = "AddressImpl_Address", visibility=VisibilityEnum.HIDDEN_ALL)
protected String tokenizedAddress;
/**
* This is intented to be used for address verification integrations and should not be modifiable in the admin
*/
@Column(name = "STANDARDIZED")
@AdminPresentation(friendlyName = "AddressImpl_Standardized", order=200, group = "AddressImpl_Address", visibility=VisibilityEnum.HIDDEN_ALL)
protected Boolean standardized = Boolean.FALSE;
/**
* This is intented to be used for address verification integrations and should not be modifiable in the admin
*/
@Column(name = "VERIFICATION_LEVEL")
@AdminPresentation(friendlyName = "AddressImpl_Verification_Level", order=210, group = "AddressImpl_Address", visibility=VisibilityEnum.HIDDEN_ALL)
protected String verificationLevel;
@Column(name = "PRIMARY_PHONE")
@Deprecated
protected String primaryPhone;
@Column(name = "SECONDARY_PHONE")
@Deprecated
protected String secondaryPhone;
@Column(name = "FAX")
@Deprecated
protected String fax;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getAddressLine1() {
return addressLine1;
}
@Override
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
@Override
public String getAddressLine2() {
return addressLine2;
}
@Override
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
@Override
public String getAddressLine3() {
return addressLine3;
}
@Override
public void setAddressLine3(String addressLine3) {
this.addressLine3 = addressLine3;
}
@Override
public String getCity() {
return city;
}
@Override
public void setCity(String city) {
this.city = city;
}
@Override
public Country getCountry() {
return country;
}
@Override
public void setCountry(Country country) {
this.country = country;
}
@Override
public String getPostalCode() {
return postalCode;
}
@Override
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
@Override
public String getCounty() {
return county;
}
@Override
public void setCounty(String county) {
this.county = county;
}
@Override
public State getState() {
return state;
}
@Override
public void setState(State state) {
this.state = state;
}
@Override
public String getTokenizedAddress() {
return tokenizedAddress;
}
@Override
public void setTokenizedAddress(String tokenizedAddress) {
this.tokenizedAddress = tokenizedAddress;
}
@Override
public Boolean getStandardized() {
return standardized;
}
@Override
public void setStandardized(Boolean standardized) {
this.standardized = standardized;
}
@Override
public String getZipFour() {
return zipFour;
}
@Override
public void setZipFour(String zipFour) {
this.zipFour = zipFour;
}
@Override
public String getCompanyName() {
return companyName;
}
@Override
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
@Override
public boolean isDefault() {
return isDefault;
}
@Override
public void setDefault(boolean isDefault) {
this.isDefault = isDefault;
}
@Override
public boolean isActive() {
return isActive;
}
@Override
public void setActive(boolean isActive) {
this.isActive = isActive;
}
@Override
public String getFirstName() {
return firstName;
}
@Override
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String getLastName() {
return lastName;
}
@Override
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
@Deprecated
public String getPrimaryPhone() {
return primaryPhone;
}
@Override
@Deprecated
public void setPrimaryPhone(String primaryPhone) {
this.primaryPhone = primaryPhone;
}
@Override
@Deprecated
public String getSecondaryPhone() {
return secondaryPhone;
}
@Override
@Deprecated
public void setSecondaryPhone(String secondaryPhone) {
this.secondaryPhone = secondaryPhone;
}
@Override
@Deprecated
public String getFax() {
return this.fax;
}
@Override
@Deprecated
public void setFax(String fax) {
this.fax = fax;
}
@Override
public Phone getPhonePrimary() {
Phone legacyPhone = new PhoneImpl();
legacyPhone.setPhoneNumber(this.primaryPhone);
return (phonePrimary == null && this.primaryPhone !=null)? legacyPhone : phonePrimary;
}
@Override
public void setPhonePrimary(Phone phonePrimary) {
this.phonePrimary = phonePrimary;
}
@Override
public Phone getPhoneSecondary() {
Phone legacyPhone = new PhoneImpl();
legacyPhone.setPhoneNumber(this.secondaryPhone);
return (phoneSecondary == null && this.secondaryPhone !=null)? legacyPhone : phoneSecondary;
}
@Override
public void setPhoneSecondary(Phone phoneSecondary) {
this.phoneSecondary = phoneSecondary;
}
@Override
public Phone getPhoneFax() {
Phone legacyPhone = new PhoneImpl();
legacyPhone.setPhoneNumber(this.fax);
return (phoneFax == null && this.fax != null)? legacyPhone : phoneFax;
}
@Override
public void setPhoneFax(Phone phoneFax) {
this.phoneFax = phoneFax;
}
@Override
public boolean isBusiness() {
return isBusiness;
}
@Override
public void setBusiness(boolean isBusiness) {
this.isBusiness = isBusiness;
}
@Override
public String getVerificationLevel() {
return verificationLevel;
}
@Override
public void setVerificationLevel(String verificationLevel) {
this.verificationLevel = verificationLevel;
}
@Override
public String getEmailAddress() {
return this.emailAddress;
}
@Override
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AddressImpl other = (AddressImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (addressLine1 == null) {
if (other.addressLine1 != null)
return false;
} else if (!addressLine1.equals(other.addressLine1))
return false;
if (addressLine2 == null) {
if (other.addressLine2 != null)
return false;
} else if (!addressLine2.equals(other.addressLine2))
return false;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (companyName == null) {
if (other.companyName != null)
return false;
} else if (!companyName.equals(other.companyName))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (county == null) {
if (other.county != null)
return false;
} else if (!county.equals(other.county))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (postalCode == null) {
if (other.postalCode != null)
return false;
} else if (!postalCode.equals(other.postalCode))
return false;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((addressLine1 == null) ? 0 : addressLine1.hashCode());
result = prime * result + ((addressLine2 == null) ? 0 : addressLine2.hashCode());
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((companyName == null) ? 0 : companyName.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((county == null) ? 0 : county.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((postalCode == null) ? 0 : postalCode.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
return result;
}
} | 1no label
| core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_AddressImpl.java |
965 | public abstract class TransportNodesOperationAction<Request extends NodesOperationRequest, Response extends NodesOperationResponse, NodeRequest extends NodeOperationRequest, NodeResponse extends NodeOperationResponse> extends TransportAction<Request, Response> {
protected final ClusterName clusterName;
protected final ClusterService clusterService;
protected final TransportService transportService;
final String transportAction;
final String transportNodeAction;
final String executor;
@Inject
public TransportNodesOperationAction(Settings settings, ClusterName clusterName, ThreadPool threadPool,
ClusterService clusterService, TransportService transportService) {
super(settings, threadPool);
this.clusterName = clusterName;
this.clusterService = clusterService;
this.transportService = transportService;
this.transportAction = transportAction();
this.transportNodeAction = transportAction() + "/n";
this.executor = executor();
transportService.registerHandler(transportAction, new TransportHandler());
transportService.registerHandler(transportNodeAction, new NodeTransportHandler());
}
@Override
protected void doExecute(Request request, ActionListener<Response> listener) {
new AsyncAction(request, listener).start();
}
protected abstract String transportAction();
protected boolean transportCompress() {
return false;
}
protected abstract String executor();
protected abstract Request newRequest();
protected abstract Response newResponse(Request request, AtomicReferenceArray nodesResponses);
protected abstract NodeRequest newNodeRequest();
protected abstract NodeRequest newNodeRequest(String nodeId, Request request);
protected abstract NodeResponse newNodeResponse();
protected abstract NodeResponse nodeOperation(NodeRequest request) throws ElasticsearchException;
protected abstract boolean accumulateExceptions();
protected String[] filterNodeIds(DiscoveryNodes nodes, String[] nodesIds) {
return nodesIds;
}
private class AsyncAction {
private final Request request;
private final String[] nodesIds;
private final ActionListener<Response> listener;
private final ClusterState clusterState;
private final AtomicReferenceArray<Object> responses;
private final AtomicInteger counter = new AtomicInteger();
private AsyncAction(Request request, ActionListener<Response> listener) {
this.request = request;
this.listener = listener;
clusterState = clusterService.state();
String[] nodesIds = clusterState.nodes().resolveNodesIds(request.nodesIds());
this.nodesIds = filterNodeIds(clusterState.nodes(), nodesIds);
this.responses = new AtomicReferenceArray<Object>(this.nodesIds.length);
}
private void start() {
if (nodesIds.length == 0) {
// nothing to notify
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
listener.onResponse(newResponse(request, responses));
}
});
return;
}
TransportRequestOptions transportRequestOptions = TransportRequestOptions.options();
if (request.timeout() != null) {
transportRequestOptions.withTimeout(request.timeout());
}
transportRequestOptions.withCompress(transportCompress());
for (int i = 0; i < nodesIds.length; i++) {
final String nodeId = nodesIds[i];
final int idx = i;
final DiscoveryNode node = clusterState.nodes().nodes().get(nodeId);
try {
if (nodeId.equals("_local") || nodeId.equals(clusterState.nodes().localNodeId())) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
onOperation(idx, nodeOperation(newNodeRequest(clusterState.nodes().localNodeId(), request)));
} catch (Throwable e) {
onFailure(idx, clusterState.nodes().localNodeId(), e);
}
}
});
} else if (nodeId.equals("_master")) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
onOperation(idx, nodeOperation(newNodeRequest(clusterState.nodes().masterNodeId(), request)));
} catch (Throwable e) {
onFailure(idx, clusterState.nodes().masterNodeId(), e);
}
}
});
} else {
if (node == null) {
onFailure(idx, nodeId, new NoSuchNodeException(nodeId));
} else {
NodeRequest nodeRequest = newNodeRequest(nodeId, request);
transportService.sendRequest(node, transportNodeAction, nodeRequest, transportRequestOptions, new BaseTransportResponseHandler<NodeResponse>() {
@Override
public NodeResponse newInstance() {
return newNodeResponse();
}
@Override
public void handleResponse(NodeResponse response) {
onOperation(idx, response);
}
@Override
public void handleException(TransportException exp) {
onFailure(idx, node.id(), exp);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
});
}
}
} catch (Throwable t) {
onFailure(idx, nodeId, t);
}
}
}
private void onOperation(int idx, NodeResponse nodeResponse) {
responses.set(idx, nodeResponse);
if (counter.incrementAndGet() == responses.length()) {
finishHim();
}
}
private void onFailure(int idx, String nodeId, Throwable t) {
if (logger.isDebugEnabled()) {
logger.debug("failed to execute on node [{}]", t, nodeId);
}
if (accumulateExceptions()) {
responses.set(idx, new FailedNodeException(nodeId, "Failed node [" + nodeId + "]", t));
}
if (counter.incrementAndGet() == responses.length()) {
finishHim();
}
}
private void finishHim() {
Response finalResponse;
try {
finalResponse = newResponse(request, responses);
} catch (Throwable t) {
logger.debug("failed to combine responses from nodes", t);
listener.onFailure(t);
return;
}
listener.onResponse(finalResponse);
}
}
private class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequest();
}
@Override
public void messageReceived(final Request request, final TransportChannel channel) throws Exception {
request.listenerThreaded(false);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
TransportResponseOptions options = TransportResponseOptions.options().withCompress(transportCompress());
try {
channel.sendResponse(response, options);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response", e);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public String toString() {
return transportAction;
}
}
private class NodeTransportHandler extends BaseTransportRequestHandler<NodeRequest> {
@Override
public NodeRequest newInstance() {
return newNodeRequest();
}
@Override
public void messageReceived(final NodeRequest request, final TransportChannel channel) throws Exception {
channel.sendResponse(nodeOperation(request));
}
@Override
public String toString() {
return transportNodeAction;
}
@Override
public String executor() {
return executor;
}
}
} | 0true
| src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java |
2,304 | public class ThreadLocalRecyclerTests extends AbstractRecyclerTests {
@Override
protected Recycler<byte[]> newRecycler() {
return Recyclers.threadLocal(Recyclers.dequeFactory(RECYCLER_C, 10));
}
} | 0true
| src_test_java_org_elasticsearch_common_recycler_ThreadLocalRecyclerTests.java |
315 | clusterService.submitStateUpdateTask("cluster_health (wait_for_events [" + request.waitForEvents() + "])", request.waitForEvents(), new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return currentState;
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
latch.countDown();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
}); | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_health_TransportClusterHealthAction.java |
2,707 | cluster().fullRestart(new RestartCallback() {
@Override
public Settings onNodeStopped(String nodeName) throws Exception {
return settingsBuilder().put("gateway.type", "local").build();
}
@Override
public boolean doRestart(String nodeName) {
return nodeToRemove.equals(nodeName);
}
}); | 0true
| src_test_java_org_elasticsearch_gateway_local_QuorumLocalGatewayTests.java |
1,121 | @Deprecated
public interface LegacyOrderService extends OrderService {
public FulfillmentGroup findDefaultFulfillmentGroupForOrder(Order order);
/**
* Note: This method will automatically associate the given <b>order</b> to the given <b>itemRequest</b> such that
* then resulting {@link OrderItem} will already have an {@link Order} associated to it.
*
* @param order
* @param itemRequest
* @return
* @throws PricingException
*/
public OrderItem addGiftWrapItemToOrder(Order order, GiftWrapOrderItemRequest itemRequest) throws PricingException;
/**
* Used to create dynamic bundles groupings of order items.
* Typically not used with ProductBundles which should instead
* call addProductToOrder.
*
* Prices the order after adding the bundle.
*
* @param order
* @param itemRequest
* @return
* @throws PricingException
*/
public OrderItem addBundleItemToOrder(Order order, BundleOrderItemRequest itemRequest) throws PricingException;
/**
* Used to create dynamic bundles groupings of order items.
* Typically not used with ProductBundles which should instead
* call addProductToOrder.
*
* Prices the order after adding the bundle if priceOrder = true. Clients
* may wish to perform many cart operations without pricing and
* then use priceOrder = true on the last operation to avoid
* exercising the pricing engine in a batch order update mode.
*
* NOTE: this will automatically associate the given <b>order</b> to the given <b>itemRequest</b> such that the
* resulting {@link OrderItem} will already have the {@link Order} associated to it
*
* @param order
* @param itemRequest
* @param priceOrder
* @return
* @throws PricingException
*/
public OrderItem addBundleItemToOrder(Order order, BundleOrderItemRequest itemRequest, boolean priceOrder) throws PricingException;
public PaymentInfo addPaymentToOrder(Order order, PaymentInfo payment);
public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest) throws PricingException;
public FulfillmentGroup addFulfillmentGroupToOrder(FulfillmentGroupRequest fulfillmentGroupRequest, boolean priceOrder) throws PricingException;
public FulfillmentGroup addFulfillmentGroupToOrder(Order order, FulfillmentGroup fulfillmentGroup) throws PricingException;
public FulfillmentGroup addFulfillmentGroupToOrder(Order order, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException;
public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity) throws PricingException;
public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity, boolean priceOrder) throws PricingException;
public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup) throws PricingException;
public FulfillmentGroup addItemToFulfillmentGroup(OrderItem item, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException;
public FulfillmentGroup addItemToFulfillmentGroup(Order order, OrderItem item, FulfillmentGroup fulfillmentGroup, int quantity, boolean priceOrder) throws PricingException;
/**
* Delegates to the fully parametrized method with priceOrder = true.
*
* @param order
* @param item
* @throws ItemNotFoundException
* @throws PricingException
*/
public void updateItemQuantity(Order order, OrderItem item) throws ItemNotFoundException, PricingException;
/**
* Updates the quantity and reprices the order.
* Removes the orderItem if the quantity is updated to 0 (or less).
*
*
* @param order
* @param item
* @param priceOrder
* @throws ItemNotFoundException
* @throws PricingException
*/
public void updateItemQuantity(Order order, OrderItem item, boolean priceOrder) throws ItemNotFoundException, PricingException;
/**
* From the given OrderItemRequestDTO object, this will look through the order's DiscreteOrderItems
* to find the item with the matching orderItemId and update this item's quantity with the value of
* the quantity field in the OrderItemRequestDTO.
*
* @param order
* @param orderItemRequestDTO
* @throws ItemNotFoundException
* @throws PricingException
*/
public void updateItemQuantity(Order order, OrderItemRequestDTO orderItemRequestDTO) throws ItemNotFoundException, PricingException;
public void removeFulfillmentGroupFromOrder(Order order, FulfillmentGroup fulfillmentGroup) throws PricingException;
public void removeFulfillmentGroupFromOrder(Order order, FulfillmentGroup fulfillmentGroup, boolean priceOrder) throws PricingException;
public Order removeItemFromOrder(Order order, OrderItem item) throws PricingException;
public Order removeItemFromOrder(Order order, OrderItem item, boolean priceOrder) throws PricingException;
public void removeNamedOrderForCustomer(String name, Customer customer);
public void removeAllFulfillmentGroupsFromOrder(Order order) throws PricingException;
public void removeAllFulfillmentGroupsFromOrder(Order order, boolean priceOrder) throws PricingException;
public List<PaymentInfo> readPaymentInfosForOrder(Order order);
public Order removeItemFromOrder(Long orderId, Long itemId) throws PricingException;
public Order removeItemFromOrder(Long orderId, Long itemId, boolean priceOrder) throws PricingException;
public FulfillmentGroup createDefaultFulfillmentGroup(Order order, Address address);
/**
* Adds an item to the passed in order.
*
* The orderItemRequest can be sparsely populated.
*
* When priceOrder is false, the system will not reprice the order. This is more performant in
* cases such as bulk adds where the repricing could be done for the last item only.
*
* @see OrderItemRequestDTO
* @param orderItemRequestDTO
* @param priceOrder
* @return
*/
public Order addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder) throws PricingException;
/**
* Not typically used in versions since 1.7.
* See: {@link #addItemToOrder(Long, OrderItemRequestDTO, boolean)}
*
* @param orderId
* @param skuId
* @param productId
* @param categoryId
* @param quantity
* @return
*/
public DiscreteOrderItemRequest createDiscreteOrderItemRequest(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity);
/**
* Adds the passed in name/value pair to the order-item. If the
* attribute already exists, then it is updated with the new value.
*
* If the value passed in is null or empty string and the attribute exists, it is removed
* from the order item.
*
* You may wish to set priceOrder to false if performing set of
* cart operations to avoid the expense of exercising the pricing engine
* until you are ready to finalize pricing after adding the last item.
*
* @param order
* @param item
* @param attributeValues
* @param priceOrder
* @return
*/
public Order addOrUpdateOrderItemAttributes(Order order, OrderItem item, Map<String,String> attributeValues, boolean priceOrder) throws ItemNotFoundException, PricingException;
/**
* Adds the passed in name/value pair to the order-item. If the
* attribute already exists, then it is updated with the new value.
*
* If the value passed in is null and the attribute exists, it is removed
* from the order item.
*
* You may wish to set priceOrder to false if performing set of
* cart operations to avoid the expense of exercising the pricing engine
* until you are ready to finalize pricing after adding the last item.
*
* @param order
* @param item
* @param attributeName
* @param priceOrder
* @return
*/
public Order removeOrderItemAttribute(Order order, OrderItem item, String attributeName, boolean priceOrder) throws ItemNotFoundException, PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param order
* @param itemRequest
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
*
* Due to cart merging and gathering requirements, the item returned is not an
* actual cart item.
*
* NOTE: this will automatically associate the given <b>order</b> to the given <b>itemRequest</b> such that the
* resulting {@link OrderItem} will already have the {@link Order} associated to it
*
* @param order
* @param itemRequest
* @param priceOrder
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, boolean priceOrder) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param orderId
* @param skuId
* @param productId
* @param categoryId
* @param quantity
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param orderId
* @param skuId
* @param productId
* @param categoryId
* @param quantity
* @param orderItemAttributes
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, Map<String,String> orderItemAttributes) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param orderId
* @param skuId
* @param productId
* @param categoryId
* @param quantity
* @param priceOrder
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, boolean priceOrder) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param orderId
* @param skuId
* @param productId
* @param categoryId
* @param quantity
* @param priceOrder
* @param orderItemAttributes
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addSkuToOrder(Long orderId, Long skuId, Long productId, Long categoryId, Integer quantity, boolean priceOrder, Map<String,String> orderItemAttributes) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param order
* @param newOrderItem
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addOrderItemToOrder(Order order, OrderItem newOrderItem) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param order
* @param newOrderItem
* @param priceOrder
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addOrderItemToOrder(Order order, OrderItem newOrderItem, boolean priceOrder) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param order
* @param itemRequest
* @param skuPricingConsiderations
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addDynamicPriceDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, @SuppressWarnings("rawtypes") HashMap skuPricingConsiderations) throws PricingException;
/**
* @deprecated Call addItemToOrder(Long orderId, OrderItemRequestDTO orderItemRequestDTO, boolean priceOrder)
* @param order
* @param itemRequest
* @param skuPricingConsiderations
* @param priceOrder
* @return
* @throws PricingException
*/
@Deprecated
public OrderItem addDynamicPriceDiscreteItemToOrder(Order order, DiscreteOrderItemRequest itemRequest, @SuppressWarnings("rawtypes") HashMap skuPricingConsiderations, boolean priceOrder) throws PricingException;
OrderItem addOrderItemToBundle(Order order, BundleOrderItem bundle, DiscreteOrderItem newOrderItem, boolean priceOrder) throws PricingException;
Order removeItemFromBundle(Order order, BundleOrderItem bundle, OrderItem item, boolean priceOrder) throws PricingException;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_legacy_LegacyOrderService.java |
1,360 | @Repository("blCodeTypeDao")
public class CodeTypeDaoImpl implements CodeTypeDao {
@PersistenceContext(unitName="blPU")
protected EntityManager em;
@Resource(name="blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
public CodeType create() {
return ((CodeType) entityConfiguration.createEntityInstance(CodeType.class.getName()));
}
@SuppressWarnings("unchecked")
public List<CodeType> readAllCodeTypes() {
Query query = em.createNamedQuery("BC_READ_ALL_CODE_TYPES");
return query.getResultList();
}
public void delete(CodeType codeType) {
if (!em.contains(codeType)) {
codeType = (CodeType) em.find(CodeTypeImpl.class, codeType.getId());
}
em.remove(codeType);
}
public CodeType readCodeTypeById(Long codeTypeId) {
return (CodeType) em.find(entityConfiguration.lookupEntityClass(CodeType.class.getName()), codeTypeId);
}
@SuppressWarnings("unchecked")
public List<CodeType> readCodeTypeByKey(String key) {
Query query = em.createNamedQuery("BC_READ_CODE_TYPE_BY_KEY");
query.setParameter("key", key);
List<CodeType> result = query.getResultList();
return result;
}
public CodeType save(CodeType codeType) {
if(codeType.getId()==null) {
em.persist(codeType);
}else {
codeType = em.merge(codeType);
}
return codeType;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_util_dao_CodeTypeDaoImpl.java |
867 | public class GetAndSetOperation extends AtomicReferenceBackupAwareOperation {
private Data newValue;
private Data returnValue;
public GetAndSetOperation() {
}
public GetAndSetOperation(String name, Data newValue) {
super(name);
this.newValue = newValue;
}
@Override
public void run() throws Exception {
ReferenceWrapper reference = getReference();
returnValue = reference.getAndSet(newValue);
}
@Override
public Object getResponse() {
return returnValue;
}
@Override
public int getId() {
return AtomicReferenceDataSerializerHook.GET_AND_SET;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(newValue);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
newValue = in.readObject();
}
@Override
public Operation getBackupOperation() {
return new SetBackupOperation(name, newValue);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_GetAndSetOperation.java |
443 | new Thread(){
public void run() {
for (int i=0; i<1000; i++){
q.offer("item"+i);
latch.countDown();
latch1.countDown();
}
}
}.start(); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_queue_ClientQueuePerformanceTest.java |
3,082 | static class DeleteByQuery {
private final Query query;
private final BytesReference source;
private final String[] filteringAliases;
private final Filter aliasFilter;
private final String[] types;
private final Filter parentFilter;
private Operation.Origin origin = Operation.Origin.PRIMARY;
private long startTime;
private long endTime;
public DeleteByQuery(Query query, BytesReference source, @Nullable String[] filteringAliases, @Nullable Filter aliasFilter, Filter parentFilter, String... types) {
this.query = query;
this.source = source;
this.types = types;
this.filteringAliases = filteringAliases;
this.aliasFilter = aliasFilter;
this.parentFilter = parentFilter;
}
public Query query() {
return this.query;
}
public BytesReference source() {
return this.source;
}
public String[] types() {
return this.types;
}
public String[] filteringAliases() {
return filteringAliases;
}
public Filter aliasFilter() {
return aliasFilter;
}
public boolean nested() {
return parentFilter != null;
}
public Filter parentFilter() {
return parentFilter;
}
public DeleteByQuery origin(Operation.Origin origin) {
this.origin = origin;
return this;
}
public Operation.Origin origin() {
return this.origin;
}
public DeleteByQuery startTime(long startTime) {
this.startTime = startTime;
return this;
}
/**
* Returns operation start time in nanoseconds.
*/
public long startTime() {
return this.startTime;
}
public DeleteByQuery endTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* Returns operation end time in nanoseconds.
*/
public long endTime() {
return this.endTime;
}
} | 0true
| src_main_java_org_elasticsearch_index_engine_Engine.java |
1,323 | assertThat(awaitBusy(new Predicate<Object>() {
public boolean apply(Object obj) {
boolean success = true;
for(Client client : cluster()) {
ClusterState state = client.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState();
success &= state.blocks().hasGlobalBlock(Discovery.NO_MASTER_BLOCK);
if (logger.isDebugEnabled()) {
logger.debug("Checking for NO_MASTER_BLOCL on client: {} NO_MASTER_BLOCK: [{}]", client, state.blocks().hasGlobalBlock(Discovery.NO_MASTER_BLOCK));
}
}
return success;
}
}, 20, TimeUnit.SECONDS), equalTo(true)); | 0true
| src_test_java_org_elasticsearch_cluster_MinimumMasterNodesTests.java |
3,296 | final class BinaryDVNumericAtomicFieldData extends AbstractAtomicNumericFieldData {
private final AtomicReader reader;
private final BinaryDocValues values;
private final NumericType numericType;
BinaryDVNumericAtomicFieldData(AtomicReader reader, BinaryDocValues values, NumericType numericType) {
super(numericType.isFloatingPoint());
this.reader = reader;
this.values = values == null ? BinaryDocValues.EMPTY : values;
this.numericType = numericType;
}
@Override
public LongValues getLongValues() {
if (numericType.isFloatingPoint()) {
return LongValues.asLongValues(getDoubleValues());
}
return new LongValues(true) {
final BytesRef bytes = new BytesRef();
final ByteArrayDataInput in = new ByteArrayDataInput();
long[] longs = new long[8];
int i = Integer.MAX_VALUE;
int valueCount = 0;
@Override
public int setDocument(int docId) {
values.get(docId, bytes);
in.reset(bytes.bytes, bytes.offset, bytes.length);
if (!in.eof()) {
// first value uses vLong on top of zig-zag encoding, then deltas are encoded using vLong
long previousValue = longs[0] = ByteUtils.zigZagDecode(ByteUtils.readVLong(in));
valueCount = 1;
while (!in.eof()) {
longs = ArrayUtil.grow(longs, valueCount + 1);
previousValue = longs[valueCount++] = previousValue + ByteUtils.readVLong(in);
}
} else {
valueCount = 0;
}
i = 0;
return valueCount;
}
@Override
public long nextValue() {
assert i < valueCount;
return longs[i++];
}
};
}
@Override
public DoubleValues getDoubleValues() {
if (!numericType.isFloatingPoint()) {
return DoubleValues.asDoubleValues(getLongValues());
}
switch (numericType) {
case FLOAT:
return new DoubleValues(true) {
final BytesRef bytes = new BytesRef();
int i = Integer.MAX_VALUE;
int valueCount = 0;
@Override
public int setDocument(int docId) {
values.get(docId, bytes);
assert bytes.length % 4 == 0;
i = 0;
return valueCount = bytes.length / 4;
}
@Override
public double nextValue() {
assert i < valueCount;
return ByteUtils.readFloatLE(bytes.bytes, bytes.offset + i++ * 4);
}
};
case DOUBLE:
return new DoubleValues(true) {
final BytesRef bytes = new BytesRef();
int i = Integer.MAX_VALUE;
int valueCount = 0;
@Override
public int setDocument(int docId) {
values.get(docId, bytes);
assert bytes.length % 8 == 0;
i = 0;
return valueCount = bytes.length / 8;
}
@Override
public double nextValue() {
assert i < valueCount;
return ByteUtils.readDoubleLE(bytes.bytes, bytes.offset + i++ * 8);
}
};
default:
throw new AssertionError();
}
}
@Override
public boolean isMultiValued() {
return true; // no way to know
}
@Override
public int getNumDocs() {
return reader.maxDoc();
}
@Override
public long getNumberUniqueValues() {
return Long.MAX_VALUE; // no clue
}
@Override
public long getMemorySizeInBytes() {
return -1; // Lucene doesn't expose it
}
@Override
public void close() {
// no-op
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_BinaryDVNumericAtomicFieldData.java |
2,272 | public class TrieNode<T> {
private transient String key;
private transient T value;
private boolean isWildcard;
private final String wildcard;
private transient String namedWildcard;
private ImmutableMap<String, TrieNode<T>> children;
private final TrieNode parent;
public TrieNode(String key, T value, TrieNode parent, String wildcard) {
this.key = key;
this.wildcard = wildcard;
this.isWildcard = (key.equals(wildcard));
this.parent = parent;
this.value = value;
this.children = ImmutableMap.of();
if (isNamedWildcard(key)) {
namedWildcard = key.substring(key.indexOf('{') + 1, key.indexOf('}'));
} else {
namedWildcard = null;
}
}
public void updateKeyWithNamedWildcard(String key) {
this.key = key;
namedWildcard = key.substring(key.indexOf('{') + 1, key.indexOf('}'));
}
public boolean isWildcard() {
return isWildcard;
}
public synchronized void addChild(TrieNode<T> child) {
children = newMapBuilder(children).put(child.key, child).immutableMap();
}
public TrieNode getChild(String key) {
return children.get(key);
}
public synchronized void insert(String[] path, int index, T value) {
if (index >= path.length)
return;
String token = path[index];
String key = token;
if (isNamedWildcard(token)) {
key = wildcard;
}
TrieNode<T> node = children.get(key);
if (node == null) {
if (index == (path.length - 1)) {
node = new TrieNode<T>(token, value, this, wildcard);
} else {
node = new TrieNode<T>(token, null, this, wildcard);
}
children = newMapBuilder(children).put(key, node).immutableMap();
} else {
if (isNamedWildcard(token)) {
node.updateKeyWithNamedWildcard(token);
}
// in case the target(last) node already exist but without a value
// than the value should be updated.
if (index == (path.length - 1)) {
assert (node.value == null || node.value == value);
if (node.value == null) {
node.value = value;
}
}
}
node.insert(path, index + 1, value);
}
private boolean isNamedWildcard(String key) {
return key.indexOf('{') != -1 && key.indexOf('}') != -1;
}
private String namedWildcard() {
return namedWildcard;
}
private boolean isNamedWildcard() {
return namedWildcard != null;
}
public T retrieve(String[] path, int index, Map<String, String> params) {
if (index >= path.length)
return null;
String token = path[index];
TrieNode<T> node = children.get(token);
boolean usedWildcard;
if (node == null) {
node = children.get(wildcard);
if (node == null) {
return null;
}
usedWildcard = true;
} else {
usedWildcard = token.equals(wildcard);
}
put(params, node, token);
if (index == (path.length - 1)) {
return node.value;
}
T res = node.retrieve(path, index + 1, params);
if (res == null && !usedWildcard) {
node = children.get(wildcard);
if (node != null) {
put(params, node, token);
res = node.retrieve(path, index + 1, params);
}
}
return res;
}
private void put(Map<String, String> params, TrieNode<T> node, String value) {
if (params != null && node.isNamedWildcard()) {
params.put(node.namedWildcard(), decoder.decode(value));
}
}
} | 0true
| src_main_java_org_elasticsearch_common_path_PathTrie.java |
347 | public class ConfigurationOnlyState {
private static final ThreadLocal<ConfigurationOnlyState> CONFIGURATIONONLYSTATE = ThreadLocalManager.createThreadLocal(ConfigurationOnlyState.class);
public static ConfigurationOnlyState getState() {
return CONFIGURATIONONLYSTATE.get();
}
public static void setState(ConfigurationOnlyState state) {
CONFIGURATIONONLYSTATE.set(state);
}
protected boolean isConfigurationOnly;
public boolean isConfigurationOnly() {
return isConfigurationOnly;
}
public void setConfigurationOnly(boolean configurationOnly) {
isConfigurationOnly = configurationOnly;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_extensibility_jpa_ConfigurationOnlyState.java |
446 | public interface KeyColumnValueStoreManager extends StoreManager {
/**
* Opens an ordered database by the given name. If the database does not exist, it is
* created. If it has already been opened, the existing handle is returned.
*
* @param name Name of database
* @return Database Handle
* @throws com.thinkaurelius.titan.diskstorage.BackendException
*
*/
public KeyColumnValueStore openDatabase(String name) throws BackendException;
/**
* Executes multiple mutations at once. For each store (identified by a string name) there is a map of (key,mutation) pairs
* that specifies all the mutations to execute against the particular store for that key.
*
* This is an optional operation. Check {@link #getFeatures()} if it is supported by a particular implementation.
*
* @param mutations
* @param txh
* @throws com.thinkaurelius.titan.diskstorage.BackendException
*/
public void mutateMany(Map<String, Map<StaticBuffer, KCVMutation>> mutations, StoreTransaction txh) throws BackendException;
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_KeyColumnValueStoreManager.java |
601 | @Component("blCurrencyResolver")
public class BroadleafCurrencyResolverImpl implements BroadleafCurrencyResolver {
private final Log LOG = LogFactory.getLog(BroadleafCurrencyResolverImpl.class);
/**
* Parameter/Attribute name for the current currency code
*/
public static String CURRENCY_CODE_PARAM = "blCurrencyCode";
/**
* Parameter/Attribute name for the current currency
*/
public static String CURRENCY_VAR = "blCurrency";
@Resource(name = "blCurrencyService")
private BroadleafCurrencyService broadleafCurrencyService;
/**
* Responsible for returning the currency to use for the current request.
*/
@Override
public BroadleafCurrency resolveCurrency(HttpServletRequest request) {
return resolveCurrency(new ServletWebRequest(request));
}
@Override
public BroadleafCurrency resolveCurrency(WebRequest request) {
BroadleafCurrency currency = null;
// 1) Check request for currency
currency = (BroadleafCurrency) request.getAttribute(CURRENCY_VAR, WebRequest.SCOPE_REQUEST);
// 2) Check for a request parameter
if (currency == null && BLCRequestUtils.getURLorHeaderParameter(request, CURRENCY_CODE_PARAM) != null) {
String currencyCode = BLCRequestUtils.getURLorHeaderParameter(request, CURRENCY_CODE_PARAM);
currency = broadleafCurrencyService.findCurrencyByCode(currencyCode);
if (LOG.isTraceEnabled()) {
LOG.trace("Attempt to find currency by param " + currencyCode + " resulted in " + currency);
}
}
// 3) Check session for currency
if (currency == null && BLCRequestUtils.isOKtoUseSession(request)) {
currency = (BroadleafCurrency) request.getAttribute(CURRENCY_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
}
// 4) Check locale for currency
if (currency == null) {
Locale locale = (Locale) request.getAttribute(BroadleafLocaleResolverImpl.LOCALE_VAR, WebRequest.SCOPE_REQUEST);
if (locale != null) {
currency = locale.getDefaultCurrency();
}
}
// 5) Check default currency from DB
if (currency == null) {
currency = broadleafCurrencyService.findDefaultBroadleafCurrency();
}
if (BLCRequestUtils.isOKtoUseSession(request)) {
request.setAttribute(CURRENCY_VAR, currency, WebRequest.SCOPE_GLOBAL_SESSION);
}
return currency;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_web_BroadleafCurrencyResolverImpl.java |
380 | static class MyEntryListener implements EntryListener {
public AtomicInteger add = new AtomicInteger(0);
public void entryAdded(EntryEvent event) {
add.incrementAndGet();
}
public void entryRemoved(EntryEvent event) {
}
public void entryUpdated(EntryEvent event) {
}
public void entryEvicted(EntryEvent event) {
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapListenerStressTest.java |
1,035 | public class OCommandExecutorSQLDelete extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest,
OCommandResultListener {
public static final String NAME = "DELETE FROM";
public static final String KEYWORD_DELETE = "DELETE";
private static final String VALUE_NOT_FOUND = "_not_found_";
private OSQLQuery<ODocument> query;
private String indexName = null;
private int recordCount = 0;
private OSQLFilter compiledFilter;
public OCommandExecutorSQLDelete() {
}
@SuppressWarnings("unchecked")
public OCommandExecutorSQLDelete parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
init((OCommandRequestText) iRequest);
query = null;
recordCount = 0;
parserRequiredKeyword(OCommandExecutorSQLDelete.KEYWORD_DELETE);
parserRequiredKeyword(OCommandExecutorSQLDelete.KEYWORD_FROM);
String subjectName = parserRequiredWord(false, "Syntax error", " =><,\r\n");
if (subjectName == null)
throwSyntaxErrorException("Invalid subject name. Expected cluster, class, index or sub-query");
if (OStringParser.startsWithIgnoreCase(subjectName, OCommandExecutorSQLAbstract.INDEX_PREFIX)) {
// INDEX
indexName = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_PREFIX.length());
if (!parserIsEnded()) {
parserNextWord(true);
if (parserGetLastWord().equalsIgnoreCase(KEYWORD_WHERE))
compiledFilter = OSQLEngine.getInstance().parseCondition(parserText.substring(parserGetCurrentPosition()), getContext(),
KEYWORD_WHERE);
} else
parserSetCurrentPosition(-1);
} else if (subjectName.startsWith("(")) {
subjectName = subjectName.trim();
query = database.command(new OSQLAsynchQuery<ODocument>(subjectName.substring(1, subjectName.length() - 1), this));
} else {
final String condition = parserGetCurrentPosition() > -1 ? " " + parserText.substring(parserGetCurrentPosition()) : "";
query = database.command(new OSQLAsynchQuery<ODocument>("select from " + subjectName + condition, this));
}
return this;
}
public Object execute(final Map<Object, Object> iArgs) {
if (query == null && indexName == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
if (query != null) {
// AGAINST CLUSTERS AND CLASSES
query.execute(iArgs);
return recordCount;
} else {
// AGAINST INDEXES
if (compiledFilter != null)
compiledFilter.bindParameters(iArgs);
final OIndex<?> index = getDatabase().getMetadata().getIndexManager().getIndex(indexName);
if (index == null)
throw new OCommandExecutionException("Target index '" + indexName + "' not found");
Object key = null;
Object value = VALUE_NOT_FOUND;
if (compiledFilter == null || compiledFilter.getRootCondition() == null) {
final long total = index.getSize();
index.clear();
return total;
} else {
if (KEYWORD_KEY.equalsIgnoreCase(compiledFilter.getRootCondition().getLeft().toString()))
// FOUND KEY ONLY
key = getIndexKey(index.getDefinition(), compiledFilter.getRootCondition().getRight());
else if (KEYWORD_RID.equalsIgnoreCase(compiledFilter.getRootCondition().getLeft().toString())) {
// BY RID
value = OSQLHelper.getValue(compiledFilter.getRootCondition().getRight());
} else if (compiledFilter.getRootCondition().getLeft() instanceof OSQLFilterCondition) {
// KEY AND VALUE
final OSQLFilterCondition leftCondition = (OSQLFilterCondition) compiledFilter.getRootCondition().getLeft();
if (KEYWORD_KEY.equalsIgnoreCase(leftCondition.getLeft().toString()))
key = getIndexKey(index.getDefinition(), leftCondition.getRight());
final OSQLFilterCondition rightCondition = (OSQLFilterCondition) compiledFilter.getRootCondition().getRight();
if (KEYWORD_RID.equalsIgnoreCase(rightCondition.getLeft().toString()))
value = OSQLHelper.getValue(rightCondition.getRight());
}
final boolean result;
if (value != VALUE_NOT_FOUND) {
assert key != null;
result = index.remove(key, (OIdentifiable) value);
} else
result = index.remove(key);
return result ? 1 : 0;
}
}
}
/**
* Delete the current record.
*/
public boolean result(final Object iRecord) {
final ORecordAbstract<?> record = (ORecordAbstract<?>) iRecord;
if (record.getIdentity().isValid()) {
// RESET VERSION TO DISABLE MVCC AVOIDING THE CONCURRENT EXCEPTION IF LOCAL CACHE IS NOT UPDATED
record.getRecordVersion().disable();
record.delete();
recordCount++;
return true;
}
return false;
}
public boolean isReplicated() {
return indexName != null;
}
public String getSyntax() {
return "DELETE FROM <Class>|RID|cluster:<cluster> [WHERE <condition>*]";
}
private Object getIndexKey(final OIndexDefinition indexDefinition, Object value) {
if (indexDefinition instanceof OCompositeIndexDefinition) {
if (value instanceof List) {
final List<?> values = (List<?>) value;
List<Object> keyParams = new ArrayList<Object>(values.size());
for (Object o : values) {
keyParams.add(OSQLHelper.getValue(o));
}
return indexDefinition.createValue(keyParams);
} else {
value = OSQLHelper.getValue(value);
if (value instanceof OCompositeKey) {
return value;
} else {
return indexDefinition.createValue(value);
}
}
} else {
return OSQLHelper.getValue(value);
}
}
@Override
public void end() {
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLDelete.java |
6 | public class HBaseStatus {
private static final Logger log =
LoggerFactory.getLogger(HBaseStatus.class);
private final File file;
private final String version;
private HBaseStatus(File file, String version) {
Preconditions.checkNotNull(file);
Preconditions.checkNotNull(version);
this.file = file;
this.version = version;
}
public String getVersion() {
return version;
}
public File getFile() {
return file;
}
public String getScriptDir() {
return HBaseStorageSetup.getScriptDirForHBaseVersion(version);
}
public String getConfDir() {
return HBaseStorageSetup.getConfDirForHBaseVersion(version);
}
public static HBaseStatus read(String path) {
File pid = new File(path);
if (!pid.exists()) {
log.info("HBase pidfile {} does not exist", path);
return null;
}
BufferedReader pidReader = null;
try {
pidReader = new BufferedReader(new FileReader(pid));
HBaseStatus s = parsePidFile(pid, pidReader);
log.info("Read HBase status from {}", path);
return s;
} catch (HBasePidfileParseException e) {
log.warn("Assuming HBase is not running", e);
} catch (IOException e) {
log.warn("Assuming HBase is not running", e);
} finally {
IOUtils.closeQuietly(pidReader);
}
return null;
}
public static HBaseStatus write(String path, String hbaseVersion) {
File f = new File(path);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
fos.write(String.format("%s", hbaseVersion).getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(fos);
}
return new HBaseStatus(f, hbaseVersion);
}
private static HBaseStatus parsePidFile(File f, BufferedReader br) throws HBasePidfileParseException, IOException {
String l = br.readLine();
if (null == l || "".equals(l.trim())) {
throw new HBasePidfileParseException("Empty HBase statusfile " + f);
}
HBaseStatus stat = new HBaseStatus(f, l.trim());
return stat;
}
private static class HBasePidfileParseException extends Exception {
private static final long serialVersionUID = 1L;
public HBasePidfileParseException(String message) {
super(message);
}
}
} | 0true
| titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStatus.java |
1,152 | public class NodesStressTest {
private Node[] nodes;
private int numberOfNodes = 2;
private Client[] clients;
private AtomicLong idGenerator = new AtomicLong();
private int fieldNumLimit = 50;
private long searcherIterations = 10;
private Searcher[] searcherThreads = new Searcher[1];
private long indexIterations = 10;
private Indexer[] indexThreads = new Indexer[1];
private TimeValue sleepAfterDone = TimeValue.timeValueMillis(0);
private TimeValue sleepBeforeClose = TimeValue.timeValueMillis(0);
private CountDownLatch latch;
private CyclicBarrier barrier1;
private CyclicBarrier barrier2;
public NodesStressTest() {
}
public NodesStressTest numberOfNodes(int numberOfNodes) {
this.numberOfNodes = numberOfNodes;
return this;
}
public NodesStressTest fieldNumLimit(int fieldNumLimit) {
this.fieldNumLimit = fieldNumLimit;
return this;
}
public NodesStressTest searchIterations(int searchIterations) {
this.searcherIterations = searchIterations;
return this;
}
public NodesStressTest searcherThreads(int numberOfSearcherThreads) {
searcherThreads = new Searcher[numberOfSearcherThreads];
return this;
}
public NodesStressTest indexIterations(long indexIterations) {
this.indexIterations = indexIterations;
return this;
}
public NodesStressTest indexThreads(int numberOfWriterThreads) {
indexThreads = new Indexer[numberOfWriterThreads];
return this;
}
public NodesStressTest sleepAfterDone(TimeValue time) {
this.sleepAfterDone = time;
return this;
}
public NodesStressTest sleepBeforeClose(TimeValue time) {
this.sleepBeforeClose = time;
return this;
}
public NodesStressTest build(Settings settings) throws Exception {
settings = settingsBuilder()
// .put("index.refresh_interval", 1, TimeUnit.SECONDS)
.put(SETTING_NUMBER_OF_SHARDS, 5)
.put(SETTING_NUMBER_OF_REPLICAS, 1)
.put(settings)
.build();
nodes = new Node[numberOfNodes];
clients = new Client[numberOfNodes];
for (int i = 0; i < numberOfNodes; i++) {
nodes[i] = nodeBuilder().settings(settingsBuilder().put(settings).put("name", "node" + i)).node();
clients[i] = nodes[i].client();
}
for (int i = 0; i < searcherThreads.length; i++) {
searcherThreads[i] = new Searcher(i);
}
for (int i = 0; i < indexThreads.length; i++) {
indexThreads[i] = new Indexer(i);
}
latch = new CountDownLatch(1);
barrier1 = new CyclicBarrier(2);
barrier2 = new CyclicBarrier(2);
// warmup
StopWatch stopWatch = new StopWatch().start();
Indexer warmup = new Indexer(-1).max(10000);
warmup.start();
barrier1.await();
barrier2.await();
latch.await();
stopWatch.stop();
System.out.println("Done Warmup, took [" + stopWatch.totalTime() + "]");
latch = new CountDownLatch(searcherThreads.length + indexThreads.length);
barrier1 = new CyclicBarrier(searcherThreads.length + indexThreads.length + 1);
barrier2 = new CyclicBarrier(searcherThreads.length + indexThreads.length + 1);
return this;
}
public void start() throws Exception {
for (Thread t : searcherThreads) {
t.start();
}
for (Thread t : indexThreads) {
t.start();
}
barrier1.await();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
barrier2.await();
latch.await();
stopWatch.stop();
System.out.println("Done, took [" + stopWatch.totalTime() + "]");
System.out.println("Sleeping before close: " + sleepBeforeClose);
Thread.sleep(sleepBeforeClose.millis());
for (Client client : clients) {
client.close();
}
for (Node node : nodes) {
node.close();
}
System.out.println("Sleeping before exit: " + sleepBeforeClose);
Thread.sleep(sleepAfterDone.millis());
}
class Searcher extends Thread {
final int id;
long counter = 0;
long max = searcherIterations;
Searcher(int id) {
super("Searcher" + id);
this.id = id;
}
@Override
public void run() {
try {
barrier1.await();
barrier2.await();
for (; counter < max; counter++) {
Client client = client(counter);
QueryBuilder query = termQuery("num", counter % fieldNumLimit);
query = constantScoreQuery(queryFilter(query));
SearchResponse search = client.search(searchRequest()
.source(searchSource().query(query)))
.actionGet();
// System.out.println("Got search response, hits [" + search.hits().totalHits() + "]");
}
} catch (Exception e) {
System.err.println("Failed to search:");
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
class Indexer extends Thread {
final int id;
long counter = 0;
long max = indexIterations;
Indexer(int id) {
super("Indexer" + id);
this.id = id;
}
Indexer max(int max) {
this.max = max;
return this;
}
@Override
public void run() {
try {
barrier1.await();
barrier2.await();
for (; counter < max; counter++) {
Client client = client(counter);
long id = idGenerator.incrementAndGet();
client.index(Requests.indexRequest().index("test").type("type1").id(Long.toString(id))
.source(XContentFactory.jsonBuilder().startObject()
.field("num", id % fieldNumLimit)
.endObject()))
.actionGet();
}
System.out.println("Indexer [" + id + "]: Done");
} catch (Exception e) {
System.err.println("Failed to index:");
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
private Client client(long i) {
return clients[((int) (i % clients.length))];
}
public static void main(String[] args) throws Exception {
NodesStressTest test = new NodesStressTest()
.numberOfNodes(2)
.indexThreads(5)
.indexIterations(10 * 1000)
.searcherThreads(5)
.searchIterations(10 * 1000)
.sleepBeforeClose(TimeValue.timeValueMinutes(10))
.sleepAfterDone(TimeValue.timeValueMinutes(10))
.build(EMPTY_SETTINGS);
test.start();
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_stress_NodesStressTest.java |
456 | public class OSBTreeIndexRIDContainerSerializationPerformanceTest {
public static final int CYCLE_COUNT = 20000;
private static final int WARMUP_CYCLE_COUNT = 30000;
public static final ODirectMemoryPointer POINTER = new ODirectMemoryPointer(2048l);
public static void main(String[] args) throws InterruptedException {
ODatabaseDocumentTx db = new ODatabaseDocumentTx("plocal:target/testdb/OSBTreeRIDSetTest");
if (db.exists()) {
db.open("admin", "admin");
db.drop();
}
db.create();
ODatabaseRecordThreadLocal.INSTANCE.set(db);
Set<OIdentifiable> data = new HashSet<OIdentifiable>(8);
data.add(new ORecordId("#77:12"));
data.add(new ORecordId("#77:13"));
data.add(new ORecordId("#77:14"));
data.add(new ORecordId("#77:15"));
data.add(new ORecordId("#77:16"));
for (int i = 0; i < WARMUP_CYCLE_COUNT; i++) {
cycle(data);
}
System.gc();
Thread.sleep(1000);
long time = System.currentTimeMillis();
for (int i = 0; i < CYCLE_COUNT; i++) {
cycle(data);
}
time = System.currentTimeMillis() - time;
System.out.println("Time: " + time + "ms.");
System.out.println("Throughput: " + (((double) CYCLE_COUNT) * 1000 / time) + " rec/sec.");
}
private static void cycle(Set<OIdentifiable> data) {
final OIndexRIDContainer valueContainer = new OIndexRIDContainer("ValueContainerPerformanceTest");
valueContainer.addAll(data);
OStreamSerializerSBTreeIndexRIDContainer.INSTANCE.serializeInDirectMemory(valueContainer, POINTER, 0l);
}
} | 0true
| core_src_test_java_com_orientechnologies_orient_core_db_record_ridset_sbtree_OSBTreeIndexRIDContainerSerializationPerformanceTest.java |
2,032 | private static class RecordingBinder implements Binder, PrivateBinder {
private final Stage stage;
private final Set<Module> modules;
private final List<Element> elements;
private final Object source;
private final SourceProvider sourceProvider;
/**
* The binder where exposed bindings will be created
*/
private final RecordingBinder parent;
private final PrivateElementsImpl privateElements;
private RecordingBinder(Stage stage) {
this.stage = stage;
this.modules = Sets.newHashSet();
this.elements = Lists.newArrayList();
this.source = null;
this.sourceProvider = new SourceProvider().plusSkippedClasses(
Elements.class, RecordingBinder.class, AbstractModule.class,
ConstantBindingBuilderImpl.class, AbstractBindingBuilder.class, BindingBuilder.class);
this.parent = null;
this.privateElements = null;
}
/**
* Creates a recording binder that's backed by {@code prototype}.
*/
private RecordingBinder(
RecordingBinder prototype, Object source, SourceProvider sourceProvider) {
checkArgument(source == null ^ sourceProvider == null);
this.stage = prototype.stage;
this.modules = prototype.modules;
this.elements = prototype.elements;
this.source = source;
this.sourceProvider = sourceProvider;
this.parent = prototype.parent;
this.privateElements = prototype.privateElements;
}
/**
* Creates a private recording binder.
*/
private RecordingBinder(RecordingBinder parent, PrivateElementsImpl privateElements) {
this.stage = parent.stage;
this.modules = Sets.newHashSet();
this.elements = privateElements.getElementsMutable();
this.source = parent.source;
this.sourceProvider = parent.sourceProvider;
this.parent = parent;
this.privateElements = privateElements;
}
public void bindScope(Class<? extends Annotation> annotationType, Scope scope) {
elements.add(new ScopeBinding(getSource(), annotationType, scope));
}
@SuppressWarnings("unchecked") // it is safe to use the type literal for the raw type
public void requestInjection(Object instance) {
requestInjection((TypeLiteral) TypeLiteral.get(instance.getClass()), instance);
}
public <T> void requestInjection(TypeLiteral<T> type, T instance) {
elements.add(new InjectionRequest<T>(getSource(), type, instance));
}
public <T> MembersInjector<T> getMembersInjector(final TypeLiteral<T> typeLiteral) {
final MembersInjectorLookup<T> element
= new MembersInjectorLookup<T>(getSource(), typeLiteral);
elements.add(element);
return element.getMembersInjector();
}
public <T> MembersInjector<T> getMembersInjector(Class<T> type) {
return getMembersInjector(TypeLiteral.get(type));
}
public void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener) {
elements.add(new TypeListenerBinding(getSource(), listener, typeMatcher));
}
public void requestStaticInjection(Class<?>... types) {
for (Class<?> type : types) {
elements.add(new StaticInjectionRequest(getSource(), type));
}
}
public void install(Module module) {
if (modules.add(module)) {
Binder binder = this;
if (module instanceof PrivateModule) {
binder = binder.newPrivateBinder();
}
try {
module.configure(binder);
} catch (RuntimeException e) {
Collection<Message> messages = Errors.getMessagesFromThrowable(e);
if (!messages.isEmpty()) {
elements.addAll(messages);
} else {
addError(e);
}
}
binder.install(ProviderMethodsModule.forModule(module));
}
}
public Stage currentStage() {
return stage;
}
public void addError(String message, Object... arguments) {
elements.add(new Message(getSource(), Errors.format(message, arguments)));
}
public void addError(Throwable t) {
String message = "An exception was caught and reported. Message: " + t.getMessage();
elements.add(new Message(ImmutableList.of(getSource()), message, t));
}
public void addError(Message message) {
elements.add(message);
}
public <T> AnnotatedBindingBuilder<T> bind(Key<T> key) {
return new BindingBuilder<T>(this, elements, getSource(), key);
}
public <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) {
return bind(Key.get(typeLiteral));
}
public <T> AnnotatedBindingBuilder<T> bind(Class<T> type) {
return bind(Key.get(type));
}
public AnnotatedConstantBindingBuilder bindConstant() {
return new ConstantBindingBuilderImpl<Void>(this, elements, getSource());
}
public <T> Provider<T> getProvider(final Key<T> key) {
final ProviderLookup<T> element = new ProviderLookup<T>(getSource(), key);
elements.add(element);
return element.getProvider();
}
public <T> Provider<T> getProvider(Class<T> type) {
return getProvider(Key.get(type));
}
public void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeConverter converter) {
elements.add(new TypeConverterBinding(getSource(), typeMatcher, converter));
}
public RecordingBinder withSource(final Object source) {
return new RecordingBinder(this, source, null);
}
public RecordingBinder skipSources(Class... classesToSkip) {
// if a source is specified explicitly, we don't need to skip sources
if (source != null) {
return this;
}
SourceProvider newSourceProvider = sourceProvider.plusSkippedClasses(classesToSkip);
return new RecordingBinder(this, null, newSourceProvider);
}
public PrivateBinder newPrivateBinder() {
PrivateElementsImpl privateElements = new PrivateElementsImpl(getSource());
elements.add(privateElements);
return new RecordingBinder(this, privateElements);
}
public void expose(Key<?> key) {
exposeInternal(key);
}
public AnnotatedElementBuilder expose(Class<?> type) {
return exposeInternal(Key.get(type));
}
public AnnotatedElementBuilder expose(TypeLiteral<?> type) {
return exposeInternal(Key.get(type));
}
private <T> AnnotatedElementBuilder exposeInternal(Key<T> key) {
if (privateElements == null) {
addError("Cannot expose %s on a standard binder. "
+ "Exposed bindings are only applicable to private binders.", key);
return new AnnotatedElementBuilder() {
public void annotatedWith(Class<? extends Annotation> annotationType) {
}
public void annotatedWith(Annotation annotation) {
}
};
}
ExposureBuilder<T> builder = new ExposureBuilder<T>(this, getSource(), key);
privateElements.addExposureBuilder(builder);
return builder;
}
private static ESLogger logger = Loggers.getLogger(Bootstrap.class);
protected Object getSource() {
Object ret;
if (logger.isDebugEnabled()) {
ret = sourceProvider != null
? sourceProvider.get()
: source;
} else {
ret = source;
}
return ret == null ? "_unknown_" : ret;
}
@Override
public String toString() {
return "Binder";
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_spi_Elements.java |
203 | public abstract class ClientAbstractSelectionHandler implements SelectionHandler, Runnable {
protected final ILogger logger;
protected final SocketChannelWrapper socketChannel;
protected final ClientConnection connection;
protected final ClientConnectionManagerImpl connectionManager;
protected final IOSelector ioSelector;
private SelectionKey sk;
public ClientAbstractSelectionHandler(final ClientConnection connection, IOSelector ioSelector) {
this.connection = connection;
this.ioSelector = ioSelector;
this.socketChannel = connection.getSocketChannelWrapper();
this.connectionManager = connection.getConnectionManager();
this.logger = Logger.getLogger(getClass().getName());
}
protected void shutdown() {
}
final void handleSocketException(Throwable e) {
if (sk != null) {
sk.cancel();
}
connection.close(e);
StringBuilder sb = new StringBuilder();
sb.append(Thread.currentThread().getName());
sb.append(" Closing socket to endpoint ");
sb.append(connection.getEndPoint());
sb.append(", Cause:").append(e);
logger.warning(sb.toString());
}
final void registerOp(final int operation) {
try {
if (!connection.live()) {
return;
}
if (sk == null) {
sk = socketChannel.keyFor(ioSelector.getSelector());
}
if (sk == null) {
sk = socketChannel.register(ioSelector.getSelector(), operation, this);
} else {
sk.interestOps(sk.interestOps() | operation);
if (sk.attachment() != this) {
sk.attach(this);
}
}
} catch (Throwable e) {
handleSocketException(e);
}
}
public void register() {
ioSelector.addTask(this);
ioSelector.wakeup();
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientAbstractSelectionHandler.java |
391 | public class IndexMutation extends Mutation<IndexEntry,IndexEntry> {
private final boolean isNew;
private boolean isDeleted;
public IndexMutation(List<IndexEntry> additions, List<IndexEntry> deletions, boolean isNew, boolean isDeleted) {
super(additions, deletions);
Preconditions.checkArgument(!(isNew && isDeleted),"Invalid status");
this.isNew = isNew;
this.isDeleted = isDeleted;
}
public IndexMutation(boolean isNew, boolean isDeleted) {
super();
Preconditions.checkArgument(!(isNew && isDeleted),"Invalid status");
this.isNew = isNew;
this.isDeleted = isDeleted;
}
public void merge(IndexMutation m) {
Preconditions.checkArgument(isNew == m.isNew,"Incompatible new status");
Preconditions.checkArgument(isDeleted == m.isDeleted,"Incompatible delete status");
super.merge(m);
}
public boolean isNew() {
return isNew;
}
public boolean isDeleted() {
return isDeleted;
}
public void resetDelete() {
isDeleted=false;
}
public static final Function<IndexEntry,String> ENTRY2FIELD_FCT = new Function<IndexEntry, String>() {
@Nullable
@Override
public String apply(@Nullable IndexEntry indexEntry) {
return indexEntry.field;
}
};
@Override
public void consolidate() {
super.consolidate(ENTRY2FIELD_FCT,ENTRY2FIELD_FCT);
}
@Override
public boolean isConsolidated() {
return super.isConsolidated(ENTRY2FIELD_FCT,ENTRY2FIELD_FCT);
}
public int determineTTL() {
return hasDeletions() ? 0 : determineTTL(getAdditions());
}
public static int determineTTL(List<IndexEntry> additions) {
if (additions == null || additions.isEmpty())
return 0;
Preconditions.checkArgument(!additions.isEmpty());
int ttl=-1;
for (IndexEntry add : additions) {
int ittl = 0;
if (add.hasMetaData()) {
Preconditions.checkArgument(add.getMetaData().size()==1 && add.getMetaData().containsKey(EntryMetaData.TTL),
"Index only supports TTL meta data. Found: %s",add.getMetaData());
ittl = (Integer)add.getMetaData().get(EntryMetaData.TTL);
}
if (ttl<0) ttl=ittl;
Preconditions.checkArgument(ttl==ittl,"Index only supports uniform TTL values across all " +
"index fields, but got additions: %s",additions);
}
assert ttl>=0;
return ttl;
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexMutation.java |
1,291 | new OCommandOutputListener() {
@Override
public void onMessage(String text) {
System.out.println(text);
}
}); | 0true
| core_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_LocalPaginatedStorageRestoreFromWAL.java |
1,597 | public class StandardLoggerFactory extends LoggerFactorySupport implements LoggerFactory {
@Override
protected ILogger createLogger(String name) {
final Logger l = Logger.getLogger(name);
return new StandardLogger(l);
}
static class StandardLogger extends AbstractLogger {
private final Logger logger;
public StandardLogger(Logger logger) {
this.logger = logger;
}
@Override
public void log(Level level, String message) {
log(level, message, null);
}
@Override
public void log(Level level, String message, Throwable thrown) {
LogRecord logRecord = new LogRecord(level, message);
logRecord.setLoggerName(logger.getName());
logRecord.setThrown(thrown);
logRecord.setSourceClassName(logger.getName());
logger.log(logRecord);
}
@Override
public void log(LogEvent logEvent) {
logger.log(logEvent.getLogRecord());
}
@Override
public Level getLevel() {
return logger.getLevel();
}
@Override
public boolean isLoggable(Level level) {
return logger.isLoggable(level);
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_logging_StandardLoggerFactory.java |
413 | @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface AdminPresentationClass {
/**
* <p>Specify whether or not the open admin module persistence mechanism
* should traverse ManyToOne or OneToOne field boundaries in the entity
* when retrieving and populating field values.</p>
*
* @return whether or not to populate ManyToOne or OneToOne fields
*/
PopulateToOneFieldsEnum populateToOneFields() default PopulateToOneFieldsEnum.NOT_SPECIFIED;
/**
* <p>The friendly name to present to a user for this field in a GUI. If supporting i18N,
* the friendly name may be a key to retrieve a localized friendly name using
* the GWT support for i18N. This name will be presented to users when they add a
* new entity in the GUI and select the polymorphic type for that new added entity.</p>
*
* @return the friendly name
*/
String friendlyName() default "";
/**
* <p>Specify the fully qualified class name of the ceiling entity for this inheritance hierarchy. This
* value affects the list of polymorphic types presented to the administrative user in the admin
* UI. By specifying a class lower in the inheritance hierarchy, you can cause only a subset of
* the entire JPA inheritance hierarchy to be presented to the user as options when creating new
* entities. This value will override any previous settings for this inheritance hierarchy.</p>
*
* @return the fully qualified classname of the new top-level member of this inheritance hierarchy
* to be displayed to the admin user
*/
String ceilingDisplayEntity() default "";
/**
* <p>Specify whether or not this class should be excluded from admin detection as a polymorphic type.
* This is useful if you have several entities that implement an interface, but you only want the
* admin to ignore one of the entities as a valid type for the interface.</p>
*
* @return Whether or not the admin should ignore this entity as a valid polymorphic type
*/
boolean excludeFromPolymorphism() default false;
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationClass.java |
624 | public class TransportIndicesStatsAction extends TransportBroadcastOperationAction<IndicesStatsRequest, IndicesStatsResponse, TransportIndicesStatsAction.IndexShardStatsRequest, ShardStats> {
private final IndicesService indicesService;
@Inject
public TransportIndicesStatsAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService,
IndicesService indicesService) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
}
@Override
protected String executor() {
return ThreadPool.Names.MANAGEMENT;
}
@Override
protected String transportAction() {
return IndicesStatsAction.NAME;
}
@Override
protected IndicesStatsRequest newRequest() {
return new IndicesStatsRequest();
}
/**
* Status goes across *all* shards.
*/
@Override
protected GroupShardsIterator shards(ClusterState clusterState, IndicesStatsRequest request, String[] concreteIndices) {
return clusterState.routingTable().allAssignedShardsGrouped(concreteIndices, true);
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, IndicesStatsRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, IndicesStatsRequest request, String[] concreteIndices) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, concreteIndices);
}
@Override
protected IndicesStatsResponse newResponse(IndicesStatsRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = null;
final List<ShardStats> shards = Lists.newArrayList();
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
// simply ignore non active shards
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
if (shardFailures == null) {
shardFailures = newArrayList();
}
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
shards.add((ShardStats) shardResponse);
successfulShards++;
}
}
return new IndicesStatsResponse(shards.toArray(new ShardStats[shards.size()]), clusterState, shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
@Override
protected IndexShardStatsRequest newShardRequest() {
return new IndexShardStatsRequest();
}
@Override
protected IndexShardStatsRequest newShardRequest(ShardRouting shard, IndicesStatsRequest request) {
return new IndexShardStatsRequest(shard.index(), shard.id(), request);
}
@Override
protected ShardStats newShardResponse() {
return new ShardStats();
}
@Override
protected ShardStats shardOperation(IndexShardStatsRequest request) throws ElasticsearchException {
InternalIndexService indexService = (InternalIndexService) indicesService.indexServiceSafe(request.index());
InternalIndexShard indexShard = (InternalIndexShard) indexService.shardSafe(request.shardId());
CommonStatsFlags flags = new CommonStatsFlags().clear();
if (request.request.docs()) {
flags.set(CommonStatsFlags.Flag.Docs);
}
if (request.request.store()) {
flags.set(CommonStatsFlags.Flag.Store);
}
if (request.request.indexing()) {
flags.set(CommonStatsFlags.Flag.Indexing);
flags.types(request.request.types());
}
if (request.request.get()) {
flags.set(CommonStatsFlags.Flag.Get);
}
if (request.request.search()) {
flags.set(CommonStatsFlags.Flag.Search);
flags.groups(request.request.groups());
}
if (request.request.merge()) {
flags.set(CommonStatsFlags.Flag.Merge);
}
if (request.request.refresh()) {
flags.set(CommonStatsFlags.Flag.Refresh);
}
if (request.request.flush()) {
flags.set(CommonStatsFlags.Flag.Flush);
}
if (request.request.warmer()) {
flags.set(CommonStatsFlags.Flag.Warmer);
}
if (request.request.filterCache()) {
flags.set(CommonStatsFlags.Flag.FilterCache);
}
if (request.request.idCache()) {
flags.set(CommonStatsFlags.Flag.IdCache);
}
if (request.request.fieldData()) {
flags.set(CommonStatsFlags.Flag.FieldData);
flags.fieldDataFields(request.request.fieldDataFields());
}
if (request.request.percolate()) {
flags.set(CommonStatsFlags.Flag.Percolate);
}
if (request.request.segments()) {
flags.set(CommonStatsFlags.Flag.Segments);
}
if (request.request.completion()) {
flags.set(CommonStatsFlags.Flag.Completion);
flags.completionDataFields(request.request.completionFields());
}
if (request.request.translog()) {
flags.set(CommonStatsFlags.Flag.Translog);
}
return new ShardStats(indexShard, flags);
}
public static class IndexShardStatsRequest extends BroadcastShardOperationRequest {
// TODO if there are many indices, the request might hold a large indices array..., we don't really need to serialize it
IndicesStatsRequest request;
IndexShardStatsRequest() {
}
IndexShardStatsRequest(String index, int shardId, IndicesStatsRequest request) {
super(index, shardId, request);
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = new IndicesStatsRequest();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
request.writeTo(out);
}
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_stats_TransportIndicesStatsAction.java |
1,321 | new SingleSourceUnitPackage(pkg, sourceUnitFullPath), moduleManager, CeylonBuilder.getProjectTypeChecker(project), tokens) {
@Override
protected boolean reuseExistingDescriptorModels() {
return true;
}
}; | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_JDTModule.java |
381 | public interface LocaleService {
/**
* @return the locale for the passed in code
*/
public Locale findLocaleByCode(String localeCode);
/**
* @return the default locale
*/
public Locale findDefaultLocale();
/**
* @return a list of all known locales
*/
public List<Locale> findAllLocales();
/**
* Persists the given locale
*
* @param locale
* @return the persisted locale
*/
public Locale save(Locale locale);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_locale_service_LocaleService.java |
386 | public interface OMultiValueChangeListener<K, V> {
/**
* Called when operation on collection is completed.
*
* @param event Operation description.
*/
public void onAfterRecordChanged(OMultiValueChangeEvent<K, V> event);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_OMultiValueChangeListener.java |
497 | return scheduledExecutor.scheduleWithFixedDelay(new Runnable() {
public void run() {
executeInternal(command);
}
}, initialDelay, period, unit); | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientExecutionServiceImpl.java |
846 | public class AtomicReferencePortableHook implements PortableHook {
static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.ATOMIC_REFERENCE_PORTABLE_FACTORY, -21);
static final int GET = 1;
static final int SET = 2;
static final int GET_AND_SET = 3;
static final int IS_NULL = 4;
static final int COMPARE_AND_SET = 5;
static final int CONTAINS = 6;
static final int APPLY = 7;
static final int ALTER = 8;
static final int ALTER_AND_GET = 9;
static final int GET_AND_ALTER = 10;
public int getFactoryId() {
return F_ID;
}
public PortableFactory createFactory() {
return new PortableFactory() {
public Portable create(int classId) {
switch (classId) {
case GET:
return new GetRequest();
case SET:
return new SetRequest();
case GET_AND_SET:
return new GetAndSetRequest();
case IS_NULL:
return new IsNullRequest();
case COMPARE_AND_SET:
return new CompareAndSetRequest();
case CONTAINS:
return new ContainsRequest();
case APPLY:
return new ApplyRequest();
case ALTER:
return new AlterRequest();
case ALTER_AND_GET:
return new AlterAndGetRequest();
case GET_AND_ALTER:
return new GetAndAlterRequest();
default:
return null;
}
}
};
}
@Override
public Collection<ClassDefinition> getBuiltinDefinitions() {
return null;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_AtomicReferencePortableHook.java |
747 | @Test
public class SBTreeWAL extends SBTreeTest {
static {
OGlobalConfiguration.INDEX_TX_MODE.setValue("FULL");
}
private String buildDirectory;
private String actualStorageDir;
private String expectedStorageDir;
private OWriteAheadLog writeAheadLog;
private ODiskCache actualDiskCache;
private ODiskCache expectedDiskCache;
private OLocalPaginatedStorage actualStorage;
private OSBTree<Integer, OIdentifiable> expectedSBTree;
private OLocalPaginatedStorage expectedStorage;
private OStorageConfiguration expectedStorageConfiguration;
private OStorageConfiguration actualStorageConfiguration;
@BeforeClass
@Override
public void beforeClass() {
actualStorage = mock(OLocalPaginatedStorage.class);
actualStorageConfiguration = mock(OStorageConfiguration.class);
expectedStorage = mock(OLocalPaginatedStorage.class);
expectedStorageConfiguration = mock(OStorageConfiguration.class);
}
@AfterClass
@Override
public void afterClass() {
}
@BeforeMethod
public void beforeMethod() throws IOException {
Mockito.reset(actualStorage, expectedStorage, expectedStorageConfiguration, actualStorageConfiguration);
buildDirectory = System.getProperty("buildDirectory", ".");
buildDirectory += "/sbtreeWithWALTest";
createExpectedSBTree();
createActualSBTree();
}
@AfterMethod
@Override
public void afterMethod() throws Exception {
sbTree.delete();
expectedSBTree.delete();
actualDiskCache.delete();
expectedDiskCache.delete();
writeAheadLog.delete();
Assert.assertTrue(new File(actualStorageDir).delete());
Assert.assertTrue(new File(expectedStorageDir).delete());
Assert.assertTrue(new File(buildDirectory).delete());
}
private void createActualSBTree() throws IOException {
actualStorageConfiguration.clusters = new ArrayList<OStorageClusterConfiguration>();
actualStorageConfiguration.fileTemplate = new OStorageSegmentConfiguration();
actualStorageDir = buildDirectory + "/sbtreeWithWALTestActual";
when(actualStorage.getStoragePath()).thenReturn(actualStorageDir);
when(actualStorage.getName()).thenReturn("sbtreeWithWALTesActual");
File buildDir = new File(buildDirectory);
if (!buildDir.exists())
buildDir.mkdirs();
File actualStorageDirFile = new File(actualStorageDir);
if (!actualStorageDirFile.exists())
actualStorageDirFile.mkdirs();
writeAheadLog = new OWriteAheadLog(6000, -1, 10 * 1024L * OWALPage.PAGE_SIZE, 100L * 1024 * 1024 * 1024, actualStorage);
actualDiskCache = new OReadWriteDiskCache(400L * 1024 * 1024 * 1024, 1648L * 1024 * 1024,
OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, 1000000, 100, actualStorage, null, false, false);
OStorageVariableParser variableParser = new OStorageVariableParser(actualStorageDir);
when(actualStorage.getStorageTransaction()).thenReturn(null);
when(actualStorage.getDiskCache()).thenReturn(actualDiskCache);
when(actualStorage.getWALInstance()).thenReturn(writeAheadLog);
when(actualStorage.getVariableParser()).thenReturn(variableParser);
when(actualStorage.getConfiguration()).thenReturn(actualStorageConfiguration);
when(actualStorage.getMode()).thenReturn("rw");
when(actualStorageConfiguration.getDirectory()).thenReturn(actualStorageDir);
sbTree = new OSBTree<Integer, OIdentifiable>(".sbt", 1, true);
sbTree.create("actualSBTree", OIntegerSerializer.INSTANCE, OLinkSerializer.INSTANCE, null, actualStorage);
}
private void createExpectedSBTree() {
expectedStorageConfiguration.clusters = new ArrayList<OStorageClusterConfiguration>();
expectedStorageConfiguration.fileTemplate = new OStorageSegmentConfiguration();
expectedStorageDir = buildDirectory + "/sbtreeWithWALTestExpected";
when(expectedStorage.getStoragePath()).thenReturn(expectedStorageDir);
when(expectedStorage.getName()).thenReturn("sbtreeWithWALTesExpected");
File buildDir = new File(buildDirectory);
if (!buildDir.exists())
buildDir.mkdirs();
File expectedStorageDirFile = new File(expectedStorageDir);
if (!expectedStorageDirFile.exists())
expectedStorageDirFile.mkdirs();
expectedDiskCache = new OReadWriteDiskCache(400L * 1024 * 1024 * 1024, 1648L * 1024 * 1024,
OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, 1000000, 100, expectedStorage, null, false, false);
OStorageVariableParser variableParser = new OStorageVariableParser(expectedStorageDir);
when(expectedStorage.getStorageTransaction()).thenReturn(null);
when(expectedStorage.getDiskCache()).thenReturn(expectedDiskCache);
when(expectedStorage.getWALInstance()).thenReturn(null);
when(expectedStorage.getVariableParser()).thenReturn(variableParser);
when(expectedStorage.getConfiguration()).thenReturn(expectedStorageConfiguration);
when(expectedStorage.getMode()).thenReturn("rw");
when(expectedStorageConfiguration.getDirectory()).thenReturn(expectedStorageDir);
expectedSBTree = new OSBTree<Integer, OIdentifiable>(".sbt", 1, true);
expectedSBTree.create("expectedSBTree", OIntegerSerializer.INSTANCE, OLinkSerializer.INSTANCE, null, expectedStorage);
}
@Override
public void testKeyPut() throws Exception {
super.testKeyPut();
assertFileRestoreFromWAL();
}
@Override
public void testKeyPutRandomUniform() throws Exception {
super.testKeyPutRandomUniform();
assertFileRestoreFromWAL();
}
@Override
public void testKeyPutRandomGaussian() throws Exception {
super.testKeyPutRandomGaussian();
assertFileRestoreFromWAL();
}
@Override
public void testKeyDeleteRandomUniform() throws Exception {
super.testKeyDeleteRandomUniform();
assertFileRestoreFromWAL();
}
@Override
public void testKeyDeleteRandomGaussian() throws Exception {
super.testKeyDeleteRandomGaussian();
assertFileRestoreFromWAL();
}
@Override
public void testKeyDelete() throws Exception {
super.testKeyDelete();
assertFileRestoreFromWAL();
}
@Override
public void testKeyAddDelete() throws Exception {
super.testKeyAddDelete();
assertFileRestoreFromWAL();
}
@Override
public void testAddKeyValuesInTwoBucketsAndMakeFirstEmpty() throws Exception {
super.testAddKeyValuesInTwoBucketsAndMakeFirstEmpty();
assertFileRestoreFromWAL();
}
@Override
public void testAddKeyValuesInTwoBucketsAndMakeLastEmpty() throws Exception {
super.testAddKeyValuesInTwoBucketsAndMakeLastEmpty();
assertFileRestoreFromWAL();
}
@Override
public void testAddKeyValuesAndRemoveFirstMiddleAndLastPages() throws Exception {
super.testAddKeyValuesAndRemoveFirstMiddleAndLastPages();
assertFileRestoreFromWAL();
}
@Test(enabled = false)
@Override
public void testValuesMajor() {
super.testValuesMajor();
}
@Test(enabled = false)
@Override
public void testValuesMinor() {
super.testValuesMinor();
}
@Test(enabled = false)
@Override
public void testValuesBetween() {
super.testValuesBetween();
}
private void assertFileRestoreFromWAL() throws IOException {
sbTree.close();
writeAheadLog.close();
expectedSBTree.close();
actualDiskCache.clear();
restoreDataFromWAL();
expectedDiskCache.clear();
assertFileContentIsTheSame(expectedSBTree.getName(), sbTree.getName());
}
private void restoreDataFromWAL() throws IOException {
OWriteAheadLog log = new OWriteAheadLog(4, -1, 10 * 1024L * OWALPage.PAGE_SIZE, 100L * 1024 * 1024 * 1024, actualStorage);
OLogSequenceNumber lsn = log.begin();
List<OWALRecord> atomicUnit = new ArrayList<OWALRecord>();
boolean atomicChangeIsProcessed = false;
while (lsn != null) {
OWALRecord walRecord = log.read(lsn);
atomicUnit.add(walRecord);
if (!atomicChangeIsProcessed) {
Assert.assertTrue(walRecord instanceof OAtomicUnitStartRecord);
atomicChangeIsProcessed = true;
} else if (walRecord instanceof OAtomicUnitEndRecord) {
atomicChangeIsProcessed = false;
for (OWALRecord restoreRecord : atomicUnit) {
if (restoreRecord instanceof OAtomicUnitStartRecord || restoreRecord instanceof OAtomicUnitEndRecord)
continue;
final OUpdatePageRecord updatePageRecord = (OUpdatePageRecord) restoreRecord;
final long fileId = updatePageRecord.getFileId();
final long pageIndex = updatePageRecord.getPageIndex();
if (!expectedDiskCache.isOpen(fileId))
expectedDiskCache.openFile(fileId);
final OCacheEntry cacheEntry = expectedDiskCache.load(fileId, pageIndex, true);
final OCachePointer cachePointer = cacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
try {
ODurablePage durablePage = new ODurablePage(cachePointer.getDataPointer(), ODurablePage.TrackMode.NONE);
durablePage.restoreChanges(updatePageRecord.getChanges());
durablePage.setLsn(updatePageRecord.getLsn());
cacheEntry.markDirty();
} finally {
cachePointer.releaseExclusiveLock();
expectedDiskCache.release(cacheEntry);
}
}
atomicUnit.clear();
} else {
Assert.assertTrue(walRecord instanceof OUpdatePageRecord);
}
lsn = log.next(lsn);
}
Assert.assertTrue(atomicUnit.isEmpty());
log.close();
}
private void assertFileContentIsTheSame(String expectedBTree, String actualBTree) throws IOException {
File expectedFile = new File(expectedStorageDir, expectedBTree + ".sbt");
RandomAccessFile fileOne = new RandomAccessFile(expectedFile, "r");
RandomAccessFile fileTwo = new RandomAccessFile(new File(actualStorageDir, actualBTree + ".sbt"), "r");
Assert.assertEquals(fileOne.length(), fileTwo.length());
byte[] expectedContent = new byte[OClusterPage.PAGE_SIZE];
byte[] actualContent = new byte[OClusterPage.PAGE_SIZE];
fileOne.seek(OAbstractFile.HEADER_SIZE);
fileTwo.seek(OAbstractFile.HEADER_SIZE);
int bytesRead = fileOne.read(expectedContent);
while (bytesRead >= 0) {
fileTwo.readFully(actualContent, 0, bytesRead);
Assert.assertEquals(expectedContent, actualContent);
expectedContent = new byte[OClusterPage.PAGE_SIZE];
actualContent = new byte[OClusterPage.PAGE_SIZE];
bytesRead = fileOne.read(expectedContent);
}
fileOne.close();
fileTwo.close();
}
} | 1no label
| core_src_test_java_com_orientechnologies_orient_core_index_sbtree_local_SBTreeWAL.java |
962 | public final class GetRemainingLeaseRequest extends KeyBasedClientRequest
implements Portable {
private Data key;
public GetRemainingLeaseRequest() {
}
public GetRemainingLeaseRequest(Data key) {
this.key = key;
}
@Override
protected Operation prepareOperation() {
String name = (String) getClientEngine().toObject(key);
return new GetRemainingLeaseTimeOperation(new InternalLockNamespace(name), key);
}
@Override
protected Object getKey() {
return key;
}
@Override
public String getServiceName() {
return LockService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return LockPortableHook.FACTORY_ID;
}
@Override
public int getClassId() {
return LockPortableHook.GET_REMAINING_LEASE;
}
public void write(PortableWriter writer) throws IOException {
ObjectDataOutput out = writer.getRawDataOutput();
key.writeData(out);
}
public void read(PortableReader reader) throws IOException {
ObjectDataInput in = reader.getRawDataInput();
key = new Data();
key.readData(in);
}
public Permission getRequiredPermission() {
String name = (String) getClientEngine().toObject(key);
return new LockPermission(name, ActionConstants.ACTION_READ);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_client_GetRemainingLeaseRequest.java |
733 | public class CollectionCompareAndRemoveRequest extends CollectionRequest {
private Set<Data> valueSet;
private boolean retain;
public CollectionCompareAndRemoveRequest() {
}
public CollectionCompareAndRemoveRequest(String name, Set<Data> valueSet, boolean retain) {
super(name);
this.valueSet = valueSet;
this.retain = retain;
}
@Override
protected Operation prepareOperation() {
return new CollectionCompareAndRemoveOperation(name, retain, valueSet);
}
@Override
public int getClassId() {
return CollectionPortableHook.COLLECTION_COMPARE_AND_REMOVE;
}
public void write(PortableWriter writer) throws IOException {
super.write(writer);
writer.writeBoolean("r", retain);
final ObjectDataOutput out = writer.getRawDataOutput();
out.writeInt(valueSet.size());
for (Data value : valueSet) {
value.writeData(out);
}
}
public void read(PortableReader reader) throws IOException {
super.read(reader);
retain = reader.readBoolean("r");
final ObjectDataInput in = reader.getRawDataInput();
final int size = in.readInt();
valueSet = new HashSet<Data>(size);
for (int i = 0; i < size; i++) {
final Data value = new Data();
value.readData(in);
valueSet.add(value);
}
}
@Override
public String getRequiredAction() {
return ActionConstants.ACTION_REMOVE;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_client_CollectionCompareAndRemoveRequest.java |
3,318 | public class DoubleArrayIndexFieldData extends AbstractIndexFieldData<DoubleArrayAtomicFieldData> implements IndexNumericFieldData<DoubleArrayAtomicFieldData> {
private final CircuitBreakerService breakerService;
public static class Builder implements IndexFieldData.Builder {
@Override
public IndexFieldData<?> build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper, IndexFieldDataCache cache,
CircuitBreakerService breakerService) {
return new DoubleArrayIndexFieldData(index, indexSettings, mapper.names(), mapper.fieldDataType(), cache, breakerService);
}
}
public DoubleArrayIndexFieldData(Index index, @IndexSettings Settings indexSettings, FieldMapper.Names fieldNames,
FieldDataType fieldDataType, IndexFieldDataCache cache, CircuitBreakerService breakerService) {
super(index, indexSettings, fieldNames, fieldDataType, cache);
this.breakerService = breakerService;
}
@Override
public NumericType getNumericType() {
return NumericType.DOUBLE;
}
@Override
public boolean valuesOrdered() {
// because we might have single values? we can dynamically update a flag to reflect that
// based on the atomic field data loaded
return false;
}
@Override
public DoubleArrayAtomicFieldData loadDirect(AtomicReaderContext context) throws Exception {
AtomicReader reader = context.reader();
Terms terms = reader.terms(getFieldNames().indexName());
DoubleArrayAtomicFieldData data = null;
// TODO: Use an actual estimator to estimate before loading.
NonEstimatingEstimator estimator = new NonEstimatingEstimator(breakerService.getBreaker());
if (terms == null) {
data = DoubleArrayAtomicFieldData.empty(reader.maxDoc());
estimator.afterLoad(null, data.getMemorySizeInBytes());
return data;
}
// TODO: how can we guess the number of terms? numerics end up creating more terms per value...
final BigDoubleArrayList values = new BigDoubleArrayList();
values.add(0); // first "t" indicates null value
final float acceptableTransientOverheadRatio = fieldDataType.getSettings().getAsFloat("acceptable_transient_overhead_ratio", OrdinalsBuilder.DEFAULT_ACCEPTABLE_OVERHEAD_RATIO);
OrdinalsBuilder builder = new OrdinalsBuilder(reader.maxDoc(), acceptableTransientOverheadRatio);
boolean success = false;
try {
final BytesRefIterator iter = builder.buildFromTerms(getNumericType().wrapTermsEnum(terms.iterator(null)));
BytesRef term;
while ((term = iter.next()) != null) {
values.add(NumericUtils.sortableLongToDouble(NumericUtils.prefixCodedToLong(term)));
}
Ordinals build = builder.build(fieldDataType.getSettings());
if (!build.isMultiValued() && CommonSettings.removeOrdsOnSingleValue(fieldDataType)) {
Docs ordinals = build.ordinals();
final FixedBitSet set = builder.buildDocsWithValuesSet();
// there's sweet spot where due to low unique value count, using ordinals will consume less memory
long singleValuesArraySize = reader.maxDoc() * RamUsageEstimator.NUM_BYTES_DOUBLE + (set == null ? 0 : RamUsageEstimator.sizeOf(set.getBits()) + RamUsageEstimator.NUM_BYTES_INT);
long uniqueValuesArraySize = values.sizeInBytes();
long ordinalsSize = build.getMemorySizeInBytes();
if (uniqueValuesArraySize + ordinalsSize < singleValuesArraySize) {
data = new DoubleArrayAtomicFieldData.WithOrdinals(values, reader.maxDoc(), build);
success = true;
return data;
}
int maxDoc = reader.maxDoc();
BigDoubleArrayList sValues = new BigDoubleArrayList(maxDoc);
for (int i = 0; i < maxDoc; i++) {
sValues.add(values.get(ordinals.getOrd(i)));
}
assert sValues.size() == maxDoc;
if (set == null) {
data = new DoubleArrayAtomicFieldData.Single(sValues, maxDoc, ordinals.getNumOrds());
} else {
data = new DoubleArrayAtomicFieldData.SingleFixedSet(sValues, maxDoc, set, ordinals.getNumOrds());
}
} else {
data = new DoubleArrayAtomicFieldData.WithOrdinals(values, reader.maxDoc(), build);
}
success = true;
return data;
} finally {
if (success) {
estimator.afterLoad(null, data.getMemorySizeInBytes());
}
builder.close();
}
}
@Override
public XFieldComparatorSource comparatorSource(@Nullable Object missingValue, SortMode sortMode) {
return new DoubleValuesComparatorSource(this, missingValue, sortMode);
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayIndexFieldData.java |
845 | public class TransportMultiSearchAction extends TransportAction<MultiSearchRequest, MultiSearchResponse> {
private final ClusterService clusterService;
private final TransportSearchAction searchAction;
@Inject
public TransportMultiSearchAction(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, TransportSearchAction searchAction) {
super(settings, threadPool);
this.clusterService = clusterService;
this.searchAction = searchAction;
transportService.registerHandler(MultiSearchAction.NAME, new TransportHandler());
}
@Override
protected void doExecute(final MultiSearchRequest request, final ActionListener<MultiSearchResponse> listener) {
ClusterState clusterState = clusterService.state();
clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ);
final AtomicArray<MultiSearchResponse.Item> responses = new AtomicArray<MultiSearchResponse.Item>(request.requests().size());
final AtomicInteger counter = new AtomicInteger(responses.length());
for (int i = 0; i < responses.length(); i++) {
final int index = i;
searchAction.execute(request.requests().get(i), new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse searchResponse) {
responses.set(index, new MultiSearchResponse.Item(searchResponse, null));
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable e) {
responses.set(index, new MultiSearchResponse.Item(null, ExceptionsHelper.detailedMessage(e)));
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
private void finishHim() {
listener.onResponse(new MultiSearchResponse(responses.toArray(new MultiSearchResponse.Item[responses.length()])));
}
});
}
}
class TransportHandler extends BaseTransportRequestHandler<MultiSearchRequest> {
@Override
public MultiSearchRequest newInstance() {
return new MultiSearchRequest();
}
@Override
public void messageReceived(final MultiSearchRequest request, final TransportChannel channel) throws Exception {
// no need to use threaded listener, since we just send a response
request.listenerThreaded(false);
execute(request, new ActionListener<MultiSearchResponse>() {
@Override
public void onResponse(MultiSearchResponse response) {
try {
channel.sendResponse(response);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send error response for action [msearch] and request [" + request + "]", e1);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
} | 0true
| src_main_java_org_elasticsearch_action_search_TransportMultiSearchAction.java |
1,355 | ShardFailedTransportHandler.ACTION, shardRoutingEntry, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send failed shard to [{}]", exp, clusterService.state().nodes().masterNode());
}
}); | 0true
| src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java |
3,321 | public class FSTBytesAtomicFieldData implements AtomicFieldData.WithOrdinals<ScriptDocValues.Strings> {
public static FSTBytesAtomicFieldData empty(int numDocs) {
return new Empty(numDocs);
}
// 0 ordinal in values means no value (its null)
protected final Ordinals ordinals;
private volatile IntArray hashes;
private long size = -1;
private final FST<Long> fst;
public FSTBytesAtomicFieldData(FST<Long> fst, Ordinals ordinals) {
this.ordinals = ordinals;
this.fst = fst;
}
@Override
public void close() {
}
@Override
public boolean isMultiValued() {
return ordinals.isMultiValued();
}
@Override
public int getNumDocs() {
return ordinals.getNumDocs();
}
@Override
public long getNumberUniqueValues() {
return ordinals.getNumOrds();
}
@Override
public boolean isValuesOrdered() {
return true;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
long size = ordinals.getMemorySizeInBytes();
// FST
size += fst == null ? 0 : fst.sizeInBytes();
this.size = size;
}
return size;
}
@Override
public BytesValues.WithOrdinals getBytesValues(boolean needsHashes) {
assert fst != null;
if (needsHashes) {
if (hashes == null) {
BytesRefFSTEnum<Long> fstEnum = new BytesRefFSTEnum<Long>(fst);
IntArray hashes = BigArrays.newIntArray(ordinals.getMaxOrd());
// we don't store an ord 0 in the FST since we could have an empty string in there and FST don't support
// empty strings twice. ie. them merge fails for long output.
hashes.set(0, new BytesRef().hashCode());
try {
for (long i = 1, maxOrd = ordinals.getMaxOrd(); i < maxOrd; ++i) {
hashes.set(i, fstEnum.next().input.hashCode());
}
assert fstEnum.next() == null;
} catch (IOException e) {
// Don't use new "AssertionError("Cannot happen", e)" directly as this is a Java 1.7-only API
final AssertionError error = new AssertionError("Cannot happen");
error.initCause(e);
throw error;
}
this.hashes = hashes;
}
return new HashedBytesValues(fst, ordinals.ordinals(), hashes);
} else {
return new BytesValues(fst, ordinals.ordinals());
}
}
@Override
public ScriptDocValues.Strings getScriptValues() {
assert fst != null;
return new ScriptDocValues.Strings(getBytesValues(false));
}
static class BytesValues extends org.elasticsearch.index.fielddata.BytesValues.WithOrdinals {
protected final FST<Long> fst;
protected final Ordinals.Docs ordinals;
// per-thread resources
protected final BytesReader in;
protected final Arc<Long> firstArc = new Arc<Long>();
protected final Arc<Long> scratchArc = new Arc<Long>();
protected final IntsRef scratchInts = new IntsRef();
BytesValues(FST<Long> fst, Ordinals.Docs ordinals) {
super(ordinals);
this.fst = fst;
this.ordinals = ordinals;
in = fst.getBytesReader();
}
@Override
public BytesRef getValueByOrd(long ord) {
assert ord != Ordinals.MISSING_ORDINAL;
in.setPosition(0);
fst.getFirstArc(firstArc);
try {
IntsRef output = Util.getByOutput(fst, ord, in, firstArc, scratchArc, scratchInts);
scratch.length = scratch.offset = 0;
scratch.grow(output.length);
Util.toBytesRef(output, scratch);
} catch (IOException ex) {
//bogus
}
return scratch;
}
}
static final class HashedBytesValues extends BytesValues {
private final IntArray hashes;
HashedBytesValues(FST<Long> fst, Docs ordinals, IntArray hashes) {
super(fst, ordinals);
this.hashes = hashes;
}
@Override
public int currentValueHash() {
assert ordinals.currentOrd() >= 0;
return hashes.get(ordinals.currentOrd());
}
}
final static class Empty extends FSTBytesAtomicFieldData {
Empty(int numDocs) {
super(null, new EmptyOrdinals(numDocs));
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public int getNumDocs() {
return ordinals.getNumDocs();
}
@Override
public boolean isValuesOrdered() {
return true;
}
@Override
public BytesValues.WithOrdinals getBytesValues(boolean needsHashes) {
return new EmptyByteValuesWithOrdinals(ordinals.ordinals());
}
@Override
public ScriptDocValues.Strings getScriptValues() {
return ScriptDocValues.EMPTY_STRINGS;
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_FSTBytesAtomicFieldData.java |
1,595 | public class Slf4jFactory extends LoggerFactorySupport {
@Override
protected ILogger createLogger(String name) {
final Logger l = LoggerFactory.getLogger(name);
return new Slf4jLogger(l);
}
static class Slf4jLogger extends AbstractLogger {
private final Logger logger;
public Slf4jLogger(Logger logger) {
this.logger = logger;
}
@Override
public void log(Level level, String message) {
if (Level.FINEST == level) {
logger.debug(message);
} else if (Level.SEVERE == level) {
logger.error(message);
} else if (Level.WARNING == level) {
logger.warn(message);
} else {
logger.info(message);
}
}
@Override
public Level getLevel() {
if (logger.isErrorEnabled()) {
return Level.SEVERE;
} else if (logger.isWarnEnabled()) {
return Level.WARNING;
} else if (logger.isInfoEnabled()) {
return Level.INFO;
} else {
return Level.FINEST;
}
}
@Override
public boolean isLoggable(Level level) {
if (Level.OFF == level) {
return false;
} else if (Level.FINEST == level) {
return logger.isDebugEnabled();
} else if (Level.INFO == level) {
return logger.isInfoEnabled();
} else if (Level.WARNING == level) {
return logger.isWarnEnabled();
} else if (Level.SEVERE == level) {
return logger.isErrorEnabled();
} else {
return logger.isInfoEnabled();
}
}
@Override
public void log(Level level, String message, Throwable thrown) {
if (Level.FINEST == level) {
logger.debug(message, thrown);
} else if (Level.INFO == level) {
logger.info(message, thrown);
} else if (Level.WARNING == level) {
logger.warn(message, thrown);
} else if (Level.SEVERE == level) {
logger.error(message, thrown);
} else {
logger.info(message, thrown);
}
}
@Override
public void log(LogEvent logEvent) {
LogRecord logRecord = logEvent.getLogRecord();
Level level = logEvent.getLogRecord().getLevel();
String message = logRecord.getMessage();
Throwable thrown = logRecord.getThrown();
log(level, message, thrown);
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_logging_Slf4jFactory.java |
333 | static class NodeInfoRequest extends NodeOperationRequest {
NodesInfoRequest request;
NodeInfoRequest() {
}
NodeInfoRequest(String nodeId, NodesInfoRequest request) {
super(request, nodeId);
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = new NodesInfoRequest();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
request.writeTo(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_node_info_TransportNodesInfoAction.java |
392 | final Iterator<OIdentifiable> subIterator = new OLazyIterator<OIdentifiable>() {
private int pos = -1;
public boolean hasNext() {
return pos < size() - 1;
}
public OIdentifiable next() {
return ORecordLazyList.this.rawGet(++pos);
}
public void remove() {
ORecordLazyList.this.remove(pos);
}
public OIdentifiable update(final OIdentifiable iValue) {
return ORecordLazyList.this.set(pos, iValue);
}
}; | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordLazyList.java |
1,137 | public class DistributedObjectEvent {
private EventType eventType;
private String serviceName;
private DistributedObject distributedObject;
public DistributedObjectEvent(EventType eventType, String serviceName, DistributedObject distributedObject) {
this.eventType = eventType;
this.serviceName = serviceName;
this.distributedObject = distributedObject;
}
/**
* Returns service name of related DistributedObject
*
* @return service name of DistributedObject
*/
public String getServiceName() {
return serviceName;
}
/**
* Returns type of this event; one of {@link EventType#CREATED} or {@link EventType#DESTROYED}
*
* @return eventType
*/
public EventType getEventType() {
return eventType;
}
/**
* Returns identifier of related DistributedObject
*
* @return identifier of DistributedObject
*/
public Object getObjectId() {
return distributedObject.getId();
}
/**
* Returns DistributedObject instance
*
* @return DistributedObject
*/
public DistributedObject getDistributedObject() {
return distributedObject;
}
public enum EventType {
CREATED, DESTROYED
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DistributedObjectEvent{");
sb.append("eventType=").append(eventType);
sb.append(", serviceName='").append(serviceName).append('\'');
sb.append(", distributedObject=").append(distributedObject);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_DistributedObjectEvent.java |
690 | @Embeddable
public class Dimension implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "WIDTH")
@AdminPresentation(friendlyName = "ProductDimension_Product_Width", order = 1000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping)
protected BigDecimal width;
@Column(name = "HEIGHT")
@AdminPresentation(friendlyName = "ProductDimension_Product_Height", order = 2000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping)
protected BigDecimal height;
@Column(name = "DEPTH")
@AdminPresentation(friendlyName = "ProductDimension_Product_Depth", order = 3000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping)
protected BigDecimal depth;
@Column(name = "GIRTH")
@AdminPresentation(friendlyName = "ProductDimension_Product_Girth", order = 4000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping)
protected BigDecimal girth;
@Column(name = "CONTAINER_SIZE")
@AdminPresentation(friendlyName = "ProductDimension_Product_Container_Size", order = 5000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.common.vendor.service.type.ContainerSizeType")
protected String size;
@Column(name = "CONTAINER_SHAPE")
@AdminPresentation(friendlyName = "ProductDimension_Product_Container_Shape", order = 6000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.common.vendor.service.type.ContainerShapeType")
protected String container;
@Column(name = "DIMENSION_UNIT_OF_MEASURE")
@AdminPresentation(friendlyName = "ProductDimension_Product_Dimension_Units", order = 7000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.common.util.DimensionUnitOfMeasureType")
protected String dimensionUnitOfMeasure;
public BigDecimal getWidth() {
return width;
}
public void setWidth(final BigDecimal width) {
this.width = width;
}
public BigDecimal getHeight() {
return height;
}
public void setHeight(final BigDecimal height) {
this.height = height;
}
public BigDecimal getDepth() {
return depth;
}
public void setDepth(final BigDecimal depth) {
this.depth = depth;
}
/**
* Returns the product dimensions as a String (assumes measurements are in
* inches)
* @return a String value of the product dimensions
*/
public String getDimensionString() {
return height + "Hx" + width + "Wx" + depth + "D\"";
}
public BigDecimal getGirth() {
return girth;
}
public void setGirth(final BigDecimal girth) {
this.girth = girth;
}
public ContainerSizeType getSize() {
return ContainerSizeType.getInstance(size);
}
public void setSize(final ContainerSizeType size) {
if (size != null) {
this.size = size.getType();
}
}
public ContainerShapeType getContainer() {
return ContainerShapeType.getInstance(container);
}
public void setContainer(final ContainerShapeType container) {
if (container != null) {
this.container = container.getType();
}
}
public DimensionUnitOfMeasureType getDimensionUnitOfMeasure() {
return DimensionUnitOfMeasureType.getInstance(dimensionUnitOfMeasure);
}
public void setDimensionUnitOfMeasure(final DimensionUnitOfMeasureType dimensionUnitOfMeasure) {
if (dimensionUnitOfMeasure != null) {
this.dimensionUnitOfMeasure = dimensionUnitOfMeasure.getType();
}
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_Dimension.java |
2,188 | public class MatchNoDocsFilter extends Filter {
@Override
public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException {
return null;
}
@Override
public int hashCode() {
return this.getClass().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null) {
return false;
}
if (obj.getClass() == this.getClass()) {
return true;
}
return false;
}
@Override
public String toString() {
return "MatchNoDocsFilter";
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_search_MatchNoDocsFilter.java |
110 | class CreateTypeParameterProposal extends CorrectionProposal {
CreateTypeParameterProposal(String desc, Image image,
int offset, int length, TextFileChange change) {
super(desc, change, new Region(offset, length), image);
}
private static void addProposal(Collection<ICompletionProposal> proposals,
boolean wasNotGeneric, String def, String name, Image image,
Declaration dec, PhasedUnit unit, Tree.Declaration decNode,
int offset, String constraints) {
IFile file = getFile(unit);
TextFileChange change = new TextFileChange("Add Parameter", file);
change.setEdit(new MultiTextEdit());
IDocument doc = EditorUtil.getDocument(change);
HashSet<Declaration> decs = new HashSet<Declaration>();
CompilationUnit cu = unit.getCompilationUnit();
int il = applyImports(change, decs, cu, doc);
change.addEdit(new InsertEdit(offset, def));
if (constraints!=null) {
int loc = getConstraintLoc(decNode);
if (loc>=0) {
change.addEdit(new InsertEdit(loc, constraints));
}
}
String desc = "Add type parameter '" + name + "'" +
" to '" + dec.getName() + "'";
int off = wasNotGeneric?1:2;
proposals.add(new CreateTypeParameterProposal(desc,
image, offset+il+off, name.length(), change));
}
private static int getConstraintLoc(Tree.Declaration decNode) {
if( decNode instanceof Tree.ClassDefinition ) {
Tree.ClassDefinition classDefinition = (Tree.ClassDefinition) decNode;
return classDefinition.getClassBody().getStartIndex();
}
else if( decNode instanceof Tree.InterfaceDefinition ) {
Tree.InterfaceDefinition interfaceDefinition = (Tree.InterfaceDefinition) decNode;
return interfaceDefinition.getInterfaceBody().getStartIndex();
}
else if( decNode instanceof Tree.MethodDefinition ) {
Tree.MethodDefinition methodDefinition = (Tree.MethodDefinition) decNode;
return methodDefinition.getBlock().getStartIndex();
}
else if( decNode instanceof Tree.ClassDeclaration ) {
Tree.ClassDeclaration classDefinition = (Tree.ClassDeclaration) decNode;
return classDefinition.getClassSpecifier().getStartIndex();
}
else if( decNode instanceof Tree.InterfaceDefinition ) {
Tree.InterfaceDeclaration interfaceDefinition = (Tree.InterfaceDeclaration) decNode;
return interfaceDefinition.getTypeSpecifier().getStartIndex();
}
else if( decNode instanceof Tree.MethodDeclaration ) {
Tree.MethodDeclaration methodDefinition = (Tree.MethodDeclaration) decNode;
return methodDefinition.getSpecifierExpression().getStartIndex();
}
else {
return -1;
}
}
static void addCreateTypeParameterProposal(Collection<ICompletionProposal> proposals,
IProject project, Tree.CompilationUnit cu, final Tree.BaseType node,
String brokenName) {
class FilterExtendsSatisfiesVisitor extends Visitor {
boolean filter = false;
@Override
public void visit(Tree.ExtendedType that) {
super.visit(that);
if (that.getType()==node) {
filter = true;
}
}
@Override
public void visit(Tree.SatisfiedTypes that) {
super.visit(that);
for (Tree.Type t: that.getTypes()) {
if (t==node) {
filter = true;
}
}
}
@Override
public void visit(Tree.CaseTypes that) {
super.visit(that);
for (Tree.Type t: that.getTypes()) {
if (t==node) {
filter = true;
}
}
}
}
FilterExtendsSatisfiesVisitor v = new FilterExtendsSatisfiesVisitor();
v.visit(cu);
if (v.filter) {
return;
}
Tree.Declaration decl = findDeclarationWithBody(cu, node);
Declaration d = decl==null ? null : decl.getDeclarationModel();
if (d == null || d.isActual() ||
!(d instanceof Method || d instanceof ClassOrInterface)) {
return;
}
Tree.TypeParameterList paramList = getTypeParameters(decl);
String paramDef;
int offset;
//TODO: add bounds as default type arg?
if (paramList != null) {
paramDef = ", " + brokenName;
offset = paramList.getStopIndex();
}
else {
paramDef = "<" + brokenName + ">";
offset = Nodes.getIdentifyingNode(decl).getStopIndex()+1;
}
class FindTypeParameterConstraintVisitor extends Visitor {
List<ProducedType> result;
@Override
public void visit(Tree.SimpleType that) {
super.visit(that);
TypeDeclaration dm = that.getDeclarationModel();
if (dm!=null) {
List<TypeParameter> tps = dm.getTypeParameters();
Tree.TypeArgumentList tal = that.getTypeArgumentList();
if (tal!=null) {
List<Tree.Type> tas = tal.getTypes();
for (int i=0; i<tas.size(); i++) {
if (tas.get(i)==node) {
result = tps.get(i).getSatisfiedTypes();
}
}
}
}
}
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
super.visit(that);
Declaration d = that.getDeclaration();
if (d instanceof Generic) {
List<TypeParameter> tps = ((Generic) d).getTypeParameters();
Tree.TypeArguments tal = that.getTypeArguments();
if (tal instanceof Tree.TypeArgumentList) {
List<Tree.Type> tas = ((Tree.TypeArgumentList) tal).getTypes();
for (int i=0; i<tas.size(); i++) {
if (tas.get(i)==node) {
result = tps.get(i).getSatisfiedTypes();
}
}
}
}
}
}
FindTypeParameterConstraintVisitor ftpcv =
new FindTypeParameterConstraintVisitor();
ftpcv.visit(cu);
String constraints;
if (ftpcv.result==null) {
constraints = null;
}
else {
String bounds = CorrectionUtil.asIntersectionTypeString(ftpcv.result);
if (bounds.isEmpty()) {
constraints = null;
}
else {
constraints = "given " + brokenName +
" satisfies " + bounds + " ";
}
}
for (PhasedUnit unit : getUnits(project)) {
if (unit.getUnit().equals(cu.getUnit())) {
addProposal(proposals, paramList==null,
paramDef, brokenName, ADD_CORR,
d, unit, decl, offset, constraints);
break;
}
}
}
private static Tree.TypeParameterList getTypeParameters(Tree.Declaration decl) {
if (decl instanceof Tree.ClassOrInterface) {
return ((Tree.ClassOrInterface) decl).getTypeParameterList();
}
else if (decl instanceof Tree.AnyMethod) {
return ((Tree.AnyMethod) decl).getTypeParameterList();
}
return null;
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CreateTypeParameterProposal.java |
1,058 | public class OCommandExecutorSQLTruncateClass extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest {
public static final String KEYWORD_TRUNCATE = "TRUNCATE";
public static final String KEYWORD_CLASS = "CLASS";
private OClass schemaClass;
@SuppressWarnings("unchecked")
public OCommandExecutorSQLTruncateClass parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
init((OCommandRequestText) iRequest);
StringBuilder word = new StringBuilder();
int oldPos = 0;
int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_TRUNCATE))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_TRUNCATE + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_CLASS))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_CLASS + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserText, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Expected class name. Use " + getSyntax(), parserText, oldPos);
final String className = word.toString();
schemaClass = database.getMetadata().getSchema().getClass(className);
if (schemaClass == null)
throw new OCommandSQLParsingException("Class '" + className + "' not found", parserText, oldPos);
return this;
}
/**
* Execute the command.
*/
public Object execute(final Map<Object, Object> iArgs) {
if (schemaClass == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final long recs = schemaClass.count();
try {
schemaClass.truncate();
} catch (IOException e) {
throw new OCommandExecutionException("Error on executing command", e);
}
return recs;
}
@Override
public String getSyntax() {
return "TRUNCATE CLASS <class-name>";
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLTruncateClass.java |
1,316 | fuzzyCheckpointExecutor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
makeFuzzyCheckpoint();
} catch (Throwable e) {
OLogManager.instance().error(this, "Error during background fuzzy checkpoint creation for storage " + name, e);
}
}
}, fuzzyCheckpointDelay, fuzzyCheckpointDelay, TimeUnit.SECONDS); | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OLocalPaginatedStorage.java |
2,311 | public class RoundingTests extends ElasticsearchTestCase {
public void testInterval() {
final long interval = randomIntBetween(1, 100);
Rounding.Interval rounding = new Rounding.Interval(interval);
for (int i = 0; i < 1000; ++i) {
long l = Math.max(randomLong(), Long.MIN_VALUE + interval);
final long r = rounding.round(l);
String message = "round(" + l + ", interval=" + interval + ") = " + r;
assertEquals(message, 0, r % interval);
assertThat(message, r, lessThanOrEqualTo(l));
assertThat(message, r + interval, greaterThan(l));
}
}
} | 0true
| src_test_java_org_elasticsearch_common_rounding_RoundingTests.java |
471 | .weigher(new Weigher<KeySliceQuery, EntryList>() {
@Override
public int weigh(KeySliceQuery keySliceQuery, EntryList entries) {
return GUAVA_CACHE_ENTRY_SIZE + KEY_QUERY_SIZE + entries.getByteSize();
}
}); | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_cache_ExpirationKCVSCache.java |
562 | public class StaticLB implements LoadBalancer {
private final Member member;
public StaticLB(Member member) {
this.member = member;
}
@Override
public void init(Cluster cluster, ClientConfig config) {
}
@Override
public Member next() {
return member;
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_util_StaticLB.java |
3,438 | public static enum Stage {
NONE,
INDEX,
TRANSLOG,
FINALIZE,
DONE,
FAILURE
} | 0true
| src_main_java_org_elasticsearch_index_gateway_SnapshotStatus.java |
124 | {
@Override
public void checkOperation( OperationType operationType, File onFile, int bytesWrittenTotal,
int bytesWrittenThisCall, long channelPosition ) throws IOException
{
if ( !broken.get() && bytesWrittenTotal == 4 )
{
broken.set( true );
throw new IOException( "IOException after which this buffer should not be used" );
}
if ( broken.get() && channelPosition == 0 )
{
throw new IOException( "This exception should never happen" );
}
}
}; | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestDirectMappedLogBuffer.java |
3,726 | public class DynamicTemplate {
public static enum MatchType {
SIMPLE,
REGEX;
public static MatchType fromString(String value) {
if ("simple".equals(value)) {
return SIMPLE;
} else if ("regex".equals(value)) {
return REGEX;
}
throw new ElasticsearchIllegalArgumentException("No matching pattern matched on [" + value + "]");
}
}
public static DynamicTemplate parse(String name, Map<String, Object> conf) throws MapperParsingException {
String match = null;
String pathMatch = null;
String unmatch = null;
String pathUnmatch = null;
Map<String, Object> mapping = null;
String matchMappingType = null;
String matchPattern = "simple";
for (Map.Entry<String, Object> entry : conf.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
if ("match".equals(propName)) {
match = entry.getValue().toString();
} else if ("path_match".equals(propName)) {
pathMatch = entry.getValue().toString();
} else if ("unmatch".equals(propName)) {
unmatch = entry.getValue().toString();
} else if ("path_unmatch".equals(propName)) {
pathUnmatch = entry.getValue().toString();
} else if ("match_mapping_type".equals(propName)) {
matchMappingType = entry.getValue().toString();
} else if ("match_pattern".equals(propName)) {
matchPattern = entry.getValue().toString();
} else if ("mapping".equals(propName)) {
mapping = (Map<String, Object>) entry.getValue();
}
}
if (match == null && pathMatch == null && matchMappingType == null) {
throw new MapperParsingException("template must have match, path_match or match_mapping_type set");
}
if (mapping == null) {
throw new MapperParsingException("template must have mapping set");
}
return new DynamicTemplate(name, conf, pathMatch, pathUnmatch, match, unmatch, matchMappingType, MatchType.fromString(matchPattern), mapping);
}
private final String name;
private final Map<String, Object> conf;
private final String pathMatch;
private final String pathUnmatch;
private final String match;
private final String unmatch;
private final MatchType matchType;
private final String matchMappingType;
private final Map<String, Object> mapping;
public DynamicTemplate(String name, Map<String, Object> conf, String pathMatch, String pathUnmatch, String match, String unmatch, String matchMappingType, MatchType matchType, Map<String, Object> mapping) {
this.name = name;
this.conf = new TreeMap<String, Object>(conf);
this.pathMatch = pathMatch;
this.pathUnmatch = pathUnmatch;
this.match = match;
this.unmatch = unmatch;
this.matchType = matchType;
this.matchMappingType = matchMappingType;
this.mapping = mapping;
}
public String name() {
return this.name;
}
public Map<String, Object> conf() {
return this.conf;
}
public boolean match(ContentPath path, String name, String dynamicType) {
if (pathMatch != null && !patternMatch(pathMatch, path.fullPathAsText(name))) {
return false;
}
if (match != null && !patternMatch(match, name)) {
return false;
}
if (pathUnmatch != null && patternMatch(pathUnmatch, path.fullPathAsText(name))) {
return false;
}
if (unmatch != null && patternMatch(unmatch, name)) {
return false;
}
if (matchMappingType != null) {
if (dynamicType == null) {
return false;
}
if (!patternMatch(matchMappingType, dynamicType)) {
return false;
}
}
return true;
}
public boolean hasType() {
return mapping.containsKey("type");
}
public String mappingType(String dynamicType) {
return mapping.containsKey("type") ? mapping.get("type").toString() : dynamicType;
}
private boolean patternMatch(String pattern, String str) {
if (matchType == MatchType.SIMPLE) {
return Regex.simpleMatch(pattern, str);
}
return str.matches(pattern);
}
public Map<String, Object> mappingForName(String name, String dynamicType) {
return processMap(mapping, name, dynamicType);
}
private Map<String, Object> processMap(Map<String, Object> map, String name, String dynamicType) {
Map<String, Object> processedMap = Maps.newHashMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
Object value = entry.getValue();
if (value instanceof Map) {
value = processMap((Map<String, Object>) value, name, dynamicType);
} else if (value instanceof List) {
value = processList((List) value, name, dynamicType);
} else if (value instanceof String) {
value = value.toString().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
}
processedMap.put(key, value);
}
return processedMap;
}
private List processList(List list, String name, String dynamicType) {
List processedList = new ArrayList();
for (Object value : list) {
if (value instanceof Map) {
value = processMap((Map<String, Object>) value, name, dynamicType);
} else if (value instanceof List) {
value = processList((List) value, name, dynamicType);
} else if (value instanceof String) {
value = value.toString().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
}
processedList.add(value);
}
return processedList;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DynamicTemplate that = (DynamicTemplate) o;
// check if same matching, if so, replace the mapping
if (match != null ? !match.equals(that.match) : that.match != null) {
return false;
}
if (matchMappingType != null ? !matchMappingType.equals(that.matchMappingType) : that.matchMappingType != null) {
return false;
}
if (matchType != that.matchType) {
return false;
}
if (unmatch != null ? !unmatch.equals(that.unmatch) : that.unmatch != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
// check if same matching, if so, replace the mapping
int result = match != null ? match.hashCode() : 0;
result = 31 * result + (unmatch != null ? unmatch.hashCode() : 0);
result = 31 * result + (matchType != null ? matchType.hashCode() : 0);
result = 31 * result + (matchMappingType != null ? matchMappingType.hashCode() : 0);
return result;
}
} | 1no label
| src_main_java_org_elasticsearch_index_mapper_object_DynamicTemplate.java |
1,362 | @Entity
@Table(name = "BLC_CODE_TYPES")
@Inheritance(strategy=InheritanceType.JOINED)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@Deprecated
public class CodeTypeImpl implements CodeType {
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "CodeTypeId", strategy = GenerationType.TABLE)
@GenericGenerator(
name="CodeTypeId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="CodeTypeImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.util.domain.CodeTypeImpl")
}
)
@Column(name = "CODE_ID")
protected Long id;
@Column(name = "CODE_TYPE", nullable=false)
protected String codeType;
@Column(name = "CODE_KEY", nullable=false)
protected String key;
@Column(name = "CODE_DESC")
protected String description;
@Column(name = "MODIFIABLE")
protected Character modifiable;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getCodeType() {
return codeType;
}
@Override
public void setCodeType(String codeType) {
this.codeType = codeType;
}
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public Boolean isModifiable() {
if(modifiable == null)
return null;
return modifiable == 'Y' ? Boolean.TRUE : Boolean.FALSE;
}
@Override
public Boolean getModifiable() {
return isModifiable();
}
@Override
public void setModifiable(Boolean modifiable) {
if(modifiable == null) {
this.modifiable = null;
} else {
this.modifiable = modifiable ? 'Y' : 'N';
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((codeType == null) ? 0 : codeType.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result
+ ((modifiable == null) ? 0 : modifiable.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;
CodeTypeImpl other = (CodeTypeImpl) obj;
if (codeType == null) {
if (other.codeType != null)
return false;
} else if (!codeType.equals(other.codeType))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
if (modifiable == null) {
if (other.modifiable != null)
return false;
} else if (!modifiable.equals(other.modifiable))
return false;
return true;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_util_domain_CodeTypeImpl.java |
1,867 | class MembersInjectorImpl<T> implements MembersInjector<T> {
private final TypeLiteral<T> typeLiteral;
private final InjectorImpl injector;
private final ImmutableList<SingleMemberInjector> memberInjectors;
private final ImmutableList<MembersInjector<? super T>> userMembersInjectors;
private final ImmutableList<InjectionListener<? super T>> injectionListeners;
MembersInjectorImpl(InjectorImpl injector, TypeLiteral<T> typeLiteral,
EncounterImpl<T> encounter, ImmutableList<SingleMemberInjector> memberInjectors) {
this.injector = injector;
this.typeLiteral = typeLiteral;
this.memberInjectors = memberInjectors;
this.userMembersInjectors = encounter.getMembersInjectors();
this.injectionListeners = encounter.getInjectionListeners();
}
public ImmutableList<SingleMemberInjector> getMemberInjectors() {
return memberInjectors;
}
public void injectMembers(T instance) {
Errors errors = new Errors(typeLiteral);
try {
injectAndNotify(instance, errors);
} catch (ErrorsException e) {
errors.merge(e.getErrors());
}
errors.throwProvisionExceptionIfErrorsExist();
}
void injectAndNotify(final T instance, final Errors errors) throws ErrorsException {
if (instance == null) {
return;
}
injector.callInContext(new ContextualCallable<Void>() {
public Void call(InternalContext context) throws ErrorsException {
injectMembers(instance, errors, context);
return null;
}
});
notifyListeners(instance, errors);
}
void notifyListeners(T instance, Errors errors) throws ErrorsException {
int numErrorsBefore = errors.size();
for (InjectionListener<? super T> injectionListener : injectionListeners) {
try {
injectionListener.afterInjection(instance);
} catch (RuntimeException e) {
errors.errorNotifyingInjectionListener(injectionListener, typeLiteral, e);
}
}
errors.throwIfNewErrors(numErrorsBefore);
}
void injectMembers(T t, Errors errors, InternalContext context) {
// optimization: use manual for/each to save allocating an iterator here
for (int i = 0, size = memberInjectors.size(); i < size; i++) {
memberInjectors.get(i).inject(errors, context, t);
}
// optimization: use manual for/each to save allocating an iterator here
for (int i = 0, size = userMembersInjectors.size(); i < size; i++) {
MembersInjector<? super T> userMembersInjector = userMembersInjectors.get(i);
try {
userMembersInjector.injectMembers(t);
} catch (RuntimeException e) {
errors.errorInUserInjector(userMembersInjector, typeLiteral, e);
}
}
}
@Override
public String toString() {
return "MembersInjector<" + typeLiteral + ">";
}
public ImmutableSet<InjectionPoint> getInjectionPoints() {
ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder();
for (SingleMemberInjector memberInjector : memberInjectors) {
builder.add(memberInjector.getInjectionPoint());
}
return builder.build();
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_MembersInjectorImpl.java |
44 | abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
Node<K,V>[] tab; // same as Traverser
Node<K,V> next;
int index;
int baseIndex;
int baseLimit;
final int baseSize;
int batch; // split control
BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
super(par);
this.batch = b;
this.index = this.baseIndex = i;
if ((this.tab = t) == null)
this.baseSize = this.baseLimit = 0;
else if (par == null)
this.baseSize = this.baseLimit = t.length;
else {
this.baseLimit = f;
this.baseSize = par.baseSize;
}
}
/**
* Same as Traverser version
*/
final Node<K,V> advance() {
Node<K,V> e;
if ((e = next) != null)
e = e.next;
for (;;) {
Node<K,V>[] t; int i, n; K ek; // must use locals in checks
if (e != null)
return next = e;
if (baseIndex >= baseLimit || (t = tab) == null ||
(n = t.length) <= (i = index) || i < 0)
return next = null;
if ((e = tabAt(t, index)) != null && e.hash < 0) {
if (e instanceof ForwardingNode) {
tab = ((ForwardingNode<K,V>)e).nextTable;
e = null;
continue;
}
else if (e instanceof TreeBin)
e = ((TreeBin<K,V>)e).first;
else
e = null;
}
if ((index += baseSize) >= n)
index = ++baseIndex; // visit upper slots if present
}
}
} | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
1,817 | constructors[QUERY_RESULT_SET] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new QueryResultSet();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_map_MapDataSerializerHook.java |
1,031 | @SuppressWarnings("unchecked")
public class OCommandExecutorSQLCreateIndex extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest {
public static final String KEYWORD_CREATE = "CREATE";
public static final String KEYWORD_INDEX = "INDEX";
public static final String KEYWORD_ON = "ON";
private String indexName;
private OClass oClass;
private String[] fields;
private OClass.INDEX_TYPE indexType;
private OType[] keyTypes;
private byte serializerKeyId;
public OCommandExecutorSQLCreateIndex parse(final OCommandRequest iRequest) {
init((OCommandRequestText) iRequest);
final StringBuilder word = new StringBuilder();
int oldPos = 0;
int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_CREATE))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_CREATE + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_INDEX))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_INDEX + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, false);
if (pos == -1)
throw new OCommandSQLParsingException("Expected index name. Use " + getSyntax(), parserText, oldPos);
indexName = word.toString();
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Index type requested. Use " + getSyntax(), parserText, oldPos + 1);
if (word.toString().equals(KEYWORD_ON)) {
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Expected class name. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
oClass = findClass(word.toString());
if (oClass == null)
throw new OCommandExecutionException("Class " + word + " not found");
pos = parserTextUpperCase.indexOf(")");
if (pos == -1) {
throw new OCommandSQLParsingException("No right bracket found. Use " + getSyntax(), parserText, oldPos);
}
final String props = parserText.substring(oldPos, pos).trim().substring(1);
List<String> propList = new ArrayList<String>();
for (String propToIndex : props.trim().split("\\s*,\\s*")) {
checkMapIndexSpecifier(propToIndex, parserText, oldPos);
propList.add(propToIndex);
}
fields = new String[propList.size()];
propList.toArray(fields);
oldPos = pos + 1;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Index type requested. Use " + getSyntax(), parserText, oldPos + 1);
} else {
if (indexName.indexOf('.') > 0) {
final String[] parts = indexName.split("\\.");
oClass = findClass(parts[0]);
if (oClass == null)
throw new OCommandExecutionException("Class " + parts[0] + " not found");
fields = new String[] { parts[1] };
}
}
indexType = OClass.INDEX_TYPE.valueOf(word.toString());
if (indexType == null)
throw new OCommandSQLParsingException("Index type is null", parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos != -1 && !word.toString().equalsIgnoreCase("NULL")) {
final String typesString = parserTextUpperCase.substring(oldPos).trim();
if (word.toString().equalsIgnoreCase("RUNTIME")) {
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
serializerKeyId = Byte.parseByte(word.toString());
} else {
ArrayList<OType> keyTypeList = new ArrayList<OType>();
for (String typeName : typesString.split("\\s*,\\s*")) {
keyTypeList.add(OType.valueOf(typeName));
}
keyTypes = new OType[keyTypeList.size()];
keyTypeList.toArray(keyTypes);
if (fields != null && fields.length != 0 && fields.length != keyTypes.length) {
throw new OCommandSQLParsingException("Count of fields does not match with count of property types. " + "Fields: "
+ Arrays.toString(fields) + "; Types: " + Arrays.toString(keyTypes), parserText, oldPos);
}
}
}
return this;
}
private OClass findClass(String part) {
return getDatabase().getMetadata().getSchema().getClass(part);
}
/**
* Execute the CREATE INDEX.
*/
@SuppressWarnings("rawtypes")
public Object execute(final Map<Object, Object> iArgs) {
if (indexName == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final ODatabaseRecord database = getDatabase();
final OIndex<?> idx;
if (fields == null || fields.length == 0) {
if (keyTypes != null)
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new OSimpleKeyIndexDefinition(keyTypes), null, null);
else if (serializerKeyId != 0) {
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new ORuntimeKeyIndexDefinition(serializerKeyId), null, null);
} else
idx = database.getMetadata().getIndexManager().createIndex(indexName, indexType.toString(), null, null, null);
} else {
if (keyTypes == null || keyTypes.length == 0) {
idx = oClass.createIndex(indexName, indexType, fields);
} else {
final OIndexDefinition idxDef = OIndexDefinitionFactory.createIndexDefinition(oClass, Arrays.asList(fields),
Arrays.asList(keyTypes));
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.name(), idxDef, oClass.getPolymorphicClusterIds(), null);
}
}
if (idx != null)
return idx.getSize();
return null;
}
private void checkMapIndexSpecifier(final String fieldName, final String text, final int pos) {
final String[] fieldNameParts = fieldName.split("\\s+");
if (fieldNameParts.length == 1)
return;
if (fieldNameParts.length == 3) {
if ("by".equals(fieldNameParts[1].toLowerCase())) {
try {
OPropertyMapIndexDefinition.INDEX_BY.valueOf(fieldNameParts[2].toUpperCase());
} catch (IllegalArgumentException iae) {
throw new OCommandSQLParsingException("Illegal field name format, should be '<property> [by key|value]' but was '"
+ fieldName + "'", text, pos);
}
return;
}
throw new OCommandSQLParsingException("Illegal field name format, should be '<property> [by key|value]' but was '"
+ fieldName + "'", text, pos);
}
throw new OCommandSQLParsingException("Illegal field name format, should be '<property> [by key|value]' but was '" + fieldName
+ "'", text, pos);
}
@Override
public String getSyntax() {
return "CREATE INDEX <name> [ON <class-name> (prop-names [COLLATE <collate>])] <type> [<key-type>]";
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLCreateIndex.java |
203 | public class OServerAdmin {
private OStorageRemote storage;
private int sessionId = -1;
/**
* Creates the object passing a remote URL to connect.
*
* @param iURL
* URL to connect. It supports only the "remote" storage type.
* @throws IOException
*/
public OServerAdmin(String iURL) throws IOException {
if (iURL.startsWith(OEngineRemote.NAME))
iURL = iURL.substring(OEngineRemote.NAME.length() + 1);
if (!iURL.contains("/"))
iURL += "/";
storage = new OStorageRemote(null, iURL, "");
}
/**
* Creates the object starting from an existent remote storage.
*
* @param iStorage
*/
public OServerAdmin(final OStorageRemote iStorage) {
storage = iStorage;
}
/**
* Connects to a remote server.
*
* @param iUserName
* Server's user name
* @param iUserPassword
* Server's password for the user name used
* @return The instance itself. Useful to execute method in chain
* @throws IOException
*/
public synchronized OServerAdmin connect(final String iUserName, final String iUserPassword) throws IOException {
storage.createConnectionPool();
storage.setSessionId(null, -1);
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_CONNECT);
storage.sendClientInfo(network);
try {
network.writeString(iUserName);
network.writeString(iUserPassword);
} finally {
storage.endRequest(network);
}
try {
storage.beginResponse(network);
sessionId = network.readInt();
storage.setSessionId(network.getServerURL(), sessionId);
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot connect to the remote server: " + storage.getName(), e, OStorageException.class);
storage.close(true);
}
return this;
}
/**
* List the databases on a remote server.
*
* @param iUserName
* Server's user name
* @param iUserPassword
* Server's password for the user name used
* @return The instance itself. Useful to execute method in chain
* @throws IOException
*/
@SuppressWarnings("unchecked")
public synchronized Map<String, String> listDatabases() throws IOException {
storage.checkConnection();
final ODocument result = new ODocument();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_LIST);
storage.endRequest(network);
try {
storage.beginResponse(network);
result.fromStream(network.readBytes());
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().exception("Cannot retrieve the configuration list", e, OStorageException.class);
storage.close(true);
}
return (Map<String, String>) result.field("databases");
}
public int getSessionId() {
return sessionId;
}
/**
* Deprecated. Use the {@link #createDatabase(String, String)} instead.
*/
@Deprecated
public synchronized OServerAdmin createDatabase(final String iStorageMode) throws IOException {
return createDatabase("document", iStorageMode);
}
/**
* Creates a database in a remote server.
*
* @param iDatabaseType
* 'document' or 'graph'
* @param iStorageMode
* local or memory
* @return The instance itself. Useful to execute method in chain
* @throws IOException
*/
public synchronized OServerAdmin createDatabase(final String iDatabaseType, String iStorageMode) throws IOException {
return createDatabase(storage.getName(), iDatabaseType, iStorageMode);
}
/**
* Creates a database in a remote server.
*
* @param iDatabaseName
* The database name
* @param iDatabaseType
* 'document' or 'graph'
* @param iStorageMode
* local or memory
* @return The instance itself. Useful to execute method in chain
* @throws IOException
*/
public synchronized OServerAdmin createDatabase(final String iDatabaseName, final String iDatabaseType, String iStorageMode)
throws IOException {
storage.checkConnection();
try {
if (iDatabaseName == null || iDatabaseName.length() <= 0) {
OLogManager.instance().error(this, "Cannot create unnamed remote storage. Check your syntax", OStorageException.class);
} else {
if (iStorageMode == null)
iStorageMode = "csv";
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_CREATE);
try {
network.writeString(iDatabaseName);
if (network.getSrvProtocolVersion() >= 8)
network.writeString(iDatabaseType);
network.writeString(iStorageMode);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
}
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot create the remote storage: " + storage.getName(), e, OStorageException.class);
storage.close(true);
}
return this;
}
/**
* Checks if a database exists in the remote server.
*
* @return true if exists, otherwise false
* @throws IOException
* @param storageType
*/
public synchronized boolean existsDatabase(String storageType) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_EXIST);
try {
network.writeString(storage.getName());
network.writeString(storageType);
} finally {
storage.endRequest(network);
}
try {
storage.beginResponse(network);
return network.readByte() == 1;
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().exception("Error on checking existence of the remote storage: " + storage.getName(), e,
OStorageException.class);
storage.close(true);
}
return false;
}
/**
* Deprecated. Use dropDatabase() instead.
*
* @return The instance itself. Useful to execute method in chain
* @see #dropDatabase(String)
* @throws IOException
* @param storageType
* Type of storage of server database.
*/
@Deprecated
public OServerAdmin deleteDatabase(String storageType) throws IOException {
return dropDatabase(storageType);
}
/**
* Drops a database from a remote server instance.
*
* @return The instance itself. Useful to execute method in chain
* @throws IOException
* @param storageType
*/
public synchronized OServerAdmin dropDatabase(String storageType) throws IOException {
storage.checkConnection();
boolean retry = true;
while (retry)
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_DROP);
try {
network.writeString(storage.getName());
network.writeString(storageType);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
retry = false;
} catch (OModificationOperationProhibitedException oope) {
retry = handleDBFreeze();
} catch (Exception e) {
OLogManager.instance().exception("Cannot delete the remote storage: " + storage.getName(), e, OStorageException.class);
}
for (OStorage s : Orient.instance().getStorages()) {
if (s.getURL().startsWith(getURL())) {
s.removeResource(OSchema.class.getSimpleName());
s.removeResource(OIndexManager.class.getSimpleName());
s.removeResource(OSecurity.class.getSimpleName());
}
}
ODatabaseRecordThreadLocal.INSTANCE.set(null);
return this;
}
private boolean handleDBFreeze() {
boolean retry;
OLogManager.instance().warn(this,
"DB is frozen will wait for " + OGlobalConfiguration.CLIENT_DB_RELEASE_WAIT_TIMEOUT.getValue() + " ms. and then retry.");
retry = true;
try {
Thread.sleep(OGlobalConfiguration.CLIENT_DB_RELEASE_WAIT_TIMEOUT.getValueAsInteger());
} catch (InterruptedException ie) {
retry = false;
Thread.currentThread().interrupt();
}
return retry;
}
public synchronized OServerAdmin freezeDatabase(String storageType) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_FREEZE);
try {
network.writeString(storage.getName());
network.writeString(storageType);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
} catch (Exception e) {
OLogManager.instance().exception("Cannot freeze the remote storage: " + storage.getName(), e, OStorageException.class);
}
return this;
}
public synchronized OServerAdmin releaseDatabase(String storageType) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_RELEASE);
try {
network.writeString(storage.getName());
network.writeString(storageType);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
} catch (Exception e) {
OLogManager.instance().exception("Cannot release the remote storage: " + storage.getName(), e, OStorageException.class);
}
return this;
}
public synchronized OServerAdmin freezeCluster(int clusterId, String storageType) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE);
try {
network.writeString(storage.getName());
network.writeShort((short) clusterId);
network.writeString(storageType);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
OLogManager.instance().exception("Cannot freeze the remote cluster " + clusterId + " on storage: " + storage.getName(), e,
OStorageException.class);
}
return this;
}
public synchronized OServerAdmin releaseCluster(int clusterId, String storageType) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE);
try {
network.writeString(storage.getName());
network.writeShort((short) clusterId);
network.writeString(storageType);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
OLogManager.instance().exception("Cannot release the remote cluster " + clusterId + " on storage: " + storage.getName(), e,
OStorageException.class);
}
return this;
}
/**
* Gets the cluster status.
*
* @return the JSON containing the current cluster structure
*/
public ODocument clusterStatus() {
final ODocument response = sendRequest(OChannelBinaryProtocol.REQUEST_CLUSTER, new ODocument().field("operation", "status"),
"Cluster status");
OLogManager.instance().debug(this, "Cluster status %s", response.toJSON("prettyPrint"));
return response;
}
/**
* Copies a database to a remote server instance.
*
* @param iDatabaseName
* @param iDatabaseUserName
* @param iDatabaseUserPassword
* @param iRemoteName
* @param iRemoteEngine
* @return The instance itself. Useful to execute method in chain
* @throws IOException
*/
public synchronized OServerAdmin copyDatabase(final String iDatabaseName, final String iDatabaseUserName,
final String iDatabaseUserPassword, final String iRemoteName, final String iRemoteEngine) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_COPY);
try {
network.writeString(iDatabaseName);
network.writeString(iDatabaseUserName);
network.writeString(iDatabaseUserPassword);
network.writeString(iRemoteName);
network.writeString(iRemoteEngine);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
OLogManager.instance().debug(this, "Database '%s' has been copied to the server '%s'", iDatabaseName, iRemoteName);
} catch (Exception e) {
OLogManager.instance().exception("Cannot copy the database: " + iDatabaseName, e, OStorageException.class);
}
return this;
}
public synchronized Map<String, String> getGlobalConfigurations() throws IOException {
storage.checkConnection();
final Map<String, String> config = new HashMap<String, String>();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_CONFIG_LIST);
storage.endRequest(network);
try {
storage.beginResponse(network);
final int num = network.readShort();
for (int i = 0; i < num; ++i)
config.put(network.readString(), network.readString());
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().exception("Cannot retrieve the configuration list", e, OStorageException.class);
storage.close(true);
}
return config;
}
public synchronized String getGlobalConfiguration(final OGlobalConfiguration iConfig) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_CONFIG_GET);
network.writeString(iConfig.getKey());
try {
storage.beginResponse(network);
return network.readString();
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().exception("Cannot retrieve the configuration value: " + iConfig.getKey(), e, OStorageException.class);
storage.close(true);
}
return null;
}
public synchronized OServerAdmin setGlobalConfiguration(final OGlobalConfiguration iConfig, final Object iValue)
throws IOException {
storage.checkConnection();
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_CONFIG_SET);
network.writeString(iConfig.getKey());
network.writeString(iValue != null ? iValue.toString() : "");
storage.getResponse(network);
} catch (Exception e) {
OLogManager.instance().exception("Cannot set the configuration value: " + iConfig.getKey(), e, OStorageException.class);
storage.close(true);
}
return this;
}
/**
* Close the connection if open.
*/
public synchronized void close() {
storage.close();
}
public synchronized void close(boolean iForce) {
storage.close(iForce);
}
public synchronized String getURL() {
return storage != null ? storage.getURL() : null;
}
protected ODocument sendRequest(final byte iRequest, final ODocument iPayLoad, final String iActivity) {
boolean retry = true;
while (retry)
try {
final OChannelBinaryAsynchClient network = storage.beginRequest(iRequest);
try {
network.writeBytes(iPayLoad.toStream());
} finally {
storage.endRequest(network);
}
retry = false;
try {
storage.beginResponse(network);
return new ODocument(network.readBytes());
} finally {
storage.endResponse(network);
}
} catch (OModificationOperationProhibitedException ompe) {
retry = handleDBFreeze();
} catch (Exception e) {
OLogManager.instance().exception("Error on executing '%s'", e, OStorageException.class, iActivity);
}
return null;
}
public boolean isConnected() {
return storage != null && !storage.isClosed();
}
} | 0true
| client_src_main_java_com_orientechnologies_orient_client_remote_OServerAdmin.java |
912 | final Object myValue = makeDbCall(iMyDb, new ODbRelatedCall<Object>() {
public Object call() {
return myEntry.getValue();
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
1,670 | runnable = new Runnable() { public void run() { map.put("key", null); } }; | 0true
| hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java |
3,396 | public class SortedSetDVBytesIndexFieldData extends DocValuesIndexFieldData implements IndexFieldData.WithOrdinals<SortedSetDVBytesAtomicFieldData> {
public SortedSetDVBytesIndexFieldData(Index index, Names fieldNames) {
super(index, fieldNames);
}
@Override
public boolean valuesOrdered() {
return true;
}
public org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource comparatorSource(Object missingValue, SortMode sortMode) {
return new BytesRefFieldComparatorSource((IndexFieldData<?>) this, missingValue, sortMode);
}
@Override
public SortedSetDVBytesAtomicFieldData load(AtomicReaderContext context) {
return new SortedSetDVBytesAtomicFieldData(context.reader(), fieldNames.indexName());
}
@Override
public SortedSetDVBytesAtomicFieldData loadDirect(AtomicReaderContext context) throws Exception {
return load(context);
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_SortedSetDVBytesIndexFieldData.java |
5,878 | public class QueryPhase implements SearchPhase {
private final FacetPhase facetPhase;
private final AggregationPhase aggregationPhase;
private final SuggestPhase suggestPhase;
private RescorePhase rescorePhase;
@Inject
public QueryPhase(FacetPhase facetPhase, AggregationPhase aggregationPhase, SuggestPhase suggestPhase, RescorePhase rescorePhase) {
this.facetPhase = facetPhase;
this.aggregationPhase = aggregationPhase;
this.suggestPhase = suggestPhase;
this.rescorePhase = rescorePhase;
}
@Override
public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder();
parseElements.put("from", new FromParseElement()).put("size", new SizeParseElement())
.put("indices_boost", new IndicesBoostParseElement())
.put("indicesBoost", new IndicesBoostParseElement())
.put("query", new QueryParseElement())
.put("queryBinary", new QueryBinaryParseElement())
.put("query_binary", new QueryBinaryParseElement())
.put("filter", new PostFilterParseElement()) // For bw comp reason, should be removed in version 1.1
.put("post_filter", new PostFilterParseElement())
.put("postFilter", new PostFilterParseElement())
.put("filterBinary", new FilterBinaryParseElement())
.put("filter_binary", new FilterBinaryParseElement())
.put("sort", new SortParseElement())
.put("trackScores", new TrackScoresParseElement())
.put("track_scores", new TrackScoresParseElement())
.put("min_score", new MinScoreParseElement())
.put("minScore", new MinScoreParseElement())
.put("timeout", new TimeoutParseElement())
.putAll(facetPhase.parseElements())
.putAll(aggregationPhase.parseElements())
.putAll(suggestPhase.parseElements())
.putAll(rescorePhase.parseElements());
return parseElements.build();
}
@Override
public void preProcess(SearchContext context) {
context.preProcess();
facetPhase.preProcess(context);
aggregationPhase.preProcess(context);
}
public void execute(SearchContext searchContext) throws QueryPhaseExecutionException {
searchContext.queryResult().searchTimedOut(false);
searchContext.searcher().inStage(ContextIndexSearcher.Stage.MAIN_QUERY);
boolean rescore = false;
try {
searchContext.queryResult().from(searchContext.from());
searchContext.queryResult().size(searchContext.size());
Query query = searchContext.query();
TopDocs topDocs;
int numDocs = searchContext.from() + searchContext.size();
if (searchContext.searchType() == SearchType.COUNT || numDocs == 0) {
TotalHitCountCollector collector = new TotalHitCountCollector();
searchContext.searcher().search(query, collector);
topDocs = new TopDocs(collector.getTotalHits(), Lucene.EMPTY_SCORE_DOCS, 0);
} else if (searchContext.searchType() == SearchType.SCAN) {
topDocs = searchContext.scanContext().execute(searchContext);
} else if (searchContext.sort() != null) {
topDocs = searchContext.searcher().search(query, null, numDocs, searchContext.sort(),
searchContext.trackScores(), searchContext.trackScores());
} else {
rescore = !searchContext.rescore().isEmpty();
for (RescoreSearchContext rescoreContext : searchContext.rescore()) {
numDocs = Math.max(rescoreContext.window(), numDocs);
}
topDocs = searchContext.searcher().search(query, numDocs);
}
searchContext.queryResult().topDocs(topDocs);
} catch (Throwable e) {
throw new QueryPhaseExecutionException(searchContext, "Failed to execute main query", e);
} finally {
searchContext.searcher().finishStage(ContextIndexSearcher.Stage.MAIN_QUERY);
}
if (rescore) { // only if we do a regular search
rescorePhase.execute(searchContext);
}
suggestPhase.execute(searchContext);
facetPhase.execute(searchContext);
aggregationPhase.execute(searchContext);
}
} | 1no label
| src_main_java_org_elasticsearch_search_query_QueryPhase.java |
1,613 | private static class LocalNodeMasterListeners implements ClusterStateListener {
private final List<LocalNodeMasterListener> listeners = new CopyOnWriteArrayList<LocalNodeMasterListener>();
private final ThreadPool threadPool;
private volatile boolean master = false;
private LocalNodeMasterListeners(ThreadPool threadPool) {
this.threadPool = threadPool;
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
if (!master && event.localNodeMaster()) {
master = true;
for (LocalNodeMasterListener listener : listeners) {
Executor executor = threadPool.executor(listener.executorName());
executor.execute(new OnMasterRunnable(listener));
}
return;
}
if (master && !event.localNodeMaster()) {
master = false;
for (LocalNodeMasterListener listener : listeners) {
Executor executor = threadPool.executor(listener.executorName());
executor.execute(new OffMasterRunnable(listener));
}
}
}
private void add(LocalNodeMasterListener listener) {
listeners.add(listener);
}
private void remove(LocalNodeMasterListener listener) {
listeners.remove(listener);
}
private void clear() {
listeners.clear();
}
} | 0true
| src_main_java_org_elasticsearch_cluster_service_InternalClusterService.java |
24 | public class LogMatchers
{
public static List<LogEntry> logEntries( FileSystemAbstraction fileSystem, String logPath ) throws IOException
{
StoreChannel fileChannel = fileSystem.open( new File( logPath ), "r" );
ByteBuffer buffer = ByteBuffer.allocateDirect( 9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10 );
try
{
// Always a header
LogIoUtils.readLogHeader( buffer, fileChannel, true );
// Read all log entries
List<LogEntry> entries = new ArrayList<LogEntry>();
DumpLogicalLog.CommandFactory cmdFactory = new DumpLogicalLog.CommandFactory();
LogEntry entry;
while ( (entry = LogIoUtils.readEntry( buffer, fileChannel, cmdFactory )) != null )
{
entries.add( entry );
}
return entries;
}
finally
{
fileChannel.close();
}
}
public static List<LogEntry> logEntries( FileSystemAbstraction fileSystem, File file ) throws IOException
{
return logEntries( fileSystem, file.getPath() );
}
public static Matcher<Iterable<LogEntry>> containsExactly( final Matcher<? extends LogEntry>... matchers )
{
return new TypeSafeMatcher<Iterable<LogEntry>>()
{
@Override
public boolean matchesSafely( Iterable<LogEntry> item )
{
Iterator<LogEntry> actualEntries = item.iterator();
for ( Matcher<? extends LogEntry> matcher : matchers )
{
if ( actualEntries.hasNext() )
{
LogEntry next = actualEntries.next();
if ( !matcher.matches( next ) )
{
// Wrong!
return false;
}
}
else
{
// Too few actual entries!
return false;
}
}
if ( actualEntries.hasNext() )
{
// Too many actual entries!
return false;
}
// All good in the hood :)
return true;
}
@Override
public void describeTo( Description description )
{
for ( Matcher<? extends LogEntry> matcher : matchers )
{
description.appendDescriptionOf( matcher ).appendText( ",\n" );
}
}
};
}
public static Matcher<? extends LogEntry> startEntry( final Integer identifier, final int masterId,
final int localId )
{
return new TypeSafeMatcher<LogEntry.Start>()
{
@Override
public boolean matchesSafely( LogEntry.Start entry )
{
return entry != null && entry.getIdentifier() == identifier && entry.getMasterId() == masterId
&& entry.getLocalId() == localId;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Start[" + identifier + ",xid=<Any Xid>,master=" + masterId + ",me=" + localId
+ ",time=<Any Date>]" );
}
};
}
public static Matcher<? extends LogEntry> onePhaseCommitEntry( final int identifier, final int txId )
{
return new TypeSafeMatcher<LogEntry.OnePhaseCommit>()
{
@Override
public boolean matchesSafely( LogEntry.OnePhaseCommit onePC )
{
return onePC != null && onePC.getIdentifier() == identifier && onePC.getTxId() == txId;
}
@Override
public void describeTo( Description description )
{
description.appendText( String.format( "1PC[%d, txId=%d, <Any Date>],", identifier, txId ) );
}
};
}
public static Matcher<? extends LogEntry> doneEntry( final int identifier )
{
return new TypeSafeMatcher<LogEntry.Done>()
{
@Override
public boolean matchesSafely( LogEntry.Done done )
{
return done != null && done.getIdentifier() == identifier;
}
@Override
public void describeTo( Description description )
{
description.appendText( String.format( "Done[%d]", identifier ) );
}
};
}
} | 1no label
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_LogMatchers.java |
3,015 | public class QueryParserCacheModule extends AbstractModule {
private final Settings settings;
public QueryParserCacheModule(Settings settings) {
this.settings = settings;
}
@Override
protected void configure() {
bind(QueryParserCache.class)
.to(settings.getAsClass("index.cache.query.parser.type", ResidentQueryParserCache.class, "org.elasticsearch.index.cache.query.parser.", "QueryParserCache"))
.in(Scopes.SINGLETON);
}
} | 0true
| src_main_java_org_elasticsearch_index_cache_query_parser_QueryParserCacheModule.java |
1,482 | public abstract class OSQLFunctionPathFinder<T extends Comparable<T>> extends OSQLFunctionMathAbstract {
protected OrientBaseGraph db;
protected Set<Vertex> settledNodes;
protected Set<Vertex> unSettledNodes;
protected Map<Vertex, Vertex> predecessors;
protected Map<Vertex, T> distance;
protected Vertex paramSourceVertex;
protected Vertex paramDestinationVertex;
protected Direction paramDirection = Direction.OUT;
public OSQLFunctionPathFinder(final String iName, final int iMinParams, final int iMaxParams) {
super(iName, iMinParams, iMaxParams);
}
protected abstract T getDistance(Vertex node, Vertex target);
protected abstract T getShortestDistance(Vertex destination);
protected abstract T getMinimumDistance();
protected abstract T sumDistances(T iDistance1, T iDistance2);
public Object execute(final Object[] iParameters, final OCommandContext iContext) {
settledNodes = new HashSet<Vertex>();
unSettledNodes = new HashSet<Vertex>();
distance = new HashMap<Vertex, T>();
predecessors = new HashMap<Vertex, Vertex>();
distance.put(paramSourceVertex, getMinimumDistance());
unSettledNodes.add(paramSourceVertex);
while (continueTraversing()) {
final Vertex node = getMinimum(unSettledNodes);
settledNodes.add(node);
unSettledNodes.remove(node);
findMinimalDistances(node);
}
return getPath();
}
/*
* This method returns the path from the source to the selected target and NULL if no path exists
*/
public LinkedList<Vertex> getPath() {
final LinkedList<Vertex> path = new LinkedList<Vertex>();
Vertex step = paramDestinationVertex;
// Check if a path exists
if (predecessors.get(step) == null)
return null;
path.add(step);
while (predecessors.get(step) != null) {
step = predecessors.get(step);
path.add(step);
}
// Put it into the correct order
Collections.reverse(path);
return path;
}
public boolean aggregateResults() {
return false;
}
@Override
public Object getResult() {
return getPath();
}
protected void findMinimalDistances(final Vertex node) {
final List<Vertex> adjacentNodes = getNeighbors(node);
for (Vertex target : adjacentNodes) {
final T d = sumDistances(getShortestDistance(node), getDistance(node, target));
if (getShortestDistance(target).compareTo(d) > 0) {
distance.put(target, d);
predecessors.put(target, node);
unSettledNodes.add(target);
}
}
}
protected List<Vertex> getNeighbors(final Vertex node) {
final List<Vertex> neighbors = new ArrayList<Vertex>();
if (node != null) {
for (Vertex v : node.getVertices(paramDirection))
if (v != null && !isSettled(v))
neighbors.add(v);
}
return neighbors;
}
protected Vertex getMinimum(final Set<Vertex> vertexes) {
Vertex minimum = null;
for (Vertex vertex : vertexes) {
if (minimum == null || getShortestDistance(vertex).compareTo(getShortestDistance(minimum)) < 0)
minimum = vertex;
}
return minimum;
}
protected boolean isSettled(final Vertex vertex) {
return settledNodes.contains(vertex.getId());
}
protected boolean continueTraversing() {
return unSettledNodes.size() > 0;
}
} | 1no label
| graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionPathFinder.java |
1,399 | public class MetaDataDeleteIndexService extends AbstractComponent {
private final ThreadPool threadPool;
private final ClusterService clusterService;
private final AllocationService allocationService;
private final NodeIndexDeletedAction nodeIndexDeletedAction;
private final MetaDataService metaDataService;
@Inject
public MetaDataDeleteIndexService(Settings settings, ThreadPool threadPool, ClusterService clusterService, AllocationService allocationService,
NodeIndexDeletedAction nodeIndexDeletedAction, MetaDataService metaDataService) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.allocationService = allocationService;
this.nodeIndexDeletedAction = nodeIndexDeletedAction;
this.metaDataService = metaDataService;
}
public void deleteIndex(final Request request, final Listener userListener) {
// we lock here, and not within the cluster service callback since we don't want to
// block the whole cluster state handling
final Semaphore mdLock = metaDataService.indexMetaDataLock(request.index);
// quick check to see if we can acquire a lock, otherwise spawn to a thread pool
if (mdLock.tryAcquire()) {
deleteIndex(request, userListener, mdLock);
return;
}
threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() {
@Override
public void run() {
try {
if (!mdLock.tryAcquire(request.masterTimeout.nanos(), TimeUnit.NANOSECONDS)) {
userListener.onFailure(new ProcessClusterEventTimeoutException(request.masterTimeout, "acquire index lock"));
return;
}
} catch (InterruptedException e) {
userListener.onFailure(e);
return;
}
deleteIndex(request, userListener, mdLock);
}
});
}
private void deleteIndex(final Request request, final Listener userListener, Semaphore mdLock) {
final DeleteIndexListener listener = new DeleteIndexListener(mdLock, userListener);
clusterService.submitStateUpdateTask("delete-index [" + request.index + "]", Priority.URGENT, new TimeoutClusterStateUpdateTask() {
@Override
public TimeValue timeout() {
return request.masterTimeout;
}
@Override
public void onFailure(String source, Throwable t) {
listener.onFailure(t);
}
@Override
public ClusterState execute(final ClusterState currentState) {
if (!currentState.metaData().hasConcreteIndex(request.index)) {
throw new IndexMissingException(new Index(request.index));
}
logger.info("[{}] deleting index", request.index);
RoutingTable.Builder routingTableBuilder = RoutingTable.builder(currentState.routingTable());
routingTableBuilder.remove(request.index);
MetaData newMetaData = MetaData.builder(currentState.metaData())
.remove(request.index)
.build();
RoutingAllocation.Result routingResult = allocationService.reroute(
ClusterState.builder(currentState).routingTable(routingTableBuilder).metaData(newMetaData).build());
ClusterBlocks blocks = ClusterBlocks.builder().blocks(currentState.blocks()).removeIndexBlocks(request.index).build();
// wait for events from all nodes that it has been removed from their respective metadata...
int count = currentState.nodes().size();
// add the notifications that the store was deleted from *data* nodes
count += currentState.nodes().dataNodes().size();
final AtomicInteger counter = new AtomicInteger(count);
// this listener will be notified once we get back a notification based on the cluster state change below.
final NodeIndexDeletedAction.Listener nodeIndexDeleteListener = new NodeIndexDeletedAction.Listener() {
@Override
public void onNodeIndexDeleted(String index, String nodeId) {
if (index.equals(request.index)) {
if (counter.decrementAndGet() == 0) {
listener.onResponse(new Response(true));
nodeIndexDeletedAction.remove(this);
}
}
}
@Override
public void onNodeIndexStoreDeleted(String index, String nodeId) {
if (index.equals(request.index)) {
if (counter.decrementAndGet() == 0) {
listener.onResponse(new Response(true));
nodeIndexDeletedAction.remove(this);
}
}
}
};
nodeIndexDeletedAction.add(nodeIndexDeleteListener);
listener.future = threadPool.schedule(request.timeout, ThreadPool.Names.SAME, new Runnable() {
@Override
public void run() {
listener.onResponse(new Response(false));
nodeIndexDeletedAction.remove(nodeIndexDeleteListener);
}
});
return ClusterState.builder(currentState).routingResult(routingResult).metaData(newMetaData).blocks(blocks).build();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
});
}
class DeleteIndexListener implements Listener {
private final AtomicBoolean notified = new AtomicBoolean();
private final Semaphore mdLock;
private final Listener listener;
volatile ScheduledFuture<?> future;
private DeleteIndexListener(Semaphore mdLock, Listener listener) {
this.mdLock = mdLock;
this.listener = listener;
}
@Override
public void onResponse(final Response response) {
if (notified.compareAndSet(false, true)) {
mdLock.release();
if (future != null) {
future.cancel(false);
}
listener.onResponse(response);
}
}
@Override
public void onFailure(Throwable t) {
if (notified.compareAndSet(false, true)) {
mdLock.release();
if (future != null) {
future.cancel(false);
}
listener.onFailure(t);
}
}
}
public static interface Listener {
void onResponse(Response response);
void onFailure(Throwable t);
}
public static class Request {
final String index;
TimeValue timeout = TimeValue.timeValueSeconds(10);
TimeValue masterTimeout = MasterNodeOperationRequest.DEFAULT_MASTER_NODE_TIMEOUT;
public Request(String index) {
this.index = index;
}
public Request timeout(TimeValue timeout) {
this.timeout = timeout;
return this;
}
public Request masterTimeout(TimeValue masterTimeout) {
this.masterTimeout = masterTimeout;
return this;
}
}
public static class Response {
private final boolean acknowledged;
public Response(boolean acknowledged) {
this.acknowledged = acknowledged;
}
public boolean acknowledged() {
return acknowledged;
}
}
} | 0true
| src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java |
1,126 | public class NativeConstantScoreScript extends AbstractSearchScript {
public static final String NATIVE_CONSTANT_SCRIPT_SCORE = "native_constant_script_score";
public static class Factory implements NativeScriptFactory {
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
return new NativeConstantScoreScript();
}
}
private NativeConstantScoreScript() {
}
@Override
public Object run() {
return 2;
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_scripts_score_script_NativeConstantScoreScript.java |
338 | static class Deal implements Serializable {
Integer id;
Deal(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java |
566 | public class AuthorizationOperation extends AbstractOperation implements JoinOperation {
private String groupName;
private String groupPassword;
private Boolean response = Boolean.TRUE;
public AuthorizationOperation() {
}
public AuthorizationOperation(String groupName, String groupPassword) {
this.groupName = groupName;
this.groupPassword = groupPassword;
}
@Override
public void run() {
GroupConfig groupConfig = getNodeEngine().getConfig().getGroupConfig();
if (!groupName.equals(groupConfig.getName())) {
response = Boolean.FALSE;
} else if (!groupPassword.equals(groupConfig.getPassword())) {
response = Boolean.FALSE;
}
}
@Override
public Object getResponse() {
return response;
}
@Override
public boolean returnsResponse() {
return true;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
groupName = in.readUTF();
groupPassword = in.readUTF();
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
out.writeUTF(groupName);
out.writeUTF(groupPassword);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_cluster_AuthorizationOperation.java |
382 | public class ClusterRerouteResponse extends AcknowledgedResponse {
private ClusterState state;
ClusterRerouteResponse() {
}
ClusterRerouteResponse(boolean acknowledged, ClusterState state) {
super(acknowledged);
this.state = state;
}
/**
* Returns the cluster state resulted from the cluster reroute request execution
*/
public ClusterState getState() {
return this.state;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
state = ClusterState.Builder.readFrom(in, null);
readAcknowledged(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
ClusterState.Builder.writeTo(state, out);
writeAcknowledged(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_reroute_ClusterRerouteResponse.java |
152 | return getGlobalConfiguration(new BackendOperation.TransactionalProvider() {
@Override
public StoreTransaction openTx() throws BackendException {
return manager.beginTransaction(StandardBaseTransactionConfig.of(config.get(TIMESTAMP_PROVIDER),features.getKeyConsistentTxConfig()));
}
@Override
public void close() throws BackendException {
manager.close();
}
},manager.openDatabase(SYSTEM_PROPERTIES_STORE_NAME),config); | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java |
129 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientServiceTest extends HazelcastTestSupport {
@Before
@After
public void cleanup() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testConnectedClients() {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final HazelcastInstance client1 = HazelcastClient.newHazelcastClient();
final HazelcastInstance client2 = HazelcastClient.newHazelcastClient();
final ClientService clientService = instance.getClientService();
final Collection<Client> connectedClients = clientService.getConnectedClients();
assertEquals(2, connectedClients.size());
final String uuid1 = client1.getLocalEndpoint().getUuid();
final String uuid2 = client2.getLocalEndpoint().getUuid();
for (Client connectedClient : connectedClients) {
final String uuid = connectedClient.getUuid();
assertTrue(uuid.equals(uuid1) || uuid.equals(uuid2));
}
}
@Test
public void testClientListener() throws InterruptedException {
final HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final ClientService clientService = instance.getClientService();
final CountDownLatch latchAdd = new CountDownLatch(2);
final CountDownLatch latchRemove = new CountDownLatch(2);
final AtomicInteger totalAdd = new AtomicInteger(0);
final ClientListener clientListener = new ClientListener() {
@Override
public void clientConnected(Client client) {
totalAdd.incrementAndGet();
latchAdd.countDown();
}
@Override
public void clientDisconnected(Client client) {
latchRemove.countDown();
}
};
final String id = clientService.addClientListener(clientListener);
final HazelcastInstance client1 = HazelcastClient.newHazelcastClient();
final HazelcastInstance client2 = HazelcastClient.newHazelcastClient();
client1.getLifecycleService().shutdown();
client2.getLifecycleService().shutdown();
assertTrue(latchAdd.await(6, TimeUnit.SECONDS));
assertTrue(latchRemove.await(6, TimeUnit.SECONDS));
assertTrue(clientService.removeClientListener(id));
assertFalse(clientService.removeClientListener("foo"));
assertEquals(0, clientService.getConnectedClients().size());
final HazelcastInstance client3 = HazelcastClient.newHazelcastClient();
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, clientService.getConnectedClients().size());
}
}, 4);
assertEquals(2, totalAdd.get());
}
@Test
public void testClientListenerForBothNodes(){
final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
final ClientListenerLatch clientListenerLatch = new ClientListenerLatch(2);
final ClientService clientService1 = instance1.getClientService();
clientService1.addClientListener(clientListenerLatch);
final ClientService clientService2 = instance2.getClientService();
clientService2.addClientListener(clientListenerLatch);
final HazelcastInstance client = HazelcastClient.newHazelcastClient();
final String instance1Key = generateKeyOwnedBy(instance1);
final String instance2Key = generateKeyOwnedBy(instance2);
final IMap<Object, Object> map = client.getMap("map");
map.put(instance1Key, 0);
map.put(instance2Key, 0);
assertClientConnected(clientService1, clientService2);
assertOpenEventually(clientListenerLatch, 5);
}
private void assertClientConnected(ClientService... services){
for (final ClientService service : services) {
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, service.getConnectedClients().size());
}
}, 5);
}
}
public static class ClientListenerLatch extends CountDownLatch implements ClientListener {
public ClientListenerLatch(int count) {
super(count);
}
@Override
public void clientConnected(Client client) {
countDown();
}
@Override
public void clientDisconnected(Client client) {
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_ClientServiceTest.java |
1,885 | public class EntityForm {
protected static final Log LOG = LogFactory.getLog(EntityForm.class);
public static final String HIDDEN_GROUP = "hiddenGroup";
public static final String MAP_KEY_GROUP = "keyGroup";
public static final String DEFAULT_GROUP_NAME = "Default";
public static final Integer DEFAULT_GROUP_ORDER = 99999;
public static final String DEFAULT_TAB_NAME = "General";
public static final Integer DEFAULT_TAB_ORDER = 100;
protected String id;
protected String idProperty = "id";
protected String ceilingEntityClassname;
protected String entityType;
protected String mainEntityName;
protected String sectionKey;
protected Set<Tab> tabs = new TreeSet<Tab>(new Comparator<Tab>() {
@Override
public int compare(Tab o1, Tab o2) {
return new CompareToBuilder()
.append(o1.getOrder(), o2.getOrder())
.append(o1.getTitle(), o2.getTitle())
.toComparison();
}
});
// This is used to data-bind when this entity form is submitted
protected Map<String, Field> fields = null;
// This is used in cases where there is a sub-form on this page that is dynamically
// rendered based on other values on this entity form. It is keyed by the name of the
// property that drives the dynamic form.
protected Map<String, EntityForm> dynamicForms = new HashMap<String, EntityForm>();
// These values are used when dynamic forms are in play. They are not rendered to the client,
// but they can be used when performing actions on the submit event
protected Map<String, DynamicEntityFormInfo> dynamicFormInfos = new HashMap<String, DynamicEntityFormInfo>();
protected List<EntityFormAction> actions = new ArrayList<EntityFormAction>();
/**
* @return a flattened, field name keyed representation of all of
* the fields in all of the groups for this form. This set will also includes all of the dynamic form
* fields.
*
* Note that if there collisions between the dynamic form fields and the fields on this form (meaning that they
* have the same name), then the dynamic form field will be excluded from the map and the preference will be given
* to first-level entities
*
* @see {@link #getFields(boolean)}
*/
public Map<String, Field> getFields() {
if (fields == null) {
Map<String, Field> map = new LinkedHashMap<String, Field>();
for (Tab tab : tabs) {
for (FieldGroup group : tab.getFieldGroups()) {
for (Field field : group.getFields()) {
map.put(field.getName(), field);
}
}
}
fields = map;
}
for (Entry<String, EntityForm> entry : dynamicForms.entrySet()) {
Map<String, Field> dynamicFormFields = entry.getValue().getFields();
for (Entry<String, Field> dynamicField : dynamicFormFields.entrySet()) {
if (fields.containsKey(dynamicField.getKey())) {
LOG.info("Excluding dynamic field " + dynamicField.getKey() + " as there is already an occurrance in" +
" this entityForm");
} else {
fields.put(dynamicField.getKey(), dynamicField.getValue());
}
}
}
return fields;
}
/**
* Clears out the cached 'fields' variable which is used to render the form on the frontend. Use this method
* if you want to force the entityForm to rebuild itself based on the tabs and groups that have been assigned and
* populated
*/
public void clearFieldsMap() {
fields = null;
}
public List<ListGrid> getAllListGrids() {
List<ListGrid> list = new ArrayList<ListGrid>();
for (Tab tab : tabs) {
for (ListGrid lg : tab.getListGrids()) {
list.add(lg);
}
}
return list;
}
/**
* Convenience method for grabbing a grid by its collection field name. This is very similar to {@link #findField(String)}
* but differs in that this only searches through the sub collections for the current entity
*
* @param collectionFieldName the field name of the collection on the top-level entity
* @return
*/
public ListGrid findListGrid(String collectionFieldName) {
for (ListGrid grid : getAllListGrids()) {
if (grid.getSubCollectionFieldName().equals(collectionFieldName)) {
return grid;
}
}
return null;
}
public Tab findTab(String tabTitle) {
for (Tab tab : tabs) {
if (tab.getTitle() != null && tab.getTitle().equals(tabTitle)) {
return tab;
}
}
return null;
}
public Tab findTabForField(String fieldName) {
fieldName = sanitizeFieldName(fieldName);
for (Tab tab : tabs) {
for (FieldGroup fieldGroup : tab.getFieldGroups()) {
for (Field field : fieldGroup.getFields()) {
if (field.getName().equals(fieldName)) {
return tab;
}
}
}
}
return null;
}
public Field findField(String fieldName) {
fieldName = sanitizeFieldName(fieldName);
for (Tab tab : tabs) {
for (FieldGroup fieldGroup : tab.getFieldGroups()) {
for (Field field : fieldGroup.getFields()) {
if (field.getName().equals(fieldName)) {
return field;
}
}
}
}
return null;
}
/**
* Since this field name could come from the frontend (where all fields are referenced like fields[name].value,
* we need to strip that part out to look up the real field name in this entity
* @param fieldName
* @return
*/
public String sanitizeFieldName(String fieldName) {
if (fieldName.contains("[")) {
fieldName = fieldName.substring(fieldName.indexOf('[') + 1, fieldName.indexOf(']'));
}
return fieldName;
}
public Field removeField(String fieldName) {
Field fieldToRemove = null;
FieldGroup containingGroup = null;
findField: {
for (Tab tab : tabs) {
for (FieldGroup fieldGroup : tab.getFieldGroups()) {
for (Field field : fieldGroup.getFields()) {
if (field.getName().equals(fieldName)) {
fieldToRemove = field;
containingGroup = fieldGroup;
break findField;
}
}
}
}
}
if (fieldToRemove != null) {
containingGroup.removeField(fieldToRemove);
}
if (fields != null) {
fields.remove(fieldName);
}
return fieldToRemove;
}
public void removeTab(Tab tab) {
tabs.remove(tab);
}
public ListGrid removeListGrid(String subCollectionFieldName) {
ListGrid lgToRemove = null;
Tab containingTab = null;
findLg: {
for (Tab tab : tabs) {
for (ListGrid lg : tab.getListGrids()) {
if (subCollectionFieldName.equals(lg.getSubCollectionFieldName())) {
lgToRemove = lg;
containingTab = tab;
break findLg;
}
}
}
}
if (lgToRemove != null) {
containingTab.removeListGrid(lgToRemove);
}
if (containingTab.getListGrids().size() == 0 && containingTab.getFields().size() == 0) {
removeTab(containingTab);
}
return lgToRemove;
}
public void addHiddenField(Field field) {
if (StringUtils.isBlank(field.getFieldType())) {
field.setFieldType(SupportedFieldType.HIDDEN.toString());
}
addField(field, HIDDEN_GROUP, DEFAULT_GROUP_ORDER, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);
}
public void addField(Field field) {
addField(field, DEFAULT_GROUP_NAME, DEFAULT_GROUP_ORDER, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);
}
public void addMapKeyField(Field field) {
addField(field, MAP_KEY_GROUP, 0, DEFAULT_TAB_NAME, DEFAULT_TAB_ORDER);
}
public void addField(Field field, String groupName, Integer groupOrder, String tabName, Integer tabOrder) {
// System.out.println(String.format("Adding field [%s] to group [%s] to tab [%s]", field.getName(), groupName, tabName));
groupName = groupName == null ? DEFAULT_GROUP_NAME : groupName;
groupOrder = groupOrder == null ? DEFAULT_GROUP_ORDER : groupOrder;
tabName = tabName == null ? DEFAULT_TAB_NAME : tabName;
tabOrder = tabOrder == null ? DEFAULT_TAB_ORDER : tabOrder;
Tab tab = findTab(tabName);
if (tab == null) {
tab = new Tab();
tab.setTitle(tabName);
tab.setOrder(tabOrder);
tabs.add(tab);
}
FieldGroup fieldGroup = tab.findGroup(groupName);
if (fieldGroup == null) {
fieldGroup = new FieldGroup();
fieldGroup.setTitle(groupName);
fieldGroup.setOrder(groupOrder);
tab.getFieldGroups().add(fieldGroup);
}
fieldGroup.addField(field);
}
public void addListGrid(ListGrid listGrid, String tabName, Integer tabOrder) {
Tab tab = findTab(tabName);
if (tab == null) {
tab = new Tab();
tab.setTitle(tabName);
tab.setOrder(tabOrder);
tabs.add(tab);
}
tab.getListGrids().add(listGrid);
}
public void addAction(EntityFormAction action) {
actions.add(action);
}
public void removeAction(EntityFormAction action) {
actions.remove(action);
}
public void removeAllActions() {
actions.clear();
}
public EntityForm getDynamicForm(String name) {
return getDynamicForms().get(name);
}
public void putDynamicForm(String name, EntityForm ef) {
getDynamicForms().put(name, ef);
}
public DynamicEntityFormInfo getDynamicFormInfo(String name) {
return getDynamicFormInfos().get(name);
}
public void putDynamicFormInfo(String name, DynamicEntityFormInfo info) {
getDynamicFormInfos().put(name, info);
}
public void setReadOnly() {
if (getFields() != null) {
for (Entry<String, Field> entry : getFields().entrySet()) {
entry.getValue().setReadOnly(true);
}
}
if (getAllListGrids() != null) {
for (ListGrid lg : getAllListGrids()) {
lg.setReadOnly(true);
}
}
if (getDynamicForms() != null) {
for (Entry<String, EntityForm> entry : getDynamicForms().entrySet()) {
entry.getValue().setReadOnly();
}
}
actions.clear();
}
public List<EntityFormAction> getActions() {
List<EntityFormAction> clonedActions = new ArrayList<EntityFormAction>(actions);
Collections.reverse(clonedActions);
return Collections.unmodifiableList(clonedActions);
}
/* *********************** */
/* GENERIC GETTERS/SETTERS */
/* *********************** */
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdProperty() {
return idProperty;
}
public void setIdProperty(String idProperty) {
this.idProperty = idProperty;
}
public String getCeilingEntityClassname() {
return ceilingEntityClassname;
}
public void setCeilingEntityClassname(String ceilingEntityClassname) {
this.ceilingEntityClassname = ceilingEntityClassname;
}
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
public String getMainEntityName() {
return StringUtils.isBlank(mainEntityName) ? "" : mainEntityName;
}
public void setMainEntityName(String mainEntityName) {
this.mainEntityName = mainEntityName;
}
public String getSectionKey() {
return sectionKey.charAt(0) == '/' ? sectionKey : '/' + sectionKey;
}
public void setSectionKey(String sectionKey) {
this.sectionKey = sectionKey;
}
public Set<Tab> getTabs() {
return tabs;
}
public void setTabs(Set<Tab> tabs) {
this.tabs = tabs;
}
public Map<String, EntityForm> getDynamicForms() {
return dynamicForms;
}
public void setDynamicForms(Map<String, EntityForm> dynamicForms) {
this.dynamicForms = dynamicForms;
}
public Map<String, DynamicEntityFormInfo> getDynamicFormInfos() {
return dynamicFormInfos;
}
public void setDynamicFormInfos(Map<String, DynamicEntityFormInfo> dynamicFormInfos) {
this.dynamicFormInfos = dynamicFormInfos;
}
public void setActions(List<EntityFormAction> actions) {
this.actions = actions;
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_form_entity_EntityForm.java |
235 | assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertEquals(CLUSTER_SIZE, map.size());
}
}); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java |
1,688 | public abstract class OBinaryNetworkProtocolAbstract extends ONetworkProtocol {
protected OChannelBinaryServer channel;
protected int requestType;
protected int clientTxId;
protected final Level logClientExceptions;
protected final boolean logClientFullStackTrace;
public OBinaryNetworkProtocolAbstract(final String iThreadName) {
super(Orient.instance().getThreadGroup(), iThreadName);
logClientExceptions = Level.parse(OGlobalConfiguration.SERVER_LOG_DUMP_CLIENT_EXCEPTION_LEVEL.getValueAsString());
logClientFullStackTrace = OGlobalConfiguration.SERVER_LOG_DUMP_CLIENT_EXCEPTION_FULLSTACKTRACE.getValueAsBoolean();
}
/**
* Executes the request.
*
* @return true if the request has been recognized, otherwise false
* @throws IOException
*/
protected abstract boolean executeRequest() throws IOException;
/**
* Executed before the request.
*
* @throws IOException
*/
protected void onBeforeRequest() throws IOException {
}
/**
* Executed after the request, also in case of error.
*
* @throws IOException
*/
protected void onAfterRequest() throws IOException {
}
@Override
public void config(final OServer iServer, final Socket iSocket, final OContextConfiguration iConfig,
final List<?> iStatelessCommands, List<?> iStatefulCommands) throws IOException {
server = iServer;
channel = new OChannelBinaryServer(iSocket, iConfig);
}
@Override
protected void execute() throws Exception {
requestType = -1;
clientTxId = 0;
long timer = 0;
try {
requestType = channel.readByte();
clientTxId = channel.readInt();
timer = Orient.instance().getProfiler().startChrono();
onBeforeRequest();
try {
if (!executeRequest()) {
OLogManager.instance().error(this, "Request not supported. Code: " + requestType);
channel.clearInput();
sendError(clientTxId, new ONetworkProtocolException("Request not supported. Code: " + requestType));
}
} finally {
onAfterRequest();
}
} catch (IOException e) {
handleConnectionError(channel, e);
sendShutdown();
} catch (OException e) {
sendError(clientTxId, e);
} catch (RuntimeException e) {
sendError(clientTxId, e);
} catch (Throwable t) {
sendError(clientTxId, t);
} finally {
Orient.instance().getProfiler()
.stopChrono("server.network.requests", "Total received requests", timer, "server.network.requests");
OSerializationThreadLocal.INSTANCE.get().clear();
}
}
@Override
public void shutdown() {
channel.close();
}
@Override
public OChannel getChannel() {
return channel;
}
protected void sendOk(final int iClientTxId) throws IOException {
channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_OK);
channel.writeInt(iClientTxId);
}
protected void sendError(final int iClientTxId, final Throwable t) throws IOException {
channel.acquireWriteLock();
try {
channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_ERROR);
channel.writeInt(iClientTxId);
Throwable current;
if (t instanceof OLockException && t.getCause() instanceof ODatabaseException)
// BYPASS THE DB POOL EXCEPTION TO PROPAGATE THE RIGHT SECURITY ONE
current = t.getCause();
else
current = t;
while (current != null) {
// MORE DETAILS ARE COMING AS EXCEPTION
channel.writeByte((byte) 1);
channel.writeString(current.getClass().getName());
channel.writeString(current != null ? current.getMessage() : null);
current = current.getCause();
}
channel.writeByte((byte) 0);
channel.flush();
if (OLogManager.instance().isLevelEnabled(logClientExceptions)) {
if (logClientFullStackTrace)
OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", t,
channel.socket.getRemoteSocketAddress(), t.toString());
else
OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", null,
channel.socket.getRemoteSocketAddress(), t.toString());
}
} catch (Exception e) {
if (e instanceof SocketException)
shutdown();
} finally {
channel.releaseWriteLock();
}
}
/**
* Write a OIdentifiable instance using this format:<br/>
* - 2 bytes: class id [-2=no record, -3=rid, -1=no class id, > -1 = valid] <br/>
* - 1 byte: record type [d,b,f] <br/>
* - 2 bytes: cluster id <br/>
* - 8 bytes: position in cluster <br/>
* - 4 bytes: record version <br/>
* - x bytes: record content <br/>
*
* @param o
* @throws IOException
*/
public void writeIdentifiable(final OIdentifiable o) throws IOException {
if (o == null)
channel.writeShort(OChannelBinaryProtocol.RECORD_NULL);
else if (o instanceof ORecordId) {
channel.writeShort(OChannelBinaryProtocol.RECORD_RID);
channel.writeRID((ORID) o);
} else {
writeRecord((ORecordInternal<?>) o.getRecord());
}
}
private void writeRecord(final ORecordInternal<?> iRecord) throws IOException {
channel.writeShort((short) 0);
channel.writeByte(iRecord.getRecordType());
channel.writeRID(iRecord.getIdentity());
channel.writeVersion(iRecord.getRecordVersion());
try {
final byte[] stream = iRecord.toStream();
// TRIM TAILING SPACES (DUE TO OVERSIZE)
int realLength = stream.length;
for (int i = stream.length - 1; i > -1; --i) {
if (stream[i] == 32)
--realLength;
else
break;
}
channel.writeBytes(stream, realLength);
} catch (Exception e) {
channel.writeBytes(null);
OLogManager.instance().error(this, "Error on unmarshalling record " + iRecord.getIdentity().toString() + " (" + e + ")",
OSerializationException.class);
}
}
protected void checkStorageExistence(final String iDatabaseName) {
for (OStorage stg : Orient.instance().getStorages()) {
if (stg.getName().equalsIgnoreCase(iDatabaseName) && stg.exists())
throw new ODatabaseException("Database named '" + iDatabaseName + "' already exists: " + stg);
}
}
protected ODatabaseDocumentTx createDatabase(final ODatabaseDocumentTx iDatabase, String dbUser, final String dbPasswd) {
if (iDatabase.exists())
throw new ODatabaseException("Database '" + iDatabase.getURL() + "' already exists");
iDatabase.create();
if (dbUser != null) {
OUser oUser = iDatabase.getMetadata().getSecurity().getUser(dbUser);
if (oUser == null) {
iDatabase.getMetadata().getSecurity().createUser(dbUser, dbPasswd, new String[] { ORole.ADMIN });
} else {
oUser.setPassword(dbPasswd);
oUser.save();
}
}
OLogManager.instance().info(this, "Created database '%s' of type '%s'", iDatabase.getName(),
iDatabase.getStorage() instanceof OStorageLocalAbstract ? iDatabase.getStorage().getType() : "memory");
// if (iDatabase.getStorage() instanceof OStorageLocal)
// // CLOSE IT BECAUSE IT WILL BE OPEN AT FIRST USE
// iDatabase.close();
return iDatabase;
}
protected ODatabaseDocumentTx getDatabaseInstance(final String dbName, final String dbType, final String storageType) {
String path;
final OStorage stg = Orient.instance().getStorage(dbName);
if (stg != null)
path = stg.getURL();
else if (storageType.equals(OEngineLocal.NAME) || storageType.equals(OEngineLocalPaginated.NAME)) {
// if this storage was configured return always path from config file, otherwise return default path
path = server.getConfiguration().getStoragePath(dbName);
if (path == null)
path = storageType + ":" + server.getDatabaseDirectory() + "/" + dbName;
} else if (storageType.equals(OEngineMemory.NAME)) {
path = storageType + ":" + dbName;
} else
throw new IllegalArgumentException("Cannot create database: storage mode '" + storageType + "' is not supported.");
return Orient.instance().getDatabaseFactory().createDatabase(dbType, path);
}
protected int deleteRecord(final ODatabaseRecord iDatabase, final ORID rid, final ORecordVersion version) {
try {
iDatabase.delete(rid, version);
return 1;
} catch (Exception e) {
return 0;
}
}
protected int cleanOutRecord(final ODatabaseRecord iDatabase, final ORID rid, final ORecordVersion version) {
iDatabase.delete(rid, version);
return 1;
}
protected ORecordInternal<?> createRecord(final ODatabaseRecord iDatabase, final ORecordId rid, final byte[] buffer,
final byte recordType, final int dataSegmentId) {
final ORecordInternal<?> record = Orient.instance().getRecordFactoryManager().newInstance(recordType);
record.fill(rid, OVersionFactory.instance().createVersion(), buffer, true);
if (dataSegmentId > 0)
record.setDataSegmentName(iDatabase.getDataSegmentNameById(dataSegmentId));
iDatabase.save(record);
return record;
}
protected ORecordVersion updateRecord(final ODatabaseRecord iDatabase, final ORecordId rid, final byte[] buffer,
final ORecordVersion version, final byte recordType) {
final ORecordInternal<?> newRecord = Orient.instance().getRecordFactoryManager().newInstance(recordType);
newRecord.fill(rid, version, buffer, true);
// if (((OSchemaProxy) iDatabase.getMetadata().getSchema()).getIdentity().equals(rid))
// // || ((OIndexManagerImpl) connection.database.getMetadata().getIndexManager()).getDocument().getIdentity().equals(rid)) {
// throw new OSecurityAccessException("Cannot update internal record " + rid);
final ORecordInternal<?> currentRecord;
if (newRecord instanceof ODocument) {
currentRecord = iDatabase.load(rid);
if (currentRecord == null)
throw new ORecordNotFoundException(rid.toString());
((ODocument) currentRecord).merge((ODocument) newRecord, false, false);
} else
currentRecord = newRecord;
currentRecord.getRecordVersion().copyFrom(version);
iDatabase.save(currentRecord);
if (currentRecord.getIdentity().toString().equals(iDatabase.getStorage().getConfiguration().indexMgrRecordId)
&& !iDatabase.getStatus().equals(STATUS.IMPORTING)) {
// FORCE INDEX MANAGER UPDATE. THIS HAPPENS FOR DIRECT CHANGES FROM REMOTE LIKE IN GRAPH
iDatabase.getMetadata().getIndexManager().reload();
}
return currentRecord.getRecordVersion();
}
protected void handleConnectionError(final OChannelBinaryServer channel, final Throwable e) {
try {
channel.flush();
} catch (IOException e1) {
}
}
} | 1no label
| server_src_main_java_com_orientechnologies_orient_server_network_protocol_binary_OBinaryNetworkProtocolAbstract.java |
192 | public static class ClientProperty {
private final String name;
private final String value;
ClientProperty(ClientConfig config, String name) {
this(config, name, (String) null);
}
ClientProperty(ClientConfig config, String name, ClientProperty defaultValue) {
this(config, name, defaultValue != null ? defaultValue.getString() : null);
}
ClientProperty(ClientConfig config, String name, String defaultValue) {
this.name = name;
String configValue = (config != null) ? config.getProperty(name) : null;
if (configValue != null) {
value = configValue;
} else if (System.getProperty(name) != null) {
value = System.getProperty(name);
} else {
value = defaultValue;
}
}
public String getName() {
return this.name;
}
public String getValue() {
return value;
}
public int getInteger() {
return Integer.parseInt(this.value);
}
public byte getByte() {
return Byte.parseByte(this.value);
}
public boolean getBoolean() {
return Boolean.valueOf(this.value);
}
public String getString() {
return value;
}
public long getLong() {
return Long.parseLong(this.value);
}
@Override
public String toString() {
return "ClientProperty [name=" + this.name + ", value=" + this.value + "]";
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_config_ClientProperties.java |
657 | OProfiler.METRIC_TYPE.SIZE, new OProfiler.OProfilerHookValue() {
public Object getValue() {
return map != null ? map.getMaxUpdatesBeforeSave() : "-";
}
}, profilerMetadataPrefix + "maxUpdateBeforeSave"); | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_engine_OMVRBTreeIndexEngine.java |
4,269 | public class FsTranslog extends AbstractIndexShardComponent implements Translog {
public static final String INDEX_TRANSLOG_FS_TYPE = "index.translog.fs.type";
class ApplySettings implements IndexSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
FsTranslogFile.Type type = FsTranslogFile.Type.fromString(settings.get(INDEX_TRANSLOG_FS_TYPE, FsTranslog.this.type.name()));
if (type != FsTranslog.this.type) {
logger.info("updating type from [{}] to [{}]", FsTranslog.this.type, type);
FsTranslog.this.type = type;
}
}
}
private final IndexSettingsService indexSettingsService;
private final ReadWriteLock rwl = new ReentrantReadWriteLock();
private final File[] locations;
private volatile FsTranslogFile current;
private volatile FsTranslogFile trans;
private FsTranslogFile.Type type;
private boolean syncOnEachOperation = false;
private volatile int bufferSize;
private volatile int transientBufferSize;
private final ApplySettings applySettings = new ApplySettings();
@Inject
public FsTranslog(ShardId shardId, @IndexSettings Settings indexSettings, IndexSettingsService indexSettingsService, NodeEnvironment nodeEnv) {
super(shardId, indexSettings);
this.indexSettingsService = indexSettingsService;
File[] shardLocations = nodeEnv.shardLocations(shardId);
this.locations = new File[shardLocations.length];
for (int i = 0; i < shardLocations.length; i++) {
locations[i] = new File(shardLocations[i], "translog");
FileSystemUtils.mkdirs(locations[i]);
}
this.type = FsTranslogFile.Type.fromString(componentSettings.get("type", FsTranslogFile.Type.BUFFERED.name()));
this.bufferSize = (int) componentSettings.getAsBytesSize("buffer_size", ByteSizeValue.parseBytesSizeValue("64k")).bytes(); // Not really interesting, updated by IndexingMemoryController...
this.transientBufferSize = (int) componentSettings.getAsBytesSize("transient_buffer_size", ByteSizeValue.parseBytesSizeValue("8k")).bytes();
indexSettingsService.addListener(applySettings);
}
public FsTranslog(ShardId shardId, @IndexSettings Settings indexSettings, File location) {
super(shardId, indexSettings);
this.indexSettingsService = null;
this.locations = new File[]{location};
FileSystemUtils.mkdirs(location);
this.type = FsTranslogFile.Type.fromString(componentSettings.get("type", FsTranslogFile.Type.BUFFERED.name()));
}
@Override
public void closeWithDelete() {
close(true);
}
@Override
public void close() throws ElasticsearchException {
close(false);
}
@Override
public void updateBuffer(ByteSizeValue bufferSize) {
this.bufferSize = bufferSize.bytesAsInt();
rwl.writeLock().lock();
try {
FsTranslogFile current1 = this.current;
if (current1 != null) {
current1.updateBufferSize(this.bufferSize);
}
current1 = this.trans;
if (current1 != null) {
current1.updateBufferSize(this.bufferSize);
}
} finally {
rwl.writeLock().unlock();
}
}
private void close(boolean delete) {
if (indexSettingsService != null) {
indexSettingsService.removeListener(applySettings);
}
rwl.writeLock().lock();
try {
FsTranslogFile current1 = this.current;
if (current1 != null) {
current1.close(delete);
}
current1 = this.trans;
if (current1 != null) {
current1.close(delete);
}
} finally {
rwl.writeLock().unlock();
}
}
public File[] locations() {
return locations;
}
@Override
public long currentId() {
FsTranslogFile current1 = this.current;
if (current1 == null) {
return -1;
}
return current1.id();
}
@Override
public int estimatedNumberOfOperations() {
FsTranslogFile current1 = this.current;
if (current1 == null) {
return 0;
}
return current1.estimatedNumberOfOperations();
}
@Override
public long memorySizeInBytes() {
return 0;
}
@Override
public long translogSizeInBytes() {
FsTranslogFile current1 = this.current;
if (current1 == null) {
return 0;
}
return current1.translogSizeInBytes();
}
@Override
public void clearUnreferenced() {
rwl.writeLock().lock();
try {
for (File location : locations) {
File[] files = location.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().equals("translog-" + current.id())) {
continue;
}
if (trans != null && file.getName().equals("translog-" + trans.id())) {
continue;
}
try {
file.delete();
} catch (Exception e) {
// ignore
}
}
}
}
} finally {
rwl.writeLock().unlock();
}
}
@Override
public void newTranslog(long id) throws TranslogException {
rwl.writeLock().lock();
try {
FsTranslogFile newFile;
long size = Long.MAX_VALUE;
File location = null;
for (File file : locations) {
long currentFree = file.getFreeSpace();
if (currentFree < size) {
size = currentFree;
location = file;
} else if (currentFree == size && ThreadLocalRandom.current().nextBoolean()) {
location = file;
}
}
try {
newFile = type.create(shardId, id, new RafReference(new File(location, "translog-" + id)), bufferSize);
} catch (IOException e) {
throw new TranslogException(shardId, "failed to create new translog file", e);
}
FsTranslogFile old = current;
current = newFile;
if (old != null) {
// we might create a new translog overriding the current translog id
boolean delete = true;
if (old.id() == id) {
delete = false;
}
old.close(delete);
}
} finally {
rwl.writeLock().unlock();
}
}
@Override
public void newTransientTranslog(long id) throws TranslogException {
rwl.writeLock().lock();
try {
assert this.trans == null;
long size = Long.MAX_VALUE;
File location = null;
for (File file : locations) {
long currentFree = file.getFreeSpace();
if (currentFree < size) {
size = currentFree;
location = file;
} else if (currentFree == size && ThreadLocalRandom.current().nextBoolean()) {
location = file;
}
}
this.trans = type.create(shardId, id, new RafReference(new File(location, "translog-" + id)), transientBufferSize);
} catch (IOException e) {
throw new TranslogException(shardId, "failed to create new translog file", e);
} finally {
rwl.writeLock().unlock();
}
}
@Override
public void makeTransientCurrent() {
FsTranslogFile old;
rwl.writeLock().lock();
try {
assert this.trans != null;
old = current;
this.current = this.trans;
this.trans = null;
} finally {
rwl.writeLock().unlock();
}
old.close(true);
current.reuse(old);
}
@Override
public void revertTransient() {
FsTranslogFile tmpTransient;
rwl.writeLock().lock();
try {
tmpTransient = trans;
this.trans = null;
} finally {
rwl.writeLock().unlock();
}
// previous transient might be null because it was failed on its creation
// for example
if (tmpTransient != null) {
tmpTransient.close(true);
}
}
public byte[] read(Location location) {
rwl.readLock().lock();
try {
FsTranslogFile trans = this.trans;
if (trans != null && trans.id() == location.translogId) {
try {
return trans.read(location);
} catch (Exception e) {
// ignore
}
}
if (current.id() == location.translogId) {
try {
return current.read(location);
} catch (Exception e) {
// ignore
}
}
return null;
} finally {
rwl.readLock().unlock();
}
}
@Override
public Location add(Operation operation) throws TranslogException {
rwl.readLock().lock();
try {
BytesStreamOutput out = new BytesStreamOutput();
out.writeInt(0); // marker for the size...
TranslogStreams.writeTranslogOperation(out, operation);
out.flush();
int size = out.size();
out.seek(0);
out.writeInt(size - 4);
Location location = current.add(out.bytes().array(), out.bytes().arrayOffset(), size);
if (syncOnEachOperation) {
current.sync();
}
FsTranslogFile trans = this.trans;
if (trans != null) {
try {
location = trans.add(out.bytes().array(), out.bytes().arrayOffset(), size);
} catch (ClosedChannelException e) {
// ignore
}
}
return location;
} catch (Exception e) {
throw new TranslogException(shardId, "Failed to write operation [" + operation + "]", e);
} finally {
rwl.readLock().unlock();
}
}
@Override
public FsChannelSnapshot snapshot() throws TranslogException {
while (true) {
FsChannelSnapshot snapshot = current.snapshot();
if (snapshot != null) {
return snapshot;
}
Thread.yield();
}
}
@Override
public Snapshot snapshot(Snapshot snapshot) {
FsChannelSnapshot snap = snapshot();
if (snap.translogId() == snapshot.translogId()) {
snap.seekForward(snapshot.position());
}
return snap;
}
@Override
public void sync() {
FsTranslogFile current1 = this.current;
if (current1 == null) {
return;
}
current1.sync();
}
@Override
public boolean syncNeeded() {
FsTranslogFile current1 = this.current;
return current1 != null && current1.syncNeeded();
}
@Override
public void syncOnEachOperation(boolean syncOnEachOperation) {
this.syncOnEachOperation = syncOnEachOperation;
if (syncOnEachOperation) {
type = FsTranslogFile.Type.SIMPLE;
} else {
type = FsTranslogFile.Type.BUFFERED;
}
}
@Override
public TranslogStats stats() {
return new TranslogStats(estimatedNumberOfOperations(), translogSizeInBytes());
}
} | 1no label
| src_main_java_org_elasticsearch_index_translog_fs_FsTranslog.java |
782 | docMapper.parse(SourceToParse.source(getResponse.getSourceAsBytesRef()).type(request.type()).id(request.id()), new DocumentMapper.ParseListenerAdapter() {
@Override
public boolean beforeFieldAdded(FieldMapper fieldMapper, Field field, Object parseContext) {
if (!field.fieldType().indexed()) {
return false;
}
if (fieldMapper instanceof InternalMapper) {
return true;
}
String value = fieldMapper.value(convertField(field)).toString();
if (value == null) {
return false;
}
if (fields.isEmpty() || fields.contains(field.name())) {
addMoreLikeThis(request, boolBuilder, fieldMapper, field, !fields.isEmpty());
}
return false;
}
}); | 0true
| src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java |
1,522 | @SuppressWarnings("rawtypes")
public class OJPAPersistenceProvider implements PersistenceProvider {
/** the log used by this class. */
private static Logger logger = Logger.getLogger(OJPAPersistenceProvider.class.getName());
private Collection<? extends PersistenceUnitInfo> persistenceUnits = null;
public OJPAPersistenceProvider() {
URL persistenceXml = Thread.currentThread().getContextClassLoader().getResource(PERSISTENCE_XML);
try {
persistenceUnits = PersistenceXmlUtil.parse(persistenceXml);
} catch (Exception e) {
logger.info("Can't parse '" + PERSISTENCE_XML + "' :" + e.getMessage());
}
}
@Override
public synchronized EntityManagerFactory createEntityManagerFactory(String emName, Map map) {
if (emName == null) {
throw new IllegalStateException("Name of the persistence unit should not be null");
}
PersistenceUnitInfo unitInfo = PersistenceXmlUtil.findPersistenceUnit(emName, persistenceUnits);
return createContainerEntityManagerFactory(unitInfo, map);
}
@SuppressWarnings("unchecked")
@Override
public synchronized EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
OJPAProperties properties = ((info == null) ? new OJPAProperties() : (OJPAProperties) info.getProperties());
// Override parsed properties with user specified
if (map != null && !map.isEmpty()) {
properties.putAll(map);
}
// register entities from <class> tag
OEntityManager entityManager = getEntityManagerByDatabaseURL(properties.getURL());
entityManager.registerEntityClasses(info.getManagedClassNames());
return new OJPAEntityManagerFactory(properties);
}
@Override
public ProviderUtil getProviderUtil() {
throw new UnsupportedOperationException("getProviderUtil");
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_jpa_OJPAPersistenceProvider.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.