Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
1,705 | return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return intersection;
}
}; | 0true
| src_main_java_org_elasticsearch_common_collect_HppcMaps.java |
150 | {
public long generate( XaDataSource dataSource, int identifier ) throws XAException
{
return dataSource.getLastCommittedTxId() + 1;
}
public int getCurrentMasterId()
{
return XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER;
}
public int getMyId()
{
return XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER;
}
@Override
public void committed( XaDataSource dataSource, int identifier, long txId, Integer externalAuthor )
{
}
}; | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_TxIdGenerator.java |
1,008 | public static class FieldOrder {
public static final int NAME = 1000;
public static final int DESCRIPTION = 2000;
public static final int FLATRATES = 9000;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_FulfillmentOptionImpl.java |
506 | public class TransportCreateIndexAction extends TransportMasterNodeOperationAction<CreateIndexRequest, CreateIndexResponse> {
private final MetaDataCreateIndexService createIndexService;
@Inject
public TransportCreateIndexAction(Settings settings, TransportService transportService, ClusterService clusterService,
ThreadPool threadPool, MetaDataCreateIndexService createIndexService) {
super(settings, transportService, clusterService, threadPool);
this.createIndexService = createIndexService;
}
@Override
protected String executor() {
// we go async right away
return ThreadPool.Names.SAME;
}
@Override
protected String transportAction() {
return CreateIndexAction.NAME;
}
@Override
protected CreateIndexRequest newRequest() {
return new CreateIndexRequest();
}
@Override
protected CreateIndexResponse newResponse() {
return new CreateIndexResponse();
}
@Override
protected ClusterBlockException checkBlock(CreateIndexRequest request, ClusterState state) {
return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, request.index());
}
@Override
protected void masterOperation(final CreateIndexRequest request, final ClusterState state, final ActionListener<CreateIndexResponse> listener) throws ElasticsearchException {
String cause = request.cause();
if (cause.length() == 0) {
cause = "api";
}
CreateIndexClusterStateUpdateRequest updateRequest = new CreateIndexClusterStateUpdateRequest(cause, request.index())
.ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout())
.settings(request.settings()).mappings(request.mappings())
.customs(request.customs());
createIndexService.createIndex(updateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new CreateIndexResponse(response.isAcknowledged()));
}
@Override
public void onFailure(Throwable t) {
if (t instanceof IndexAlreadyExistsException) {
logger.trace("[{}] failed to create", t, request.index());
} else {
logger.debug("[{}] failed to create", t, request.index());
}
listener.onFailure(t);
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_create_TransportCreateIndexAction.java |
392 | static class UnLockThread extends Thread{
public Exception exception=null;
public MultiMap mm=null;
public Object key=null;
public UnLockThread(MultiMap mm, Object key){
this.mm = mm;
this.key = key;
}
public void run() {
try{
mm.unlock(key);
}catch (Exception e){
exception = e;
}
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapLockTest.java |
1,186 | public class MapStoreAdapter<K, V> implements MapStore<K, V> {
/**
* {@inheritDoc}
*/
public void delete(final K key) {
}
/**
* {@inheritDoc}
*/
public void store(final K key, final V value) {
}
/**
* {@inheritDoc}
*/
public void storeAll(final Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
store(entry.getKey(), entry.getValue());
}
}
/**
* {@inheritDoc}
*/
public void deleteAll(final Collection<K> keys) {
for (K key : keys) {
delete(key);
}
}
/**
* {@inheritDoc}
*/
public V load(final K key) {
return null;
}
/**
* {@inheritDoc}
*/
public Map<K, V> loadAll(final Collection<K> keys) {
Map<K, V> result = new HashMap<K, V>();
for (K key : keys) {
V value = load(key);
if (value != null) {
result.put(key, value);
}
}
return result;
}
/**
* {@inheritDoc}
*/
public Set<K> loadAllKeys() {
return null;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_MapStoreAdapter.java |
1,312 | public class DistributedExecutorService implements ManagedService, RemoteService, ExecutionTracingService {
public static final String SERVICE_NAME = "hz:impl:executorService";
//Updates the CallableProcessor.responseFlag field. An AtomicBoolean is simpler, but creates another unwanted
//object. Using this approach, you don't create that object.
private static final AtomicReferenceFieldUpdater<CallableProcessor, Boolean> RESPONSE_FLAG_FIELD_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(CallableProcessor.class, Boolean.class, "responseFlag");
private NodeEngine nodeEngine;
private ExecutionService executionService;
private final ConcurrentMap<String, CallableProcessor> submittedTasks
= new ConcurrentHashMap<String, CallableProcessor>(100);
private final Set<String> shutdownExecutors
= Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
private final ConcurrentHashMap<String, LocalExecutorStatsImpl> statsMap
= new ConcurrentHashMap<String, LocalExecutorStatsImpl>();
private final ConstructorFunction<String, LocalExecutorStatsImpl> localExecutorStatsConstructorFunction
= new ConstructorFunction<String, LocalExecutorStatsImpl>() {
public LocalExecutorStatsImpl createNew(String key) {
return new LocalExecutorStatsImpl();
}
};
private ILogger logger;
@Override
public void init(NodeEngine nodeEngine, Properties properties) {
this.nodeEngine = nodeEngine;
this.executionService = nodeEngine.getExecutionService();
this.logger = nodeEngine.getLogger(DistributedExecutorService.class);
}
@Override
public void reset() {
shutdownExecutors.clear();
submittedTasks.clear();
statsMap.clear();
}
@Override
public void shutdown(boolean terminate) {
reset();
}
public void execute(String name, String uuid, Callable callable, ResponseHandler responseHandler) {
startPending(name);
CallableProcessor processor = new CallableProcessor(name, uuid, callable, responseHandler);
if (uuid != null) {
submittedTasks.put(uuid, processor);
}
try {
executionService.execute(name, processor);
} catch (RejectedExecutionException e) {
rejectExecution(name);
logger.warning("While executing " + callable + " on Executor[" + name + "]", e);
if (uuid != null) {
submittedTasks.remove(uuid);
}
processor.sendResponse(e);
}
}
public boolean cancel(String uuid, boolean interrupt) {
CallableProcessor processor = submittedTasks.remove(uuid);
if (processor != null && processor.cancel(interrupt)) {
processor.sendResponse(new CancellationException());
getLocalExecutorStats(processor.name).cancelExecution();
return true;
}
return false;
}
public void shutdownExecutor(String name) {
executionService.shutdownExecutor(name);
shutdownExecutors.add(name);
}
public boolean isShutdown(String name) {
return shutdownExecutors.contains(name);
}
@Override
public ExecutorServiceProxy createDistributedObject(String name) {
return new ExecutorServiceProxy(name, nodeEngine, this);
}
@Override
public void destroyDistributedObject(String name) {
shutdownExecutors.remove(name);
executionService.shutdownExecutor(name);
}
LocalExecutorStatsImpl getLocalExecutorStats(String name) {
return ConcurrencyUtil.getOrPutIfAbsent(statsMap, name, localExecutorStatsConstructorFunction);
}
private void startExecution(String name, long elapsed) {
getLocalExecutorStats(name).startExecution(elapsed);
}
private void finishExecution(String name, long elapsed) {
getLocalExecutorStats(name).finishExecution(elapsed);
}
private void startPending(String name) {
getLocalExecutorStats(name).startPending();
}
private void rejectExecution(String name) {
getLocalExecutorStats(name).rejectExecution();
}
@Override
public boolean isOperationExecuting(Address callerAddress, String callerUuid, Object identifier) {
String uuid = String.valueOf(identifier);
return submittedTasks.containsKey(uuid);
}
private final class CallableProcessor extends FutureTask implements Runnable {
//is being used through the RESPONSE_FLAG_FIELD_UPDATER. Can't be private due to reflection constraint.
volatile Boolean responseFlag = Boolean.FALSE;
private final String name;
private final String uuid;
private final ResponseHandler responseHandler;
private final String callableToString;
private final long creationTime = Clock.currentTimeMillis();
private CallableProcessor(String name, String uuid, Callable callable, ResponseHandler responseHandler) {
//noinspection unchecked
super(callable);
this.name = name;
this.uuid = uuid;
this.callableToString = String.valueOf(callable);
this.responseHandler = responseHandler;
}
@Override
public void run() {
long start = Clock.currentTimeMillis();
startExecution(name, start - creationTime);
Object result = null;
try {
super.run();
if (!isCancelled()) {
result = get();
}
} catch (Exception e) {
logException(e);
result = e;
} finally {
if (uuid != null) {
submittedTasks.remove(uuid);
}
sendResponse(result);
if (!isCancelled()) {
finishExecution(name, Clock.currentTimeMillis() - start);
}
}
}
private void logException(Exception e) {
if (logger.isFinestEnabled()) {
logger.finest("While executing callable: " + callableToString, e);
}
}
private void sendResponse(Object result) {
if (RESPONSE_FLAG_FIELD_UPDATER.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) {
responseHandler.sendResponse(result);
}
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_executor_DistributedExecutorService.java |
1,603 | public interface OReplicationConflictResolver {
public void startup(final OServer iServer, ODistributedServerManager iCluster, String iStorageName);
public void shutdown();
public ODocument getAllConflicts();
public void handleUpdateConflict(String iRemoteNodeId, ORecordId iCurrentRID, ORecordVersion iCurrentVersion,
ORecordVersion iOtherVersion);
public void handleCreateConflict(String iRemoteNodeId, ORecordId iCurrentRID, int iCurrentVersion, ORecordId iOtherRID,
int iOtherVersion);
public void handleDeleteConflict(String iRemoteNodeId, ORecordId iCurrentRID);
public void handleCommandConflict(String iRemoteNodeId, Object iCommand, Object iLocalResult, Object iRemoteResult);
public boolean existConflictsForRecord(final ORecordId iRID);
public ODocument reset();
} | 0true
| server_src_main_java_com_orientechnologies_orient_server_distributed_conflict_OReplicationConflictResolver.java |
2,015 | class RealElement implements Element {
private static final AtomicInteger nextUniqueId = new AtomicInteger(1);
private final int uniqueId;
private final String setName;
RealElement(String setName) {
uniqueId = nextUniqueId.getAndIncrement();
this.setName = setName;
}
public String setName() {
return setName;
}
public int uniqueId() {
return uniqueId;
}
public Class<? extends Annotation> annotationType() {
return Element.class;
}
@Override
public String toString() {
return "@" + Element.class.getName() + "(setName=" + setName
+ ",uniqueId=" + uniqueId + ")";
}
@Override
public boolean equals(Object o) {
return o instanceof Element
&& ((Element) o).setName().equals(setName())
&& ((Element) o).uniqueId() == uniqueId();
}
@Override
public int hashCode() {
return 127 * ("setName".hashCode() ^ setName.hashCode())
+ 127 * ("uniqueId".hashCode() ^ uniqueId);
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_multibindings_RealElement.java |
762 | @Test
public class OSBTreeBonsaiNonLeafBucketTest {
public void testInitialization() throws Exception {
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, false,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
Assert.assertEquals(treeBucket.size(), 0);
Assert.assertFalse(treeBucket.isLeaf());
treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE,
ODurablePage.TrackMode.FULL);
Assert.assertEquals(treeBucket.size(), 0);
Assert.assertFalse(treeBucket.isLeaf());
Assert.assertEquals(treeBucket.getLeftSibling().getPageIndex(), -1);
Assert.assertEquals(treeBucket.getRightSibling().getPageIndex(), -1);
pointer.free();
}
public void testSearch() throws Exception {
long seed = 1381299802658L;// System.currentTimeMillis();
System.out.println("testSearch seed : " + seed);
TreeSet<Long> keys = new TreeSet<Long>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, false,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
int index = 0;
Map<Long, Integer> keyIndexMap = new HashMap<Long, Integer>();
for (Long key : keys) {
if (!treeBucket.addEntry(index,
new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(new OBonsaiBucketPointer(random.nextInt(Integer.MAX_VALUE),
8192 * 2), new OBonsaiBucketPointer(random.nextInt(Integer.MAX_VALUE), 8192 * 2), key, null), true))
break;
keyIndexMap.put(key, index);
index++;
}
Assert.assertEquals(treeBucket.size(), keyIndexMap.size());
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
int bucketIndex = treeBucket.find(keyIndexEntry.getKey());
Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
}
OBonsaiBucketPointer prevRight = OBonsaiBucketPointer.NULL;
for (int i = 0; i < treeBucket.size(); i++) {
OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable> entry = treeBucket.getEntry(i);
if (prevRight.getPageIndex() > 0)
Assert.assertEquals(entry.leftChild, prevRight);
prevRight = entry.rightChild;
}
OBonsaiBucketPointer prevLeft = OBonsaiBucketPointer.NULL;
for (int i = treeBucket.size() - 1; i >= 0; i--) {
OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable> entry = treeBucket.getEntry(i);
if (prevLeft.getPageIndex() > 0)
Assert.assertEquals(entry.rightChild, prevLeft);
prevLeft = entry.leftChild;
}
pointer.free();
}
public void testShrink() throws Exception {
long seed = System.currentTimeMillis();
System.out.println("testShrink seed : " + seed);
TreeSet<Long> keys = new TreeSet<Long>();
Random random = new Random(seed);
while (keys.size() < 2 * OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
keys.add(random.nextLong());
}
ODirectMemoryPointer pointer = new ODirectMemoryPointer(OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024);
OSBTreeBonsaiBucket<Long, OIdentifiable> treeBucket = new OSBTreeBonsaiBucket<Long, OIdentifiable>(pointer, 0, false,
OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE, ODurablePage.TrackMode.FULL);
int index = 0;
for (Long key : keys) {
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(new OBonsaiBucketPointer(index,
8192 * 2), new OBonsaiBucketPointer(index + 1, 8192 * 2), key, null), true))
break;
index++;
}
int originalSize = treeBucket.size();
treeBucket.shrink(treeBucket.size() / 2);
Assert.assertEquals(treeBucket.size(), index / 2);
index = 0;
final Map<Long, Integer> keyIndexMap = new HashMap<Long, Integer>();
Iterator<Long> keysIterator = keys.iterator();
while (keysIterator.hasNext() && index < treeBucket.size()) {
Long key = keysIterator.next();
keyIndexMap.put(key, index);
index++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
int bucketIndex = treeBucket.find(keyIndexEntry.getKey());
Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable> entry = treeBucket.getEntry(keyIndexEntry.getValue());
Assert.assertEquals(entry,
new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(new OBonsaiBucketPointer(keyIndexEntry.getValue(), 8192 * 2),
new OBonsaiBucketPointer(keyIndexEntry.getValue() + 1, 8192 * 2), keyIndexEntry.getKey(), null));
}
int keysToAdd = originalSize - treeBucket.size();
int addedKeys = 0;
while (keysIterator.hasNext() && index < originalSize) {
Long key = keysIterator.next();
if (!treeBucket.addEntry(index, new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(new OBonsaiBucketPointer(index,
8192 * 2), new OBonsaiBucketPointer(index + 1, 8192 * 2), key, null), true))
break;
keyIndexMap.put(key, index);
index++;
addedKeys++;
}
for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable> entry = treeBucket.getEntry(keyIndexEntry.getValue());
Assert.assertEquals(entry,
new OSBTreeBonsaiBucket.SBTreeEntry<Long, OIdentifiable>(new OBonsaiBucketPointer(keyIndexEntry.getValue(), 8192 * 2),
new OBonsaiBucketPointer(keyIndexEntry.getValue() + 1, 8192 * 2), keyIndexEntry.getKey(), null));
}
Assert.assertEquals(treeBucket.size(), originalSize);
Assert.assertEquals(addedKeys, keysToAdd);
pointer.free();
}
} | 0true
| core_src_test_java_com_orientechnologies_orient_core_index_sbtreebonsai_local_OSBTreeBonsaiNonLeafBucketTest.java |
2,243 | public class ThreadSafeInputStreamIndexInput extends InputStreamIndexInput {
public ThreadSafeInputStreamIndexInput(IndexInput indexInput, long limit) {
super(indexInput, limit);
}
@Override
public synchronized int read(byte[] b, int off, int len) throws IOException {
return super.read(b, off, len);
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_store_ThreadSafeInputStreamIndexInput.java |
1,392 | @RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class LocalRegionFactoryDefaultTest extends RegionFactoryDefaultTest {
protected Properties getCacheProperties() {
Properties props = new Properties();
props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastLocalCacheRegionFactory.class.getName());
return props;
}
@Test
public void testEntity() {
final HazelcastInstance hz = getHazelcastInstance(sf);
assertNotNull(hz);
final int count = 100;
final int childCount = 3;
insertDummyEntities(count, childCount);
sleep(1);
List<DummyEntity> list = new ArrayList<DummyEntity>(count);
Session session = sf.openSession();
try {
for (int i = 0; i < count; i++) {
DummyEntity e = (DummyEntity) session.get(DummyEntity.class, (long) i);
session.evict(e);
list.add(e);
}
} finally {
session.close();
}
session = sf.openSession();
Transaction tx = session.beginTransaction();
try {
for (DummyEntity dummy : list) {
dummy.setDate(new Date());
session.update(dummy);
}
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
Statistics stats = sf.getStatistics();
assertEquals((childCount + 1) * count, stats.getEntityInsertCount());
// twice put of entity and properties (on load and update) and once put of collection
assertEquals((childCount + 1) * count * 2 + count, stats.getSecondLevelCachePutCount());
assertEquals(childCount * count, stats.getEntityLoadCount());
assertEquals(count, stats.getSecondLevelCacheHitCount());
// collection cache miss
assertEquals(count, stats.getSecondLevelCacheMissCount());
stats.logSummary();
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate4_src_test_java_com_hazelcast_hibernate_LocalRegionFactoryDefaultTest.java |
1,374 | doWithBindings(new ActionOnMethodBinding() {
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClass,
MethodBinding method) {
if (CharOperation.equals(declaringClass.readableName(), "ceylon.language.Identifiable".toCharArray())) {
if ("equals".equals(name)
|| "hashCode".equals(name)) {
isOverriding = true;
return;
}
}
if (CharOperation.equals(declaringClass.readableName(), "ceylon.language.Object".toCharArray())) {
if ("equals".equals(name)
|| "hashCode".equals(name)
|| "toString".equals(name)) {
isOverriding = false;
return;
}
}
// try the superclass first
if (isDefinedInSuperClasses(declaringClass, method)) {
isOverriding = true;
}
if (isDefinedInSuperInterfaces(declaringClass, method)) {
isOverriding = true;
}
}
}); | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_mirror_JDTMethod.java |
311 | public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget {
private static final String JDT_DEBUG_PLUGIN_ID= "org.eclipse.jdt.debug";
public ToggleBreakpointAdapter() {
}
public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
if (selection instanceof ITextSelection) {
ITextSelection textSel= (ITextSelection) selection;
IEditorPart editorPart= (IEditorPart) part.getAdapter(IEditorPart.class);
//TODO: handle org.eclipse.ui.ide.FileStoreEditorInput
// to set breakpoints in code from archives
IEditorInput editorInput = editorPart.getEditorInput();
final IFile origSrcFile;
if (editorInput instanceof IFileEditorInput) {
origSrcFile= ((IFileEditorInput)editorInput).getFile();
} else if (editorInput instanceof FileStoreEditorInput) {
URI uri = ((FileStoreEditorInput) editorInput).getURI();
IResource resource = ExternalSourceArchiveManager.toResource(uri);
if (resource instanceof IFile) {
origSrcFile = (IFile) resource;
} else {
origSrcFile = null;
}
} else {
origSrcFile = null;
}
final int lineNumber = textSel.getStartLine()+1;
IWorkspaceRunnable wr= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
IMarker marker = findBreakpointMarker(origSrcFile, lineNumber);
if (marker != null) {
// The following will delete the associated marker
clearLineBreakpoint(origSrcFile, lineNumber);
} else {
// The following will create a marker as a side-effect
setLineBreakpoint(origSrcFile, lineNumber);
}
}
};
try {
getWorkspace().run(wr, null);
}
catch (CoreException e) {
throw new DebugException(e.getStatus());
}
}
}
private IMarker findBreakpointMarker(IFile srcFile, int lineNumber) throws CoreException {
IMarker[] markers = srcFile.findMarkers(IBreakpoint.LINE_BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
for (int k = 0; k < markers.length; k++ ){
if (((Integer) markers[k].getAttribute(IMarker.LINE_NUMBER)).intValue() == lineNumber){
return markers[k];
}
}
return null;
}
public void setLineBreakpoint(IFile file, int lineNumber) throws CoreException {
String srcFileName= file.getName();
String typeName= srcFileName.substring(0, srcFileName.lastIndexOf('.'));
Map<String,Object> bkptAttributes= new HashMap<String, Object>();
bkptAttributes.put("org.eclipse.jdt.debug.core.sourceName", srcFileName);
bkptAttributes.put("org.eclipse.jdt.debug.core.typeName", typeName);
try {
JDIDebugModel.createStratumBreakpoint(file, null, srcFileName, null, null, lineNumber, -1, -1, 0, true, bkptAttributes);
}
catch (CoreException e) {
e.printStackTrace();
}
}
public void clearLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt= findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.delete();
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
public void disableLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt= findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.setEnabled(false);
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
public void enableLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt= findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.setEnabled(true);
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
/**
* Returns a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number.
*
* @param typeName fully qualified type name
* @param lineNumber line number
* @return a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number or <code>null</code>
* if no such breakpoint is registered
* @exception CoreException if unable to retrieve the associated marker
* attributes (line number).
*/
public static IJavaLineBreakpoint findStratumBreakpoint(IResource resource, int lineNumber) throws CoreException {
String modelId= JDT_DEBUG_PLUGIN_ID;
String markerType= "org.eclipse.jdt.debug.javaStratumLineBreakpointMarker";
IBreakpointManager manager= DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints= manager.getBreakpoints(modelId);
for (int i = 0; i < breakpoints.length; i++) {
if (!(breakpoints[i] instanceof IJavaLineBreakpoint)) {
continue;
}
IJavaLineBreakpoint breakpoint = (IJavaLineBreakpoint) breakpoints[i];
IMarker marker = breakpoint.getMarker();
if (marker != null && marker.exists() && marker.getType().equals(markerType)) {
if (breakpoint.getLineNumber() == lineNumber &&
resource.equals(marker.getResource())) {
return breakpoint;
}
}
}
return null;
}
public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) {
return true;
}
public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
}
public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) {
return false;
}
public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
}
public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) {
return false;
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_ToggleBreakpointAdapter.java |
252 | public final class RateLimitedFSDirectory extends FilterDirectory{
private final StoreRateLimiting.Provider rateLimitingProvider;
private final StoreRateLimiting.Listener rateListener;
public RateLimitedFSDirectory(FSDirectory wrapped, StoreRateLimiting.Provider rateLimitingProvider,
StoreRateLimiting.Listener rateListener) {
super(wrapped);
this.rateLimitingProvider = rateLimitingProvider;
this.rateListener = rateListener;
}
@Override
public IndexOutput createOutput(String name, IOContext context) throws IOException {
final IndexOutput output = in.createOutput(name, context);
StoreRateLimiting rateLimiting = rateLimitingProvider.rateLimiting();
StoreRateLimiting.Type type = rateLimiting.getType();
RateLimiter limiter = rateLimiting.getRateLimiter();
if (type == StoreRateLimiting.Type.NONE || limiter == null) {
return output;
}
if (context.context == Context.MERGE) {
// we are mering, and type is either MERGE or ALL, rate limit...
return new RateLimitedIndexOutput(limiter, rateListener, output);
}
if (type == StoreRateLimiting.Type.ALL) {
return new RateLimitedIndexOutput(limiter, rateListener, output);
}
// we shouldn't really get here...
return output;
}
@Override
public void close() throws IOException {
in.close();
}
@Override
public String toString() {
StoreRateLimiting rateLimiting = rateLimitingProvider.rateLimiting();
StoreRateLimiting.Type type = rateLimiting.getType();
RateLimiter limiter = rateLimiting.getRateLimiter();
if (type == StoreRateLimiting.Type.NONE || limiter == null) {
return StoreUtils.toString(in);
} else {
return "rate_limited(" + StoreUtils.toString(in) + ", type=" + type.name() + ", rate=" + limiter.getMbPerSec() + ")";
}
}
static final class RateLimitedIndexOutput extends BufferedIndexOutput {
private final IndexOutput delegate;
private final BufferedIndexOutput bufferedDelegate;
private final RateLimiter rateLimiter;
private final StoreRateLimiting.Listener rateListener;
RateLimitedIndexOutput(final RateLimiter rateLimiter, final StoreRateLimiting.Listener rateListener, final IndexOutput delegate) {
super(delegate instanceof BufferedIndexOutput ? ((BufferedIndexOutput) delegate).getBufferSize() : BufferedIndexOutput.DEFAULT_BUFFER_SIZE);
if (delegate instanceof BufferedIndexOutput) {
bufferedDelegate = (BufferedIndexOutput) delegate;
this.delegate = delegate;
} else {
this.delegate = delegate;
bufferedDelegate = null;
}
this.rateLimiter = rateLimiter;
this.rateListener = rateListener;
}
@Override
protected void flushBuffer(byte[] b, int offset, int len) throws IOException {
rateListener.onPause(rateLimiter.pause(len));
if (bufferedDelegate != null) {
bufferedDelegate.flushBuffer(b, offset, len);
} else {
delegate.writeBytes(b, offset, len);
}
}
@Override
public long length() throws IOException {
return delegate.length();
}
@Override
public void seek(long pos) throws IOException {
flush();
delegate.seek(pos);
}
@Override
public void flush() throws IOException {
try {
super.flush();
} finally {
delegate.flush();
}
}
@Override
public void setLength(long length) throws IOException {
delegate.setLength(length);
}
@Override
public void close() throws IOException {
try {
super.close();
} finally {
delegate.close();
}
}
}
} | 1no label
| src_main_java_org_apache_lucene_store_RateLimitedFSDirectory.java |
1,329 | PhasedUnit phasedUnit = new CeylonSourceParser<PhasedUnit>() {
@Override
protected String getCharset() {
try {
//TODO: is this correct? does this file actually
// live in the project, or is it external?
// should VirtualFile have a getCharset()?
return javaProject != null ?
javaProject.getProject().getDefaultCharset()
: ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected PhasedUnit createPhasedUnit(CompilationUnit cu, Package pkg, CommonTokenStream tokenStream) {
if (referencedProject == null) {
return new ExternalPhasedUnit(file, srcDir, cu,
pkg, getModuleManager(),
getTypeChecker(), tokenStream.getTokens());
}
else {
return new CrossProjectPhasedUnit(file, srcDir, cu,
pkg, getModuleManager(),
getTypeChecker(), tokenStream.getTokens(), referencedProject);
}
}
}.parseFileToPhasedUnit(getModuleManager(), getTypeChecker(), file, srcDir, pkg); | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_JDTModuleManager.java |
808 | public interface OProperty extends Comparable<OProperty> {
public static enum ATTRIBUTES {
LINKEDTYPE, LINKEDCLASS, MIN, MAX, MANDATORY, NAME, NOTNULL, REGEXP, TYPE, CUSTOM, READONLY, COLLATE
}
public String getName();
/**
* Returns the full name as <class>.<property>
*/
public String getFullName();
public OProperty setName(String iName);
public void set(ATTRIBUTES attribute, Object iValue);
public OType getType();
/**
* Returns the linked class in lazy mode because while unmarshalling the class could be not loaded yet.
*
* @return
*/
public OClass getLinkedClass();
public OType getLinkedType();
public boolean isNotNull();
public OProperty setNotNull(boolean iNotNull);
public OCollate getCollate();
public OProperty setCollate(String iCollateName);
public boolean isMandatory();
public OProperty setMandatory(boolean mandatory);
boolean isReadonly();
OPropertyImpl setReadonly(boolean iReadonly);
/**
* Min behavior depends on the Property OType.
* <p>
* <ul>
* <li>String : minimum length</li>
* <li>Number : minimum value</li>
* <li>date and time : minimum time in millisecond, date must be written in the storage date format</li>
* <li>binary : minimum size of the byte array</li>
* <li>List,Set,Collection : minimum size of the collection</li>
* </ul>
*
* @return String, can be null
*/
public String getMin();
/**
* @see OProperty#getMin()
* @param min
* can be null
* @return this property
*/
public OProperty setMin(String min);
/**
* Max behavior depends on the Property OType.
* <p>
* <ul>
* <li>String : maximum length</li>
* <li>Number : maximum value</li>
* <li>date and time : maximum time in millisecond, date must be written in the storage date format</li>
* <li>binary : maximum size of the byte array</li>
* <li>List,Set,Collection : maximum size of the collection</li>
* </ul>
*
* @return String, can be null
*/
public String getMax();
/**
* @see OProperty#getMax()
* @param max
* can be null
* @return this property
*/
public OProperty setMax(String max);
/**
* Creates an index on this property. Indexes speed up queries but slow down insert and update operations. For massive inserts we
* suggest to remove the index, make the massive insert and recreate it.
*
*
* @param iType
* One of types supported.
* <ul>
* <li>UNIQUE: Doesn't allow duplicates</li>
* <li>NOTUNIQUE: Allow duplicates</li>
* <li>FULLTEXT: Indexes single word for full text search</li>
* </ul>
* @return see {@link OClass#createIndex(String, OClass.INDEX_TYPE, String...)}.
*/
public OIndex<?> createIndex(final OClass.INDEX_TYPE iType);
/**
* Creates an index on this property. Indexes speed up queries but slow down insert and update operations. For massive inserts we
* suggest to remove the index, make the massive insert and recreate it.
*
*
* @param iType
* @return see {@link OClass#createIndex(String, OClass.INDEX_TYPE, String...)}.
*/
public OIndex<?> createIndex(final String iType);
/**
* Remove the index on property
*
* @return
* @deprecated Use {@link com.orientechnologies.orient.core.index.OIndexManager#dropIndex(String)} instead.
*/
@Deprecated
public OPropertyImpl dropIndexes();
/**
* @return All indexes in which this property participates as first key item.
*
* @deprecated Use {@link OClass#getInvolvedIndexes(String...)} instead.
*/
@Deprecated
public Set<OIndex<?>> getIndexes();
/**
* @return The first index in which this property participates as first key item.
*
* @deprecated Use {@link OClass#getInvolvedIndexes(String...)} instead.
*/
@Deprecated
public OIndex<?> getIndex();
/**
* @return All indexes in which this property participates.
*/
public Collection<OIndex<?>> getAllIndexes();
/**
* Indicates whether property is contained in indexes as its first key item. If you would like to fetch all indexes or check
* property presence in other indexes use {@link #getAllIndexes()} instead.
*
* @return <code>true</code> if and only if this property is contained in indexes as its first key item.
* @deprecated Use {@link OClass#areIndexed(String...)} instead.
*/
@Deprecated
public boolean isIndexed();
public String getRegexp();
public OPropertyImpl setRegexp(String regexp);
/**
* Change the type. It checks for compatibility between the change of type.
*
* @param iType
*/
public OPropertyImpl setType(final OType iType);
public String getCustom(final String iName);
public OPropertyImpl setCustom(final String iName, final String iValue);
public void removeCustom(final String iName);
public void clearCustom();
public Set<String> getCustomKeys();
public Object get(ATTRIBUTES iAttribute);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OProperty.java |
841 | public class ReferenceWrapper {
private Data value;
public Data get() {
return value;
}
public void set(Data value) {
this.value = value;
}
public boolean compareAndSet(Data expect, Data value) {
if (!contains(expect)) {
return false;
}
this.value = value;
return true;
}
public boolean contains(Data expected) {
if (value == null) {
return expected == null;
}
return value.equals(expected);
}
public Data getAndSet(Data value) {
Data tempValue = this.value;
this.value = value;
return tempValue;
}
public boolean isNull() {
return value == null;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_ReferenceWrapper.java |
557 | public final class AddressHelper {
private static final int MAX_PORT_TRIES = 3;
private static final int INITIAL_FIRST_PORT = 5701;
private AddressHelper() {
}
public static Collection<InetSocketAddress> getSocketAddresses(String address) {
final AddressHolder addressHolder = AddressUtil.getAddressHolder(address, -1);
final String scopedAddress = addressHolder.getScopeId() != null
? addressHolder.getAddress() + "%" + addressHolder.getScopeId()
: addressHolder.getAddress();
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getByName(scopedAddress);
} catch (UnknownHostException ignored) {
Logger.getLogger(AddressHelper.class).finest("Address not available", ignored);
}
return getPossibleSocketAddresses(inetAddress, addressHolder.getPort(), scopedAddress);
}
public static Collection<InetSocketAddress> getPossibleSocketAddresses(
InetAddress inetAddress, int port, String scopedAddress) {
int possiblePort = port;
int portTryCount = 1;
if (possiblePort == -1) {
portTryCount = MAX_PORT_TRIES;
possiblePort = INITIAL_FIRST_PORT;
}
final Collection<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
if (inetAddress == null) {
for (int i = 0; i < portTryCount; i++) {
socketAddresses.add(new InetSocketAddress(scopedAddress, possiblePort + i));
}
} else if (inetAddress instanceof Inet4Address) {
for (int i = 0; i < portTryCount; i++) {
socketAddresses.add(new InetSocketAddress(inetAddress, possiblePort + i));
}
} else if (inetAddress instanceof Inet6Address) {
final Collection<Inet6Address> addresses = getPossibleInetAddressesFor((Inet6Address) inetAddress);
for (Inet6Address inet6Address : addresses) {
for (int i = 0; i < portTryCount; i++) {
socketAddresses.add(new InetSocketAddress(inet6Address, possiblePort + i));
}
}
}
return socketAddresses;
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_util_AddressHelper.java |
1,853 | static class Builder {
private final List<Element> elements = Lists.newArrayList();
private final List<Module> modules = Lists.newArrayList();
/**
* lazily constructed
*/
private State state;
private InjectorImpl parent;
private Stage stage;
/**
* null unless this exists in a {@link Binder#newPrivateBinder private environment}
*/
private PrivateElementsImpl privateElements;
Builder parent(InjectorImpl parent) {
this.parent = parent;
this.state = new InheritingState(parent.state);
return this;
}
Builder stage(Stage stage) {
this.stage = stage;
return this;
}
Builder privateElements(PrivateElements privateElements) {
this.privateElements = (PrivateElementsImpl) privateElements;
this.elements.addAll(privateElements.getElements());
return this;
}
void addModules(Iterable<? extends Module> modules) {
for (Module module : modules) {
this.modules.add(module);
}
}
/**
* Synchronize on this before calling {@link #build}.
*/
Object lock() {
return getState().lock();
}
/**
* Creates and returns the injector shells for the current modules. Multiple shells will be
* returned if any modules contain {@link Binder#newPrivateBinder private environments}. The
* primary injector will be first in the returned list.
*/
List<InjectorShell> build(Initializer initializer, BindingProcessor bindingProcessor,
Stopwatch stopwatch, Errors errors) {
checkState(stage != null, "Stage not initialized");
checkState(privateElements == null || parent != null, "PrivateElements with no parent");
checkState(state != null, "no state. Did you remember to lock() ?");
InjectorImpl injector = new InjectorImpl(parent, state, initializer);
if (privateElements != null) {
privateElements.initInjector(injector);
}
// bind Stage and Singleton if this is a top-level injector
if (parent == null) {
modules.add(0, new RootModule(stage));
new TypeConverterBindingProcessor(errors).prepareBuiltInConverters(injector);
}
elements.addAll(Elements.getElements(stage, modules));
stopwatch.resetAndLog("Module execution");
new MessageProcessor(errors).process(injector, elements);
new TypeListenerBindingProcessor(errors).process(injector, elements);
List<TypeListenerBinding> listenerBindings = injector.state.getTypeListenerBindings();
injector.membersInjectorStore = new MembersInjectorStore(injector, listenerBindings);
stopwatch.resetAndLog("TypeListeners creation");
new ScopeBindingProcessor(errors).process(injector, elements);
stopwatch.resetAndLog("Scopes creation");
new TypeConverterBindingProcessor(errors).process(injector, elements);
stopwatch.resetAndLog("Converters creation");
bindInjector(injector);
bindLogger(injector);
bindingProcessor.process(injector, elements);
stopwatch.resetAndLog("Binding creation");
List<InjectorShell> injectorShells = Lists.newArrayList();
injectorShells.add(new InjectorShell(this, elements, injector));
// recursively build child shells
PrivateElementProcessor processor = new PrivateElementProcessor(errors, stage);
processor.process(injector, elements);
for (Builder builder : processor.getInjectorShellBuilders()) {
injectorShells.addAll(builder.build(initializer, bindingProcessor, stopwatch, errors));
}
stopwatch.resetAndLog("Private environment creation");
return injectorShells;
}
private State getState() {
if (state == null) {
state = new InheritingState(State.NONE);
}
return state;
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_InjectorShell.java |
1,296 | @Repository("blSearchSynonymDao")
public class SearchSynonymDaoImpl implements SearchSynonymDao {
@PersistenceContext(unitName = "blPU")
protected EntityManager em;
@SuppressWarnings("unchecked")
public List<SearchSynonym> getAllSynonyms() {
Query query = em.createNamedQuery("BC_READ_SEARCH_SYNONYMS");
List<SearchSynonym> result;
try {
result = (List<SearchSynonym>) query.getResultList();
} catch (NoResultException e) {
result = null;
}
return result;
}
public void createSynonym(SearchSynonym synonym) {
em.persist(synonym);
}
public void deleteSynonym(SearchSynonym synonym) {
em.remove(synonym);
}
public void updateSynonym(SearchSynonym synonym) {
em.merge(synonym);
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_dao_SearchSynonymDaoImpl.java |
649 | public class StatusExposingServletResponse extends HttpServletResponseWrapper {
private int httpStatus=200;
public StatusExposingServletResponse(HttpServletResponse response) {
super(response);
}
@Override
public void sendError(int sc) throws IOException {
httpStatus = sc;
super.sendError(sc);
}
@Override
public void sendError(int sc, String msg) throws IOException {
httpStatus = sc;
super.sendError(sc, msg);
}
@Override
public void setStatus(int sc) {
httpStatus = sc;
super.setStatus(sc);
}
@Override
public void reset() {
super.reset();
this.httpStatus = SC_OK;
}
@Override
public void setStatus(int status, String string) {
super.setStatus(status, string);
this.httpStatus = status;
}
public int getStatus() {
return httpStatus;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_web_util_StatusExposingServletResponse.java |
1,666 | private static final class FindSuccessorNodeCall extends NodeCall<Long> {
private long keyId;
public FindSuccessorNodeCall() {
}
private FindSuccessorNodeCall(long nodeId, String memberUUID, long keyId) {
super(nodeId, memberUUID);
this.keyId = keyId;
}
@Override
protected Long call(ODHTNode node) {
return node.findSuccessor(keyId);
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeLong(keyId);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
keyId = in.readLong();
}
} | 0true
| distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_oldsharding_hazelcast_OHazelcastDHTNodeProxy.java |
632 | public class IndexStatus implements Iterable<IndexShardStatus> {
private final String index;
private final Map<Integer, IndexShardStatus> indexShards;
IndexStatus(String index, ShardStatus[] shards) {
this.index = index;
Map<Integer, List<ShardStatus>> tmpIndexShards = Maps.newHashMap();
for (ShardStatus shard : shards) {
List<ShardStatus> lst = tmpIndexShards.get(shard.getShardRouting().id());
if (lst == null) {
lst = newArrayList();
tmpIndexShards.put(shard.getShardRouting().id(), lst);
}
lst.add(shard);
}
indexShards = Maps.newHashMap();
for (Map.Entry<Integer, List<ShardStatus>> entry : tmpIndexShards.entrySet()) {
indexShards.put(entry.getKey(), new IndexShardStatus(entry.getValue().get(0).getShardRouting().shardId(), entry.getValue().toArray(new ShardStatus[entry.getValue().size()])));
}
}
public String getIndex() {
return this.index;
}
/**
* A shard id to index shard status map (note, index shard status is the replication shard group that maps
* to the shard id).
*/
public Map<Integer, IndexShardStatus> getShards() {
return this.indexShards;
}
/**
* Returns only the primary shards store size in bytes.
*/
public ByteSizeValue getPrimaryStoreSize() {
long bytes = -1;
for (IndexShardStatus shard : this) {
if (shard.getPrimaryStoreSize() != null) {
if (bytes == -1) {
bytes = 0;
}
bytes += shard.getPrimaryStoreSize().bytes();
}
}
if (bytes == -1) {
return null;
}
return new ByteSizeValue(bytes);
}
/**
* Returns the full store size in bytes, of both primaries and replicas.
*/
public ByteSizeValue getStoreSize() {
long bytes = -1;
for (IndexShardStatus shard : this) {
if (shard.getStoreSize() != null) {
if (bytes == -1) {
bytes = 0;
}
bytes += shard.getStoreSize().bytes();
}
}
if (bytes == -1) {
return null;
}
return new ByteSizeValue(bytes);
}
public long getTranslogOperations() {
long translogOperations = -1;
for (IndexShardStatus shard : this) {
if (shard.getTranslogOperations() != -1) {
if (translogOperations == -1) {
translogOperations = 0;
}
translogOperations += shard.getTranslogOperations();
}
}
return translogOperations;
}
private transient DocsStatus docs;
public DocsStatus getDocs() {
if (docs != null) {
return docs;
}
DocsStatus docs = null;
for (IndexShardStatus shard : this) {
if (shard.getDocs() == null) {
continue;
}
if (docs == null) {
docs = new DocsStatus();
}
docs.numDocs += shard.getDocs().getNumDocs();
docs.maxDoc += shard.getDocs().getMaxDoc();
docs.deletedDocs += shard.getDocs().getDeletedDocs();
}
this.docs = docs;
return docs;
}
/**
* Total merges of this index.
*/
public MergeStats getMergeStats() {
MergeStats mergeStats = new MergeStats();
for (IndexShardStatus shard : this) {
mergeStats.add(shard.getMergeStats());
}
return mergeStats;
}
public RefreshStats getRefreshStats() {
RefreshStats refreshStats = new RefreshStats();
for (IndexShardStatus shard : this) {
refreshStats.add(shard.getRefreshStats());
}
return refreshStats;
}
public FlushStats getFlushStats() {
FlushStats flushStats = new FlushStats();
for (IndexShardStatus shard : this) {
flushStats.add(shard.getFlushStats());
}
return flushStats;
}
@Override
public Iterator<IndexShardStatus> iterator() {
return indexShards.values().iterator();
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_status_IndexStatus.java |
67 | public class FieldType implements Serializable {
private static final long serialVersionUID = 1L;
private static final Map<String, FieldType> TYPES = new HashMap<String, FieldType>();
public static final FieldType BOOLEAN = new FieldType("BOOLEAN", "Boolean");
public static final FieldType DATE = new FieldType("DATE", "Date");
public static final FieldType TIME = new FieldType("TIME", "Time");
public static final FieldType INTEGER = new FieldType("INTEGER", "Integer");
public static final FieldType DECIMAL = new FieldType("DECIMAL", "Decimal");
public static final FieldType STRING = new FieldType("STRING", "String");
public static final FieldType RICH_TEXT = new FieldType("RICH_TEXT", "Rich Text");
public static final FieldType HTML = new FieldType("HTML", "HTML");
public static final FieldType ENUMERATION = new FieldType("ENUMERATION", "Enumeration");
public static FieldType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public FieldType() {
//do nothing
}
public FieldType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FieldType other = (FieldType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
} | 1no label
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_field_type_FieldType.java |
986 | indexAction.execute(indexRequest, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse result) {
indexResponses.set(indexCounter.getAndIncrement(), result);
if (completionCounter.decrementAndGet() == 0) {
listener.onResponse(newResponseInstance(request, indexResponses));
}
}
@Override
public void onFailure(Throwable e) {
int index = indexCounter.getAndIncrement();
if (accumulateExceptions()) {
indexResponses.set(index, e);
}
if (completionCounter.decrementAndGet() == 0) {
listener.onResponse(newResponseInstance(request, indexResponses));
}
}
}); | 0true
| src_main_java_org_elasticsearch_action_support_replication_TransportIndicesReplicationOperationAction.java |
2,245 | public static class DocIdAndVersion {
public final int docId;
public final long version;
public final AtomicReaderContext context;
public DocIdAndVersion(int docId, long version, AtomicReaderContext context) {
this.docId = docId;
this.version = version;
this.context = context;
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_uid_Versions.java |
1,597 | class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
int primariesInitialRecoveries = settings.getAsInt(CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES, ThrottlingAllocationDecider.this.primariesInitialRecoveries);
if (primariesInitialRecoveries != ThrottlingAllocationDecider.this.primariesInitialRecoveries) {
logger.info("updating [cluster.routing.allocation.node_initial_primaries_recoveries] from [{}] to [{}]", ThrottlingAllocationDecider.this.primariesInitialRecoveries, primariesInitialRecoveries);
ThrottlingAllocationDecider.this.primariesInitialRecoveries = primariesInitialRecoveries;
}
int concurrentRecoveries = settings.getAsInt(CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, ThrottlingAllocationDecider.this.concurrentRecoveries);
if (concurrentRecoveries != ThrottlingAllocationDecider.this.concurrentRecoveries) {
logger.info("updating [cluster.routing.allocation.node_concurrent_recoveries] from [{}] to [{}]", ThrottlingAllocationDecider.this.concurrentRecoveries, concurrentRecoveries);
ThrottlingAllocationDecider.this.concurrentRecoveries = concurrentRecoveries;
}
}
} | 0true
| src_main_java_org_elasticsearch_cluster_routing_allocation_decider_ThrottlingAllocationDecider.java |
2,153 | public class AllDocIdSet extends DocIdSet {
private final int maxDoc;
public AllDocIdSet(int maxDoc) {
this.maxDoc = maxDoc;
}
/**
* Does not go to the reader and ask for data, so can be cached.
*/
@Override
public boolean isCacheable() {
return true;
}
@Override
public DocIdSetIterator iterator() throws IOException {
return new Iterator(maxDoc);
}
@Override
public Bits bits() throws IOException {
return new Bits.MatchAllBits(maxDoc);
}
public static final class Iterator extends DocIdSetIterator {
private final int maxDoc;
private int doc = -1;
public Iterator(int maxDoc) {
this.maxDoc = maxDoc;
}
@Override
public int docID() {
return doc;
}
@Override
public int nextDoc() throws IOException {
if (++doc < maxDoc) {
return doc;
}
return doc = NO_MORE_DOCS;
}
@Override
public int advance(int target) throws IOException {
doc = target;
if (doc < maxDoc) {
return doc;
}
return doc = NO_MORE_DOCS;
}
@Override
public long cost() {
return maxDoc;
}
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_docset_AllDocIdSet.java |
248 | @Service("blCurrencyService")
public class BroadleafCurrencyServiceImpl implements BroadleafCurrencyService {
@Resource(name="blCurrencyDao")
protected BroadleafCurrencyDao currencyDao;
/**
* Returns the default Broadleaf currency
* @return The default currency
*/
@Override
public BroadleafCurrency findDefaultBroadleafCurrency() {
return currencyDao.findDefaultBroadleafCurrency();
}
/**
* @return The currency for the passed in code
*/
@Override
public BroadleafCurrency findCurrencyByCode(String currencyCode) {
return currencyDao.findCurrencyByCode(currencyCode);
}
/**
* Returns a list of all the Broadleaf Currencies
*@return List of currencies
*/
@Override
public List<BroadleafCurrency> getAllCurrencies() {
return currencyDao.getAllCurrencies();
}
@Override
public BroadleafCurrency save(BroadleafCurrency currency) {
return currencyDao.save(currency);
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_currency_service_BroadleafCurrencyServiceImpl.java |
1,622 | static class ThreadCpuInfo {
final Thread thread;
long lastSet = 0;
long lastValue = 0;
ThreadCpuInfo(Thread thread) {
this.thread = thread;
}
public double setNewValue(long newValue, long now) {
double diff = newValue - lastValue;
double timeDiff = now - lastSet;
lastSet = now;
lastValue = newValue;
return diff / timeDiff;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ThreadCpuInfo that = (ThreadCpuInfo) o;
return thread.getId() == that.thread.getId();
}
@Override
public int hashCode() {
return thread.hashCode();
}
@Override
public String toString() {
return "ThreadCpuInfo{" +
"name='" + thread.getName() + '\'' +
", threadId=" + thread.getId() +
", lastSet=" + lastSet +
", lastValue=" + lastValue +
'}';
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_management_ThreadMonitoringService.java |
1,665 | map.addEntryListener(new EntryAdapter<String, String>() {
public void entryEvicted(EntryEvent<String, String> event) {
latch.countDown();
}
}, true); | 0true
| hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java |
16 | final class DescendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
3,506 | public class MapperParsingException extends MapperException {
public MapperParsingException(String message) {
super(message);
}
public MapperParsingException(String message, Throwable cause) {
super(message, cause);
}
@Override
public RestStatus status() {
return RestStatus.BAD_REQUEST;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_MapperParsingException.java |
353 | public static class Connection {
private final Node node;
private final Client client;
public Connection(Node node, Client client) {
this.node = node;
this.client = client;
Preconditions.checkNotNull(this.client, "Unable to instantiate Elasticsearch Client object");
// node may be null
}
public Node getNode() {
return node;
}
public Client getClient() {
return client;
}
} | 0true
| titan-es_src_main_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchSetup.java |
11 | @edu.umd.cs.findbugs.annotations.SuppressWarnings("MS_OOI_PKGPROTECT")
public interface TextCommandConstants {
int MONTH_SECONDS = 60 * 60 * 24 * 30;
byte[] SPACE = stringToBytes(" ");
byte[] RETURN = stringToBytes("\r\n");
byte[] FLAG_ZERO = stringToBytes(" 0 ");
byte[] VALUE_SPACE = stringToBytes("VALUE ");
byte[] DELETED = stringToBytes("DELETED\r\n");
byte[] STORED = stringToBytes("STORED\r\n");
byte[] TOUCHED = stringToBytes("TOUCHED\r\n");
byte[] NOT_STORED = stringToBytes("NOT_STORED\r\n");
byte[] NOT_FOUND = stringToBytes("NOT_FOUND\r\n");
byte[] RETURN_END = stringToBytes("\r\nEND\r\n");
byte[] END = stringToBytes("END\r\n");
byte[] ERROR = stringToBytes("ERROR");
byte[] CLIENT_ERROR = stringToBytes("CLIENT_ERROR ");
byte[] SERVER_ERROR = stringToBytes("SERVER_ERROR ");
enum TextCommandType {
GET((byte) 0),
PARTIAL_GET((byte) 1),
GETS((byte) 2),
SET((byte) 3),
APPEND((byte) 4),
PREPEND((byte) 5),
ADD((byte) 6),
REPLACE((byte) 7),
DELETE((byte) 8),
QUIT((byte) 9),
STATS((byte) 10),
GET_END((byte) 11),
ERROR_CLIENT((byte) 12),
ERROR_SERVER((byte) 13),
UNKNOWN((byte) 14),
VERSION((byte) 15),
TOUCH((byte) 16),
INCREMENT((byte) 17),
DECREMENT((byte) 18),
HTTP_GET((byte) 30),
HTTP_POST((byte) 31),
HTTP_PUT((byte) 32),
HTTP_DELETE((byte) 33),
NO_OP((byte) 98),
STOP((byte) 99);
final byte value;
TextCommandType(byte type) {
value = type;
}
public byte getValue() {
return value;
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_TextCommandConstants.java |
1,689 | public class ONetworkProtocolBinary extends OBinaryNetworkProtocolAbstract {
protected OClientConnection connection;
protected OUser account;
private String dbType;
public ONetworkProtocolBinary() {
super("OrientDB <- BinaryClient/?");
}
public ONetworkProtocolBinary(final String iThreadName) {
super(iThreadName);
}
@Override
public void config(final OServer iServer, final Socket iSocket, final OContextConfiguration iConfig,
final List<?> iStatelessCommands, List<?> iStatefulCommands) throws IOException {
// CREATE THE CLIENT CONNECTION
connection = OClientConnectionManager.instance().connect(this);
super.config(iServer, iSocket, iConfig, iStatelessCommands, iStatefulCommands);
// SEND PROTOCOL VERSION
channel.writeShort((short) OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION);
channel.flush();
start();
setName("OrientDB <- BinaryClient (" + iSocket.getRemoteSocketAddress() + ")");
}
@Override
public int getVersion() {
return OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION;
}
@Override
protected void onBeforeRequest() throws IOException {
waitNodeIsOnline();
connection = OClientConnectionManager.instance().getConnection(clientTxId);
if (clientTxId < 0) {
short protocolId = 0;
if (connection != null)
protocolId = connection.data.protocolVersion;
connection = OClientConnectionManager.instance().connect(this);
if (connection != null)
connection.data.protocolVersion = protocolId;
}
if (connection != null) {
ODatabaseRecordThreadLocal.INSTANCE.set(connection.database);
if (connection.database != null) {
connection.data.lastDatabase = connection.database.getName();
connection.data.lastUser = connection.database.getUser() != null ? connection.database.getUser().getName() : null;
} else {
connection.data.lastDatabase = null;
connection.data.lastUser = null;
}
++connection.data.totalRequests;
setDataCommandInfo("Listening");
connection.data.commandDetail = "-";
connection.data.lastCommandReceived = System.currentTimeMillis();
} else {
if (requestType != OChannelBinaryProtocol.REQUEST_DB_CLOSE && requestType != OChannelBinaryProtocol.REQUEST_SHUTDOWN) {
OLogManager.instance().debug(this, "Found unknown session %d, shutdown current connection", clientTxId);
shutdown();
throw new OIOException("Found unknown session " + clientTxId);
}
}
OServerPluginHelper.invokeHandlerCallbackOnBeforeClientRequest(server, connection, (byte) requestType);
}
@Override
protected void onAfterRequest() throws IOException {
OServerPluginHelper.invokeHandlerCallbackOnAfterClientRequest(server, connection, (byte) requestType);
if (connection != null) {
if (connection.database != null)
if (!connection.database.isClosed())
connection.database.getLevel1Cache().clear();
connection.data.lastCommandExecutionTime = System.currentTimeMillis() - connection.data.lastCommandReceived;
connection.data.totalCommandExecutionTime += connection.data.lastCommandExecutionTime;
connection.data.lastCommandInfo = connection.data.commandInfo;
connection.data.lastCommandDetail = connection.data.commandDetail;
setDataCommandInfo("Listening");
connection.data.commandDetail = "-";
}
}
protected boolean executeRequest() throws IOException {
switch (requestType) {
case OChannelBinaryProtocol.REQUEST_SHUTDOWN:
shutdownConnection();
break;
case OChannelBinaryProtocol.REQUEST_CONNECT:
connect();
break;
case OChannelBinaryProtocol.REQUEST_DB_LIST:
listDatabases();
break;
case OChannelBinaryProtocol.REQUEST_DB_OPEN:
openDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_RELOAD:
reloadDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_CREATE:
createDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_CLOSE:
closeDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_EXIST:
existsDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_DROP:
dropDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_SIZE:
sizeDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_COUNTRECORDS:
countDatabaseRecords();
break;
case OChannelBinaryProtocol.REQUEST_DB_COPY:
copyDatabase();
break;
case OChannelBinaryProtocol.REQUEST_REPLICATION:
replicationDatabase();
break;
case OChannelBinaryProtocol.REQUEST_CLUSTER:
distributedCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATASEGMENT_ADD:
addDataSegment();
break;
case OChannelBinaryProtocol.REQUEST_DATASEGMENT_DROP:
dropDataSegment();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_COUNT:
countClusters();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DATARANGE:
rangeCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_ADD:
addCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DROP:
removeCluster();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_METADATA:
readRecordMetadata();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_LOAD:
readRecord();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_CREATE:
createRecord();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_UPDATE:
updateRecord();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_DELETE:
deleteRecord();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_HIGHER:
higherPositions();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_CEILING:
ceilingPositions();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_LOWER:
lowerPositions();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_FLOOR:
floorPositions();
break;
case OChannelBinaryProtocol.REQUEST_COUNT:
throw new UnsupportedOperationException("Operation OChannelBinaryProtocol.REQUEST_COUNT has been deprecated");
case OChannelBinaryProtocol.REQUEST_COMMAND:
command();
break;
case OChannelBinaryProtocol.REQUEST_TX_COMMIT:
commit();
break;
case OChannelBinaryProtocol.REQUEST_CONFIG_GET:
configGet();
break;
case OChannelBinaryProtocol.REQUEST_CONFIG_SET:
configSet();
break;
case OChannelBinaryProtocol.REQUEST_CONFIG_LIST:
configList();
break;
case OChannelBinaryProtocol.REQUEST_DB_FREEZE:
freezeDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_RELEASE:
releaseDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE:
freezeCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE:
releaseCluster();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT:
cleanOutRecord();
break;
default:
setDataCommandInfo("Command not supported");
return false;
}
return true;
}
private void lowerPositions() throws IOException {
setDataCommandInfo("Retrieve lower positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
final OPhysicalPosition[] previousPositions = connection.database.getStorage().lowerPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (previousPositions != null) {
channel.writeInt(previousPositions.length);
for (final OPhysicalPosition physicalPosition : previousPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private void floorPositions() throws IOException {
setDataCommandInfo("Retrieve floor positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
final OPhysicalPosition[] previousPositions = connection.database.getStorage().floorPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (previousPositions != null) {
channel.writeInt(previousPositions.length);
for (final OPhysicalPosition physicalPosition : previousPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private void higherPositions() throws IOException {
setDataCommandInfo("Retrieve higher positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
OPhysicalPosition[] nextPositions = connection.database.getStorage().higherPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (nextPositions != null) {
channel.writeInt(nextPositions.length);
for (final OPhysicalPosition physicalPosition : nextPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private void ceilingPositions() throws IOException {
setDataCommandInfo("Retrieve ceiling positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
final OPhysicalPosition[] previousPositions = connection.database.getStorage().ceilingPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (previousPositions != null) {
channel.writeInt(previousPositions.length);
for (final OPhysicalPosition physicalPosition : previousPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
protected void checkServerAccess(final String iResource) {
if (connection.serverUser == null)
throw new OSecurityAccessException("Server user not authenticated.");
if (!server.authenticate(connection.serverUser.name, null, iResource))
throw new OSecurityAccessException("User '" + connection.serverUser.name + "' cannot access to the resource [" + iResource
+ "]. Use another server user or change permission in the file config/orientdb-server-config.xml");
}
protected ODatabaseComplex<?> openDatabase(final ODatabaseComplex<?> database, final String iUser, final String iPassword) {
if (database.isClosed())
if (database.getStorage() instanceof OStorageMemory && !database.exists())
database.create();
else {
try {
database.open(iUser, iPassword);
} catch (OSecurityException e) {
// TRY WITH SERVER'S USER
try {
connection.serverUser = server.serverLogin(iUser, iPassword, "database.passthrough");
} catch (OSecurityException ex) {
throw e;
}
// SERVER AUTHENTICATED, BYPASS SECURITY
database.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE);
database.open(iUser, iPassword);
}
}
return database;
}
protected void addDataSegment() throws IOException {
setDataCommandInfo("Add data segment");
if (!isConnectionAlive())
return;
final String name = channel.readString();
final String location = channel.readString();
final int num = connection.database.addDataSegment(name, location);
beginResponse();
try {
sendOk(clientTxId);
channel.writeInt(num);
} finally {
endResponse();
}
}
protected void dropDataSegment() throws IOException {
setDataCommandInfo("Drop data segment");
if (!isConnectionAlive())
return;
final String name = channel.readString();
boolean result = connection.database.dropDataSegment(name);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) (result ? 1 : 0));
} finally {
endResponse();
}
}
protected void removeCluster() throws IOException {
setDataCommandInfo("Remove cluster");
if (!isConnectionAlive())
return;
final int id = channel.readShort();
final String clusterName = connection.database.getClusterNameById(id);
if (clusterName == null)
throw new IllegalArgumentException("Cluster " + id
+ " doesn't exist anymore. Refresh the db structure or just reconnect to the database");
boolean result = connection.database.dropCluster(clusterName, true);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) (result ? 1 : 0));
} finally {
endResponse();
}
}
protected void addCluster() throws IOException {
setDataCommandInfo("Add cluster");
if (!isConnectionAlive())
return;
final String type = channel.readString();
final String name = channel.readString();
int clusterId = -1;
final String location;
if (connection.data.protocolVersion >= 10 || type.equalsIgnoreCase("PHYSICAL"))
location = channel.readString();
else
location = null;
final String dataSegmentName;
if (connection.data.protocolVersion >= 10)
dataSegmentName = channel.readString();
else {
channel.readInt(); // OLD INIT SIZE, NOT MORE USED
dataSegmentName = null;
}
if (connection.data.protocolVersion >= 18)
clusterId = channel.readShort();
Object[] params = null;
final int num;
if (clusterId < 0)
num = connection.database.addCluster(type, name, location, dataSegmentName, params);
else
num = connection.database.addCluster(type, name, clusterId, location, dataSegmentName, params);
beginResponse();
try {
sendOk(clientTxId);
channel.writeShort((short) num);
} finally {
endResponse();
}
}
protected void rangeCluster() throws IOException {
setDataCommandInfo("Get the begin/end range of data in cluster");
if (!isConnectionAlive())
return;
OClusterPosition[] pos = connection.database.getStorage().getClusterDataRange(channel.readShort());
beginResponse();
try {
sendOk(clientTxId);
channel.writeClusterPosition(pos[0]);
channel.writeClusterPosition(pos[1]);
} finally {
endResponse();
}
}
protected void countClusters() throws IOException {
setDataCommandInfo("Count cluster elements");
if (!isConnectionAlive())
return;
int[] clusterIds = new int[channel.readShort()];
for (int i = 0; i < clusterIds.length; ++i)
clusterIds[i] = channel.readShort();
boolean countTombstones = false;
if (connection.data.protocolVersion >= 13)
countTombstones = channel.readByte() > 0;
final long count = connection.database.countClusterElements(clusterIds, countTombstones);
beginResponse();
try {
sendOk(clientTxId);
channel.writeLong(count);
} finally {
endResponse();
}
}
protected void reloadDatabase() throws IOException {
setDataCommandInfo("Reload database information");
if (!isConnectionAlive())
return;
beginResponse();
try {
sendOk(clientTxId);
sendDatabaseInformation();
} finally {
endResponse();
}
}
protected void openDatabase() throws IOException {
setDataCommandInfo("Open database");
readConnectionData();
final String dbURL = channel.readString();
dbType = ODatabaseDocument.TYPE;
if (connection.data.protocolVersion >= 8)
// READ DB-TYPE FROM THE CLIENT
dbType = channel.readString();
final String user = channel.readString();
final String passwd = channel.readString();
connection.database = (ODatabaseDocumentTx) server.openDatabase(dbType, dbURL, user, passwd);
connection.rawDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());
if (connection.database.getStorage() instanceof OStorageProxy && !loadUserFromSchema(user, passwd)) {
sendError(clientTxId, new OSecurityAccessException(connection.database.getName(),
"User or password not valid for database: '" + connection.database.getName() + "'"));
} else {
beginResponse();
try {
sendOk(clientTxId);
channel.writeInt(connection.id);
sendDatabaseInformation();
final OServerPlugin plugin = server.getPlugin("cluster");
ODocument distributedCfg = null;
if (plugin != null && plugin instanceof ODistributedServerManager)
distributedCfg = ((ODistributedServerManager) plugin).getClusterConfiguration();
channel.writeBytes(distributedCfg != null ? distributedCfg.toStream() : null);
if (connection.data.protocolVersion >= 14)
channel.writeString(OConstants.getVersion());
} finally {
endResponse();
}
}
}
protected void connect() throws IOException {
setDataCommandInfo("Connect");
readConnectionData();
connection.serverUser = server.serverLogin(channel.readString(), channel.readString(), "connect");
beginResponse();
try {
sendOk(clientTxId);
channel.writeInt(connection.id);
} finally {
endResponse();
}
}
protected void shutdownConnection() throws IOException {
setDataCommandInfo("Shutdowning");
OLogManager.instance().info(this, "Received shutdown command from the remote client %s:%d", channel.socket.getInetAddress(),
channel.socket.getPort());
final String user = channel.readString();
final String passwd = channel.readString();
if (server.authenticate(user, passwd, "shutdown")) {
OLogManager.instance().info(this, "Remote client %s:%d authenticated. Starting shutdown of server...",
channel.socket.getInetAddress(), channel.socket.getPort());
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
channel.close();
server.shutdown();
System.exit(0);
}
OLogManager.instance().error(this, "Authentication error of remote client %s:%d: shutdown is aborted.",
channel.socket.getInetAddress(), channel.socket.getPort());
sendError(clientTxId, new OSecurityAccessException("Invalid user/password to shutdown the server"));
}
protected void copyDatabase() throws IOException {
setDataCommandInfo("Copy the database to a remote server");
final String dbUrl = channel.readString();
final String dbUser = channel.readString();
final String dbPassword = channel.readString();
final String remoteServerName = channel.readString();
final String remoteServerEngine = channel.readString();
checkServerAccess("database.copy");
final ODatabaseDocumentTx db = (ODatabaseDocumentTx) server.openDatabase(ODatabaseDocument.TYPE, dbUrl, dbUser, dbPassword);
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void replicationDatabase() throws IOException {
setDataCommandInfo("Replication command");
final ODocument request = new ODocument(channel.readBytes());
final ODistributedServerManager dManager = server.getDistributedManager();
if (dManager == null)
throw new OConfigurationException("No distributed manager configured");
final String operation = request.field("operation");
ODocument response = null;
if (operation.equals("start")) {
checkServerAccess("server.replication.start");
} else if (operation.equals("stop")) {
checkServerAccess("server.replication.stop");
} else if (operation.equals("config")) {
checkServerAccess("server.replication.config");
response = new ODocument().fromJSON(dManager.getDatabaseConfiguration((String) request.field("db")).serialize()
.toJSON("prettyPrint"));
}
sendResponse(response);
}
protected void distributedCluster() throws IOException {
setDataCommandInfo("Cluster status");
final ODocument req = new ODocument(channel.readBytes());
ODocument response = null;
final String operation = req.field("operation");
if (operation == null)
throw new IllegalArgumentException("Cluster operation is null");
if (operation.equals("status")) {
final OServerPlugin plugin = server.getPlugin("cluster");
if (plugin != null && plugin instanceof ODistributedServerManager)
response = ((ODistributedServerManager) plugin).getClusterConfiguration();
} else
throw new IllegalArgumentException("Cluster operation '" + operation + "' is not supported");
sendResponse(response);
}
protected void countDatabaseRecords() throws IOException {
setDataCommandInfo("Database count records");
if (!isConnectionAlive())
return;
beginResponse();
try {
sendOk(clientTxId);
channel.writeLong(connection.database.getStorage().countRecords());
} finally {
endResponse();
}
}
protected void sizeDatabase() throws IOException {
setDataCommandInfo("Database size");
if (!isConnectionAlive())
return;
beginResponse();
try {
sendOk(clientTxId);
channel.writeLong(connection.database.getStorage().getSize());
} finally {
endResponse();
}
}
protected void dropDatabase() throws IOException {
setDataCommandInfo("Drop database");
String dbName = channel.readString();
String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
checkServerAccess("database.delete");
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Dropped database '%s'", connection.database.getName());
if (connection.database.isClosed())
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
connection.database.drop();
connection.close();
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void existsDatabase() throws IOException {
setDataCommandInfo("Exists database");
final String dbName = channel.readString();
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
checkServerAccess("database.exists");
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) (connection.database.exists() ? 1 : 0));
} finally {
endResponse();
}
}
protected void createDatabase() throws IOException {
setDataCommandInfo("Create database");
String dbName = channel.readString();
String dbType = ODatabaseDocument.TYPE;
if (connection.data.protocolVersion >= 8)
// READ DB-TYPE FROM THE CLIENT
dbType = channel.readString();
String storageType = channel.readString();
checkServerAccess("database.create");
checkStorageExistence(dbName);
connection.database = getDatabaseInstance(dbName, dbType, storageType);
createDatabase(connection.database, null, null);
connection.rawDatabase = (((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void closeDatabase() throws IOException {
setDataCommandInfo("Close Database");
if (connection != null) {
if (connection.data.protocolVersion > 0 && connection.data.protocolVersion < 9)
// OLD CLIENTS WAIT FOR A OK
sendOk(clientTxId);
if (OClientConnectionManager.instance().disconnect(connection.id))
sendShutdown();
}
}
protected void configList() throws IOException {
setDataCommandInfo("List config");
checkServerAccess("server.config.get");
beginResponse();
try {
sendOk(clientTxId);
channel.writeShort((short) OGlobalConfiguration.values().length);
for (OGlobalConfiguration cfg : OGlobalConfiguration.values()) {
String key;
try {
key = cfg.getKey();
} catch (Exception e) {
key = "?";
}
String value;
try {
value = cfg.getValueAsString() != null ? cfg.getValueAsString() : "";
} catch (Exception e) {
value = "";
}
channel.writeString(key);
channel.writeString(value);
}
} finally {
endResponse();
}
}
protected void configSet() throws IOException {
setDataCommandInfo("Get config");
checkServerAccess("server.config.set");
final String key = channel.readString();
final String value = channel.readString();
final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key);
if (cfg != null)
cfg.setValue(value);
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void configGet() throws IOException {
setDataCommandInfo("Get config");
checkServerAccess("server.config.get");
final String key = channel.readString();
final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key);
String cfgValue = cfg != null ? cfg.getValueAsString() : "";
beginResponse();
try {
sendOk(clientTxId);
channel.writeString(cfgValue);
} finally {
endResponse();
}
}
protected void commit() throws IOException {
setDataCommandInfo("Transaction commit");
if (!isConnectionAlive())
return;
final OTransactionOptimisticProxy tx = new OTransactionOptimisticProxy((ODatabaseRecordTx) connection.database.getUnderlying(),
channel);
try {
connection.database.begin(tx);
try {
connection.database.commit();
beginResponse();
try {
sendOk(clientTxId);
// SEND BACK ALL THE RECORD IDS FOR THE CREATED RECORDS
channel.writeInt(tx.getCreatedRecords().size());
for (Entry<ORecordId, ORecordInternal<?>> entry : tx.getCreatedRecords().entrySet()) {
channel.writeRID(entry.getKey());
channel.writeRID(entry.getValue().getIdentity());
// IF THE NEW OBJECT HAS VERSION > 0 MEANS THAT HAS BEEN UPDATED IN THE SAME TX. THIS HAPPENS FOR GRAPHS
if (entry.getValue().getRecordVersion().getCounter() > 0)
tx.getUpdatedRecords().put((ORecordId) entry.getValue().getIdentity(), entry.getValue());
}
// SEND BACK ALL THE NEW VERSIONS FOR THE UPDATED RECORDS
channel.writeInt(tx.getUpdatedRecords().size());
for (Entry<ORecordId, ORecordInternal<?>> entry : tx.getUpdatedRecords().entrySet()) {
channel.writeRID(entry.getKey());
channel.writeVersion(entry.getValue().getRecordVersion());
}
} finally {
endResponse();
}
} catch (Exception e) {
connection.database.rollback();
sendError(clientTxId, e);
}
} catch (OTransactionAbortedException e) {
// TX ABORTED BY THE CLIENT
} catch (Exception e) {
// Error during TX initialization, possibly index constraints violation.
tx.rollback();
tx.close();
sendError(clientTxId, e);
}
}
protected void command() throws IOException {
setDataCommandInfo("Execute remote command");
final boolean asynch = channel.readByte() == 'a';
final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE.fromStream(channel
.readBytes());
connection.data.commandDetail = command.getText();
// ENABLES THE CACHE TO IMPROVE PERFORMANCE OF COMPLEX COMMANDS LIKE TRAVERSE
// connection.database.getLevel1Cache().setEnable(true);
beginResponse();
try {
final OAbstractCommandResultListener listener;
if (asynch) {
listener = new OAsyncCommandResultListener(this, clientTxId);
command.setResultListener(listener);
} else
listener = new OSyncCommandResultListener();
final long serverTimeout = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
if (serverTimeout > 0 && command.getTimeoutTime() > serverTimeout)
// FORCE THE SERVER'S TIMEOUT
command.setTimeout(serverTimeout, command.getTimeoutStrategy());
if (!isConnectionAlive())
return;
// ASSIGNED THE PARSED FETCHPLAN
listener.setFetchPlan(((OCommandRequestInternal) connection.database.command(command)).getFetchPlan());
final Object result = ((OCommandRequestInternal) connection.database.command(command)).execute();
if (asynch) {
// ASYNCHRONOUS
if (listener.isEmpty())
try {
sendOk(clientTxId);
} catch (IOException e1) {
}
} else {
// SYNCHRONOUS
sendOk(clientTxId);
if (result == null) {
// NULL VALUE
channel.writeByte((byte) 'n');
} else if (result instanceof OIdentifiable) {
// RECORD
channel.writeByte((byte) 'r');
listener.result(result);
writeIdentifiable((OIdentifiable) result);
} else if (OMultiValue.isMultiValue(result)) {
channel.writeByte((byte) 'l');
channel.writeInt(OMultiValue.getSize(result));
for (Object o : OMultiValue.getMultiValueIterable(result)) {
listener.result(o);
writeIdentifiable((OIdentifiable) o);
}
} else {
// ANY OTHER (INCLUDING LITERALS)
channel.writeByte((byte) 'a');
final StringBuilder value = new StringBuilder();
listener.result(result);
ORecordSerializerStringAbstract.fieldTypeToString(value, OType.getTypeByClass(result.getClass()), result);
channel.writeString(value.toString());
}
}
if (asynch || connection.data.protocolVersion >= 17) {
// SEND FETCHED RECORDS TO LOAD IN CLIENT CACHE
for (ODocument doc : listener.getFetchedRecordsToSend()) {
channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT
// ISN'T PART OF THE
// RESULT SET
writeIdentifiable(doc);
}
channel.writeByte((byte) 0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private boolean isConnectionAlive() {
if (connection == null || connection.database == null) {
// CONNECTION/DATABASE CLOSED, KILL IT
OClientConnectionManager.instance().kill(connection);
return false;
}
return true;
}
protected void deleteRecord() throws IOException {
setDataCommandInfo("Delete record");
if (!isConnectionAlive())
return;
final ORID rid = channel.readRID();
final ORecordVersion version = channel.readVersion();
final byte mode = channel.readByte();
final int result = deleteRecord(connection.database, rid, version);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) result);
} finally {
endResponse();
}
}
}
protected void cleanOutRecord() throws IOException {
setDataCommandInfo("Clean out record");
if (!isConnectionAlive())
return;
final ORID rid = channel.readRID();
final ORecordVersion version = channel.readVersion();
final byte mode = channel.readByte();
final int result = cleanOutRecord(connection.database, rid, version);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) result);
} finally {
endResponse();
}
}
}
/**
* VERSION MANAGEMENT:<br/>
* -1 : DOCUMENT UPDATE, NO VERSION CONTROL<br/>
* -2 : DOCUMENT UPDATE, NO VERSION CONTROL, NO VERSION INCREMENT<br/>
* -3 : DOCUMENT ROLLBACK, DECREMENT VERSION<br/>
* >-1 : MVCC CONTROL, RECORD UPDATE AND VERSION INCREMENT<br/>
* <-3 : WRONG VERSION VALUE
*
* @throws IOException
*/
protected void updateRecord() throws IOException {
setDataCommandInfo("Update record");
if (!isConnectionAlive())
return;
if (!isConnectionAlive())
return;
final ORecordId rid = channel.readRID();
final byte[] buffer = channel.readBytes();
final ORecordVersion version = channel.readVersion();
final byte recordType = channel.readByte();
final byte mode = channel.readByte();
final ORecordVersion newVersion = updateRecord(connection.database, rid, buffer, version, recordType);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeVersion(newVersion);
} finally {
endResponse();
}
}
}
protected void createRecord() throws IOException {
setDataCommandInfo("Create record");
if (!isConnectionAlive())
return;
final int dataSegmentId = connection.data.protocolVersion >= 10 ? channel.readInt() : 0;
final ORecordId rid = new ORecordId(channel.readShort(), ORID.CLUSTER_POS_INVALID);
final byte[] buffer = channel.readBytes();
final byte recordType = channel.readByte();
final byte mode = channel.readByte();
final ORecord<?> record = createRecord(connection.database, rid, buffer, recordType, dataSegmentId);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeClusterPosition(record.getIdentity().getClusterPosition());
if (connection.data.protocolVersion >= 11)
channel.writeVersion(record.getRecordVersion());
} finally {
endResponse();
}
}
}
protected void readRecordMetadata() throws IOException {
setDataCommandInfo("Record metadata");
final ORID rid = channel.readRID();
beginResponse();
try {
final ORecordMetadata metadata = connection.database.getRecordMetadata(rid);
sendOk(clientTxId);
channel.writeRID(metadata.getRecordId());
channel.writeVersion(metadata.getRecordVersion());
} finally {
endResponse();
}
}
protected void readRecord() throws IOException {
setDataCommandInfo("Load record");
if (!isConnectionAlive())
return;
final ORecordId rid = channel.readRID();
final String fetchPlanString = channel.readString();
boolean ignoreCache = false;
if (connection.data.protocolVersion >= 9)
ignoreCache = channel.readByte() == 1;
boolean loadTombstones = false;
if (connection.data.protocolVersion >= 13)
loadTombstones = channel.readByte() > 0;
if (rid.clusterId == 0 && rid.clusterPosition.longValue() == 0) {
// @COMPATIBILITY 0.9.25
// SEND THE DB CONFIGURATION INSTEAD SINCE IT WAS ON RECORD 0:0
OFetchHelper.checkFetchPlanValid(fetchPlanString);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) 1);
channel.writeBytes(connection.database.getStorage().getConfiguration().toStream());
channel.writeVersion(OVersionFactory.instance().createVersion());
channel.writeByte(ORecordBytes.RECORD_TYPE);
channel.writeByte((byte) 0); // NO MORE RECORDS
} finally {
endResponse();
}
} else {
final ORecordInternal<?> record = connection.database.load(rid, fetchPlanString, ignoreCache, loadTombstones);
beginResponse();
try {
sendOk(clientTxId);
if (record != null) {
channel.writeByte((byte) 1); // HAS RECORD
channel.writeBytes(record.toStream());
channel.writeVersion(record.getRecordVersion());
channel.writeByte(record.getRecordType());
if (fetchPlanString.length() > 0) {
// BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH
// PLAN
if (record instanceof ODocument) {
final Map<String, Integer> fetchPlan = OFetchHelper.buildFetchPlan(fetchPlanString);
final Set<ODocument> recordsToSend = new HashSet<ODocument>();
final ODocument doc = (ODocument) record;
final OFetchListener listener = new ORemoteFetchListener(recordsToSend);
final OFetchContext context = new ORemoteFetchContext();
OFetchHelper.fetch(doc, doc, fetchPlan, listener, context, "");
// SEND RECORDS TO LOAD IN CLIENT CACHE
for (ODocument d : recordsToSend) {
if (d.getIdentity().isValid()) {
channel.writeByte((byte) 2); // CLIENT CACHE
// RECORD. IT ISN'T PART OF THE RESULT SET
writeIdentifiable(d);
}
}
}
}
}
channel.writeByte((byte) 0); // NO MORE RECORDS
} finally {
endResponse();
}
}
}
protected void beginResponse() {
channel.acquireWriteLock();
}
protected void endResponse() throws IOException {
channel.flush();
channel.releaseWriteLock();
}
protected void setDataCommandInfo(final String iCommandInfo) {
if (connection != null)
connection.data.commandInfo = iCommandInfo;
}
protected void readConnectionData() throws IOException {
connection.data.driverName = channel.readString();
connection.data.driverVersion = channel.readString();
connection.data.protocolVersion = channel.readShort();
connection.data.clientId = channel.readString();
}
private void sendDatabaseInformation() throws IOException {
final Collection<? extends OCluster> clusters = connection.database.getStorage().getClusterInstances();
int clusterCount = 0;
for (OCluster c : clusters) {
if (c != null) {
++clusterCount;
}
}
if (connection.data.protocolVersion >= 7)
channel.writeShort((short) clusterCount);
else
channel.writeInt(clusterCount);
for (OCluster c : clusters) {
if (c != null) {
channel.writeString(c.getName());
channel.writeShort((short) c.getId());
channel.writeString(c.getType());
if (connection.data.protocolVersion >= 12)
channel.writeShort((short) c.getDataSegmentId());
}
}
}
@Override
public void startup() {
super.startup();
OServerPluginHelper.invokeHandlerCallbackOnClientConnection(server, connection);
}
@Override
public void shutdown() {
sendShutdown();
super.shutdown();
if (connection == null)
return;
OServerPluginHelper.invokeHandlerCallbackOnClientDisconnection(server, connection);
OClientConnectionManager.instance().disconnect(connection);
}
protected void sendOk(final int iClientTxId) throws IOException {
channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_OK);
channel.writeInt(iClientTxId);
}
private void listDatabases() throws IOException {
checkServerAccess("server.dblist");
final ODocument result = new ODocument();
result.field("databases", server.getAvailableStorageNames());
setDataCommandInfo("List databases");
beginResponse();
try {
sendOk(clientTxId);
channel.writeBytes(result.toStream());
} finally {
endResponse();
}
}
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;
final Throwable original = current;
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);
if (connection != null && connection.data.protocolVersion >= 19) {
final OMemoryStream memoryStream = new OMemoryStream();
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(memoryStream);
objectOutputStream.writeObject(original);
objectOutputStream.flush();
final byte[] result = memoryStream.toByteArray();
objectOutputStream.close();
channel.writeBytes(result);
}
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();
}
}
private boolean loadUserFromSchema(final String iUserName, final String iUserPassword) {
account = connection.database.getMetadata().getSecurity().authenticate(iUserName, iUserPassword);
return true;
}
@Override
protected void handleConnectionError(final OChannelBinaryServer iChannel, final Throwable e) {
super.handleConnectionError(channel, e);
OServerPluginHelper.invokeHandlerCallbackOnClientError(server, connection, e);
}
public String getType() {
return "binary";
}
protected void sendResponse(final ODocument iResponse) throws IOException {
beginResponse();
try {
sendOk(clientTxId);
channel.writeBytes(iResponse != null ? iResponse.toStream() : null);
} finally {
endResponse();
}
}
protected void freezeDatabase() throws IOException {
setDataCommandInfo("Freeze database");
String dbName = channel.readString();
checkServerAccess("database.freeze");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Freezing database '%s'", connection.database.getURL());
if (connection.database.isClosed())
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
connection.database.freeze(true);
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void releaseDatabase() throws IOException {
setDataCommandInfo("Release database");
String dbName = channel.readString();
checkServerAccess("database.release");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Realising database '%s'", connection.database.getURL());
if (connection.database.isClosed())
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
connection.database.release();
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void freezeCluster() throws IOException {
setDataCommandInfo("Freeze cluster");
final String dbName = channel.readString();
final int clusterId = channel.readShort();
checkServerAccess("database.freeze");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Freezing database '%s' cluster %d", connection.database.getURL(), clusterId);
if (connection.database.isClosed()) {
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
}
connection.database.freezeCluster(clusterId);
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void releaseCluster() throws IOException {
setDataCommandInfo("Release database");
final String dbName = channel.readString();
final int clusterId = channel.readShort();
checkServerAccess("database.release");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Realising database '%s' cluster %d", connection.database.getURL(), clusterId);
if (connection.database.isClosed()) {
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
}
connection.database.releaseCluster(clusterId);
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
} | 1no label
| server_src_main_java_com_orientechnologies_orient_server_network_protocol_binary_ONetworkProtocolBinary.java |
2,178 | static class NotDeleteBits implements Bits {
private final Bits bits;
private final Bits liveDocs;
NotDeleteBits(Bits bits, Bits liveDocs) {
this.bits = bits;
this.liveDocs = liveDocs;
}
@Override
public boolean get(int index) {
return liveDocs.get(index) && bits.get(index);
}
@Override
public int length() {
return bits.length();
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_search_ApplyAcceptedDocsFilter.java |
988 | new Thread() {
public void run() {
for (int j = 0; j < loopCount; j++) {
try {
semaphore.acquire();
sleepMillis((int) (Math.random() * 3));
counter.inc();
} catch (InterruptedException e) {
return;
} finally {
semaphore.release();
}
}
latch.countDown();
}
}.start(); | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_semaphore_AdvancedSemaphoreTest.java |
1,174 | public interface InitialMembershipListener extends MembershipListener {
/**
* Is called when this listener is registered.
*
* @param event the MembershipInitializeEvent
*/
void init(InitialMembershipEvent event);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_InitialMembershipListener.java |
1,526 | public class ConnectionFactoryImpl implements HazelcastConnectionFactory {
/**
* identity generator
*/
private static final AtomicInteger ID_GEN = new AtomicInteger();
/**
* class LOGGER
*/
private static final ILogger LOGGER = Logger.getLogger("com.hazelcast.jca");
/**
* this identity
*/
private static final long serialVersionUID = -5909363703528221650L;
/**
* Access to this resource adapter infrastructure
*/
private ManagedConnectionFactoryImpl mcf;
/**
* Container's connection manager - i.e. for pooling
*/
private ConnectionManager cm;
/**
* JNDI reference - not used
*/
private Reference ref;
private final transient int id;
public ConnectionFactoryImpl() {
id = ID_GEN.incrementAndGet();
}
public ConnectionFactoryImpl(ManagedConnectionFactoryImpl mcf, ConnectionManager cm) {
this();
this.mcf = mcf;
this.cm = cm;
}
/* (non-Javadoc)
* @see com.hazelcast.jca.HazelcastConnectionFactory#getConnection()
*/
public HazelcastConnection getConnection() throws ResourceException {
LOGGER.finest("getConnection");
return this.getConnection(null);
}
/* (non-Javadoc)
* @see com.hazelcast.jca.HazelcastConnectionFactory#getConnection(javax.resource.cci.ConnectionSpec)
*/
public HazelcastConnection getConnection(ConnectionSpec connSpec) throws ResourceException {
if (LOGGER.isFinestEnabled()) {
LOGGER.finest("getConnection spec: " + connSpec);
}
return (HazelcastConnectionImpl) cm.allocateConnection(mcf, null);
}
/* (non-Javadoc)
* @see javax.resource.cci.ConnectionFactory#getMetaData()
*/
public ResourceAdapterMetaData getMetaData() throws ResourceException {
return new ConnectionFactoryMetaData();
}
/* (non-Javadoc)
* @see javax.resource.cci.ConnectionFactory#getRecordFactory()
*/
public RecordFactory getRecordFactory() throws ResourceException {
return null;
}
/* (non-Javadoc)
* @see javax.resource.Referenceable#setReference(javax.naming.Reference)
*/
public void setReference(Reference ref) {
this.ref = ref;
}
/* (non-Javadoc)
* @see javax.naming.Referenceable#getReference()
*/
public Reference getReference() throws NamingException {
return ref;
}
@Override
public String toString() {
return "hazelcast.ConnectionFactoryImpl [" + id + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ConnectionFactoryImpl other = (ConnectionFactoryImpl) obj;
if (id != other.id) {
return false;
}
return true;
}
} | 0true
| hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_ConnectionFactoryImpl.java |
3,585 | public class IntegerFieldMapper extends NumberFieldMapper<Integer> {
public static final String CONTENT_TYPE = "integer";
public static class Defaults extends NumberFieldMapper.Defaults {
public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.freeze();
}
public static final Integer NULL_VALUE = null;
}
public static class Builder extends NumberFieldMapper.Builder<Builder, IntegerFieldMapper> {
protected Integer nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
builder = this;
}
public Builder nullValue(int nullValue) {
this.nullValue = nullValue;
return this;
}
@Override
public IntegerFieldMapper build(BuilderContext context) {
fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
IntegerFieldMapper fieldMapper = new IntegerFieldMapper(buildNames(context), precisionStep, boost, fieldType, docValues,
nullValue, ignoreMalformed(context), coerce(context), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings,
context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
fieldMapper.includeInAll(includeInAll);
return fieldMapper;
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
IntegerFieldMapper.Builder builder = integerField(name);
parseNumberField(builder, name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
Object propNode = entry.getValue();
if (propName.equals("null_value")) {
builder.nullValue(nodeIntegerValue(propNode));
}
}
return builder;
}
}
private Integer nullValue;
private String nullValueAsString;
protected IntegerFieldMapper(Names names, int precisionStep, float boost, FieldType fieldType, Boolean docValues,
Integer nullValue, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce,
PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider,
SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings,
Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
super(names, precisionStep, boost, fieldType, docValues, ignoreMalformed, coerce,
NumericIntegerAnalyzer.buildNamedAnalyzer(precisionStep), NumericIntegerAnalyzer.buildNamedAnalyzer(Integer.MAX_VALUE),
postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo);
this.nullValue = nullValue;
this.nullValueAsString = nullValue == null ? null : nullValue.toString();
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return new FieldDataType("int");
}
@Override
protected int maxPrecisionStep() {
return 32;
}
@Override
public Integer value(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof BytesRef) {
return Numbers.bytesToInt((BytesRef) value);
}
return Integer.parseInt(value.toString());
}
@Override
public BytesRef indexedValueForSearch(Object value) {
BytesRef bytesRef = new BytesRef();
NumericUtils.intToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match
return bytesRef;
}
private int parseValue(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof BytesRef) {
return Integer.parseInt(((BytesRef) value).utf8ToString());
}
return Integer.parseInt(value.toString());
}
@Override
public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) {
int iValue = Integer.parseInt(value);
int iSim = fuzziness.asInt();
return NumericRangeQuery.newIntRange(names.indexName(), precisionStep,
iValue - iSim,
iValue + iSim,
true, true);
}
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
int iValue = parseValue(value);
return NumericRangeQuery.newIntRange(names.indexName(), precisionStep,
iValue, iValue, true, true);
}
@Override
public Filter termFilter(Object value, @Nullable QueryParseContext context) {
int iValue = parseValue(value);
return NumericRangeFilter.newIntRange(names.indexName(), precisionStep,
iValue, iValue, true, true);
}
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeQuery.newIntRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeFilter.newIntRange(names.indexName(), precisionStep,
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
return NumericRangeFieldDataFilter.newIntRange((IndexNumericFieldData) fieldData.getForField(this),
lowerTerm == null ? null : parseValue(lowerTerm),
upperTerm == null ? null : parseValue(upperTerm),
includeLower, includeUpper);
}
@Override
public Filter nullValueFilter() {
if (nullValue == null) {
return null;
}
return NumericRangeFilter.newIntRange(names.indexName(), precisionStep,
nullValue,
nullValue,
true, true);
}
@Override
protected boolean customBoost() {
return true;
}
@Override
protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException {
int value;
float boost = this.boost;
if (context.externalValueSet()) {
Object externalValue = context.externalValue();
if (externalValue == null) {
if (nullValue == null) {
return;
}
value = nullValue;
} else if (externalValue instanceof String) {
String sExternalValue = (String) externalValue;
if (sExternalValue.length() == 0) {
if (nullValue == null) {
return;
}
value = nullValue;
} else {
value = Integer.parseInt(sExternalValue);
}
} else {
value = ((Number) externalValue).intValue();
}
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(names.fullName(), Integer.toString(value), boost);
}
} else {
XContentParser parser = context.parser();
if (parser.currentToken() == XContentParser.Token.VALUE_NULL ||
(parser.currentToken() == XContentParser.Token.VALUE_STRING && parser.textLength() == 0)) {
if (nullValue == null) {
return;
}
value = nullValue;
if (nullValueAsString != null && (context.includeInAll(includeInAll, this))) {
context.allEntries().addText(names.fullName(), nullValueAsString, boost);
}
} else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
XContentParser.Token token;
String currentFieldName = null;
Integer objValue = nullValue;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) {
if (parser.currentToken() != XContentParser.Token.VALUE_NULL) {
objValue = parser.intValue(coerce.value());
}
} else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else {
throw new ElasticsearchIllegalArgumentException("unknown property [" + currentFieldName + "]");
}
}
}
if (objValue == null) {
// no value
return;
}
value = objValue;
} else {
value = parser.intValue(coerce.value());
if (context.includeInAll(includeInAll, this)) {
context.allEntries().addText(names.fullName(), parser.text(), boost);
}
}
}
addIntegerFields(context, fields, value, boost);
}
protected void addIntegerFields(ParseContext context, List<Field> fields, int value, float boost) {
if (fieldType.indexed() || fieldType.stored()) {
CustomIntegerNumericField field = new CustomIntegerNumericField(this, value, fieldType);
field.setBoost(boost);
fields.add(field);
}
if (hasDocValues()) {
addDocValue(context, value);
}
}
protected Integer nullValue() {
return nullValue;
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
super.merge(mergeWith, mergeContext);
if (!this.getClass().equals(mergeWith.getClass())) {
return;
}
if (!mergeContext.mergeFlags().simulate()) {
this.nullValue = ((IntegerFieldMapper) mergeWith).nullValue;
this.nullValueAsString = ((IntegerFieldMapper) mergeWith).nullValueAsString;
}
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
super.doXContentBody(builder, includeDefaults, params);
if (includeDefaults || precisionStep != Defaults.PRECISION_STEP) {
builder.field("precision_step", precisionStep);
}
if (includeDefaults || nullValue != null) {
builder.field("null_value", nullValue);
}
if (includeInAll != null) {
builder.field("include_in_all", includeInAll);
} else if (includeDefaults) {
builder.field("include_in_all", false);
}
}
public static class CustomIntegerNumericField extends CustomNumericField {
private final int number;
private final NumberFieldMapper mapper;
public CustomIntegerNumericField(NumberFieldMapper mapper, int number, FieldType fieldType) {
super(mapper, number, fieldType);
this.mapper = mapper;
this.number = number;
}
@Override
public TokenStream tokenStream(Analyzer analyzer) throws IOException {
if (fieldType().indexed()) {
return mapper.popCachedStream().setIntValue(number);
}
return null;
}
@Override
public String numericAsString() {
return Integer.toString(number);
}
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_IntegerFieldMapper.java |
888 | public interface PromotableFulfillmentGroupAdjustment extends Serializable {
/**
* Returns the associated promotableFulfillmentGroup
* @return
*/
public PromotableFulfillmentGroup getPromotableFulfillmentGroup();
/**
* Returns the associated promotableCandidateOrderOffer
* @return
*/
public PromotableCandidateFulfillmentGroupOffer getPromotableCandidateFulfillmentGroupOffer();
/**
* Returns the value of this adjustment
* @return
*/
public Money getSaleAdjustmentValue();
/**
* Returns the value of this adjustment
* @return
*/
public Money getRetailAdjustmentValue();
/**
* Returns the value of this adjustment
* @return
*/
public Money getAdjustmentValue();
/**
* Returns true if this adjustment represents a combinable offer.
*/
boolean isCombinable();
/**
* Returns true if this adjustment represents a totalitarian offer.
*/
boolean isTotalitarian();
/**
* Updates the adjustmentValue to the sales or retail value based on the passed in param
*/
void finalizeAdjustment(boolean useSaleAdjustments);
boolean isAppliedToSalePrice();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableFulfillmentGroupAdjustment.java |
1,407 | 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 |
719 | public interface SkuAttribute extends Searchable<String> {
/**
* Gets the id.
*
* @return the id
*/
public Long getId();
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(Long id);
/**
* Gets the sku.
*
* @return the sku
*/
public Sku getSku();
/**
* Sets the sku.
*
* @param sku the new sku
*/
public void setSku(Sku sku);
/**
* Gets the name.
*
* @return the name
*/
public String getName();
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_SkuAttribute.java |
1,627 | public interface EJB3ConfigurationDao {
public abstract Ejb3Configuration getConfiguration();
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_EJB3ConfigurationDao.java |
1,041 | public class MultiTermVectorsItemResponse implements Streamable {
private TermVectorResponse response;
private MultiTermVectorsResponse.Failure failure;
MultiTermVectorsItemResponse() {
}
public MultiTermVectorsItemResponse(TermVectorResponse response, MultiTermVectorsResponse.Failure failure) {
assert (((response == null) && (failure != null)) || ((response != null) && (failure == null)));
this.response = response;
this.failure = failure;
}
/**
* The index name of the document.
*/
public String getIndex() {
if (failure != null) {
return failure.getIndex();
}
return response.getIndex();
}
/**
* The type of the document.
*/
public String getType() {
if (failure != null) {
return failure.getType();
}
return response.getType();
}
/**
* The id of the document.
*/
public String getId() {
if (failure != null) {
return failure.getId();
}
return response.getId();
}
/**
* Is this a failed execution?
*/
public boolean isFailed() {
return failure != null;
}
/**
* The actual get response, <tt>null</tt> if its a failure.
*/
public TermVectorResponse getResponse() {
return this.response;
}
/**
* The failure if relevant.
*/
public MultiTermVectorsResponse.Failure getFailure() {
return this.failure;
}
public static MultiTermVectorsItemResponse readItemResponse(StreamInput in) throws IOException {
MultiTermVectorsItemResponse response = new MultiTermVectorsItemResponse();
response.readFrom(in);
return response;
}
@Override
public void readFrom(StreamInput in) throws IOException {
if (in.readBoolean()) {
failure = MultiTermVectorsResponse.Failure.readFailure(in);
} else {
response = new TermVectorResponse();
response.readFrom(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (failure != null) {
out.writeBoolean(true);
failure.writeTo(out);
} else {
out.writeBoolean(false);
response.writeTo(out);
}
}
} | 0true
| src_main_java_org_elasticsearch_action_termvector_MultiTermVectorsItemResponse.java |
1,213 | public class RuntimeInterruptedException extends HazelcastException {
public RuntimeInterruptedException() {
}
public RuntimeInterruptedException(String message) {
super(message);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_RuntimeInterruptedException.java |
30 | {
@Override
public int getServerId()
{
return config.get( ClusterSettings.server_id );
}
@Override
public List<HostnamePort> getInitialHosts()
{
return config.get( ClusterSettings.initial_hosts );
}
@Override
public String getClusterName()
{
return config.get( ClusterSettings.cluster_name );
}
@Override
public HostnamePort getAddress()
{
return config.get( ClusterSettings.cluster_server );
}
@Override
public boolean isAllowedToCreateCluster()
{
return config.get( ClusterSettings.allow_init_cluster );
}
// Timeouts
@Override
public long defaultTimeout()
{
return config.get( ClusterSettings.default_timeout );
}
@Override
public long heartbeatTimeout()
{
return config.get( ClusterSettings.heartbeat_timeout );
}
@Override
public long heartbeatInterval()
{
return config.get( ClusterSettings.heartbeat_interval );
}
@Override
public long joinTimeout()
{
return config.get( ClusterSettings.join_timeout );
}
@Override
public long configurationTimeout()
{
return config.get( ClusterSettings.configuration_timeout );
}
@Override
public long leaveTimeout()
{
return config.get( ClusterSettings.leave_timeout );
}
@Override
public long electionTimeout()
{
return config.get( ClusterSettings.election_timeout );
}
@Override
public long broadcastTimeout()
{
return config.get( ClusterSettings.broadcast_timeout );
}
@Override
public long paxosTimeout()
{
return config.get( ClusterSettings.paxos_timeout );
}
@Override
public long phase1Timeout()
{
return config.get( ClusterSettings.phase1_timeout );
}
@Override
public long phase2Timeout()
{
return config.get( ClusterSettings.phase2_timeout );
}
@Override
public long learnTimeout()
{
return config.get( ClusterSettings.learn_timeout );
}
@Override
public long clusterJoinTimeout()
{
return config.get(clusterJoinTimeout);
}
@Override
public String name()
{
return config.get( ClusterSettings.instance_name );
}
}; | 1no label
| enterprise_cluster_src_main_java_org_neo4j_cluster_client_ClusterClient.java |
1,626 | public class GetMapConfigOperation extends Operation {
private String mapName;
private MapConfig mapConfig;
public GetMapConfigOperation() {
}
public GetMapConfigOperation(String mapName) {
this.mapName = mapName;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
MapService service = getService();
mapConfig = service.getMapContainer(mapName).getMapConfig();
}
@Override
public void afterRun() throws Exception {
}
@Override
public boolean returnsResponse() {
return true;
}
@Override
public Object getResponse() {
return mapConfig;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
out.writeUTF(mapName);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
mapName = in.readUTF();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_management_operation_GetMapConfigOperation.java |
843 | class TransportHandler extends BaseTransportRequestHandler<ClearScrollRequest> {
@Override
public ClearScrollRequest newInstance() {
return new ClearScrollRequest();
}
@Override
public void messageReceived(final ClearScrollRequest 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<ClearScrollResponse>() {
@Override
public void onResponse(ClearScrollResponse 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 [clear_sc] and request [" + request + "]", e1);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
} | 0true
| src_main_java_org_elasticsearch_action_search_TransportClearScrollAction.java |
2,319 | static class TimeTimeZoneRoundingFloor extends TimeZoneRounding {
static final byte ID = 1;
private DateTimeUnit unit;
private DateTimeZone preTz;
private DateTimeZone postTz;
TimeTimeZoneRoundingFloor() { // for serialization
}
TimeTimeZoneRoundingFloor(DateTimeUnit unit, DateTimeZone preTz, DateTimeZone postTz) {
this.unit = unit;
this.preTz = preTz;
this.postTz = postTz;
}
@Override
public byte id() {
return ID;
}
@Override
public long roundKey(long utcMillis) {
long time = utcMillis + preTz.getOffset(utcMillis);
return unit.field().roundFloor(time);
}
@Override
public long valueForKey(long time) {
// now, time is still in local, move it to UTC (or the adjustLargeInterval flag is set)
time = time - preTz.getOffset(time);
// now apply post Tz
time = time + postTz.getOffset(time);
return time;
}
@Override
public long nextRoundingValue(long value) {
return unit.field().roundCeiling(value + 1);
}
@Override
public void readFrom(StreamInput in) throws IOException {
unit = DateTimeUnit.resolve(in.readByte());
preTz = DateTimeZone.forID(in.readSharedString());
postTz = DateTimeZone.forID(in.readSharedString());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeByte(unit.id());
out.writeSharedString(preTz.getID());
out.writeSharedString(postTz.getID());
}
} | 0true
| src_main_java_org_elasticsearch_common_rounding_TimeZoneRounding.java |
881 | public interface PromotableCandidateFulfillmentGroupOffer {
public HashMap<OfferItemCriteria, List<PromotableOrderItem>> getCandidateQualifiersMap();
public void setCandidateQualifiersMap(HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateItemsMap);
public Money computeDiscountedAmount();
public Money getDiscountedPrice();
public Offer getOffer();
public PromotableFulfillmentGroup getFulfillmentGroup();
public Money getDiscountedAmount();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableCandidateFulfillmentGroupOffer.java |
271 | public class NullEmailInfo extends EmailInfo {
private static final long serialVersionUID = 1L;
public NullEmailInfo() throws IOException {
super();
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_email_service_info_NullEmailInfo.java |
644 | public class DeleteIndexTemplateRequest extends MasterNodeOperationRequest<DeleteIndexTemplateRequest> {
private String name;
DeleteIndexTemplateRequest() {
}
/**
* Constructs a new delete index request for the specified name.
*/
public DeleteIndexTemplateRequest(String name) {
this.name = name;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (name == null) {
validationException = addValidationError("name is missing", validationException);
}
return validationException;
}
/**
* The index template name to delete.
*/
String name() {
return name;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
name = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(name);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_template_delete_DeleteIndexTemplateRequest.java |
3,210 | DOUBLE(64, true, SortField.Type.DOUBLE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) {
@Override
public double toDouble(BytesRef indexForm) {
return NumericUtils.sortableLongToDouble(NumericUtils.prefixCodedToLong(indexForm));
}
@Override
public void toIndexForm(Number number, BytesRef bytes) {
NumericUtils.longToPrefixCodedBytes(NumericUtils.doubleToSortableLong(number.doubleValue()), 0, bytes);
}
@Override
public Number toNumber(BytesRef indexForm) {
return NumericUtils.sortableLongToDouble(NumericUtils.prefixCodedToLong(indexForm));
}
}; | 0true
| src_main_java_org_elasticsearch_index_fielddata_IndexNumericFieldData.java |
353 | public class OScenarioThreadLocal extends ThreadLocal<RUN_MODE> {
public static OScenarioThreadLocal INSTANCE = new OScenarioThreadLocal();
public enum RUN_MODE {
DEFAULT, RUNNING_DISTRIBUTED
}
public OScenarioThreadLocal() {
set(RUN_MODE.DEFAULT);
}
@Override
public void set(final RUN_MODE value) {
super.set(value);
}
@Override
public RUN_MODE get() {
RUN_MODE result = super.get();
if (result == null)
result = RUN_MODE.DEFAULT;
return result;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_OScenarioThreadLocal.java |
289 | list.getTable().addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent e) {
go();
}
@Override
public void mouseDown(MouseEvent e) {}
@Override
public void mouseDoubleClick(MouseEvent e) {
go();
}
}); | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_RecentFilesPopup.java |
3,473 | public static class SlowLogParsedDocumentPrinter {
private final ParsedDocument doc;
private final long tookInNanos;
private final boolean reformat;
public SlowLogParsedDocumentPrinter(ParsedDocument doc, long tookInNanos, boolean reformat) {
this.doc = doc;
this.tookInNanos = tookInNanos;
this.reformat = reformat;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("took[").append(TimeValue.timeValueNanos(tookInNanos)).append("], took_millis[").append(TimeUnit.NANOSECONDS.toMillis(tookInNanos)).append("], ");
sb.append("type[").append(doc.type()).append("], ");
sb.append("id[").append(doc.id()).append("], ");
if (doc.routing() == null) {
sb.append("routing[], ");
} else {
sb.append("routing[").append(doc.routing()).append("], ");
}
if (doc.source() != null && doc.source().length() > 0) {
try {
sb.append("source[").append(XContentHelper.convertToJson(doc.source(), reformat)).append("]");
} catch (IOException e) {
sb.append("source[_failed_to_convert_]");
}
} else {
sb.append("source[]");
}
return sb.toString();
}
} | 0true
| src_main_java_org_elasticsearch_index_indexing_slowlog_ShardSlowLogIndexingService.java |
3,434 | private static class RemoteInvocationResponseHandler implements ResponseHandler {
private final NodeEngine nodeEngine;
private final Operation op;
private final AtomicBoolean sent = new AtomicBoolean(false);
private RemoteInvocationResponseHandler(NodeEngine nodeEngine, Operation op) {
this.nodeEngine = nodeEngine;
this.op = op;
}
@Override
public void sendResponse(Object obj) {
long callId = op.getCallId();
Connection conn = op.getConnection();
if (!sent.compareAndSet(false, true)) {
throw new ResponseAlreadySentException("NormalResponse already sent for call: " + callId
+ " to " + conn.getEndPoint() + ", current-response: " + obj);
}
NormalResponse response;
if (!(obj instanceof NormalResponse)) {
response = new NormalResponse(obj, op.getCallId(), 0, op.isUrgent());
} else {
response = (NormalResponse) obj;
}
nodeEngine.getOperationService().send(response, op.getCallerAddress());
}
@Override
public boolean isLocal() {
return false;
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_spi_impl_ResponseHandlerFactory.java |
2,126 | public class Log4jESLoggerFactory extends ESLoggerFactory {
@Override
protected ESLogger rootLogger() {
return new Log4jESLogger(null, Logger.getRootLogger());
}
@Override
protected ESLogger newInstance(String prefix, String name) {
final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(name);
return new Log4jESLogger(prefix, logger);
}
} | 0true
| src_main_java_org_elasticsearch_common_logging_log4j_Log4jESLoggerFactory.java |
2,297 | return new FilterRecycler<T>() {
SoftReference<Recycler<T>> ref;
{
ref = new SoftReference<Recycler<T>>(null);
}
@Override
protected Recycler<T> getDelegate() {
Recycler<T> recycler = ref.get();
if (recycler == null) {
recycler = factory.build();
ref = new SoftReference<Recycler<T>>(recycler);
}
return recycler;
}
}; | 0true
| src_main_java_org_elasticsearch_common_recycler_Recyclers.java |
1,684 | public interface AdminRole extends Serializable {
public void setId(Long id);
public Long getId();
public String getName();
public void setName(String name);
public String getDescription();
public void setDescription(String description);
public Set<AdminPermission> getAllPermissions();
public AdminRole clone();
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_domain_AdminRole.java |
3,471 | public class ShardSlowLogIndexingService extends AbstractIndexShardComponent {
private boolean reformat;
private long indexWarnThreshold;
private long indexInfoThreshold;
private long indexDebugThreshold;
private long indexTraceThreshold;
private String level;
private final ESLogger indexLogger;
private final ESLogger deleteLogger;
public static final String INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN = "index.indexing.slowlog.threshold.index.warn";
public static final String INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO = "index.indexing.slowlog.threshold.index.info";
public static final String INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG = "index.indexing.slowlog.threshold.index.debug";
public static final String INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE = "index.indexing.slowlog.threshold.index.trace";
public static final String INDEX_INDEXING_SLOWLOG_REFORMAT = "index.indexing.slowlog.reformat";
public static final String INDEX_INDEXING_SLOWLOG_LEVEL = "index.indexing.slowlog.level";
class ApplySettings implements IndexSettingsService.Listener {
@Override
public synchronized void onRefreshSettings(Settings settings) {
long indexWarnThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexWarnThreshold)).nanos();
if (indexWarnThreshold != ShardSlowLogIndexingService.this.indexWarnThreshold) {
ShardSlowLogIndexingService.this.indexWarnThreshold = indexWarnThreshold;
}
long indexInfoThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexInfoThreshold)).nanos();
if (indexInfoThreshold != ShardSlowLogIndexingService.this.indexInfoThreshold) {
ShardSlowLogIndexingService.this.indexInfoThreshold = indexInfoThreshold;
}
long indexDebugThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexDebugThreshold)).nanos();
if (indexDebugThreshold != ShardSlowLogIndexingService.this.indexDebugThreshold) {
ShardSlowLogIndexingService.this.indexDebugThreshold = indexDebugThreshold;
}
long indexTraceThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexTraceThreshold)).nanos();
if (indexTraceThreshold != ShardSlowLogIndexingService.this.indexTraceThreshold) {
ShardSlowLogIndexingService.this.indexTraceThreshold = indexTraceThreshold;
}
String level = settings.get(INDEX_INDEXING_SLOWLOG_LEVEL, ShardSlowLogIndexingService.this.level);
if (!level.equals(ShardSlowLogIndexingService.this.level)) {
ShardSlowLogIndexingService.this.indexLogger.setLevel(level.toUpperCase(Locale.ROOT));
ShardSlowLogIndexingService.this.deleteLogger.setLevel(level.toUpperCase(Locale.ROOT));
ShardSlowLogIndexingService.this.level = level;
}
boolean reformat = settings.getAsBoolean(INDEX_INDEXING_SLOWLOG_REFORMAT, ShardSlowLogIndexingService.this.reformat);
if (reformat != ShardSlowLogIndexingService.this.reformat) {
ShardSlowLogIndexingService.this.reformat = reformat;
}
}
}
@Inject
public ShardSlowLogIndexingService(ShardId shardId, @IndexSettings Settings indexSettings, IndexSettingsService indexSettingsService) {
super(shardId, indexSettings);
this.reformat = componentSettings.getAsBoolean("reformat", true);
this.indexWarnThreshold = componentSettings.getAsTime("threshold.index.warn", TimeValue.timeValueNanos(-1)).nanos();
this.indexInfoThreshold = componentSettings.getAsTime("threshold.index.info", TimeValue.timeValueNanos(-1)).nanos();
this.indexDebugThreshold = componentSettings.getAsTime("threshold.index.debug", TimeValue.timeValueNanos(-1)).nanos();
this.indexTraceThreshold = componentSettings.getAsTime("threshold.index.trace", TimeValue.timeValueNanos(-1)).nanos();
this.level = componentSettings.get("level", "TRACE").toUpperCase(Locale.ROOT);
this.indexLogger = Loggers.getLogger(logger, ".index");
this.deleteLogger = Loggers.getLogger(logger, ".delete");
indexLogger.setLevel(level);
deleteLogger.setLevel(level);
indexSettingsService.addListener(new ApplySettings());
}
public void postIndex(Engine.Index index, long tookInNanos) {
postIndexing(index.parsedDoc(), tookInNanos);
}
public void postCreate(Engine.Create create, long tookInNanos) {
postIndexing(create.parsedDoc(), tookInNanos);
}
private void postIndexing(ParsedDocument doc, long tookInNanos) {
if (indexWarnThreshold >= 0 && tookInNanos > indexWarnThreshold) {
indexLogger.warn("{}", new SlowLogParsedDocumentPrinter(doc, tookInNanos, reformat));
} else if (indexInfoThreshold >= 0 && tookInNanos > indexInfoThreshold) {
indexLogger.info("{}", new SlowLogParsedDocumentPrinter(doc, tookInNanos, reformat));
} else if (indexDebugThreshold >= 0 && tookInNanos > indexDebugThreshold) {
indexLogger.debug("{}", new SlowLogParsedDocumentPrinter(doc, tookInNanos, reformat));
} else if (indexTraceThreshold >= 0 && tookInNanos > indexTraceThreshold) {
indexLogger.trace("{}", new SlowLogParsedDocumentPrinter(doc, tookInNanos, reformat));
}
}
public static class SlowLogParsedDocumentPrinter {
private final ParsedDocument doc;
private final long tookInNanos;
private final boolean reformat;
public SlowLogParsedDocumentPrinter(ParsedDocument doc, long tookInNanos, boolean reformat) {
this.doc = doc;
this.tookInNanos = tookInNanos;
this.reformat = reformat;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("took[").append(TimeValue.timeValueNanos(tookInNanos)).append("], took_millis[").append(TimeUnit.NANOSECONDS.toMillis(tookInNanos)).append("], ");
sb.append("type[").append(doc.type()).append("], ");
sb.append("id[").append(doc.id()).append("], ");
if (doc.routing() == null) {
sb.append("routing[], ");
} else {
sb.append("routing[").append(doc.routing()).append("], ");
}
if (doc.source() != null && doc.source().length() > 0) {
try {
sb.append("source[").append(XContentHelper.convertToJson(doc.source(), reformat)).append("]");
} catch (IOException e) {
sb.append("source[_failed_to_convert_]");
}
} else {
sb.append("source[]");
}
return sb.toString();
}
}
} | 0true
| src_main_java_org_elasticsearch_index_indexing_slowlog_ShardSlowLogIndexingService.java |
968 | public final class UnlockRequest extends AbstractUnlockRequest {
public UnlockRequest() {
}
public UnlockRequest(Data key, long threadId) {
super(key, threadId);
}
public UnlockRequest(Data key, long threadId, boolean force) {
super(key, threadId, force);
}
@Override
protected InternalLockNamespace getNamespace() {
String name = getName();
return new InternalLockNamespace(name);
}
@Override
public int getFactoryId() {
return LockPortableHook.FACTORY_ID;
}
@Override
public int getClassId() {
return LockPortableHook.UNLOCK;
}
@Override
public Permission getRequiredPermission() {
String name = getName();
return new LockPermission(name, ActionConstants.ACTION_LOCK);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_client_UnlockRequest.java |
934 | if (makeDbCall(iOtherDb, new ODbRelatedCall<Boolean>() {
public Boolean call() {
return !otherMap.containsKey(myKey);
}
})) | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
936 | final Thread thread = new Thread() {
public void run() {
result.set(lock.isLockedByCurrentThread());
}
}; | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_lock_LockTest.java |
1,715 | runnable = new Runnable() { public void run() { map.putAll(mapWithNullValue); } }; | 0true
| hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java |
706 | public static class Order {
public static final int General = 1000;
public static final int Price = 2000;
public static final int ActiveDateRange = 3000;
public static final int Advanced = 1000;
public static final int Inventory = 1000;
public static final int Badges = 1000;
public static final int Shipping = 1000;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_ProductImpl.java |
1,413 | private static final class OSimpleVersionSerializer implements ORecordVersionSerializer {
private static final OSimpleVersionSerializer INSTANCE = new OSimpleVersionSerializer();
@Override
public void writeTo(DataOutput out, ORecordVersion version) throws IOException {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
out.writeInt(simpleVersion.version);
}
@Override
public void readFrom(DataInput in, ORecordVersion version) throws IOException {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
simpleVersion.version = in.readInt();
}
@Override
public void readFrom(InputStream stream, ORecordVersion version) throws IOException {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
simpleVersion.version = OBinaryProtocol.bytes2int(stream);
}
@Override
public void writeTo(OutputStream stream, ORecordVersion version) throws IOException {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
stream.write(OBinaryProtocol.int2bytes(simpleVersion.version));
}
@Override
public int writeTo(byte[] iStream, int pos, ORecordVersion version) {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
OBinaryProtocol.int2bytes(simpleVersion.version, iStream, pos);
return OBinaryProtocol.SIZE_INT;
}
@Override
public int readFrom(byte[] iStream, int pos, ORecordVersion version) {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
simpleVersion.version = OBinaryProtocol.bytes2int(iStream, pos);
return OBinaryProtocol.SIZE_INT;
}
@Override
public int writeTo(OFile file, long offset, ORecordVersion version) throws IOException {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
file.writeInt(offset, simpleVersion.version);
return OBinaryProtocol.SIZE_INT;
}
@Override
public long readFrom(OFile file, long offset, ORecordVersion version) throws IOException {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
simpleVersion.version = file.readInt(offset);
return OBinaryProtocol.SIZE_INT;
}
@Override
public int fastWriteTo(byte[] iStream, int pos, ORecordVersion version) {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
CONVERTER.putInt(iStream, pos, simpleVersion.version, ByteOrder.nativeOrder());
return OBinaryProtocol.SIZE_INT;
}
@Override
public int fastReadFrom(byte[] iStream, int pos, ORecordVersion version) {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
simpleVersion.version = CONVERTER.getInt(iStream, pos, ByteOrder.nativeOrder());
return OBinaryProtocol.SIZE_INT;
}
@Override
public byte[] toByteArray(ORecordVersion version) {
final byte[] bytes = new byte[OBinaryProtocol.SIZE_INT];
fastWriteTo(bytes, 0, version);
return bytes;
}
@Override
public String toString(ORecordVersion recordVersion) {
final OSimpleVersion simpleVersion = (OSimpleVersion) recordVersion;
return String.valueOf(simpleVersion.version);
}
@Override
public void fromString(String string, ORecordVersion version) {
final OSimpleVersion simpleVersion = (OSimpleVersion) version;
simpleVersion.version = Integer.parseInt(string);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_version_OSimpleVersion.java |
2,496 | EntryListener listener = new EntryAdapter() {
@Override
public void onEntryEvent(EntryEvent event) {
send(event);
}
private void send(EntryEvent event) {
if (endpoint.live()) {
Data key = clientEngine.toData(event.getKey());
Data value = clientEngine.toData(event.getValue());
Data oldValue = clientEngine.toData(event.getOldValue());
final EntryEventType type = event.getEventType();
final String uuid = event.getMember().getUuid();
PortableEntryEvent portableEntryEvent = new PortableEntryEvent(key, value, oldValue, type, uuid);
endpoint.sendEvent(portableEntryEvent, getCallId());
}
}
}; | 1no label
| hazelcast_src_main_java_com_hazelcast_multimap_operations_client_AddEntryListenerRequest.java |
205 | public static class
Start extends LogEntry
{
private final Xid xid;
private final int masterId;
private final int myId;
private final long timeWritten;
private final long lastCommittedTxWhenTransactionStarted;
private long startPosition;
Start( Xid xid, int identifier, int masterId, int myId, long startPosition, long timeWritten,
long lastCommittedTxWhenTransactionStarted )
{
super( identifier );
this.xid = xid;
this.masterId = masterId;
this.myId = myId;
this.startPosition = startPosition;
this.timeWritten = timeWritten;
this.lastCommittedTxWhenTransactionStarted = lastCommittedTxWhenTransactionStarted;
}
public Xid getXid()
{
return xid;
}
public int getMasterId()
{
return masterId;
}
public int getLocalId()
{
return myId;
}
public long getStartPosition()
{
return startPosition;
}
void setStartPosition( long position )
{
this.startPosition = position;
}
public long getTimeWritten()
{
return timeWritten;
}
public long getLastCommittedTxWhenTransactionStarted()
{
return lastCommittedTxWhenTransactionStarted;
}
/**
* @return combines necessary state to get a unique checksum to identify this transaction uniquely.
*/
public long getChecksum()
{
// [4 bits combined masterId/myId][4 bits xid hashcode, which combines time/randomness]
long lowBits = xid.hashCode();
long highBits = masterId*37 + myId;
return (highBits << 32) | (lowBits & 0xFFFFFFFFL);
}
@Override
public String toString()
{
return toString( Format.DEFAULT_TIME_ZONE );
}
@Override
public String toString( TimeZone timeZone )
{
return "Start[" + getIdentifier() + ",xid=" + xid + ",master=" + masterId + ",me=" + myId + ",time=" +
timestamp( timeWritten, timeZone ) + ",lastCommittedTxWhenTransactionStarted="+
lastCommittedTxWhenTransactionStarted+"]";
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogEntry.java |
527 | public class FlushResponse extends BroadcastOperationResponse {
FlushResponse() {
}
FlushResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_flush_FlushResponse.java |
229 | public interface SystemPropertiesDao {
public SystemProperty saveSystemProperty(SystemProperty systemProperty);
public void deleteSystemProperty(SystemProperty systemProperty);
public List<SystemProperty> readAllSystemProperties();
public SystemProperty readSystemPropertyByName(String name);
public SystemProperty createNewSystemProperty();
} | 0true
| common_src_main_java_org_broadleafcommerce_common_config_dao_SystemPropertiesDao.java |
700 | constructors[LIST_SUB] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListSubRequest();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java |
1,566 | @ManagedDescription("HazelcastInstance.OperationService")
public class OperationServiceMBean extends HazelcastMBean<OperationService> {
public OperationServiceMBean(HazelcastInstance hazelcastInstance, OperationService operationService,
ManagementService service) {
super(operationService, service);
Hashtable<String, String> properties = new Hashtable<String, String>(3);
properties.put("type", quote("HazelcastInstance.OperationService"));
properties.put("name", quote("operationService" + hazelcastInstance.getName()));
properties.put("instance", quote(hazelcastInstance.getName()));
setObjectName(properties);
}
@ManagedAnnotation("responseQueueSize")
@ManagedDescription("The size of the response queue")
public int getResponseQueueSize() {
return managedObject.getResponseQueueSize();
}
@ManagedAnnotation("operationExecutorQueueSize")
@ManagedDescription("The size of the operation executor queue")
int getOperationExecutorQueueSize() {
return managedObject.getOperationExecutorQueueSize();
}
@ManagedAnnotation("runningOperationsCount")
@ManagedDescription("the running operations count")
public int getRunningOperationsCount() {
return managedObject.getRunningOperationsCount();
}
@ManagedAnnotation("remoteOperationCount")
@ManagedDescription("The number of remote operations")
public int getRemoteOperationsCount() {
return managedObject.getRemoteOperationsCount();
}
@ManagedAnnotation("executedOperationCount")
@ManagedDescription("The number of executed operations")
public long getExecutedOperationCount() {
return managedObject.getExecutedOperationCount();
}
@ManagedAnnotation("operationThreadCount")
@ManagedDescription("Number of threads executing operations")
public long getOperationThreadCount() {
return managedObject.getPartitionOperationThreadCount();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_jmx_OperationServiceMBean.java |
233 | assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertTrue(map.isEmpty());
}
}); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java |
3,005 | public interface IdReaderTypeCache {
/**
* @param docId The Lucene docId of the child document to return the parent _uid for.
* @return The parent _uid for the specified docId (which is a child document)
*/
HashedBytesArray parentIdByDoc(int docId);
/**
* @param uid The uid of the document to return the lucene docId for
* @return The lucene docId for the specified uid
*/
int docById(HashedBytesArray uid);
/**
* @param docId The lucene docId of the document to return _uid for
* @return The _uid of the specified docId
*/
HashedBytesArray idByDoc(int docId);
/**
* @return The size in bytes for this particular instance
*/
long sizeInBytes();
} | 0true
| src_main_java_org_elasticsearch_index_cache_id_IdReaderTypeCache.java |
1,437 | public class RepositoriesMetaData implements MetaData.Custom {
public static final String TYPE = "repositories";
public static final Factory FACTORY = new Factory();
private final ImmutableList<RepositoryMetaData> repositories;
/**
* Constructs new repository metadata
*
* @param repositories list of repositories
*/
public RepositoriesMetaData(RepositoryMetaData... repositories) {
this.repositories = ImmutableList.copyOf(repositories);
}
/**
* Returns list of currently registered repositories
*
* @return list of repositories
*/
public ImmutableList<RepositoryMetaData> repositories() {
return this.repositories;
}
/**
* Returns a repository with a given name or null if such repository doesn't exist
*
* @param name name of repository
* @return repository metadata
*/
public RepositoryMetaData repository(String name) {
for (RepositoryMetaData repository : repositories) {
if (name.equals(repository.name())) {
return repository;
}
}
return null;
}
/**
* Repository metadata factory
*/
public static class Factory implements MetaData.Custom.Factory<RepositoriesMetaData> {
/**
* {@inheritDoc}
*/
@Override
public String type() {
return TYPE;
}
/**
* {@inheritDoc}
*/
@Override
public RepositoriesMetaData readFrom(StreamInput in) throws IOException {
RepositoryMetaData[] repository = new RepositoryMetaData[in.readVInt()];
for (int i = 0; i < repository.length; i++) {
repository[i] = RepositoryMetaData.readFrom(in);
}
return new RepositoriesMetaData(repository);
}
/**
* {@inheritDoc}
*/
@Override
public void writeTo(RepositoriesMetaData repositories, StreamOutput out) throws IOException {
out.writeVInt(repositories.repositories().size());
for (RepositoryMetaData repository : repositories.repositories()) {
repository.writeTo(out);
}
}
/**
* {@inheritDoc}
*/
@Override
public RepositoriesMetaData fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token;
List<RepositoryMetaData> repository = new ArrayList<RepositoryMetaData>();
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
String name = parser.currentName();
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("failed to parse repository [" + name + "], expected object");
}
String type = null;
Settings settings = ImmutableSettings.EMPTY;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
String currentFieldName = parser.currentName();
if ("type".equals(currentFieldName)) {
if (parser.nextToken() != XContentParser.Token.VALUE_STRING) {
throw new ElasticsearchParseException("failed to parse repository [" + name + "], unknown type");
}
type = parser.text();
} else if ("settings".equals(currentFieldName)) {
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("failed to parse repository [" + name + "], incompatible params");
}
settings = ImmutableSettings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())).build();
} else {
throw new ElasticsearchParseException("failed to parse repository [" + name + "], unknown field [" + currentFieldName + "]");
}
} else {
throw new ElasticsearchParseException("failed to parse repository [" + name + "]");
}
}
if (type == null) {
throw new ElasticsearchParseException("failed to parse repository [" + name + "], missing repository type");
}
repository.add(new RepositoryMetaData(name, type, settings));
} else {
throw new ElasticsearchParseException("failed to parse repositories");
}
}
return new RepositoriesMetaData(repository.toArray(new RepositoryMetaData[repository.size()]));
}
/**
* {@inheritDoc}
*/
@Override
public void toXContent(RepositoriesMetaData customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
for (RepositoryMetaData repository : customIndexMetaData.repositories()) {
toXContent(repository, builder, params);
}
}
/**
* Serializes information about a single repository
*
* @param repository repository metadata
* @param builder XContent builder
* @param params serialization parameters
* @throws IOException
*/
public void toXContent(RepositoryMetaData repository, XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject(repository.name(), XContentBuilder.FieldCaseConversion.NONE);
builder.field("type", repository.type());
builder.startObject("settings");
for (Map.Entry<String, String> settingEntry : repository.settings().getAsMap().entrySet()) {
builder.field(settingEntry.getKey(), settingEntry.getValue());
}
builder.endObject();
builder.endObject();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPersistent() {
return true;
}
}
} | 0true
| src_main_java_org_elasticsearch_cluster_metadata_RepositoriesMetaData.java |
1,139 | public interface DistributedObjectListener extends EventListener {
/**
* Invoked when a DistributedObject is created.
*
* @param event event
*/
void distributedObjectCreated(DistributedObjectEvent event);
/**
* Invoked when a DistributedObject is destroyed.
*
* @param event event
*/
void distributedObjectDestroyed(DistributedObjectEvent event);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_DistributedObjectListener.java |
428 | public class ClusterStateRequestBuilder extends MasterNodeReadOperationRequestBuilder<ClusterStateRequest, ClusterStateResponse, ClusterStateRequestBuilder> {
public ClusterStateRequestBuilder(ClusterAdminClient clusterClient) {
super((InternalClusterAdminClient) clusterClient, new ClusterStateRequest());
}
/**
* Include all data
*/
public ClusterStateRequestBuilder all() {
request.all();
return this;
}
/**
* Do not include any data
*/
public ClusterStateRequestBuilder clear() {
request.clear();
return this;
}
public ClusterStateRequestBuilder setBlocks(boolean filter) {
request.blocks(filter);
return this;
}
/**
* Should the cluster state result include the {@link org.elasticsearch.cluster.metadata.MetaData}. Defaults
* to <tt>true</tt>.
*/
public ClusterStateRequestBuilder setMetaData(boolean filter) {
request.metaData(filter);
return this;
}
/**
* Should the cluster state result include the {@link org.elasticsearch.cluster.node.DiscoveryNodes}. Defaults
* to <tt>true</tt>.
*/
public ClusterStateRequestBuilder setNodes(boolean filter) {
request.nodes(filter);
return this;
}
/**
* Should the cluster state result include teh {@link org.elasticsearch.cluster.routing.RoutingTable}. Defaults
* to <tt>true</tt>.
*/
public ClusterStateRequestBuilder setRoutingTable(boolean filter) {
request.routingTable(filter);
return this;
}
/**
* When {@link #setMetaData(boolean)} is set, which indices to return the {@link org.elasticsearch.cluster.metadata.IndexMetaData}
* for. Defaults to all indices.
*/
public ClusterStateRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
public ClusterStateRequestBuilder setIndexTemplates(String... templates) {
request.indexTemplates(templates);
return this;
}
@Override
protected void doExecute(ActionListener<ClusterStateResponse> listener) {
((ClusterAdminClient) client).state(request, listener);
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_cluster_state_ClusterStateRequestBuilder.java |
114 | public class OLogManager {
private boolean debug = true;
private boolean info = true;
private boolean warn = true;
private boolean error = true;
private Level minimumLevel = Level.SEVERE;
private static final String DEFAULT_LOG = "com.orientechnologies";
private static final OLogManager instance = new OLogManager();
protected OLogManager() {
}
public void setConsoleLevel(final String iLevel) {
setLevel(iLevel, ConsoleHandler.class);
}
public void setFileLevel(final String iLevel) {
setLevel(iLevel, FileHandler.class);
}
public void log(final Object iRequester, final Level iLevel, String iMessage, final Throwable iException,
final Object... iAdditionalArgs) {
if (iMessage != null) {
final Logger log = iRequester != null ? Logger.getLogger(iRequester.getClass().getName()) : Logger.getLogger(DEFAULT_LOG);
if (log == null) {
// USE SYSERR
try {
System.err.println(String.format(iMessage, iAdditionalArgs));
} catch (Exception e) {
OLogManager.instance().warn(this, "Error on formatting message", e);
}
} else if (log.isLoggable(iLevel)) {
// USE THE LOG
try {
final String msg = String.format(iMessage, iAdditionalArgs);
if (iException != null)
log.log(iLevel, msg, iException);
else
log.log(iLevel, msg);
} catch (Exception e) {
OLogManager.instance().warn(this, "Error on formatting message", e);
}
}
}
}
public void debug(final Object iRequester, final String iMessage, final Object... iAdditionalArgs) {
if (isDebugEnabled())
log(iRequester, Level.FINE, iMessage, null, iAdditionalArgs);
}
public void debug(final Object iRequester, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) {
if (isDebugEnabled())
log(iRequester, Level.FINE, iMessage, iException, iAdditionalArgs);
}
public void debug(final Object iRequester, final String iMessage, final Throwable iException,
final Class<? extends OException> iExceptionClass, final Object... iAdditionalArgs) {
debug(iRequester, iMessage, iException, iAdditionalArgs);
if (iExceptionClass != null)
try {
throw iExceptionClass.getConstructor(String.class, Throwable.class).newInstance(iMessage, iException);
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
public void info(final Object iRequester, final String iMessage, final Object... iAdditionalArgs) {
if (isInfoEnabled())
log(iRequester, Level.INFO, iMessage, null, iAdditionalArgs);
}
public void info(final Object iRequester, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) {
if (isInfoEnabled())
log(iRequester, Level.INFO, iMessage, iException, iAdditionalArgs);
}
public void warn(final Object iRequester, final String iMessage, final Object... iAdditionalArgs) {
if (isWarnEnabled())
log(iRequester, Level.WARNING, iMessage, null, iAdditionalArgs);
}
public void warn(final Object iRequester, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) {
if (isWarnEnabled())
log(iRequester, Level.WARNING, iMessage, iException, iAdditionalArgs);
}
public void config(final Object iRequester, final String iMessage, final Object... iAdditionalArgs) {
log(iRequester, Level.CONFIG, iMessage, null, iAdditionalArgs);
}
public void error(final Object iRequester, final String iMessage, final Object... iAdditionalArgs) {
log(iRequester, Level.SEVERE, iMessage, null, iAdditionalArgs);
}
public void error(final Object iRequester, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) {
if (isErrorEnabled())
log(iRequester, Level.SEVERE, iMessage, iException, iAdditionalArgs);
}
public void error(final Object iRequester, final String iMessage, final Throwable iException,
final Class<? extends OException> iExceptionClass, final Object... iAdditionalArgs) {
error(iRequester, iMessage, iException, iAdditionalArgs);
final String msg = String.format(iMessage, iAdditionalArgs);
if (iExceptionClass != null)
try {
throw iExceptionClass.getConstructor(String.class, Throwable.class).newInstance(msg, iException);
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
public void error(final Object iRequester, final String iMessage, final Class<? extends OException> iExceptionClass) {
error(iRequester, iMessage, (Throwable) null);
try {
throw iExceptionClass.getConstructor(String.class).newInstance(iMessage);
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
}
}
@SuppressWarnings("unchecked")
public void exception(final String iMessage, final Exception iNestedException, final Class<? extends OException> iExceptionClass,
final Object... iAdditionalArgs) throws OException {
if (iMessage == null)
return;
// FORMAT THE MESSAGE
String msg = String.format(iMessage, iAdditionalArgs);
Constructor<OException> c;
OException exceptionToThrow = null;
try {
if (iNestedException != null) {
c = (Constructor<OException>) iExceptionClass.getConstructor(String.class, Throwable.class);
exceptionToThrow = c.newInstance(msg, iNestedException);
}
} catch (Exception e) {
}
if (exceptionToThrow == null)
try {
c = (Constructor<OException>) iExceptionClass.getConstructor(String.class);
exceptionToThrow = c.newInstance(msg);
} catch (SecurityException e1) {
} catch (NoSuchMethodException e1) {
} catch (IllegalArgumentException e1) {
} catch (InstantiationException e1) {
} catch (IllegalAccessException e1) {
} catch (InvocationTargetException e1) {
}
if (exceptionToThrow != null)
throw exceptionToThrow;
else
throw new IllegalArgumentException("Cannot create the exception of type: " + iExceptionClass);
}
public boolean isWarn() {
return warn;
}
public void setWarnEnabled(boolean warn) {
this.warn = warn;
}
public void setInfoEnabled(boolean info) {
this.info = info;
}
public void setDebugEnabled(boolean debug) {
this.debug = debug;
}
public void setErrorEnabled(boolean error) {
this.error = error;
}
public boolean isLevelEnabled(final Level level) {
if (level.equals(Level.FINER) || level.equals(Level.FINE) || level.equals(Level.FINEST))
return debug;
else if (level.equals(Level.INFO))
return info;
else if (level.equals(Level.WARNING))
return warn;
else if (level.equals(Level.SEVERE))
return error;
return false;
}
public boolean isDebugEnabled() {
return debug;
}
public boolean isInfoEnabled() {
return info;
}
public boolean isWarnEnabled() {
return warn;
}
public boolean isErrorEnabled() {
return error;
}
public static OLogManager instance() {
return instance;
}
public Level setLevel(final String iLevel, final Class<? extends Handler> iHandler) {
final Level level = iLevel != null ? Level.parse(iLevel.toUpperCase(Locale.ENGLISH)) : Level.INFO;
if (level.intValue() < minimumLevel.intValue()) {
// UPDATE MINIMUM LEVEL
minimumLevel = level;
if (level.equals(Level.FINER) || level.equals(Level.FINE) || level.equals(Level.FINEST))
debug = info = warn = error = true;
else if (level.equals(Level.INFO)) {
info = warn = error = true;
debug = false;
} else if (level.equals(Level.WARNING)) {
warn = error = true;
debug = info = false;
} else if (level.equals(Level.SEVERE)) {
error = true;
debug = info = warn = false;
}
}
Logger log = Logger.getLogger(DEFAULT_LOG);
for (Handler h : log.getHandlers()) {
if (h.getClass().isAssignableFrom(iHandler)) {
h.setLevel(level);
break;
}
}
return level;
}
public static void installCustomFormatter() {
try {
// ASSURE TO HAVE THE ORIENT LOG FORMATTER TO THE CONSOLE EVEN IF NO CONFIGURATION FILE IS TAKEN
final Logger log = Logger.getLogger("");
if (log.getHandlers().length == 0) {
// SET DEFAULT LOG FORMATTER
final Handler h = new ConsoleHandler();
h.setFormatter(new OLogFormatter());
log.addHandler(h);
} else {
for (Handler h : log.getHandlers()) {
if (h instanceof ConsoleHandler && !h.getFormatter().getClass().equals(OLogFormatter.class))
h.setFormatter(new OLogFormatter());
}
}
} catch (Exception e) {
System.err.println("Error while installing custom formatter. Logging could be disabled. Cause: " + e.toString());
}
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_log_OLogManager.java |
228 | @Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
/**
* Tells to OrientDB to call the method BEFORE the record is read and unmarshalled from database.
* Applies only to the entity Objects reachable by the OrientDB engine after have registered them.
*/
public @interface OBeforeDeserialization {
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_annotation_OBeforeDeserialization.java |
1,211 | public class OPhysicalPosition implements OSerializableStream, Comparable<OPhysicalPosition>, Externalizable {
// POSITION IN THE CLUSTER
public OClusterPosition clusterPosition;
// ID OF DATA SEGMENT
public int dataSegmentId;
// POSITION OF CHUNK EXPRESSES AS OFFSET IN BYTES INSIDE THE DATA SEGMENT
public long dataSegmentPos;
// TYPE
public byte recordType;
// VERSION
public ORecordVersion recordVersion = OVersionFactory.instance().createVersion();
// SIZE IN BYTES OF THE RECORD. USED ONLY IN MEMORY
public int recordSize;
public static int binarySize;
private static boolean binarySizeKnown = false;
public OPhysicalPosition() {
}
public OPhysicalPosition(final OClusterPosition iClusterPosition) {
clusterPosition = iClusterPosition;
}
public OPhysicalPosition(final int iDataSegmentId, final long iDataSegmentPosition, final byte iRecordType) {
dataSegmentId = iDataSegmentId;
dataSegmentPos = iDataSegmentPosition;
recordType = iRecordType;
}
public OPhysicalPosition(final OClusterPosition iClusterPosition, final ORecordVersion iVersion) {
clusterPosition = iClusterPosition;
recordVersion.copyFrom(iVersion);
}
public void copyTo(final OPhysicalPosition iDest) {
iDest.clusterPosition = clusterPosition;
iDest.dataSegmentId = dataSegmentId;
iDest.dataSegmentPos = dataSegmentPos;
iDest.recordType = recordType;
iDest.recordVersion = recordVersion;
iDest.recordSize = recordSize;
}
public void copyFrom(final OPhysicalPosition iSource) {
iSource.copyTo(this);
}
@Override
public String toString() {
return "rid(?:" + clusterPosition + ") data(" + dataSegmentId + ":" + dataSegmentPos + ") record(type:" + recordType + " size:"
+ recordSize + " v:" + recordVersion + ")";
}
public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException {
int pos = 0;
clusterPosition = OClusterPositionFactory.INSTANCE.fromStream(iStream);
pos += OClusterPositionFactory.INSTANCE.getSerializedSize();
dataSegmentId = OBinaryProtocol.bytes2int(iStream, pos);
pos += OBinaryProtocol.SIZE_INT;
dataSegmentPos = OBinaryProtocol.bytes2long(iStream, pos);
pos += OBinaryProtocol.SIZE_LONG;
recordType = iStream[pos];
pos += OBinaryProtocol.SIZE_BYTE;
recordSize = OBinaryProtocol.bytes2int(iStream, pos);
pos += OBinaryProtocol.SIZE_INT;
recordVersion.getSerializer().readFrom(iStream, pos, recordVersion);
return this;
}
public byte[] toStream() throws OSerializationException {
byte[] buffer = new byte[binarySize()];
int pos = 0;
final byte[] clusterContent = clusterPosition.toStream();
System.arraycopy(clusterContent, 0, buffer, 0, clusterContent.length);
pos += clusterContent.length;
OBinaryProtocol.int2bytes(dataSegmentId, buffer, pos);
pos += OBinaryProtocol.SIZE_INT;
OBinaryProtocol.long2bytes(dataSegmentPos, buffer, pos);
pos += OBinaryProtocol.SIZE_LONG;
buffer[pos] = recordType;
pos += OBinaryProtocol.SIZE_BYTE;
OBinaryProtocol.int2bytes(recordSize, buffer, pos);
pos += OBinaryProtocol.SIZE_INT;
recordVersion.getSerializer().writeTo(buffer, pos, recordVersion);
return buffer;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof OPhysicalPosition))
return false;
final OPhysicalPosition other = (OPhysicalPosition) obj;
return clusterPosition.equals(other.clusterPosition) && recordType == other.recordType
&& recordVersion.equals(other.recordVersion) && recordSize == other.recordSize;
}
@Override
public int hashCode() {
int result = clusterPosition != null ? clusterPosition.hashCode() : 0;
result = 31 * result + dataSegmentId;
result = 31 * result + (int) (dataSegmentPos ^ (dataSegmentPos >>> 32));
result = 31 * result + (int) recordType;
result = 31 * result + (recordVersion != null ? recordVersion.hashCode() : 0);
result = 31 * result + recordSize;
return result;
}
public int compareTo(final OPhysicalPosition iOther) {
return (int) (dataSegmentPos - iOther.dataSegmentPos);
}
public void writeExternal(final ObjectOutput out) throws IOException {
final byte[] clusterContent = clusterPosition.toStream();
out.write(clusterContent);
out.writeInt(dataSegmentId);
out.writeLong(dataSegmentPos);
out.writeByte(recordType);
out.writeInt(recordSize);
recordVersion.getSerializer().writeTo(out, recordVersion);
}
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
clusterPosition = OClusterPositionFactory.INSTANCE.fromStream(in);
dataSegmentId = in.readInt();
dataSegmentPos = in.readLong();
recordType = in.readByte();
recordSize = in.readInt();
recordVersion.getSerializer().readFrom(in, recordVersion);
}
public static int binarySize() {
if (binarySizeKnown)
return binarySize;
binarySizeKnown = true;
binarySize = OClusterPositionFactory.INSTANCE.getSerializedSize() + OBinaryProtocol.SIZE_INT + OBinaryProtocol.SIZE_LONG
+ OBinaryProtocol.SIZE_BYTE + OVersionFactory.instance().getVersionSize() + OBinaryProtocol.SIZE_INT;
return binarySize;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_OPhysicalPosition.java |
747 | public class GetAction extends Action<GetRequest, GetResponse, GetRequestBuilder> {
public static final GetAction INSTANCE = new GetAction();
public static final String NAME = "get";
private GetAction() {
super(NAME);
}
@Override
public GetResponse newResponse() {
return new GetResponse();
}
@Override
public GetRequestBuilder newRequestBuilder(Client client) {
return new GetRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_get_GetAction.java |
4,679 | final static class MatchAndScore extends QueryCollector {
final PercolateContext context;
final HighlightPhase highlightPhase;
final List<BytesRef> matches = new ArrayList<BytesRef>();
final List<Map<String, HighlightField>> hls = new ArrayList<Map<String, HighlightField>>();
// TODO: Use thread local in order to cache the scores lists?
final FloatArrayList scores = new FloatArrayList();
final boolean limit;
final int size;
long counter = 0;
private Scorer scorer;
MatchAndScore(ESLogger logger, PercolateContext context, HighlightPhase highlightPhase) {
super(logger, context);
this.limit = context.limit;
this.size = context.size;
this.context = context;
this.highlightPhase = highlightPhase;
}
@Override
public void collect(int doc) throws IOException {
final Query query = getQuery(doc);
if (query == null) {
// log???
return;
}
// run the query
try {
collector.reset();
if (context.highlight() != null) {
context.parsedQuery(new ParsedQuery(query, ImmutableMap.<String, Filter>of()));
context.hitContext().cache().clear();
}
searcher.search(query, collector);
if (collector.exists()) {
if (!limit || counter < size) {
matches.add(values.copyShared());
scores.add(scorer.score());
if (context.highlight() != null) {
highlightPhase.hitExecute(context, context.hitContext());
hls.add(context.hitContext().hit().getHighlightFields());
}
}
counter++;
if (facetAndAggregatorCollector != null) {
facetAndAggregatorCollector.collect(doc);
}
}
} catch (IOException e) {
logger.warn("[" + spare.bytes.utf8ToString() + "] failed to execute query", e);
}
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
}
long counter() {
return counter;
}
List<BytesRef> matches() {
return matches;
}
FloatArrayList scores() {
return scores;
}
List<Map<String, HighlightField>> hls() {
return hls;
}
} | 1no label
| src_main_java_org_elasticsearch_percolator_QueryCollector.java |
290 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="BLC_DATA_DRVN_ENUM")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "DataDrivenEnumerationImpl_friendyName")
public class DataDrivenEnumerationImpl implements DataDrivenEnumeration {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "DataDrivenEnumerationId")
@GenericGenerator(
name="DataDrivenEnumerationId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="DataDrivenEnumerationImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.common.enumeration.domain.DataDrivenEnumerationImpl")
}
)
@Column(name = "ENUM_ID")
protected Long id;
@Column(name = "ENUM_KEY")
@Index(name = "ENUM_KEY_INDEX", columnNames = {"KEY"})
@AdminPresentation(friendlyName = "DataDrivenEnumerationImpl_Key", order = 1, gridOrder = 1, prominent = true)
protected String key;
@Column(name = "MODIFIABLE")
@AdminPresentation(friendlyName = "DataDrivenEnumerationImpl_Modifiable", order = 2, gridOrder = 2, prominent = true)
protected Boolean modifiable = false;
@OneToMany(mappedBy = "type", targetEntity = DataDrivenEnumerationValueImpl.class, cascade = {CascadeType.ALL})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationCollection(addType = AddMethodType.PERSIST, friendlyName = "DataDrivenEnumerationImpl_Enum_Values", order = 3)
protected List<DataDrivenEnumerationValue> enumValues = new ArrayList<DataDrivenEnumerationValue>();
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public Boolean getModifiable() {
if (modifiable == null) {
return Boolean.FALSE;
} else {
return modifiable;
}
}
@Override
public void setModifiable(Boolean modifiable) {
this.modifiable = modifiable;
}
@Override
public List<DataDrivenEnumerationValue> getEnumValues() {
return enumValues;
}
@Override
public void setEnumValues(List<DataDrivenEnumerationValue> enumValues) {
this.enumValues = enumValues;
}
@Override
@Deprecated
public List<DataDrivenEnumerationValue> getOrderItems() {
return enumValues;
}
@Override
@Deprecated
public void setOrderItems(List<DataDrivenEnumerationValue> orderItems) {
this.enumValues = orderItems;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_enumeration_domain_DataDrivenEnumerationImpl.java |
3,186 | private static final class Empty extends GeoPointValues {
protected Empty() {
super(false);
}
@Override
public int setDocument(int docId) {
return 0;
}
@Override
public GeoPoint nextValue() {
throw new ElasticsearchIllegalStateException("Empty GeoPointValues has no next value");
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_GeoPointValues.java |
3,007 | public class ShardIdCacheModule extends AbstractModule {
@Override
protected void configure() {
bind(ShardIdCache.class).asEagerSingleton();
}
} | 0true
| src_main_java_org_elasticsearch_index_cache_id_ShardIdCacheModule.java |
639 | @Test
public class OPropertyIndexDefinitionTest {
private OPropertyIndexDefinition propertyIndex;
@BeforeMethod
public void beforeMethod() {
propertyIndex = new OPropertyIndexDefinition("testClass", "fOne", OType.INTEGER);
}
@Test
public void testCreateValueSingleParameter() {
final Object result = propertyIndex.createValue(Collections.singletonList("12"));
Assert.assertEquals(result, 12);
}
@Test
public void testCreateValueTwoParameters() {
final Object result = propertyIndex.createValue(Arrays.asList("12", "25"));
Assert.assertEquals(result, 12);
}
@Test(expectedExceptions = NumberFormatException.class)
public void testCreateValueWrongParameter() {
propertyIndex.createValue(Collections.singletonList("tt"));
}
@Test
public void testCreateValueSingleParameterArrayParams() {
final Object result = propertyIndex.createValue("12");
Assert.assertEquals(result, 12);
}
@Test
public void testCreateValueTwoParametersArrayParams() {
final Object result = propertyIndex.createValue("12", "25");
Assert.assertEquals(result, 12);
}
@Test(expectedExceptions = NumberFormatException.class)
public void testCreateValueWrongParameterArrayParams() {
propertyIndex.createValue("tt");
}
@Test
public void testGetDocumentValueToIndex() {
final ODocument document = new ODocument();
document.field("fOne", "15");
document.field("fTwo", 10);
final Object result = propertyIndex.getDocumentValueToIndex(document);
Assert.assertEquals(result, 15);
}
@Test
public void testGetFields() {
final List<String> result = propertyIndex.getFields();
Assert.assertEquals(result.size(), 1);
Assert.assertEquals(result.get(0), "fOne");
}
@Test
public void testGetTypes() {
final OType[] result = propertyIndex.getTypes();
Assert.assertEquals(result.length, 1);
Assert.assertEquals(result[0], OType.INTEGER);
}
@Test
public void testEmptyIndexReload() {
final ODatabaseDocumentTx database = new ODatabaseDocumentTx("memory:propertytest");
database.create();
propertyIndex = new OPropertyIndexDefinition("tesClass", "fOne", OType.INTEGER);
final ODocument docToStore = propertyIndex.toStream();
database.save(docToStore);
final ODocument docToLoad = database.load(docToStore.getIdentity());
final OPropertyIndexDefinition result = new OPropertyIndexDefinition();
result.fromStream(docToLoad);
database.drop();
Assert.assertEquals(result, propertyIndex);
}
@Test
public void testIndexReload() {
final ODocument docToStore = propertyIndex.toStream();
final OPropertyIndexDefinition result = new OPropertyIndexDefinition();
result.fromStream(docToStore);
Assert.assertEquals(result, propertyIndex);
}
@Test
public void testGetParamCount() {
Assert.assertEquals(propertyIndex.getParamCount(), 1);
}
@Test
public void testClassName() {
Assert.assertEquals("testClass", propertyIndex.getClassName());
}
} | 0true
| core_src_test_java_com_orientechnologies_orient_core_index_OPropertyIndexDefinitionTest.java |
43 | public class MultiPaxosServerFactory
implements ProtocolServerFactory
{
private final ClusterConfiguration initialConfig;
private final Logging logging;
public MultiPaxosServerFactory( ClusterConfiguration initialConfig, Logging logging )
{
this.initialConfig = initialConfig;
this.logging = logging;
}
@Override
public ProtocolServer newProtocolServer( InstanceId me, TimeoutStrategy timeoutStrategy, MessageSource input,
MessageSender output, AcceptorInstanceStore acceptorInstanceStore,
ElectionCredentialsProvider electionCredentialsProvider,
Executor stateMachineExecutor,
ObjectInputStreamFactory objectInputStreamFactory,
ObjectOutputStreamFactory objectOutputStreamFactory )
{
DelayedDirectExecutor executor = new DelayedDirectExecutor();
// Create state machines
Timeouts timeouts = new Timeouts( timeoutStrategy );
final MultiPaxosContext context = new MultiPaxosContext( me,
Iterables.<ElectionRole,ElectionRole>iterable( new ElectionRole(ClusterConfiguration.COORDINATOR )),
new ClusterConfiguration( initialConfig.getName(), logging.getMessagesLog( ClusterConfiguration.class ),
initialConfig.getMemberURIs() ),
executor, logging, objectInputStreamFactory, objectOutputStreamFactory, acceptorInstanceStore, timeouts,
electionCredentialsProvider);
SnapshotContext snapshotContext = new SnapshotContext( context.getClusterContext(),context.getLearnerContext());
return newProtocolServer( me, input, output, stateMachineExecutor, executor, timeouts,
context, snapshotContext );
}
public ProtocolServer newProtocolServer( InstanceId me, MessageSource input, MessageSender output,
Executor stateMachineExecutor, DelayedDirectExecutor executor, Timeouts timeouts,
MultiPaxosContext context, SnapshotContext snapshotContext )
{
return constructSupportingInfrastructureFor( me, input, output, executor, timeouts, stateMachineExecutor, context, new StateMachine[]
{
new StateMachine( context.getAtomicBroadcastContext(), AtomicBroadcastMessage.class,
AtomicBroadcastState.start, logging ),
new StateMachine( context.getAcceptorContext(), AcceptorMessage.class, AcceptorState.start, logging ),
new StateMachine( context.getProposerContext(), ProposerMessage.class, ProposerState.start, logging ),
new StateMachine( context.getLearnerContext(), LearnerMessage.class, LearnerState.start, logging ),
new StateMachine( context.getHeartbeatContext(), HeartbeatMessage.class, HeartbeatState.start,
logging ),
new StateMachine( context.getElectionContext(), ElectionMessage.class, ElectionState.start, logging ),
new StateMachine( snapshotContext, SnapshotMessage.class, SnapshotState.start, logging ),
new StateMachine( context.getClusterContext(), ClusterMessage.class, ClusterState.start, logging )
});
}
/**
* Sets up the supporting infrastructure and communication hooks for our state machines. This is here to support
* an external requirement for assembling protocol servers given an existing set of state machines (used to prove
* correctness).
* */
public ProtocolServer constructSupportingInfrastructureFor( InstanceId me, MessageSource input,
MessageSender output, DelayedDirectExecutor executor, Timeouts timeouts,
Executor stateMachineExecutor, final MultiPaxosContext context,
StateMachine[] machines )
{
StateMachines stateMachines = new StateMachines( input, output, timeouts, executor, stateMachineExecutor, me );
for ( StateMachine machine : machines )
{
stateMachines.addStateMachine( machine );
}
final ProtocolServer server = new ProtocolServer( me, stateMachines, logging );
server.addBindingListener( new BindingListener()
{
@Override
public void listeningAt( URI me )
{
context.getClusterContext().setBoundAt( me );
}
} );
stateMachines.addMessageProcessor( new HeartbeatRefreshProcessor( stateMachines.getOutgoing
(), context.getClusterContext() ) );
input.addMessageProcessor( new HeartbeatIAmAliveProcessor( stateMachines.getOutgoing(),
context.getClusterContext() ) );
server.newClient( Cluster.class ).addClusterListener( new HeartbeatJoinListener( stateMachines
.getOutgoing() ) );
context.getHeartbeatContext().addHeartbeatListener( new HeartbeatReelectionListener(
server.newClient( Election.class ), logging.getMessagesLog( ClusterLeaveReelectionListener.class ) ) );
context.getClusterContext().addClusterListener( new ClusterLeaveReelectionListener( server.newClient(
Election.class ),
logging.getMessagesLog( ClusterLeaveReelectionListener.class ) ) );
StateMachineRules rules = new StateMachineRules( stateMachines.getOutgoing() )
.rule( ClusterState.start, ClusterMessage.create, ClusterState.entered,
internal( AtomicBroadcastMessage.entered ),
internal( ProposerMessage.join ),
internal( AcceptorMessage.join ),
internal( LearnerMessage.join ),
internal( HeartbeatMessage.join ),
internal( ElectionMessage.created ),
internal( SnapshotMessage.join ) )
.rule( ClusterState.discovery, ClusterMessage.configurationResponse, ClusterState.joining,
internal( AcceptorMessage.join ),
internal( LearnerMessage.join ),
internal( AtomicBroadcastMessage.join ) )
.rule( ClusterState.discovery, ClusterMessage.configurationResponse, ClusterState.entered,
internal( AtomicBroadcastMessage.entered ),
internal( ProposerMessage.join ),
internal( AcceptorMessage.join ),
internal( LearnerMessage.join ),
internal( HeartbeatMessage.join ),
internal( ElectionMessage.join ),
internal( SnapshotMessage.join ) )
.rule( ClusterState.joining, ClusterMessage.configurationChanged, ClusterState.entered,
internal( AtomicBroadcastMessage.entered ),
internal( ProposerMessage.join ),
internal( AcceptorMessage.join ),
internal( LearnerMessage.join ),
internal( HeartbeatMessage.join ),
internal( ElectionMessage.join ),
internal( SnapshotMessage.join ) )
.rule( ClusterState.joining, ClusterMessage.joinFailure, ClusterState.start,
internal( AtomicBroadcastMessage.leave ),
internal( AcceptorMessage.leave ),
internal( LearnerMessage.leave ),
internal( ProposerMessage.leave ) )
.rule( ClusterState.entered, ClusterMessage.leave, ClusterState.start,
internal( AtomicBroadcastMessage.leave ),
internal( AcceptorMessage.leave ),
internal( LearnerMessage.leave ),
internal( HeartbeatMessage.leave ),
internal( SnapshotMessage.leave ),
internal( ElectionMessage.leave ),
internal( ProposerMessage.leave ) )
.rule( ClusterState.entered, ClusterMessage.leave, ClusterState.start,
internal( AtomicBroadcastMessage.leave ),
internal( AcceptorMessage.leave ),
internal( LearnerMessage.leave ),
internal( HeartbeatMessage.leave ),
internal( ElectionMessage.leave ),
internal( SnapshotMessage.leave ),
internal( ProposerMessage.leave ) )
.rule( ClusterState.leaving, ClusterMessage.configurationChanged, ClusterState.start,
internal( AtomicBroadcastMessage.leave ),
internal( AcceptorMessage.leave ),
internal( LearnerMessage.leave ),
internal( HeartbeatMessage.leave ),
internal( ElectionMessage.leave ),
internal( SnapshotMessage.leave ),
internal( ProposerMessage.leave ) )
.rule( ClusterState.leaving, ClusterMessage.leaveTimedout, ClusterState.start,
internal( AtomicBroadcastMessage.leave ),
internal( AcceptorMessage.leave ),
internal( LearnerMessage.leave ),
internal( HeartbeatMessage.leave ),
internal( ElectionMessage.leave ),
internal( SnapshotMessage.leave ),
internal( ProposerMessage.leave ) );
stateMachines.addStateTransitionListener( rules );
return server;
}
} | 1no label
| enterprise_cluster_src_main_java_org_neo4j_cluster_MultiPaxosServerFactory.java |
600 | public class GetSettingsAction extends IndicesAction<GetSettingsRequest, GetSettingsResponse, GetSettingsRequestBuilder> {
public static final GetSettingsAction INSTANCE = new GetSettingsAction();
public static final String NAME = "indices/settings/get";
public GetSettingsAction() {
super(NAME);
}
@Override
public GetSettingsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new GetSettingsRequestBuilder((InternalGenericClient) client);
}
@Override
public GetSettingsResponse newResponse() {
return new GetSettingsResponse();
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_settings_get_GetSettingsAction.java |
3,347 | public static class SingleFixedSet extends GeoPointCompressedAtomicFieldData {
private final GeoPointFieldMapper.Encoding encoding;
private final PagedMutable lon, lat;
private final FixedBitSet set;
private final long numOrds;
public SingleFixedSet(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, int numDocs, FixedBitSet set, long numOrds) {
super(numDocs);
this.encoding = encoding;
this.lon = lon;
this.lat = lat;
this.set = set;
this.numOrds = numOrds;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrds;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + lon.ramBytesUsed() + lat.ramBytesUsed() + RamUsageEstimator.sizeOf(set.getBits());
}
return size;
}
@Override
public GeoPointValues getGeoPointValues() {
return new GeoPointValuesSingleFixedSet(encoding, lon, lat, set);
}
static class GeoPointValuesSingleFixedSet extends GeoPointValues {
private final GeoPointFieldMapper.Encoding encoding;
private final PagedMutable lat, lon;
private final FixedBitSet set;
private final GeoPoint scratch = new GeoPoint();
GeoPointValuesSingleFixedSet(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, FixedBitSet set) {
super(false);
this.encoding = encoding;
this.lon = lon;
this.lat = lat;
this.set = set;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return set.get(docId) ? 1 : 0;
}
@Override
public GeoPoint nextValue() {
return encoding.decode(lat.get(docId), lon.get(docId), scratch);
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_GeoPointCompressedAtomicFieldData.java |
80 | public static class FieldOrder {
// General Fields
public static final int NAME = 1000;
public static final int URL = 2000;
public static final int TITLE = 3000;
public static final int ALT_TEXT = 4000;
public static final int MIME_TYPE = 5000;
public static final int FILE_EXTENSION = 6000;
public static final int FILE_SIZE = 7000;
// Used by subclasses to know where the last field is.
public static final int LAST = 7000;
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java |
3,130 | static class VersionValue {
private final long version;
private final boolean delete;
private final long time;
private final Translog.Location translogLocation;
VersionValue(long version, boolean delete, long time, Translog.Location translogLocation) {
this.version = version;
this.delete = delete;
this.time = time;
this.translogLocation = translogLocation;
}
public long time() {
return this.time;
}
public long version() {
return version;
}
public boolean delete() {
return delete;
}
public Translog.Location translogLocation() {
return this.translogLocation;
}
} | 0true
| src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java |
140 | public abstract class LocalProposal extends AbstractLinkedMode
implements ICompletionProposal, ICompletionProposalExtension6 {
protected int offset;
protected int exitPos;
protected ProducedType type;
protected String initialName;
protected String[] nameProposals;
protected final int currentOffset;
@Override
protected String getHintTemplate() {
return "Enter type and name for new local {0}";
}
@Override
protected final void updatePopupLocation() {
LinkedPosition currentLinkedPosition = getCurrentLinkedPosition();
if (currentLinkedPosition==null) {
getInfoPopup().setHintTemplate(getHintTemplate());
}
else if (currentLinkedPosition.getSequenceNumber()==1) {
getInfoPopup().setHintTemplate("Enter type for new local {0}");
}
else {
getInfoPopup().setHintTemplate("Enter name for new local {0}");
}
}
private void performInitialChange(IDocument document) {
Tree.Statement st = findStatement(rootNode, node);
Node expression;
Node expanse;
ProducedType resultType;
if (st instanceof Tree.ExpressionStatement) {
Tree.Expression e =
((Tree.ExpressionStatement) st).getExpression();
expression = e;
expanse = st;
resultType = e.getTypeModel();
if (e.getTerm() instanceof Tree.InvocationExpression) {
Primary primary =
((Tree.InvocationExpression) e.getTerm()).getPrimary();
if (primary instanceof Tree.QualifiedMemberExpression) {
Tree.QualifiedMemberExpression prim =
(Tree.QualifiedMemberExpression) primary;
if (prim.getMemberOperator().getToken()==null) {
//an expression followed by two annotations
//can look like a named operator expression
//even though that is disallowed as an
//expression statement
Tree.Primary p = prim.getPrimary();
expression = p;
expanse = expression;
resultType = p.getTypeModel();
}
}
}
}
else if (st instanceof Tree.Declaration) {
Tree.Declaration dec = (Tree.Declaration) st;
Declaration d = dec.getDeclarationModel();
if (d==null || d.isToplevel()) {
return;
}
//some expressions get interpreted as annotations
List<Annotation> annotations =
dec.getAnnotationList().getAnnotations();
Tree.AnonymousAnnotation aa =
dec.getAnnotationList().getAnonymousAnnotation();
if (aa!=null && currentOffset<=aa.getStopIndex()+1) {
expression = aa;
expanse = expression;
resultType = aa.getUnit().getStringDeclaration().getType();
}
else if (!annotations.isEmpty() &&
currentOffset<=dec.getAnnotationList().getStopIndex()+1) {
Tree.Annotation a = annotations.get(0);
expression = a;
expanse = expression;
resultType = a.getTypeModel();
}
else if (st instanceof Tree.TypedDeclaration) {
//some expressions look like a type declaration
//when they appear right in front of an annotation
//or function invocations
Tree.Type type = ((Tree.TypedDeclaration) st).getType();
if (type instanceof Tree.SimpleType) {
expression = type;
expanse = expression;
resultType = type.getTypeModel();
}
else if (type instanceof Tree.FunctionType) {
expression = type;
expanse = expression;
resultType = node.getUnit()
.getCallableReturnType(type.getTypeModel());
}
else {
return;
}
}
else {
return;
}
}
else {
return;
}
Integer stopIndex = expanse.getStopIndex();
if (currentOffset<expanse.getStartIndex() ||
currentOffset>stopIndex+1) {
return;
}
nameProposals = computeNameProposals(expression);
initialName = nameProposals[0];
offset = expanse.getStartIndex();
type = resultType==null ?
null : node.getUnit().denotableType(resultType);
DocumentChange change =
createChange(document, expanse, stopIndex);
try {
change.perform(new NullProgressMonitor());
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
String[] computeNameProposals(Node expression) {
return Nodes.nameProposals(expression);
}
protected abstract DocumentChange createChange(IDocument document,
Node expanse, Integer stopIndex);
protected final Node node;
protected final Tree.CompilationUnit rootNode;
@Override
public void apply(IDocument document) {
try {
performInitialChange(document);
CeylonParseController cpc = editor.getParseController();
Unit unit = cpc.getRootNode().getUnit();
addLinkedPositions(document, unit);
enterLinkedMode(document, 2, exitPos + initialName.length() + 9);
openPopup();
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
protected abstract void addLinkedPositions(IDocument document, Unit unit)
throws BadLocationException;
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), false, true);
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public Image getImage() {
return MINOR_CHANGE;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
public LocalProposal(Tree.CompilationUnit cu, Node node,
int currentOffset) {
super((CeylonEditor) EditorUtil.getCurrentEditor());
this.rootNode = cu;
this.node = node;
this.currentOffset = currentOffset;
}
boolean isEnabled(ProducedType resultType) {
return true;
}
boolean isEnabled() {
Tree.Statement st = findStatement(rootNode, node);
if (st instanceof Tree.ExpressionStatement) {
Tree.Expression e =
((Tree.ExpressionStatement) st).getExpression();
ProducedType resultType = e.getTypeModel();
if (e.getTerm() instanceof Tree.InvocationExpression) {
Primary primary =
((Tree.InvocationExpression) e.getTerm()).getPrimary();
if (primary instanceof Tree.QualifiedMemberExpression) {
Tree.QualifiedMemberExpression prim =
(Tree.QualifiedMemberExpression) primary;
if (prim.getMemberOperator().getToken()==null) {
//an expression followed by two annotations
//can look like a named operator expression
//even though that is disallowed as an
//expression statement
Tree.Primary p = prim.getPrimary();
resultType = p.getTypeModel();
}
}
}
return isEnabled(resultType);
}
else if (st instanceof Tree.Declaration) {
Tree.Declaration dec = (Tree.Declaration) st;
Identifier id = dec.getIdentifier();
if (id==null) {
return false;
}
int line = id.getToken().getLine();
Declaration d = dec.getDeclarationModel();
if (d==null || d.isToplevel()) {
return false;
}
//some expressions get interpreted as annotations
List<Annotation> annotations =
dec.getAnnotationList().getAnnotations();
Tree.AnonymousAnnotation aa =
dec.getAnnotationList().getAnonymousAnnotation();
ProducedType resultType;
if (aa!=null && currentOffset<=aa.getStopIndex()+1) {
if (aa.getEndToken().getLine()==line) {
return false;
}
resultType = aa.getUnit().getStringDeclaration().getType();
}
else if (!annotations.isEmpty() &&
currentOffset<=dec.getAnnotationList().getStopIndex()+1) {
Tree.Annotation a = annotations.get(0);
if (a.getEndToken().getLine()==line) {
return false;
}
resultType = a.getTypeModel();
}
else if (st instanceof Tree.TypedDeclaration) {
//some expressions look like a type declaration
//when they appear right in front of an annotation
//or function invocations
Tree.Type type = ((Tree.TypedDeclaration) st).getType();
if (currentOffset<=type.getStopIndex()+1 &&
currentOffset>=type.getStartIndex() &&
type.getEndToken().getLine()!=line) {
resultType = type.getTypeModel();
if (type instanceof Tree.SimpleType) {
//just use that type
}
else if (type instanceof Tree.FunctionType) {
//instantiation expressions look like a
//function type declaration
resultType = node.getUnit()
.getCallableReturnType(resultType);
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
return isEnabled(resultType);
}
return false;
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_LocalProposal.java |
196 | public class UniqueTokenFilter extends TokenFilter {
private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);
private final PositionIncrementAttribute posIncAttribute = addAttribute(PositionIncrementAttribute.class);
// use a fixed version, as we don't care about case sensitivity.
private final CharArraySet previous = new CharArraySet(Version.LUCENE_31, 8, false);
private final boolean onlyOnSamePosition;
public UniqueTokenFilter(TokenStream in) {
this(in, false);
}
public UniqueTokenFilter(TokenStream in, boolean onlyOnSamePosition) {
super(in);
this.onlyOnSamePosition = onlyOnSamePosition;
}
@Override
public final boolean incrementToken() throws IOException {
while (input.incrementToken()) {
final char term[] = termAttribute.buffer();
final int length = termAttribute.length();
boolean duplicate;
if (onlyOnSamePosition) {
final int posIncrement = posIncAttribute.getPositionIncrement();
if (posIncrement > 0) {
previous.clear();
}
duplicate = (posIncrement == 0 && previous.contains(term, 0, length));
} else {
duplicate = previous.contains(term, 0, length);
}
// clone the term, and add to the set of seen terms.
char saved[] = new char[length];
System.arraycopy(term, 0, saved, 0, length);
previous.add(saved);
if (!duplicate) {
return true;
}
}
return false;
}
@Override
public final void reset() throws IOException {
super.reset();
previous.clear();
}
} | 0true
| src_main_java_org_apache_lucene_analysis_miscellaneous_UniqueTokenFilter.java |
697 | public class BulkRequestBuilder extends ActionRequestBuilder<BulkRequest, BulkResponse, BulkRequestBuilder> {
public BulkRequestBuilder(Client client) {
super((InternalClient) client, new BulkRequest());
}
/**
* Adds an {@link IndexRequest} to the list of actions to execute. Follows the same behavior of {@link IndexRequest}
* (for example, if no id is provided, one will be generated, or usage of the create flag).
*/
public BulkRequestBuilder add(IndexRequest request) {
super.request.add(request);
return this;
}
/**
* Adds an {@link IndexRequest} to the list of actions to execute. Follows the same behavior of {@link IndexRequest}
* (for example, if no id is provided, one will be generated, or usage of the create flag).
*/
public BulkRequestBuilder add(IndexRequestBuilder request) {
super.request.add(request.request());
return this;
}
/**
* Adds an {@link DeleteRequest} to the list of actions to execute.
*/
public BulkRequestBuilder add(DeleteRequest request) {
super.request.add(request);
return this;
}
/**
* Adds an {@link DeleteRequest} to the list of actions to execute.
*/
public BulkRequestBuilder add(DeleteRequestBuilder request) {
super.request.add(request.request());
return this;
}
/**
* Adds an {@link DeleteRequest} to the list of actions to execute.
*/
public BulkRequestBuilder add(UpdateRequest request) {
super.request.add(request);
return this;
}
/**
* Adds an {@link DeleteRequest} to the list of actions to execute.
*/
public BulkRequestBuilder add(UpdateRequestBuilder request) {
super.request.add(request.request());
return this;
}
/**
* Adds a framed data in binary format
*/
public BulkRequestBuilder add(byte[] data, int from, int length, boolean contentUnsafe) throws Exception {
request.add(data, from, length, contentUnsafe, null, null);
return this;
}
/**
* Adds a framed data in binary format
*/
public BulkRequestBuilder add(byte[] data, int from, int length, boolean contentUnsafe, @Nullable String defaultIndex, @Nullable String defaultType) throws Exception {
request.add(data, from, length, contentUnsafe, defaultIndex, defaultType);
return this;
}
/**
* Set the replication type for this operation.
*/
public BulkRequestBuilder setReplicationType(ReplicationType replicationType) {
request.replicationType(replicationType);
return this;
}
/**
* Sets the consistency level. Defaults to {@link org.elasticsearch.action.WriteConsistencyLevel#DEFAULT}.
*/
public BulkRequestBuilder setConsistencyLevel(WriteConsistencyLevel consistencyLevel) {
request.consistencyLevel(consistencyLevel);
return this;
}
/**
* Should a refresh be executed post this bulk operation causing the operations to
* be searchable. Note, heavy indexing should not set this to <tt>true</tt>. Defaults
* to <tt>false</tt>.
*/
public BulkRequestBuilder setRefresh(boolean refresh) {
request.refresh(refresh);
return this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
public final BulkRequestBuilder setTimeout(TimeValue timeout) {
request.timeout(timeout);
return this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
public final BulkRequestBuilder setTimeout(String timeout) {
request.timeout(timeout);
return this;
}
/**
* The number of actions currently in the bulk.
*/
public int numberOfActions() {
return request.numberOfActions();
}
@Override
protected void doExecute(ActionListener<BulkResponse> listener) {
((Client) client).bulk(request, listener);
}
} | 0true
| src_main_java_org_elasticsearch_action_bulk_BulkRequestBuilder.java |
2,715 | public class LocalAllocateDangledIndices extends AbstractComponent {
private final TransportService transportService;
private final ClusterService clusterService;
private final AllocationService allocationService;
@Inject
public LocalAllocateDangledIndices(Settings settings, TransportService transportService, ClusterService clusterService, AllocationService allocationService) {
super(settings);
this.transportService = transportService;
this.clusterService = clusterService;
this.allocationService = allocationService;
transportService.registerHandler(AllocateDangledRequestHandler.ACTION, new AllocateDangledRequestHandler());
}
public void allocateDangled(IndexMetaData[] indices, final Listener listener) {
ClusterState clusterState = clusterService.state();
DiscoveryNode masterNode = clusterState.nodes().masterNode();
if (masterNode == null) {
listener.onFailure(new MasterNotDiscoveredException("no master to send allocate dangled request"));
return;
}
AllocateDangledRequest request = new AllocateDangledRequest(clusterService.localNode(), indices);
transportService.sendRequest(masterNode, AllocateDangledRequestHandler.ACTION, request, new TransportResponseHandler<AllocateDangledResponse>() {
@Override
public AllocateDangledResponse newInstance() {
return new AllocateDangledResponse();
}
@Override
public void handleResponse(AllocateDangledResponse response) {
listener.onResponse(response);
}
@Override
public void handleException(TransportException exp) {
listener.onFailure(exp);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
});
}
public static interface Listener {
void onResponse(AllocateDangledResponse response);
void onFailure(Throwable e);
}
class AllocateDangledRequestHandler extends BaseTransportRequestHandler<AllocateDangledRequest> {
public static final String ACTION = "/gateway/local/allocate_dangled";
@Override
public AllocateDangledRequest newInstance() {
return new AllocateDangledRequest();
}
@Override
public void messageReceived(final AllocateDangledRequest request, final TransportChannel channel) throws Exception {
String[] indexNames = new String[request.indices.length];
for (int i = 0; i < request.indices.length; i++) {
indexNames[i] = request.indices[i].index();
}
clusterService.submitStateUpdateTask("allocation dangled indices " + Arrays.toString(indexNames), new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (currentState.blocks().disableStatePersistence()) {
return currentState;
}
MetaData.Builder metaData = MetaData.builder(currentState.metaData());
ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
RoutingTable.Builder routingTableBuilder = RoutingTable.builder(currentState.routingTable());
boolean importNeeded = false;
StringBuilder sb = new StringBuilder();
for (IndexMetaData indexMetaData : request.indices) {
if (currentState.metaData().hasIndex(indexMetaData.index())) {
continue;
}
importNeeded = true;
metaData.put(indexMetaData, false);
blocks.addBlocks(indexMetaData);
routingTableBuilder.addAsRecovery(indexMetaData);
sb.append("[").append(indexMetaData.index()).append("/").append(indexMetaData.state()).append("]");
}
if (!importNeeded) {
return currentState;
}
logger.info("auto importing dangled indices {} from [{}]", sb.toString(), request.fromNode);
ClusterState updatedState = ClusterState.builder(currentState).metaData(metaData).blocks(blocks).routingTable(routingTableBuilder).build();
// now, reroute
RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(updatedState).routingTable(routingTableBuilder).build());
return ClusterState.builder(updatedState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
try {
channel.sendResponse(t);
} catch (Exception e) {
logger.error("failed send response for allocating dangled", e);
}
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
try {
channel.sendResponse(new AllocateDangledResponse(true));
} catch (IOException e) {
logger.error("failed send response for allocating dangled", e);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
static class AllocateDangledRequest extends TransportRequest {
DiscoveryNode fromNode;
IndexMetaData[] indices;
AllocateDangledRequest() {
}
AllocateDangledRequest(DiscoveryNode fromNode, IndexMetaData[] indices) {
this.fromNode = fromNode;
this.indices = indices;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
fromNode = DiscoveryNode.readNode(in);
indices = new IndexMetaData[in.readVInt()];
for (int i = 0; i < indices.length; i++) {
indices[i] = IndexMetaData.Builder.readFrom(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
fromNode.writeTo(out);
out.writeVInt(indices.length);
for (IndexMetaData indexMetaData : indices) {
IndexMetaData.Builder.writeTo(indexMetaData, out);
}
}
}
public static class AllocateDangledResponse extends TransportResponse {
private boolean ack;
AllocateDangledResponse() {
}
AllocateDangledResponse(boolean ack) {
this.ack = ack;
}
public boolean ack() {
return ack;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
ack = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(ack);
}
}
} | 0true
| src_main_java_org_elasticsearch_gateway_local_state_meta_LocalAllocateDangledIndices.java |
9 | Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdownHBase(stat);
}
}); | 0true
| titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStorageSetup.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.