Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
1,012 | public class OStringSerializerAnyRuntime implements OStringSerializer {
public static final OStringSerializerAnyRuntime INSTANCE = new OStringSerializerAnyRuntime();
private static final String NAME = "au";
public String getName() {
return NAME;
}
/**
* Re-Create any object if the class has a public constructor that accepts a String as unique parameter.
*/
public Object fromStream(final String iStream) {
if (iStream == null || iStream.length() == 0)
// NULL VALUE
return null;
int pos = iStream.indexOf(OStreamSerializerHelper.SEPARATOR);
if (pos < 0)
OLogManager.instance().error(this, "Class signature not found in ANY element: " + iStream, OSerializationException.class);
final String className = iStream.substring(0, pos);
try {
Class<?> clazz = Class.forName(className);
return clazz.getDeclaredConstructor(String.class).newInstance(iStream.substring(pos + 1));
} catch (Exception e) {
OLogManager.instance().error(this, "Error on unmarshalling content. Class: " + className, e, OSerializationException.class);
}
return null;
}
public StringBuilder toStream(final StringBuilder iOutput, Object iObject) {
if (iObject != null) {
iOutput.append(iObject.getClass().getName());
iOutput.append(OStreamSerializerHelper.SEPARATOR);
iOutput.append(iObject.toString());
}
return iOutput;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_string_OStringSerializerAnyRuntime.java |
1,489 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class HibernateSerializationHookNonAvailableTest {
private static final Field ORIGINAL;
private static final Field TYPE_MAP;
private static final Method GET_SERIALIZATION_SERVICE;
private static final ClassLoader FILTERING_CLASS_LOADER;
static {
try {
List<String> excludes = Arrays.asList(new String[]{"org.hibernate"});
FILTERING_CLASS_LOADER = new FilteringClassLoader(excludes, "com.hazelcast");
String hazelcastInstanceImplClassName = "com.hazelcast.instance.HazelcastInstanceImpl";
Class<?> hazelcastInstanceImplClass = FILTERING_CLASS_LOADER.loadClass(hazelcastInstanceImplClassName);
GET_SERIALIZATION_SERVICE = hazelcastInstanceImplClass.getMethod("getSerializationService");
String hazelcastInstanceProxyClassName = "com.hazelcast.instance.HazelcastInstanceProxy";
Class<?> hazelcastInstanceProxyClass = FILTERING_CLASS_LOADER.loadClass(hazelcastInstanceProxyClassName);
ORIGINAL = hazelcastInstanceProxyClass.getDeclaredField("original");
ORIGINAL.setAccessible(true);
String serializationServiceImplClassName = "com.hazelcast.nio.serialization.SerializationServiceImpl";
Class<?> serializationServiceImplClass = FILTERING_CLASS_LOADER.loadClass(serializationServiceImplClassName);
TYPE_MAP = serializationServiceImplClass.getDeclaredField("typeMap");
TYPE_MAP.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testAutoregistrationOnHibernate3NonAvailable()
throws Exception {
Thread thread = Thread.currentThread();
ClassLoader tccl = thread.getContextClassLoader();
try {
thread.setContextClassLoader(FILTERING_CLASS_LOADER);
Class<?> configClazz = FILTERING_CLASS_LOADER.loadClass("com.hazelcast.config.Config");
Object config = configClazz.newInstance();
Method setClassLoader = configClazz.getDeclaredMethod("setClassLoader", ClassLoader.class);
setClassLoader.invoke(config, FILTERING_CLASS_LOADER);
Class<?> hazelcastClazz = FILTERING_CLASS_LOADER.loadClass("com.hazelcast.core.Hazelcast");
Method newHazelcastInstance = hazelcastClazz.getDeclaredMethod("newHazelcastInstance", configClazz);
Object hz = newHazelcastInstance.invoke(hazelcastClazz, config);
Object impl = ORIGINAL.get(hz);
Object serializationService = GET_SERIALIZATION_SERVICE.invoke(impl);
ConcurrentMap<Class, ?> typeMap = (ConcurrentMap<Class, ?>) TYPE_MAP.get(serializationService);
boolean cacheKeySerializerFound = false;
boolean cacheEntrySerializerFound = false;
for (Class clazz : typeMap.keySet()) {
if (clazz == CacheKey.class) {
cacheKeySerializerFound = true;
} else if (clazz == CacheEntry.class) {
cacheEntrySerializerFound = true;
}
}
assertFalse("CacheKey serializer found", cacheKeySerializerFound);
assertFalse("CacheEntry serializer found", cacheEntrySerializerFound);
} finally {
thread.setContextClassLoader(tccl);
}
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate3_src_test_java_com_hazelcast_hibernate_serialization_HibernateSerializationHookNonAvailableTest.java |
860 | threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
DfsSearchResult dfsResult = entry.value;
DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
}
}
}); | 0true
| src_main_java_org_elasticsearch_action_search_type_TransportSearchDfsQueryAndFetchAction.java |
1,900 | @Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RUNTIME)
@ScopeAnnotation
public @interface Singleton {
} | 0true
| src_main_java_org_elasticsearch_common_inject_Singleton.java |
224 | public class TransactionWriter
{
private final LogBuffer buffer;
private final int identifier;
private final int localId;
public TransactionWriter( LogBuffer buffer, int identifier, int localId )
{
this.buffer = buffer;
this.identifier = identifier;
this.localId = localId;
}
// Transaction coordination
public void start( int masterId, int myId, long latestCommittedTxWhenTxStarted ) throws IOException
{
start( getNewGlobalId( DEFAULT_SEED, localId ), masterId, myId, currentTimeMillis(), latestCommittedTxWhenTxStarted );
}
public void start( byte[] globalId, int masterId, int myId, long startTimestamp,
long latestCommittedTxWhenTxStarted ) throws IOException
{
Xid xid = new XidImpl( globalId, NeoStoreXaDataSource.BRANCH_ID );
LogIoUtils.writeStart( buffer, this.identifier, xid, masterId, myId, startTimestamp, latestCommittedTxWhenTxStarted );
}
public void prepare() throws IOException
{
prepare( System.currentTimeMillis() );
}
public void prepare( long prepareTimestamp ) throws IOException
{
LogIoUtils.writePrepare( buffer, identifier, prepareTimestamp );
}
public void commit( boolean twoPhase, long txId ) throws IOException
{
commit( twoPhase, txId, System.currentTimeMillis() );
}
public void commit( boolean twoPhase, long txId, long commitTimestamp ) throws IOException
{
LogIoUtils.writeCommit( twoPhase, buffer, identifier, txId, commitTimestamp );
}
public void done() throws IOException
{
LogIoUtils.writeDone( buffer, identifier );
}
// Transaction data
public void propertyKey( int id, String key, int... dynamicIds ) throws IOException
{
write( new Command.PropertyKeyTokenCommand( null, withName( new PropertyKeyTokenRecord( id ), dynamicIds, key ) ) );
}
public void label( int id, String name, int... dynamicIds ) throws IOException
{
write( new Command.LabelTokenCommand( null, withName( new LabelTokenRecord( id ), dynamicIds, name ) ) );
}
public void relationshipType( int id, String label, int... dynamicIds ) throws IOException
{
write( new Command.RelationshipTypeTokenCommand( null,
withName( new RelationshipTypeTokenRecord( id ), dynamicIds, label ) ) );
}
public void update( NeoStoreRecord record ) throws IOException
{
write( new Command.NeoStoreCommand( null, record ) );
}
public void create( NodeRecord node ) throws IOException
{
node.setCreated();
update( new NodeRecord( node.getId(), NO_PREV_RELATIONSHIP.intValue(), NO_NEXT_PROPERTY.intValue() ), node );
}
public void update( NodeRecord before, NodeRecord node ) throws IOException
{
node.setInUse( true );
add( before, node );
}
public void delete( NodeRecord node ) throws IOException
{
node.setInUse( false );
add( node, new NodeRecord( node.getId(), NO_PREV_RELATIONSHIP.intValue(), NO_NEXT_PROPERTY.intValue() ) );
}
public void create( RelationshipRecord relationship ) throws IOException
{
relationship.setCreated();
update( relationship );
}
public void createSchema( Collection<DynamicRecord> beforeRecord, Collection<DynamicRecord> afterRecord ) throws IOException
{
for ( DynamicRecord record : afterRecord )
{
record.setCreated();
}
updateSchema( beforeRecord, afterRecord );
}
public void updateSchema(Collection<DynamicRecord> beforeRecords, Collection<DynamicRecord> afterRecords) throws IOException
{
for ( DynamicRecord record : afterRecords )
{
record.setInUse( true );
}
addSchema( beforeRecords, afterRecords );
}
public void update( RelationshipRecord relationship ) throws IOException
{
relationship.setInUse( true );
add( relationship );
}
public void delete( RelationshipRecord relationship ) throws IOException
{
relationship.setInUse( false );
add( relationship );
}
public void create( PropertyRecord property ) throws IOException
{
property.setCreated();
PropertyRecord before = new PropertyRecord( property.getLongId() );
if ( property.isNodeSet() )
before.setNodeId( property.getNodeId() );
if ( property.isRelSet() )
before.setRelId( property.getRelId() );
update( before, property );
}
public void update( PropertyRecord before, PropertyRecord after ) throws IOException
{
after.setInUse(true);
add( before, after );
}
public void delete( PropertyRecord before, PropertyRecord after ) throws IOException
{
after.setInUse(false);
add( before, after );
}
// Internals
private void addSchema( Collection<DynamicRecord> beforeRecords, Collection<DynamicRecord> afterRecords ) throws IOException
{
write( new Command.SchemaRuleCommand( null, null, null, beforeRecords, afterRecords, null, Long.MAX_VALUE ) );
}
public void add( NodeRecord before, NodeRecord after ) throws IOException
{
write( new Command.NodeCommand( null, before, after ) );
}
public void add( RelationshipRecord relationship ) throws IOException
{
write( new Command.RelationshipCommand( null, relationship ) );
}
public void add( PropertyRecord before, PropertyRecord property ) throws IOException
{
write( new Command.PropertyCommand( null, before, property ) );
}
public void add( RelationshipTypeTokenRecord record ) throws IOException
{
write( new Command.RelationshipTypeTokenCommand( null, record ) );
}
public void add( PropertyKeyTokenRecord record ) throws IOException
{
write( new Command.PropertyKeyTokenCommand( null, record ) );
}
public void add( NeoStoreRecord record ) throws IOException
{
write( new Command.NeoStoreCommand( null, record ) );
}
private void write( Command command ) throws IOException
{
LogIoUtils.writeCommand( buffer, identifier, command );
}
private static <T extends TokenRecord> T withName( T record, int[] dynamicIds, String name )
{
if ( dynamicIds == null || dynamicIds.length == 0 )
{
throw new IllegalArgumentException( "No dynamic records for storing the name." );
}
record.setInUse( true );
byte[] data = PropertyStore.encodeString( name );
if ( data.length > dynamicIds.length * NAME_STORE_BLOCK_SIZE )
{
throw new IllegalArgumentException(
String.format( "[%s] is too long to fit in %d blocks", name, dynamicIds.length ) );
}
else if ( data.length <= (dynamicIds.length - 1) * NAME_STORE_BLOCK_SIZE )
{
throw new IllegalArgumentException(
String.format( "[%s] is to short to fill %d blocks", name, dynamicIds.length ) );
}
for ( int i = 0; i < dynamicIds.length; i++ )
{
byte[] part = new byte[Math.min( NAME_STORE_BLOCK_SIZE, data.length - i * NAME_STORE_BLOCK_SIZE )];
System.arraycopy( data, i * NAME_STORE_BLOCK_SIZE, part, 0, part.length );
DynamicRecord dynamicRecord = new DynamicRecord( dynamicIds[i] );
dynamicRecord.setInUse( true );
dynamicRecord.setData( part );
dynamicRecord.setCreated();
record.addNameRecord( dynamicRecord );
}
record.setNameId( dynamicIds[0] );
return record;
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_TransactionWriter.java |
1,787 | public class FieldPathBuilder {
protected DynamicDaoHelper dynamicDaoHelper = new DynamicDaoHelperImpl();
protected CriteriaQuery criteria;
protected List<Predicate> restrictions;
public FieldPath getFieldPath(From root, String fullPropertyName) {
String[] pieces = fullPropertyName.split("\\.");
List<String> associationPath = new ArrayList<String>();
List<String> basicProperties = new ArrayList<String>();
int j = 0;
for (String piece : pieces) {
checkPiece: {
if (j == 0) {
Path path = root.get(piece);
if (path instanceof PluralAttributePath) {
associationPath.add(piece);
break checkPiece;
}
}
basicProperties.add(piece);
}
j++;
}
FieldPath fieldPath = new FieldPath()
.withAssociationPath(associationPath)
.withTargetPropertyPieces(basicProperties);
return fieldPath;
}
public Path getPath(From root, String fullPropertyName, CriteriaBuilder builder) {
return getPath(root, getFieldPath(root, fullPropertyName), builder);
}
@SuppressWarnings({"rawtypes", "unchecked", "serial"})
public Path getPath(From root, FieldPath fieldPath, final CriteriaBuilder builder) {
FieldPath myFieldPath = fieldPath;
if (!StringUtils.isEmpty(fieldPath.getTargetProperty())) {
myFieldPath = getFieldPath(root, fieldPath.getTargetProperty());
}
From myRoot = root;
for (String pathElement : myFieldPath.getAssociationPath()) {
myRoot = myRoot.join(pathElement);
}
Path path = myRoot;
for (int i = 0; i < myFieldPath.getTargetPropertyPieces().size(); i++) {
String piece = myFieldPath.getTargetPropertyPieces().get(i);
if (path.getJavaType().isAnnotationPresent(Embeddable.class)) {
String original = ((SingularAttributePath) path).getAttribute().getDeclaringType().getJavaType().getName() + "." + ((SingularAttributePath) path).getAttribute().getName() + "." + piece;
String copy = path.getJavaType().getName() + "." + piece;
copyCollectionPersister(original, copy, ((CriteriaBuilderImpl) builder).getEntityManagerFactory().getSessionFactory());
}
try {
path = path.get(piece);
} catch (IllegalArgumentException e) {
// We weren't able to resolve the requested piece, likely because it's in a polymoprhic version
// of the path we're currently on. Let's see if there's any polymoprhic version of our class to
// use instead.
EntityManagerFactoryImpl em = ((CriteriaBuilderImpl) builder).getEntityManagerFactory();
Metamodel mm = em.getMetamodel();
boolean found = false;
Class<?>[] polyClasses = dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(
path.getJavaType(), em.getSessionFactory(), true, true);
for (Class<?> clazz : polyClasses) {
ManagedType mt = mm.managedType(clazz);
try {
Attribute attr = mt.getAttribute(piece);
if (attr != null) {
Root additionalRoot = criteria.from(clazz);
restrictions.add(builder.equal(path, additionalRoot));
path = additionalRoot.get(piece);
found = true;
break;
}
} catch (IllegalArgumentException e2) {
// Do nothing - we'll try the next class and see if it has the attribute
}
}
if (!found) {
throw new IllegalArgumentException("Could not resolve requested attribute against path, including" +
" known polymorphic versions of the root", e);
}
}
if (path.getParentPath() != null && path.getParentPath().getJavaType().isAnnotationPresent(Embeddable.class) && path instanceof PluralAttributePath) {
//TODO this code should work, but there still appear to be bugs in Hibernate's JPA criteria handling for lists
//inside Embeddables
Class<?> myClass = ((PluralAttributePath) path).getAttribute().getClass().getInterfaces()[0];
//we don't know which version of "join" to call, so we'll let reflection figure it out
try {
From embeddedJoin = myRoot.join(((SingularAttributePath) path.getParentPath()).getAttribute());
Method join = embeddedJoin.getClass().getMethod("join", myClass);
path = (Path) join.invoke(embeddedJoin, ((PluralAttributePath) path).getAttribute());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return path;
}
/**
* This is a workaround for HHH-6562 (https://hibernate.atlassian.net/browse/HHH-6562)
*/
@SuppressWarnings("unchecked")
private void copyCollectionPersister(String originalKey, String copyKey,
SessionFactoryImpl sessionFactory) {
try {
Field collectionPersistersField = SessionFactoryImpl.class
.getDeclaredField("collectionPersisters");
collectionPersistersField.setAccessible(true);
Map collectionPersisters = (Map) collectionPersistersField.get(sessionFactory);
if (collectionPersisters.containsKey(originalKey)) {
Object collectionPersister = collectionPersisters.get(originalKey);
collectionPersisters.put(copyKey, collectionPersister);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public CriteriaQuery getCriteria() {
return criteria;
}
public void setCriteria(CriteriaQuery criteria) {
this.criteria = criteria;
}
public List<Predicate> getRestrictions() {
return restrictions;
}
public void setRestrictions(List<Predicate> restrictions) {
this.restrictions = restrictions;
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_criteria_FieldPathBuilder.java |
1,330 | public interface OClusterAwareWALRecord {
int getClusterId();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OClusterAwareWALRecord.java |
462 | public class ODatabaseCompare extends ODatabaseImpExpAbstract {
private OStorage storage1;
private OStorage storage2;
private ODatabaseDocumentTx databaseDocumentTxOne;
private ODatabaseDocumentTx databaseDocumentTxTwo;
private boolean compareEntriesForAutomaticIndexes = false;
private boolean autoDetectExportImportMap = true;
private OIndex<OIdentifiable> exportImportHashTable = null;
private int differences = 0;
public ODatabaseCompare(String iDb1URL, String iDb2URL, final OCommandOutputListener iListener) throws IOException {
super(null, null, iListener);
listener.onMessage("\nComparing two local databases:\n1) " + iDb1URL + "\n2) " + iDb2URL + "\n");
storage1 = Orient.instance().loadStorage(iDb1URL);
storage1.open(null, null, null);
storage2 = Orient.instance().loadStorage(iDb2URL);
storage2.open(null, null, null);
}
public ODatabaseCompare(String iDb1URL, String iDb2URL, final String userName, final String userPassword,
final OCommandOutputListener iListener) throws IOException {
super(null, null, iListener);
listener.onMessage("\nComparing two local databases:\n1) " + iDb1URL + "\n2) " + iDb2URL + "\n");
databaseDocumentTxOne = new ODatabaseDocumentTx(iDb1URL);
databaseDocumentTxOne.open(userName, userPassword);
databaseDocumentTxTwo = new ODatabaseDocumentTx(iDb2URL);
databaseDocumentTxTwo.open(userName, userPassword);
storage1 = databaseDocumentTxOne.getStorage();
storage2 = databaseDocumentTxTwo.getStorage();
// exclude automatically generated clusters
excludeClusters.add("orids");
excludeClusters.add(OMetadataDefault.CLUSTER_INDEX_NAME);
excludeClusters.add(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME);
}
public boolean isCompareEntriesForAutomaticIndexes() {
return compareEntriesForAutomaticIndexes;
}
public void setAutoDetectExportImportMap(boolean autoDetectExportImportMap) {
this.autoDetectExportImportMap = autoDetectExportImportMap;
}
public void setCompareEntriesForAutomaticIndexes(boolean compareEntriesForAutomaticIndexes) {
this.compareEntriesForAutomaticIndexes = compareEntriesForAutomaticIndexes;
}
public boolean compare() {
if (isDocumentDatabases() && (databaseDocumentTxOne == null || databaseDocumentTxTwo == null)) {
listener.onMessage("\nPassed in URLs are related to document databases but credentials "
+ "were not provided to open them. Please provide user name + password for databases to compare");
return false;
}
if (!isDocumentDatabases() && (databaseDocumentTxOne != null || databaseDocumentTxTwo != null)) {
listener.onMessage("\nPassed in URLs are not related to document databases but credentials "
+ "were provided to open them. Please do not provide user name + password for databases to compare");
return false;
}
try {
ODocumentHelper.RIDMapper ridMapper = null;
if (autoDetectExportImportMap) {
listener
.onMessage("\nAuto discovery of mapping between RIDs of exported and imported records is switched on, try to discover mapping data on disk.");
exportImportHashTable = (OIndex<OIdentifiable>) databaseDocumentTxTwo.getMetadata().getIndexManager()
.getIndex(ODatabaseImport.EXPORT_IMPORT_MAP_NAME);
if (exportImportHashTable != null) {
listener.onMessage("\nMapping data were found and will be loaded.");
ridMapper = new ODocumentHelper.RIDMapper() {
@Override
public ORID map(ORID rid) {
if (rid == null)
return null;
if (!rid.isPersistent())
return null;
final OIdentifiable result = exportImportHashTable.get(rid);
if (result == null)
return null;
return result.getIdentity();
}
};
} else
listener.onMessage("\nMapping data were not found.");
}
compareClusters();
compareRecords(ridMapper);
if (isDocumentDatabases())
compareIndexes(ridMapper);
if (differences == 0) {
listener.onMessage("\n\nDatabases match.");
return true;
} else {
listener.onMessage("\n\nDatabases do not match. Found " + differences + " difference(s).");
return false;
}
} catch (Exception e) {
e.printStackTrace();
throw new ODatabaseExportException("Error on compare of database '" + storage1.getName() + "' against '" + storage2.getName()
+ "'", e);
} finally {
storage1.close();
storage2.close();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void compareIndexes(ODocumentHelper.RIDMapper ridMapper) {
listener.onMessage("\nStarting index comparison:");
boolean ok = true;
final OIndexManager indexManagerOne = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<OIndexManager>() {
public OIndexManager call() {
return databaseDocumentTxOne.getMetadata().getIndexManager();
}
});
final OIndexManager indexManagerTwo = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<OIndexManager>() {
public OIndexManager call() {
return databaseDocumentTxTwo.getMetadata().getIndexManager();
}
});
final Collection<? extends OIndex<?>> indexesOne = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Collection<? extends OIndex<?>>>() {
public Collection<? extends OIndex<?>> call() {
return indexManagerOne.getIndexes();
}
});
int indexesSizeOne = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Integer>() {
public Integer call() {
return indexesOne.size();
}
});
int indexesSizeTwo = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Integer>() {
public Integer call() {
return indexManagerTwo.getIndexes().size();
}
});
if (exportImportHashTable != null)
indexesSizeTwo--;
if (indexesSizeOne != indexesSizeTwo) {
ok = false;
listener.onMessage("\n- ERR: Amount of indexes are different.");
listener.onMessage("\n--- DB1: " + indexesSizeOne);
listener.onMessage("\n--- DB2: " + indexesSizeTwo);
listener.onMessage("\n");
++differences;
}
final Iterator<? extends OIndex<?>> iteratorOne = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Iterator<? extends OIndex<?>>>() {
public Iterator<? extends OIndex<?>> call() {
return indexesOne.iterator();
}
});
while (makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Boolean>() {
public Boolean call() {
return iteratorOne.hasNext();
}
})) {
final OIndex indexOne = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<OIndex<?>>() {
public OIndex<?> call() {
return iteratorOne.next();
}
});
final OIndex<?> indexTwo = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<OIndex<?>>() {
public OIndex<?> call() {
return indexManagerTwo.getIndex(indexOne.getName());
}
});
if (indexTwo == null) {
ok = false;
listener.onMessage("\n- ERR: Index " + indexOne.getName() + " is absent in DB2.");
++differences;
continue;
}
if (!indexOne.getType().equals(indexTwo.getType())) {
ok = false;
listener.onMessage("\n- ERR: Index types for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOne.getType());
listener.onMessage("\n--- DB2: " + indexTwo.getType());
listener.onMessage("\n");
++differences;
continue;
}
if (!indexOne.getClusters().equals(indexTwo.getClusters())) {
ok = false;
listener.onMessage("\n- ERR: Clusters to index for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOne.getClusters());
listener.onMessage("\n--- DB2: " + indexTwo.getClusters());
listener.onMessage("\n");
++differences;
continue;
}
if (indexOne.getDefinition() == null && indexTwo.getDefinition() != null) {
ok = false;
listener.onMessage("\n- ERR: Index definition for index " + indexOne.getName() + " for DB2 is not null.");
++differences;
continue;
} else if (indexOne.getDefinition() != null && indexTwo.getDefinition() == null) {
ok = false;
listener.onMessage("\n- ERR: Index definition for index " + indexOne.getName() + " for DB2 is null.");
++differences;
continue;
} else if (indexOne.getDefinition() != null && !indexOne.getDefinition().equals(indexTwo.getDefinition())) {
ok = false;
listener.onMessage("\n- ERR: Index definitions for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOne.getDefinition());
listener.onMessage("\n--- DB2: " + indexTwo.getDefinition());
listener.onMessage("\n");
++differences;
continue;
}
final long indexOneSize = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Long>() {
public Long call() {
return indexOne.getSize();
}
});
final long indexTwoSize = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Long>() {
public Long call() {
return indexTwo.getSize();
}
});
if (indexOneSize != indexTwoSize) {
ok = false;
listener.onMessage("\n- ERR: Amount of entries for index " + indexOne.getName() + " are different.");
listener.onMessage("\n--- DB1: " + indexOneSize);
listener.onMessage("\n--- DB2: " + indexTwoSize);
listener.onMessage("\n");
++differences;
}
if (((compareEntriesForAutomaticIndexes && !indexOne.getType().equals("DICTIONARY")) || !indexOne.isAutomatic())) {
final Iterator<Map.Entry<Object, Object>> indexIteratorOne = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Iterator<Map.Entry<Object, Object>>>() {
public Iterator<Map.Entry<Object, Object>> call() {
return indexOne.iterator();
}
});
while (makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Boolean>() {
public Boolean call() {
return indexIteratorOne.hasNext();
}
})) {
final Map.Entry<Object, Object> indexOneEntry = makeDbCall(databaseDocumentTxOne,
new ODbRelatedCall<Map.Entry<Object, Object>>() {
public Map.Entry<Object, Object> call() {
return indexIteratorOne.next();
}
});
final Object key = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Object>() {
public Object call() {
return indexOneEntry.getKey();
}
});
Object indexOneValue = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Object>() {
public Object call() {
return indexOneEntry.getValue();
}
});
final Object indexTwoValue = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Object>() {
public Object call() {
return indexTwo.get(key);
}
});
if (indexTwoValue == null) {
ok = false;
listener.onMessage("\n- ERR: Entry with key " + key + " is absent in index " + indexOne.getName() + " for DB2.");
++differences;
continue;
}
if (indexOneValue instanceof Set && indexTwoValue instanceof Set) {
final Set<Object> indexOneValueSet = (Set<Object>) indexOneValue;
final Set<Object> indexTwoValueSet = (Set<Object>) indexTwoValue;
if (!ODocumentHelper.compareSets(databaseDocumentTxOne, indexOneValueSet, databaseDocumentTxTwo, indexTwoValueSet,
ridMapper)) {
ok = false;
reportIndexDiff(indexOne, key, indexOneValue, indexTwoValue);
}
} else if (indexOneValue instanceof ORID && indexTwoValue instanceof ORID) {
if (ridMapper != null && ((ORID) indexOneValue).isPersistent()) {
OIdentifiable identifiable = ridMapper.map((ORID) indexOneValue);
if (identifiable != null)
indexOneValue = identifiable.getIdentity();
}
if (!indexOneValue.equals(indexTwoValue)) {
ok = false;
reportIndexDiff(indexOne, key, indexOneValue, indexTwoValue);
}
} else if (!indexOneValue.equals(indexTwoValue)) {
ok = false;
reportIndexDiff(indexOne, key, indexOneValue, indexTwoValue);
}
}
}
}
if (ok)
listener.onMessage("OK");
}
private boolean compareClusters() {
listener.onMessage("\nStarting shallow comparison of clusters:");
listener.onMessage("\nChecking the number of clusters...");
if (storage1.getClusterNames().size() != storage1.getClusterNames().size()) {
listener.onMessage("ERR: cluster sizes are different: " + storage1.getClusterNames().size() + " <-> "
+ storage1.getClusterNames().size());
++differences;
}
int cluster2Id;
boolean ok;
for (String clusterName : storage1.getClusterNames()) {
// CHECK IF THE CLUSTER IS INCLUDED
if (includeClusters != null) {
if (!includeClusters.contains(clusterName))
continue;
} else if (excludeClusters != null) {
if (excludeClusters.contains(clusterName))
continue;
}
ok = true;
cluster2Id = storage2.getClusterIdByName(clusterName);
listener.onMessage("\n- Checking cluster " + String.format("%-25s: ", "'" + clusterName + "'"));
if (cluster2Id == -1) {
listener.onMessage("ERR: cluster name " + clusterName + " was not found on database " + storage2);
++differences;
ok = false;
}
if (cluster2Id != storage1.getClusterIdByName(clusterName)) {
listener.onMessage("ERR: cluster id is different for cluster " + clusterName + ": "
+ storage1.getClusterIdByName(clusterName) + " <-> " + cluster2Id);
++differences;
ok = false;
}
if (storage1.count(cluster2Id) != storage2.count(cluster2Id)) {
listener.onMessage("ERR: number of records different in cluster '" + clusterName + "' (id=" + cluster2Id + "): "
+ storage1.count(cluster2Id) + " <-> " + storage2.count(cluster2Id));
++differences;
ok = false;
}
if (ok)
listener.onMessage("OK");
}
listener.onMessage("\n\nShallow analysis done.");
return true;
}
private boolean compareRecords(ODocumentHelper.RIDMapper ridMapper) {
listener.onMessage("\nStarting deep comparison record by record. This may take a few minutes. Wait please...");
int clusterId;
for (String clusterName : storage1.getClusterNames()) {
// CHECK IF THE CLUSTER IS INCLUDED
if (includeClusters != null) {
if (!includeClusters.contains(clusterName))
continue;
} else if (excludeClusters != null) {
if (excludeClusters.contains(clusterName))
continue;
}
clusterId = storage1.getClusterIdByName(clusterName);
OClusterPosition[] db1Range = storage1.getClusterDataRange(clusterId);
OClusterPosition[] db2Range = storage2.getClusterDataRange(clusterId);
final OClusterPosition db1Max = db1Range[1];
final OClusterPosition db2Max = db2Range[1];
final ODocument doc1 = new ODocument();
final ODocument doc2 = new ODocument();
final ORecordId rid = new ORecordId(clusterId);
// TODO why this maximums can be different?
final OClusterPosition clusterMax = db1Max.compareTo(db2Max) > 0 ? db1Max : db2Max;
final OStorage storage;
if (clusterMax.equals(db1Max))
storage = storage1;
else
storage = storage2;
OPhysicalPosition[] physicalPositions = storage.ceilingPhysicalPositions(clusterId, new OPhysicalPosition(
OClusterPositionFactory.INSTANCE.valueOf(0)));
long recordsCounter = 0;
while (physicalPositions.length > 0) {
for (OPhysicalPosition physicalPosition : physicalPositions) {
recordsCounter++;
final OClusterPosition position = physicalPosition.clusterPosition;
rid.clusterPosition = position;
if (isDocumentDatabases() && rid.equals(new ORecordId(storage1.getConfiguration().indexMgrRecordId))
&& rid.equals(new ORecordId(storage2.getConfiguration().indexMgrRecordId)))
continue;
final ORawBuffer buffer1 = storage1.readRecord(rid, null, true, null, false).getResult();
final ORawBuffer buffer2;
if (ridMapper == null)
buffer2 = storage2.readRecord(rid, null, true, null, false).getResult();
else {
final ORID newRid = ridMapper.map(rid);
if (newRid == null)
buffer2 = storage2.readRecord(rid, null, true, null, false).getResult();
else
buffer2 = storage2.readRecord(new ORecordId(newRid), null, true, null, false).getResult();
}
if (buffer1 == null && buffer2 == null)
// BOTH RECORD NULL, OK
continue;
else if (buffer1 == null && buffer2 != null) {
// REC1 NULL
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " is null in DB1");
++differences;
} else if (buffer1 != null && buffer2 == null) {
// REC2 NULL
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " is null in DB2");
++differences;
} else {
if (buffer1.recordType != buffer2.recordType) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " recordType is different: "
+ (char) buffer1.recordType + " <-> " + (char) buffer2.recordType);
++differences;
}
if (buffer1.buffer == null && buffer2.buffer == null) {
} else if (buffer1.buffer == null && buffer2.buffer != null) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content is different: null <-> "
+ buffer2.buffer.length);
++differences;
} else if (buffer1.buffer != null && buffer2.buffer == null) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content is different: " + buffer1.buffer.length
+ " <-> null");
++differences;
} else {
if (buffer1.recordType == ODocument.RECORD_TYPE) {
// DOCUMENT: TRY TO INSTANTIATE AND COMPARE
makeDbCall(databaseDocumentTxOne, new ODocumentHelper.ODbRelatedCall<Object>() {
public Object call() {
doc1.reset();
doc1.fromStream(buffer1.buffer);
return null;
}
});
makeDbCall(databaseDocumentTxTwo, new ODocumentHelper.ODbRelatedCall<Object>() {
public Object call() {
doc2.reset();
doc2.fromStream(buffer2.buffer);
return null;
}
});
if (rid.toString().equals(storage1.getConfiguration().schemaRecordId)
&& rid.toString().equals(storage2.getConfiguration().schemaRecordId)) {
makeDbCall(databaseDocumentTxOne, new ODocumentHelper.ODbRelatedCall<java.lang.Object>() {
public Object call() {
convertSchemaDoc(doc1);
return null;
}
});
makeDbCall(databaseDocumentTxTwo, new ODocumentHelper.ODbRelatedCall<java.lang.Object>() {
public Object call() {
convertSchemaDoc(doc2);
return null;
}
});
}
if (!ODocumentHelper.hasSameContentOf(doc1, databaseDocumentTxOne, doc2, databaseDocumentTxTwo, ridMapper)) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " document content is different");
listener.onMessage("\n--- REC1: " + new String(buffer1.buffer));
listener.onMessage("\n--- REC2: " + new String(buffer2.buffer));
listener.onMessage("\n");
++differences;
}
} else {
if (buffer1.buffer.length != buffer2.buffer.length) {
// CHECK IF THE TRIMMED SIZE IS THE SAME
final String rec1 = new String(buffer1.buffer).trim();
final String rec2 = new String(buffer2.buffer).trim();
if (rec1.length() != rec2.length()) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content length is different: "
+ buffer1.buffer.length + " <-> " + buffer2.buffer.length);
if (buffer1.recordType == ODocument.RECORD_TYPE || buffer1.recordType == ORecordFlat.RECORD_TYPE)
listener.onMessage("\n--- REC1: " + rec1);
if (buffer2.recordType == ODocument.RECORD_TYPE || buffer2.recordType == ORecordFlat.RECORD_TYPE)
listener.onMessage("\n--- REC2: " + rec2);
listener.onMessage("\n");
++differences;
}
} else {
// CHECK BYTE PER BYTE
for (int b = 0; b < buffer1.buffer.length; ++b) {
if (buffer1.buffer[b] != buffer2.buffer[b]) {
listener.onMessage("\n- ERR: RID=" + clusterId + ":" + position + " content is different at byte #" + b
+ ": " + buffer1.buffer[b] + " <-> " + buffer2.buffer[b]);
listener.onMessage("\n--- REC1: " + new String(buffer1.buffer));
listener.onMessage("\n--- REC2: " + new String(buffer2.buffer));
listener.onMessage("\n");
++differences;
break;
}
}
}
}
}
}
}
physicalPositions = storage.higherPhysicalPositions(clusterId, physicalPositions[physicalPositions.length - 1]);
if (recordsCounter % 10000 == 0)
listener.onMessage("\n" + recordsCounter + " records were processed for cluster " + clusterName + " ...");
}
listener.onMessage("\nCluster comparison was finished, " + recordsCounter + " records were processed for cluster "
+ clusterName + " ...");
}
return true;
}
private void convertSchemaDoc(final ODocument document) {
if (document.field("classes") != null) {
document.setFieldType("classes", OType.EMBEDDEDSET);
for (ODocument classDoc : document.<Set<ODocument>> field("classes")) {
classDoc.setFieldType("properties", OType.EMBEDDEDSET);
}
}
}
private boolean isDocumentDatabases() {
return storage1.getConfiguration().schemaRecordId != null && storage2.getConfiguration().schemaRecordId != null;
}
private void reportIndexDiff(OIndex<?> indexOne, Object key, final Object indexOneValue, final Object indexTwoValue) {
listener.onMessage("\n- ERR: Entry values for key '" + key + "' are different for index " + indexOne.getName());
listener.onMessage("\n--- DB1: " + makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<String>() {
public String call() {
return indexOneValue.toString();
}
}));
listener.onMessage("\n--- DB2: " + makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<String>() {
public String call() {
return indexTwoValue.toString();
}
}));
listener.onMessage("\n");
++differences;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java |
1,257 | addOperation(operations, new Runnable() {
public void run() {
IMap map = hazelcast.getMap("myMap");
Iterator it = map.entrySet(new SqlPredicate("name=" + random.nextInt(10000))).iterator();
while (it.hasNext()) {
it.next();
}
}
}, 10); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
1,688 | public interface AdminSecurityContext extends Serializable {
public ContextType getContextType();
public void setContextType(ContextType contextType);
public String getContextKey();
public void setContextKey(String contextKey);
public Set<AdminRole> getAllRoles();
public void setAllRoles(Set<AdminRole> allRoles);
public Set<AdminPermission> getAllPermissions();
public void setAllPermissions(Set<AdminPermission> allPermissions);
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_domain_AdminSecurityContext.java |
465 | public interface StoreManager {
/**
* Returns a transaction handle for a new transaction according to the given configuration.
*
* @return New Transaction Handle
*/
public StoreTransaction beginTransaction(BaseTransactionConfig config) throws BackendException;
/**
* Closes the Storage Manager and all databases that have been opened.
*/
public void close() throws BackendException;
/**
* Deletes and clears all database in this storage manager.
* <p/>
* ATTENTION: Invoking this method will delete ALL your data!!
*/
public void clearStorage() throws BackendException;
/**
* Returns the features supported by this storage manager
*
* @return The supported features of this storage manager
* @see StoreFeatures
*/
public StoreFeatures getFeatures();
/**
* Return an identifier for the StoreManager. Two managers with the same
* name would open databases that read and write the same underlying data;
* two store managers with different names should be, for data read/write
* purposes, completely isolated from each other.
* <p/>
* Examples:
* <ul>
* <li>Cassandra keyspace</li>
* <li>HBase tablename</li>
* <li>InMemoryStore heap address (i.e. default toString()).</li>
* </ul>
*
* @return Name for this StoreManager
*/
public String getName();
/**
* Returns {@code KeyRange}s locally hosted on this machine. The start of
* each {@code KeyRange} is inclusive. The end is exclusive. The start and
* end must each be at least 4 bytes in length.
*
* @return A list of local key ranges
* @throws UnsupportedOperationException
* if the underlying store does not support this operation.
* Check {@link StoreFeatures#hasLocalKeyPartition()} first.
*/
public List<KeyRange> getLocalKeyPartition() throws BackendException;
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_StoreManager.java |
1,469 | public final class HazelcastEntityRegion<Cache extends RegionCache>
extends AbstractTransactionalDataRegion<Cache> implements EntityRegion {
public HazelcastEntityRegion(final HazelcastInstance instance,
final String regionName, final Properties props,
final CacheDataDescription metadata, final Cache cache) {
super(instance, regionName, props, metadata, cache);
}
public EntityRegionAccessStrategy buildAccessStrategy(final AccessType accessType) throws CacheException {
if (null == accessType) {
throw new CacheException(
"Got null AccessType while attempting to determine a proper EntityRegionAccessStrategy. This can't happen!");
}
if (AccessType.READ_ONLY.equals(accessType)) {
return new EntityRegionAccessStrategyAdapter(
new ReadOnlyAccessDelegate<HazelcastEntityRegion>(this, props));
}
if (AccessType.NONSTRICT_READ_WRITE.equals(accessType)) {
return new EntityRegionAccessStrategyAdapter(
new NonStrictReadWriteAccessDelegate<HazelcastEntityRegion>(this, props));
}
if (AccessType.READ_WRITE.equals(accessType)) {
return new EntityRegionAccessStrategyAdapter(
new ReadWriteAccessDelegate<HazelcastEntityRegion>(this, props));
}
if (AccessType.TRANSACTIONAL.equals(accessType)) {
throw new CacheException("Transactional access is not currently supported by Hazelcast.");
}
throw new CacheException("Got unknown AccessType \"" + accessType
+ "\" while attempting to build EntityRegionAccessStrategy.");
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_region_HazelcastEntityRegion.java |
724 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class SetTest extends HazelcastTestSupport {
@Test
public void testSetMethods() throws Exception {
Config config = new Config();
final String name = "defSet";
final int count = 100;
final int insCount = 2;
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(insCount);
final HazelcastInstance[] instances = factory.newInstances(config);
for (int i=0; i<count; i++){
assertTrue(getSet(instances, name).add("item"+i));
}
assertFalse(getSet(instances, name).add("item0"));
Iterator iter = getSet(instances, name).iterator();
int item = 0;
while (iter.hasNext()){
getSet(instances, name).contains(iter.next());
item++;
}
assertEquals(count, item);
assertEquals(count, getSet(instances, name).size());
assertTrue(getSet(instances, name).remove("item99"));
assertFalse(getSet(instances, name).remove("item99"));
List list = new ArrayList();
list.add("item-1");
list.add("item-2");
assertTrue(getSet(instances, name).addAll(list));
assertEquals(count+list.size()-1, getSet(instances, name).size());
assertFalse(getSet(instances, name).addAll(list));
assertEquals(count+list.size()-1, getSet(instances, name).size());
assertTrue(getSet(instances, name).containsAll(list));
list.add("asd");
assertFalse(getSet(instances, name).containsAll(list));
assertTrue(getSet(instances, name).contains("item98"));
assertFalse(getSet(instances, name).contains("item99"));
}
@Test
public void testListener() throws Exception {
Config config = new Config();
final String name = "defSet";
final int count = 10;
final int insCount = 4;
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(insCount);
final HazelcastInstance[] instances = factory.newInstances(config);
final CountDownLatch latchAdd = new CountDownLatch(count);
final CountDownLatch latchRemove = new CountDownLatch(count);
ItemListener listener = new ItemListener() {
public void itemAdded(ItemEvent item) {
latchAdd.countDown();
}
public void itemRemoved(ItemEvent item) {
latchRemove.countDown();
}
};
getSet(instances, name).addItemListener(listener, true);
for (int i = 0; i < count; i++) {
assertTrue(getSet(instances, name).add("item" + i));
}
for (int i = 0; i < count; i++) {
assertTrue(getSet(instances, name).remove("item" + i));
}
assertTrue(latchAdd.await(5, TimeUnit.SECONDS));
assertTrue(latchRemove.await(5, TimeUnit.SECONDS));
}
@Test
public void testMigration(){
final String name = "defSet";
final int insCount = 4;
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(insCount);
HazelcastInstance instance1 = factory.newHazelcastInstance();
ISet set = instance1.getSet(name);
for (int i=0; i<100; i++){
set.add("item" + i);
}
HazelcastInstance instance2 = factory.newHazelcastInstance();
assertEquals(100, instance2.getSet(name).size());
HazelcastInstance instance3 = factory.newHazelcastInstance();
assertEquals(100, instance3.getSet(name).size());
instance1.shutdown();
assertEquals(100, instance3.getSet(name).size());
set = instance2.getSet(name);
for (int i=0; i<100; i++){
set.add("item-" + i);
}
instance2.shutdown();
assertEquals(200, instance3.getSet(name).size());
instance1 = factory.newHazelcastInstance();
assertEquals(200, instance1.getSet(name).size());
instance3.shutdown();
assertEquals(200, instance1.getSet(name).size());
}
@Test
public void testMaxSize(){
Config config = new Config();
final String name = "defSet";
config.addSetConfig(new SetConfig().setName(name).setBackupCount(1).setMaxSize(100));
final int insCount = 2;
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(insCount);
HazelcastInstance instance1 = factory.newHazelcastInstance(config);
HazelcastInstance instance2 = factory.newHazelcastInstance(config);
ISet set = instance1.getSet(name);
for (int i=0; i<100; i++){
assertTrue(set.add("item" + i));
}
assertFalse(set.add("item"));
assertNotNull(set.remove("item0"));
assertTrue(set.add("item"));
}
private ISet getSet(HazelcastInstance[] instances, String name){
final Random rnd = new Random();
return instances[rnd.nextInt(instances.length)].getSet(name);
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_collection_SetTest.java |
255 | service.submitToMembers(callable, selector, new MultiExecutionCallback() {
public void onResponse(Member member, Object value) {
if (value.equals(msg + AppendCallable.APPENDAGE)) {
responseLatch.countDown();
}
}
public void onComplete(Map<Member, Object> values) {
completeLatch.countDown();
}
}); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java |
104 | public class TestRWLock
{
private LockManagerImpl lm;
@Before
public void before() throws Exception
{
lm = new LockManagerImpl( new RagManager() );
}
@Test
public void testSingleThread() throws Exception
{
Transaction tx = mock( Transaction.class );
try
{
lm.getReadLock( null, tx );
fail( "Null parameter should throw exception" );
}
catch ( Exception e )
{
// good
}
try
{
lm.getWriteLock( null, tx );
fail( "Null parameter should throw exception" );
}
catch ( Exception e )
{
// good
}
try
{
lm.releaseReadLock( null, tx );
fail( "Null parameter should throw exception" );
}
catch ( Exception e )
{
// good
}
try
{
lm.releaseWriteLock( null, tx );
fail( "Null parameter should throw exception" );
}
catch ( Exception e )
{
// good
}
Object entity = new Object();
try
{
lm.releaseWriteLock( entity, tx );
fail( "Invalid release should throw exception" );
}
catch ( Exception e )
{
// good
}
try
{
lm.releaseReadLock( entity, tx );
fail( "Invalid release should throw exception" );
}
catch ( Exception e )
{
// good
}
lm.getReadLock( entity, tx );
try
{
lm.releaseWriteLock( entity, tx );
fail( "Invalid release should throw exception" );
}
catch ( Exception e )
{
// good
}
lm.releaseReadLock( entity, tx );
lm.getWriteLock( entity, tx );
try
{
lm.releaseReadLock( entity, tx );
fail( "Invalid release should throw exception" );
}
catch ( Exception e )
{
// good
}
lm.releaseWriteLock( entity, tx );
lm.getReadLock( entity, tx );
lm.getWriteLock( entity, tx );
lm.releaseWriteLock( entity, tx );
lm.releaseReadLock( entity, tx );
lm.getWriteLock( entity, tx );
lm.getReadLock( entity, tx );
lm.releaseReadLock( entity, tx );
lm.releaseWriteLock( entity, tx );
for ( int i = 0; i < 10; i++ )
{
if ( (i % 2) == 0 )
{
lm.getWriteLock( entity, tx );
}
else
{
lm.getReadLock( entity, tx );
}
}
for ( int i = 9; i >= 0; i-- )
{
if ( (i % 2) == 0 )
{
lm.releaseWriteLock( entity , tx );
}
else
{
lm.releaseReadLock( entity, tx );
}
}
}
@Test
public void testMultipleThreads()
{
LockWorker t1 = new LockWorker( "T1", lm );
LockWorker t2 = new LockWorker( "T2", lm );
LockWorker t3 = new LockWorker( "T3", lm );
LockWorker t4 = new LockWorker( "T4", lm );
ResourceObject r1 = newResourceObject( "R1" );
try
{
t1.getReadLock( r1, true );
t2.getReadLock( r1, true );
t3.getReadLock( r1, true );
Future<Void> t4Wait = t4.getWriteLock( r1, false );
t3.releaseReadLock( r1 );
t2.releaseReadLock( r1 );
assertTrue( !t4Wait.isDone() );
t1.releaseReadLock( r1 );
// now we can wait for write lock since it can be acquired
// get write lock
t4.awaitFuture( t4Wait );
t4.getReadLock( r1, true );
t4.getReadLock( r1, true );
// put readlock in queue
Future<Void> t1Wait = t1.getReadLock( r1, false );
t4.getReadLock( r1, true );
t4.releaseReadLock( r1 );
t4.getWriteLock( r1, true );
t4.releaseWriteLock( r1 );
assertTrue( !t1Wait.isDone() );
t4.releaseWriteLock( r1 );
// get read lock
t1.awaitFuture( t1Wait );
t4.releaseReadLock( r1 );
// t4 now has 1 readlock and t1 one readlock
// let t1 drop readlock and t4 get write lock
t4Wait = t4.getWriteLock( r1, false );
t1.releaseReadLock( r1 );
t4.awaitFuture( t4Wait );
t4.releaseReadLock( r1 );
t4.releaseWriteLock( r1 );
t4.getWriteLock( r1, true );
t1Wait = t1.getReadLock( r1, false );
Future<Void> t2Wait = t2.getReadLock( r1, false );
Future<Void> t3Wait = t3.getReadLock( r1, false );
t4.getReadLock( r1, true );
t4.releaseWriteLock( r1 );
t1.awaitFuture( t1Wait );
t2.awaitFuture( t2Wait );
t3.awaitFuture( t3Wait );
t1Wait = t1.getWriteLock( r1, false );
t2.releaseReadLock( r1 );
t4.releaseReadLock( r1 );
t3.releaseReadLock( r1 );
t1.awaitFuture( t1Wait );
t1.releaseWriteLock( r1 );
t2.getReadLock( r1, true );
t1.releaseReadLock( r1 );
t2.getWriteLock( r1, true );
t2.releaseWriteLock( r1 );
t2.releaseReadLock( r1 );
}
catch ( Exception e )
{
File file = new LockWorkFailureDump( getClass() ).dumpState( lm, new LockWorker[] { t1, t2, t3, t4 } );
throw new RuntimeException( "Failed, forensics information dumped to " + file.getAbsolutePath(), e );
}
}
public class StressThread extends Thread
{
private final Random rand = new Random( currentTimeMillis() );
private final Object READ = new Object();
private final Object WRITE = new Object();
private final String name;
private final int numberOfIterations;
private final int depthCount;
private final float readWriteRatio;
private final Object resource;
private final CountDownLatch startSignal;
private final Transaction tx = mock( Transaction.class );
private Exception error;
StressThread( String name, int numberOfIterations, int depthCount,
float readWriteRatio, Object resource, CountDownLatch startSignal )
{
super();
this.name = name;
this.numberOfIterations = numberOfIterations;
this.depthCount = depthCount;
this.readWriteRatio = readWriteRatio;
this.resource = resource;
this.startSignal = startSignal;
}
@Override
public void run()
{
try
{
startSignal.await();
java.util.Stack<Object> lockStack = new java.util.Stack<Object>();
for ( int i = 0; i < numberOfIterations; i++ )
{
try
{
int depth = depthCount;
do
{
float f = rand.nextFloat();
if ( f < readWriteRatio )
{
lm.getReadLock( resource, tx );
lockStack.push( READ );
}
else
{
lm.getWriteLock( resource, tx );
lockStack.push( WRITE );
}
}
while ( --depth > 0 );
while ( !lockStack.isEmpty() )
{
if ( lockStack.pop() == READ )
{
lm.releaseReadLock( resource, tx );
}
else
{
lm.releaseWriteLock( resource , tx );
}
}
}
catch ( DeadlockDetectedException e )
{
}
finally
{
while ( !lockStack.isEmpty() )
{
if ( lockStack.pop() == READ )
{
lm.releaseReadLock( resource, tx );
}
else
{
lm.releaseWriteLock( resource , tx );
}
}
}
}
}
catch ( Exception e )
{
error = e;
}
}
@Override
public String toString()
{
return this.name;
}
}
@Test
public void testStressMultipleThreads() throws Exception
{
ResourceObject r1 = new ResourceObject( "R1" );
StressThread stressThreads[] = new StressThread[100];
CountDownLatch startSignal = new CountDownLatch( 1 );
for ( int i = 0; i < 100; i++ )
{
stressThreads[i] = new StressThread( "Thread" + i, 100, 9, 0.50f, r1, startSignal );
}
for ( int i = 0; i < 100; i++ )
{
stressThreads[i].start();
}
startSignal.countDown();
long end = currentTimeMillis() + SECONDS.toMillis( 20 );
boolean anyAlive = true;
while ( (anyAlive = anyAliveAndAllWell( stressThreads )) && currentTimeMillis() < end )
{
sleepALittle();
}
assertFalse( anyAlive );
for ( StressThread stressThread : stressThreads )
if ( stressThread.error != null )
throw stressThread.error;
}
private void sleepALittle()
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
private boolean anyAliveAndAllWell( StressThread[] stressThreads )
{
for ( StressThread stressThread : stressThreads )
{
if ( stressThread.error != null )
return false;
if ( stressThread.isAlive() )
return true;
}
return false;
}
} | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestRWLock.java |
351 | TRANSPORT_CLIENT {
@Override
public Connection connect(Configuration config) throws IOException {
log.debug("Configuring TransportClient");
ImmutableSettings.Builder settingsBuilder = settingsBuilder(config);
if (config.has(ElasticSearchIndex.CLIENT_SNIFF)) {
String k = "client.transport.sniff";
settingsBuilder.put(k, config.get(ElasticSearchIndex.CLIENT_SNIFF));
log.debug("Set {}: {}", k, config.get(ElasticSearchIndex.CLIENT_SNIFF));
}
TransportClient tc = new TransportClient(settingsBuilder.build());
int defaultPort = config.has(INDEX_PORT) ? config.get(INDEX_PORT) : ElasticSearchIndex.HOST_PORT_DEFAULT;
for (String host : config.get(INDEX_HOSTS)) {
String[] hostparts = host.split(":");
String hostname = hostparts[0];
int hostport = defaultPort;
if (hostparts.length == 2) hostport = Integer.parseInt(hostparts[1]);
log.info("Configured remote host: {} : {}", hostname, hostport);
tc.addTransportAddress(new InetSocketTransportAddress(hostname, hostport));
}
return new Connection(null, tc);
}
}, | 0true
| titan-es_src_main_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchSetup.java |
644 | @Component("blAuthenticationFailureRedirectStrategy")
public class BroadleafAuthenticationFailureRedirectStrategy implements RedirectStrategy {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
if (BroadleafControllerUtility.isAjaxRequest(request)) {
url = updateUrlForAjax(url);
}
redirectStrategy.sendRedirect(request, response, url);
}
public String updateUrlForAjax(String url) {
String blcAjax = BroadleafControllerUtility.BLC_AJAX_PARAMETER;
if (url != null && url.indexOf("?") > 0) {
url = url + "&" + blcAjax + "=true";
} else {
url = url + "?" + blcAjax + "=true";
}
return url;
}
public RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_common_web_security_BroadleafAuthenticationFailureRedirectStrategy.java |
1,578 | public interface ODistributedDatabase {
public ODistributedResponse send(ODistributedRequest iRequest) throws InterruptedException;
void send2Node(ODistributedRequest iRequest, String iTargetNode);
} | 0true
| server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedDatabase.java |
3,342 | public class GeoPointBinaryDVIndexFieldData extends DocValuesIndexFieldData implements IndexGeoPointFieldData<AtomicGeoPointFieldData<ScriptDocValues>> {
public GeoPointBinaryDVIndexFieldData(Index index, Names fieldNames) {
super(index, fieldNames);
}
@Override
public boolean valuesOrdered() {
return false;
}
@Override
public final XFieldComparatorSource comparatorSource(@Nullable Object missingValue, SortMode sortMode) {
throw new ElasticsearchIllegalArgumentException("can't sort on geo_point field without using specific sorting feature, like geo_distance");
}
@Override
public AtomicGeoPointFieldData<ScriptDocValues> load(AtomicReaderContext context) {
try {
return new GeoPointBinaryDVAtomicFieldData(context.reader(), context.reader().getBinaryDocValues(fieldNames.indexName()));
} catch (IOException e) {
throw new ElasticsearchIllegalStateException("Cannot load doc values", e);
}
}
@Override
public AtomicGeoPointFieldData<ScriptDocValues> loadDirect(AtomicReaderContext context) throws Exception {
return load(context);
}
public static class Builder implements IndexFieldData.Builder {
@Override
public IndexFieldData<?> build(Index index, Settings indexSettings, FieldMapper<?> mapper, IndexFieldDataCache cache,
CircuitBreakerService breakerService) {
// Ignore breaker
final FieldMapper.Names fieldNames = mapper.names();
return new GeoPointBinaryDVIndexFieldData(index, fieldNames);
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_GeoPointBinaryDVIndexFieldData.java |
441 | @Deprecated
public @interface AdminPresentationCollectionOverride {
/**
* The name of the property whose AdminPresentation annotation should be overwritten
*
* @return the name of the property that should be overwritten
*/
String name();
/**
* The AdminPresentation to overwrite the property with
*
* @return the AdminPresentation being mapped to the attribute
*/
AdminPresentationCollection value();
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_override_AdminPresentationCollectionOverride.java |
3,639 | public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
Builder builder = geoPointField(name);
parseField(builder, name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue();
if (fieldName.equals("path")) {
builder.multiFieldPathType(parsePathType(name, fieldNode.toString()));
} else if (fieldName.equals("lat_lon")) {
builder.enableLatLon(XContentMapValues.nodeBooleanValue(fieldNode));
} else if (fieldName.equals("geohash")) {
builder.enableGeoHash(XContentMapValues.nodeBooleanValue(fieldNode));
} else if (fieldName.equals("geohash_prefix")) {
builder.geohashPrefix(XContentMapValues.nodeBooleanValue(fieldNode));
if (XContentMapValues.nodeBooleanValue(fieldNode)) {
builder.enableGeoHash(true);
}
} else if (fieldName.equals("precision_step")) {
builder.precisionStep(XContentMapValues.nodeIntegerValue(fieldNode));
} else if (fieldName.equals("geohash_precision")) {
builder.geoHashPrecision(XContentMapValues.nodeIntegerValue(fieldNode));
} else if (fieldName.equals("validate")) {
builder.validateLat = XContentMapValues.nodeBooleanValue(fieldNode);
builder.validateLon = XContentMapValues.nodeBooleanValue(fieldNode);
} else if (fieldName.equals("validate_lon")) {
builder.validateLon = XContentMapValues.nodeBooleanValue(fieldNode);
} else if (fieldName.equals("validate_lat")) {
builder.validateLat = XContentMapValues.nodeBooleanValue(fieldNode);
} else if (fieldName.equals("normalize")) {
builder.normalizeLat = XContentMapValues.nodeBooleanValue(fieldNode);
builder.normalizeLon = XContentMapValues.nodeBooleanValue(fieldNode);
} else if (fieldName.equals("normalize_lat")) {
builder.normalizeLat = XContentMapValues.nodeBooleanValue(fieldNode);
} else if (fieldName.equals("normalize_lon")) {
builder.normalizeLon = XContentMapValues.nodeBooleanValue(fieldNode);
} else {
parseMultiField(builder, name, node, parserContext, fieldName, fieldNode);
}
}
return builder;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_geo_GeoPointFieldMapper.java |
343 | public class BerkeleyElasticsearchTest extends TitanIndexTest {
public BerkeleyElasticsearchTest() {
super(true, true, true);
}
@Override
public WriteConfiguration getConfiguration() {
ModifiableConfiguration config = getBerkeleyJEConfiguration();
//Add index
config.set(INDEX_BACKEND,"elasticsearch",INDEX);
config.set(LOCAL_MODE,true,INDEX);
config.set(CLIENT_ONLY,false,INDEX);
config.set(INDEX_DIRECTORY,StorageSetup.getHomeDir("es"),INDEX);
return config.getConfiguration();
}
@Override
public boolean supportsLuceneStyleQueries() {
return true;
}
/**
* Test {@link com.thinkaurelius.titan.example.GraphOfTheGodsFactory#create(String)}.
*/
@Test
public void testGraphOfTheGodsFactoryCreate() {
String bdbtmp = Joiner.on(File.separator).join("target", "gotgfactory");
TitanGraph gotg = GraphOfTheGodsFactory.create(bdbtmp);
TitanIndexTest.assertGraphOfTheGods(gotg);
gotg.shutdown();
}
} | 0true
| titan-es_src_test_java_com_thinkaurelius_titan_diskstorage_es_BerkeleyElasticsearchTest.java |
1,880 | boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<Object, Object> txMap = context.getMap("default");
assertEquals(0, txMap.values(new SqlPredicate("age <= 10")).size());
txMap.put(2, emp2);
Collection coll = txMap.values(new SqlPredicate("age <= 10"));
Iterator<Object> iterator = coll.iterator();
while (iterator.hasNext()) {
final SampleObjects.Employee e = (SampleObjects.Employee) iterator.next();
assertEquals(emp2, e);
}
coll = txMap.values(new SqlPredicate("age > 30 "));
iterator = coll.iterator();
while (iterator.hasNext()) {
final SampleObjects.Employee e = (SampleObjects.Employee) iterator.next();
assertEquals(emp1, e);
}
txMap.remove(2);
coll = txMap.values(new SqlPredicate("age <= 10 "));
assertEquals(0, coll.size());
return true;
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java |
2,779 | public class IndexNameModule extends AbstractModule {
private final Index index;
public IndexNameModule(Index index) {
this.index = index;
}
@Override
protected void configure() {
bind(Index.class).toInstance(index);
}
} | 0true
| src_main_java_org_elasticsearch_index_IndexNameModule.java |
3,698 | public static class Builder extends AbstractFieldMapper.Builder<Builder, TypeFieldMapper> {
public Builder() {
super(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE));
indexName = Defaults.INDEX_NAME;
}
@Override
public TypeFieldMapper build(BuilderContext context) {
return new TypeFieldMapper(name, indexName, boost, fieldType, postingsProvider, docValuesProvider, fieldDataSettings, context.indexSettings());
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_internal_TypeFieldMapper.java |
411 | }, new TxJob() {
@Override
public void run(IndexTransaction tx) {
tx.add(defStore, defDoc, NAME, nameValue, false);
}
}); | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java |
263 | public interface IProblemChangedListener {
/**
* Called when problems changed. This call is posted in an aynch exec, therefore passed
* resources must not exist.
* @param changedResources A set with elements of type <code>IResource</code> that
* describe the resources that had an problem change.
* @param isMarkerChange If set to <code>true</code>, the change was a marker change, if
* <code>false</code>, the change came from an annotation model modification.
*/
void problemsChanged(IResource[] changedResources, boolean isMarkerChange);
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_IProblemChangedListener.java |
451 | executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
valuesTestValues.add(entry.getValue());
}
}
}, 2, EntryEventType.ADDED, 100, 0.75, map1, map2); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_replicatedmap_ClientReplicatedMapTest.java |
1,028 | transportService.sendRequest(node, transportShardAction, new ShardSingleOperationRequest(request, shardRouting.id()), new BaseTransportResponseHandler<Response>() {
@Override
public Response newInstance() {
return newResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(final Response response) {
listener.onResponse(response);
}
@Override
public void handleException(TransportException exp) {
onFailure(shardRouting, exp);
}
}); | 0true
| src_main_java_org_elasticsearch_action_support_single_shard_TransportShardSingleOperationAction.java |
426 | public enum PopulateToOneFieldsEnum {
TRUE,FALSE,NOT_SPECIFIED
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_PopulateToOneFieldsEnum.java |
249 | service.submitToMembers(runnable, collection, new MultiExecutionCallback() {
public void onResponse(Member member, Object value) {
responseLatch.countDown();
}
public void onComplete(Map<Member, Object> values) {
completeLatch.countDown();
}
}); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java |
1,582 | ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
}; | 0true
| src_test_java_org_elasticsearch_cluster_routing_allocation_decider_DiskThresholdDeciderTests.java |
201 | new IPropertyListener() {
public void propertyChanged(Object source, int propId) {
if (source == CeylonEditor.this && propId == IEditorPart.PROP_INPUT) {
IDocument oldDoc = getParseController().getDocument();
IDocument curDoc = getDocumentProvider().getDocument(getEditorInput());
if (curDoc!=oldDoc) {
// Need to unwatch the old document and watch the new document
if (oldDoc!=null) {
oldDoc.removeDocumentListener(documentListener);
}
curDoc.addDocumentListener(documentListener);
}
initializeParseController();
}
}
}; | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java |
266 | public class CancellationAwareTask implements Callable<Boolean>, Serializable {
long sleepTime;
public CancellationAwareTask(long sleepTime) {
this.sleepTime = sleepTime;
}
public Boolean call() throws InterruptedException {
Thread.sleep(sleepTime);
return Boolean.TRUE;
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_tasks_CancellationAwareTask.java |
5,325 | public class UnmappedTerms extends InternalTerms {
public static final Type TYPE = new Type("terms", "umterms");
private static final Collection<Bucket> BUCKETS = Collections.emptyList();
private static final Map<String, Bucket> BUCKETS_MAP = Collections.emptyMap();
public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public UnmappedTerms readResult(StreamInput in) throws IOException {
UnmappedTerms buckets = new UnmappedTerms();
buckets.readFrom(in);
return buckets;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
UnmappedTerms() {} // for serialization
public UnmappedTerms(String name, InternalOrder order, int requiredSize, long minDocCount) {
super(name, order, requiredSize, minDocCount, BUCKETS);
}
@Override
public Type type() {
return TYPE;
}
@Override
public void readFrom(StreamInput in) throws IOException {
this.name = in.readString();
this.order = InternalOrder.Streams.readOrder(in);
this.requiredSize = readSize(in);
this.minDocCount = in.readVLong();
this.buckets = BUCKETS;
this.bucketMap = BUCKETS_MAP;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
InternalOrder.Streams.writeOrder(order, out);
writeSize(requiredSize, out);
out.writeVLong(minDocCount);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.startArray(CommonFields.BUCKETS).endArray();
builder.endObject();
return builder;
}
} | 1no label
| src_main_java_org_elasticsearch_search_aggregations_bucket_terms_UnmappedTerms.java |
1,664 | private static final class CreateRecordNodeCall extends NodeCall<OPhysicalPosition> {
private String storageName;
private ORecordId recordId;
private byte[] content;
private ORecordVersion recordVersion;
private byte recordType;
public CreateRecordNodeCall() {
recordVersion = OVersionFactory.instance().createVersion();
}
private CreateRecordNodeCall(long nodeId, String memberUUID, String storageName, ORecordId iRecordId, byte[] iContent,
ORecordVersion iRecordVersion, byte iRecordType) {
super(nodeId, memberUUID);
this.storageName = storageName;
this.recordId = iRecordId;
this.content = iContent;
this.recordVersion = iRecordVersion;
this.recordType = iRecordType;
}
@Override
protected OPhysicalPosition call(ODHTNode node) {
return node.createRecord(storageName, recordId, content, recordVersion, recordType);
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeObject(storageName);
out.writeObject(recordId);
writeBytes(out, content);
recordVersion.getSerializer().writeTo(out, recordVersion);
out.writeByte(recordType);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
storageName = (String) in.readObject();
recordId = (ORecordId) in.readObject();
content = readBytes(in);
recordVersion.getSerializer().readFrom(in, recordVersion);
recordType = in.readByte();
}
} | 0true
| distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_oldsharding_hazelcast_OHazelcastDHTNodeProxy.java |
1,397 | public interface OMVRBTreeEntryDataProvider<K, V> {
public ORID getIdentity();
public K getKeyAt(int iIndex);
public V getValueAt(int iIndex);
public ORID getParent();
public ORID getLeft();
public ORID getRight();
public int getSize();
public int getPageSize();
public boolean getColor();
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean setValueAt(int iIndex, V iValue);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean insertAt(int iIndex, K iKey, V iValue);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean removeAt(int iIndex);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean copyDataFrom(OMVRBTreeEntryDataProvider<K, V> iFrom, int iStartPosition);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean truncate(int iNewSize);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean setParent(ORID iRid);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean setLeft(ORID iRid);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean setRight(ORID iRid);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean setColor(final boolean iColor);
/**
* @return <code>true</code> if this entry become dirty with this update.
*/
public boolean copyFrom(OMVRBTreeEntryDataProvider<K, V> iSource);
public boolean isEntryDirty();
public void save();
public void delete();
public void setIdentityChangedListener(final OIdentityChangedListener listener);
public void removeIdentityChangedListener(final OIdentityChangedListener listener);
/** SPEED UP MEMORY CLAIM BY RESETTING INTERNAL FIELDS */
public void clear();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_type_tree_provider_OMVRBTreeEntryDataProvider.java |
1,338 | @Service("blSolrSearchServiceExtensionManager")
public class SolrSearchServiceExtensionManager extends ExtensionManager<SolrSearchServiceExtensionHandler> {
public SolrSearchServiceExtensionManager() {
super(SolrSearchServiceExtensionHandler.class);
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_solr_SolrSearchServiceExtensionManager.java |
434 | public static class ShardStats implements ToXContent, Streamable {
int indices;
int total;
int primaries;
// min/max
int minIndexShards = -1;
int maxIndexShards = -1;
int minIndexPrimaryShards = -1;
int maxIndexPrimaryShards = -1;
double minIndexReplication = -1;
double totalIndexReplication = 0;
double maxIndexReplication = -1;
public ShardStats() {
}
/**
* number of indices in the cluster
*/
public int getIndices() {
return this.indices;
}
/**
* total number of shards in the cluster
*/
public int getTotal() {
return this.total;
}
/**
* total number of primary shards in the cluster
*/
public int getPrimaries() {
return this.primaries;
}
/**
* returns how many *redundant* copies of the data the cluster holds - running with no replicas will return 0
*/
public double getReplication() {
if (primaries == 0) {
return 0;
}
return (((double) (total - primaries)) / primaries);
}
/**
* the maximum number of shards (primary+replicas) an index has
*/
public int getMaxIndexShards() {
return this.maxIndexShards;
}
/**
* the minimum number of shards (primary+replicas) an index has
*/
public int getMinIndexShards() {
return this.minIndexShards;
}
/**
* average number of shards (primary+replicas) across the indices
*/
public double getAvgIndexShards() {
if (this.indices == 0) {
return -1;
}
return ((double) this.total) / this.indices;
}
/**
* the maximum number of primary shards an index has
*/
public int getMaxIndexPrimaryShards() {
return this.maxIndexPrimaryShards;
}
/**
* the minimum number of primary shards an index has
*/
public int getMinIndexPrimaryShards() {
return this.minIndexPrimaryShards;
}
/**
* the average number primary shards across the indices
*/
public double getAvgIndexPrimaryShards() {
if (this.indices == 0) {
return -1;
}
return ((double) this.primaries) / this.indices;
}
/**
* minimum replication factor across the indices. See {@link #getReplication}
*/
public double getMinIndexReplication() {
return this.minIndexReplication;
}
/**
* average replication factor across the indices. See {@link #getReplication}
*/
public double getAvgIndexReplication() {
if (indices == 0) {
return -1;
}
return this.totalIndexReplication / this.indices;
}
/**
* maximum replication factor across the indices. See {@link #getReplication
*/
public double getMaxIndexReplication() {
return this.maxIndexReplication;
}
public void addIndexShardCount(ShardStats indexShardCount) {
this.indices++;
this.primaries += indexShardCount.primaries;
this.total += indexShardCount.total;
this.totalIndexReplication += indexShardCount.getReplication();
if (this.indices == 1) {
// first index, uninitialized.
minIndexPrimaryShards = indexShardCount.primaries;
maxIndexPrimaryShards = indexShardCount.primaries;
minIndexShards = indexShardCount.total;
maxIndexShards = indexShardCount.total;
minIndexReplication = indexShardCount.getReplication();
maxIndexReplication = minIndexReplication;
} else {
minIndexShards = Math.min(minIndexShards, indexShardCount.total);
minIndexPrimaryShards = Math.min(minIndexPrimaryShards, indexShardCount.primaries);
minIndexReplication = Math.min(minIndexReplication, indexShardCount.getReplication());
maxIndexShards = Math.max(maxIndexShards, indexShardCount.total);
maxIndexPrimaryShards = Math.max(maxIndexPrimaryShards, indexShardCount.primaries);
maxIndexReplication = Math.max(maxIndexReplication, indexShardCount.getReplication());
}
}
public static ShardStats readShardStats(StreamInput in) throws IOException {
ShardStats c = new ShardStats();
c.readFrom(in);
return c;
}
@Override
public void readFrom(StreamInput in) throws IOException {
indices = in.readVInt();
total = in.readVInt();
primaries = in.readVInt();
minIndexShards = in.readVInt();
maxIndexShards = in.readVInt();
minIndexPrimaryShards = in.readVInt();
maxIndexPrimaryShards = in.readVInt();
minIndexReplication = in.readDouble();
totalIndexReplication = in.readDouble();
maxIndexReplication = in.readDouble();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(indices);
out.writeVInt(total);
out.writeVInt(primaries);
out.writeVInt(minIndexShards);
out.writeVInt(maxIndexShards);
out.writeVInt(minIndexPrimaryShards);
out.writeVInt(maxIndexPrimaryShards);
out.writeDouble(minIndexReplication);
out.writeDouble(totalIndexReplication);
out.writeDouble(maxIndexReplication);
}
static final class Fields {
static final XContentBuilderString SHARDS = new XContentBuilderString("shards");
static final XContentBuilderString TOTAL = new XContentBuilderString("total");
static final XContentBuilderString PRIMARIES = new XContentBuilderString("primaries");
static final XContentBuilderString REPLICATION = new XContentBuilderString("replication");
static final XContentBuilderString MIN = new XContentBuilderString("min");
static final XContentBuilderString MAX = new XContentBuilderString("max");
static final XContentBuilderString AVG = new XContentBuilderString("avg");
static final XContentBuilderString INDEX = new XContentBuilderString("index");
}
private void addIntMinMax(XContentBuilderString field, int min, int max, double avg, XContentBuilder builder) throws IOException {
builder.startObject(field);
builder.field(Fields.MIN, min);
builder.field(Fields.MAX, max);
builder.field(Fields.AVG, avg);
builder.endObject();
}
private void addDoubleMinMax(XContentBuilderString field, double min, double max, double avg, XContentBuilder builder) throws IOException {
builder.startObject(field);
builder.field(Fields.MIN, min);
builder.field(Fields.MAX, max);
builder.field(Fields.AVG, avg);
builder.endObject();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.SHARDS);
if (indices > 0) {
builder.field(Fields.TOTAL, total);
builder.field(Fields.PRIMARIES, primaries);
builder.field(Fields.REPLICATION, getReplication());
builder.startObject(Fields.INDEX);
addIntMinMax(Fields.SHARDS, minIndexShards, maxIndexShards, getAvgIndexShards(), builder);
addIntMinMax(Fields.PRIMARIES, minIndexPrimaryShards, maxIndexPrimaryShards, getAvgIndexPrimaryShards(), builder);
addDoubleMinMax(Fields.REPLICATION, minIndexReplication, maxIndexReplication, getAvgIndexReplication(), builder);
builder.endObject();
}
builder.endObject();
return builder;
}
@Override
public String toString() {
return "total [" + total + "] primaries [" + primaries + "]";
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsIndices.java |
1,523 | public class OJPAPersistenceUnitInfo implements PersistenceUnitInfo {
/**
* the name of the persistence unit
*/
private final String unitName;
/**
* transaction type of the entity managers created by the EntityManagerFactory
*/
private final PersistenceUnitTransactionType transactionType;
/**
* The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit. The
* scope of the persistence unit is determined by the persistence unit's root.
*/
private final URL unitRootUrl;
/**
* the list of mapping file names that the persistence provider must load to determine the mappings for the entity classes
*/
private final List<String> mappingFileNames = new ArrayList<String>();
/**
* the list of the names of the classes that the persistence provider must add to its set of managed classes
*/
private final List<String> managedClassNames = new ArrayList<String>();
/**
* whether classes in the root of the persistence unit that have not been explicitly listed are to be included in the set of
* managed classes. When set to true then only listed classes and jars will be scanned for persistent classes, otherwise the
* enclosing jar or directory will also be scanned. Not applicable to Java SE persistence units.
*
* @see 'Note' http://static.springsource.org/spring/docs/4.0.x/spring-framework-reference/html/orm.html#orm-jpa-setup-lcemfb The
* exclude-unlisted-classes element always indicates that no scanning for annotated entity classes is supposed to occur, in
* order to support the <exclude-unlisted-classes/> shortcut. This is in line with the JPA specification, which suggests that
* shortcut, but unfortunately is in conflict with the JPA XSD, which implies false for that shortcut. Consequently,
* <exclude-unlisted-classes> false </exclude-unlisted-classes/> is not supported. Simply omit the exclude-unlisted-classes
* element if you want entity class scanning to occur.
*/
private boolean excludeUnlistedClasses = false;
/**
* the second-level cache mode that must be used by the provider for the persistence unit
*
*/
private SharedCacheMode sharedCacheMode = SharedCacheMode.UNSPECIFIED;
/**
* the validation mode to be used by the persistence provider for the persistence unit
*/
private ValidationMode validationMode = ValidationMode.AUTO;
/**
* OrientDB Properties object
*/
private final Properties properties = new OJPAProperties();
/**
* TODO: implement transformer provider-supplied transformer that the container invokes at class-(re)definition time
*/
private final Set<ClassTransformer> classTransformers = new HashSet<ClassTransformer>();
private final List<URL> jarFileUrls = new ArrayList<URL>();
private String providerClassName;
private final JPAVersion xmlSchemaVersion;
/**
* Create a new persistence unit with the given name, transaction type, location and defining bundle
*
* @param unitName
* must not be null
* @param transactionType
* may be null
* @param unitRootUrl
* root of the persistence unit
* @param schemaVersion
* The version of the JPA schema used in persistence.xml
*/
public OJPAPersistenceUnitInfo(String unitName, String transactionType, URL unitRootUrl, String xmlSchemaVersion) {
this.unitName = unitName;
this.unitRootUrl = unitRootUrl;
if (unitName == null || unitName.isEmpty()) {
throw new IllegalStateException("PersistenceUnitName for entity manager should not be null or empty");
}
this.xmlSchemaVersion = JPAVersion.parse(xmlSchemaVersion);
this.transactionType = initTransactionType(transactionType);
}
/**
* @param provider
*/
public void setProviderClassName(String providerClassName) {
this.providerClassName = providerClassName;
}
/**
* @param jtaDataSource
*/
public void setJtaDataSource(String jtaDataSource) {
// TODO: implement
}
/**
* @param nonJtaDataSource
*/
public void setNonJtaDataSource(String nonJtaDataSource) {
// TODO: implement
}
/**
* @param mappingFileName
*/
public void addMappingFileName(String mappingFileName) {
mappingFileNames.add(mappingFileName);
}
/**
* @param jarFileName
*/
public void addJarFileName(String jarFileName) {
jarFileUrls.add(initJarFile(jarFileName));
}
/**
* @param className
*/
public void addClassName(String className) {
managedClassNames.add(className);
}
/**
* @param exclude
*/
public void setExcludeUnlisted(boolean exclude) {
excludeUnlistedClasses = exclude;
}
/**
* @param name
* @param value
*/
public void addProperty(String name, String value) {
properties.setProperty(name, value);
}
/**
* @param sharedCacheMode
*/
public void setSharedCacheMode(String sharedCacheMode) {
this.sharedCacheMode = initSharedCacheMode(sharedCacheMode);
}
/**
* @param validationMode
*/
public void setValidationMode(String validationMode) {
this.validationMode = initValidationMode(validationMode);
}
@Override
public String toString() {
return "PersistenceUnit@" + unitName + " " + super.toString();
}
@Override
public String getPersistenceUnitName() {
return unitName;
}
@Override
public String getPersistenceProviderClassName() {
return providerClassName;
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
@Override
public DataSource getJtaDataSource() {
// TODO Auto-generated method stub
return null;
}
@Override
public DataSource getNonJtaDataSource() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<String> getMappingFileNames() {
return mappingFileNames;
}
@Override
public List<URL> getJarFileUrls() {
return jarFileUrls;
}
@Override
public URL getPersistenceUnitRootUrl() {
return unitRootUrl;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return excludeUnlistedClasses;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return sharedCacheMode;
}
@Override
public ValidationMode getValidationMode() {
return validationMode;
}
@Override
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return xmlSchemaVersion.getVersion();
}
@Override
public ClassLoader getClassLoader() {
return ThreadLocal.class.getClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
classTransformers.add(transformer);
}
@Override
public ClassLoader getNewTempClassLoader() {
// TODO Auto-generated method stub
return null;
}
@Override
public int hashCode() {
return unitName.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return unitName.equals(((OJPAPersistenceUnitInfo) obj).getPersistenceUnitName());
}
// ------------- helpers
/**
* TODO: init default value In a Java EE environment, if this element is not specified, the default is JTA. In a Java SE
* environment, if this element is not specified, a default of RESOURCE_LOCAL may be assumed.
*
* @param elementContent
* @return
*/
public static PersistenceUnitTransactionType initTransactionType(String elementContent) {
if (elementContent == null || elementContent.isEmpty()) {
return null;
}
try {
return PersistenceUnitTransactionType.valueOf(elementContent.toUpperCase());
} catch (IllegalArgumentException ex) {
throw new PersistenceException("Unknown TransactionType: " + elementContent, ex);
}
}
public static ValidationMode initValidationMode(String validationMode) {
if (validationMode == null || validationMode.isEmpty()) {
return ValidationMode.AUTO;
}
try {
return ValidationMode.valueOf(validationMode.toUpperCase());
} catch (IllegalArgumentException ex) {
throw new PersistenceException("Unknown ValidationMode: " + validationMode, ex);
}
}
public static SharedCacheMode initSharedCacheMode(String sharedCacheMode) {
if (sharedCacheMode == null || sharedCacheMode.isEmpty()) {
return SharedCacheMode.UNSPECIFIED;
}
try {
return SharedCacheMode.valueOf(sharedCacheMode.toUpperCase());
} catch (IllegalArgumentException ex) {
throw new PersistenceException("Unknown ValidationMode: " + sharedCacheMode, ex);
}
}
public static URL initJarFile(String jarFileName) {
try {
return new URL("file://" + jarFileName);
} catch (MalformedURLException e) {
throw new PersistenceException("Unknown jar file name: " + jarFileName, e);
}
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_jpa_OJPAPersistenceUnitInfo.java |
596 | public class JoinRequestOperation extends AbstractClusterOperation implements JoinOperation {
private JoinRequest message;
public JoinRequestOperation() {
}
public JoinRequestOperation(JoinRequest message) {
this.message = message;
}
@Override
public void run() {
ClusterServiceImpl cm = getService();
cm.handleJoinRequest(this);
}
public JoinRequest getMessage() {
return message;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
message = new JoinRequest();
message.readData(in);
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
message.writeData(out);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("JoinRequestOperation");
sb.append("{message=").append(message);
sb.append('}');
return sb.toString();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_cluster_JoinRequestOperation.java |
1,799 | assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertEquals(expectedLocal, localCount.get());
assertEquals(expectedGlobal, globalCount.get());
assertEquals(expectedValue, valueCount.get());
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_map_ListenerTest.java |
262 | class GotoPreviousTargetAction extends TargetNavigationAction {
public GotoPreviousTargetAction() {
this(null);
}
public GotoPreviousTargetAction(CeylonEditor editor) {
super(editor, "Go to Previous Navigation Target", GOTO_PREVIOUS_TARGET);
}
@Override
protected Object getNavTarget(Object o, Object astRoot) {
return null;
//return fNavTargetFinder.getPreviousTarget(o, astRoot);
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_GotoPreviousTargetAction.java |
518 | MessageListener listener = new MessageListener() {
public void onMessage(Message message) {
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_topic_ClientTopicTest.java |
1,334 | Future future = executorService.submit(new Callable<String>() {
@Override
public String call() {
try {
latch1.await(30, TimeUnit.SECONDS);
return "success";
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java |
2,667 | public class DefaultPortableReader implements PortableReader {
protected final ClassDefinition cd;
private final PortableSerializer serializer;
private final BufferObjectDataInput in;
private final int finalPosition;
private final int offset;
private boolean raw;
public DefaultPortableReader(PortableSerializer serializer, BufferObjectDataInput in, ClassDefinition cd) {
this.in = in;
this.serializer = serializer;
this.cd = cd;
try {
// final position after portable is read
finalPosition = in.readInt();
} catch (IOException e) {
throw new HazelcastSerializationException(e);
}
this.offset = in.position();
}
public int getVersion() {
return cd.getVersion();
}
public boolean hasField(String fieldName) {
return cd.hasField(fieldName);
}
public Set<String> getFieldNames() {
return cd.getFieldNames();
}
public FieldType getFieldType(String fieldName) {
return cd.getFieldType(fieldName);
}
public int getFieldClassId(String fieldName) {
return cd.getFieldClassId(fieldName);
}
public int readInt(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readInt(pos);
}
public long readLong(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readLong(pos);
}
public String readUTF(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return in.readUTF();
} finally {
in.position(currentPos);
}
}
public boolean readBoolean(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readBoolean(pos);
}
public byte readByte(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readByte(pos);
}
public char readChar(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readChar(pos);
}
public double readDouble(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readDouble(pos);
}
public float readFloat(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readFloat(pos);
}
public short readShort(String fieldName) throws IOException {
int pos = getPosition(fieldName);
return in.readShort(pos);
}
public byte[] readByteArray(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return IOUtil.readByteArray(in);
} finally {
in.position(currentPos);
}
}
public char[] readCharArray(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return in.readCharArray();
} finally {
in.position(currentPos);
}
}
public int[] readIntArray(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return in.readIntArray();
} finally {
in.position(currentPos);
}
}
public long[] readLongArray(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return in.readLongArray();
} finally {
in.position(currentPos);
}
}
public double[] readDoubleArray(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return in.readDoubleArray();
} finally {
in.position(currentPos);
}
}
public float[] readFloatArray(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return in.readFloatArray();
} finally {
in.position(currentPos);
}
}
public short[] readShortArray(String fieldName) throws IOException {
final int currentPos = in.position();
try {
int pos = getPosition(fieldName);
in.position(pos);
return in.readShortArray();
} finally {
in.position(currentPos);
}
}
public Portable readPortable(String fieldName) throws IOException {
FieldDefinition fd = cd.get(fieldName);
if (fd == null) {
throw throwUnknownFieldException(fieldName);
}
final int currentPos = in.position();
try {
int pos = getPosition(fd);
in.position(pos);
final boolean NULL = in.readBoolean();
if (!NULL) {
final PortableContextAwareInputStream ctxIn = (PortableContextAwareInputStream) in;
try {
ctxIn.setFactoryId(fd.getFactoryId());
ctxIn.setClassId(fd.getClassId());
return serializer.readAndInitialize(in);
} finally {
ctxIn.setFactoryId(cd.getFactoryId());
ctxIn.setClassId(cd.getClassId());
}
}
return null;
} finally {
in.position(currentPos);
}
}
private HazelcastSerializationException throwUnknownFieldException(String fieldName) {
return new HazelcastSerializationException("Unknown field name: '" + fieldName
+ "' for ClassDefinition {id: " + cd.getClassId() + ", version: " + cd.getVersion() + "}");
}
public Portable[] readPortableArray(String fieldName) throws IOException {
FieldDefinition fd = cd.get(fieldName);
if (fd == null) {
throw throwUnknownFieldException(fieldName);
}
final int currentPos = in.position();
try {
int pos = getPosition(fd);
in.position(pos);
final int len = in.readInt();
final Portable[] portables = new Portable[len];
if (len > 0) {
final int offset = in.position();
final PortableContextAwareInputStream ctxIn = (PortableContextAwareInputStream) in;
try {
ctxIn.setFactoryId(fd.getFactoryId());
ctxIn.setClassId(fd.getClassId());
for (int i = 0; i < len; i++) {
final int start = in.readInt(offset + i * 4);
in.position(start);
portables[i] = serializer.readAndInitialize(in);
}
} finally {
ctxIn.setFactoryId(cd.getFactoryId());
ctxIn.setClassId(cd.getClassId());
}
}
return portables;
} finally {
in.position(currentPos);
}
}
protected int getPosition(String fieldName) throws IOException {
if (raw) {
throw new HazelcastSerializationException("Cannot read Portable fields after getRawDataInput() is called!");
}
FieldDefinition fd = cd.get(fieldName);
if (fd == null) {
throw throwUnknownFieldException(fieldName);
}
return getPosition(fd);
}
protected int getPosition(FieldDefinition fd) throws IOException {
return in.readInt(offset + fd.getIndex() * 4);
}
public ObjectDataInput getRawDataInput() throws IOException {
if (!raw) {
int pos = in.readInt(offset + cd.getFieldCount() * 4);
in.position(pos);
}
raw = true;
return in;
}
void end() throws IOException {
in.position(finalPosition);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_nio_serialization_DefaultPortableReader.java |
763 | public class ListSetBackupOperation extends CollectionOperation implements BackupOperation {
private long oldItemId;
private long itemId;
private Data value;
public ListSetBackupOperation() {
}
public ListSetBackupOperation(String name, long oldItemId, long itemId, Data value) {
super(name);
this.oldItemId = oldItemId;
this.itemId = itemId;
this.value = value;
}
@Override
public int getId() {
return CollectionDataSerializerHook.LIST_SET_BACKUP;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
getOrCreateListContainer().setBackup(oldItemId, itemId, value);
}
@Override
public void afterRun() throws Exception {
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(oldItemId);
out.writeLong(itemId);
value.writeData(out);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
oldItemId = in.readLong();
itemId = in.readLong();
value = new Data();
value.readData(in);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_list_ListSetBackupOperation.java |
13 | final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1,new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
r.run();
}
}); | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java |
2,929 | public class ReverseTokenFilterFactory extends AbstractTokenFilterFactory {
@Inject
public ReverseTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new ReverseStringFilter(version, tokenStream);
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_ReverseTokenFilterFactory.java |
1,188 | public interface Member extends DataSerializable, Endpoint {
/**
* Returns if this member is the local member.
*
* @return <tt>true<tt> if this member is the
* local member, <tt>false</tt> otherwise.
*/
boolean localMember();
/**
* Returns the InetSocketAddress of this member.
*
* @return InetSocketAddress of this member
*
* @deprecated use {@link #getSocketAddress()} instead
*/
@Deprecated
InetSocketAddress getInetSocketAddress();
/**
* Returns the socket address of this member.
*
* @return socket address of this member
*/
InetSocketAddress getSocketAddress();
/**
* Returns UUID of this member.
*
* @return UUID of this member.
*/
String getUuid();
/**
* Returns configured attributes for this member.<br/>
* <b>This method might not be available on all native clients.</b>
*
* @return Attributes for this member.
* @since 3.2
*/
Map<String, Object> getAttributes();
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
String getStringAttribute(String key);
/**
* Defines a key-value pair string attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setStringAttribute(String key, String value);
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
Boolean getBooleanAttribute(String key);
/**
* Defines a key-value pair boolean attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setBooleanAttribute(String key, boolean value);
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
Byte getByteAttribute(String key);
/**
* Defines a key-value pair byte attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setByteAttribute(String key, byte value);
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
Short getShortAttribute(String key);
/**
* Defines a key-value pair short attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setShortAttribute(String key, short value);
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
Integer getIntAttribute(String key);
/**
* Defines a key-value pair int attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setIntAttribute(String key, int value);
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
Long getLongAttribute(String key);
/**
* Defines a key-value pair long attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setLongAttribute(String key, long value);
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
Float getFloatAttribute(String key);
/**
* Defines a key-value pair float attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setFloatAttribute(String key, float value);
/**
* Returns the value of the specified key for this member or
* null if value is undefined.
*
* @param key The key to lookup.
* @return The value for this members key.
* @since 3.2
*/
Double getDoubleAttribute(String key);
/**
* Defines a key-value pair double attribute for this member available
* to other cluster members.
*
* @param key The key for this property.
* @param value The value corresponds to this attribute and this member.
* @since 3.2
*/
void setDoubleAttribute(String key, double value);
/**
* Removes a key-value pair attribute for this member if given key was
* previously assigned as an attribute.<br/>
* If key wasn't assigned to a value this method does nothing.
*
* @param key The key to be deleted from the member attributes
* @since 3.2
*/
void removeAttribute(String key);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_Member.java |
696 | constructors[LIST_SET] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListSetRequest();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java |
3,004 | public interface IdReaderCache {
IdReaderTypeCache type(String type);
HashedBytesArray parentIdByDoc(String type, int docId);
int docById(String type, HashedBytesArray id);
long sizeInBytes();
} | 0true
| src_main_java_org_elasticsearch_index_cache_id_IdReaderCache.java |
3,839 | public class GeoBoundingBoxFilterParser implements FilterParser {
public static final String TOP = "top";
public static final String LEFT = "left";
public static final String RIGHT = "right";
public static final String BOTTOM = "bottom";
public static final String TOP_LEFT = TOP + "_" + LEFT;
public static final String TOP_RIGHT = TOP + "_" + RIGHT;
public static final String BOTTOM_LEFT = BOTTOM + "_" + LEFT;
public static final String BOTTOM_RIGHT = BOTTOM + "_" + RIGHT;
public static final String TOPLEFT = "topLeft";
public static final String TOPRIGHT = "topRight";
public static final String BOTTOMLEFT = "bottomLeft";
public static final String BOTTOMRIGHT = "bottomRight";
public static final String NAME = "geo_bbox";
public static final String FIELD = "field";
@Inject
public GeoBoundingBoxFilterParser() {
}
@Override
public String[] names() {
return new String[]{NAME, "geoBbox", "geo_bounding_box", "geoBoundingBox"};
}
@Override
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
boolean cache = false;
CacheKeyFilter.Key cacheKey = null;
String fieldName = null;
double top = Double.NaN;
double bottom = Double.NaN;
double left = Double.NaN;
double right = Double.NaN;
String filterName = null;
String currentFieldName = null;
XContentParser.Token token;
boolean normalize = true;
GeoPoint sparse = new GeoPoint();
String type = "memory";
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
token = parser.nextToken();
if (FIELD.equals(currentFieldName)) {
fieldName = parser.text();
} else if (TOP.equals(currentFieldName)) {
top = parser.doubleValue();
} else if (BOTTOM.equals(currentFieldName)) {
bottom = parser.doubleValue();
} else if (LEFT.equals(currentFieldName)) {
left = parser.doubleValue();
} else if (RIGHT.equals(currentFieldName)) {
right = parser.doubleValue();
} else {
if (TOP_LEFT.equals(currentFieldName) || TOPLEFT.equals(currentFieldName)) {
GeoPoint.parse(parser, sparse);
top = sparse.getLat();
left = sparse.getLon();
} else if (BOTTOM_RIGHT.equals(currentFieldName) || BOTTOMRIGHT.equals(currentFieldName)) {
GeoPoint.parse(parser, sparse);
bottom = sparse.getLat();
right = sparse.getLon();
} else if (TOP_RIGHT.equals(currentFieldName) || TOPRIGHT.equals(currentFieldName)) {
GeoPoint.parse(parser, sparse);
top = sparse.getLat();
right = sparse.getLon();
} else if (BOTTOM_LEFT.equals(currentFieldName) || BOTTOMLEFT.equals(currentFieldName)) {
GeoPoint.parse(parser, sparse);
bottom = sparse.getLat();
left = sparse.getLon();
} else {
throw new ElasticsearchParseException("Unexpected field [" + currentFieldName + "]");
}
}
} else {
throw new ElasticsearchParseException("fieldname expected but [" + token + "] found");
}
}
} else if (token.isValue()) {
if ("_name".equals(currentFieldName)) {
filterName = parser.text();
} else if ("_cache".equals(currentFieldName)) {
cache = parser.booleanValue();
} else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
cacheKey = new CacheKeyFilter.Key(parser.text());
} else if ("normalize".equals(currentFieldName)) {
normalize = parser.booleanValue();
} else if ("type".equals(currentFieldName)) {
type = parser.text();
} else {
throw new QueryParsingException(parseContext.index(), "[geo_bbox] filter does not support [" + currentFieldName + "]");
}
}
}
final GeoPoint topLeft = sparse.reset(top, left); //just keep the object
final GeoPoint bottomRight = new GeoPoint(bottom, right);
if (normalize) {
GeoUtils.normalizePoint(topLeft);
GeoUtils.normalizePoint(bottomRight);
}
MapperService.SmartNameFieldMappers smartMappers = parseContext.smartFieldMappers(fieldName);
if (smartMappers == null || !smartMappers.hasMapper()) {
throw new QueryParsingException(parseContext.index(), "failed to find geo_point field [" + fieldName + "]");
}
FieldMapper<?> mapper = smartMappers.mapper();
if (!(mapper instanceof GeoPointFieldMapper)) {
throw new QueryParsingException(parseContext.index(), "field [" + fieldName + "] is not a geo_point field");
}
GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper) mapper);
Filter filter;
if ("indexed".equals(type)) {
filter = IndexedGeoBoundingBoxFilter.create(topLeft, bottomRight, geoMapper);
} else if ("memory".equals(type)) {
IndexGeoPointFieldData<?> indexFieldData = parseContext.fieldData().getForField(mapper);
filter = new InMemoryGeoBoundingBoxFilter(topLeft, bottomRight, indexFieldData);
} else {
throw new QueryParsingException(parseContext.index(), "geo bounding box type [" + type + "] not supported, either 'indexed' or 'memory' are allowed");
}
if (cache) {
filter = parseContext.cacheFilter(filter, cacheKey);
}
filter = wrapSmartNameFilter(filter, smartMappers, parseContext);
if (filterName != null) {
parseContext.addNamedFilter(filterName, filter);
}
return filter;
}
} | 1no label
| src_main_java_org_elasticsearch_index_query_GeoBoundingBoxFilterParser.java |
625 | h3.getLifecycleService().addLifecycleListener(new LifecycleListener() {
public void stateChanged(LifecycleEvent event) {
if (event.getState() == LifecycleState.MERGED) {
latch.countDown();
}
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_cluster_SplitBrainHandlerTest.java |
1,045 | @Entity
@Table(name = "BLC_ITEM_OFFER_QUALIFIER")
@Inheritance(strategy=InheritanceType.JOINED)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
public class OrderItemQualifierImpl implements OrderItemQualifier {
public static final Log LOG = LogFactory.getLog(OrderItemQualifierImpl.class);
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "OrderItemQualifierId")
@GenericGenerator(
name = "OrderItemQualifierId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name = "segment_value", value = "OrderItemQualifierImpl"),
@Parameter(name = "entity_name", value = "org.broadleafcommerce.core.order.domain.OrderItemQualifierImpl")
}
)
@Column(name = "ITEM_OFFER_QUALIFIER_ID")
protected Long id;
@ManyToOne(targetEntity = OrderItemImpl.class)
@JoinColumn(name = "ORDER_ITEM_ID")
protected OrderItem orderItem;
@ManyToOne(targetEntity = OfferImpl.class, optional=false)
@JoinColumn(name = "OFFER_ID")
protected Offer offer;
@Column(name = "QUANTITY")
protected Long quantity;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public OrderItem getOrderItem() {
return orderItem;
}
@Override
public void setOrderItem(OrderItem orderItem) {
this.orderItem = orderItem;
}
@Override
public void setOffer(Offer offer) {
this.offer = offer;
}
@Override
public Offer getOffer() {
return offer;
}
@Override
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
@Override
public Long getQuantity() {
return quantity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((offer == null) ? 0 : offer.hashCode());
result = prime * result + ((orderItem == null) ? 0 : orderItem.hashCode());
result = prime * result + ((quantity == null) ? 0 : quantity.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;
OrderItemQualifierImpl other = (OrderItemQualifierImpl) obj;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
if (offer == null) {
if (other.offer != null) return false;
} else if (!offer.equals(other.offer)) return false;
if (orderItem == null) {
if (other.orderItem != null) return false;
} else if (!orderItem.equals(other.orderItem)) return false;
if (quantity == null) {
if (other.quantity != null) return false;
} else if (!quantity.equals(other.quantity)) return false;
return true;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderItemQualifierImpl.java |
1,555 | @XmlRootElement(name = "command")
@XmlType(propOrder = { "parameters", "implementation", "pattern" })
public class OServerCommandConfiguration {
@XmlAttribute(required = true)
public String pattern;
@XmlAttribute(required = true)
public String implementation;
@XmlAttribute(required = false)
public boolean stateful;
@XmlElementWrapper(required = false)
@XmlElementRef(type = OServerEntryConfiguration.class)
public OServerEntryConfiguration[] parameters;
} | 0true
| server_src_main_java_com_orientechnologies_orient_server_config_OServerCommandConfiguration.java |
336 | new Thread() {
public void run() {
try {
if (!tempMap.tryLock("key1", 2, TimeUnit.SECONDS)) {
latch.countDown();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start(); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java |
1,237 | addOperation(operations, new Runnable() {
public void run() {
IMap map = hazelcast.getMap("myMap");
map.getEntryView(random.nextInt(SIZE));
}
}, 2); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
2,918 | public class PortugueseAnalyzerProvider extends AbstractIndexAnalyzerProvider<PortugueseAnalyzer> {
private final PortugueseAnalyzer analyzer;
@Inject
public PortugueseAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
analyzer = new PortugueseAnalyzer(version,
Analysis.parseStopWords(env, settings, PortugueseAnalyzer.getDefaultStopSet(), version),
Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET, version));
}
@Override
public PortugueseAnalyzer get() {
return this.analyzer;
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_PortugueseAnalyzerProvider.java |
697 | class LRUList implements Iterable<OCacheEntry> {
private static final int SEED = 362498820;
private LRUEntry head;
private LRUEntry tail;
private int nextThreshold;
private int size;
private LRUEntry entries[];
public LRUList() {
entries = new LRUEntry[1024];
nextThreshold = (int) (entries.length * 0.75);
}
public OCacheEntry get(long fileId, long pageIndex) {
long hashCode = hashCode(fileId, pageIndex);
int index = index(hashCode);
LRUEntry lruEntry = entries[index];
while (lruEntry != null
&& (lruEntry.hashCode != hashCode || lruEntry.cacheEntry.pageIndex != pageIndex || lruEntry.cacheEntry.fileId != fileId))
lruEntry = lruEntry.next;
if (lruEntry == null)
return null;
return lruEntry.cacheEntry;
}
public OCacheEntry remove(long fileId, long pageIndex) {
long hashCode = hashCode(fileId, pageIndex);
int index = index(hashCode);
LRUEntry lruEntry = entries[index];
LRUEntry prevEntry = null;
while (lruEntry != null
&& (lruEntry.hashCode != hashCode || lruEntry.cacheEntry.fileId != fileId || lruEntry.cacheEntry.pageIndex != pageIndex)) {
prevEntry = lruEntry;
lruEntry = lruEntry.next;
}
if (lruEntry == null)
return null;
assert tail == null || tail.before != tail;
assert tail == null || tail.after == null;
removeFromLRUList(lruEntry);
if (prevEntry == null)
entries[index] = lruEntry.next;
else
prevEntry.next = lruEntry.next;
assert tail == null || tail.before != tail;
assert tail == null || tail.after == null;
size--;
return lruEntry.cacheEntry;
}
private void removeFromLRUList(LRUEntry lruEntry) {
LRUEntry before = lruEntry.before;
LRUEntry after = lruEntry.after;
if (before != null)
before.after = after;
if (after != null)
after.before = before;
if (lruEntry == head)
head = lruEntry.after;
if (lruEntry == tail)
tail = lruEntry.before;
}
public void putToMRU(OCacheEntry cacheEntry) {
final long fileId = cacheEntry.fileId;
final long pageIndex = cacheEntry.pageIndex;
long hashCode = hashCode(cacheEntry.fileId, cacheEntry.pageIndex);
int index = index(hashCode);
LRUEntry lruEntry = entries[index];
LRUEntry prevEntry = null;
while (lruEntry != null
&& (lruEntry.hashCode != hashCode || lruEntry.cacheEntry.fileId != fileId || lruEntry.cacheEntry.pageIndex != pageIndex)) {
prevEntry = lruEntry;
lruEntry = lruEntry.next;
}
assert tail == null || tail.before != tail;
assert tail == null || tail.after == null;
if (lruEntry == null) {
lruEntry = new LRUEntry();
lruEntry.hashCode = hashCode;
if (prevEntry == null)
entries[index] = lruEntry;
else
prevEntry.next = lruEntry;
size++;
}
lruEntry.cacheEntry = cacheEntry;
removeFromLRUList(lruEntry);
if (head == null) {
head = lruEntry;
tail = lruEntry;
lruEntry.before = null;
lruEntry.after = null;
} else {
tail.after = lruEntry;
lruEntry.before = tail;
lruEntry.after = null;
tail = lruEntry;
}
assert tail.before != tail;
assert tail.after == null;
if (size >= nextThreshold)
rehash();
}
public void clear() {
entries = new LRUEntry[1024];
nextThreshold = (int) (entries.length * 0.75);
head = tail = null;
size = 0;
}
private void rehash() {
long len = entries.length << 1;
if (len >= Integer.MAX_VALUE) {
if (entries.length < Integer.MAX_VALUE)
len = Integer.MAX_VALUE;
else
return;
}
LRUEntry[] oldLruEntries = entries;
entries = new LRUEntry[(int) len];
for (LRUEntry oldLruEntry : oldLruEntries) {
LRUEntry currentLRUEntry = oldLruEntry;
while (currentLRUEntry != null) {
int index = index(currentLRUEntry.hashCode);
LRUEntry nexEntry = currentLRUEntry.next;
appendEntry(index, currentLRUEntry);
currentLRUEntry = nexEntry;
}
}
nextThreshold = (int) (entries.length * 0.75);
}
private void appendEntry(int index, LRUEntry entry) {
LRUEntry lruEntry = entries[index];
if (lruEntry == null)
entries[index] = entry;
else {
while (lruEntry.next != null)
lruEntry = lruEntry.next;
lruEntry.next = entry;
}
entry.next = null;
}
public boolean contains(long fileId, long filePosition) {
return get(fileId, filePosition) != null;
}
public int size() {
return size;
}
public OCacheEntry removeLRU() {
LRUEntry entryToRemove = head;
while (entryToRemove != null && (entryToRemove.cacheEntry.dataPointer != null && entryToRemove.cacheEntry.usagesCount != 0)) {
entryToRemove = entryToRemove.after;
}
if (entryToRemove != null) {
return remove(entryToRemove.cacheEntry.fileId, entryToRemove.cacheEntry.pageIndex);
} else {
return null;
}
}
public OCacheEntry getLRU() {
return head.cacheEntry;
}
@Override
public Iterator<OCacheEntry> iterator() {
return new MRUEntryIterator();
}
private int index(long hashCode) {
return (int) ((entries.length - 1) & hashCode);
}
private long hashCode(long fileId, long filePosition) {
final byte[] result = new byte[2 * OLongSerializer.LONG_SIZE];
OLongSerializer.INSTANCE.serialize(fileId, result, OLongSerializer.LONG_SIZE);
OLongSerializer.INSTANCE.serialize(filePosition, result, OLongSerializer.LONG_SIZE);
return OMurmurHash3.murmurHash3_x64_64(result, SEED);
}
private final class MRUEntryIterator implements Iterator<OCacheEntry> {
private LRUEntry current = tail;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public OCacheEntry next() {
if (!hasNext())
throw new NoSuchElementException();
LRUEntry entry = current;
current = entry.before;
return entry.cacheEntry;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_cache_LRUList.java |
4,742 | public class FsRepository extends BlobStoreRepository {
public final static String TYPE = "fs";
private final FsBlobStore blobStore;
private ByteSizeValue chunkSize;
private final BlobPath basePath;
private boolean compress;
/**
* Constructs new shared file system repository
*
* @param name repository name
* @param repositorySettings repository settings
* @param indexShardRepository index shard repository
* @throws IOException
*/
@Inject
public FsRepository(RepositoryName name, RepositorySettings repositorySettings, IndexShardRepository indexShardRepository) throws IOException {
super(name.getName(), repositorySettings, indexShardRepository);
File locationFile;
String location = repositorySettings.settings().get("location", componentSettings.get("location"));
if (location == null) {
logger.warn("using local fs location for gateway, should be changed to be a shared location across nodes");
throw new RepositoryException(name.name(), "missing location");
} else {
locationFile = new File(location);
}
int concurrentStreams = repositorySettings.settings().getAsInt("concurrent_streams", componentSettings.getAsInt("concurrent_streams", 5));
ExecutorService concurrentStreamPool = EsExecutors.newScaling(1, concurrentStreams, 60, TimeUnit.SECONDS, EsExecutors.daemonThreadFactory(settings, "[fs_stream]"));
blobStore = new FsBlobStore(componentSettings, concurrentStreamPool, locationFile);
this.chunkSize = repositorySettings.settings().getAsBytesSize("chunk_size", componentSettings.getAsBytesSize("chunk_size", null));
this.compress = repositorySettings.settings().getAsBoolean("compress", componentSettings.getAsBoolean("compress", false));
this.basePath = BlobPath.cleanPath();
}
/**
* {@inheritDoc}
*/
@Override
protected BlobStore blobStore() {
return blobStore;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean isCompress() {
return compress;
}
/**
* {@inheritDoc}
*/
@Override
protected ByteSizeValue chunkSize() {
return chunkSize;
}
@Override
protected BlobPath basePath() {
return basePath;
}
} | 1no label
| src_main_java_org_elasticsearch_repositories_fs_FsRepository.java |
569 | trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
firedEvents.add(event);
}
}); | 0true
| core_src_test_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinitionTest.java |
386 | public class ModuleLifecycleLoggingBean {
private String moduleName;
private LifeCycleEvent lifeCycleEvent;
@PostConstruct
/**
* Initialize the bean and cause the logging message to take place
*/
public void init() {
if (moduleName == null || lifeCycleEvent == null) {
throw new IllegalArgumentException("Must supply the moduleName and lifeCycleEvent properties!");
}
SupportLogger logger = SupportLogManager.getLogger(moduleName, ModuleLifecycleLoggingBean.class);
logger.lifecycle(lifeCycleEvent, "");
}
/**
* Retrieve the type of life cycle event for this logging message
*
* @return life cycle event type
*/
public LifeCycleEvent getLifeCycleEvent() {
return lifeCycleEvent;
}
/**
* Set the type of life cycle event for this logging message
*
* @param lifeCycleEvent life cycle event type
*/
public void setLifeCycleEvent(LifeCycleEvent lifeCycleEvent) {
this.lifeCycleEvent = lifeCycleEvent;
}
/**
* The name of the module that this log message applies to
*
* @return the module name for this logging message
*/
public String getModuleName() {
return moduleName;
}
/**
* Set the name of the module that this log message applies to
*
* @param moduleName the module name for this logging message
*/
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_logging_ModuleLifecycleLoggingBean.java |
2,115 | public interface Releasable {
boolean release() throws ElasticsearchException;
} | 0true
| src_main_java_org_elasticsearch_common_lease_Releasable.java |
1,920 | final class FactoryProvider2<F> implements InvocationHandler, Provider<F> {
/**
* if a factory method parameter isn't annotated, it gets this annotation.
*/
static final Assisted DEFAULT_ANNOTATION = new Assisted() {
public String value() {
return "";
}
public Class<? extends Annotation> annotationType() {
return Assisted.class;
}
@Override
public boolean equals(Object o) {
return o instanceof Assisted
&& ((Assisted) o).value().equals("");
}
@Override
public int hashCode() {
return 127 * "value".hashCode() ^ "".hashCode();
}
@Override
public String toString() {
return "@" + Assisted.class.getName() + "(value=)";
}
};
/**
* the produced type, or null if all methods return concrete types
*/
private final Key<?> producedType;
private final ImmutableMap<Method, Key<?>> returnTypesByMethod;
private final ImmutableMap<Method, ImmutableList<Key<?>>> paramTypes;
/**
* the hosting injector, or null if we haven't been initialized yet
*/
private Injector injector;
/**
* the factory interface, implemented and provided
*/
private final F factory;
/**
* @param factoryType a Java interface that defines one or more create methods.
* @param producedType a concrete type that is assignable to the return types of all factory
* methods.
*/
FactoryProvider2(TypeLiteral<F> factoryType, Key<?> producedType) {
this.producedType = producedType;
Errors errors = new Errors();
@SuppressWarnings("unchecked") // we imprecisely treat the class literal of T as a Class<T>
Class<F> factoryRawType = (Class) factoryType.getRawType();
try {
ImmutableMap.Builder<Method, Key<?>> returnTypesBuilder = ImmutableMap.builder();
ImmutableMap.Builder<Method, ImmutableList<Key<?>>> paramTypesBuilder
= ImmutableMap.builder();
// TODO: also grab methods from superinterfaces
for (Method method : factoryRawType.getMethods()) {
Key<?> returnType = getKey(
factoryType.getReturnType(method), method, method.getAnnotations(), errors);
returnTypesBuilder.put(method, returnType);
List<TypeLiteral<?>> params = factoryType.getParameterTypes(method);
Annotation[][] paramAnnotations = method.getParameterAnnotations();
int p = 0;
List<Key<?>> keys = Lists.newArrayList();
for (TypeLiteral<?> param : params) {
Key<?> paramKey = getKey(param, method, paramAnnotations[p++], errors);
keys.add(assistKey(method, paramKey, errors));
}
paramTypesBuilder.put(method, ImmutableList.copyOf(keys));
}
returnTypesByMethod = returnTypesBuilder.build();
paramTypes = paramTypesBuilder.build();
} catch (ErrorsException e) {
throw new ConfigurationException(e.getErrors().getMessages());
}
factory = factoryRawType.cast(Proxy.newProxyInstance(factoryRawType.getClassLoader(),
new Class[]{factoryRawType}, this));
}
public F get() {
return factory;
}
/**
* Returns a key similar to {@code key}, but with an {@literal @}Assisted binding annotation.
* This fails if another binding annotation is clobbered in the process. If the key already has
* the {@literal @}Assisted annotation, it is returned as-is to preserve any String value.
*/
private <T> Key<T> assistKey(Method method, Key<T> key, Errors errors) throws ErrorsException {
if (key.getAnnotationType() == null) {
return Key.get(key.getTypeLiteral(), DEFAULT_ANNOTATION);
} else if (key.getAnnotationType() == Assisted.class) {
return key;
} else {
errors.withSource(method).addMessage(
"Only @Assisted is allowed for factory parameters, but found @%s",
key.getAnnotationType());
throw errors.toException();
}
}
/**
* At injector-creation time, we initialize the invocation handler. At this time we make sure
* all factory methods will be able to build the target types.
*/
@Inject
void initialize(Injector injector) {
if (this.injector != null) {
throw new ConfigurationException(ImmutableList.of(new Message(FactoryProvider2.class,
"Factories.create() factories may only be used in one Injector!")));
}
this.injector = injector;
for (Method method : returnTypesByMethod.keySet()) {
Object[] args = new Object[method.getParameterTypes().length];
Arrays.fill(args, "dummy object for validating Factories");
getBindingFromNewInjector(method, args); // throws if the binding isn't properly configured
}
}
/**
* Creates a child injector that binds the args, and returns the binding for the method's result.
*/
public Binding<?> getBindingFromNewInjector(final Method method, final Object[] args) {
checkState(injector != null,
"Factories.create() factories cannot be used until they're initialized by Guice.");
final Key<?> returnType = returnTypesByMethod.get(method);
Module assistedModule = new AbstractModule() {
@SuppressWarnings("unchecked") // raw keys are necessary for the args array and return value
protected void configure() {
Binder binder = binder().withSource(method);
int p = 0;
for (Key<?> paramKey : paramTypes.get(method)) {
// Wrap in a Provider to cover null, and to prevent Guice from injecting the parameter
binder.bind((Key) paramKey).toProvider(Providers.of(args[p++]));
}
if (producedType != null && !returnType.equals(producedType)) {
binder.bind(returnType).to((Key) producedType);
} else {
binder.bind(returnType);
}
}
};
Injector forCreate = injector.createChildInjector(assistedModule);
return forCreate.getBinding(returnType);
}
/**
* When a factory method is invoked, we create a child injector that binds all parameters, then
* use that to get an instance of the return type.
*/
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
Provider<?> provider = getBindingFromNewInjector(method, args).getProvider();
try {
return provider.get();
} catch (ProvisionException e) {
// if this is an exception declared by the factory method, throw it as-is
if (e.getErrorMessages().size() == 1) {
Message onlyError = Iterables.getOnlyElement(e.getErrorMessages());
Throwable cause = onlyError.getCause();
if (cause != null && canRethrow(method, cause)) {
throw cause;
}
}
throw e;
}
}
@Override
public String toString() {
return factory.getClass().getInterfaces()[0].getName()
+ " for " + producedType.getTypeLiteral();
}
@Override
public boolean equals(Object o) {
return o == this || o == factory;
}
/**
* Returns true if {@code thrown} can be thrown by {@code invoked} without wrapping.
*/
static boolean canRethrow(Method invoked, Throwable thrown) {
if (thrown instanceof Error || thrown instanceof RuntimeException) {
return true;
}
for (Class<?> declared : invoked.getExceptionTypes()) {
if (declared.isInstance(thrown)) {
return true;
}
}
return false;
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_assistedinject_FactoryProvider2.java |
3,205 | BYTE(8, false, SortField.Type.INT, Byte.MIN_VALUE, Byte.MAX_VALUE) {
@Override
public long toLong(BytesRef indexForm) {
return INT.toLong(indexForm);
}
@Override
public void toIndexForm(Number number, BytesRef bytes) {
INT.toIndexForm(number, bytes);
}
@Override
public Number toNumber(BytesRef indexForm) {
return INT.toNumber(indexForm);
}
}, | 0true
| src_main_java_org_elasticsearch_index_fielddata_IndexNumericFieldData.java |
1,329 | public class OCheckpointEndRecord implements OWALRecord {
private OLogSequenceNumber lsn;
public OCheckpointEndRecord() {
}
@Override
public int toStream(byte[] content, int offset) {
return offset;
}
@Override
public int fromStream(byte[] content, int offset) {
return offset;
}
@Override
public int serializedSize() {
return 0;
}
@Override
public boolean isUpdateMasterRecord() {
return false;
}
@Override
public OLogSequenceNumber getLsn() {
return lsn;
}
@Override
public void setLsn(OLogSequenceNumber lsn) {
this.lsn = lsn;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
return true;
}
@Override
public String toString() {
return "OCheckpointEndRecord{" + "lsn=" + lsn + '}';
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OCheckpointEndRecord.java |
1,770 | public enum SpatialStrategy {
TERM("term"),
RECURSIVE("recursive");
private final String strategyName;
private SpatialStrategy(String strategyName) {
this.strategyName = strategyName;
}
public String getStrategyName() {
return strategyName;
}
public PrefixTreeStrategy create(SpatialPrefixTree grid, String fieldName) {
if (this == TERM) {
return new TermQueryPrefixTreeStrategy(grid, fieldName);
}
return new RecursivePrefixTreeStrategy(grid, fieldName);
}
} | 0true
| src_main_java_org_elasticsearch_common_geo_SpatialStrategy.java |
1,229 | QUEUE {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) {
return concurrentDeque(c, limit);
}
}, | 0true
| src_main_java_org_elasticsearch_cache_recycler_PageCacheRecycler.java |
67 | public interface TitanMultiVertexQuery<Q extends TitanMultiVertexQuery<Q>> extends BaseVertexQuery<Q> {
/* ---------------------------------------------------------------
* Query Specification
* ---------------------------------------------------------------
*/
/**
* Adds the given vertex to the set of vertices against which to execute this query.
*
* @param vertex
* @return this query builder
*/
public TitanMultiVertexQuery addVertex(TitanVertex vertex);
/**
* Adds the given collection of vertices to the set of vertices against which to execute this query.
*
* @param vertices
* @return this query builder
*/
public TitanMultiVertexQuery addAllVertices(Collection<TitanVertex> vertices);
@Override
public Q adjacent(TitanVertex vertex);
@Override
public Q types(RelationType... type);
@Override
public Q labels(String... labels);
@Override
public Q keys(String... keys);
@Override
public Q direction(Direction d);
@Override
public Q has(PropertyKey key, Object value);
@Override
public Q has(EdgeLabel label, TitanVertex vertex);
@Override
public Q has(String key);
@Override
public Q hasNot(String key);
@Override
public Q has(String type, Object value);
@Override
public Q hasNot(String key, Object value);
@Override
public Q has(PropertyKey key, Predicate predicate, Object value);
@Override
public Q has(String key, Predicate predicate, Object value);
@Override
public <T extends Comparable<?>> Q interval(String key, T start, T end);
@Override
public <T extends Comparable<?>> Q interval(PropertyKey key, T start, T end);
@Override
public Q limit(int limit);
@Override
public Q orderBy(String key, Order order);
@Override
public Q orderBy(PropertyKey key, Order order);
/* ---------------------------------------------------------------
* Query execution
* ---------------------------------------------------------------
*/
/**
* Returns an iterable over all incident edges that match this query for each vertex
*
* @return Iterable over all incident edges that match this query for each vertex
*/
public Map<TitanVertex, Iterable<TitanEdge>> titanEdges();
/**
* Returns an iterable over all incident properties that match this query for each vertex
*
* @return Iterable over all incident properties that match this query for each vertex
*/
public Map<TitanVertex, Iterable<TitanProperty>> properties();
/**
* Returns an iterable over all incident relations that match this query for each vertex
*
* @return Iterable over all incident relations that match this query for each vertex
*/
public Map<TitanVertex, Iterable<TitanRelation>> relations();
/**
* Retrieves all vertices connected to each of the query's base vertices by edges
* matching the conditions defined in this query.
* <p/>
*
* @return An iterable of all vertices connected to each of the query's central vertices by matching edges
*/
public Map<TitanVertex, Iterable<TitanVertex>> vertices();
/**
* Retrieves all vertices connected to each of the query's central vertices by edges
* matching the conditions defined in this query.
* <p/>
* The query engine will determine the most efficient way to retrieve the vertices that match this query.
*
* @return A list of all vertices' ids connected to each of the query's central vertex by matching edges
*/
public Map<TitanVertex, VertexList> vertexIds();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_TitanMultiVertexQuery.java |
277 | public class DefaultSchemaIndexProviderMap implements SchemaIndexProviderMap
{
private final SchemaIndexProvider indexProvider;
public DefaultSchemaIndexProviderMap( SchemaIndexProvider indexProvider )
{
this.indexProvider = indexProvider;
}
@Override
public SchemaIndexProvider getDefaultProvider()
{
return indexProvider;
}
@Override
public SchemaIndexProvider apply( SchemaIndexProvider.Descriptor descriptor )
{
if ( indexProvider.getProviderDescriptor().getKey().equals( descriptor.getKey() ) )
return indexProvider;
throw new IllegalArgumentException( "Tried to get index provider for an existing index with provider " +
descriptor + " whereas the default and only supported provider in this session is " +
indexProvider.getProviderDescriptor() );
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_DefaultSchemaIndexProviderMap.java |
385 | public class DocumentationHover
implements ITextHover, ITextHoverExtension, ITextHoverExtension2 {
private CeylonEditor editor;
public DocumentationHover(CeylonEditor editor) {
this.editor = editor;
}
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
IDocument document = textViewer.getDocument();
int start= -2;
int end= -1;
try {
int pos= offset;
char c;
while (pos >= 0) {
c= document.getChar(pos);
if (!Character.isJavaIdentifierPart(c)) {
break;
}
--pos;
}
start= pos;
pos= offset;
int length= document.getLength();
while (pos < length) {
c= document.getChar(pos);
if (!Character.isJavaIdentifierPart(c)) {
break;
}
++pos;
}
end= pos;
} catch (BadLocationException x) {
}
if (start >= -1 && end > -1) {
if (start == offset && end == offset)
return new Region(offset, 0);
else if (start == offset)
return new Region(start, end - start);
else
return new Region(start + 1, end - start - 1);
}
return null;
}
final class CeylonLocationListener implements LocationListener {
private final BrowserInformationControl control;
CeylonLocationListener(BrowserInformationControl control) {
this.control = control;
}
@Override
public void changing(LocationEvent event) {
String location = event.location;
//necessary for windows environment (fix for blank page)
//somehow related to this: https://bugs.eclipse.org/bugs/show_bug.cgi?id=129236
if (!"about:blank".equals(location)) {
event.doit= false;
}
handleLink(location);
/*else if (location.startsWith("javadoc:")) {
final DocBrowserInformationControlInput input = (DocBrowserInformationControlInput) control.getInput();
int beginIndex = input.getHtml().indexOf("javadoc:")+8;
final String handle = input.getHtml().substring(beginIndex, input.getHtml().indexOf("\"",beginIndex));
new Job("Fetching Javadoc") {
@Override
protected IStatus run(IProgressMonitor monitor) {
final IJavaElement elem = JavaCore.create(handle);
try {
final String javadoc = JavadocContentAccess2.getHTMLContent((IMember) elem, true);
if (javadoc!=null) {
PlatformUI.getWorkbench().getProgressService()
.runInUI(editor.getSite().getWorkbenchWindow(), new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
StringBuilder sb = new StringBuilder();
HTMLPrinter.insertPageProlog(sb, 0, getStyleSheet());
appendJavadoc(elem, javadoc, sb);
HTMLPrinter.addPageEpilog(sb);
control.setInput(new DocBrowserInformationControlInput(input, null, sb.toString(), 0));
}
}, null);
}
}
catch (Exception e) {
e.printStackTrace();
}
return Status.OK_STATUS;
}
}.schedule();
}*/
}
private void handleLink(String location) {
if (location.startsWith("dec:")) {
Referenceable target = getLinkedModel(editor, location);
if (target!=null) {
close(control); //FIXME: should have protocol to hide, rather than dispose
gotoDeclaration(target, editor);
}
}
else if (location.startsWith("doc:")) {
Referenceable target = getLinkedModel(editor, location);
if (target!=null) {
control.setInput(getHoverInfo(target, control.getInput(), editor, null));
}
}
else if (location.startsWith("ref:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindReferencesAction(editor, (Declaration) target).run();
}
else if (location.startsWith("sub:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindSubtypesAction(editor, (Declaration) target).run();
}
else if (location.startsWith("act:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindRefinementsAction(editor, (Declaration) target).run();
}
else if (location.startsWith("ass:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindAssignmentsAction(editor, (Declaration) target).run();
}
else if (location.startsWith("stp:")) {
close(control);
CompilationUnit rn = editor.getParseController().getRootNode();
Node node = Nodes.findNode(rn, Integer.parseInt(location.substring(4)));
for (SpecifyTypeProposal stp: SpecifyTypeProposal.createProposals(rn, node, editor)) {
stp.apply(editor.getParseController().getDocument());
break;
}
}
else if (location.startsWith("exv:")) {
close(control);
new ExtractValueProposal(editor).apply(editor.getParseController().getDocument());
}
else if (location.startsWith("exf:")) {
close(control);
new ExtractFunctionProposal(editor).apply(editor.getParseController().getDocument());
}
}
@Override
public void changed(LocationEvent event) {}
}
/**
* Action to go back to the previous input in the hover control.
*/
static final class BackAction extends Action {
private final BrowserInformationControl fInfoControl;
public BackAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Back");
ISharedImages images= getWorkbench().getSharedImages();
setImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK));
setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK_DISABLED));
update();
}
@Override
public void run() {
BrowserInput previous= (BrowserInput) fInfoControl.getInput().getPrevious();
if (previous != null) {
fInfoControl.setInput(previous);
}
}
public void update() {
BrowserInput current= fInfoControl.getInput();
if (current != null && current.getPrevious() != null) {
BrowserInput previous= current.getPrevious();
setToolTipText("Back to " + previous.getInputName());
setEnabled(true);
} else {
setToolTipText("Back");
setEnabled(false);
}
}
}
/**
* Action to go forward to the next input in the hover control.
*/
static final class ForwardAction extends Action {
private final BrowserInformationControl fInfoControl;
public ForwardAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Forward");
ISharedImages images= getWorkbench().getSharedImages();
setImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD));
setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD_DISABLED));
update();
}
@Override
public void run() {
BrowserInput next= (BrowserInput) fInfoControl.getInput().getNext();
if (next != null) {
fInfoControl.setInput(next);
}
}
public void update() {
BrowserInput current= fInfoControl.getInput();
if (current != null && current.getNext() != null) {
setToolTipText("Forward to " + current.getNext().getInputName());
setEnabled(true);
} else {
setToolTipText("Forward");
setEnabled(false);
}
}
}
/**
* Action that shows the current hover contents in the Javadoc view.
*/
/*private static final class ShowInDocViewAction extends Action {
private final BrowserInformationControl fInfoControl;
public ShowInJavadocViewAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Show in Ceylondoc View");
setImageDescriptor(JavaPluginImages.DESC_OBJS_JAVADOCTAG); //TODO: better image
}
@Override
public void run() {
DocBrowserInformationControlInput infoInput= (DocBrowserInformationControlInput) fInfoControl.getInput(); //TODO: check cast
fInfoControl.notifyDelayedInputChange(null);
fInfoControl.dispose(); //FIXME: should have protocol to hide, rather than dispose
try {
JavadocView view= (JavadocView) JavaPlugin.getActivePage().showView(JavaUI.ID_JAVADOC_VIEW);
view.setInput(infoInput);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
}*/
/**
* Action that opens the current hover input element.
*/
final class OpenDeclarationAction extends Action {
private final BrowserInformationControl fInfoControl;
public OpenDeclarationAction(BrowserInformationControl infoControl) {
fInfoControl = infoControl;
setText("Open Declaration");
setLocalImageDescriptors(this, "goto_input.gif");
}
@Override
public void run() {
close(fInfoControl); //FIXME: should have protocol to hide, rather than dispose
CeylonBrowserInput input = (CeylonBrowserInput) fInfoControl.getInput();
gotoDeclaration(getLinkedModel(editor, input.getAddress()), editor);
}
}
private static void close(BrowserInformationControl control) {
control.notifyDelayedInputChange(null);
control.dispose();
}
/**
* The hover control creator.
*/
private IInformationControlCreator fHoverControlCreator;
/**
* The presentation control creator.
*/
private IInformationControlCreator fPresenterControlCreator;
private IInformationControlCreator getInformationPresenterControlCreator() {
if (fPresenterControlCreator == null)
fPresenterControlCreator= new PresenterControlCreator(this);
return fPresenterControlCreator;
}
@Override
public IInformationControlCreator getHoverControlCreator() {
return getHoverControlCreator("F2 for focus");
}
public IInformationControlCreator getHoverControlCreator(
String statusLineMessage) {
if (fHoverControlCreator == null) {
fHoverControlCreator= new HoverControlCreator(this,
getInformationPresenterControlCreator(),
statusLineMessage);
}
return fHoverControlCreator;
}
void addLinkListener(final BrowserInformationControl control) {
control.addLocationListener(new CeylonLocationListener(control));
}
public static Referenceable getLinkedModel(CeylonEditor editor, String location) {
if (location==null) {
return null;
}
else if (location.equals("doc:ceylon.language:ceylon.language:Nothing")) {
return editor.getParseController().getRootNode().getUnit().getNothingDeclaration();
}
TypeChecker tc = editor.getParseController().getTypeChecker();
String[] bits = location.split(":");
JDTModelLoader modelLoader = getModelLoader(tc);
String moduleName = bits[1];
Module module = modelLoader.getLoadedModule(moduleName);
if (module==null || bits.length==2) {
return module;
}
Referenceable target = module.getPackage(bits[2]);
for (int i=3; i<bits.length; i++) {
Scope scope;
if (target instanceof Scope) {
scope = (Scope) target;
}
else if (target instanceof TypedDeclaration) {
scope = ((TypedDeclaration) target).getType().getDeclaration();
}
else {
return null;
}
if (scope instanceof Value) {
TypeDeclaration val = ((Value) scope).getTypeDeclaration();
if (val.isAnonymous()) {
scope = val;
}
}
target = scope.getDirectMember(bits[i], null, false);
}
return target;
}
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
CeylonBrowserInput info = (CeylonBrowserInput)
getHoverInfo2(textViewer, hoverRegion);
return info!=null ? info.getHtml() : null;
}
@Override
public CeylonBrowserInput getHoverInfo2(ITextViewer textViewer,
IRegion hoverRegion) {
return internalGetHoverInfo(editor, hoverRegion);
}
static CeylonBrowserInput internalGetHoverInfo(CeylonEditor editor,
IRegion hoverRegion) {
if (editor==null || editor.getSelectionProvider()==null) {
return null;
}
CeylonBrowserInput result =
getExpressionHover(editor, hoverRegion);
if (result==null) {
result = getDeclarationHover(editor, hoverRegion);
}
return result;
}
static CeylonBrowserInput getExpressionHover(CeylonEditor editor,
IRegion hoverRegion) {
CeylonParseController parseController =
editor.getParseController();
if (parseController==null) {
return null;
}
Tree.CompilationUnit rn =
parseController.getRootNode();
if (rn!=null) {
int hoffset = hoverRegion.getOffset();
ITextSelection selection =
editor.getSelectionFromThread();
if (selection!=null &&
selection.getOffset()<=hoffset &&
selection.getOffset()+selection.getLength()>=hoffset) {
Node node = findNode(rn,
selection.getOffset(),
selection.getOffset()+selection.getLength()-1);
if (node instanceof Tree.Type) {
return getTypeHoverInfo(node,
selection.getText(),
editor.getCeylonSourceViewer().getDocument(),
editor.getParseController().getProject());
}
if (node instanceof Tree.Expression) {
node = ((Tree.Expression) node).getTerm();
}
if (node instanceof Tree.Term) {
return getTermTypeHoverInfo(node,
selection.getText(),
editor.getCeylonSourceViewer().getDocument(),
editor.getParseController().getProject());
}
else {
return null;
}
}
else {
return null;
}
}
else {
return null;
}
}
static CeylonBrowserInput getDeclarationHover(CeylonEditor editor,
IRegion hoverRegion) {
CeylonParseController parseController =
editor.getParseController();
if (parseController==null) {
return null;
}
Tree.CompilationUnit rootNode =
parseController.getRootNode();
if (rootNode!=null) {
Node node = findNode(rootNode,
hoverRegion.getOffset());
if (node instanceof Tree.ImportPath) {
Referenceable r =
((Tree.ImportPath) node).getModel();
if (r!=null) {
return getHoverInfo(r, null, editor, node);
}
else {
return null;
}
}
else if (node instanceof Tree.LocalModifier) {
return getInferredTypeHoverInfo(node,
parseController.getProject());
}
else if (node instanceof Tree.Literal) {
return getTermTypeHoverInfo(node, null,
editor.getCeylonSourceViewer().getDocument(),
parseController.getProject());
}
else {
return getHoverInfo(getReferencedDeclaration(node),
null, editor, node);
}
}
else {
return null;
}
}
private static CeylonBrowserInput getInferredTypeHoverInfo(Node node,
IProject project) {
ProducedType t = ((Tree.LocalModifier) node).getTypeModel();
if (t==null) return null;
StringBuilder buffer = new StringBuilder();
HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet());
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("types.gif").toExternalForm(),
16, 16,
"<tt>" + producedTypeLink(t, node.getUnit()) + "</tt>",
20, 4);
buffer.append("<br/>");
if (!t.containsUnknowns()) {
buffer.append("One quick assist available:<br/>");
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("correction_change.gif").toExternalForm(),
16, 16,
"<a href=\"stp:" + node.getStartIndex() + "\">Specify explicit type</a>",
20, 4);
}
//buffer.append(getDocumentationFor(editor.getParseController(), t.getDeclaration()));
HTMLPrinter.addPageEpilog(buffer);
return new CeylonBrowserInput(null, null, buffer.toString());
}
private static CeylonBrowserInput getTypeHoverInfo(Node node, String selectedText,
IDocument doc, IProject project) {
ProducedType t = ((Tree.Type) node).getTypeModel();
if (t==null) return null;
// String expr = "";
// try {
// expr = doc.get(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1);
// }
// catch (BadLocationException e) {
// e.printStackTrace();
// }
String abbreviated = PRINTER.getProducedTypeName(t, node.getUnit());
String unabbreviated = VERBOSE_PRINTER.getProducedTypeName(t, node.getUnit());
StringBuilder buffer = new StringBuilder();
HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet());
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("types.gif").toExternalForm(),
16, 16,
"<tt>" + producedTypeLink(t, node.getUnit()) + "</tt> ",
20, 4);
if (!abbreviated.equals(unabbreviated)) {
buffer.append("<br/>")
.append("Abbreviation of: ")
.append(unabbreviated);
}
HTMLPrinter.addPageEpilog(buffer);
return new CeylonBrowserInput(null, null, buffer.toString());
}
private static CeylonBrowserInput getTermTypeHoverInfo(Node node, String selectedText,
IDocument doc, IProject project) {
ProducedType t = ((Tree.Term) node).getTypeModel();
if (t==null) return null;
// String expr = "";
// try {
// expr = doc.get(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1);
// }
// catch (BadLocationException e) {
// e.printStackTrace();
// }
StringBuilder buffer = new StringBuilder();
HTMLPrinter.insertPageProlog(buffer, 0, HTML.getStyleSheet());
String desc = node instanceof Tree.Literal ? "literal" : "expression";
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("types.gif").toExternalForm(),
16, 16,
"<tt>" + producedTypeLink(t, node.getUnit()) + "</tt> " + desc,
20, 4);
if (node instanceof Tree.StringLiteral) {
buffer.append( "<br/>")
.append("<code style='color:")
.append(toHex(getCurrentThemeColor(STRINGS)))
.append("'><pre>")
.append('\"')
.append(convertToHTMLContent(node.getText()))
.append('\"')
.append("</pre></code>");
// If a single char selection, then append info on that character too
if (selectedText != null
&& codePointCount(selectedText, 0, selectedText.length()) == 1) {
appendCharacterHoverInfo(buffer, selectedText);
}
}
else if (node instanceof Tree.CharLiteral) {
String character = node.getText();
if (character.length()>2) {
appendCharacterHoverInfo(buffer,
character.substring(1, character.length()-1));
}
}
else if (node instanceof Tree.NaturalLiteral) {
buffer.append("<br/>")
.append("<code style='color:")
.append(toHex(getCurrentThemeColor(NUMBERS)))
.append("'>");
String text = node.getText().replace("_", "");
switch (text.charAt(0)) {
case '#':
buffer.append(parseInt(text.substring(1),16));
break;
case '$':
buffer.append(parseInt(text.substring(1),2));
break;
default:
buffer.append(parseInt(text));
}
buffer.append("</code>");
}
else if (node instanceof Tree.FloatLiteral) {
buffer.append("<br/>")
.append("<code style='color:")
.append(toHex(getCurrentThemeColor(NUMBERS)))
.append("'>")
.append(parseFloat(node.getText().replace("_", "")))
.append("</code>");
}
if (selectedText!=null) {
buffer.append("<br/>")
.append("Two quick assists available:<br/>");
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("change.png").toExternalForm(),
16, 16,
"<a href=\"exv:\">Extract value</a>",
20, 4);
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("change.png").toExternalForm(),
16, 16,
"<a href=\"exf:\">Extract function</a>",
20, 4);
buffer.append("<br/>");
}
HTMLPrinter.addPageEpilog(buffer);
return new CeylonBrowserInput(null, null, buffer.toString());
}
private static void appendCharacterHoverInfo(StringBuilder buffer, String character) {
buffer.append( "<br/>")
.append("<code style='color:")
.append(toHex(getCurrentThemeColor(CHARS)))
.append("'>")
.append('\'')
.append(convertToHTMLContent(character))
.append('\'')
.append("</code>");
int codepoint = Character.codePointAt(character, 0);
String name = Character.getName(codepoint);
buffer.append("<br/>Unicode Name: <code>").append(name).append("</code>");
String hex = Integer.toHexString(codepoint).toUpperCase();
while (hex.length() < 4) {
hex = "0" + hex;
}
buffer.append("<br/>Codepoint: <code>").append("U+").append(hex).append("</code>");
buffer.append("<br/>General Category: <code>").append(getCodepointGeneralCategoryName(codepoint)).append("</code>");
Character.UnicodeScript script = Character.UnicodeScript.of(codepoint);
buffer.append("<br/>Script: <code>").append(script.name()).append("</code>");
Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint);
buffer.append("<br/>Block: <code>").append(block).append("</code><br/>");
}
private static String getCodepointGeneralCategoryName(int codepoint) {
String gc;
switch (Character.getType(codepoint)) {
case Character.COMBINING_SPACING_MARK:
gc = "Mark, combining spacing"; break;
case Character.CONNECTOR_PUNCTUATION:
gc = "Punctuation, connector"; break;
case Character.CONTROL:
gc = "Other, control"; break;
case Character.CURRENCY_SYMBOL:
gc = "Symbol, currency"; break;
case Character.DASH_PUNCTUATION:
gc = "Punctuation, dash"; break;
case Character.DECIMAL_DIGIT_NUMBER:
gc = "Number, decimal digit"; break;
case Character.ENCLOSING_MARK:
gc = "Mark, enclosing"; break;
case Character.END_PUNCTUATION:
gc = "Punctuation, close"; break;
case Character.FINAL_QUOTE_PUNCTUATION:
gc = "Punctuation, final quote"; break;
case Character.FORMAT:
gc = "Other, format"; break;
case Character.INITIAL_QUOTE_PUNCTUATION:
gc = "Punctuation, initial quote"; break;
case Character.LETTER_NUMBER:
gc = "Number, letter"; break;
case Character.LINE_SEPARATOR:
gc = "Separator, line"; break;
case Character.LOWERCASE_LETTER:
gc = "Letter, lowercase"; break;
case Character.MATH_SYMBOL:
gc = "Symbol, math"; break;
case Character.MODIFIER_LETTER:
gc = "Letter, modifier"; break;
case Character.MODIFIER_SYMBOL:
gc = "Symbol, modifier"; break;
case Character.NON_SPACING_MARK:
gc = "Mark, nonspacing"; break;
case Character.OTHER_LETTER:
gc = "Letter, other"; break;
case Character.OTHER_NUMBER:
gc = "Number, other"; break;
case Character.OTHER_PUNCTUATION:
gc = "Punctuation, other"; break;
case Character.OTHER_SYMBOL:
gc = "Symbol, other"; break;
case Character.PARAGRAPH_SEPARATOR:
gc = "Separator, paragraph"; break;
case Character.PRIVATE_USE:
gc = "Other, private use"; break;
case Character.SPACE_SEPARATOR:
gc = "Separator, space"; break;
case Character.START_PUNCTUATION:
gc = "Punctuation, open"; break;
case Character.SURROGATE:
gc = "Other, surrogate"; break;
case Character.TITLECASE_LETTER:
gc = "Letter, titlecase"; break;
case Character.UNASSIGNED:
gc = "Other, unassigned"; break;
case Character.UPPERCASE_LETTER:
gc = "Letter, uppercase"; break;
default:
gc = "<Unknown>";
}
return gc;
}
private static String getIcon(Object obj) {
if (obj instanceof Module) {
return "jar_l_obj.gif";
}
else if (obj instanceof Package) {
return "package_obj.gif";
}
else if (obj instanceof Declaration) {
Declaration dec = (Declaration) obj;
if (dec instanceof Class) {
String icon = dec.isShared() ?
"class_obj.gif" :
"innerclass_private_obj.gif";
return decorateTypeIcon(dec, icon);
}
else if (dec instanceof Interface) {
String icon = dec.isShared() ?
"int_obj.gif" :
"innerinterface_private_obj.gif";
return decorateTypeIcon(dec, icon);
}
else if (dec instanceof TypeAlias||
dec instanceof NothingType) {
return "type_alias.gif";
}
else if (dec.isParameter()) {
if (dec instanceof Method) {
return "methpro_obj.gif";
}
else {
return "field_protected_obj.gif";
}
}
else if (dec instanceof Method) {
String icon = dec.isShared() ?
"public_co.gif" :
"private_co.gif";
return decorateFunctionIcon(dec, icon);
}
else if (dec instanceof MethodOrValue) {
return dec.isShared() ?
"field_public_obj.gif" :
"field_private_obj.gif";
}
else if (dec instanceof TypeParameter) {
return "typevariable_obj.gif";
}
}
return null;
}
private static String decorateFunctionIcon(Declaration dec, String icon) {
if (dec.isAnnotation()) {
return icon.replace("co", "ann");
}
else {
return icon;
}
}
private static String decorateTypeIcon(Declaration dec, String icon) {
if (((TypeDeclaration) dec).getCaseTypes()!=null) {
return icon.replace("obj", "enum");
}
else if (dec.isAnnotation()) {
return icon.replace("obj", "ann");
}
else if (((TypeDeclaration) dec).isAlias()) {
return icon.replace("obj", "alias");
}
else {
return icon;
}
}
/**
* Computes the hover info.
* @param previousInput the previous input, or <code>null</code>
* @param node
* @param elements the resolved elements
* @param editorInputElement the editor input, or <code>null</code>
*
* @return the HTML hover info for the given element(s) or <code>null</code>
* if no information is available
* @since 3.4
*/
static CeylonBrowserInput getHoverInfo(Referenceable model,
BrowserInput previousInput, CeylonEditor editor, Node node) {
if (model instanceof Declaration) {
Declaration dec = (Declaration) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec, node, null));
}
else if (model instanceof Package) {
Package dec = (Package) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec));
}
else if (model instanceof Module) {
Module dec = (Module) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec));
}
else {
return null;
}
}
private static void appendJavadoc(IJavaElement elem, StringBuilder sb) {
if (elem instanceof IMember) {
try {
//TODO: Javadoc @ icon?
IMember mem = (IMember) elem;
String jd = JavadocContentAccess2.getHTMLContent(mem, true);
if (jd!=null) {
sb.append("<br/>").append(jd);
String base = getBaseURL(mem, mem.isBinary());
int endHeadIdx= sb.indexOf("</head>");
sb.insert(endHeadIdx, "\n<base href='" + base + "'>\n");
}
}
catch (JavaModelException e) {
e.printStackTrace();
}
}
}
private static String getBaseURL(IJavaElement element, boolean isBinary)
throws JavaModelException {
if (isBinary) {
// Source attachment usually does not include Javadoc resources
// => Always use the Javadoc location as base:
URL baseURL = JavaUI.getJavadocLocation(element, false);
if (baseURL != null) {
if (baseURL.getProtocol().equals("jar")) {
// It's a JarURLConnection, which is not known to the browser widget.
// Let's start the help web server:
URL baseURL2 = PlatformUI.getWorkbench().getHelpSystem()
.resolve(baseURL.toExternalForm(), true);
if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available
baseURL = baseURL2;
}
}
return baseURL.toExternalForm();
}
}
else {
IResource resource = element.getResource();
if (resource != null) {
/*
* Too bad: Browser widget knows nothing about EFS and custom URL handlers,
* so IResource#getLocationURI() does not work in all cases.
* We only support the local file system for now.
* A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 .
*/
IPath location = resource.getLocation();
if (location != null) {
return location.toFile().toURI().toString();
}
}
}
return null;
}
public static String getDocumentationFor(CeylonParseController cpc,
Package pack) {
StringBuilder buffer= new StringBuilder();
addMainPackageDescription(pack, buffer);
addPackageDocumentation(cpc, pack, buffer);
addAdditionalPackageInfo(buffer, pack);
addPackageMembers(buffer, pack);
addPackageModuleInfo(pack, buffer);
insertPageProlog(buffer, 0, HTML.getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static void addPackageMembers(StringBuilder buffer,
Package pack) {
boolean first = true;
for (Declaration dec: pack.getMembers()) {
if (dec instanceof Class && ((Class)dec).isOverloaded()) {
continue;
}
if (dec.isShared() && !dec.isAnonymous()) {
if (first) {
buffer.append("<p>Contains: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" +
dec.getName() + "</a></tt>", 20, 2);*/
appendLink(buffer, dec);
}
}
if (!first) {
buffer.append(".</p>");
}
}
private static void appendLink(StringBuilder buffer, Referenceable dec) {
buffer.append("<tt><a ").append(HTML.link(dec)).append(">");
if (dec instanceof Declaration) {
buffer.append(((Declaration) dec).getName());
}
else if (dec instanceof Package) {
buffer.append(getLabel((Package)dec));
}
else if (dec instanceof Module) {
buffer.append(getLabel((Module)dec));
}
buffer.append("</a></tt>");
}
private static String link(Referenceable dec) {
StringBuilder builder = new StringBuilder();
appendLink(builder, dec);
return builder.toString();
}
private static void addAdditionalPackageInfo(StringBuilder buffer,
Package pack) {
Module mod = pack.getModule();
if (mod.isJava()) {
buffer.append("<p>This package is implemented in Java.</p>");
}
if (JDKUtils.isJDKModule(mod.getNameAsString())) {
buffer.append("<p>This package forms part of the Java SDK.</p>");
}
}
private static void addMainPackageDescription(Package pack,
StringBuilder buffer) {
if (pack.isShared()) {
String ann = toHex(getCurrentThemeColor(ANNOTATIONS));
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("annotation_obj.gif").toExternalForm(),
16, 16,
"<tt style='font-size:90%;color:" + ann + "'>shared</tt>"
, 20, 4);
}
HTML.addImageAndLabel(buffer, pack,
HTML.fileUrl(getIcon(pack)).toExternalForm(),
16, 16,
"<tt style='font-size:102%'>" +
HTML.highlightLine(description(pack)) +
"</tt>",
20, 4);
}
private static void addPackageModuleInfo(Package pack,
StringBuilder buffer) {
Module mod = pack.getModule();
HTML.addImageAndLabel(buffer, mod,
HTML.fileUrl(getIcon(mod)).toExternalForm(),
16, 16,
"<span style='font-size:96%'>in module " +
link(mod) + "</span>",
20, 2);
}
private static String description(Package pack) {
return "package " + getLabel(pack);
}
public static String getDocumentationFor(ModuleDetails mod, String version,
Scope scope, Unit unit) {
return getDocumentationForModule(mod.getName(), version, mod.getDoc(),
scope, unit);
}
public static String getDocumentationForModule(String name,
String version, String doc, Scope scope, Unit unit) {
StringBuilder buffer = new StringBuilder();
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("jar_l_obj.gif").toExternalForm(),
16, 16,
"<tt style='font-size:102%'>" +
HTML.highlightLine(description(name, version)) +
"</tt></b>",
20, 4);
if (doc!=null) {
buffer.append(markdown(doc, scope, unit));
}
insertPageProlog(buffer, 0, HTML.getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static String description(String name, String version) {
return "module " + name + " \"" + version + "\"";
}
private static String getDocumentationFor(CeylonParseController cpc,
Module mod) {
StringBuilder buffer = new StringBuilder();
addMainModuleDescription(mod, buffer);
addAdditionalModuleInfo(buffer, mod);
addModuleDocumentation(cpc, mod, buffer);
addModuleMembers(buffer, mod);
insertPageProlog(buffer, 0, HTML.getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static void addAdditionalModuleInfo(StringBuilder buffer,
Module mod) {
if (mod.isJava()) {
buffer.append("<p>This module is implemented in Java.</p>");
}
if (mod.isDefault()) {
buffer.append("<p>The default module for packages which do not belong to explicit module.</p>");
}
if (JDKUtils.isJDKModule(mod.getNameAsString())) {
buffer.append("<p>This module forms part of the Java SDK.</p>");
}
}
private static void addMainModuleDescription(Module mod,
StringBuilder buffer) {
HTML.addImageAndLabel(buffer, mod,
HTML.fileUrl(getIcon(mod)).toExternalForm(),
16, 16,
"<tt style='font-size:102%'>" +
HTML.highlightLine(description(mod)) +
"</tt>",
20, 4);
}
private static void addModuleDocumentation(CeylonParseController cpc,
Module mod, StringBuilder buffer) {
Unit unit = mod.getUnit();
PhasedUnit pu = null;
if (unit instanceof CeylonUnit) {
pu = ((CeylonUnit)unit).getPhasedUnit();
}
if (pu!=null) {
List<Tree.ModuleDescriptor> moduleDescriptors =
pu.getCompilationUnit().getModuleDescriptors();
if (!moduleDescriptors.isEmpty()) {
Tree.ModuleDescriptor refnode = moduleDescriptors.get(0);
if (refnode!=null) {
Scope linkScope = mod.getPackage(mod.getNameAsString());
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
}
}
}
private static void addPackageDocumentation(CeylonParseController cpc,
Package pack, StringBuilder buffer) {
Unit unit = pack.getUnit();
PhasedUnit pu = null;
if (unit instanceof CeylonUnit) {
pu = ((CeylonUnit)unit).getPhasedUnit();
}
if (pu!=null) {
List<Tree.PackageDescriptor> packageDescriptors =
pu.getCompilationUnit().getPackageDescriptors();
if (!packageDescriptors.isEmpty()) {
Tree.PackageDescriptor refnode = packageDescriptors.get(0);
if (refnode!=null) {
Scope linkScope = pack;
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
}
}
}
private static void addModuleMembers(StringBuilder buffer,
Module mod) {
boolean first = true;
for (Package pack: mod.getPackages()) {
if (pack.isShared()) {
if (first) {
buffer.append("<p>Contains: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" +
dec.getName() + "</a></tt>", 20, 2);*/
appendLink(buffer, pack);
}
}
if (!first) {
buffer.append(".</p>");
}
}
private static String description(Module mod) {
return "module " + getLabel(mod) + " \"" + mod.getVersion() + "\"";
}
public static String getDocumentationFor(CeylonParseController cpc,
Declaration dec) {
return getDocumentationFor(cpc, dec, null, null);
}
public static String getDocumentationFor(CeylonParseController cpc,
Declaration dec, ProducedReference pr) {
return getDocumentationFor(cpc, dec, null, pr);
}
private static String getDocumentationFor(CeylonParseController cpc,
Declaration dec, Node node, ProducedReference pr) {
if (dec==null) return null;
if (dec instanceof Value) {
TypeDeclaration val = ((Value) dec).getTypeDeclaration();
if (val!=null && val.isAnonymous()) {
dec = val;
}
}
Unit unit = cpc.getRootNode().getUnit();
StringBuilder buffer = new StringBuilder();
insertPageProlog(buffer, 0, HTML.getStyleSheet());
addMainDescription(buffer, dec, node, pr, cpc, unit);
boolean obj = addInheritanceInfo(dec, node, pr, buffer, unit);
addContainerInfo(dec, node, buffer); //TODO: use the pr to get the qualifying type??
boolean hasDoc = addDoc(cpc, dec, node, buffer);
addRefinementInfo(cpc, dec, node, buffer, hasDoc, unit); //TODO: use the pr to get the qualifying type??
addReturnType(dec, buffer, node, pr, obj, unit);
addParameters(cpc, dec, node, pr, buffer, unit);
addClassMembersInfo(dec, buffer);
addUnitInfo(dec, buffer);
addPackageInfo(dec, buffer);
if (dec instanceof NothingType) {
addNothingTypeInfo(buffer);
}
else {
appendExtraActions(dec, buffer);
}
addPageEpilog(buffer);
return buffer.toString();
}
private static void addMainDescription(StringBuilder buffer,
Declaration dec, Node node, ProducedReference pr,
CeylonParseController cpc, Unit unit) {
StringBuilder buf = new StringBuilder();
if (dec.isShared()) buf.append("shared ");
if (dec.isActual()) buf.append("actual ");
if (dec.isDefault()) buf.append("default ");
if (dec.isFormal()) buf.append("formal ");
if (dec instanceof Value && ((Value) dec).isLate())
buf.append("late ");
if (isVariable(dec)) buf.append("variable ");
if (dec.isNative()) buf.append("native ");
if (dec instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) dec;
if (td.isSealed()) buf.append("sealed ");
if (td.isFinal()) buf.append("final ");
if (td instanceof Class && ((Class)td).isAbstract())
buf.append("abstract ");
}
if (dec.isAnnotation()) buf.append("annotation ");
if (buf.length()!=0) {
String ann = toHex(getCurrentThemeColor(ANNOTATIONS));
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("annotation_obj.gif").toExternalForm(),
16, 16,
"<tt style='font-size:91%;color:" + ann + "'>" + buf + "</tt>",
20, 4);
}
HTML.addImageAndLabel(buffer, dec,
HTML.fileUrl(getIcon(dec)).toExternalForm(),
16, 16,
"<tt style='font-size:105%'>" +
(dec.isDeprecated() ? "<s>":"") +
description(dec, node, pr, cpc, unit) +
(dec.isDeprecated() ? "</s>":"") +
"</tt>",
20, 4);
}
private static void addClassMembersInfo(Declaration dec,
StringBuilder buffer) {
if (dec instanceof ClassOrInterface) {
if (!dec.getMembers().isEmpty()) {
boolean first = true;
for (Declaration mem: dec.getMembers()) {
if (mem instanceof Method &&
((Method) mem).isOverloaded()) {
continue;
}
if (mem.isShared()) {
if (first) {
buffer.append("<p>Members: ");
first = false;
}
else {
buffer.append(", ");
}
appendLink(buffer, mem);
}
}
if (!first) {
buffer.append(".</p>");
//extraBreak = true;
}
}
}
}
private static void addNothingTypeInfo(StringBuilder buffer) {
buffer.append("Special bottom type defined by the language. "
+ "<code>Nothing</code> is assignable to all types, but has no value. "
+ "A function or value of type <code>Nothing</code> either throws "
+ "an exception, or never returns.");
}
private static boolean addInheritanceInfo(Declaration dec,
Node node, ProducedReference pr, StringBuilder buffer,
Unit unit) {
buffer.append("<p><div style='padding-left:20px'>");
boolean obj=false;
if (dec instanceof TypedDeclaration) {
TypeDeclaration td =
((TypedDeclaration) dec).getTypeDeclaration();
if (td!=null && td.isAnonymous()) {
obj=true;
documentInheritance(td, node, pr, buffer, unit);
}
}
else if (dec instanceof TypeDeclaration) {
documentInheritance((TypeDeclaration) dec, node, pr, buffer, unit);
}
buffer.append("</div></p>");
documentTypeParameters(dec, node, pr, buffer, unit);
buffer.append("</p>");
return obj;
}
private static void addRefinementInfo(CeylonParseController cpc,
Declaration dec, Node node, StringBuilder buffer,
boolean hasDoc, Unit unit) {
Declaration rd = dec.getRefinedDeclaration();
if (dec!=rd && rd!=null) {
buffer.append("<p>");
TypeDeclaration superclass = (TypeDeclaration) rd.getContainer();
ClassOrInterface outer = (ClassOrInterface) dec.getContainer();
ProducedType sup = getQualifyingType(node, outer).getSupertype(superclass);
HTML.addImageAndLabel(buffer, rd,
HTML.fileUrl(rd.isFormal() ? "implm_co.gif" : "over_co.gif").toExternalForm(),
16, 16,
"refines " + link(rd) +
" declared by <tt>" +
producedTypeLink(sup, unit) + "</tt>",
20, 2);
buffer.append("</p>");
if (!hasDoc) {
Tree.Declaration refnode2 =
(Tree.Declaration) getReferencedNode(rd, cpc);
if (refnode2!=null) {
appendDocAnnotationContent(refnode2.getAnnotationList(),
buffer, resolveScope(rd));
}
}
}
}
private static void appendParameters(Declaration d, ProducedReference pr,
Unit unit, StringBuilder result/*, CeylonParseController cpc*/) {
if (d instanceof Functional) {
List<ParameterList> plists = ((Functional) d).getParameterLists();
if (plists!=null) {
for (ParameterList params: plists) {
if (params.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
for (Parameter p: params.getParameters()) {
appendParameter(result, pr, p, unit);
// if (cpc!=null) {
// result.append(getDefaultValueDescription(p, cpc));
// }
result.append(", ");
}
result.setLength(result.length()-2);
result.append(")");
}
}
}
}
}
private static void appendParameter(StringBuilder result,
ProducedReference pr, Parameter p, Unit unit) {
if (p.getModel() == null) {
result.append(p.getName());
}
else {
ProducedTypedReference ppr = pr==null ?
null : pr.getTypedParameter(p);
if (p.isDeclaredVoid()) {
result.append(HTML.keyword("void"));
}
else {
if (ppr!=null) {
ProducedType pt = ppr.getType();
if (p.isSequenced() && pt!=null) {
pt = p.getDeclaration().getUnit()
.getSequentialElementType(pt);
}
result.append(producedTypeLink(pt, unit));
if (p.isSequenced()) {
result.append(p.isAtLeastOne()?'+':'*');
}
}
else if (p.getModel() instanceof Method) {
result.append(HTML.keyword("function"));
}
else {
result.append(HTML.keyword("value"));
}
}
result.append(" ");
appendLink(result, p.getModel());
appendParameters(p.getModel(), ppr, unit, result);
}
}
private static void addParameters(CeylonParseController cpc,
Declaration dec, Node node, ProducedReference pr,
StringBuilder buffer, Unit unit) {
if (dec instanceof Functional) {
if (pr==null) {
pr = getProducedReference(dec, node);
}
if (pr==null) return;
for (ParameterList pl: ((Functional) dec).getParameterLists()) {
if (!pl.getParameters().isEmpty()) {
buffer.append("<p>");
for (Parameter p: pl.getParameters()) {
MethodOrValue model = p.getModel();
if (model!=null) {
StringBuilder param = new StringBuilder();
param.append("<span style='font-size:96%'>accepts <tt>");
appendParameter(param, pr, p, unit);
param.append(HTML.highlightLine(getInitialValueDescription(model, cpc)))
.append("</tt>");
Tree.Declaration refNode =
(Tree.Declaration) getReferencedNode(model, cpc);
if (refNode!=null) {
appendDocAnnotationContent(refNode.getAnnotationList(),
param, resolveScope(dec));
}
param.append("</span>");
HTML.addImageAndLabel(buffer, model,
HTML.fileUrl("methpro_obj.gif").toExternalForm(),
16, 16, param.toString(), 20, 2);
}
}
buffer.append("</p>");
}
}
}
}
private static void addReturnType(Declaration dec, StringBuilder buffer,
Node node, ProducedReference pr, boolean obj, Unit unit) {
if (dec instanceof TypedDeclaration && !obj) {
if (pr==null) {
pr = getProducedReference(dec, node);
}
if (pr==null) return;
ProducedType ret = pr.getType();
if (ret!=null) {
buffer.append("<p>");
StringBuilder buf = new StringBuilder("returns <tt>");
buf.append(producedTypeLink(ret, unit)).append("|");
buf.setLength(buf.length()-1);
buf.append("</tt>");
HTML.addImageAndLabel(buffer, ret.getDeclaration(),
HTML.fileUrl("stepreturn_co.gif").toExternalForm(),
16, 16, buf.toString(), 20, 2);
buffer.append("</p>");
}
}
}
private static ProducedTypeNamePrinter printer(boolean abbreviate) {
return new ProducedTypeNamePrinter(abbreviate, true, false, true) {
@Override
protected String getSimpleDeclarationName(Declaration declaration, Unit unit) {
return "<a " + HTML.link(declaration) + ">" +
super.getSimpleDeclarationName(declaration, unit) +
"</a>";
}
@Override
protected String amp() {
return "&";
}
@Override
protected String lt() {
return "<";
}
@Override
protected String gt() {
return ">";
}
};
}
private static ProducedTypeNamePrinter PRINTER = printer(true);
private static ProducedTypeNamePrinter VERBOSE_PRINTER = printer(false);
private static String producedTypeLink(ProducedType pt, Unit unit) {
return PRINTER.getProducedTypeName(pt, unit);
}
private static ProducedReference getProducedReference(Declaration dec,
Node node) {
if (node instanceof Tree.MemberOrTypeExpression) {
return ((Tree.MemberOrTypeExpression) node).getTarget();
}
else if (node instanceof Tree.Type) {
return ((Tree.Type) node).getTypeModel();
}
ClassOrInterface outer = dec.isClassOrInterfaceMember() ?
(ClassOrInterface) dec.getContainer() : null;
return dec.getProducedReference(getQualifyingType(node, outer),
Collections.<ProducedType>emptyList());
}
private static boolean addDoc(CeylonParseController cpc,
Declaration dec, Node node, StringBuilder buffer) {
boolean hasDoc = false;
Node rn = getReferencedNode(dec, cpc);
if (rn instanceof Tree.Declaration) {
Tree.Declaration refnode = (Tree.Declaration) rn;
appendDeprecatedAnnotationContent(refnode.getAnnotationList(),
buffer, resolveScope(dec));
int len = buffer.length();
appendDocAnnotationContent(refnode.getAnnotationList(),
buffer, resolveScope(dec));
hasDoc = buffer.length()!=len;
appendThrowAnnotationContent(refnode.getAnnotationList(),
buffer, resolveScope(dec));
appendSeeAnnotationContent(refnode.getAnnotationList(),
buffer);
}
else {
appendJavadoc(dec, cpc.getProject(), buffer, node);
}
return hasDoc;
}
private static void addContainerInfo(Declaration dec, Node node,
StringBuilder buffer) {
buffer.append("<p>");
if (dec.isParameter()) {
Declaration pd =
((MethodOrValue) dec).getInitializerParameter()
.getDeclaration();
if (pd.getName().startsWith("anonymous#")) {
buffer.append("Parameter of anonymous function.");
}
else {
buffer.append("Parameter of ");
appendLink(buffer, pd);
buffer.append(".");
}
// HTML.addImageAndLabel(buffer, pd,
// HTML.fileUrl(getIcon(pd)).toExternalForm(),
// 16, 16,
// "<span style='font-size:96%'>parameter of <tt><a " + HTML.link(pd) + ">" +
// pd.getName() +"</a></tt><span>", 20, 2);
}
else if (dec instanceof TypeParameter) {
Declaration pd = ((TypeParameter) dec).getDeclaration();
buffer.append("Type parameter of ");
appendLink(buffer, pd);
buffer.append(".");
// HTML.addImageAndLabel(buffer, pd,
// HTML.fileUrl(getIcon(pd)).toExternalForm(),
// 16, 16,
// "<span style='font-size:96%'>type parameter of <tt><a " + HTML.link(pd) + ">" +
// pd.getName() +"</a></tt></span>",
// 20, 2);
}
else {
if (dec.isClassOrInterfaceMember()) {
ClassOrInterface outer = (ClassOrInterface) dec.getContainer();
ProducedType qt = getQualifyingType(node, outer);
if (qt!=null) {
Unit unit = node==null ? null : node.getUnit();
buffer.append("Member of <tt>" +
producedTypeLink(qt, unit) + "</tt>.");
// HTML.addImageAndLabel(buffer, outer,
// HTML.fileUrl(getIcon(outer)).toExternalForm(),
// 16, 16,
// "<span style='font-size:96%'>member of <tt>" +
// producedTypeLink(qt, unit) + "</tt></span>",
// 20, 2);
}
}
}
buffer.append("</p>");
}
private static void addPackageInfo(Declaration dec,
StringBuilder buffer) {
buffer.append("<p>");
Package pack = dec.getUnit().getPackage();
if ((dec.isShared() || dec.isToplevel()) &&
!(dec instanceof NothingType)) {
String label;
if (pack.getNameAsString().isEmpty()) {
label = "<span style='font-size:96%'>in default package</span>";
}
else {
label = "<span style='font-size:96%'>in package " +
link(pack) + "</span>";
}
HTML.addImageAndLabel(buffer, pack,
HTML.fileUrl(getIcon(pack)).toExternalForm(),
16, 16, label, 20, 2);
Module mod = pack.getModule();
HTML.addImageAndLabel(buffer, mod,
HTML.fileUrl(getIcon(mod)).toExternalForm(),
16, 16,
"<span style='font-size:96%'>in module " +
link(mod) + "</span>",
20, 2);
}
buffer.append("</p>");
}
private static ProducedType getQualifyingType(Node node,
ClassOrInterface outer) {
if (outer == null) {
return null;
}
if (node instanceof Tree.MemberOrTypeExpression) {
ProducedReference pr = ((Tree.MemberOrTypeExpression) node).getTarget();
if (pr!=null) {
return pr.getQualifyingType();
}
}
if (node instanceof Tree.QualifiedType) {
return ((Tree.QualifiedType) node).getOuterType().getTypeModel();
}
return outer.getType();
}
private static void addUnitInfo(Declaration dec,
StringBuilder buffer) {
buffer.append("<p>");
String unitName = null;
if (dec.getUnit() instanceof CeylonUnit) {
// Manage the case of CeylonBinaryUnit : getFileName() would return the class file name.
// but getCeylonFileName() will return the ceylon source file name if any.
unitName = ((CeylonUnit)dec.getUnit()).getCeylonFileName();
}
if (unitName == null) {
unitName = dec.getUnit().getFilename();
}
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("unit.gif").toExternalForm(),
16, 16,
"<span style='font-size:96%'>declared in <tt><a href='dec:" +
HTML.declink(dec) + "'>"+ unitName + "</a></tt></span>",
20, 2);
//}
buffer.append("</p>");
}
private static void appendExtraActions(Declaration dec,
StringBuilder buffer) {
buffer.append("<p>");
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("search_ref_obj.png").toExternalForm(),
16, 16,
"<span style='font-size:96%'><a href='ref:" + HTML.declink(dec) +
"'>find references</a> to <tt>" +
dec.getName() + "</tt></span>",
20, 2);
if (dec instanceof ClassOrInterface) {
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("search_decl_obj.png").toExternalForm(),
16, 16,
"<span style='font-size:96%'><a href='sub:" + HTML.declink(dec) +
"'>find subtypes</a> of <tt>" +
dec.getName() + "</tt></span>",
20, 2);
}
if (dec instanceof MethodOrValue ||
dec instanceof TypeParameter) {
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("search_ref_obj.png").toExternalForm(),
16, 16,
"<span style='font-size:96%'><a href='ass:" + HTML.declink(dec) +
"'>find assignments</a> to <tt>" +
dec.getName() + "</tt></span>",
20, 2);
}
if (dec.isFormal() || dec.isDefault()) {
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("search_decl_obj.png").toExternalForm(),
16, 16,
"<span style='font-size:96%'><a href='act:" + HTML.declink(dec) +
"'>find refinements</a> of <tt>" +
dec.getName() + "</tt></span>",
20, 2);
}
buffer.append("</p>");
}
private static void documentInheritance(TypeDeclaration dec,
Node node, ProducedReference pr, StringBuilder buffer,
Unit unit) {
if (pr==null) {
pr = getProducedReference(dec, node);
}
ProducedType type;
if (pr instanceof ProducedType) {
type = (ProducedType) pr;
}
else {
type = dec.getType();
}
List<ProducedType> cts = type.getCaseTypes();
if (cts!=null) {
StringBuilder cases = new StringBuilder();
for (ProducedType ct: cts) {
if (cases.length()>0) {
cases.append(" | ");
}
cases.append(producedTypeLink(ct, unit));
}
if (dec.getSelfType()!=null) {
cases.append(" (self type)");
}
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("sub.gif").toExternalForm(),
16, 16,
" <tt style='font-size:96%'>of " + cases +"</tt>",
20, 2);
}
if (dec instanceof Class) {
ProducedType sup = type.getExtendedType();
if (sup!=null) {
HTML.addImageAndLabel(buffer, sup.getDeclaration(),
HTML.fileUrl("superclass.gif").toExternalForm(),
16, 16,
"<tt style='font-size:96%'>extends " +
producedTypeLink(sup, unit) +"</tt>",
20, 2);
}
}
List<ProducedType> sts = type.getSatisfiedTypes();
if (!sts.isEmpty()) {
StringBuilder satisfies = new StringBuilder();
for (ProducedType st: sts) {
if (satisfies.length()>0) {
satisfies.append(" & ");
}
satisfies.append(producedTypeLink(st, unit));
}
HTML.addImageAndLabel(buffer, null,
HTML.fileUrl("super.gif").toExternalForm(),
16, 16,
"<tt style='font-size:96%'>satisfies " + satisfies +"</tt>",
20, 2);
}
}
private static void documentTypeParameters(Declaration dec,
Node node, ProducedReference pr, StringBuilder buffer,
Unit unit) {
if (pr==null) {
pr = getProducedReference(dec, node);
}
List<TypeParameter> typeParameters;
if (dec instanceof Functional) {
typeParameters = ((Functional) dec).getTypeParameters();
}
else if (dec instanceof Interface) {
typeParameters = ((Interface) dec).getTypeParameters();
}
else {
typeParameters = Collections.emptyList();
}
for (TypeParameter tp: typeParameters) {
StringBuilder bounds = new StringBuilder();
for (ProducedType st: tp.getSatisfiedTypes()) {
if (bounds.length() == 0) {
bounds.append(" satisfies ");
}
else {
bounds.append(" & ");
}
bounds.append(producedTypeLink(st, dec.getUnit()));
}
String arg;
ProducedType typeArg = pr==null ? null : pr.getTypeArguments().get(tp);
if (typeArg!=null && !tp.getType().isExactly(typeArg)) {
arg = " = " + producedTypeLink(typeArg, unit);
}
else {
arg = "";
}
HTML.addImageAndLabel(buffer, tp,
HTML.fileUrl(getIcon(tp)).toExternalForm(),
16, 16,
"<tt style='font-size:96%'>given <a " + HTML.link(tp) + ">" +
tp.getName() + "</a>" + bounds + arg + "</tt>",
20, 4);
}
}
private static String description(Declaration dec, Node node,
ProducedReference pr, CeylonParseController cpc, Unit unit) {
if (pr==null) {
pr = getProducedReference(dec, node);
}
String description = getDocDescriptionFor(dec, pr, unit);
if (dec instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) dec;
if (td.isAlias() && td.getExtendedType()!=null) {
description += " => " +
td.getExtendedType().getProducedTypeName();
}
}
if (dec instanceof Value && !isVariable(dec) ||
dec instanceof Method) {
description += getInitialValueDescription(dec, cpc);
}
return HTML.highlightLine(description);
}
private static void appendJavadoc(Declaration model, IProject project,
StringBuilder buffer, Node node) {
try {
appendJavadoc(getJavaElement(model), buffer);
}
catch (JavaModelException jme) {
jme.printStackTrace();
}
}
private static void appendDocAnnotationContent(Tree.AnnotationList annotationList,
StringBuilder documentation, Scope linkScope) {
if (annotationList!=null) {
AnonymousAnnotation aa = annotationList.getAnonymousAnnotation();
if (aa!=null) {
documentation.append(markdown(aa.getStringLiteral().getText(),
linkScope, annotationList.getUnit()));
// HTML.addImageAndLabel(documentation, null,
// HTML.fileUrl("toc_obj.gif").toExternalForm(),
// 16, 16,
// markdown(aa.getStringLiteral().getText(),
// linkScope, annotationList.getUnit()),
// 20, 0);
}
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("doc".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (!args.isEmpty()) {
Tree.PositionalArgument a = args.get(0);
if (a instanceof Tree.ListedArgument) {
String text = ((Tree.ListedArgument) a).getExpression()
.getTerm().getText();
if (text!=null) {
documentation.append(markdown(text, linkScope,
annotationList.getUnit()));
}
}
}
}
}
}
}
}
}
private static void appendDeprecatedAnnotationContent(Tree.AnnotationList annotationList,
StringBuilder documentation, Scope linkScope) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("deprecated".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (!args.isEmpty()) {
Tree.PositionalArgument a = args.get(0);
if (a instanceof Tree.ListedArgument) {
String text = ((Tree.ListedArgument) a).getExpression()
.getTerm().getText();
if (text!=null) {
documentation.append(markdown("_(This is a deprecated program element.)_\n\n" + text,
linkScope, annotationList.getUnit()));
}
}
}
}
}
}
}
}
}
private static void appendSeeAnnotationContent(Tree.AnnotationList annotationList,
StringBuilder documentation) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("see".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
StringBuilder sb = new StringBuilder();
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
for (Tree.PositionalArgument arg: args) {
if (arg instanceof Tree.ListedArgument) {
Tree.Term term = ((Tree.ListedArgument) arg).getExpression().getTerm();
if (term instanceof Tree.MetaLiteral) {
Declaration dec = ((Tree.MetaLiteral) term).getDeclaration();
if (dec!=null) {
String dn = dec.getName();
if (dec.isClassOrInterfaceMember()) {
dn = ((ClassOrInterface) dec.getContainer()).getName() + "." + dn;
}
if (sb.length()!=0) sb.append(", ");
sb.append("<tt><a "+HTML.link(dec)+">"+dn+"</a></tt>");
}
}
}
}
if (sb.length()!=0) {
HTML.addImageAndLabel(documentation, null,
HTML.fileUrl("link_obj.gif"/*getIcon(dec)*/).toExternalForm(),
16, 16,
"see " + sb + ".",
20, 2);
}
}
}
}
}
}
}
private static void appendThrowAnnotationContent(Tree.AnnotationList annotationList,
StringBuilder documentation, Scope linkScope) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("throws".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (args.isEmpty()) continue;
Tree.PositionalArgument typeArg = args.get(0);
Tree.PositionalArgument textArg = args.size()>1 ? args.get(1) : null;
if (typeArg instanceof Tree.ListedArgument &&
(textArg==null || textArg instanceof Tree.ListedArgument)) {
Tree.Term typeArgTerm = ((Tree.ListedArgument) typeArg).getExpression().getTerm();
Tree.Term textArgTerm = textArg==null ? null : ((Tree.ListedArgument) textArg).getExpression().getTerm();
String text = textArgTerm instanceof Tree.StringLiteral ?
textArgTerm.getText() : "";
if (typeArgTerm instanceof Tree.MetaLiteral) {
Declaration dec = ((Tree.MetaLiteral) typeArgTerm).getDeclaration();
if (dec!=null) {
String dn = dec.getName();
if (typeArgTerm instanceof Tree.QualifiedMemberOrTypeExpression) {
Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) typeArgTerm).getPrimary();
if (p instanceof Tree.MemberOrTypeExpression) {
dn = ((Tree.MemberOrTypeExpression) p).getDeclaration().getName()
+ "." + dn;
}
}
HTML.addImageAndLabel(documentation, dec,
HTML.fileUrl("ihigh_obj.gif"/*getIcon(dec)*/).toExternalForm(),
16, 16,
"throws <tt><a "+HTML.link(dec)+">"+dn+"</a></tt>" +
markdown(text, linkScope, annotationList.getUnit()),
20, 2);
}
}
}
}
}
}
}
}
}
private static String markdown(String text, final Scope linkScope, final Unit unit) {
if (text == null || text.isEmpty()) {
return text;
}
Builder builder = Configuration.builder().forceExtentedProfile();
builder.setCodeBlockEmitter(new CeylonBlockEmitter());
if (linkScope!=null && unit!=null) {
builder.setSpecialLinkEmitter(new CeylonSpanEmitter(linkScope, unit));
}
else {
builder.setSpecialLinkEmitter(new UnlinkedSpanEmitter());
}
return Processor.process(text, builder.build());
}
private static Scope resolveScope(Declaration decl) {
if (decl == null) {
return null;
}
else if (decl instanceof Scope) {
return (Scope) decl;
}
else {
return decl.getContainer();
}
}
static Module resolveModule(Scope scope) {
if (scope == null) {
return null;
}
else if (scope instanceof Package) {
return ((Package) scope).getModule();
}
else {
return resolveModule(scope.getContainer());
}
}
/**
* Creates the "enriched" control.
*/
private final class PresenterControlCreator extends AbstractReusableInformationControlCreator {
private final DocumentationHover docHover;
PresenterControlCreator(DocumentationHover docHover) {
this.docHover = docHover;
}
@Override
public IInformationControl doCreateInformationControl(Shell parent) {
if (isAvailable(parent)) {
ToolBarManager tbm = new ToolBarManager(SWT.FLAT);
BrowserInformationControl control = new BrowserInformationControl(parent,
APPEARANCE_JAVADOC_FONT, tbm);
final BackAction backAction = new BackAction(control);
backAction.setEnabled(false);
tbm.add(backAction);
final ForwardAction forwardAction = new ForwardAction(control);
tbm.add(forwardAction);
forwardAction.setEnabled(false);
//final ShowInJavadocViewAction showInJavadocViewAction= new ShowInJavadocViewAction(iControl);
//tbm.add(showInJavadocViewAction);
final OpenDeclarationAction openDeclarationAction = new OpenDeclarationAction(control);
tbm.add(openDeclarationAction);
// final SimpleSelectionProvider selectionProvider = new SimpleSelectionProvider();
//TODO: an action to open the generated ceylondoc
// from the doc archive, in a browser window
/*if (fSite != null) {
OpenAttachedJavadocAction openAttachedJavadocAction= new OpenAttachedJavadocAction(fSite);
openAttachedJavadocAction.setSpecialSelectionProvider(selectionProvider);
openAttachedJavadocAction.setImageDescriptor(DESC_ELCL_OPEN_BROWSER);
openAttachedJavadocAction.setDisabledImageDescriptor(DESC_DLCL_OPEN_BROWSER);
selectionProvider.addSelectionChangedListener(openAttachedJavadocAction);
selectionProvider.setSelection(new StructuredSelection());
tbm.add(openAttachedJavadocAction);
}*/
IInputChangedListener inputChangeListener = new IInputChangedListener() {
public void inputChanged(Object newInput) {
backAction.update();
forwardAction.update();
// if (newInput == null) {
// selectionProvider.setSelection(new StructuredSelection());
// }
// else
boolean isDeclaration = false;
if (newInput instanceof CeylonBrowserInput) {
// Object inputElement = ((CeylonBrowserInput) newInput).getInputElement();
// selectionProvider.setSelection(new StructuredSelection(inputElement));
//showInJavadocViewAction.setEnabled(isJavaElementInput);
isDeclaration = ((CeylonBrowserInput) newInput).getAddress()!=null;
}
openDeclarationAction.setEnabled(isDeclaration);
}
};
control.addInputChangeListener(inputChangeListener);
tbm.update(true);
docHover.addLinkListener(control);
return control;
}
else {
return new DefaultInformationControl(parent, true);
}
}
}
private final class HoverControlCreator extends AbstractReusableInformationControlCreator {
private final DocumentationHover docHover;
private String statusLineMessage;
private final IInformationControlCreator enrichedControlCreator;
HoverControlCreator(DocumentationHover docHover,
IInformationControlCreator enrichedControlCreator,
String statusLineMessage) {
this.docHover = docHover;
this.enrichedControlCreator = enrichedControlCreator;
this.statusLineMessage = statusLineMessage;
}
@Override
public IInformationControl doCreateInformationControl(Shell parent) {
if (enrichedControlCreator!=null && isAvailable(parent)) {
BrowserInformationControl control = new BrowserInformationControl(parent,
APPEARANCE_JAVADOC_FONT, statusLineMessage) {
@Override
public IInformationControlCreator getInformationPresenterControlCreator() {
return enrichedControlCreator;
}
};
if (docHover!=null) {
docHover.addLinkListener(control);
}
return control;
}
else {
return new DefaultInformationControl(parent, statusLineMessage);
}
}
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_hover_DocumentationHover.java |
1,516 | public class ScriptMap {
public static final String CLASS = Tokens.makeNamespace(ScriptMap.class) + ".class";
public static final String SCRIPT_PATH = Tokens.makeNamespace(ScriptMap.class) + ".scriptPath";
public static final String SCRIPT_ARGS = Tokens.makeNamespace(ScriptMap.class) + ".scriptArgs";
private static final String ARGS = "args";
private static final String V = "v";
private static final String SETUP_ARGS = "setup(args)";
private static final String MAP_V_ARGS = "map(v,args)";
private static final String CLEANUP_ARGS = "cleanup(args)";
public static Configuration createConfiguration(final String scriptUri, final String... args) {
Configuration configuration = new EmptyConfiguration();
configuration.set(SCRIPT_PATH, scriptUri);
configuration.setStrings(SCRIPT_ARGS, args);
return configuration;
}
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private final ScriptEngine engine = new FaunusGremlinScriptEngine();
private SafeMapperOutputs outputs;
private Text textWritable = new Text();
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
final FileSystem fs = FileSystem.get(context.getConfiguration());
try {
this.engine.eval(new InputStreamReader(fs.open(new Path(context.getConfiguration().get(SCRIPT_PATH)))));
this.engine.put(ARGS, context.getConfiguration().getStrings(SCRIPT_ARGS));
this.engine.eval(SETUP_ARGS);
} catch (Exception e) {
throw new InterruptedException(e.getMessage());
}
this.outputs = new SafeMapperOutputs(context);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
if (value.hasPaths()) {
final Object result;
try {
this.engine.put(V, value);
result = engine.eval(MAP_V_ARGS);
} catch (Exception e) {
throw new InterruptedException(e.getMessage());
}
this.textWritable.set((null == result) ? Tokens.NULL : result.toString());
this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), this.textWritable);
}
this.outputs.write(Tokens.GRAPH, NullWritable.get(), value);
}
@Override
public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
try {
this.engine.eval(CLEANUP_ARGS);
} catch (Exception e) {
throw new InterruptedException(e.getMessage());
}
this.outputs.close();
}
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_ScriptMap.java |
1,964 | public class MapValuesRequest extends AllPartitionsClientRequest implements Portable, RetryableRequest, SecureRequest {
private String name;
public MapValuesRequest() {
}
public MapValuesRequest(String name) {
this.name = name;
}
@Override
protected OperationFactory createOperationFactory() {
return new MapValuesOperationFactory(name);
}
@Override
protected Object reduce(Map<Integer, Object> results) {
List<Data> values = new ArrayList<Data>();
MapService mapService = getService();
for (Object result : results.values()) {
values.addAll(((MapValueCollection) mapService.toObject(result)).getValues());
}
return new MapValueCollection(values);
}
public String getServiceName() {
return MapService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return MapPortableHook.F_ID;
}
public int getClassId() {
return MapPortableHook.VALUES;
}
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
}
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
}
public Permission getRequiredPermission() {
return new MapPermission(name, ActionConstants.ACTION_READ);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_client_MapValuesRequest.java |
473 | makeDbCall(databaseDocumentTxOne, new ODocumentHelper.ODbRelatedCall<Object>() {
public Object call() {
doc1.reset();
doc1.fromStream(buffer1.buffer);
return null;
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java |
973 | execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
TransportResponseOptions options = TransportResponseOptions.options().withCompress(transportCompress());
try {
channel.sendResponse(response, options);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response", e);
}
}
}); | 0true
| src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java |
902 | final class ConditionInfo implements DataSerializable {
private String conditionId;
private Map<ConditionWaiter, ConditionWaiter> waiters = new HashMap<ConditionWaiter, ConditionWaiter>(2);
public ConditionInfo() {
}
public ConditionInfo(String conditionId) {
this.conditionId = conditionId;
}
public boolean addWaiter(String caller, long threadId) {
ConditionWaiter waiter = new ConditionWaiter(caller, threadId);
return waiters.put(waiter, waiter) == null;
}
public boolean removeWaiter(String caller, long threadId) {
ConditionWaiter waiter = new ConditionWaiter(caller, threadId);
return waiters.remove(waiter) != null;
}
public String getConditionId() {
return conditionId;
}
public int getAwaitCount() {
return waiters.size();
}
public boolean startWaiter(String caller, long threadId) {
ConditionWaiter key = new ConditionWaiter(caller, threadId);
ConditionWaiter waiter = waiters.get(key);
if (waiter == null) {
throw new IllegalStateException();
}
if (waiter.started) {
return false;
} else {
waiter.started = true;
return true;
}
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(conditionId);
int len = waiters.size();
out.writeInt(len);
if (len > 0) {
for (ConditionWaiter w : waiters.values()) {
out.writeUTF(w.caller);
out.writeLong(w.threadId);
}
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
conditionId = in.readUTF();
int len = in.readInt();
if (len > 0) {
for (int i = 0; i < len; i++) {
ConditionWaiter waiter = new ConditionWaiter(in.readUTF(), in.readLong());
waiters.put(waiter, waiter);
}
}
}
private static class ConditionWaiter {
private final String caller;
private final long threadId;
private transient boolean started;
ConditionWaiter(String caller, long threadId) {
this.caller = caller;
this.threadId = threadId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConditionWaiter that = (ConditionWaiter) o;
if (threadId != that.threadId) {
return false;
}
if (caller != null ? !caller.equals(that.caller) : that.caller != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = caller != null ? caller.hashCode() : 0;
result = 31 * result + (int) (threadId ^ (threadId >>> 32));
return result;
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_ConditionInfo.java |
613 | public class CommonStatsFlags implements Streamable, Cloneable {
public final static CommonStatsFlags ALL = new CommonStatsFlags().all();
public final static CommonStatsFlags NONE = new CommonStatsFlags().clear();
private EnumSet<Flag> flags = EnumSet.allOf(Flag.class);
private String[] types = null;
private String[] groups = null;
private String[] fieldDataFields = null;
private String[] completionDataFields = null;
/**
* @param flags flags to set. If no flags are supplied, default flags will be set.
*/
public CommonStatsFlags(Flag... flags) {
if (flags.length > 0) {
clear();
for (Flag f : flags) {
this.flags.add(f);
}
}
}
/**
* Sets all flags to return all stats.
*/
public CommonStatsFlags all() {
flags = EnumSet.allOf(Flag.class);
types = null;
groups = null;
fieldDataFields = null;
completionDataFields = null;
return this;
}
/**
* Clears all stats.
*/
public CommonStatsFlags clear() {
flags = EnumSet.noneOf(Flag.class);
types = null;
groups = null;
fieldDataFields = null;
completionDataFields = null;
return this;
}
public boolean anySet() {
return !flags.isEmpty();
}
public Flag[] getFlags() {
return flags.toArray(new Flag[flags.size()]);
}
/**
* Document types to return stats for. Mainly affects {@link Flag#Indexing} when
* enabled, returning specific indexing stats for those types.
*/
public CommonStatsFlags types(String... types) {
this.types = types;
return this;
}
/**
* Document types to return stats for. Mainly affects {@link Flag#Indexing} when
* enabled, returning specific indexing stats for those types.
*/
public String[] types() {
return this.types;
}
/**
* Sets specific search group stats to retrieve the stats for. Mainly affects search
* when enabled.
*/
public CommonStatsFlags groups(String... groups) {
this.groups = groups;
return this;
}
public String[] groups() {
return this.groups;
}
/**
* Sets specific search group stats to retrieve the stats for. Mainly affects search
* when enabled.
*/
public CommonStatsFlags fieldDataFields(String... fieldDataFields) {
this.fieldDataFields = fieldDataFields;
return this;
}
public String[] fieldDataFields() {
return this.fieldDataFields;
}
public CommonStatsFlags completionDataFields(String... completionDataFields) {
this.completionDataFields = completionDataFields;
return this;
}
public String[] completionDataFields() {
return this.completionDataFields;
}
public boolean isSet(Flag flag) {
return flags.contains(flag);
}
boolean unSet(Flag flag) {
return flags.remove(flag);
}
void set(Flag flag) {
flags.add(flag);
}
public CommonStatsFlags set(Flag flag, boolean add) {
if (add) {
set(flag);
} else {
unSet(flag);
}
return this;
}
public static CommonStatsFlags readCommonStatsFlags(StreamInput in) throws IOException {
CommonStatsFlags flags = new CommonStatsFlags();
flags.readFrom(in);
return flags;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
long longFlags = 0;
for (Flag flag : flags) {
longFlags |= (1 << flag.ordinal());
}
out.writeLong(longFlags);
out.writeStringArrayNullable(types);
out.writeStringArrayNullable(groups);
out.writeStringArrayNullable(fieldDataFields);
out.writeStringArrayNullable(completionDataFields);
}
@Override
public void readFrom(StreamInput in) throws IOException {
final long longFlags = in.readLong();
flags.clear();
for (Flag flag : Flag.values()) {
if ((longFlags & (1 << flag.ordinal())) != 0) {
flags.add(flag);
}
}
types = in.readStringArray();
groups = in.readStringArray();
fieldDataFields = in.readStringArray();
completionDataFields = in.readStringArray();
}
@Override
public CommonStatsFlags clone() {
try {
CommonStatsFlags cloned = (CommonStatsFlags) super.clone();
cloned.flags = flags.clone();
return cloned;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
public static enum Flag {
// Do not change the order of these flags we use
// the ordinal for encoding! Only append to the end!
Store("store"),
Indexing("indexing"),
Get("get"),
Search("search"),
Merge("merge"),
Flush("flush"),
Refresh("refresh"),
FilterCache("filter_cache"),
IdCache("id_cache"),
FieldData("fielddata"),
Docs("docs"),
Warmer("warmer"),
Percolate("percolate"),
Completion("completion"),
Segments("segments"),
Translog("translog");
private final String restName;
Flag(String restName) {
this.restName = restName;
}
public String getRestName() {
return restName;
}
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_stats_CommonStatsFlags.java |
4,964 | public static PathTrie.Decoder REST_DECODER = new PathTrie.Decoder() {
@Override
public String decode(String value) {
return RestUtils.decodeComponent(value);
}
}; | 1no label
| src_main_java_org_elasticsearch_rest_support_RestUtils.java |
1,208 | public interface PartitioningStrategy<K> {
/**
* Returns the key object that will be used by Hazelcast to specify the partition.
*
* @param key actual key object
* @return partition key object or null to fallback to default partition calculation
*/
Object getPartitionKey(K key);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_PartitioningStrategy.java |
1,523 | public final class TerminatedLifecycleService implements LifecycleService {
@Override
public boolean isRunning() {
return false;
}
@Override
public void shutdown() {
}
@Override
public void terminate() {
}
@Override
public String addLifecycleListener(LifecycleListener lifecycleListener) {
throw new HazelcastInstanceNotActiveException();
}
@Override
public boolean removeLifecycleListener(String registrationId) {
throw new HazelcastInstanceNotActiveException();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_instance_TerminatedLifecycleService.java |
1,595 | public class ServerClusterLocalInsertTest extends AbstractServerClusterInsertTest {
protected String getDatabaseURL(final ServerRun server) {
return "local:" + server.getDatabasePath(getDatabaseName());
}
} | 0true
| distributed_src_test_java_com_orientechnologies_orient_server_distributed_ServerClusterLocalInsertTest.java |
1,879 | public abstract class PrivateModule implements Module {
/**
* Like abstract module, the binder of the current private module
*/
private PrivateBinder binder;
public final synchronized void configure(Binder binder) {
checkState(this.binder == null, "Re-entry is not allowed.");
// Guice treats PrivateModules specially and passes in a PrivateBinder automatically.
this.binder = (PrivateBinder) binder.skipSources(PrivateModule.class);
try {
configure();
} finally {
this.binder = null;
}
}
/**
* Creates bindings and other configurations private to this module. Use {@link #expose(Class)
* expose()} to make the bindings in this module available externally.
*/
protected abstract void configure();
/**
* Makes the binding for {@code key} available to other modules and the injector.
*/
protected final <T> void expose(Key<T> key) {
binder.expose(key);
}
/**
* Makes a binding for {@code type} available to other modules and the injector. Use {@link
* AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a
* binding annotation.
*/
protected final AnnotatedElementBuilder expose(Class<?> type) {
return binder.expose(type);
}
/**
* Makes a binding for {@code type} available to other modules and the injector. Use {@link
* AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a
* binding annotation.
*/
protected final AnnotatedElementBuilder expose(TypeLiteral<?> type) {
return binder.expose(type);
}
// everything below is copied from AbstractModule
/**
* Returns the current binder.
*/
protected final PrivateBinder binder() {
return binder;
}
/**
* @see Binder#bindScope(Class, Scope)
*/
protected final void bindScope(Class<? extends Annotation> scopeAnnotation, Scope scope) {
binder.bindScope(scopeAnnotation, scope);
}
/**
* @see Binder#bind(Key)
*/
protected final <T> LinkedBindingBuilder<T> bind(Key<T> key) {
return binder.bind(key);
}
/**
* @see Binder#bind(TypeLiteral)
*/
protected final <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) {
return binder.bind(typeLiteral);
}
/**
* @see Binder#bind(Class)
*/
protected final <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz) {
return binder.bind(clazz);
}
/**
* @see Binder#bindConstant()
*/
protected final AnnotatedConstantBindingBuilder bindConstant() {
return binder.bindConstant();
}
/**
* @see Binder#install(Module)
*/
protected final void install(Module module) {
binder.install(module);
}
/**
* @see Binder#addError(String, Object[])
*/
protected final void addError(String message, Object... arguments) {
binder.addError(message, arguments);
}
/**
* @see Binder#addError(Throwable)
*/
protected final void addError(Throwable t) {
binder.addError(t);
}
/**
* @see Binder#addError(Message)
*/
protected final void addError(Message message) {
binder.addError(message);
}
/**
* @see Binder#requestInjection(Object)
*/
protected final void requestInjection(Object instance) {
binder.requestInjection(instance);
}
/**
* @see Binder#requestStaticInjection(Class[])
*/
protected final void requestStaticInjection(Class<?>... types) {
binder.requestStaticInjection(types);
}
/**
* Instructs Guice to require a binding to the given key.
*/
protected final void requireBinding(Key<?> key) {
binder.getProvider(key);
}
/**
* Instructs Guice to require a binding to the given type.
*/
protected final void requireBinding(Class<?> type) {
binder.getProvider(type);
}
/**
* @see Binder#getProvider(Key)
*/
protected final <T> Provider<T> getProvider(Key<T> key) {
return binder.getProvider(key);
}
/**
* @see Binder#getProvider(Class)
*/
protected final <T> Provider<T> getProvider(Class<T> type) {
return binder.getProvider(type);
}
/**
* @see Binder#convertToTypes(org.elasticsearch.common.inject.matcher.Matcher, org.elasticsearch.common.inject.spi.TypeConverter)
*/
protected final void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeConverter converter) {
binder.convertToTypes(typeMatcher, converter);
}
/**
* @see Binder#currentStage()
*/
protected final Stage currentStage() {
return binder.currentStage();
}
/**
* @see Binder#getMembersInjector(Class)
*/
protected <T> MembersInjector<T> getMembersInjector(Class<T> type) {
return binder.getMembersInjector(type);
}
/**
* @see Binder#getMembersInjector(TypeLiteral)
*/
protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) {
return binder.getMembersInjector(type);
}
/**
* @see Binder#bindListener(org.elasticsearch.common.inject.matcher.Matcher, org.elasticsearch.common.inject.spi.TypeListener)
*/
protected void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher,
TypeListener listener) {
binder.bindListener(typeMatcher, listener);
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_PrivateModule.java |
1,225 | addOperation(operations, new Runnable() {
public void run() {
IQueue q = hazelcast.getQueue("myQ");
try {
q.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, 10); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
4,836 | public class RestGetFieldMappingAction extends BaseRestHandler {
@Inject
public RestGetFieldMappingAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_mapping/field/{fields}", this);
controller.registerHandler(GET, "/_mapping/{type}/field/{fields}", this);
controller.registerHandler(GET, "/{index}/_mapping/field/{fields}", this);
controller.registerHandler(GET, "/{index}/{type}/_mapping/field/{fields}", this);
controller.registerHandler(GET, "/{index}/_mapping/{type}/field/{fields}", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
final String[] types = request.paramAsStringArrayOrEmptyIfAll("type");
final String[] fields = Strings.splitStringByCommaToArray(request.param("fields"));
GetFieldMappingsRequest getMappingsRequest = new GetFieldMappingsRequest();
getMappingsRequest.indices(indices).types(types).fields(fields).includeDefaults(request.paramAsBoolean("include_defaults", false));
getMappingsRequest.indicesOptions(IndicesOptions.fromRequest(request, getMappingsRequest.indicesOptions()));
getMappingsRequest.local(request.paramAsBoolean("local", getMappingsRequest.local()));
client.admin().indices().getFieldMappings(getMappingsRequest, new ActionListener<GetFieldMappingsResponse>() {
@SuppressWarnings("unchecked")
@Override
public void onResponse(GetFieldMappingsResponse response) {
try {
ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex = response.mappings();
boolean isPossibleSingleFieldRequest = indices.length == 1 && types.length == 1 && fields.length == 1;
if (isPossibleSingleFieldRequest && isFieldMappingMissingField(mappingsByIndex)) {
channel.sendResponse(new XContentRestResponse(request, OK, emptyBuilder(request)));
return;
}
RestStatus status = OK;
if (mappingsByIndex.isEmpty() && fields.length > 0) {
status = NOT_FOUND;
}
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
channel.sendResponse(new XContentRestResponse(request, status, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new XContentThrowableRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
/**
*
* Helper method to find out if the only included fieldmapping metadata is typed NULL, which means
* that type and index exist, but the field did not
*/
private boolean isFieldMappingMissingField(ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex) throws IOException {
if (mappingsByIndex.size() != 1) {
return false;
}
for (ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>> value : mappingsByIndex.values()) {
for (ImmutableMap<String, FieldMappingMetaData> fieldValue : value.values()) {
for (Map.Entry<String, FieldMappingMetaData> fieldMappingMetaDataEntry : fieldValue.entrySet()) {
if (fieldMappingMetaDataEntry.getValue().isNull()) {
return true;
}
}
}
}
return false;
}
} | 1no label
| src_main_java_org_elasticsearch_rest_action_admin_indices_mapping_get_RestGetFieldMappingAction.java |
3,758 | return new FilterAtomicReader(reader) {
@Override
public FieldInfos getFieldInfos() {
return newFieldInfos;
}
@Override
public NumericDocValues getNumericDocValues(String field) throws IOException {
if (VersionFieldMapper.NAME.equals(field)) {
return versionValues;
}
return super.getNumericDocValues(field);
}
@Override
public Bits getDocsWithField(String field) throws IOException {
return new Bits.MatchAllBits(in.maxDoc());
}
}; | 0true
| src_main_java_org_elasticsearch_index_merge_policy_IndexUpgraderMergePolicy.java |
2,551 | public interface Discovery extends LifecycleComponent<Discovery> {
final ClusterBlock NO_MASTER_BLOCK = new ClusterBlock(2, "no master", true, true, RestStatus.SERVICE_UNAVAILABLE, ClusterBlockLevel.ALL);
public static final TimeValue DEFAULT_PUBLISH_TIMEOUT = TimeValue.timeValueSeconds(30);
DiscoveryNode localNode();
void addListener(InitialStateDiscoveryListener listener);
void removeListener(InitialStateDiscoveryListener listener);
String nodeDescription();
/**
* Here as a hack to solve dep injection problem...
*/
void setNodeService(@Nullable NodeService nodeService);
/**
* Another hack to solve dep injection problem..., note, this will be called before
* any start is called.
*/
void setAllocationService(AllocationService allocationService);
/**
* Publish all the changes to the cluster from the master (can be called just by the master). The publish
* process should not publish this state to the master as well! (the master is sending it...).
*
* The {@link AckListener} allows to keep track of the ack received from nodes, and verify whether
* they updated their own cluster state or not.
*/
void publish(ClusterState clusterState, AckListener ackListener);
public static interface AckListener {
void onNodeAck(DiscoveryNode node, @Nullable Throwable t);
void onTimeout();
}
} | 0true
| src_main_java_org_elasticsearch_discovery_Discovery.java |
32 | public class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new ValueIterator(getFirstEntry());
}
public Iterator<V> inverseIterator() {
return new ValueInverseIterator(getLastEntry());
}
@Override
public int size() {
return OMVRBTree.this.size();
}
@Override
public boolean contains(final Object o) {
return OMVRBTree.this.containsValue(o);
}
@Override
public boolean remove(final Object o) {
for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) {
if (valEquals(e.getValue(), o)) {
deleteEntry(e);
return true;
}
}
return false;
}
@Override
public void clear() {
OMVRBTree.this.clear();
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
3,747 | public class SimpleStringMappingTests extends ElasticsearchTestCase {
private static Settings DOC_VALUES_SETTINGS = ImmutableSettings.builder().put(FieldDataType.FORMAT_KEY, FieldDataType.DOC_VALUES_FORMAT_VALUE).build();
@Test
public void testLimit() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field").field("type", "string").field("ignore_above", 5).endObject().endObject()
.endObject().endObject().string();
DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "1234")
.endObject()
.bytes());
assertThat(doc.rootDoc().getField("field"), notNullValue());
doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "12345")
.endObject()
.bytes());
assertThat(doc.rootDoc().getField("field"), notNullValue());
doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "123456")
.endObject()
.bytes());
assertThat(doc.rootDoc().getField("field"), nullValue());
}
private void assertDefaultAnalyzedFieldType(IndexableFieldType fieldType) {
assertThat(fieldType.omitNorms(), equalTo(false));
assertThat(fieldType.indexOptions(), equalTo(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS));
assertThat(fieldType.storeTermVectors(), equalTo(false));
assertThat(fieldType.storeTermVectorOffsets(), equalTo(false));
assertThat(fieldType.storeTermVectorPositions(), equalTo(false));
assertThat(fieldType.storeTermVectorPayloads(), equalTo(false));
}
private void assertEquals(IndexableFieldType ft1, IndexableFieldType ft2) {
assertEquals(ft1.indexed(), ft2.indexed());
assertEquals(ft1.tokenized(), ft2.tokenized());
assertEquals(ft1.omitNorms(), ft2.omitNorms());
assertEquals(ft1.indexOptions(), ft2.indexOptions());
assertEquals(ft1.storeTermVectors(), ft2.storeTermVectors());
assertEquals(ft1.docValueType(), ft2.docValueType());
}
private void assertParseIdemPotent(IndexableFieldType expected, DocumentMapper mapper) throws Exception {
String mapping = mapper.toXContent(XContentFactory.jsonBuilder().startObject(), new ToXContent.MapParams(ImmutableMap.<String, String>of())).endObject().string();
mapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = mapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "2345")
.endObject()
.bytes());
assertEquals(expected, doc.rootDoc().getField("field").fieldType());
}
@Test
public void testDefaultsForAnalyzed() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field").field("type", "string").endObject().endObject()
.endObject().endObject().string();
DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "1234")
.endObject()
.bytes());
IndexableFieldType fieldType = doc.rootDoc().getField("field").fieldType();
assertDefaultAnalyzedFieldType(fieldType);
assertParseIdemPotent(fieldType, defaultMapper);
}
@Test
public void testDefaultsForNotAnalyzed() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field").field("type", "string").field("index", "not_analyzed").endObject().endObject()
.endObject().endObject().string();
DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "1234")
.endObject()
.bytes());
IndexableFieldType fieldType = doc.rootDoc().getField("field").fieldType();
assertThat(fieldType.omitNorms(), equalTo(true));
assertThat(fieldType.indexOptions(), equalTo(FieldInfo.IndexOptions.DOCS_ONLY));
assertThat(fieldType.storeTermVectors(), equalTo(false));
assertThat(fieldType.storeTermVectorOffsets(), equalTo(false));
assertThat(fieldType.storeTermVectorPositions(), equalTo(false));
assertThat(fieldType.storeTermVectorPayloads(), equalTo(false));
assertParseIdemPotent(fieldType, defaultMapper);
// now test it explicitly set
mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field").field("type", "string").field("index", "not_analyzed").startObject("norms").field("enabled", true).endObject().field("index_options", "freqs").endObject().endObject()
.endObject().endObject().string();
defaultMapper = MapperTestUtils.newParser().parse(mapping);
doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "1234")
.endObject()
.bytes());
fieldType = doc.rootDoc().getField("field").fieldType();
assertThat(fieldType.omitNorms(), equalTo(false));
assertThat(fieldType.indexOptions(), equalTo(FieldInfo.IndexOptions.DOCS_AND_FREQS));
assertThat(fieldType.storeTermVectors(), equalTo(false));
assertThat(fieldType.storeTermVectorOffsets(), equalTo(false));
assertThat(fieldType.storeTermVectorPositions(), equalTo(false));
assertThat(fieldType.storeTermVectorPayloads(), equalTo(false));
assertParseIdemPotent(fieldType, defaultMapper);
// also test the deprecated omit_norms
mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field").field("type", "string").field("index", "not_analyzed").field("omit_norms", false).endObject().endObject()
.endObject().endObject().string();
defaultMapper = MapperTestUtils.newParser().parse(mapping);
doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", "1234")
.endObject()
.bytes());
fieldType = doc.rootDoc().getField("field").fieldType();
assertThat(fieldType.omitNorms(), equalTo(false));
assertParseIdemPotent(fieldType, defaultMapper);
}
@Test
public void testTermVectors() throws Exception {
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("field1")
.field("type", "string")
.field("term_vector", "no")
.endObject()
.startObject("field2")
.field("type", "string")
.field("term_vector", "yes")
.endObject()
.startObject("field3")
.field("type", "string")
.field("term_vector", "with_offsets")
.endObject()
.startObject("field4")
.field("type", "string")
.field("term_vector", "with_positions")
.endObject()
.startObject("field5")
.field("type", "string")
.field("term_vector", "with_positions_offsets")
.endObject()
.startObject("field6")
.field("type", "string")
.field("term_vector", "with_positions_offsets_payloads")
.endObject()
.endObject()
.endObject().endObject().string();
DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field1", "1234")
.field("field2", "1234")
.field("field3", "1234")
.field("field4", "1234")
.field("field5", "1234")
.field("field6", "1234")
.endObject()
.bytes());
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectors(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field1").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field2").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorPositions(), equalTo(false));
assertThat(doc.rootDoc().getField("field3").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorOffsets(), equalTo(false));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field4").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field5").fieldType().storeTermVectorPayloads(), equalTo(false));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectors(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorOffsets(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorPositions(), equalTo(true));
assertThat(doc.rootDoc().getField("field6").fieldType().storeTermVectorPayloads(), equalTo(true));
}
public void testDocValues() throws Exception {
// doc values only work on non-analyzed content
final BuilderContext ctx = new BuilderContext(null, new ContentPath(1));
try {
new StringFieldMapper.Builder("anything").fieldDataSettings(DOC_VALUES_SETTINGS).build(ctx);
fail();
} catch (Exception e) { /* OK */ }
new StringFieldMapper.Builder("anything").tokenized(false).fieldDataSettings(DOC_VALUES_SETTINGS).build(ctx);
new StringFieldMapper.Builder("anything").index(false).fieldDataSettings(DOC_VALUES_SETTINGS).build(ctx);
assertFalse(new StringFieldMapper.Builder("anything").index(false).build(ctx).hasDocValues());
assertTrue(new StringFieldMapper.Builder("anything").index(false).fieldDataSettings(DOC_VALUES_SETTINGS).build(ctx).hasDocValues());
assertTrue(new StringFieldMapper.Builder("anything").index(false).docValues(true).build(ctx).hasDocValues());
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("str1")
.field("type", "string")
.startObject("fielddata")
.field("format", "fst")
.endObject()
.endObject()
.startObject("str2")
.field("type", "string")
.field("index", "not_analyzed")
.startObject("fielddata")
.field("format", "doc_values")
.endObject()
.endObject()
.endObject()
.endObject().endObject().string();
DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping);
ParsedDocument parsedDoc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("str1", "1234")
.field("str2", "1234")
.endObject()
.bytes());
final Document doc = parsedDoc.rootDoc();
assertEquals(null, docValuesType(doc, "str1"));
assertEquals(DocValuesType.SORTED_SET, docValuesType(doc, "str2"));
}
public static DocValuesType docValuesType(Document document, String fieldName) {
for (IndexableField field : document.getFields(fieldName)) {
if (field.fieldType().docValueType() != null) {
return field.fieldType().docValueType();
}
}
return null;
}
} | 0true
| src_test_java_org_elasticsearch_index_mapper_string_SimpleStringMappingTests.java |
455 | public class StaticArrayEntryTest {
private static final RelationCache cache = new RelationCache(Direction.OUT,5,105,"Hello");
private static final EntryMetaData[] metaSchema = { EntryMetaData.TIMESTAMP, EntryMetaData.TTL, EntryMetaData.VISIBILITY};
private static final Map<EntryMetaData,Object> metaData = new EntryMetaData.Map() {{
put(EntryMetaData.TIMESTAMP,Long.valueOf(101));
put(EntryMetaData.TTL, 42);
put(EntryMetaData.VISIBILITY,"SOS/K5a-89 SOS/sdf3");
}};
@Test
public void testArrayBuffer() {
WriteBuffer wb = new WriteByteBuffer(128);
wb.putInt(1).putInt(2).putInt(3).putInt(4);
int valuePos = wb.getPosition();
wb.putInt(5).putInt(6);
Entry entry = new StaticArrayEntry(wb.getStaticBuffer(),valuePos);
assertEquals(4*4,entry.getValuePosition());
assertEquals(6*4,entry.length());
assertTrue(entry.hasValue());
for (int i=1;i<=6;i++) assertEquals(i,entry.getInt((i-1)*4));
ReadBuffer rb = entry.asReadBuffer();
for (int i=1;i<=6;i++) assertEquals(i,rb.getInt());
assertFalse(rb.hasRemaining());
assertNull(entry.getCache());
entry.setCache(cache);
assertEquals(cache,entry.getCache());
rb = entry.getColumnAs(StaticBuffer.STATIC_FACTORY).asReadBuffer();
for (int i=1;i<=4;i++) assertEquals(i,rb.getInt());
assertFalse(rb.hasRemaining());
rb = entry.getValueAs(StaticBuffer.STATIC_FACTORY).asReadBuffer();
for (int i=5;i<=6;i++) assertEquals(i,rb.getInt());
assertFalse(rb.hasRemaining());
}
@Test
public void testReadWrite() {
WriteBuffer b = new WriteByteBuffer(10);
for (int i=1;i<4;i++) b.putByte((byte) i);
for (int i=1;i<4;i++) b.putShort((short) i);
for (int i=1;i<4;i++) b.putInt(i);
for (int i=1;i<4;i++) b.putLong(i);
for (int i=1;i<4;i++) b.putFloat(i);
for (int i=1;i<4;i++) b.putDouble(i);
for (int i=101;i<104;i++) b.putChar((char) i);
ReadBuffer r = b.getStaticBuffer().asReadBuffer();
assertEquals(1,r.getByte());
assertTrue(Arrays.equals(new byte[]{2,3},r.getBytes(2)));
assertEquals(1,r.getShort());
assertTrue(Arrays.equals(new short[]{2,3},r.getShorts(2)));
assertEquals(1,r.getInt());
assertEquals(2,r.getInt());
assertTrue(Arrays.equals(new int[]{3},r.getInts(1)));
assertEquals(1,r.getLong());
assertTrue(Arrays.equals(new long[]{2,3},r.getLongs(2)));
assertEquals(1.0,r.getFloat(),0.00001);
assertTrue(Arrays.equals(new float[]{2.0f,3.0f},r.getFloats(2)));
assertEquals(1,r.getDouble(),0.0001);
assertTrue(Arrays.equals(new double[]{2.0,3.0},r.getDoubles(2)));
assertEquals((char)101,r.getChar());
assertEquals((char)102,r.getChar());
assertTrue(Arrays.equals(new char[]{(char)103},r.getChars(1)));
}
@Test
public void testInversion() {
WriteBuffer wb = new WriteByteBuffer(20);
wb.putInt(1).putInt(2).putInt(3).putInt(4);
Entry entry = new StaticArrayEntry(wb.getStaticBufferFlipBytes(4,2*4),3*4);
ReadBuffer rb = entry.asReadBuffer();
assertEquals(1, rb.getInt());
assertEquals(2,rb.subrange(4,true).getInt());
assertEquals(~2, rb.getInt());
assertEquals(3, rb.getInt());
assertEquals(4,rb.getInt());
rb.movePositionTo(entry.getValuePosition());
assertEquals(4,rb.getInt());
}
@Test
public void testEntryList() {
Map<Integer,Long> entries = new HashMap<Integer,Long>();
for (int i=0;i<50;i++) entries.put(i*2+7,Math.round(Math.random()/2*Long.MAX_VALUE));
EntryList[] el = new EntryList[7];
el[0] = StaticArrayEntryList.ofBytes(entries.entrySet(), ByteEntryGetter.INSTANCE);
el[1] = StaticArrayEntryList.ofByteBuffer(entries.entrySet(), BBEntryGetter.INSTANCE);
el[2] = StaticArrayEntryList.ofStaticBuffer(entries.entrySet(), StaticEntryGetter.INSTANCE);
el[3] = StaticArrayEntryList.ofByteBuffer(entries.entrySet().iterator(), BBEntryGetter.INSTANCE);
el[4] = StaticArrayEntryList.ofStaticBuffer(entries.entrySet().iterator(), StaticEntryGetter.INSTANCE);
el[5] = StaticArrayEntryList.of(Iterables.transform(entries.entrySet(),new Function<Map.Entry<Integer, Long>, Entry>() {
@Nullable
@Override
public Entry apply(@Nullable Map.Entry<Integer, Long> entry) {
return StaticArrayEntry.ofByteBuffer(entry, BBEntryGetter.INSTANCE);
}
}));
el[6] = StaticArrayEntryList.of(Iterables.transform(entries.entrySet(),new Function<Map.Entry<Integer, Long>, Entry>() {
@Nullable
@Override
public Entry apply(@Nullable Map.Entry<Integer, Long> entry) {
return StaticArrayEntry.ofBytes(entry, ByteEntryGetter.INSTANCE);
}
}));
for (int i = 0; i < el.length; i++) {
assertEquals(entries.size(),el[i].size());
int num=0;
for (Entry e : el[i]) {
checkEntry(e,entries);
assertFalse(e.hasMetaData());
assertTrue(e.getMetaData().isEmpty());
assertNull(e.getCache());
e.setCache(cache);
num++;
}
assertEquals(entries.size(),num);
Iterator<Entry> iter = el[i].reuseIterator();
num=0;
while (iter.hasNext()) {
Entry e = iter.next();
checkEntry(e, entries);
assertFalse(e.hasMetaData());
assertTrue(e.getMetaData().isEmpty());
assertEquals(cache,e.getCache());
num++;
}
assertEquals(entries.size(),num);
}
}
/**
* Copied from above - the only difference is using schema instances and checking the schema
*/
@Test
public void testEntryListWithMetaSchema() {
Map<Integer,Long> entries = new HashMap<Integer,Long>();
for (int i=0;i<50;i++) entries.put(i*2+7,Math.round(Math.random()/2*Long.MAX_VALUE));
EntryList[] el = new EntryList[7];
el[0] = StaticArrayEntryList.ofBytes(entries.entrySet(), ByteEntryGetter.SCHEMA_INSTANCE);
el[1] = StaticArrayEntryList.ofByteBuffer(entries.entrySet(), BBEntryGetter.SCHEMA_INSTANCE);
el[2] = StaticArrayEntryList.ofStaticBuffer(entries.entrySet(), StaticEntryGetter.SCHEMA_INSTANCE);
el[3] = StaticArrayEntryList.ofByteBuffer(entries.entrySet().iterator(), BBEntryGetter.SCHEMA_INSTANCE);
el[4] = StaticArrayEntryList.ofStaticBuffer(entries.entrySet().iterator(), StaticEntryGetter.SCHEMA_INSTANCE);
el[5] = StaticArrayEntryList.of(Iterables.transform(entries.entrySet(),new Function<Map.Entry<Integer, Long>, Entry>() {
@Nullable
@Override
public Entry apply(@Nullable Map.Entry<Integer, Long> entry) {
return StaticArrayEntry.ofByteBuffer(entry, BBEntryGetter.SCHEMA_INSTANCE);
}
}));
el[6] = StaticArrayEntryList.of(Iterables.transform(entries.entrySet(),new Function<Map.Entry<Integer, Long>, Entry>() {
@Nullable
@Override
public Entry apply(@Nullable Map.Entry<Integer, Long> entry) {
return StaticArrayEntry.ofBytes(entry, ByteEntryGetter.SCHEMA_INSTANCE);
}
}));
for (int i = 0; i < el.length; i++) {
//System.out.println("Iteration: " + i);
assertEquals(entries.size(),el[i].size());
int num=0;
for (Entry e : el[i]) {
checkEntry(e,entries);
assertTrue(e.hasMetaData());
assertFalse(e.getMetaData().isEmpty());
assertEquals(metaData,e.getMetaData());
assertNull(e.getCache());
e.setCache(cache);
num++;
}
assertEquals(entries.size(),num);
Iterator<Entry> iter = el[i].reuseIterator();
num=0;
while (iter.hasNext()) {
Entry e = iter.next();
assertTrue(e.hasMetaData());
assertFalse(e.getMetaData().isEmpty());
assertEquals(metaData,e.getMetaData());
assertEquals(cache,e.getCache());
checkEntry(e, entries);
num++;
}
assertEquals(entries.size(),num);
}
}
@Test
public void testTTLMetadata() throws Exception {
WriteBuffer wb = new WriteByteBuffer(128);
wb.putInt(1).putInt(2).putInt(3).putInt(4);
int valuePos = wb.getPosition();
wb.putInt(5).putInt(6);
StaticArrayEntry entry = new StaticArrayEntry(wb.getStaticBuffer(),valuePos);
entry.setMetaData(EntryMetaData.TTL, 42);
assertEquals(42, entry.getMetaData().get(EntryMetaData.TTL));
}
private static void checkEntry(Entry e, Map<Integer,Long> entries) {
ReadBuffer rb = e.asReadBuffer();
int key = rb.getInt();
assertEquals(e.getValuePosition(),rb.getPosition());
assertTrue(e.hasValue());
long value = rb.getLong();
assertFalse(rb.hasRemaining());
assertEquals((long)entries.get(key),value);
rb = e.getColumnAs(StaticBuffer.STATIC_FACTORY).asReadBuffer();
assertEquals(key,rb.getInt());
assertFalse(rb.hasRemaining());
rb = e.getValueAs(StaticBuffer.STATIC_FACTORY).asReadBuffer();
assertEquals(value,rb.getLong());
assertFalse(rb.hasRemaining());
}
private static enum BBEntryGetter implements StaticArrayEntry.GetColVal<Map.Entry<Integer, Long>, ByteBuffer> {
INSTANCE, SCHEMA_INSTANCE;
@Override
public ByteBuffer getColumn(Map.Entry<Integer, Long> element) {
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(element.getKey()).flip();
return b;
}
@Override
public ByteBuffer getValue(Map.Entry<Integer, Long> element) {
ByteBuffer b = ByteBuffer.allocate(8);
b.putLong(element.getValue()).flip();
return b;
}
@Override
public EntryMetaData[] getMetaSchema(Map.Entry<Integer, Long> element) {
if (this==INSTANCE) return StaticArrayEntry.EMPTY_SCHEMA;
else return metaSchema;
}
@Override
public Object getMetaData(Map.Entry<Integer, Long> element, EntryMetaData meta) {
if (this==INSTANCE) throw new UnsupportedOperationException("Unsupported meta data: " + meta);
else return metaData.get(meta);
}
}
private static enum ByteEntryGetter implements StaticArrayEntry.GetColVal<Map.Entry<Integer, Long>, byte[]> {
INSTANCE, SCHEMA_INSTANCE;
@Override
public byte[] getColumn(Map.Entry<Integer, Long> element) {
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(element.getKey());
return b.array();
}
@Override
public byte[] getValue(Map.Entry<Integer, Long> element) {
ByteBuffer b = ByteBuffer.allocate(8);
b.putLong(element.getValue());
return b.array();
}
@Override
public EntryMetaData[] getMetaSchema(Map.Entry<Integer, Long> element) {
if (this==INSTANCE) return StaticArrayEntry.EMPTY_SCHEMA;
else return metaSchema;
}
@Override
public Object getMetaData(Map.Entry<Integer, Long> element, EntryMetaData meta) {
if (this==INSTANCE) throw new UnsupportedOperationException("Unsupported meta data: " + meta);
else return metaData.get(meta);
}
}
private static enum StaticEntryGetter implements StaticArrayEntry.GetColVal<Map.Entry<Integer, Long>, StaticBuffer> {
INSTANCE, SCHEMA_INSTANCE;
@Override
public StaticBuffer getColumn(Map.Entry<Integer, Long> element) {
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(element.getKey());
return StaticArrayBuffer.of(b.array());
}
@Override
public StaticBuffer getValue(Map.Entry<Integer, Long> element) {
ByteBuffer b = ByteBuffer.allocate(8);
b.putLong(element.getValue());
return StaticArrayBuffer.of(b.array());
}
@Override
public EntryMetaData[] getMetaSchema(Map.Entry<Integer, Long> element) {
if (this==INSTANCE) return StaticArrayEntry.EMPTY_SCHEMA;
else return metaSchema;
}
@Override
public Object getMetaData(Map.Entry<Integer, Long> element, EntryMetaData meta) {
if (this==INSTANCE) throw new UnsupportedOperationException("Unsupported meta data: " + meta);
else return metaData.get(meta);
}
}
} | 0true
| titan-test_src_test_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_StaticArrayEntryTest.java |
1,230 | public interface FulfillmentPricingService {
/**
* Called during the Pricing workflow to determine the cost for the {@link FulfillmentGroup}. This will loop through
* {@link #getProcessors()} and call {@link FulfillmentPricingProvider#calculateCostForFulfillmentGroup(FulfillmentGroup)}
* on the first processor that returns true from {@link FulfillmentPricingProvider#canCalculateCostForFulfillmentGroup(FulfillmentGroup)}
*
* @param fulfillmentGroup
* @return the updated </b>fulfillmentGroup</b> with its shippingPrice set
* @throws FulfillmentPriceException if <b>fulfillmentGroup</b> does not have a FulfillmentOption associated to it or
* if there was no processor found to calculate costs for <b>fulfillmentGroup</b>
* @see {@link FulfillmentPricingProvider}
*/
public FulfillmentGroup calculateCostForFulfillmentGroup(FulfillmentGroup fulfillmentGroup) throws FulfillmentPriceException;
/**
* This provides an estimation for a {@link FulfillmentGroup} with a {@link FulfillmentOption}. The main use case for this method
* is in a view cart controller that wants to provide estimations for different {@link FulfillmentOption}s before the user
* actually selects one. This uses {@link #getProviders()} to allow third-party integrations to respond to
* estimations, and returns the first processor that returns true from {@link FulfillmentPricingProvider#canCalculateCostForFulfillmentGroup(FulfillmentGroup, FulfillmentOption)}.
*
* @param fulfillmentGroup
* @param options
* @return the price estimation for a particular {@link FulfillmentGroup} with a candidate {@link FulfillmentOption}
* @throws FulfillmentPriceException if no processor was found to estimate costs for <b>fulfillmentGroup</b> with the given <b>option</b>
* @see {@link FulfillmentPricingProvider}
*/
public FulfillmentEstimationResponse estimateCostForFulfillmentGroup(FulfillmentGroup fulfillmentGroup, Set<FulfillmentOption> options) throws FulfillmentPriceException;
public List<FulfillmentPricingProvider> getProviders();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_FulfillmentPricingService.java |
220 | public class OConstants {
public static final String ORIENT_VERSION = "1.6.2";
public static final String ORIENT_URL = "www.orientechnologies.com";
public static String getVersion() {
final StringBuilder buffer = new StringBuilder();
buffer.append(OConstants.ORIENT_VERSION);
final String buildNumber = System.getProperty("orientdb.build.number");
if (buildNumber != null) {
buffer.append(" (build ");
buffer.append(buildNumber);
buffer.append(")");
}
return buffer.toString();
}
public static String getBuildNumber() {
final String buildNumber = System.getProperty("orientdb.build.number");
if (buildNumber == null)
return null;
return buildNumber;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_OConstants.java |
257 | public interface EmailTrackingClicks extends Serializable {
/**
* @return the emailId
*/
public abstract Long getId();
/**
* @param id the i to set
*/
public abstract void setId(Long id);
/**
* @return the dateClicked
*/
public abstract Date getDateClicked();
/**
* @param dateClicked the dateClicked to set
*/
public abstract void setDateClicked(Date dateClicked);
/**
* @return the destinationUri
*/
public abstract String getDestinationUri();
/**
* @param destinationUri the destinationUri to set
*/
public abstract void setDestinationUri(String destinationUri);
/**
* @return the queryString
*/
public abstract String getQueryString();
/**
* @param queryString the queryString to set
*/
public abstract void setQueryString(String queryString);
/**
* @return the emailTracking
*/
public abstract EmailTracking getEmailTracking();
/**
* @param emailTracking the emailTracking to set
*/
public abstract void setEmailTracking(EmailTracking emailTracking);
public abstract String getCustomerId();
/**
* @param customerId the customer to set
*/
public abstract void setCustomerId(String customerId);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_email_domain_EmailTrackingClicks.java |
293 | public class RefinementAnnotationImageProvider implements IAnnotationImageProvider {
private static Image DEFAULT = CeylonPlugin.getInstance()
.getImageRegistry().get(CEYLON_DEFAULT_REFINEMENT);
private static Image FORMAL = CeylonPlugin.getInstance()
.getImageRegistry().get(CEYLON_FORMAL_REFINEMENT);
@Override
public Image getManagedImage(Annotation annotation) {
RefinementAnnotation ra = (RefinementAnnotation) annotation;
return ra.getDeclaration().isFormal() ? FORMAL : DEFAULT;
}
@Override
public String getImageDescriptorId(Annotation annotation) {
return null;
}
@Override
public ImageDescriptor getImageDescriptor(String imageDescritporId) {
return null;
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_RefinementAnnotationImageProvider.java |
459 | executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
}
}
}, 2, EntryEventType.ADDED, 100, 0.75, map1, map2); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_replicatedmap_ClientReplicatedMapTest.java |
768 | public class SetReplicationOperation extends CollectionReplicationOperation {
public SetReplicationOperation() {
}
public SetReplicationOperation(Map<String, CollectionContainer> migrationData, int partitionId, int replicaIndex) {
super(migrationData, partitionId, replicaIndex);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
int mapSize = in.readInt();
migrationData = new HashMap<String, CollectionContainer>(mapSize);
for (int i = 0; i < mapSize; i++) {
String name = in.readUTF();
SetContainer container = new SetContainer();
container.readData(in);
migrationData.put(name, container);
}
}
@Override
public int getId() {
return CollectionDataSerializerHook.SET_REPLICATION;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_set_SetReplicationOperation.java |
1,260 | addOperation(operations, new Runnable() {
public void run() {
IMap map = hazelcast.getMap("myMap");
Iterator it = map.localKeySet(new SqlPredicate("name=" + random.nextInt(10000))).iterator();
while (it.hasNext()) {
it.next();
}
}
}, 10); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
1,264 | addOperation(operations, new Runnable() {
public void run() {
IMap map = hazelcast.getMap("myMap");
final CountDownLatch latch = new CountDownLatch(1);
EntryListener listener = new EntryAdapter() {
@Override
public void onEntryEvent(EntryEvent event) {
latch.countDown();
}
};
String id = map.addLocalEntryListener(listener);
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
map.removeEntryListener(id);
}
}, 1); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_AllTest.java |
2,517 | public class JsonXContentParser extends AbstractXContentParser {
final JsonParser parser;
public JsonXContentParser(JsonParser parser) {
this.parser = parser;
}
@Override
public XContentType contentType() {
return XContentType.JSON;
}
@Override
public Token nextToken() throws IOException {
return convertToken(parser.nextToken());
}
@Override
public void skipChildren() throws IOException {
parser.skipChildren();
}
@Override
public Token currentToken() {
return convertToken(parser.getCurrentToken());
}
@Override
public NumberType numberType() throws IOException {
return convertNumberType(parser.getNumberType());
}
@Override
public boolean estimatedNumberType() {
return true;
}
@Override
public String currentName() throws IOException {
return parser.getCurrentName();
}
@Override
protected boolean doBooleanValue() throws IOException {
return parser.getBooleanValue();
}
@Override
public String text() throws IOException {
return parser.getText();
}
@Override
public BytesRef bytes() throws IOException {
BytesRef bytes = new BytesRef();
UnicodeUtil.UTF16toUTF8(parser.getTextCharacters(), parser.getTextOffset(), parser.getTextLength(), bytes);
return bytes;
}
@Override
public Object objectText() throws IOException {
JsonToken currentToken = parser.getCurrentToken();
if (currentToken == JsonToken.VALUE_STRING) {
return text();
} else if (currentToken == JsonToken.VALUE_NUMBER_INT || currentToken == JsonToken.VALUE_NUMBER_FLOAT) {
return parser.getNumberValue();
} else if (currentToken == JsonToken.VALUE_TRUE) {
return Boolean.TRUE;
} else if (currentToken == JsonToken.VALUE_FALSE) {
return Boolean.FALSE;
} else if (currentToken == JsonToken.VALUE_NULL) {
return null;
} else {
return text();
}
}
@Override
public Object objectBytes() throws IOException {
JsonToken currentToken = parser.getCurrentToken();
if (currentToken == JsonToken.VALUE_STRING) {
return bytes();
} else if (currentToken == JsonToken.VALUE_NUMBER_INT || currentToken == JsonToken.VALUE_NUMBER_FLOAT) {
return parser.getNumberValue();
} else if (currentToken == JsonToken.VALUE_TRUE) {
return Boolean.TRUE;
} else if (currentToken == JsonToken.VALUE_FALSE) {
return Boolean.FALSE;
} else if (currentToken == JsonToken.VALUE_NULL) {
return null;
} else {
return bytes();
}
}
@Override
public boolean hasTextCharacters() {
return parser.hasTextCharacters();
}
@Override
public char[] textCharacters() throws IOException {
return parser.getTextCharacters();
}
@Override
public int textLength() throws IOException {
return parser.getTextLength();
}
@Override
public int textOffset() throws IOException {
return parser.getTextOffset();
}
@Override
public Number numberValue() throws IOException {
return parser.getNumberValue();
}
@Override
public short doShortValue() throws IOException {
return parser.getShortValue();
}
@Override
public int doIntValue() throws IOException {
return parser.getIntValue();
}
@Override
public long doLongValue() throws IOException {
return parser.getLongValue();
}
@Override
public float doFloatValue() throws IOException {
return parser.getFloatValue();
}
@Override
public double doDoubleValue() throws IOException {
return parser.getDoubleValue();
}
@Override
public byte[] binaryValue() throws IOException {
return parser.getBinaryValue();
}
@Override
public void close() {
try {
parser.close();
} catch (IOException e) {
// ignore
}
}
private NumberType convertNumberType(JsonParser.NumberType numberType) {
switch (numberType) {
case INT:
return NumberType.INT;
case LONG:
return NumberType.LONG;
case FLOAT:
return NumberType.FLOAT;
case DOUBLE:
return NumberType.DOUBLE;
}
throw new ElasticsearchIllegalStateException("No matching token for number_type [" + numberType + "]");
}
private Token convertToken(JsonToken token) {
if (token == null) {
return null;
}
switch (token) {
case FIELD_NAME:
return Token.FIELD_NAME;
case VALUE_FALSE:
case VALUE_TRUE:
return Token.VALUE_BOOLEAN;
case VALUE_STRING:
return Token.VALUE_STRING;
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
return Token.VALUE_NUMBER;
case VALUE_NULL:
return Token.VALUE_NULL;
case START_OBJECT:
return Token.START_OBJECT;
case END_OBJECT:
return Token.END_OBJECT;
case START_ARRAY:
return Token.START_ARRAY;
case END_ARRAY:
return Token.END_ARRAY;
case VALUE_EMBEDDED_OBJECT:
return Token.VALUE_EMBEDDED_OBJECT;
}
throw new ElasticsearchIllegalStateException("No matching token for json_token [" + token + "]");
}
} | 0true
| src_main_java_org_elasticsearch_common_xcontent_json_JsonXContentParser.java |
1,263 | threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() {
@Override
public void run() {
try {
if (!transportService.nodeConnected(listedNode)) {
try {
// if its one of hte actual nodes we will talk to, not to listed nodes, fully connect
if (nodes.contains(listedNode)) {
logger.trace("connecting to cluster node [{}]", listedNode);
transportService.connectToNode(listedNode);
} else {
// its a listed node, light connect to it...
logger.trace("connecting to listed node (light) [{}]", listedNode);
transportService.connectToNodeLight(listedNode);
}
} catch (Exception e) {
logger.debug("failed to connect to node [{}], ignoring...", e, listedNode);
latch.countDown();
return;
}
}
transportService.sendRequest(listedNode, ClusterStateAction.NAME,
Requests.clusterStateRequest()
.clear().nodes(true).local(true),
TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout),
new BaseTransportResponseHandler<ClusterStateResponse>() {
@Override
public ClusterStateResponse newInstance() {
return new ClusterStateResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(ClusterStateResponse response) {
clusterStateResponses.put(listedNode, response);
latch.countDown();
}
@Override
public void handleException(TransportException e) {
logger.info("failed to get local cluster state for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
});
} catch (Throwable e) {
logger.info("failed to get local cluster state info for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
}
}); | 0true
| src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.