Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
1,784 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class InterceptorTest extends HazelcastTestSupport {
@Test
public void testMapInterceptor() throws InterruptedException {
TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
Config cfg = new Config();
cfg.getMapConfig("default").setInMemoryFormat(InMemoryFormat.OBJECT);
HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(cfg);
HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(cfg);
final IMap<Object, Object> map = instance1.getMap("testMapInterceptor");
SimpleInterceptor interceptor = new SimpleInterceptor();
String id = map.addInterceptor(interceptor);
map.put(1, "New York");
map.put(2, "Istanbul");
map.put(3, "Tokyo");
map.put(4, "London");
map.put(5, "Paris");
map.put(6, "Cairo");
map.put(7, "Hong Kong");
try {
map.remove(1);
} catch (Exception ignore) {
}
try {
map.remove(2);
} catch (Exception ignore) {
}
assertEquals(map.size(), 6);
assertEquals(map.get(1), null);
assertEquals(map.get(2), "ISTANBUL:");
assertEquals(map.get(3), "TOKYO:");
assertEquals(map.get(4), "LONDON:");
assertEquals(map.get(5), "PARIS:");
assertEquals(map.get(6), "CAIRO:");
assertEquals(map.get(7), "HONG KONG:");
map.removeInterceptor(id);
map.put(8, "Moscow");
assertEquals(map.get(8), "Moscow");
assertEquals(map.get(1), null);
assertEquals(map.get(2), "ISTANBUL");
assertEquals(map.get(3), "TOKYO");
assertEquals(map.get(4), "LONDON");
assertEquals(map.get(5), "PARIS");
assertEquals(map.get(6), "CAIRO");
assertEquals(map.get(7), "HONG KONG");
}
static class SimpleInterceptor implements MapInterceptor, Serializable {
@Override
public Object interceptGet(Object value) {
if (value == null)
return null;
return value + ":";
}
@Override
public void afterGet(Object value) {
}
@Override
public Object interceptPut(Object oldValue, Object newValue) {
return newValue.toString().toUpperCase();
}
@Override
public void afterPut(Object value) {
}
@Override
public Object interceptRemove(Object removedValue) {
if (removedValue.equals("ISTANBUL"))
throw new RuntimeException("you can not remove this");
return removedValue;
}
@Override
public void afterRemove(Object value) {
}
}
@Test
public void testMapInterceptorOnNewMember() throws InterruptedException {
TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
Config cfg = new Config();
cfg.getMapConfig("default").setInMemoryFormat(InMemoryFormat.OBJECT);
HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(cfg);
IMap map = instance1.getMap("map");
for (int i = 0; i < 100; i++) {
map.put(i,i);
}
map.addInterceptor(new NegativeInterceptor());
for (int i = 0; i < 100; i++) {
assertEquals(i*-1, map.get(i));
}
HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(cfg);
for (int i = 0; i < 100; i++) {
assertEquals(i*-1, map.get(i));
}
}
static class NegativeInterceptor implements MapInterceptor, Serializable {
@Override
public Object interceptGet(Object value) {
return ((Integer)value)*-1;
}
@Override
public void afterGet(Object value) {
}
@Override
public Object interceptPut(Object oldValue, Object newValue) {
return newValue;
}
@Override
public void afterPut(Object value) {
}
@Override
public Object interceptRemove(Object removedValue) {
return removedValue;
}
@Override
public void afterRemove(Object value) {
}
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_InterceptorTest.java |
354 | public class ElasticsearchRunner extends DaemonRunner<ElasticsearchStatus> {
private final String homedir;
private static final Logger log =
LoggerFactory.getLogger(ElasticsearchRunner.class);
public static final String ES_PID_FILE = "/tmp/titan-test-es.pid";
public ElasticsearchRunner() {
this.homedir = ".";
}
public ElasticsearchRunner(String esHome) {
this.homedir = esHome;
}
@Override
protected String getDaemonShortName() {
return "Elasticsearch";
}
@Override
protected void killImpl(ElasticsearchStatus stat) throws IOException {
log.info("Killing {} pid {}...", getDaemonShortName(), stat.getPid());
runCommand("/bin/kill", String.valueOf(stat.getPid()));
log.info("Sent SIGTERM to {} pid {}", getDaemonShortName(), stat.getPid());
stat.getFile().delete();
log.info("Deleted {}", stat.getFile());
}
@Override
protected ElasticsearchStatus startImpl() throws IOException {
File data = new File(homedir + File.separator + "target" + File.separator + "es-data");
if (data.exists() && data.isDirectory()) {
log.info("Deleting {}", data);
FileUtils.deleteDirectory(data);
}
runCommand(homedir + File.separator + "bin/elasticsearch", "-d", "-p", ES_PID_FILE);
try {
// I should really retry parsing the pidfile in a loop up to some timeout
Thread.sleep(2000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return readStatusFromDisk();
}
@Override
protected ElasticsearchStatus readStatusFromDisk() {
return ElasticsearchStatus.read(ES_PID_FILE);
}
} | 0true
| titan-es_src_test_java_com_thinkaurelius_titan_diskstorage_es_ElasticsearchRunner.java |
1,524 | final class OJPAProperties extends Properties {
private static final long serialVersionUID = -8158054712863843518L;
public final static String URL = "javax.persistence.jdbc.url";
public final static String USER = "javax.persistence.jdbc.user";
public final static String PASSWORD = "javax.persistence.jdbc.password";
/**
* OrientDB specific
*/
public final static String ENTITY_CLASSES_PACKAGE = "com.orientdb.entityClasses";
public OJPAProperties() {
}
/**
* Checks properties
*
* @param properties
*/
public OJPAProperties(final Map<String, Object> properties) {
putAll(properties);
if (properties == null) {
throw new IllegalStateException("Map properties for entity manager should not be null");
}
if (!checkContainsValue(URL)) {
throw new IllegalStateException("URL propertiy for entity manager should not be null or empty");
}
if (!checkContainsValue(USER)) {
throw new IllegalStateException("User propertiy for entity manager should not be null or empty");
}
}
/**
* @return Unmodifiable Map of properties for use by the persistence provider.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<String, Object> getUnmodifiableProperties() {
return Collections.unmodifiableMap((Map) this);
}
public String getUser() {
return getProperty(USER);
}
public String getPassword() {
return getProperty(PASSWORD);
}
public String getURL() {
return getProperty(URL);
}
public String getEntityClasses() {
return getProperty(ENTITY_CLASSES_PACKAGE);
}
/**
* Optional
*
* @return true if key exists and value isn't empty
*/
public boolean isEntityClasses() {
return checkContainsValue(ENTITY_CLASSES_PACKAGE);
}
private boolean checkContainsValue(String property) {
if (!containsKey(property)) {
return false;
}
String value = (String) get(property);
return value != null && !value.isEmpty();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Entry<Object, Object> property : entrySet()) {
builder.append(',').append(property.getKey()).append('=').append(property.getValue());
}
return builder.toString();
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_jpa_OJPAProperties.java |
10 | static final class AsyncAcceptBoth<T,U> extends Async {
final T arg1;
final U arg2;
final BiAction<? super T,? super U> fn;
final CompletableFuture<Void> dst;
AsyncAcceptBoth(T arg1, U arg2,
BiAction<? super T,? super U> fn,
CompletableFuture<Void> dst) {
this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst;
}
public final boolean exec() {
CompletableFuture<Void> d; Throwable ex;
if ((d = this.dst) != null && d.result == null) {
try {
fn.accept(arg1, arg2);
ex = null;
} catch (Throwable rex) {
ex = rex;
}
d.internalComplete(null, ex);
}
return true;
}
private static final long serialVersionUID = 5232453952276885070L;
} | 0true
| src_main_java_jsr166e_CompletableFuture.java |
1,169 | public interface ISemaphore extends DistributedObject {
/**
* Returns the name of this ISemaphore instance.
*
* @return name of this instance
*/
public String getName();
/**
* Try to initialize this ISemaphore instance with given permit count
*
* @return true if initialization success
*/
public boolean init(int permits);
/**
* <p>Acquires a permit, if one is available and returns immediately,
* reducing the number of available permits by one.
* <p/>
* <p>If no permit is available then the current thread becomes
* disabled for thread scheduling purposes and lies dormant until
* one of three things happens:
* <ul>
* <li>Some other thread invokes one of the {@link #release} methods for this
* semaphore and the current thread is next to be assigned a permit;
* <li>This ISemaphore instance is destroyed; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread.
* </ul>
* <p>If the current thread:
* <ul>
* <li>has its interrupted status set on entry to this method; or
* <li>is {@linkplain Thread#interrupt interrupted} while waiting
* for a permit,
* </ul>
* then {@link InterruptedException} is thrown and the current thread's
* interrupted status is cleared.
*
* @throws InterruptedException if the current thread is interrupted
* @throws IllegalStateException if hazelcast instance is shutdown while waiting
*/
public void acquire() throws InterruptedException;
/**
* <p>Acquires the given number of permits, if they are available,
* and returns immediately, reducing the number of available permits
* by the given amount.
* <p/>
* <p>If insufficient permits are available then the current thread becomes
* disabled for thread scheduling purposes and lies dormant until
* one of three things happens:
* <ul>
* <li>Some other thread invokes one of the {@link #release() release}
* methods for this semaphore, the current thread is next to be assigned
* permits and the number of available permits satisfies this request;
* <li>This ISemaphore instance is destroyed; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread.
* </ul>
* <p/>
* <p>If the current thread:
* <ul>
* <li>has its interrupted status set on entry to this method; or
* <li>is {@linkplain Thread#interrupt interrupted} while waiting
* for a permit,
* </ul>
* then {@link InterruptedException} is thrown and the current thread's
* interrupted status is cleared.
*
* @param permits the number of permits to acquire
* @throws InterruptedException if the current thread is interrupted
* @throws IllegalArgumentException if {@code permits} is negative
* @throws IllegalStateException if hazelcast instance is shutdown while waiting
*/
public void acquire(int permits) throws InterruptedException;
/**
* Returns the current number of permits currently available in this semaphore.
* <p/>
* <ul><li>This method is typically used for debugging and testing purposes.
* </ul>
*
* @return the number of permits available in this semaphore
*/
public int availablePermits();
/**
* Acquires and returns all permits that are immediately available.
*
* @return the number of permits drained
*/
public int drainPermits();
/**
* Shrinks the number of available permits by the indicated
* reduction. This method differs from {@code acquire} in that it does not
* block waiting for permits to become available.
*
* @param reduction the number of permits to remove
* @throws IllegalArgumentException if {@code reduction} is negative
*/
public void reducePermits(int reduction);
/**
* Releases a permit, increasing the number of available permits by
* one. If any threads in the cluster are trying to acquire a permit,
* then one is selected and given the permit that was just released.
* <p/>
* There is no requirement that a thread that releases a permit must
* have acquired that permit by calling one of the {@link #acquire() acquire} methods.
* Correct usage of a semaphore is established by programming convention
* in the application.
*/
public void release();
/**
* Releases the given number of permits, increasing the number of
* available permits by that amount.
* <p/>
* There is no requirement that a thread that releases a permit must
* have acquired that permit by calling one of the {@link #acquire() acquire} methods.
* Correct usage of a semaphore is established by programming convention
* in the application.
*
* @param permits the number of permits to release
* @throws IllegalArgumentException if {@code permits} is negative
*/
public void release(int permits);
/**
* Acquires a permit, if one is available and returns immediately,
* with the value {@code true},
* reducing the number of available permits by one.
* <p/>
* If no permit is available then this method will return
* immediately with the value {@code false}.
*
* @return {@code true} if a permit was acquired and {@code false}
* otherwise
*/
public boolean tryAcquire();
/**
* Acquires the given number of permits, if they are available, and
* returns immediately, with the value {@code true},
* reducing the number of available permits by the given amount.
* <p/>
* <p>If insufficient permits are available then this method will return
* immediately with the value {@code false} and the number of available
* permits is unchanged.
*
* @param permits the number of permits to acquire
* @return {@code true} if the permits were acquired and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code permits} is negative
*/
public boolean tryAcquire(int permits);
/**
* Acquires a permit from this semaphore, if one becomes available
* within the given waiting time and the current thread has not
* been {@linkplain Thread#interrupt interrupted}.
* <p/>
* Acquires a permit, if one is available and returns immediately,
* with the value {@code true},
* reducing the number of available permits by one.
* <p/>
* If no permit is available then the current thread becomes
* disabled for thread scheduling purposes and lies dormant until
* one of three things happens:
* <ul>
* <li>Some other thread invokes the {@link #release} method for this
* semaphore and the current thread is next to be assigned a permit; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
* <li>The specified waiting time elapses.
* </ul>
* <p/>
* If a permit is acquired then the value {@code true} is returned.
* <p/>
* If the specified waiting time elapses then the value {@code false}
* is returned. If the time is less than or equal to zero, the method
* will not wait at all.
* <p/>
* <p>If the current thread:
* <ul>
* <li>has its interrupted status set on entry to this method; or
* <li>is {@linkplain Thread#interrupt interrupted} while waiting
* for a permit,
* </ul>
* then {@link InterruptedException} is thrown and the current thread's
* interrupted status is cleared.
*
* @param timeout the maximum time to wait for a permit
* @param unit the time unit of the {@code timeout} argument
* @return {@code true} if a permit was acquired and {@code false}
* if the waiting time elapsed before a permit was acquired
* @throws InterruptedException if the current thread is interrupted
* @throws IllegalStateException if hazelcast instance is shutdown while waiting
*/
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException;
/**
* Acquires the given number of permits, if they are available and
* returns immediately, with the value {@code true},
* reducing the number of available permits by the given amount.
* <p/>
* If insufficient permits are available then
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until one of three things happens:
* <ul>
* <li>Some other thread invokes one of the {@link #release() release}
* methods for this semaphore, the current thread is next to be assigned
* permits and the number of available permits satisfies this request; or
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
* <li>The specified waiting time elapses.
* </ul>
* <p/>
* If the permits are acquired then the value {@code true} is returned.
* <p/>
* If the specified waiting time elapses then the value {@code false}
* is returned. If the time is less than or equal to zero, the method
* will not wait at all.
* <p/>
* <p>If the current thread:
* <ul>
* <li>has its interrupted status set on entry to this method; or
* <li>is {@linkplain Thread#interrupt interrupted} while waiting
* for a permit,
* </ul>
* then {@link InterruptedException} is thrown and the current thread's
* interrupted status is cleared.
*
* @param permits the number of permits to acquire
* @param timeout the maximum time to wait for the permits
* @param unit the time unit of the {@code timeout} argument
* @return {@code true} if all permits were acquired and {@code false}
* if the waiting time elapsed before all permits could be acquired
* @throws InterruptedException if the current thread is interrupted
* @throws IllegalArgumentException if {@code permits} is negative
* @throws IllegalStateException if hazelcast instance is shutdown while waiting
*/
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException;
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_ISemaphore.java |
515 | public class IndicesExistsRequest extends MasterNodeReadOperationRequest<IndicesExistsRequest> {
private String[] indices = Strings.EMPTY_ARRAY;
private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, true);
public IndicesExistsRequest(String... indices) {
this.indices = indices;
}
public String[] indices() {
return indices;
}
public IndicesExistsRequest indices(String[] indices) {
this.indices = indices;
return this;
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public IndicesExistsRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (indices == null || indices.length == 0) {
validationException = addValidationError("index/indices is missing", validationException);
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = in.readStringArray();
indicesOptions = IndicesOptions.readIndicesOptions(in);
readLocal(in, Version.V_1_0_0_RC2);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArray(indices);
indicesOptions.writeIndicesOptions(out);
writeLocal(out, Version.V_1_0_0_RC2);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_exists_indices_IndicesExistsRequest.java |
157 | private final Function<String, Locker> CONSISTENT_KEY_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
KeyColumnValueStore lockerStore;
try {
lockerStore = storeManager.openDatabase(lockerName);
} catch (BackendException e) {
throw new TitanConfigurationException("Could not retrieve store named " + lockerName + " for locker configuration", e);
}
return new ConsistentKeyLocker.Builder(lockerStore, storeManager).fromConfig(configuration).build();
}
}; | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java |
196 | public class XmlClientConfigBuilder extends AbstractXmlConfigHelper {
private static final ILogger LOGGER = Logger.getLogger(XmlClientConfigBuilder.class);
private ClientConfig clientConfig;
private InputStream in;
public XmlClientConfigBuilder(String resource) throws IOException {
URL url = ConfigLoader.locateConfig(resource);
if (url == null) {
throw new IllegalArgumentException("Could not load " + resource);
}
this.in = url.openStream();
}
public XmlClientConfigBuilder(File file) throws IOException {
if (file == null) {
throw new NullPointerException("File is null!");
}
in = new FileInputStream(file);
}
public XmlClientConfigBuilder(URL url) throws IOException {
if (url == null) {
throw new NullPointerException("URL is null!");
}
in = url.openStream();
}
public XmlClientConfigBuilder(InputStream in) {
this.in = in;
}
public XmlClientConfigBuilder() {
String configFile = System.getProperty("hazelcast.client.config");
try {
File configurationFile = null;
if (configFile != null) {
configurationFile = new File(configFile);
LOGGER.info("Using configuration file at " + configurationFile.getAbsolutePath());
if (!configurationFile.exists()) {
String msg = "Config file at '" + configurationFile.getAbsolutePath() + "' doesn't exist.";
msg += "\nHazelcast will try to use the hazelcast-client.xml config file in the working directory.";
LOGGER.warning(msg);
configurationFile = null;
}
}
if (configurationFile == null) {
configFile = "hazelcast-client.xml";
configurationFile = new File("hazelcast-client.xml");
if (!configurationFile.exists()) {
configurationFile = null;
}
}
URL configurationUrl;
if (configurationFile != null) {
LOGGER.info("Using configuration file at " + configurationFile.getAbsolutePath());
try {
in = new FileInputStream(configurationFile);
} catch (final Exception e) {
String msg = "Having problem reading config file at '" + configFile + "'.";
msg += "\nException message: " + e.getMessage();
msg += "\nHazelcast will try to use the hazelcast-client.xml config file in classpath.";
LOGGER.warning(msg);
in = null;
}
}
if (in == null) {
LOGGER.info("Looking for hazelcast-client.xml config file in classpath.");
configurationUrl = Config.class.getClassLoader().getResource("hazelcast-client.xml");
if (configurationUrl == null) {
configurationUrl = Config.class.getClassLoader().getResource("hazelcast-client-default.xml");
LOGGER.warning(
"Could not find hazelcast-client.xml in classpath."
+ "\nHazelcast will use hazelcast-client-default.xml config file in jar.");
if (configurationUrl == null) {
LOGGER.warning("Could not find hazelcast-client-default.xml in the classpath!"
+ "\nThis may be due to a wrong-packaged or corrupted jar file.");
return;
}
}
LOGGER.info("Using configuration file " + configurationUrl.getFile() + " in the classpath.");
in = configurationUrl.openStream();
if (in == null) {
throw new IllegalStateException("Cannot read configuration file, giving up.");
}
}
} catch (final Throwable e) {
LOGGER.severe("Error while creating configuration:" + e.getMessage(), e);
}
}
public ClientConfig build() {
return build(Thread.currentThread().getContextClassLoader());
}
public ClientConfig build(ClassLoader classLoader) {
final ClientConfig clientConfig = new ClientConfig();
clientConfig.setClassLoader(classLoader);
try {
parse(clientConfig);
return clientConfig;
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
private void parse(ClientConfig clientConfig) throws Exception {
this.clientConfig = clientConfig;
final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc;
try {
doc = builder.parse(in);
} catch (final Exception e) {
throw new IllegalStateException("Could not parse configuration file, giving up.");
}
Element element = doc.getDocumentElement();
try {
element.getTextContent();
} catch (final Throwable e) {
domLevel3 = false;
}
handleConfig(element);
}
private void handleConfig(final Element docElement) throws Exception {
for (Node node : new IterableNodeList(docElement.getChildNodes())) {
final String nodeName = cleanNodeName(node.getNodeName());
if ("security".equals(nodeName)) {
handleSecurity(node);
} else if ("proxy-factories".equals(nodeName)) {
handleProxyFactories(node);
} else if ("properties".equals(nodeName)) {
fillProperties(node, clientConfig.getProperties());
} else if ("serialization".equals(nodeName)) {
handleSerialization(node);
} else if ("group".equals(nodeName)) {
handleGroup(node);
} else if ("listeners".equals(nodeName)) {
handleListeners(node);
} else if ("network".equals(nodeName)) {
handleNetwork(node);
} else if ("load-balancer".equals(nodeName)) {
handleLoadBalancer(node);
} else if ("near-cache".equals(nodeName)) {
handleNearCache(node);
} else if ("executor-pool-size".equals(nodeName)) {
final int poolSize = Integer.parseInt(getTextContent(node));
clientConfig.setExecutorPoolSize(poolSize);
}
}
}
private void handleNearCache(Node node) {
final String name = getAttribute(node, "name");
final NearCacheConfig nearCacheConfig = new NearCacheConfig();
for (Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child);
if ("max-size".equals(nodeName)) {
nearCacheConfig.setMaxSize(Integer.parseInt(getTextContent(child)));
} else if ("time-to-live-seconds".equals(nodeName)) {
nearCacheConfig.setTimeToLiveSeconds(Integer.parseInt(getTextContent(child)));
} else if ("max-idle-seconds".equals(nodeName)) {
nearCacheConfig.setMaxIdleSeconds(Integer.parseInt(getTextContent(child)));
} else if ("eviction-policy".equals(nodeName)) {
nearCacheConfig.setEvictionPolicy(getTextContent(child));
} else if ("in-memory-format".equals(nodeName)) {
nearCacheConfig.setInMemoryFormat(InMemoryFormat.valueOf(getTextContent(child)));
} else if ("invalidate-on-change".equals(nodeName)) {
nearCacheConfig.setInvalidateOnChange(Boolean.parseBoolean(getTextContent(child)));
} else if ("cache-local-entries".equals(nodeName)) {
nearCacheConfig.setCacheLocalEntries(Boolean.parseBoolean(getTextContent(child)));
}
}
clientConfig.addNearCacheConfig(name, nearCacheConfig);
}
private void handleLoadBalancer(Node node) {
final String type = getAttribute(node, "type");
if ("random".equals(type)) {
clientConfig.setLoadBalancer(new RandomLB());
} else if ("round-robin".equals(type)) {
clientConfig.setLoadBalancer(new RoundRobinLB());
}
}
private void handleNetwork(Node node) {
final ClientNetworkConfig clientNetworkConfig = new ClientNetworkConfig();
for (Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child);
if ("cluster-members".equals(nodeName)) {
handleClusterMembers(child, clientNetworkConfig);
} else if ("smart-routing".equals(nodeName)) {
clientNetworkConfig.setSmartRouting(Boolean.parseBoolean(getTextContent(child)));
} else if ("redo-operation".equals(nodeName)) {
clientNetworkConfig.setRedoOperation(Boolean.parseBoolean(getTextContent(child)));
} else if ("connection-timeout".equals(nodeName)) {
clientNetworkConfig.setConnectionTimeout(Integer.parseInt(getTextContent(child)));
} else if ("connection-attempt-period".equals(nodeName)) {
clientNetworkConfig.setConnectionAttemptPeriod(Integer.parseInt(getTextContent(child)));
} else if ("connection-attempt-limit".equals(nodeName)) {
clientNetworkConfig.setConnectionAttemptLimit(Integer.parseInt(getTextContent(child)));
} else if ("socket-options".equals(nodeName)) {
handleSocketOptions(child, clientNetworkConfig);
} else if ("socket-interceptor".equals(nodeName)) {
handleSocketInterceptorConfig(node, clientNetworkConfig);
} else if ("ssl".equals(nodeName)) {
handleSSLConfig(node, clientNetworkConfig);
}
}
clientConfig.setNetworkConfig(clientNetworkConfig);
}
private void handleSSLConfig(final org.w3c.dom.Node node, ClientNetworkConfig clientNetworkConfig) {
SSLConfig sslConfig = new SSLConfig();
final NamedNodeMap atts = node.getAttributes();
final Node enabledNode = atts.getNamedItem("enabled");
final boolean enabled = enabledNode != null && checkTrue(getTextContent(enabledNode).trim());
sslConfig.setEnabled(enabled);
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(n.getNodeName());
if ("factory-class-name".equals(nodeName)) {
sslConfig.setFactoryClassName(getTextContent(n).trim());
} else if ("properties".equals(nodeName)) {
fillProperties(n, sslConfig.getProperties());
}
}
clientNetworkConfig.setSSLConfig(sslConfig);
}
private void handleSocketOptions(Node node, ClientNetworkConfig clientNetworkConfig) {
SocketOptions socketOptions = clientConfig.getSocketOptions();
for (Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child);
if ("tcp-no-delay".equals(nodeName)) {
socketOptions.setTcpNoDelay(Boolean.parseBoolean(getTextContent(child)));
} else if ("keep-alive".equals(nodeName)) {
socketOptions.setKeepAlive(Boolean.parseBoolean(getTextContent(child)));
} else if ("reuse-address".equals(nodeName)) {
socketOptions.setReuseAddress(Boolean.parseBoolean(getTextContent(child)));
} else if ("linger-seconds".equals(nodeName)) {
socketOptions.setLingerSeconds(Integer.parseInt(getTextContent(child)));
} else if ("buffer-size".equals(nodeName)) {
socketOptions.setBufferSize(Integer.parseInt(getTextContent(child)));
}
}
clientNetworkConfig.setSocketOptions(socketOptions);
}
private void handleClusterMembers(Node node, ClientNetworkConfig clientNetworkConfig) {
for (Node child : new IterableNodeList(node.getChildNodes())) {
if ("address".equals(cleanNodeName(child))) {
clientNetworkConfig.addAddress(getTextContent(child));
}
}
}
private void handleListeners(Node node) throws Exception {
for (Node child : new IterableNodeList(node.getChildNodes())) {
if ("listener".equals(cleanNodeName(child))) {
String className = getTextContent(child);
clientConfig.addListenerConfig(new ListenerConfig(className));
}
}
}
private void handleGroup(Node node) {
for (org.w3c.dom.Node n : new IterableNodeList(node.getChildNodes())) {
final String value = getTextContent(n).trim();
final String nodeName = cleanNodeName(n.getNodeName());
if ("name".equals(nodeName)) {
clientConfig.getGroupConfig().setName(value);
} else if ("password".equals(nodeName)) {
clientConfig.getGroupConfig().setPassword(value);
}
}
}
private void handleSerialization(Node node) {
SerializationConfig serializationConfig = parseSerialization(node);
clientConfig.setSerializationConfig(serializationConfig);
}
private void handleProxyFactories(Node node) throws Exception {
for (Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("proxy-factory".equals(nodeName)) {
handleProxyFactory(child);
}
}
}
private void handleProxyFactory(Node node) throws Exception {
final String service = getAttribute(node, "service");
final String className = getAttribute(node, "class-name");
final ProxyFactoryConfig proxyFactoryConfig = new ProxyFactoryConfig(className, service);
clientConfig.addProxyFactoryConfig(proxyFactoryConfig);
}
private void handleSocketInterceptorConfig(final org.w3c.dom.Node node, ClientNetworkConfig clientNetworkConfig) {
SocketInterceptorConfig socketInterceptorConfig = parseSocketInterceptorConfig(node);
clientNetworkConfig.setSocketInterceptorConfig(socketInterceptorConfig);
}
private void handleSecurity(Node node) throws Exception {
for (Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("login-credentials".equals(nodeName)) {
handleLoginCredentials(child);
}
}
}
private void handleLoginCredentials(Node node) {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();
for (Node child : new IterableNodeList(node.getChildNodes())) {
final String nodeName = cleanNodeName(child.getNodeName());
if ("username".equals(nodeName)) {
credentials.setUsername(getTextContent(child));
} else if ("password".equals(nodeName)) {
credentials.setPassword(getTextContent(child));
}
}
clientConfig.setCredentials(credentials);
}
} | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_config_XmlClientConfigBuilder.java |
97 | @SuppressWarnings("serial")
static final class SearchKeysTask<K,V,U>
extends BulkTask<K,V,U> {
final Fun<? super K, ? extends U> searchFunction;
final AtomicReference<U> result;
SearchKeysTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Fun<? super K, ? extends U> searchFunction,
AtomicReference<U> result) {
super(p, b, i, f, t);
this.searchFunction = searchFunction; this.result = result;
}
public final U getRawResult() { return result.get(); }
public final void compute() {
final Fun<? super K, ? extends U> searchFunction;
final AtomicReference<U> result;
if ((searchFunction = this.searchFunction) != null &&
(result = this.result) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
if (result.get() != null)
return;
addToPendingCount(1);
new SearchKeysTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
searchFunction, result).fork();
}
while (result.get() == null) {
U u;
Node<K,V> p;
if ((p = advance()) == null) {
propagateCompletion();
break;
}
if ((u = searchFunction.apply(p.key)) != null) {
if (result.compareAndSet(null, u))
quietlyCompleteRoot();
break;
}
}
}
}
} | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
3,655 | public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
AllFieldMapper.Builder builder = all();
parseField(builder, 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("enabled")) {
builder.enabled(nodeBooleanValue(fieldNode));
} else if (fieldName.equals("auto_boost")) {
builder.autoBoost = nodeBooleanValue(fieldNode);
}
}
return builder;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_internal_AllFieldMapper.java |
2,252 | public class MeanMetric implements Metric {
private final LongAdder counter = new LongAdder();
private final LongAdder sum = new LongAdder();
public void inc(long n) {
counter.increment();
sum.add(n);
}
public void dec(long n) {
counter.decrement();
sum.add(-n);
}
public long count() {
return counter.sum();
}
public long sum() {
return sum.sum();
}
public double mean() {
long count = count();
if (count > 0) {
return sum.sum() / (double) count;
}
return 0.0;
}
public void clear() {
counter.reset();
sum.reset();
}
} | 0true
| src_main_java_org_elasticsearch_common_metrics_MeanMetric.java |
620 | public class NullBroadleafSiteResolver implements BroadleafSiteResolver {
@Override
public Site resolveSite(HttpServletRequest request) {
return resolveSite(new ServletWebRequest(request));
}
@Override
public Site resolveSite(WebRequest request) {
return null;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_web_NullBroadleafSiteResolver.java |
1,381 | public static enum State {
OPEN((byte) 0),
CLOSE((byte) 1);
private final byte id;
State(byte id) {
this.id = id;
}
public byte id() {
return this.id;
}
public static State fromId(byte id) {
if (id == 0) {
return OPEN;
} else if (id == 1) {
return CLOSE;
}
throw new ElasticsearchIllegalStateException("No state match for id [" + id + "]");
}
public static State fromString(String state) {
if ("open".equals(state)) {
return OPEN;
} else if ("close".equals(state)) {
return CLOSE;
}
throw new ElasticsearchIllegalStateException("No state match for [" + state + "]");
}
} | 0true
| src_main_java_org_elasticsearch_cluster_metadata_IndexMetaData.java |
794 | new Callable<OSchedulerListener>() {
public OSchedulerListener call() {
final OSchedulerListenerImpl instance = new OSchedulerListenerImpl();
if (iLoad)
instance.load();
return instance;
}
}), database); | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_OMetadataDefault.java |
901 | public interface PromotableOrderItemPriceDetailAdjustment extends Serializable {
/**
* Returns the associated promotableOrderItemPriceDetail
* @return
*/
PromotableOrderItemPriceDetail getPromotableOrderItemPriceDetail();
/**
* Returns the associated promotableCandidateItemOffer
* @return
*/
Offer getOffer();
/**
* Returns the value of this adjustment if only retail prices
* can be used.
* @return
*/
Money getRetailAdjustmentValue();
/**
* Returns the value of this adjustment if sale prices
* can be used.
* @return
*/
Money getSaleAdjustmentValue();
/**
* Returns the value of this adjustment.
* can be used.
* @return
*/
Money getAdjustmentValue();
/**
* Returns true if the value was applied to the sale price.
* @return
*/
boolean isAppliedToSalePrice();
/**
* Returns true if this adjustment represents a combinable offer.
*/
boolean isCombinable();
/**
* Returns true if this adjustment represents a totalitarian offer.
*/
boolean isTotalitarian();
/**
* Returns the id of the contained offer.
* @return
*/
Long getOfferId();
/**
* Sets the adjustment price based on the passed in parameter.
*/
void finalizeAdjustment(boolean useSalePrice);
/**
* Copy this adjustment. Used when a detail that contains this adjustment needs to be split.
* @param discountQty
* @param copy
* @return
*/
public PromotableOrderItemPriceDetailAdjustment copy();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableOrderItemPriceDetailAdjustment.java |
1,194 | class BulkListener implements BulkProcessor.Listener {
@Override
public void beforeBulk(long executionId, BulkRequest request) {
if (logger.isTraceEnabled()) {
logger.trace("[{}] executing [{}]/[{}]", executionId, request.numberOfActions(), new ByteSizeValue(request.estimatedSizeInBytes()));
}
}
@Override
public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
if (logger.isTraceEnabled()) {
logger.trace("[{}] executed [{}]/[{}], took [{}]", executionId, request.numberOfActions(), new ByteSizeValue(request.estimatedSizeInBytes()), response.getTook());
}
if (response.hasFailures()) {
logger.warn("[{}] failed to execute bulk request: {}", executionId, response.buildFailureMessage());
}
}
@Override
public void afterBulk(long executionId, BulkRequest request, Throwable e) {
logger.warn("[{}] failed to execute bulk request", e, executionId);
}
} | 0true
| src_main_java_org_elasticsearch_bulk_udp_BulkUdpService.java |
2,083 | public class PartitionWideEntryWithPredicateOperation extends PartitionWideEntryOperation {
Predicate predicate;
public PartitionWideEntryWithPredicateOperation() {
}
public PartitionWideEntryWithPredicateOperation(String name, EntryProcessor entryProcessor, Predicate predicate) {
super(name, entryProcessor);
this.predicate = predicate;
}
@Override
protected Predicate getPredicate() {
return predicate;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
predicate = in.readObject();
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(predicate);
}
@Override
public String toString() {
return "PartitionWideEntryWithPredicateOperation{}";
}
@Override
public Operation getBackupOperation() {
EntryBackupProcessor backupProcessor = entryProcessor.getBackupProcessor();
return backupProcessor != null ? new PartitionWideEntryWithPredicateBackupOperation(name, backupProcessor, predicate) : null;
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_operation_PartitionWideEntryWithPredicateOperation.java |
1,539 | @Service("blUpdateCartServiceExtensionManager")
public class UpdateCartServiceExtensionManager extends ExtensionManager<UpdateCartServiceExtensionHandler> {
public UpdateCartServiceExtensionManager() {
super(UpdateCartServiceExtensionHandler.class);
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_service_UpdateCartServiceExtensionManager.java |
25 | public class ErrorCommandProcessor extends AbstractTextCommandProcessor<ErrorCommand> {
public ErrorCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
}
public void handle(ErrorCommand command) {
textCommandService.sendResponse(command);
}
public void handleRejection(ErrorCommand command) {
handle(command);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_memcache_ErrorCommandProcessor.java |
891 | @SuppressWarnings({ "unchecked", "serial" })
public abstract class ORecordAbstract<T> implements ORecord<T>, ORecordInternal<T> {
protected ORecordId _recordId;
protected ORecordVersion _recordVersion = OVersionFactory.instance().createVersion();
protected byte[] _source;
protected int _size;
protected String _dataSegmentName;
protected transient ORecordSerializer _recordFormat;
protected Boolean _pinned = null;
protected boolean _dirty = true;
protected ORecordElement.STATUS _status = ORecordElement.STATUS.LOADED;
protected transient Set<ORecordListener> _listeners = null;
public ORecordAbstract() {
}
public ORecordAbstract(final byte[] iSource) {
_source = iSource;
_size = iSource.length;
unsetDirty();
}
public ORecordAbstract<?> fill(final ORID iRid, final ORecordVersion iVersion, final byte[] iBuffer, boolean iDirty) {
_recordId.clusterId = iRid.getClusterId();
_recordId.clusterPosition = iRid.getClusterPosition();
_recordVersion.copyFrom(iVersion);
_status = ORecordElement.STATUS.LOADED;
_source = iBuffer;
_size = iBuffer != null ? iBuffer.length : 0;
if (_source != null && _source.length > 0)
_dirty = iDirty;
return this;
}
public ORID getIdentity() {
return _recordId;
}
public ORecord<?> getRecord() {
return this;
}
public ORecordAbstract<?> setIdentity(final int iClusterId, final OClusterPosition iClusterPosition) {
if (_recordId == null || _recordId == ORecordId.EMPTY_RECORD_ID)
_recordId = new ORecordId(iClusterId, iClusterPosition);
else {
_recordId.clusterId = iClusterId;
_recordId.clusterPosition = iClusterPosition;
}
return this;
}
public ORecordAbstract<?> setIdentity(final ORecordId iIdentity) {
_recordId = iIdentity;
return this;
}
public boolean detach() {
return true;
}
public ORecordAbstract<T> clear() {
setDirty();
invokeListenerEvent(ORecordListener.EVENT.CLEAR);
return this;
}
public ORecordAbstract<T> reset() {
_status = ORecordElement.STATUS.LOADED;
_recordVersion.reset();
_size = 0;
setDirty();
if (_recordId != null)
_recordId.reset();
invokeListenerEvent(ORecordListener.EVENT.RESET);
return this;
}
public byte[] toStream() {
if (_source == null)
_source = _recordFormat.toStream(this, false);
invokeListenerEvent(ORecordListener.EVENT.MARSHALL);
return _source;
}
public ORecordAbstract<T> fromStream(final byte[] iRecordBuffer) {
_dirty = false;
_source = iRecordBuffer;
_size = iRecordBuffer != null ? iRecordBuffer.length : 0;
_status = ORecordElement.STATUS.LOADED;
invokeListenerEvent(ORecordListener.EVENT.UNMARSHALL);
return this;
}
public void unsetDirty() {
if (_dirty)
_dirty = false;
}
public ORecordAbstract<T> setDirty() {
if (!_dirty && _status != STATUS.UNMARSHALLING) {
_dirty = true;
_source = null;
}
return this;
}
public void onBeforeIdentityChanged(final ORID iRID) {
}
public void onAfterIdentityChanged(final ORecord<?> iRecord) {
invokeListenerEvent(ORecordListener.EVENT.IDENTITY_CHANGED);
}
public boolean isDirty() {
return _dirty;
}
public Boolean isPinned() {
return _pinned;
}
public ORecordAbstract<T> pin() {
_pinned = Boolean.TRUE;
return this;
}
public ORecordAbstract<T> unpin() {
_pinned = Boolean.FALSE;
return this;
}
public <RET extends ORecord<T>> RET fromJSON(final String iSource, final String iOptions) {
// ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null, iOptions);
ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null, iOptions, false); // Add new parameter to accommodate new API,
// noting change
return (RET) this;
}
public <RET extends ORecord<T>> RET fromJSON(final String iSource) {
ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null);
return (RET) this;
}
// Add New API to load record if rid exist
public <RET extends ORecord<T>> RET fromJSON(final String iSource, boolean needReload) {
return (RET) ORecordSerializerJSON.INSTANCE.fromString(iSource, this, null, needReload);
}
public <RET extends ORecord<T>> RET fromJSON(final InputStream iContentResult) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
OIOUtils.copyStream(iContentResult, out, -1);
ORecordSerializerJSON.INSTANCE.fromString(out.toString(), this, null);
return (RET) this;
}
public String toJSON() {
return toJSON("rid,version,class,type,attribSameRow,keepTypes,alwaysFetchEmbedded,fetchPlan:*:0");
}
public String toJSON(final String iFormat) {
return ORecordSerializerJSON.INSTANCE.toString(this, new StringBuilder(), iFormat).toString();
}
@Override
public String toString() {
return (_recordId.isValid() ? _recordId : "") + (_source != null ? Arrays.toString(_source) : "[]") + " v"
+ _recordVersion.toString();
}
public String getDataSegmentName() {
return _dataSegmentName;
}
public <RET extends ORecord<T>> RET setDataSegmentName(final String iName) {
if (_recordId.isValid())
throw new IllegalStateException("Cannot assign a data segment to a not new record");
_dataSegmentName = iName;
return (RET) this;
}
public int getVersion() {
checkForLoading();
return _recordVersion.getCounter();
}
public void setVersion(final int iVersion) {
_recordVersion.setCounter(iVersion);
}
public ORecordVersion getRecordVersion() {
checkForLoading();
return _recordVersion;
}
public ORecordAbstract<T> unload() {
_status = ORecordElement.STATUS.NOT_LOADED;
_source = null;
unsetDirty();
invokeListenerEvent(ORecordListener.EVENT.UNLOAD);
return this;
}
public ORecordInternal<T> load() {
if (!getIdentity().isValid())
throw new ORecordNotFoundException("The record has no id, probably it's new or transient yet ");
try {
final ORecordInternal<?> result = getDatabase().load(this);
if (result == null)
throw new ORecordNotFoundException("The record with id '" + getIdentity() + "' not found");
return (ORecordInternal<T>) result;
} catch (Exception e) {
throw new ORecordNotFoundException("The record with id '" + getIdentity() + "' not found", e);
}
}
public ODatabaseRecord getDatabase() {
return ODatabaseRecordThreadLocal.INSTANCE.get();
}
public ORecordInternal<T> reload() {
return reload(null);
}
public ORecordInternal<T> reload(final String iFetchPlan) {
return reload(null, true);
}
public ORecordInternal<T> reload(final String iFetchPlan, final boolean iIgnoreCache) {
if (!getIdentity().isValid())
throw new ORecordNotFoundException("The record has no id. It is probably new or still transient");
try {
getDatabase().reload(this, iFetchPlan, iIgnoreCache);
// GET CONTENT
// fromStream(toStream());
return this;
} catch (Exception e) {
throw new ORecordNotFoundException("The record with id '" + getIdentity() + "' not found", e);
}
}
public ORecordAbstract<T> save() {
return save(false);
}
public ORecordAbstract<T> save(final String iClusterName) {
return save(iClusterName, false);
}
public ORecordAbstract<T> save(boolean forceCreate) {
getDatabase().save(this, ODatabaseComplex.OPERATION_MODE.SYNCHRONOUS, forceCreate, null, null);
return this;
}
public ORecordAbstract<T> save(String iClusterName, boolean forceCreate) {
getDatabase().save(this, iClusterName, ODatabaseComplex.OPERATION_MODE.SYNCHRONOUS, forceCreate, null, null);
return this;
}
public ORecordAbstract<T> delete() {
getDatabase().delete(this);
setDirty();
return this;
}
public int getSize() {
return _size;
}
protected void setup() {
if (_recordId == null)
_recordId = new ORecordId();
}
@Override
public int hashCode() {
return _recordId != null ? _recordId.hashCode() : 0;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof OIdentifiable)
return _recordId.equals(((OIdentifiable) obj).getIdentity());
return false;
}
public int compare(final OIdentifiable iFirst, final OIdentifiable iSecond) {
if (iFirst == null || iSecond == null)
return -1;
return iFirst.compareTo(iSecond);
}
public int compareTo(final OIdentifiable iOther) {
if (iOther == null)
return 1;
if (_recordId == null)
return iOther.getIdentity() == null ? 0 : 1;
return _recordId.compareTo(iOther.getIdentity());
}
public ORecordElement.STATUS getInternalStatus() {
return _status;
}
public void setInternalStatus(final ORecordElement.STATUS iStatus) {
this._status = iStatus;
}
public ORecordAbstract<T> copyTo(final ORecordAbstract<T> cloned) {
cloned._source = _source;
cloned._size = _size;
cloned._recordId = _recordId.copy();
cloned._recordVersion = _recordVersion.copy();
cloned._pinned = _pinned;
cloned._status = _status;
cloned._recordFormat = _recordFormat;
cloned._listeners = null;
cloned._dirty = false;
return cloned;
}
/**
* Add a listener to the current document to catch all the supported events.
*
* @see ORecordListener
*
* @param iListener
* ODocumentListener implementation
*/
public void addListener(final ORecordListener iListener) {
if (_listeners == null)
_listeners = Collections.newSetFromMap(new WeakHashMap<ORecordListener, Boolean>());
_listeners.add(iListener);
}
/**
* Remove the current event listener.
*
* @see ORecordListener
*/
public void removeListener(final ORecordListener listener) {
if (_listeners != null) {
_listeners.remove(listener);
if (_listeners.isEmpty())
_listeners = null;
}
}
protected void invokeListenerEvent(final ORecordListener.EVENT iEvent) {
if (_listeners != null)
for (final ORecordListener listener : _listeners)
if (listener != null)
listener.onEvent(this, iEvent);
}
public <RET extends ORecord<T>> RET flatCopy() {
return (RET) copy();
}
protected void checkForLoading() {
if (_status == ORecordElement.STATUS.NOT_LOADED && ODatabaseRecordThreadLocal.INSTANCE.isDefined())
reload(null, true);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_ORecordAbstract.java |
5,403 | public static abstract class Bytes extends FieldDataSource {
public static abstract class WithOrdinals extends Bytes {
public abstract BytesValues.WithOrdinals bytesValues();
public static class FieldData extends WithOrdinals implements ReaderContextAware {
protected boolean needsHashes;
protected final IndexFieldData.WithOrdinals<?> indexFieldData;
protected final MetaData metaData;
protected AtomicFieldData.WithOrdinals<?> atomicFieldData;
private BytesValues.WithOrdinals bytesValues;
public FieldData(IndexFieldData.WithOrdinals<?> indexFieldData, MetaData metaData) {
this.indexFieldData = indexFieldData;
this.metaData = metaData;
needsHashes = false;
}
@Override
public MetaData metaData() {
return metaData;
}
public final void setNeedsHashes(boolean needsHashes) {
this.needsHashes = needsHashes;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
atomicFieldData = indexFieldData.load(reader);
if (bytesValues != null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
}
@Override
public BytesValues.WithOrdinals bytesValues() {
if (bytesValues == null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
return bytesValues;
}
}
}
public static class FieldData extends Bytes implements ReaderContextAware {
protected boolean needsHashes;
protected final IndexFieldData<?> indexFieldData;
protected final MetaData metaData;
protected AtomicFieldData<?> atomicFieldData;
private BytesValues bytesValues;
public FieldData(IndexFieldData<?> indexFieldData, MetaData metaData) {
this.indexFieldData = indexFieldData;
this.metaData = metaData;
needsHashes = false;
}
@Override
public MetaData metaData() {
return metaData;
}
public final void setNeedsHashes(boolean needsHashes) {
this.needsHashes = needsHashes;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
atomicFieldData = indexFieldData.load(reader);
if (bytesValues != null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = atomicFieldData.getBytesValues(needsHashes);
}
return bytesValues;
}
}
public static class Script extends Bytes {
private final ScriptBytesValues values;
public Script(SearchScript script) {
values = new ScriptBytesValues(script);
}
@Override
public MetaData metaData() {
return MetaData.UNKNOWN;
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
return values;
}
}
public static class SortedAndUnique extends Bytes implements ReaderContextAware {
private final FieldDataSource delegate;
private final MetaData metaData;
private BytesValues bytesValues;
public SortedAndUnique(FieldDataSource delegate) {
this.delegate = delegate;
this.metaData = MetaData.builder(delegate.metaData()).uniqueness(MetaData.Uniqueness.UNIQUE).build();
}
@Override
public MetaData metaData() {
return metaData;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
bytesValues = null; // order may change per-segment -> reset
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = delegate.bytesValues();
if (bytesValues.isMultiValued() &&
(!delegate.metaData().uniqueness.unique() || bytesValues.getOrder() != Order.BYTES)) {
bytesValues = new SortedUniqueBytesValues(bytesValues);
}
}
return bytesValues;
}
static class SortedUniqueBytesValues extends FilterBytesValues {
final BytesRef spare;
int[] sortedIds;
final BytesRefHash bytes;
int numUniqueValues;
int pos = Integer.MAX_VALUE;
public SortedUniqueBytesValues(BytesValues delegate) {
super(delegate);
bytes = new BytesRefHash();
spare = new BytesRef();
}
@Override
public int setDocument(int docId) {
final int numValues = super.setDocument(docId);
if (numValues == 0) {
sortedIds = null;
return 0;
}
bytes.clear();
bytes.reinit();
for (int i = 0; i < numValues; ++i) {
bytes.add(super.nextValue(), super.currentValueHash());
}
numUniqueValues = bytes.size();
sortedIds = bytes.sort(BytesRef.getUTF8SortedAsUnicodeComparator());
pos = 0;
return numUniqueValues;
}
@Override
public BytesRef nextValue() {
bytes.get(sortedIds[pos++], spare);
return spare;
}
@Override
public int currentValueHash() {
return spare.hashCode();
}
@Override
public Order getOrder() {
return Order.BYTES;
}
}
}
} | 1no label
| src_main_java_org_elasticsearch_search_aggregations_support_FieldDataSource.java |
1,212 | public class PaymentInfoType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, PaymentInfoType> TYPES = new LinkedHashMap<String, PaymentInfoType>();
public static final PaymentInfoType GIFT_CARD = new PaymentInfoType("GIFT_CARD", "Gift Card");
public static final PaymentInfoType CREDIT_CARD = new PaymentInfoType("CREDIT_CARD", "Credit Card");
public static final PaymentInfoType BANK_ACCOUNT = new PaymentInfoType("BANK_ACCOUNT", "Bank Account");
public static final PaymentInfoType PAYPAL = new PaymentInfoType("PAYPAL", "PayPal");
public static final PaymentInfoType CHECK = new PaymentInfoType("CHECK", "Check");
public static final PaymentInfoType ELECTRONIC_CHECK = new PaymentInfoType("ELECTRONIC_CHECK", "Electronic Check");
public static final PaymentInfoType WIRE = new PaymentInfoType("WIRE", "Wire Transfer");
public static final PaymentInfoType MONEY_ORDER = new PaymentInfoType("MONEY_ORDER", "Money Order");
public static final PaymentInfoType CUSTOMER_CREDIT = new PaymentInfoType("CUSTOMER_CREDIT", "Customer Credit");
public static final PaymentInfoType ACCOUNT = new PaymentInfoType("ACCOUNT", "Account");
public static PaymentInfoType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public PaymentInfoType() {
//do nothing
}
public PaymentInfoType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PaymentInfoType other = (PaymentInfoType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_type_PaymentInfoType.java |
1,657 | @javax.persistence.Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="BLC_SANDBOX_ACTION")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blSandBoxElements")
@EntityListeners(value = { AdminAuditableListener.class })
public class SandBoxActionImpl implements SandBoxAction {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "SandBoxActionId")
@GenericGenerator(
name="SandBoxActionId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="SandBoxActionImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.openadmin.server.domain.SandBoxActionImpl")
}
)
@Column(name = "SANDBOX_ACTION_ID")
protected Long id;
@Embedded
@AdminPresentation(excluded = true)
protected AdminAuditable auditable = new AdminAuditable();
@Column(name = "ACTION_TYPE")
protected String sandBoxActionType;
@Column(name = "ACTION_COMMENT")
protected String comment;
@ManyToMany(targetEntity = SandBoxItemImpl.class, cascade = CascadeType.ALL)
@JoinTable(
name = "SANDBOX_ITEM_ACTION",
joinColumns = {@JoinColumn(name = "SANDBOX_ACTION_ID", referencedColumnName = "SANDBOX_ACTION_ID")},
inverseJoinColumns = {@JoinColumn(name ="SANDBOX_ITEM_ID", referencedColumnName = "SANDBOX_ITEM_ID")}
)
protected List<SandBoxItem> sandBoxItems;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public SandBoxActionType getActionType() {
return SandBoxActionType.getInstance(sandBoxActionType);
}
@Override
public void setActionType(SandBoxActionType type) {
sandBoxActionType = type.getType();
}
@Override
public String getComment() {
return comment;
}
@Override
public void setComment(String comment) {
this.comment = comment;
}
@Override
public List<SandBoxItem> getSandBoxItems() {
return sandBoxItems;
}
@Override
public void setSandBoxItems(List<SandBoxItem> sandBoxItems) {
this.sandBoxItems = sandBoxItems;
}
@Override
public void addSandBoxItem(SandBoxItem item) {
if (sandBoxItems == null) {
sandBoxItems = new ArrayList<SandBoxItem>();
}
sandBoxItems.add(item);
}
@Override
public AdminAuditable getAuditable() {
return auditable;
}
@Override
public void setAuditable(AdminAuditable auditable) {
this.auditable = auditable;
}
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_domain_SandBoxActionImpl.java |
854 | BINARY("Binary", 8, new Class<?>[] { byte[].class }, new Class<?>[] { byte[].class }) {
}, | 0true
| core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java |
3,234 | public final static class Strings extends ScriptDocValues {
private final BytesValues values;
private final CharsRef spare = new CharsRef();
private SlicedObjectList<String> list;
public Strings(BytesValues values) {
this.values = values;
list = new SlicedObjectList<String>(values.isMultiValued() ? new String[10] : new String[1]) {
@Override
public void grow(int newLength) {
assert offset == 0; // NOTE: senseless if offset != 0
if (values.length >= newLength) {
return;
}
final String[] current = values;
values = new String[ArrayUtil.oversize(newLength, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(current, 0, values, 0, current.length);
}
};
}
@Override
public boolean isEmpty() {
return values.setDocument(docId) == 0;
}
public BytesValues getInternalValues() {
return this.values;
}
public BytesRef getBytesValue() {
int numValues = values.setDocument(docId);
if (numValues == 0) {
return null;
}
return values.nextValue();
}
public String getValue() {
String value = null;
if (values.setDocument(docId) > 0) {
UnicodeUtil.UTF8toUTF16(values.nextValue(), spare);
value = spare.toString();
}
return value;
}
public List<String> getValues() {
if (!listLoaded) {
final int numValues = values.setDocument(docId);
list.offset = 0;
list.grow(numValues);
list.length = numValues;
for (int i = 0; i < numValues; i++) {
BytesRef next = values.nextValue();
UnicodeUtil.UTF8toUTF16(next, spare);
list.values[i] = spare.toString();
}
listLoaded = true;
}
return list;
}
} | 1no label
| src_main_java_org_elasticsearch_index_fielddata_ScriptDocValues.java |
1,154 | class Searcher extends Thread {
final int id;
long counter = 0;
long max = searcherIterations;
Searcher(int id) {
super("Searcher" + id);
this.id = id;
}
@Override
public void run() {
try {
barrier1.await();
barrier2.await();
for (; counter < max; counter++) {
Client client = client(counter);
QueryBuilder query = termQuery("num", counter % fieldNumLimit);
query = constantScoreQuery(queryFilter(query));
SearchResponse search = client.search(searchRequest()
.source(searchSource().query(query)))
.actionGet();
// System.out.println("Got search response, hits [" + search.hits().totalHits() + "]");
}
} catch (Exception e) {
System.err.println("Failed to search:");
e.printStackTrace();
} finally {
latch.countDown();
}
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_stress_NodesStressTest.java |
442 | public class KCVSManagerProxy implements KeyColumnValueStoreManager {
protected final KeyColumnValueStoreManager manager;
public KCVSManagerProxy(KeyColumnValueStoreManager manager) {
Preconditions.checkArgument(manager != null);
this.manager = manager;
}
@Override
public StoreTransaction beginTransaction(BaseTransactionConfig config) throws BackendException {
return manager.beginTransaction(config);
}
@Override
public void close() throws BackendException {
manager.close();
}
@Override
public void clearStorage() throws BackendException {
manager.clearStorage();
}
@Override
public StoreFeatures getFeatures() {
return manager.getFeatures();
}
@Override
public String getName() {
return manager.getName();
}
@Override
public List<KeyRange> getLocalKeyPartition() throws BackendException {
return manager.getLocalKeyPartition();
}
@Override
public KeyColumnValueStore openDatabase(String name) throws BackendException {
return manager.openDatabase(name);
}
@Override
public void mutateMany(Map<String, Map<StaticBuffer, KCVMutation>> mutations, StoreTransaction txh) throws BackendException {
manager.mutateMany(mutations,txh);
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_KCVSManagerProxy.java |
1,200 | public interface MultiExecutionCallback {
/**
* Called when an execution is completed on a member.
*
* @param member member which task is submitted to.
* @param value result of execution
*/
void onResponse(Member member, Object value);
/**
* Called after all executions are completed.
*
* @param values map of Member-Response pairs
*/
void onComplete(Map<Member, Object> values);
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_MultiExecutionCallback.java |
634 | public class MergeContextLoader extends ContextLoader {
/**
* Name of servlet context parameter (i.e., "<code>patchConfigLocation</code>")
* that can specify the config location for the rootId context.
*/
public static final String PATCH_LOCATION_PARAM = "patchConfigLocation";
/**
* Name of a bean to hook before Spring shutdown for this
* context commences.
*/
public static final String SHUTDOWN_HOOK_BEAN = "shutdownHookBean";
/**
* Name of method to call on the shutdown hook bean before
* Spring shutdown for this context commences
*/
public static final String SHUTDOWN_HOOK_METHOD = "shutdownHookMethod";
/**
* Instantiate the rootId WebApplicationContext for this loader, either the
* default context class or a custom context class if specified.
* <p>This implementation expects custom contexts to implement the
* {@link ConfigurableWebApplicationContext} interface.
* Can be overridden in subclasses.
* <p>In addition, {@link #customizeContext} gets called prior to refreshing the
* context, allowing subclasses to perform custom modifications to the context.
* @param servletContext current servlet context
* @param parent the parent ApplicationContext to use, or <code>null</code> if none
* @return the rootId WebApplicationContext
* @throws BeansException if the context couldn't be initialized
* @see ConfigurableWebApplicationContext
*/
@Deprecated
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext, ApplicationContext parent) throws BeansException {
MergeXmlWebApplicationContext wac = new MergeXmlWebApplicationContext();
wac.setParent(parent);
wac.setServletContext(servletContext);
wac.setConfigLocation(servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM));
wac.setPatchLocation(servletContext.getInitParameter(PATCH_LOCATION_PARAM));
wac.setShutdownBean(servletContext.getInitParameter(SHUTDOWN_HOOK_BEAN));
wac.setShutdownMethod(servletContext.getInitParameter(SHUTDOWN_HOOK_METHOD));
customizeContext(servletContext, wac);
wac.refresh();
return wac;
}
/**
* Instantiate the rootId WebApplicationContext for this loader, either the
* default context class or a custom context class if specified.
* <p>This implementation expects custom contexts to implement the
* {@link ConfigurableWebApplicationContext} interface.
* Can be overridden in subclasses.
* <p>In addition, {@link #customizeContext} gets called prior to refreshing the
* context, allowing subclasses to perform custom modifications to the context.
* @param servletContext current servlet context
* @return the rootId WebApplicationContext
* @throws BeansException if the context couldn't be initialized
* @see ConfigurableWebApplicationContext
*/
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) throws BeansException {
MergeXmlWebApplicationContext wac = new MergeXmlWebApplicationContext();
wac.setServletContext(servletContext);
wac.setConfigLocation(servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM));
wac.setPatchLocation(servletContext.getInitParameter(PATCH_LOCATION_PARAM));
wac.setShutdownBean(servletContext.getInitParameter(SHUTDOWN_HOOK_BEAN));
wac.setShutdownMethod(servletContext.getInitParameter(SHUTDOWN_HOOK_METHOD));
customizeContext(servletContext, wac);
//NOTE: in Spring 3.1, refresh gets called automatically. All that is required is to return the context back to Spring
//wac.refresh();
return wac;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_web_extensibility_MergeContextLoader.java |
4,469 | class RecoveryFileChunkRequest extends TransportRequest {
private long recoveryId;
private ShardId shardId;
private String name;
private long position;
private long length;
private String checksum;
private BytesReference content;
RecoveryFileChunkRequest() {
}
RecoveryFileChunkRequest(long recoveryId, ShardId shardId, String name, long position, long length, String checksum, BytesArray content) {
this.recoveryId = recoveryId;
this.shardId = shardId;
this.name = name;
this.position = position;
this.length = length;
this.checksum = checksum;
this.content = content;
}
public long recoveryId() {
return this.recoveryId;
}
public ShardId shardId() {
return shardId;
}
public String name() {
return name;
}
public long position() {
return position;
}
@Nullable
public String checksum() {
return this.checksum;
}
public long length() {
return length;
}
public BytesReference content() {
return content;
}
public RecoveryFileChunkRequest readFileChunk(StreamInput in) throws IOException {
RecoveryFileChunkRequest request = new RecoveryFileChunkRequest();
request.readFrom(in);
return request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
recoveryId = in.readLong();
shardId = ShardId.readShardId(in);
name = in.readString();
position = in.readVLong();
length = in.readVLong();
checksum = in.readOptionalString();
content = in.readBytesReference();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeLong(recoveryId);
shardId.writeTo(out);
out.writeString(name);
out.writeVLong(position);
out.writeVLong(length);
out.writeOptionalString(checksum);
out.writeBytesReference(content);
}
@Override
public String toString() {
return shardId + ": name='" + name + '\'' +
", position=" + position +
", length=" + length;
}
} | 1no label
| src_main_java_org_elasticsearch_indices_recovery_RecoveryFileChunkRequest.java |
453 | 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 |
708 | private class PinnedPage implements Comparable<PinnedPage> {
private final long fileId;
private final long pageIndex;
private PinnedPage(long fileId, long pageIndex) {
this.fileId = fileId;
this.pageIndex = pageIndex;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PinnedPage that = (PinnedPage) o;
if (fileId != that.fileId)
return false;
if (pageIndex != that.pageIndex)
return false;
return true;
}
@Override
public String toString() {
return "PinnedPage{" + "fileId=" + fileId + ", pageIndex=" + pageIndex + '}';
}
@Override
public int hashCode() {
int result = (int) (fileId ^ (fileId >>> 32));
result = 31 * result + (int) (pageIndex ^ (pageIndex >>> 32));
return result;
}
@Override
public int compareTo(PinnedPage other) {
if (fileId > other.fileId)
return 1;
if (fileId < other.fileId)
return -1;
if (pageIndex > other.pageIndex)
return 1;
if (pageIndex < other.pageIndex)
return -1;
return 0;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_cache_OReadWriteDiskCache.java |
2,568 | public interface DiscoveryNodesProvider {
DiscoveryNodes nodes();
@Nullable
NodeService nodeService();
} | 0true
| src_main_java_org_elasticsearch_discovery_zen_DiscoveryNodesProvider.java |
2,055 | public class InvalidateNearCacheOperation extends AbstractOperation {
private Data key;
private String mapName;
public InvalidateNearCacheOperation(String mapName, Data key) {
this.key = key;
this.mapName = mapName;
}
public InvalidateNearCacheOperation() {
}
public void run() {
MapService mapService = getService();
if (mapService.getMapContainer(mapName).isNearCacheEnabled()) {
mapService.invalidateNearCache(mapName, key);
} else {
getLogger().warning("Cache clear operation has been accepted while near cache is not enabled for "
+ mapName + " map. Possible configuration conflict among nodes.");
}
}
@Override
public boolean returnsResponse() {
return false;
}
@Override
public void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
mapName = in.readUTF();
key = in.readObject();
}
@Override
public void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(mapName);
out.writeObject(key);
}
@Override
public String toString() {
return "InvalidateNearCacheOperation{}";
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_operation_InvalidateNearCacheOperation.java |
704 | shardBulkAction.execute(bulkShardRequest, new ActionListener<BulkShardResponse>() {
@Override
public void onResponse(BulkShardResponse bulkShardResponse) {
for (BulkItemResponse bulkItemResponse : bulkShardResponse.getResponses()) {
responses.set(bulkItemResponse.getItemId(), bulkItemResponse);
}
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable e) {
// create failures for all relevant requests
String message = ExceptionsHelper.detailedMessage(e);
RestStatus status = ExceptionsHelper.status(e);
for (BulkItemRequest request : requests) {
if (request.request() instanceof IndexRequest) {
IndexRequest indexRequest = (IndexRequest) request.request();
responses.set(request.id(), new BulkItemResponse(request.id(), indexRequest.opType().toString().toLowerCase(Locale.ENGLISH),
new BulkItemResponse.Failure(indexRequest.index(), indexRequest.type(), indexRequest.id(), message, status)));
} else if (request.request() instanceof DeleteRequest) {
DeleteRequest deleteRequest = (DeleteRequest) request.request();
responses.set(request.id(), new BulkItemResponse(request.id(), "delete",
new BulkItemResponse.Failure(deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), message, status)));
} else if (request.request() instanceof UpdateRequest) {
UpdateRequest updateRequest = (UpdateRequest) request.request();
responses.set(request.id(), new BulkItemResponse(request.id(), "update",
new BulkItemResponse.Failure(updateRequest.index(), updateRequest.type(), updateRequest.id(), message, status)));
}
}
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
private void finishHim() {
listener.onResponse(new BulkResponse(responses.toArray(new BulkItemResponse[responses.length()]), System.currentTimeMillis() - startTime));
}
}); | 0true
| src_main_java_org_elasticsearch_action_bulk_TransportBulkAction.java |
194 | public class TruncateTokenFilterTests extends ElasticsearchTestCase {
@Test
public void simpleTest() throws IOException {
Analyzer analyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
Tokenizer t = new WhitespaceTokenizer(Lucene.VERSION, reader);
return new TokenStreamComponents(t, new TruncateTokenFilter(t, 3));
}
};
TokenStream test = analyzer.tokenStream("test", "a bb ccc dddd eeeee");
test.reset();
CharTermAttribute termAttribute = test.addAttribute(CharTermAttribute.class);
assertThat(test.incrementToken(), equalTo(true));
assertThat(termAttribute.toString(), equalTo("a"));
assertThat(test.incrementToken(), equalTo(true));
assertThat(termAttribute.toString(), equalTo("bb"));
assertThat(test.incrementToken(), equalTo(true));
assertThat(termAttribute.toString(), equalTo("ccc"));
assertThat(test.incrementToken(), equalTo(true));
assertThat(termAttribute.toString(), equalTo("ddd"));
assertThat(test.incrementToken(), equalTo(true));
assertThat(termAttribute.toString(), equalTo("eee"));
assertThat(test.incrementToken(), equalTo(false));
}
} | 0true
| src_test_java_org_apache_lucene_analysis_miscellaneous_TruncateTokenFilterTests.java |
204 | public interface StaticBuffer extends Comparable<StaticBuffer> {
public int length();
public byte getByte(int position);
public boolean getBoolean(int position);
public short getShort(int position);
public int getInt(int position);
public long getLong(int position);
public char getChar(int position);
public float getFloat(int position);
public double getDouble(int position);
public byte[] getBytes(int position, int length);
public short[] getShorts(int position, int length);
public int[] getInts(int position, int length);
public long[] getLongs(int position, int length);
public char[] getChars(int position, int length);
public float[] getFloats(int position, int length);
public double[] getDoubles(int position, int length);
public StaticBuffer subrange(int position, int length);
public StaticBuffer subrange(int position, int length, boolean invert);
public ReadBuffer asReadBuffer();
public<T> T as(Factory<T> factory);
//Convenience method
public ByteBuffer asByteBuffer();
public interface Factory<T> {
public T get(byte[] array, int offset, int limit);
}
public static final Factory<byte[]> ARRAY_FACTORY = new Factory<byte[]>() {
@Override
public byte[] get(byte[] array, int offset, int limit) {
if (offset==0 && limit==array.length) return array;
else return Arrays.copyOfRange(array,offset,limit);
}
};
public static final Factory<ByteBuffer> BB_FACTORY = new Factory<ByteBuffer>() {
@Override
public ByteBuffer get(byte[] array, int offset, int limit) {
return ByteBuffer.wrap(array, offset, limit - offset);
}
};
public static final Factory<StaticBuffer> STATIC_FACTORY = new Factory<StaticBuffer>() {
@Override
public StaticBuffer get(byte[] array, int offset, int limit) {
return new StaticArrayBuffer(array, offset, limit);
}
};
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_StaticBuffer.java |
3,364 | return new LongValues(false) {
@Override
public int setDocument(int docId) {
this.docId = docId;
return docValues.docsWithField.get(docId) ? 1 : 0;
}
@Override
public long nextValue() {
return docValues.values.get(docId);
}
}; | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_NumericDVAtomicFieldData.java |
5,226 | public class InternalHistogram<B extends InternalHistogram.Bucket> extends InternalAggregation implements Histogram {
final static Type TYPE = new Type("histogram", "histo");
final static Factory FACTORY = new Factory();
private final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalHistogram readResult(StreamInput in) throws IOException {
InternalHistogram histogram = new InternalHistogram();
histogram.readFrom(in);
return histogram;
}
};
public static void registerStream() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
public static class Bucket implements Histogram.Bucket {
long key;
long docCount;
InternalAggregations aggregations;
public Bucket(long key, long docCount, InternalAggregations aggregations) {
this.key = key;
this.docCount = docCount;
this.aggregations = aggregations;
}
@Override
public String getKey() {
return String.valueOf(key);
}
@Override
public Text getKeyAsText() {
return new StringText(getKey());
}
@Override
public Number getKeyAsNumber() {
return key;
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
<B extends Bucket> B reduce(List<B> buckets, CacheRecycler cacheRecycler) {
if (buckets.size() == 1) {
// we only need to reduce the sub aggregations
Bucket bucket = buckets.get(0);
bucket.aggregations.reduce(cacheRecycler);
return (B) bucket;
}
List<InternalAggregations> aggregations = new ArrayList<InternalAggregations>(buckets.size());
Bucket reduced = null;
for (Bucket bucket : buckets) {
if (reduced == null) {
reduced = bucket;
} else {
reduced.docCount += bucket.docCount;
}
aggregations.add((InternalAggregations) bucket.getAggregations());
}
reduced.aggregations = InternalAggregations.reduce(aggregations, cacheRecycler);
return (B) reduced;
}
}
static class EmptyBucketInfo {
final Rounding rounding;
final InternalAggregations subAggregations;
EmptyBucketInfo(Rounding rounding, InternalAggregations subAggregations) {
this.rounding = rounding;
this.subAggregations = subAggregations;
}
public static EmptyBucketInfo readFrom(StreamInput in) throws IOException {
return new EmptyBucketInfo(Rounding.Streams.read(in), InternalAggregations.readAggregations(in));
}
public static void writeTo(EmptyBucketInfo info, StreamOutput out) throws IOException {
Rounding.Streams.write(info.rounding, out);
info.subAggregations.writeTo(out);
}
}
static class Factory<B extends InternalHistogram.Bucket> {
protected Factory() {
}
public String type() {
return TYPE.name();
}
public InternalHistogram<B> create(String name, List<B> buckets, InternalOrder order, long minDocCount,
EmptyBucketInfo emptyBucketInfo, ValueFormatter formatter, boolean keyed) {
return new InternalHistogram<B>(name, buckets, order, minDocCount, emptyBucketInfo, formatter, keyed);
}
public B createBucket(long key, long docCount, InternalAggregations aggregations, ValueFormatter formatter) {
return (B) new Bucket(key, docCount, aggregations);
}
}
private List<B> buckets;
private LongObjectOpenHashMap<B> bucketsMap;
private InternalOrder order;
private ValueFormatter formatter;
private boolean keyed;
private long minDocCount;
private EmptyBucketInfo emptyBucketInfo;
InternalHistogram() {} // for serialization
InternalHistogram(String name, List<B> buckets, InternalOrder order, long minDocCount, EmptyBucketInfo emptyBucketInfo, ValueFormatter formatter, boolean keyed) {
super(name);
this.buckets = buckets;
this.order = order;
assert (minDocCount == 0) == (emptyBucketInfo != null);
this.minDocCount = minDocCount;
this.emptyBucketInfo = emptyBucketInfo;
this.formatter = formatter;
this.keyed = keyed;
}
@Override
public Type type() {
return TYPE;
}
@Override
public Collection<B> getBuckets() {
return buckets;
}
@Override
public B getBucketByKey(String key) {
return getBucketByKey(Long.valueOf(key));
}
@Override
public B getBucketByKey(Number key) {
if (bucketsMap == null) {
bucketsMap = new LongObjectOpenHashMap<B>(buckets.size());
for (B bucket : buckets) {
bucketsMap.put(bucket.key, bucket);
}
}
return bucketsMap.get(key.longValue());
}
@Override
public InternalAggregation reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
if (aggregations.size() == 1) {
InternalHistogram<B> histo = (InternalHistogram<B>) aggregations.get(0);
if (minDocCount == 1) {
for (B bucket : histo.buckets) {
bucket.aggregations.reduce(reduceContext.cacheRecycler());
}
return histo;
}
CollectionUtil.introSort(histo.buckets, order.asc ? InternalOrder.KEY_ASC.comparator() : InternalOrder.KEY_DESC.comparator());
List<B> list = order.asc ? histo.buckets : Lists.reverse(histo.buckets);
B prevBucket = null;
ListIterator<B> iter = list.listIterator();
if (minDocCount == 0) {
// we need to fill the gaps with empty buckets
while (iter.hasNext()) {
// look ahead on the next bucket without advancing the iter
// so we'll be able to insert elements at the right position
B nextBucket = list.get(iter.nextIndex());
nextBucket.aggregations.reduce(reduceContext.cacheRecycler());
if (prevBucket != null) {
long key = emptyBucketInfo.rounding.nextRoundingValue(prevBucket.key);
while (key != nextBucket.key) {
iter.add(createBucket(key, 0, emptyBucketInfo.subAggregations, formatter));
key = emptyBucketInfo.rounding.nextRoundingValue(key);
}
}
prevBucket = iter.next();
}
} else {
while (iter.hasNext()) {
InternalHistogram.Bucket bucket = iter.next();
if (bucket.getDocCount() < minDocCount) {
iter.remove();
} else {
bucket.aggregations.reduce(reduceContext.cacheRecycler());
}
}
}
if (order != InternalOrder.KEY_ASC && order != InternalOrder.KEY_DESC) {
CollectionUtil.introSort(histo.buckets, order.comparator());
}
return histo;
}
InternalHistogram reduced = (InternalHistogram) aggregations.get(0);
Recycler.V<LongObjectOpenHashMap<List<Histogram.Bucket>>> bucketsByKey = reduceContext.cacheRecycler().longObjectMap(-1);
for (InternalAggregation aggregation : aggregations) {
InternalHistogram<B> histogram = (InternalHistogram) aggregation;
for (B bucket : histogram.buckets) {
List<Histogram.Bucket> bucketList = bucketsByKey.v().get(bucket.key);
if (bucketList == null) {
bucketList = new ArrayList<Histogram.Bucket>(aggregations.size());
bucketsByKey.v().put(bucket.key, bucketList);
}
bucketList.add(bucket);
}
}
List<B> reducedBuckets = new ArrayList<B>(bucketsByKey.v().size());
Object[] buckets = bucketsByKey.v().values;
boolean[] allocated = bucketsByKey.v().allocated;
for (int i = 0; i < allocated.length; i++) {
if (allocated[i]) {
B bucket = ((List<B>) buckets[i]).get(0).reduce(((List<B>) buckets[i]), reduceContext.cacheRecycler());
if (bucket.getDocCount() >= minDocCount) {
reducedBuckets.add(bucket);
}
}
}
bucketsByKey.release();
// adding empty buckets in needed
if (minDocCount == 0) {
CollectionUtil.introSort(reducedBuckets, order.asc ? InternalOrder.KEY_ASC.comparator() : InternalOrder.KEY_DESC.comparator());
List<B> list = order.asc ? reducedBuckets : Lists.reverse(reducedBuckets);
B prevBucket = null;
ListIterator<B> iter = list.listIterator();
while (iter.hasNext()) {
B nextBucket = list.get(iter.nextIndex());
if (prevBucket != null) {
long key = emptyBucketInfo.rounding.nextRoundingValue(prevBucket.key);
while (key != nextBucket.key) {
iter.add(createBucket(key, 0, emptyBucketInfo.subAggregations, formatter));
key = emptyBucketInfo.rounding.nextRoundingValue(key);
}
}
prevBucket = iter.next();
}
if (order != InternalOrder.KEY_ASC && order != InternalOrder.KEY_DESC) {
CollectionUtil.introSort(reducedBuckets, order.comparator());
}
} else {
CollectionUtil.introSort(reducedBuckets, order.comparator());
}
reduced.buckets = reducedBuckets;
return reduced;
}
protected B createBucket(long key, long docCount, InternalAggregations aggregations, ValueFormatter formatter) {
return (B) new InternalHistogram.Bucket(key, docCount, aggregations);
}
@Override
public void readFrom(StreamInput in) throws IOException {
name = in.readString();
order = InternalOrder.Streams.readOrder(in);
minDocCount = in.readVLong();
if (minDocCount == 0) {
emptyBucketInfo = EmptyBucketInfo.readFrom(in);
}
formatter = ValueFormatterStreams.readOptional(in);
keyed = in.readBoolean();
int size = in.readVInt();
List<B> buckets = new ArrayList<B>(size);
for (int i = 0; i < size; i++) {
buckets.add(createBucket(in.readLong(), in.readVLong(), InternalAggregations.readAggregations(in), formatter));
}
this.buckets = buckets;
this.bucketsMap = null;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
InternalOrder.Streams.writeOrder(order, out);
out.writeVLong(minDocCount);
if (minDocCount == 0) {
EmptyBucketInfo.writeTo(emptyBucketInfo, out);
}
ValueFormatterStreams.writeOptional(formatter, out);
out.writeBoolean(keyed);
out.writeVInt(buckets.size());
for (B bucket : buckets) {
out.writeLong(bucket.key);
out.writeVLong(bucket.docCount);
bucket.aggregations.writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
if (keyed) {
builder.startObject(CommonFields.BUCKETS);
} else {
builder.startArray(CommonFields.BUCKETS);
}
for (B bucket : buckets) {
if (formatter != null) {
Text keyTxt = new StringText(formatter.format(bucket.key));
if (keyed) {
builder.startObject(keyTxt.string());
} else {
builder.startObject();
}
builder.field(CommonFields.KEY_AS_STRING, keyTxt);
} else {
if (keyed) {
builder.startObject(String.valueOf(bucket.getKeyAsNumber()));
} else {
builder.startObject();
}
}
builder.field(CommonFields.KEY, bucket.key);
builder.field(CommonFields.DOC_COUNT, bucket.docCount);
bucket.aggregations.toXContentInternal(builder, params);
builder.endObject();
}
if (keyed) {
builder.endObject();
} else {
builder.endArray();
}
return builder.endObject();
}
} | 1no label
| src_main_java_org_elasticsearch_search_aggregations_bucket_histogram_InternalHistogram.java |
16 | public interface PersistenceService {
/**
* This method is invoked when starting a set of related persistence operations in the current thread. If the underlying
* persistence implementation is a database this will likely start a transaction. This method will
* generally only be used from code that operates outside the scope of an action, for example an action
* that does some processing in the background.
*/
void startRelatedOperations();
/**
* This method is invoked when completing a set of related persistence operations. This method must
* be invoked following {@link #startRelatedOperations()} and only a single time. T
* @param save if the operation should be saved, false if the operation should not be saved.
*/
void completeRelatedOperations(boolean save);
/**
* Checks if <code>tagId</code> is used on at least one component in the database.
* @param tagId tag ID
* @return true there are components tagged with <code>tagId</code>; false, otherwise.
*/
boolean hasComponentsTaggedBy(String tagId);
/**
* Returns the component with the specified external key and component type.
* @param externalKey to use for search criteria
* @param componentType to use with external key
* @param <T> type of component
* @return instance of component with the given type or null if the component cannot be found.
*/
<T extends AbstractComponent> T getComponent(String externalKey, Class<T> componentType);
/**
* Returns the component with the specified external key and component type.
* @param externalKey to use for search criteria
* @param componentType to use with external key
* @return instance of component with the given type or null if the component cannot
* be found.
*/
AbstractComponent getComponent(String externalKey, String componentType);
} | 0true
| mctcore_src_main_java_gov_nasa_arc_mct_api_persistence_PersistenceService.java |
1,719 | return new UnmodifiableIterator<KType>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public KType next() {
return iterator.next().value;
}
}; | 0true
| src_main_java_org_elasticsearch_common_collect_ImmutableOpenMap.java |
1,454 | public class TitanHadoopSetupImpl extends TitanHadoopSetupCommon {
private final StandardTitanGraph graph;
private final StandardTitanTx tx;
public TitanHadoopSetupImpl(final Configuration config) {
BasicConfiguration bc = ModifiableHadoopConfiguration.of(config).getInputConf();
graph = (StandardTitanGraph)TitanFactory.open(bc);
tx = (StandardTitanTx)graph.buildTransaction().readOnly().setVertexCacheSize(200).start();
}
@Override
public TypeInspector getTypeInspector() {
//Pre-load schema
for (TitanSchemaCategory sc : TitanSchemaCategory.values()) {
for (TitanVertex k : tx.getVertices(BaseKey.SchemaCategory, sc)) {
assert k instanceof TitanSchemaVertex;
TitanSchemaVertex s = (TitanSchemaVertex)k;
if (sc.hasName()) {
String name = s.getName();
Preconditions.checkNotNull(name);
}
TypeDefinitionMap dm = s.getDefinition();
Preconditions.checkNotNull(dm);
s.getRelated(TypeDefinitionCategory.TYPE_MODIFIER, Direction.OUT);
s.getRelated(TypeDefinitionCategory.TYPE_MODIFIER, Direction.IN);
}
}
return tx;
}
@Override
public SystemTypeInspector getSystemTypeInspector() {
return new SystemTypeInspector() {
@Override
public boolean isSystemType(long typeid) {
return IDManager.isSystemRelationTypeId(typeid);
}
@Override
public boolean isVertexExistsSystemType(long typeid) {
return typeid == BaseKey.VertexExists.getLongId();
}
@Override
public boolean isVertexLabelSystemType(long typeid) {
return typeid == BaseLabel.VertexLabelEdge.getLongId();
}
@Override
public boolean isTypeSystemType(long typeid) {
return typeid == BaseKey.SchemaCategory.getLongId() ||
typeid == BaseKey.SchemaDefinitionProperty.getLongId() ||
typeid == BaseKey.SchemaDefinitionDesc.getLongId() ||
typeid == BaseKey.SchemaName.getLongId() ||
typeid == BaseLabel.SchemaDefinitionEdge.getLongId();
}
};
}
@Override
public VertexReader getVertexReader() {
return new VertexReader() {
@Override
public long getVertexId(StaticBuffer key) {
return graph.getIDManager().getKeyID(key);
}
};
}
@Override
public RelationReader getRelationReader(long vertexid) {
return graph.getEdgeSerializer();
}
@Override
public void close() {
tx.rollback();
graph.shutdown();
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_util_input_current_TitanHadoopSetupImpl.java |
3,325 | public class FSTBytesIndexFieldData extends AbstractBytesIndexFieldData<FSTBytesAtomicFieldData> {
private final CircuitBreakerService breakerService;
public static class Builder implements IndexFieldData.Builder {
@Override
public IndexFieldData<FSTBytesAtomicFieldData> build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper,
IndexFieldDataCache cache, CircuitBreakerService breakerService) {
return new FSTBytesIndexFieldData(index, indexSettings, mapper.names(), mapper.fieldDataType(), cache, breakerService);
}
}
FSTBytesIndexFieldData(Index index, @IndexSettings Settings indexSettings, FieldMapper.Names fieldNames, FieldDataType fieldDataType,
IndexFieldDataCache cache, CircuitBreakerService breakerService) {
super(index, indexSettings, fieldNames, fieldDataType, cache);
this.breakerService = breakerService;
}
@Override
public FSTBytesAtomicFieldData loadDirect(AtomicReaderContext context) throws Exception {
AtomicReader reader = context.reader();
Terms terms = reader.terms(getFieldNames().indexName());
FSTBytesAtomicFieldData data = null;
// TODO: Use an actual estimator to estimate before loading.
NonEstimatingEstimator estimator = new NonEstimatingEstimator(breakerService.getBreaker());
if (terms == null) {
data = FSTBytesAtomicFieldData.empty(reader.maxDoc());
estimator.afterLoad(null, data.getMemorySizeInBytes());
return data;
}
PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
org.apache.lucene.util.fst.Builder<Long> fstBuilder = new org.apache.lucene.util.fst.Builder<Long>(INPUT_TYPE.BYTE1, outputs);
final IntsRef scratch = new IntsRef();
final long numTerms;
if (regex == null && frequency == null) {
numTerms = terms.size();
} else {
numTerms = -1;
}
final float acceptableTransientOverheadRatio = fieldDataType.getSettings().getAsFloat("acceptable_transient_overhead_ratio", OrdinalsBuilder.DEFAULT_ACCEPTABLE_OVERHEAD_RATIO);
OrdinalsBuilder builder = new OrdinalsBuilder(numTerms, reader.maxDoc(), acceptableTransientOverheadRatio);
boolean success = false;
try {
// we don't store an ord 0 in the FST since we could have an empty string in there and FST don't support
// empty strings twice. ie. them merge fails for long output.
TermsEnum termsEnum = filter(terms, reader);
DocsEnum docsEnum = null;
for (BytesRef term = termsEnum.next(); term != null; term = termsEnum.next()) {
final long termOrd = builder.nextOrdinal();
assert termOrd > 0;
fstBuilder.add(Util.toIntsRef(term, scratch), (long)termOrd);
docsEnum = termsEnum.docs(null, docsEnum, DocsEnum.FLAG_NONE);
for (int docId = docsEnum.nextDoc(); docId != DocsEnum.NO_MORE_DOCS; docId = docsEnum.nextDoc()) {
builder.addDoc(docId);
}
}
FST<Long> fst = fstBuilder.finish();
final Ordinals ordinals = builder.build(fieldDataType.getSettings());
data = new FSTBytesAtomicFieldData(fst, ordinals);
success = true;
return data;
} finally {
if (success) {
estimator.afterLoad(null, data.getMemorySizeInBytes());
}
builder.close();
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_FSTBytesIndexFieldData.java |
604 | public class TransportGetSettingsAction extends TransportMasterNodeReadOperationAction<GetSettingsRequest, GetSettingsResponse> {
private final SettingsFilter settingsFilter;
@Inject
public TransportGetSettingsAction(Settings settings, TransportService transportService, ClusterService clusterService,
ThreadPool threadPool, SettingsFilter settingsFilter) {
super(settings, transportService, clusterService, threadPool);
this.settingsFilter = settingsFilter;
}
@Override
protected String transportAction() {
return GetSettingsAction.NAME;
}
@Override
protected String executor() {
// Very lightweight operation
return ThreadPool.Names.SAME;
}
@Override
protected GetSettingsRequest newRequest() {
return new GetSettingsRequest();
}
@Override
protected GetSettingsResponse newResponse() {
return new GetSettingsResponse();
}
@Override
protected void masterOperation(GetSettingsRequest request, ClusterState state, ActionListener<GetSettingsResponse> listener) throws ElasticsearchException {
request.indices(state.metaData().concreteIndices(request.indices(), request.indicesOptions()));
ImmutableOpenMap.Builder<String, Settings> indexToSettingsBuilder = ImmutableOpenMap.builder();
for (String concreteIndex : request.indices()) {
IndexMetaData indexMetaData = state.getMetaData().index(concreteIndex);
if (indexMetaData == null) {
continue;
}
Settings settings = settingsFilter.filterSettings(indexMetaData.settings());
if (!CollectionUtils.isEmpty(request.names())) {
ImmutableSettings.Builder settingsBuilder = ImmutableSettings.builder();
for (Map.Entry<String, String> entry : settings.getAsMap().entrySet()) {
if (Regex.simpleMatch(request.names(), entry.getKey())) {
settingsBuilder.put(entry.getKey(), entry.getValue());
}
}
settings = settingsBuilder.build();
}
indexToSettingsBuilder.put(concreteIndex, settings);
}
listener.onResponse(new GetSettingsResponse(indexToSettingsBuilder.build()));
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_settings_get_TransportGetSettingsAction.java |
509 | @RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
public class MapStableReadStressTest extends StressTestSupport {
public static final int CLIENT_THREAD_COUNT = 5;
public static final int MAP_SIZE = 100 * 1000;
private HazelcastInstance client;
private IMap<Integer, Integer> map;
private StressThread[] stressThreads;
@Before
public void setUp() {
super.setUp();
ClientConfig clientConfig = new ClientConfig();
clientConfig.setRedoOperation(true);
client = HazelcastClient.newHazelcastClient(clientConfig);
map = client.getMap("map");
stressThreads = new StressThread[CLIENT_THREAD_COUNT];
for (int k = 0; k < stressThreads.length; k++) {
stressThreads[k] = new StressThread();
stressThreads[k].start();
}
}
@After
public void tearDown() {
super.tearDown();
if (client != null) {
client.shutdown();
}
}
//@Test
public void testChangingCluster() {
test(true);
}
@Test
public void testFixedCluster() {
test(false);
}
public void test(boolean clusterChangeEnabled) {
setClusterChangeEnabled(clusterChangeEnabled);
fillMap();
startAndWaitForTestCompletion();
joinAll(stressThreads);
}
private void fillMap() {
System.out.println("==================================================================");
System.out.println("Inserting data in map");
System.out.println("==================================================================");
for (int k = 0; k < MAP_SIZE; k++) {
map.put(k, k);
if (k % 10000 == 0) {
System.out.println("Inserted data: "+k);
}
}
System.out.println("==================================================================");
System.out.println("Completed with inserting data in map");
System.out.println("==================================================================");
}
public class StressThread extends TestThread {
@Override
public void doRun() throws Exception {
while (!isStopped()) {
int key = random.nextInt(MAP_SIZE);
int value = map.get(key);
assertEquals("The value for the key was not consistent", key, value);
}
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_stress_MapStableReadStressTest.java |
29 | @Service("blFulfillmentGroupFieldService")
public class FulfillmentGroupFieldServiceImpl extends AbstractRuleBuilderFieldService {
@Override
public void init() {
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupFirstName")
.name("address.firstName")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupLastName")
.name("address.lastName")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupAddresLine1")
.name("address.addressLine1")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupAddressLine2")
.name("address.addressLine2")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupCity")
.name("address.city")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupCounty")
.name("address.county")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupState")
.name("address.state.name")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupPostalCode")
.name("address.postalCode")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupCountry")
.name("address.country.name")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupPrimaryPhone")
.name("address.phonePrimary.phoneNumber")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupSecondaryPhone")
.name("address.phoneSecondary.phoneNumber")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupFax")
.name("address.phoneFax.phoneNumber")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupTotal")
.name("total")
.operators("blcOperators_Numeric")
.options("[]")
.type(SupportedFieldType.MONEY)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupPrice")
.name("fulfillmentPrice")
.operators("blcOperators_Numeric")
.options("[]")
.type(SupportedFieldType.MONEY)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupRetailPrice")
.name("retailFulfillmentPrice")
.operators("blcOperators_Numeric")
.options("[]")
.type(SupportedFieldType.MONEY)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupSalePrice")
.name("saleFulfillmentPrice")
.operators("blcOperators_Numeric")
.options("[]")
.type(SupportedFieldType.MONEY)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupType")
.name("type")
.operators("blcOperators_Enumeration")
.options("blcOptions_FulfillmentType")
.type(SupportedFieldType.BROADLEAF_ENUMERATION)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupMerchandiseTotal")
.name("merchandiseTotal")
.operators("blcOperators_Numeric")
.options("[]")
.type(SupportedFieldType.MONEY)
.build());
fields.add(new FieldData.Builder()
.label("rule_fulfillmentGroupFulfillmentOption")
.name("fulfillmentOption.name")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
}
@Override
public String getName() {
return RuleIdentifier.FULFILLMENTGROUP;
}
@Override
public String getDtoClassName() {
return "org.broadleafcommerce.core.order.domain.FulfillmentGroupImpl";
}
} | 0true
| admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_FulfillmentGroupFieldServiceImpl.java |
871 | public class SetBackupOperation extends AtomicReferenceBaseOperation implements BackupOperation {
private Data newValue;
public SetBackupOperation() {
}
public SetBackupOperation(String name, Data newValue) {
super(name);
this.newValue = newValue;
}
@Override
public void run() throws Exception {
ReferenceWrapper reference = getReference();
reference.set(newValue);
}
@Override
public int getId() {
return AtomicReferenceDataSerializerHook.SET_BACKUP;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(newValue);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
newValue = in.readObject();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_SetBackupOperation.java |
930 | public interface LockStoreInfo {
int getBackupCount();
int getAsyncBackupCount();
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockStoreInfo.java |
6,323 | public static class Names {
public static final String SAME = "same";
public static final String GENERIC = "generic";
public static final String GET = "get";
public static final String INDEX = "index";
public static final String BULK = "bulk";
public static final String SEARCH = "search";
public static final String SUGGEST = "suggest";
public static final String PERCOLATE = "percolate";
public static final String MANAGEMENT = "management";
public static final String FLUSH = "flush";
public static final String MERGE = "merge";
public static final String REFRESH = "refresh";
public static final String WARMER = "warmer";
public static final String SNAPSHOT = "snapshot";
public static final String OPTIMIZE = "optimize";
} | 1no label
| src_main_java_org_elasticsearch_threadpool_ThreadPool.java |
1,426 | public class OChannelBinaryServer extends OChannelBinary {
public OChannelBinaryServer(final Socket iSocket, final OContextConfiguration iConfig) throws IOException {
super(iSocket, iConfig);
inStream = new BufferedInputStream(socket.getInputStream(), socketBufferSize);
outStream = new BufferedOutputStream(socket.getOutputStream(), socketBufferSize);
out = new DataOutputStream(outStream);
in = new DataInputStream(inStream);
connected();
}
} | 0true
| enterprise_src_main_java_com_orientechnologies_orient_enterprise_channel_binary_OChannelBinaryServer.java |
3,453 | threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(new Runnable() {
@Override
public void run() {
try {
indexShard.translog().sync();
} catch (Exception e) {
if (indexShard.state() == IndexShardState.STARTED) {
logger.warn("failed to sync translog", e);
}
}
if (indexShard.state() != IndexShardState.CLOSED) {
flushScheduler = threadPool.schedule(syncInterval, ThreadPool.Names.SAME, Sync.this);
}
}
}); | 1no label
| src_main_java_org_elasticsearch_index_gateway_local_LocalIndexShardGateway.java |
1,851 | return new InternalFactory<Provider<T>>() {
public Provider<T> get(Errors errors, InternalContext context, Dependency dependency) {
return provider;
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_InjectorImpl.java |
2,928 | public class PreBuiltTokenizerFactoryFactoryTests extends ElasticsearchTestCase {
@Test
public void testThatDifferentVersionsCanBeLoaded() {
PreBuiltTokenizerFactoryFactory factory = new PreBuiltTokenizerFactoryFactory(PreBuiltTokenizers.STANDARD.getTokenizerFactory(Version.CURRENT));
TokenizerFactory emptySettingsTokenizerFactory = factory.create("standard", ImmutableSettings.EMPTY);
// different es versions, same lucene version, thus cached
TokenizerFactory former090TokenizerFactory = factory.create("standard", ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.V_0_90_1).build());
TokenizerFactory former090TokenizerFactoryCopy = factory.create("standard", ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.V_0_90_2).build());
TokenizerFactory currentTokenizerFactory = factory.create("standard", ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build());
assertThat(emptySettingsTokenizerFactory, is(currentTokenizerFactory));
assertThat(emptySettingsTokenizerFactory, is(not(former090TokenizerFactory)));
assertThat(emptySettingsTokenizerFactory, is(not(former090TokenizerFactoryCopy)));
assertThat(former090TokenizerFactory, is(former090TokenizerFactoryCopy));
}
} | 0true
| src_test_java_org_elasticsearch_index_analysis_PreBuiltTokenizerFactoryFactoryTests.java |
318 | assertFalse(Iterables.any(GraphDatabaseConfiguration.LOG_NS.getChildren(), new Predicate<ConfigElement>() {
@Override
public boolean apply(ConfigElement elem) {
return elem instanceof ConfigOption<?> && elem.getName().equals("max-write-time");
}
})); | 0true
| titan-test_src_test_java_com_thinkaurelius_titan_diskstorage_configuration_ConfigurationTest.java |
56 | public interface OLock {
public void lock();
public void unlock();
public <V> V callInLock(Callable<V> iCallback) throws Exception;
} | 0true
| commons_src_main_java_com_orientechnologies_common_concur_lock_OLock.java |
1,538 | public class OObjectCustomSerializerMap<TYPE> extends HashMap<Object, Object> implements Serializable,
OObjectLazyCustomSerializer<Map<Object, TYPE>> {
private static final long serialVersionUID = -8606432090996808181L;
private final ORecord<?> sourceRecord;
private final Map<Object, Object> underlying;
private boolean converted = false;
private final Class<?> deserializeClass;
public OObjectCustomSerializerMap(final Class<?> iDeserializeClass, final ORecord<?> iSourceRecord,
final Map<Object, Object> iRecordMap) {
super();
this.sourceRecord = iSourceRecord;
this.underlying = iRecordMap;
converted = iRecordMap.isEmpty();
this.deserializeClass = iDeserializeClass;
}
public OObjectCustomSerializerMap(final Class<?> iDeserializeClass, final ORecord<?> iSourceRecord,
final Map<Object, Object> iRecordMap, final Map<Object, Object> iSourceMap) {
this(iDeserializeClass, iSourceRecord, iRecordMap);
putAll(iSourceMap);
}
@Override
public int size() {
return underlying.size();
}
@Override
public boolean isEmpty() {
return underlying.isEmpty();
}
@Override
public boolean containsKey(final Object k) {
return underlying.containsKey(k);
}
@Override
public boolean containsValue(final Object o) {
boolean underlyingContains = underlying.containsValue(OObjectEntitySerializer.serializeFieldValue(deserializeClass, o));
return underlyingContains || super.containsValue(o);
}
@Override
public Object put(final Object iKey, final Object e) {
setDirty();
underlying.put(iKey, OObjectEntitySerializer.serializeFieldValue(deserializeClass, e));
return super.put(iKey, e);
}
@Override
public Object remove(final Object iKey) {
underlying.remove((String) iKey);
setDirty();
return super.remove(iKey);
}
@Override
public void clear() {
converted = true;
underlying.clear();
super.clear();
setDirty();
}
public boolean isConverted() {
return converted;
}
@Override
public String toString() {
return underlying.toString();
}
@Override
public Set<java.util.Map.Entry<Object, Object>> entrySet() {
convertAll();
return super.entrySet();
}
@Override
public Object get(final Object iKey) {
convert(iKey);
return super.get(iKey);
}
@Override
public Set<Object> keySet() {
convertAll();
return underlying.keySet();
}
@Override
public void putAll(final Map<? extends Object, ? extends Object> iMap) {
for (java.util.Map.Entry<? extends Object, ? extends Object> e : iMap.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@Override
public Collection<Object> values() {
convertAll();
return super.values();
}
public void setDirty() {
if (sourceRecord != null)
sourceRecord.setDirty();
}
/**
* Assure that the requested key is converted.
*/
private void convert(final Object iKey) {
if (converted)
return;
if (super.containsKey(iKey))
return;
Object o = underlying.get(String.valueOf(iKey));
super.put(iKey, OObjectEntitySerializer.deserializeFieldValue(deserializeClass, o));
}
public void detach() {
convertAll();
}
public void detach(boolean nonProxiedInstance) {
convertAll();
}
public void detachAll(boolean nonProxiedInstance) {
convertAll();
}
@Override
@SuppressWarnings("unchecked")
public Map<Object, TYPE> getNonOrientInstance() {
Map<Object, TYPE> map = new HashMap<Object, TYPE>();
map.putAll((Map<Object, TYPE>) this);
return map;
}
@Override
public Object getUnderlying() {
return underlying;
}
/**
* Converts all the items
*/
protected void convertAll() {
if (converted)
return;
for (java.util.Map.Entry<Object, Object> e : underlying.entrySet())
super.put(e.getKey(), OObjectEntitySerializer.deserializeFieldValue(deserializeClass, e.getValue()));
converted = true;
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_serialization_OObjectCustomSerializerMap.java |
2,477 | public class SizeBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E> {
private final BlockingQueue<E> queue;
private final int capacity;
private final AtomicInteger size = new AtomicInteger();
public SizeBlockingQueue(BlockingQueue<E> queue, int capacity) {
assert capacity >= 0;
this.queue = queue;
this.capacity = capacity;
}
@Override
public int size() {
return size.get();
}
public int capacity() {
return this.capacity;
}
@Override
public Iterator<E> iterator() {
final Iterator<E> it = queue.iterator();
return new Iterator<E>() {
E current;
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public E next() {
current = it.next();
return current;
}
@Override
public void remove() {
// note, we can't call #remove on the iterator because we need to know
// if it was removed or not
if (queue.remove(current)) {
size.decrementAndGet();
}
}
};
}
@Override
public E peek() {
return queue.peek();
}
@Override
public E poll() {
E e = queue.poll();
if (e != null) {
size.decrementAndGet();
}
return e;
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
E e = queue.poll(timeout, unit);
if (e != null) {
size.decrementAndGet();
}
return e;
}
@Override
public boolean remove(Object o) {
boolean v = queue.remove(o);
if (v) {
size.decrementAndGet();
}
return v;
}
/**
* Forces adding an element to the queue, without doing size checks.
*/
public void forcePut(E e) throws InterruptedException {
size.incrementAndGet();
try {
queue.put(e);
} catch (InterruptedException ie) {
size.decrementAndGet();
throw ie;
}
}
@Override
public boolean offer(E e) {
int count = size.incrementAndGet();
if (count > capacity) {
size.decrementAndGet();
return false;
}
boolean offered = queue.offer(e);
if (!offered) {
size.decrementAndGet();
}
return offered;
}
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
// note, not used in ThreadPoolExecutor
throw new ElasticsearchIllegalStateException("offer with timeout not allowed on size queue");
}
@Override
public void put(E e) throws InterruptedException {
// note, not used in ThreadPoolExecutor
throw new ElasticsearchIllegalStateException("put not allowed on size queue");
}
@Override
public E take() throws InterruptedException {
E e;
try {
e = queue.take();
size.decrementAndGet();
} catch (InterruptedException ie) {
throw ie;
}
return e;
}
@Override
public int remainingCapacity() {
return capacity - size.get();
}
@Override
public int drainTo(Collection<? super E> c) {
int v = queue.drainTo(c);
size.addAndGet(-v);
return v;
}
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
int v = queue.drainTo(c, maxElements);
size.addAndGet(-v);
return v;
}
@Override
public Object[] toArray() {
return queue.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return (T[]) queue.toArray(a);
}
@Override
public boolean contains(Object o) {
return queue.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return queue.containsAll(c);
}
} | 0true
| src_main_java_org_elasticsearch_common_util_concurrent_SizeBlockingQueue.java |
415 | public class GetSnapshotsResponse extends ActionResponse implements ToXContent {
private ImmutableList<SnapshotInfo> snapshots = ImmutableList.of();
GetSnapshotsResponse() {
}
GetSnapshotsResponse(ImmutableList<SnapshotInfo> snapshots) {
this.snapshots = snapshots;
}
/**
* Returns the list of snapshots
*
* @return the list of snapshots
*/
public ImmutableList<SnapshotInfo> getSnapshots() {
return snapshots;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
int size = in.readVInt();
ImmutableList.Builder<SnapshotInfo> builder = ImmutableList.builder();
for (int i = 0; i < size; i++) {
builder.add(SnapshotInfo.readSnapshotInfo(in));
}
snapshots = builder.build();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(snapshots.size());
for (SnapshotInfo snapshotInfo : snapshots) {
snapshotInfo.writeTo(out);
}
}
static final class Fields {
static final XContentBuilderString SNAPSHOTS = new XContentBuilderString("snapshots");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startArray(Fields.SNAPSHOTS);
for (SnapshotInfo snapshotInfo : snapshots) {
snapshotInfo.toXContent(builder, params);
}
builder.endArray();
return builder;
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_GetSnapshotsResponse.java |
1,965 | public static class MemberImpl implements Member, Serializable {
private final Class<?> declaringClass;
private final String name;
private final int modifiers;
private final boolean synthetic;
private final Class<? extends Member> memberType;
private final String memberKey;
private MemberImpl(Member member) {
this.declaringClass = member.getDeclaringClass();
this.name = member.getName();
this.modifiers = member.getModifiers();
this.synthetic = member.isSynthetic();
this.memberType = memberType(member);
this.memberKey = memberKey(member);
}
public Class getDeclaringClass() {
return declaringClass;
}
public String getName() {
return name;
}
public int getModifiers() {
return modifiers;
}
public boolean isSynthetic() {
return synthetic;
}
@Override
public String toString() {
return MoreTypes.toString(this);
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_MoreTypes.java |
3,281 | return new FilteredTermsEnum(termsEnum, false) {
@Override
protected AcceptStatus accept(BytesRef term) throws IOException {
// we stop accepting terms once we moved across the prefix codec terms - redundant values!
return NumericUtils.getPrefixCodedIntShift(term) == 0 ? AcceptStatus.YES : AcceptStatus.END;
}
}; | 0true
| src_main_java_org_elasticsearch_index_fielddata_ordinals_OrdinalsBuilder.java |
303 | static class DumPredicate implements Predicate {
public boolean apply(Map.Entry mapEntry) {
return false;
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapBasicTest.java |
146 | @Entity
@Table(name = "BLC_SC_ITEM_CRITERIA")
@Inheritance(strategy=InheritanceType.JOINED)
@AdminPresentationClass(friendlyName = "StructuredContentItemCriteriaImpl_baseStructuredContentItemCriteria")
public class StructuredContentItemCriteriaImpl implements StructuredContentItemCriteria {
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator= "SCItemCriteriaId")
@GenericGenerator(
name="SCItemCriteriaId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="StructuredContentItemCriteriaImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.cms.page.domain.StructuredContentItemCriteriaImpl")
}
)
@Column(name = "SC_ITEM_CRITERIA_ID")
@AdminPresentation(friendlyName = "StructuredContentItemCriteriaImpl_Item_Criteria_Id", group = "StructuredContentItemCriteriaImpl_Description", visibility =VisibilityEnum.HIDDEN_ALL)
protected Long id;
@Column(name = "QUANTITY", nullable=false)
@AdminPresentation(friendlyName = "StructuredContentItemCriteriaImpl_Quantity", group = "StructuredContentItemCriteriaImpl_Description", visibility =VisibilityEnum.HIDDEN_ALL)
protected Integer quantity;
@Lob
@Type(type = "org.hibernate.type.StringClobType")
@Column(name = "ORDER_ITEM_MATCH_RULE", length = Integer.MAX_VALUE - 1)
@AdminPresentation(friendlyName = "StructuredContentItemCriteriaImpl_Order_Item_Match_Rule", group = "StructuredContentItemCriteriaImpl_Description", visibility = VisibilityEnum.HIDDEN_ALL)
protected String orderItemMatchRule;
@ManyToOne(targetEntity = StructuredContentImpl.class)
@JoinTable(name = "BLC_QUAL_CRIT_SC_XREF", joinColumns = @JoinColumn(name = "SC_ITEM_CRITERIA_ID"), inverseJoinColumns = @JoinColumn(name = "SC_ID"))
protected StructuredContent structuredContent;
/* (non-Javadoc)
* @see org.broadleafcommerce.core.offer.domain.StructuredContentItemCriteria#getId()
*/
@Override
public Long getId() {
return id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.offer.domain.StructuredContentItemCriteria#setId(java.lang.Long)
*/
@Override
public void setId(Long id) {
this.id = id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.offer.domain.StructuredContentItemCriteria#getReceiveQuantity()
*/
@Override
public Integer getQuantity() {
return quantity;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.offer.domain.StructuredContentItemCriteria#setReceiveQuantity(java.lang.Integer)
*/
@Override
public void setQuantity(Integer receiveQuantity) {
this.quantity = receiveQuantity;
}
@Override
public String getMatchRule() {
return orderItemMatchRule;
}
@Override
public void setMatchRule(String matchRule) {
this.orderItemMatchRule = matchRule;
}
@Override
public StructuredContent getStructuredContent() {
return structuredContent;
}
@Override
public void setStructuredContent(StructuredContent structuredContent) {
this.structuredContent = structuredContent;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((orderItemMatchRule == null) ? 0 : orderItemMatchRule.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;
StructuredContentItemCriteriaImpl other = (StructuredContentItemCriteriaImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (orderItemMatchRule == null) {
if (other.orderItemMatchRule != null)
return false;
} else if (!orderItemMatchRule.equals(other.orderItemMatchRule))
return false;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
return true;
}
@Override
public StructuredContentItemCriteria cloneEntity() {
StructuredContentItemCriteriaImpl newField = new StructuredContentItemCriteriaImpl();
newField.quantity = quantity;
newField.orderItemMatchRule = orderItemMatchRule;
return newField;
}
} | 1no label
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentItemCriteriaImpl.java |
1,052 | Collections.sort(indexSearchResults, new Comparator<OIndexSearchResult>() {
public int compare(final OIndexSearchResult searchResultOne, final OIndexSearchResult searchResultTwo) {
return searchResultTwo.getFieldCount() - searchResultOne.getFieldCount();
}
}); | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLSelect.java |
744 | public class SkuFeeType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, SkuFeeType> TYPES = new LinkedHashMap<String, SkuFeeType>();
public static final SkuFeeType FULFILLMENT = new SkuFeeType("FULFILLMENT", "Fulfillment");
public static SkuFeeType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public SkuFeeType() {
//do nothing
}
public SkuFeeType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
@Override
public String getType() {
return type;
}
@Override
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SkuFeeType other = (SkuFeeType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_service_type_SkuFeeType.java |
618 | private static final class MultiValuesTransformer implements OIndexEngine.ValuesTransformer<Set<OIdentifiable>> {
private static final MultiValuesTransformer INSTANCE = new MultiValuesTransformer();
@Override
public Collection<OIdentifiable> transformFromValue(Set<OIdentifiable> value) {
return value;
}
@Override
public Set<OIdentifiable> transformToValue(Collection<OIdentifiable> collection) {
return (Set<OIdentifiable>) collection;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java |
1,507 | public static class Map extends Mapper<NullWritable, FaunusVertex, Text, LongWritable> {
private Closure keyClosure;
private Closure valueClosure;
private boolean isVertex;
private CounterMap<Object> map;
private int mapSpillOver;
private SafeMapperOutputs outputs;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
Configuration hc = DEFAULT_COMPAT.getContextConfiguration(context);
ModifiableHadoopConfiguration titanConf = ModifiableHadoopConfiguration.of(hc);
try {
this.mapSpillOver = titanConf.get(PIPELINE_MAP_SPILL_OVER);
final String keyClosureString = context.getConfiguration().get(KEY_CLOSURE, null);
if (null == keyClosureString)
this.keyClosure = null;
else
this.keyClosure = (Closure) engine.eval(keyClosureString);
final String valueClosureString = context.getConfiguration().get(VALUE_CLOSURE, null);
if (null == valueClosureString)
this.valueClosure = null;
else
this.valueClosure = (Closure) engine.eval(valueClosureString);
} catch (final ScriptException e) {
throw new IOException(e.getMessage(), e);
}
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
this.map = new CounterMap<Object>();
this.outputs = new SafeMapperOutputs(context);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, Text, LongWritable>.Context context) throws IOException, InterruptedException {
if (this.isVertex) {
if (value.hasPaths()) {
final Object object = (null == this.keyClosure) ? new FaunusVertex.MicroVertex(value.getLongId()) : this.keyClosure.call(value);
final Number number = (null == this.valueClosure) ? 1 : (Number) this.valueClosure.call(value);
this.map.incr(object, number.longValue() * value.pathCount());
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L);
}
} else {
long edgesProcessed = 0;
for (final Edge e : value.getEdges(Direction.OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
final Object object = (null == this.keyClosure) ? new StandardFaunusEdge.MicroEdge(edge.getLongId()) : this.keyClosure.call(edge);
final Number number = (null == this.valueClosure) ? 1 : (Number) this.valueClosure.call(edge);
this.map.incr(object, number.longValue() * edge.pathCount());
edgesProcessed++;
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed);
}
// protected against memory explosion
if (this.map.size() > this.mapSpillOver) {
this.dischargeMap(context);
}
this.outputs.write(Tokens.GRAPH, NullWritable.get(), value);
}
private final Text textWritable = new Text();
private final LongWritable longWritable = new LongWritable();
public void dischargeMap(final Mapper<NullWritable, FaunusVertex, Text, LongWritable>.Context context) throws IOException, InterruptedException {
for (final java.util.Map.Entry<Object, Long> entry : this.map.entrySet()) {
this.textWritable.set(null == entry.getKey() ? Tokens.NULL : entry.getKey().toString());
this.longWritable.set(entry.getValue());
context.write(this.textWritable, this.longWritable);
}
this.map.clear();
}
@Override
public void cleanup(final Mapper<NullWritable, FaunusVertex, Text, LongWritable>.Context context) throws IOException, InterruptedException {
this.dischargeMap(context);
this.outputs.close();
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_GroupCountMapReduce.java |
91 | mapClient.addEntryListener(new EntryAdapter<Integer, GenericEvent>() {
public void entryAdded(EntryEvent<Integer, GenericEvent> event) {
adds++;
}
public void entryEvicted(EntryEvent<Integer, GenericEvent> event) {
if (event.getValue() == null) evictionsNull++;
}
}, true); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_ClientEntryListenerDisconnectTest.java |
2,366 | PB {
@Override
public long toBytes(long size) {
return x(size, C5 / C0, MAX / (C5 / C0));
}
@Override
public long toKB(long size) {
return x(size, C5 / C1, MAX / (C5 / C1));
}
@Override
public long toMB(long size) {
return x(size, C5 / C2, MAX / (C5 / C2));
}
@Override
public long toGB(long size) {
return x(size, C5 / C3, MAX / (C5 / C3));
}
@Override
public long toTB(long size) {
return x(size, C5 / C4, MAX / (C5 / C4));
}
@Override
public long toPB(long size) {
return size;
}
}; | 0true
| src_main_java_org_elasticsearch_common_unit_ByteSizeUnit.java |
3,362 | public class NonEstimatingEstimator implements AbstractIndexFieldData.PerValueEstimator {
private final MemoryCircuitBreaker breaker;
NonEstimatingEstimator(MemoryCircuitBreaker breaker) {
this.breaker = breaker;
}
@Override
public long bytesPerValue(BytesRef term) {
return 0;
}
@Override
public TermsEnum beforeLoad(Terms terms) throws IOException {
return null;
}
@Override
public void afterLoad(@Nullable TermsEnum termsEnum, long actualUsed) {
breaker.addWithoutBreaking(actualUsed);
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_NonEstimatingEstimator.java |
3,373 | public static class SingleSparse extends PackedArrayAtomicFieldData {
private final PackedInts.Mutable values;
private final long minValue;
private final long missingValue;
private final long numOrds;
public SingleSparse(PackedInts.Mutable values, long minValue, int numDocs, long missingValue, long numOrds) {
super(numDocs);
this.values = values;
this.minValue = minValue;
this.missingValue = missingValue;
this.numOrds = numOrds;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrds;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = values.ramBytesUsed() + 2 * RamUsageEstimator.NUM_BYTES_LONG;
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, minValue, missingValue);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, minValue, missingValue);
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final PackedInts.Mutable values;
private final long minValue;
private final long missingValue;
LongValues(PackedInts.Mutable values, long minValue, long missingValue) {
super(false);
this.values = values;
this.minValue = minValue;
this.missingValue = missingValue;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return values.get(docId) != missingValue ? 1 : 0;
}
@Override
public long nextValue() {
return minValue + values.get(docId);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues {
private final PackedInts.Mutable values;
private final long minValue;
private final long missingValue;
DoubleValues(PackedInts.Mutable values, long minValue, long missingValue) {
super(false);
this.values = values;
this.minValue = minValue;
this.missingValue = missingValue;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return values.get(docId) != missingValue ? 1 : 0;
}
@Override
public double nextValue() {
return minValue + values.get(docId);
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_PackedArrayAtomicFieldData.java |
960 | public abstract class NodeOperationRequest extends TransportRequest {
private String nodeId;
protected NodeOperationRequest() {
}
protected NodeOperationRequest(NodesOperationRequest request, String nodeId) {
super(request);
this.nodeId = nodeId;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
nodeId = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(nodeId);
}
} | 0true
| src_main_java_org_elasticsearch_action_support_nodes_NodeOperationRequest.java |
2,209 | return new Filter() {
@Override
public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) {
return new DocIdSet() {
@Override
public DocIdSetIterator iterator() {
return null;
}
@Override
public boolean isCacheable() {
return true;
}
};
}
}; | 0true
| src_test_java_org_elasticsearch_common_lucene_search_XBooleanFilterLuceneTests.java |
806 | public class CompareAndSetRequest extends AtomicLongRequest {
private long expect;
public CompareAndSetRequest() {
}
public CompareAndSetRequest(String name, long expect, long value) {
super(name, value);
this.expect = expect;
}
@Override
protected Operation prepareOperation() {
return new CompareAndSetOperation(name, expect, delta);
}
@Override
public int getClassId() {
return AtomicLongPortableHook.COMPARE_AND_SET;
}
@Override
public void write(PortableWriter writer) throws IOException {
super.write(writer);
writer.writeLong("e", expect);
}
@Override
public void read(PortableReader reader) throws IOException {
super.read(reader);
expect = reader.readLong("e");
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_CompareAndSetRequest.java |
204 | public class ClientConnection implements Connection, Closeable {
private static final int SLEEP_TIME = 10;
private volatile boolean live = true;
private final ILogger logger = Logger.getLogger(ClientConnection.class);
private final ClientWriteHandler writeHandler;
private final ClientReadHandler readHandler;
private final ClientConnectionManagerImpl connectionManager;
private final int connectionId;
private final SocketChannelWrapper socketChannelWrapper;
private volatile Address remoteEndpoint;
private final ConcurrentMap<Integer, ClientCallFuture> callIdMap
= new ConcurrentHashMap<Integer, ClientCallFuture>();
private final ConcurrentMap<Integer, ClientCallFuture> eventHandlerMap
= new ConcurrentHashMap<Integer, ClientCallFuture>();
private final ByteBuffer readBuffer;
private final SerializationService serializationService;
private final ClientExecutionService executionService;
private final ClientInvocationServiceImpl invocationService;
private boolean readFromSocket = true;
private final AtomicInteger packetCount = new AtomicInteger(0);
private volatile int failedHeartBeat;
public ClientConnection(ClientConnectionManagerImpl connectionManager, IOSelector in, IOSelector out,
int connectionId, SocketChannelWrapper socketChannelWrapper, ClientExecutionService executionService,
ClientInvocationServiceImpl invocationService) throws IOException {
final Socket socket = socketChannelWrapper.socket();
this.connectionManager = connectionManager;
this.serializationService = connectionManager.getSerializationService();
this.executionService = executionService;
this.invocationService = invocationService;
this.socketChannelWrapper = socketChannelWrapper;
this.connectionId = connectionId;
this.readHandler = new ClientReadHandler(this, in, socket.getReceiveBufferSize());
this.writeHandler = new ClientWriteHandler(this, out, socket.getSendBufferSize());
this.readBuffer = ByteBuffer.allocate(socket.getReceiveBufferSize());
}
public void incrementPacketCount() {
packetCount.incrementAndGet();
}
public void decrementPacketCount() {
packetCount.decrementAndGet();
}
public void registerCallId(ClientCallFuture future) {
final int callId = connectionManager.newCallId();
future.getRequest().setCallId(callId);
callIdMap.put(callId, future);
if (future.getHandler() != null) {
eventHandlerMap.put(callId, future);
}
}
public ClientCallFuture deRegisterCallId(int callId) {
return callIdMap.remove(callId);
}
public ClientCallFuture deRegisterEventHandler(int callId) {
return eventHandlerMap.remove(callId);
}
public EventHandler getEventHandler(int callId) {
final ClientCallFuture future = eventHandlerMap.get(callId);
if (future == null) {
return null;
}
return future.getHandler();
}
@Override
public boolean write(SocketWritable packet) {
if (!live) {
if (logger.isFinestEnabled()) {
logger.finest("Connection is closed, won't write packet -> " + packet);
}
return false;
}
if (!isHeartBeating()) {
if (logger.isFinestEnabled()) {
logger.finest("Connection is not heart-beating, won't write packet -> " + packet);
}
return false;
}
writeHandler.enqueueSocketWritable(packet);
return true;
}
public void init() throws IOException {
final ByteBuffer buffer = ByteBuffer.allocate(6);
buffer.put(stringToBytes(Protocols.CLIENT_BINARY));
buffer.put(stringToBytes(ClientTypes.JAVA));
buffer.flip();
socketChannelWrapper.write(buffer);
}
public void write(Data data) throws IOException {
final int totalSize = data.totalSize();
final int bufferSize = ClientConnectionManagerImpl.BUFFER_SIZE;
final ByteBuffer buffer = ByteBuffer.allocate(totalSize > bufferSize ? bufferSize : totalSize);
final DataAdapter packet = new DataAdapter(data);
boolean complete = false;
while (!complete) {
complete = packet.writeTo(buffer);
buffer.flip();
try {
socketChannelWrapper.write(buffer);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
buffer.clear();
}
}
public Data read() throws IOException {
ClientPacket packet = new ClientPacket(serializationService.getSerializationContext());
while (true) {
if (readFromSocket) {
int readBytes = socketChannelWrapper.read(readBuffer);
if (readBytes == -1) {
throw new EOFException("Remote socket closed!");
}
readBuffer.flip();
}
boolean complete = packet.readFrom(readBuffer);
if (complete) {
if (readBuffer.hasRemaining()) {
readFromSocket = false;
} else {
readBuffer.compact();
readFromSocket = true;
}
return packet.getData();
}
readFromSocket = true;
readBuffer.clear();
}
}
@Override
public Address getEndPoint() {
return remoteEndpoint;
}
@Override
public boolean live() {
return live;
}
@Override
public long lastReadTime() {
return readHandler.getLastHandle();
}
@Override
public long lastWriteTime() {
return writeHandler.getLastHandle();
}
@Override
public void close() {
close(null);
}
@Override
public ConnectionType getType() {
return ConnectionType.JAVA_CLIENT;
}
@Override
public boolean isClient() {
return true;
}
@Override
public InetAddress getInetAddress() {
return socketChannelWrapper.socket().getInetAddress();
}
@Override
public InetSocketAddress getRemoteSocketAddress() {
return (InetSocketAddress) socketChannelWrapper.socket().getRemoteSocketAddress();
}
@Override
public int getPort() {
return socketChannelWrapper.socket().getPort();
}
public SocketChannelWrapper getSocketChannelWrapper() {
return socketChannelWrapper;
}
public ClientConnectionManagerImpl getConnectionManager() {
return connectionManager;
}
public ClientReadHandler getReadHandler() {
return readHandler;
}
public void setRemoteEndpoint(Address remoteEndpoint) {
this.remoteEndpoint = remoteEndpoint;
}
public Address getRemoteEndpoint() {
return remoteEndpoint;
}
public InetSocketAddress getLocalSocketAddress() {
return (InetSocketAddress) socketChannelWrapper.socket().getLocalSocketAddress();
}
void innerClose() throws IOException {
if (!live) {
return;
}
live = false;
if (socketChannelWrapper.isOpen()) {
socketChannelWrapper.close();
}
readHandler.shutdown();
writeHandler.shutdown();
if (socketChannelWrapper.isBlocking()) {
return;
}
if (connectionManager.isLive()) {
try {
executionService.executeInternal(new CleanResourcesTask());
} catch (RejectedExecutionException e) {
logger.warning("Execution rejected ", e);
}
} else {
cleanResources(new HazelcastException("Client is shutting down!!!"));
}
}
private class CleanResourcesTask implements Runnable {
@Override
public void run() {
waitForPacketsProcessed();
cleanResources(new TargetDisconnectedException(remoteEndpoint));
}
private void waitForPacketsProcessed() {
final long begin = System.currentTimeMillis();
int count = packetCount.get();
while (count != 0) {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
logger.warning(e);
break;
}
long elapsed = System.currentTimeMillis() - begin;
if (elapsed > 5000) {
logger.warning("There are packets which are not processed " + count);
break;
}
count = packetCount.get();
}
}
}
private void cleanResources(HazelcastException response) {
final Iterator<Map.Entry<Integer, ClientCallFuture>> iter = callIdMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<Integer, ClientCallFuture> entry = iter.next();
iter.remove();
entry.getValue().notify(response);
eventHandlerMap.remove(entry.getKey());
}
final Iterator<ClientCallFuture> iterator = eventHandlerMap.values().iterator();
while (iterator.hasNext()) {
final ClientCallFuture future = iterator.next();
iterator.remove();
future.notify(response);
}
}
public void close(Throwable t) {
if (!live) {
return;
}
try {
innerClose();
} catch (Exception e) {
logger.warning(e);
}
String message = "Connection [" + socketChannelWrapper.socket().getRemoteSocketAddress() + "] lost. Reason: ";
if (t != null) {
message += t.getClass().getName() + "[" + t.getMessage() + "]";
} else {
message += "Socket explicitly closed";
}
logger.warning(message);
if (!socketChannelWrapper.isBlocking()) {
connectionManager.destroyConnection(this);
}
}
//failedHeartBeat is incremented in single thread.
@edu.umd.cs.findbugs.annotations.SuppressWarnings("VO_VOLATILE_INCREMENT")
void heartBeatingFailed() {
failedHeartBeat++;
if (failedHeartBeat == connectionManager.maxFailedHeartbeatCount) {
connectionManager.connectionMarkedAsNotResponsive(this);
final Iterator<ClientCallFuture> iterator = eventHandlerMap.values().iterator();
final TargetDisconnectedException response = new TargetDisconnectedException(remoteEndpoint);
while (iterator.hasNext()) {
final ClientCallFuture future = iterator.next();
iterator.remove();
future.notify(response);
}
}
}
void heartBeatingSucceed() {
if (failedHeartBeat != 0) {
if (failedHeartBeat >= connectionManager.maxFailedHeartbeatCount) {
try {
final RemoveDistributedObjectListenerRequest request = new RemoveDistributedObjectListenerRequest();
request.setName(RemoveDistributedObjectListenerRequest.CLEAR_LISTENERS_COMMAND);
final ICompletableFuture future = invocationService.send(request, ClientConnection.this);
future.get(1500, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.warning("Clearing listeners upon recovering from heart-attack failed", e);
}
}
failedHeartBeat = 0;
}
}
public boolean isHeartBeating() {
return failedHeartBeat < connectionManager.maxFailedHeartbeatCount;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ClientConnection)) {
return false;
}
ClientConnection that = (ClientConnection) o;
if (connectionId != that.connectionId) {
return false;
}
return true;
}
@Override
public int hashCode() {
return connectionId;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ClientConnection{");
sb.append("live=").append(live);
sb.append(", writeHandler=").append(writeHandler);
sb.append(", readHandler=").append(readHandler);
sb.append(", connectionId=").append(connectionId);
sb.append(", socketChannel=").append(socketChannelWrapper);
sb.append(", remoteEndpoint=").append(remoteEndpoint);
sb.append('}');
return sb.toString();
}
} | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnection.java |
1,570 | public class TestRollbackHandler implements RollbackHandler {
private static final Log LOG = LogFactory.getLog(TestRollbackHandler.class);
@Override
@Transactional("blTransactionManager")
public void rollbackState(Activity<? extends ProcessContext> activity,
ProcessContext processContext, Map<String, Object> stateConfiguration) throws RollbackFailureException {
LOG.warn("******************* TestRollbackHandler Engaged *********************");
LOG.warn("******************* Activity: " + activity.getBeanName() + " *********************");
RollbackStateLocal rollbackStateLocal = RollbackStateLocal.getRollbackStateLocal();
LOG.warn("******************* Workflow: " + rollbackStateLocal.getWorkflowId() + " *********************");
LOG.warn("******************* Thread: " + rollbackStateLocal.getThreadId() + " *********************");
}
} | 0true
| integration_src_main_java_org_broadleafcommerce_core_workflow_state_test_TestRollbackHandler.java |
28 | static final class ThenAccept<T> extends Completion {
final CompletableFuture<? extends T> src;
final Action<? super T> fn;
final CompletableFuture<Void> dst;
final Executor executor;
ThenAccept(CompletableFuture<? extends T> src,
Action<? super T> fn,
CompletableFuture<Void> dst,
Executor executor) {
this.src = src; this.fn = fn; this.dst = dst;
this.executor = executor;
}
public final void run() {
final CompletableFuture<? extends T> a;
final Action<? super T> fn;
final CompletableFuture<Void> dst;
Object r; T t; Throwable ex;
if ((dst = this.dst) != null &&
(fn = this.fn) != null &&
(a = this.src) != null &&
(r = a.result) != null &&
compareAndSet(0, 1)) {
if (r instanceof AltResult) {
ex = ((AltResult)r).ex;
t = null;
}
else {
ex = null;
@SuppressWarnings("unchecked") T tr = (T) r;
t = tr;
}
Executor e = executor;
if (ex == null) {
try {
if (e != null)
e.execute(new AsyncAccept<T>(t, fn, dst));
else
fn.accept(t);
} catch (Throwable rex) {
ex = rex;
}
}
if (e == null || ex != null)
dst.internalComplete(null, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
} | 0true
| src_main_java_jsr166e_CompletableFuture.java |
37 | Runnable r = new Runnable() {
@Override
public void run() {
try {
Map<String, SortedMap<Long, Map<String, String>>> dataSlice = getData(databases[dataIndex],
groupFeeds[dataIndex], timeUnit, startTime, endTime);
if (dataSlice != null) {
dataSlices[dataIndex] = dataSlice;
}
} finally {
readLatch.countDown();
}
}
}; | 0true
| timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_disk_internal_PartitionFastDiskBuffer.java |
4,837 | 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);
}
}
}); | 1no label
| src_main_java_org_elasticsearch_rest_action_admin_indices_mapping_get_RestGetFieldMappingAction.java |
2,492 | public class XContentFactory {
private static int GUESS_HEADER_LENGTH = 20;
/**
* Returns a content builder using JSON format ({@link org.elasticsearch.common.xcontent.XContentType#JSON}.
*/
public static XContentBuilder jsonBuilder() throws IOException {
return contentBuilder(XContentType.JSON);
}
/**
* Constructs a new json builder that will output the result into the provided output stream.
*/
public static XContentBuilder jsonBuilder(OutputStream os) throws IOException {
return new XContentBuilder(JsonXContent.jsonXContent, os);
}
/**
* Returns a content builder using SMILE format ({@link org.elasticsearch.common.xcontent.XContentType#SMILE}.
*/
public static XContentBuilder smileBuilder() throws IOException {
return contentBuilder(XContentType.SMILE);
}
/**
* Constructs a new json builder that will output the result into the provided output stream.
*/
public static XContentBuilder smileBuilder(OutputStream os) throws IOException {
return new XContentBuilder(SmileXContent.smileXContent, os);
}
/**
* Returns a content builder using YAML format ({@link org.elasticsearch.common.xcontent.XContentType#YAML}.
*/
public static XContentBuilder yamlBuilder() throws IOException {
return contentBuilder(XContentType.SMILE);
}
/**
* Constructs a new yaml builder that will output the result into the provided output stream.
*/
public static XContentBuilder yamlBuilder(OutputStream os) throws IOException {
return new XContentBuilder(YamlXContent.yamlXContent, os);
}
/**
* Constructs a xcontent builder that will output the result into the provided output stream.
*/
public static XContentBuilder contentBuilder(XContentType type, OutputStream outputStream) throws IOException {
if (type == XContentType.JSON) {
return jsonBuilder(outputStream);
} else if (type == XContentType.SMILE) {
return smileBuilder(outputStream);
} else if (type == XContentType.YAML) {
return yamlBuilder(outputStream);
}
throw new ElasticsearchIllegalArgumentException("No matching content type for " + type);
}
/**
* Returns a binary content builder for the provided content type.
*/
public static XContentBuilder contentBuilder(XContentType type) throws IOException {
if (type == XContentType.JSON) {
return JsonXContent.contentBuilder();
} else if (type == XContentType.SMILE) {
return SmileXContent.contentBuilder();
} else if (type == XContentType.YAML) {
return YamlXContent.contentBuilder();
}
throw new ElasticsearchIllegalArgumentException("No matching content type for " + type);
}
/**
* Returns the {@link org.elasticsearch.common.xcontent.XContent} for the provided content type.
*/
public static XContent xContent(XContentType type) {
return type.xContent();
}
/**
* Guesses the content type based on the provided char sequence.
*/
public static XContentType xContentType(CharSequence content) {
int length = content.length() < GUESS_HEADER_LENGTH ? content.length() : GUESS_HEADER_LENGTH;
if (length == 0) {
return null;
}
char first = content.charAt(0);
if (first == '{') {
return XContentType.JSON;
}
// Should we throw a failure here? Smile idea is to use it in bytes....
if (length > 2 && first == SmileConstants.HEADER_BYTE_1 && content.charAt(1) == SmileConstants.HEADER_BYTE_2 && content.charAt(2) == SmileConstants.HEADER_BYTE_3) {
return XContentType.SMILE;
}
if (length > 2 && first == '-' && content.charAt(1) == '-' && content.charAt(2) == '-') {
return XContentType.YAML;
}
for (int i = 0; i < length; i++) {
char c = content.charAt(i);
if (c == '{') {
return XContentType.JSON;
}
}
return null;
}
/**
* Guesses the content (type) based on the provided char sequence.
*/
public static XContent xContent(CharSequence content) {
XContentType type = xContentType(content);
if (type == null) {
throw new ElasticsearchParseException("Failed to derive xcontent from " + content);
}
return xContent(type);
}
/**
* Guesses the content type based on the provided bytes.
*/
public static XContent xContent(byte[] data) {
return xContent(data, 0, data.length);
}
/**
* Guesses the content type based on the provided bytes.
*/
public static XContent xContent(byte[] data, int offset, int length) {
XContentType type = xContentType(data, offset, length);
if (type == null) {
throw new ElasticsearchParseException("Failed to derive xcontent from (offset=" + offset + ", length=" + length + "): " + Arrays.toString(data));
}
return xContent(type);
}
/**
* Guesses the content type based on the provided bytes.
*/
public static XContentType xContentType(byte[] data) {
return xContentType(data, 0, data.length);
}
/**
* Guesses the content type based on the provided input stream.
*/
public static XContentType xContentType(InputStream si) throws IOException {
int first = si.read();
if (first == -1) {
return null;
}
int second = si.read();
if (second == -1) {
return null;
}
if (first == SmileConstants.HEADER_BYTE_1 && second == SmileConstants.HEADER_BYTE_2) {
int third = si.read();
if (third == SmileConstants.HEADER_BYTE_3) {
return XContentType.SMILE;
}
}
if (first == '{' || second == '{') {
return XContentType.JSON;
}
if (first == '-' && second == '-') {
int third = si.read();
if (third == '-') {
return XContentType.YAML;
}
}
for (int i = 2; i < GUESS_HEADER_LENGTH; i++) {
int val = si.read();
if (val == -1) {
return null;
}
if (val == '{') {
return XContentType.JSON;
}
}
return null;
}
/**
* Guesses the content type based on the provided bytes.
*/
public static XContentType xContentType(byte[] data, int offset, int length) {
return xContentType(new BytesArray(data, offset, length));
}
public static XContent xContent(BytesReference bytes) {
XContentType type = xContentType(bytes);
if (type == null) {
throw new ElasticsearchParseException("Failed to derive xcontent from " + bytes);
}
return xContent(type);
}
/**
* Guesses the content type based on the provided bytes.
*/
public static XContentType xContentType(BytesReference bytes) {
int length = bytes.length() < GUESS_HEADER_LENGTH ? bytes.length() : GUESS_HEADER_LENGTH;
if (length == 0) {
return null;
}
byte first = bytes.get(0);
if (first == '{') {
return XContentType.JSON;
}
if (length > 2 && first == SmileConstants.HEADER_BYTE_1 && bytes.get(1) == SmileConstants.HEADER_BYTE_2 && bytes.get(2) == SmileConstants.HEADER_BYTE_3) {
return XContentType.SMILE;
}
if (length > 2 && first == '-' && bytes.get(1) == '-' && bytes.get(2) == '-') {
return XContentType.YAML;
}
for (int i = 0; i < length; i++) {
if (bytes.get(i) == '{') {
return XContentType.JSON;
}
}
return null;
}
} | 1no label
| src_main_java_org_elasticsearch_common_xcontent_XContentFactory.java |
1,803 | return new Predicate<String, String>() {
@Override
public boolean apply(Map.Entry<String, String> mapEntry) {
return true;
}
}; | 0true
| hazelcast_src_test_java_com_hazelcast_map_ListenerTest.java |
1,859 | public class Key<T> {
private final AnnotationStrategy annotationStrategy;
private final TypeLiteral<T> typeLiteral;
private final int hashCode;
/**
* Constructs a new key. Derives the type from this class's type parameter.
* <p/>
* <p>Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute it
* at runtime despite erasure.
* <p/>
* <p>Example usage for a binding of type {@code Foo} annotated with
* {@code @Bar}:
* <p/>
* <p>{@code new Key<Foo>(Bar.class) {}}.
*/
@SuppressWarnings("unchecked")
protected Key(Class<? extends Annotation> annotationType) {
this.annotationStrategy = strategyFor(annotationType);
this.typeLiteral = (TypeLiteral<T>) TypeLiteral.fromSuperclassTypeParameter(getClass());
this.hashCode = computeHashCode();
}
/**
* Constructs a new key. Derives the type from this class's type parameter.
* <p/>
* <p>Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute it
* at runtime despite erasure.
* <p/>
* <p>Example usage for a binding of type {@code Foo} annotated with
* {@code @Bar}:
* <p/>
* <p>{@code new Key<Foo>(new Bar()) {}}.
*/
@SuppressWarnings("unchecked")
protected Key(Annotation annotation) {
// no usages, not test-covered
this.annotationStrategy = strategyFor(annotation);
this.typeLiteral = (TypeLiteral<T>) TypeLiteral.fromSuperclassTypeParameter(getClass());
this.hashCode = computeHashCode();
}
/**
* Constructs a new key. Derives the type from this class's type parameter.
* <p/>
* <p>Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute it
* at runtime despite erasure.
* <p/>
* <p>Example usage for a binding of type {@code Foo}:
* <p/>
* <p>{@code new Key<Foo>() {}}.
*/
@SuppressWarnings("unchecked")
protected Key() {
this.annotationStrategy = NullAnnotationStrategy.INSTANCE;
this.typeLiteral = (TypeLiteral<T>) TypeLiteral.fromSuperclassTypeParameter(getClass());
this.hashCode = computeHashCode();
}
/**
* Unsafe. Constructs a key from a manually specified type.
*/
@SuppressWarnings("unchecked")
private Key(Type type, AnnotationStrategy annotationStrategy) {
this.annotationStrategy = annotationStrategy;
this.typeLiteral = MoreTypes.makeKeySafe((TypeLiteral<T>) TypeLiteral.get(type));
this.hashCode = computeHashCode();
}
/**
* Constructs a key from a manually specified type.
*/
private Key(TypeLiteral<T> typeLiteral, AnnotationStrategy annotationStrategy) {
this.annotationStrategy = annotationStrategy;
this.typeLiteral = MoreTypes.makeKeySafe(typeLiteral);
this.hashCode = computeHashCode();
}
private int computeHashCode() {
return typeLiteral.hashCode() * 31 + annotationStrategy.hashCode();
}
/**
* Gets the key type.
*/
public final TypeLiteral<T> getTypeLiteral() {
return typeLiteral;
}
/**
* Gets the annotation type.
*/
public final Class<? extends Annotation> getAnnotationType() {
return annotationStrategy.getAnnotationType();
}
/**
* Gets the annotation.
*/
public final Annotation getAnnotation() {
return annotationStrategy.getAnnotation();
}
boolean hasAnnotationType() {
return annotationStrategy.getAnnotationType() != null;
}
String getAnnotationName() {
Annotation annotation = annotationStrategy.getAnnotation();
if (annotation != null) {
return annotation.toString();
}
// not test-covered
return annotationStrategy.getAnnotationType().toString();
}
Class<? super T> getRawType() {
return typeLiteral.getRawType();
}
/**
* Gets the key of this key's provider.
*/
Key<Provider<T>> providerKey() {
return ofType(typeLiteral.providerType());
}
@Override
public final boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Key<?>)) {
return false;
}
Key<?> other = (Key<?>) o;
return annotationStrategy.equals(other.annotationStrategy)
&& typeLiteral.equals(other.typeLiteral);
}
@Override
public final int hashCode() {
return this.hashCode;
}
@Override
public final String toString() {
return new ToStringBuilder(Key.class)
.add("type", typeLiteral)
.add("annotation", annotationStrategy)
.toString();
}
/**
* Gets a key for an injection type and an annotation strategy.
*/
static <T> Key<T> get(Class<T> type,
AnnotationStrategy annotationStrategy) {
return new Key<T>(type, annotationStrategy);
}
/**
* Gets a key for an injection type.
*/
public static <T> Key<T> get(Class<T> type) {
return new Key<T>(type, NullAnnotationStrategy.INSTANCE);
}
/**
* Gets a key for an injection type and an annotation type.
*/
public static <T> Key<T> get(Class<T> type,
Class<? extends Annotation> annotationType) {
return new Key<T>(type, strategyFor(annotationType));
}
/**
* Gets a key for an injection type and an annotation.
*/
public static <T> Key<T> get(Class<T> type, Annotation annotation) {
return new Key<T>(type, strategyFor(annotation));
}
/**
* Gets a key for an injection type.
*/
public static Key<?> get(Type type) {
return new Key<Object>(type, NullAnnotationStrategy.INSTANCE);
}
/**
* Gets a key for an injection type and an annotation type.
*/
public static Key<?> get(Type type,
Class<? extends Annotation> annotationType) {
return new Key<Object>(type, strategyFor(annotationType));
}
/**
* Gets a key for an injection type and an annotation.
*/
public static Key<?> get(Type type, Annotation annotation) {
return new Key<Object>(type, strategyFor(annotation));
}
/**
* Gets a key for an injection type.
*/
public static <T> Key<T> get(TypeLiteral<T> typeLiteral) {
return new Key<T>(typeLiteral, NullAnnotationStrategy.INSTANCE);
}
/**
* Gets a key for an injection type and an annotation type.
*/
public static <T> Key<T> get(TypeLiteral<T> typeLiteral,
Class<? extends Annotation> annotationType) {
return new Key<T>(typeLiteral, strategyFor(annotationType));
}
/**
* Gets a key for an injection type and an annotation.
*/
public static <T> Key<T> get(TypeLiteral<T> typeLiteral,
Annotation annotation) {
return new Key<T>(typeLiteral, strategyFor(annotation));
}
/**
* Returns a new key of the specified type with the same annotation as this
* key.
*/
<T> Key<T> ofType(Class<T> type) {
return new Key<T>(type, annotationStrategy);
}
/**
* Returns a new key of the specified type with the same annotation as this
* key.
*/
Key<?> ofType(Type type) {
return new Key<Object>(type, annotationStrategy);
}
/**
* Returns a new key of the specified type with the same annotation as this
* key.
*/
<T> Key<T> ofType(TypeLiteral<T> type) {
return new Key<T>(type, annotationStrategy);
}
/**
* Returns true if this key has annotation attributes.
*/
boolean hasAttributes() {
return annotationStrategy.hasAttributes();
}
/**
* Returns this key without annotation attributes, i.e. with only the
* annotation type.
*/
Key<T> withoutAttributes() {
return new Key<T>(typeLiteral, annotationStrategy.withoutAttributes());
}
interface AnnotationStrategy {
Annotation getAnnotation();
Class<? extends Annotation> getAnnotationType();
boolean hasAttributes();
AnnotationStrategy withoutAttributes();
}
/**
* Returns {@code true} if the given annotation type has no attributes.
*/
static boolean isMarker(Class<? extends Annotation> annotationType) {
return annotationType.getDeclaredMethods().length == 0;
}
/**
* Gets the strategy for an annotation.
*/
static AnnotationStrategy strategyFor(Annotation annotation) {
checkNotNull(annotation, "annotation");
Class<? extends Annotation> annotationType = annotation.annotationType();
ensureRetainedAtRuntime(annotationType);
ensureIsBindingAnnotation(annotationType);
if (annotationType.getDeclaredMethods().length == 0) {
return new AnnotationTypeStrategy(annotationType, annotation);
}
return new AnnotationInstanceStrategy(annotation);
}
/**
* Gets the strategy for an annotation type.
*/
static AnnotationStrategy strategyFor(Class<? extends Annotation> annotationType) {
checkNotNull(annotationType, "annotation type");
ensureRetainedAtRuntime(annotationType);
ensureIsBindingAnnotation(annotationType);
return new AnnotationTypeStrategy(annotationType, null);
}
private static void ensureRetainedAtRuntime(
Class<? extends Annotation> annotationType) {
checkArgument(Annotations.isRetainedAtRuntime(annotationType),
"%s is not retained at runtime. Please annotate it with @Retention(RUNTIME).",
annotationType.getName());
}
private static void ensureIsBindingAnnotation(
Class<? extends Annotation> annotationType) {
checkArgument(isBindingAnnotation(annotationType),
"%s is not a binding annotation. Please annotate it with @BindingAnnotation.",
annotationType.getName());
}
static enum NullAnnotationStrategy implements AnnotationStrategy {
INSTANCE;
public boolean hasAttributes() {
return false;
}
public AnnotationStrategy withoutAttributes() {
throw new UnsupportedOperationException("Key already has no attributes.");
}
public Annotation getAnnotation() {
return null;
}
public Class<? extends Annotation> getAnnotationType() {
return null;
}
@Override
public String toString() {
return "[none]";
}
}
// this class not test-covered
static class AnnotationInstanceStrategy implements AnnotationStrategy {
final Annotation annotation;
AnnotationInstanceStrategy(Annotation annotation) {
this.annotation = checkNotNull(annotation, "annotation");
}
public boolean hasAttributes() {
return true;
}
public AnnotationStrategy withoutAttributes() {
return new AnnotationTypeStrategy(getAnnotationType(), annotation);
}
public Annotation getAnnotation() {
return annotation;
}
public Class<? extends Annotation> getAnnotationType() {
return annotation.annotationType();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AnnotationInstanceStrategy)) {
return false;
}
AnnotationInstanceStrategy other = (AnnotationInstanceStrategy) o;
return annotation.equals(other.annotation);
}
@Override
public int hashCode() {
return annotation.hashCode();
}
@Override
public String toString() {
return annotation.toString();
}
}
static class AnnotationTypeStrategy implements AnnotationStrategy {
final Class<? extends Annotation> annotationType;
// Keep the instance around if we have it so the client can request it.
final Annotation annotation;
AnnotationTypeStrategy(Class<? extends Annotation> annotationType,
Annotation annotation) {
this.annotationType = checkNotNull(annotationType, "annotation type");
this.annotation = annotation;
}
public boolean hasAttributes() {
return false;
}
public AnnotationStrategy withoutAttributes() {
throw new UnsupportedOperationException("Key already has no attributes.");
}
public Annotation getAnnotation() {
return annotation;
}
public Class<? extends Annotation> getAnnotationType() {
return annotationType;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AnnotationTypeStrategy)) {
return false;
}
AnnotationTypeStrategy other = (AnnotationTypeStrategy) o;
return annotationType.equals(other.annotationType);
}
@Override
public int hashCode() {
return annotationType.hashCode();
}
@Override
public String toString() {
return "@" + annotationType.getName();
}
}
static boolean isBindingAnnotation(Annotation annotation) {
return isBindingAnnotation(annotation.annotationType());
}
static boolean isBindingAnnotation(
Class<? extends Annotation> annotationType) {
return annotationType.getAnnotation(BindingAnnotation.class) != null;
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_Key.java |
2,230 | public static class FilterFunction {
public final Filter filter;
public final ScoreFunction function;
public FilterFunction(Filter filter, ScoreFunction function) {
this.filter = filter;
this.function = function;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
FilterFunction that = (FilterFunction) o;
if (filter != null ? !filter.equals(that.filter) : that.filter != null)
return false;
if (function != null ? !function.equals(that.function) : that.function != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = filter != null ? filter.hashCode() : 0;
result = 31 * result + (function != null ? function.hashCode() : 0);
return result;
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_search_function_FiltersFunctionScoreQuery.java |
1,228 | THREAD_LOCAL {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) {
return threadLocal(dequeFactory(c, limit / estimatedThreadPoolSize));
}
}, | 0true
| src_main_java_org_elasticsearch_cache_recycler_PageCacheRecycler.java |
2,543 | public class JacksonLocationTests extends ElasticsearchTestCase {
@Test
public void testLocationExtraction() throws IOException {
// {
// "index" : "test",
// "source" : {
// value : "something"
// }
// }
BytesStreamOutput os = new BytesStreamOutput();
JsonGenerator gen = new JsonFactory().createGenerator(os);
gen.writeStartObject();
gen.writeStringField("index", "test");
gen.writeFieldName("source");
gen.writeStartObject();
gen.writeStringField("value", "something");
gen.writeEndObject();
gen.writeEndObject();
gen.close();
byte[] data = os.bytes().toBytes();
JsonParser parser = new JsonFactory().createParser(data);
assertThat(parser.nextToken(), equalTo(JsonToken.START_OBJECT));
assertThat(parser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "index"
assertThat(parser.nextToken(), equalTo(JsonToken.VALUE_STRING));
assertThat(parser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "source"
// JsonLocation location1 = parser.getCurrentLocation();
// parser.skipChildren();
// JsonLocation location2 = parser.getCurrentLocation();
//
// byte[] sourceData = new byte[(int) (location2.getByteOffset() - location1.getByteOffset())];
// System.arraycopy(data, (int) location1.getByteOffset(), sourceData, 0, sourceData.length);
//
// JsonParser sourceParser = new JsonFactory().createJsonParser(new FastByteArrayInputStream(sourceData));
// assertThat(sourceParser.nextToken(), equalTo(JsonToken.START_OBJECT));
// assertThat(sourceParser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "value"
// assertThat(sourceParser.nextToken(), equalTo(JsonToken.VALUE_STRING));
// assertThat(sourceParser.nextToken(), equalTo(JsonToken.END_OBJECT));
}
} | 0true
| src_test_java_org_elasticsearch_deps_jackson_JacksonLocationTests.java |
2,987 | public class FilterCacheTests extends ElasticsearchTestCase {
@Test
public void testNoCache() throws Exception {
verifyCache(new NoneFilterCache(new Index("test"), EMPTY_SETTINGS));
}
private void verifyCache(FilterCache filterCache) throws Exception {
Directory dir = new RAMDirectory();
IndexWriter indexWriter = new IndexWriter(dir, new IndexWriterConfig(Lucene.VERSION, Lucene.STANDARD_ANALYZER));
DirectoryReader reader = DirectoryReader.open(indexWriter, true);
for (int i = 0; i < 100; i++) {
Document document = new Document();
document.add(new TextField("id", Integer.toString(i), Field.Store.YES));
indexWriter.addDocument(document);
}
reader = refreshReader(reader);
IndexSearcher searcher = new IndexSearcher(reader);
assertThat(Lucene.count(searcher, new ConstantScoreQuery(filterCache.cache(new TermFilter(new Term("id", "1"))))), equalTo(1l));
assertThat(Lucene.count(searcher, new XFilteredQuery(new MatchAllDocsQuery(), filterCache.cache(new TermFilter(new Term("id", "1"))))), equalTo(1l));
indexWriter.deleteDocuments(new Term("id", "1"));
reader = refreshReader(reader);
searcher = new IndexSearcher(reader);
TermFilter filter = new TermFilter(new Term("id", "1"));
Filter cachedFilter = filterCache.cache(filter);
long constantScoreCount = filter == cachedFilter ? 0 : 1;
// sadly, when caching based on cacheKey with NRT, this fails, that's why we have DeletionAware one
assertThat(Lucene.count(searcher, new ConstantScoreQuery(cachedFilter)), equalTo(constantScoreCount));
assertThat(Lucene.count(searcher, new XConstantScoreQuery(cachedFilter)), equalTo(0l));
assertThat(Lucene.count(searcher, new XFilteredQuery(new MatchAllDocsQuery(), cachedFilter)), equalTo(0l));
indexWriter.close();
}
private DirectoryReader refreshReader(DirectoryReader reader) throws IOException {
IndexReader oldReader = reader;
reader = DirectoryReader.openIfChanged(reader);
if (reader != oldReader) {
oldReader.close();
}
return reader;
}
} | 0true
| src_test_java_org_elasticsearch_index_cache_filter_FilterCacheTests.java |
366 | public class TransportDeleteRepositoryAction extends TransportMasterNodeOperationAction<DeleteRepositoryRequest, DeleteRepositoryResponse> {
private final RepositoriesService repositoriesService;
@Inject
public TransportDeleteRepositoryAction(Settings settings, TransportService transportService, ClusterService clusterService,
RepositoriesService repositoriesService, ThreadPool threadPool) {
super(settings, transportService, clusterService, threadPool);
this.repositoriesService = repositoriesService;
}
@Override
protected String executor() {
return ThreadPool.Names.SAME;
}
@Override
protected String transportAction() {
return DeleteRepositoryAction.NAME;
}
@Override
protected DeleteRepositoryRequest newRequest() {
return new DeleteRepositoryRequest();
}
@Override
protected DeleteRepositoryResponse newResponse() {
return new DeleteRepositoryResponse();
}
@Override
protected ClusterBlockException checkBlock(DeleteRepositoryRequest request, ClusterState state) {
return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, "");
}
@Override
protected void masterOperation(final DeleteRepositoryRequest request, ClusterState state, final ActionListener<DeleteRepositoryResponse> listener) throws ElasticsearchException {
repositoriesService.unregisterRepository(
new RepositoriesService.UnregisterRepositoryRequest("delete_repository [" + request.name() + "]", request.name())
.masterNodeTimeout(request.masterNodeTimeout()).ackTimeout(request.timeout()),
new ActionListener<RepositoriesService.UnregisterRepositoryResponse>() {
@Override
public void onResponse(RepositoriesService.UnregisterRepositoryResponse unregisterRepositoryResponse) {
listener.onResponse(new DeleteRepositoryResponse(unregisterRepositoryResponse.isAcknowledged()));
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_action_admin_cluster_repositories_delete_TransportDeleteRepositoryAction.java |
1,116 | public class OSQLFunctionMin extends OSQLFunctionMathAbstract {
public static final String NAME = "min";
private Object context;
public OSQLFunctionMin() {
super(NAME, 1, -1);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters,
OCommandContext iContext) {
// calculate min value for current record
// consider both collection of parameters and collection in each parameter
Object min = null;
for (Object item : iParameters) {
if (item instanceof Collection<?>) {
for (Object subitem : ((Collection<?>) item)) {
if (min == null || subitem != null && ((Comparable) subitem).compareTo(min) < 0)
min = subitem;
}
} else {
if (min == null || item != null && ((Comparable) item).compareTo(min) < 0)
min = item;
}
}
// what to do with the result, for current record, depends on how this function has been invoked
// for an unique result aggregated from all output records
if (aggregateResults() && min != null) {
if (context == null)
// FIRST TIME
context = (Comparable) min;
else {
if (context instanceof Number && min instanceof Number) {
final Number[] casted = OType.castComparableNumber((Number) context, (Number) min);
context = casted[0];
min = casted[1];
}
if (((Comparable<Object>) context).compareTo((Comparable) min) > 0)
// MINOR
context = (Comparable) min;
}
return null;
}
// for non aggregated results (a result per output record)
return min;
}
public boolean aggregateResults() {
// LET definitions (contain $current) does not require results aggregation
return ((configuredParameters.length == 1) && !configuredParameters[0].toString().contains("$current"));
}
public String getSyntax() {
return "Syntax error: min(<field> [,<field>*])";
}
@Override
public Object getResult() {
return context;
}
@SuppressWarnings("unchecked")
@Override
public Object mergeDistributedResult(List<Object> resultsToMerge) {
Comparable<Object> context = null;
for (Object iParameter : resultsToMerge) {
final Comparable<Object> value = (Comparable<Object>) iParameter;
if (context == null)
// FIRST TIME
context = value;
else if (context.compareTo(value) > 0)
// BIGGER
context = value;
}
return context;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_functions_math_OSQLFunctionMin.java |
1,598 | public class ServerRun {
protected String rootPath;
protected final String serverId;
protected OServer server;
public ServerRun(final String iRootPath, final String serverId) {
this.rootPath = iRootPath;
this.serverId = serverId;
}
protected ODatabaseDocumentTx createDatabase(final String iName) {
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false);
String dbPath = getDatabasePath(iName);
new File(dbPath).mkdirs();
final ODatabaseDocumentTx database = new ODatabaseDocumentTx("local:" + dbPath);
if (database.exists()) {
System.out.println("Dropping previous database '" + iName + "' under: " + dbPath + "...");
OFileUtils.deleteRecursively(new File(dbPath));
}
System.out.println("Creating database '" + iName + "' under: " + dbPath + "...");
database.create();
return database;
}
protected void copyDatabase(final String iDatabaseName, final String iDestinationDirectory) throws IOException {
// COPY THE DATABASE TO OTHER DIRECTORIES
System.out.println("Dropping any previous database '" + iDatabaseName + "' under: " + iDatabaseName + "...");
OFileUtils.deleteRecursively(new File(iDestinationDirectory));
System.out.println("Copying database folder " + iDatabaseName + " to " + iDestinationDirectory + "...");
OFileUtils.copyDirectory(new File(getDatabasePath(iDatabaseName)), new File(iDestinationDirectory));
}
public OServer getServerInstance() {
return server;
}
public String getServerId() {
return serverId;
}
protected OServer startServer(final String iConfigFile) throws Exception, InstantiationException, IllegalAccessException,
ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IOException {
System.out.println("Starting server " + serverId + " from " + getServerHome() + "...");
System.setProperty("ORIENTDB_HOME", getServerHome());
server = new OServer();
server.startup(getClass().getClassLoader().getResourceAsStream(iConfigFile));
server.activate();
return server;
}
protected void shutdownServer() {
if (server != null)
server.shutdown();
}
protected String getServerHome() {
return getServerHome(serverId);
}
protected String getDatabasePath(final String iDatabaseName) {
return getDatabasePath(serverId, iDatabaseName);
}
public String getBinaryProtocolAddress() {
return server.getListenerByProtocol(ONetworkProtocolBinary.class).getListeningAddress();
}
public static String getServerHome(final String iServerId) {
return "target/server" + iServerId;
}
public static String getDatabasePath(final String iServerId, final String iDatabaseName) {
return getServerHome(iServerId) + "/databases/" + iDatabaseName;
}
} | 1no label
| distributed_src_test_java_com_orientechnologies_orient_server_distributed_ServerRun.java |
1,075 | public interface FulfillmentOptionService {
public FulfillmentOption readFulfillmentOptionById(Long fulfillmentOptionId);
public FulfillmentOption save(FulfillmentOption option);
public List<FulfillmentOption> readAllFulfillmentOptions();
public List<FulfillmentOption> readAllFulfillmentOptionsByFulfillmentType(FulfillmentType type);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_FulfillmentOptionService.java |
1,377 | public abstract class CartEndpoint extends BaseEndpoint {
@Resource(name="blOrderService")
protected OrderService orderService;
@Resource(name="blOfferService")
protected OfferService offerService;
@Resource(name="blCustomerService")
protected CustomerService customerService;
/**
* Search for {@code Order} by {@code Customer}
*
* @return the cart for the customer
*/
public OrderWrapper findCartForCustomer(HttpServletRequest request) {
Order cart = CartState.getCart();
if (cart != null) {
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
/**
* Create a new {@code Order} for {@code Customer}
*
* @return the cart for the customer
*/
public OrderWrapper createNewCartForCustomer(HttpServletRequest request) {
Customer customer = CustomerState.getCustomer(request);
if (customer == null) {
customer = customerService.createCustomerFromId(null);
}
Order cart = orderService.findCartForCustomer(customer);
if (cart == null) {
cart = orderService.createNewCartForCustomer(customer);
CartState.setCart(cart);
}
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
}
/**
* This method takes in a categoryId and productId as path parameters. In addition, query parameters can be supplied including:
*
* <li>skuId</li>
* <li>quantity</li>
* <li>priceOrder</li>
*
* You must provide a ProductId OR ProductId with product options. Product options can be posted as form or querystring parameters.
* You must pass in the ProductOption attributeName as the key and the
* ProductOptionValue attributeValue as the value. See {@link CatalogEndpoint}.
*
* @param request
* @param uriInfo
* @param categoryId
* @param productId
* @param quantity
* @param priceOrder
* @return OrderWrapper
*/
public OrderWrapper addProductToOrder(HttpServletRequest request,
UriInfo uriInfo,
Long productId,
Long categoryId,
int quantity,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart != null) {
try {
//We allow product options to be submitted via form post or via query params. We need to take
//the product options and build a map with them...
MultivaluedMap<String, String> multiValuedMap = uriInfo.getQueryParameters();
HashMap<String, String> productOptions = new HashMap<String, String>();
//Fill up a map of key values that will represent product options
Set<String> keySet = multiValuedMap.keySet();
for (String key : keySet) {
if (multiValuedMap.getFirst(key) != null) {
//Product options should be returned with "productOption." as a prefix. We'll look for those, and
//remove the prefix.
if (key.startsWith("productOption.")) {
productOptions.put(StringUtils.removeStart(key, "productOption."), multiValuedMap.getFirst(key));
}
}
}
OrderItemRequestDTO orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setProductId(productId);
orderItemRequestDTO.setCategoryId(categoryId);
orderItemRequestDTO.setQuantity(quantity);
//If we have product options set them on the DTO
if (productOptions.size() > 0) {
orderItemRequestDTO.setItemAttributes(productOptions);
}
Order order = orderService.addItem(cart.getId(), orderItemRequestDTO, priceOrder);
order = orderService.save(order, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(order, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the order.").build());
} catch (AddToCartException e) {
if (e.getCause() != null) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("" + e.getCause()).build());
}
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured adding the item to the cart." + e.getCause()).build());
}
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
public OrderWrapper removeItemFromOrder(HttpServletRequest request,
Long itemId,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart != null) {
try {
Order order = orderService.removeItem(cart.getId(), itemId, priceOrder);
order = orderService.save(order, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(order, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
} catch (RemoveFromCartException e) {
if (e.getCause() instanceof ItemNotFoundException) {
throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Could not find order item id " + itemId).build());
} else {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured removing the item to the cart.").build());
}
}
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
public OrderWrapper updateItemQuantity(HttpServletRequest request,
Long itemId,
Integer quantity,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart != null) {
try {
OrderItemRequestDTO orderItemRequestDTO = new OrderItemRequestDTO();
orderItemRequestDTO.setOrderItemId(itemId);
orderItemRequestDTO.setQuantity(quantity);
Order order = orderService.updateItemQuantity(cart.getId(), orderItemRequestDTO, priceOrder);
order = orderService.save(order, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(order, request);
return wrapper;
} catch (UpdateCartException e) {
if (e.getCause() instanceof ItemNotFoundException) {
throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Could not find order item id " + itemId).build());
} else {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured removing the item to the cart.").build());
}
} catch (RemoveFromCartException e) {
if (e.getCause() instanceof ItemNotFoundException) {
throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Could not find order item id " + itemId).build());
} else {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured removing the item to the cart.").build());
}
} catch (PricingException pe) {
throw new WebApplicationException(pe, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
}
}
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
public OrderWrapper addOfferCode(HttpServletRequest request,
String promoCode,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
OfferCode offerCode = offerService.lookupOfferCodeByCode(promoCode);
if (offerCode == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Offer Code could not be found").build());
}
try {
cart = orderService.addOfferCode(cart, offerCode, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
} catch (OfferMaxUseExceededException e) {
throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.TEXT_PLAIN).entity("The offer (promo) code provided has exceeded its max usages: " + promoCode).build());
}
}
public OrderWrapper removeOfferCode(HttpServletRequest request,
String promoCode,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
OfferCode offerCode = offerService.lookupOfferCodeByCode(promoCode);
if (offerCode == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Offer code was invalid or could not be found.").build());
}
try {
cart = orderService.removeOfferCode(cart, offerCode, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
}
}
public OrderWrapper removeAllOfferCodes(HttpServletRequest request,
boolean priceOrder) {
Order cart = CartState.getCart();
if (cart == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build());
}
try {
cart = orderService.removeAllOfferCodes(cart, priceOrder);
OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName());
wrapper.wrapDetails(cart, request);
return wrapper;
} catch (PricingException e) {
throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.TEXT_PLAIN).entity("An error occured pricing the cart.").build());
}
}
} | 1no label
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_endpoint_order_CartEndpoint.java |
877 | threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node);
}
}); | 0true
| src_main_java_org_elasticsearch_action_search_type_TransportSearchQueryThenFetchAction.java |
413 | public class ClientExecutorServiceProxy extends ClientProxy implements IExecutorService {
private final String name;
private final Random random = new Random(-System.currentTimeMillis());
private final AtomicInteger consecutiveSubmits = new AtomicInteger();
private volatile long lastSubmitTime;
public ClientExecutorServiceProxy(String instanceName, String serviceName, String objectId) {
super(instanceName, serviceName, objectId);
name = objectId;
}
// execute on members
@Override
public void execute(Runnable command) {
submit(command);
}
@Override
public void executeOnKeyOwner(Runnable command, Object key) {
Callable<?> callable = createRunnableAdapter(command);
submitToKeyOwner(callable, key);
}
@Override
public void executeOnMember(Runnable command, Member member) {
Callable<?> callable = createRunnableAdapter(command);
submitToMember(callable, member);
}
@Override
public void executeOnMembers(Runnable command, Collection<Member> members) {
Callable<?> callable = createRunnableAdapter(command);
for (Member member : members) {
submitToMember(callable, member);
}
}
@Override
public void execute(Runnable command, MemberSelector memberSelector) {
List<Member> members = selectMembers(memberSelector);
int selectedMember = random.nextInt(members.size());
executeOnMember(command, members.get(selectedMember));
}
@Override
public void executeOnMembers(Runnable command, MemberSelector memberSelector) {
List<Member> members = selectMembers(memberSelector);
executeOnMembers(command, members);
}
@Override
public void executeOnAllMembers(Runnable command) {
Callable<?> callable = createRunnableAdapter(command);
final Collection<MemberImpl> memberList = getContext().getClusterService().getMemberList();
for (MemberImpl member : memberList) {
submitToMember(callable, member);
}
}
// submit to members
@Override
public <T> Future<T> submitToMember(Callable<T> task, Member member) {
final Address memberAddress = getMemberAddress(member);
return submitToTargetInternal(task, memberAddress, null, false);
}
@Override
public <T> Map<Member, Future<T>> submitToMembers(Callable<T> task, Collection<Member> members) {
Map<Member, Future<T>> futureMap = new HashMap<Member, Future<T>>(members.size());
for (Member member : members) {
final Address memberAddress = getMemberAddress(member);
Future<T> f = submitToTargetInternal(task, memberAddress, null, true);
futureMap.put(member, f);
}
return futureMap;
}
@Override
public <T> Future<T> submit(Callable<T> task, MemberSelector memberSelector) {
List<Member> members = selectMembers(memberSelector);
int selectedMember = random.nextInt(members.size());
return submitToMember(task, members.get(selectedMember));
}
@Override
public <T> Map<Member, Future<T>> submitToMembers(Callable<T> task, MemberSelector memberSelector) {
List<Member> members = selectMembers(memberSelector);
return submitToMembers(task, members);
}
@Override
public <T> Map<Member, Future<T>> submitToAllMembers(Callable<T> task) {
final Collection<MemberImpl> memberList = getContext().getClusterService().getMemberList();
Map<Member, Future<T>> futureMap = new HashMap<Member, Future<T>>(memberList.size());
for (MemberImpl m : memberList) {
Future<T> f = submitToTargetInternal(task, m.getAddress(), null, true);
futureMap.put(m, f);
}
return futureMap;
}
// submit to members callback
@Override
public void submitToMember(Runnable command, Member member, ExecutionCallback callback) {
Callable<?> callable = createRunnableAdapter(command);
submitToMember(callable, member, callback);
}
@Override
public void submitToMembers(Runnable command, Collection<Member> members, MultiExecutionCallback callback) {
Callable<?> callable = createRunnableAdapter(command);
MultiExecutionCallbackWrapper multiExecutionCallbackWrapper =
new MultiExecutionCallbackWrapper(members.size(), callback);
for (Member member : members) {
final ExecutionCallbackWrapper executionCallback =
new ExecutionCallbackWrapper(multiExecutionCallbackWrapper, member);
submitToMember(callable, member, executionCallback);
}
}
@Override
public <T> void submitToMember(Callable<T> task, Member member, ExecutionCallback<T> callback) {
final Address memberAddress = getMemberAddress(member);
submitToTargetInternal(task, memberAddress, callback);
}
@Override
public <T> void submitToMembers(Callable<T> task, Collection<Member> members, MultiExecutionCallback callback) {
MultiExecutionCallbackWrapper multiExecutionCallbackWrapper =
new MultiExecutionCallbackWrapper(members.size(), callback);
for (Member member : members) {
final ExecutionCallbackWrapper executionCallback =
new ExecutionCallbackWrapper(multiExecutionCallbackWrapper, member);
submitToMember(task, member, executionCallback);
}
}
@Override
public void submit(Runnable task, MemberSelector memberSelector, ExecutionCallback callback) {
List<Member> members = selectMembers(memberSelector);
int selectedMember = random.nextInt(members.size());
submitToMember(task, members.get(selectedMember), callback);
}
@Override
public void submitToMembers(Runnable task, MemberSelector memberSelector, MultiExecutionCallback callback) {
List<Member> members = selectMembers(memberSelector);
submitToMembers(task, members, callback);
}
@Override
public <T> void submit(Callable<T> task, MemberSelector memberSelector, ExecutionCallback<T> callback) {
List<Member> members = selectMembers(memberSelector);
int selectedMember = random.nextInt(members.size());
submitToMember(task, members.get(selectedMember), callback);
}
@Override
public <T> void submitToMembers(Callable<T> task, MemberSelector memberSelector, MultiExecutionCallback callback) {
List<Member> members = selectMembers(memberSelector);
submitToMembers(task, members, callback);
}
@Override
public void submitToAllMembers(Runnable command, MultiExecutionCallback callback) {
Callable<?> callable = createRunnableAdapter(command);
submitToAllMembers(callable, callback);
}
@Override
public <T> void submitToAllMembers(Callable<T> task, MultiExecutionCallback callback) {
final Collection<MemberImpl> memberList = getContext().getClusterService().getMemberList();
MultiExecutionCallbackWrapper multiExecutionCallbackWrapper =
new MultiExecutionCallbackWrapper(memberList.size(), callback);
for (Member member : memberList) {
final ExecutionCallbackWrapper executionCallback =
new ExecutionCallbackWrapper(multiExecutionCallbackWrapper, member);
submitToMember(task, member, executionCallback);
}
}
// submit random
public Future<?> submit(Runnable command) {
final Object partitionKey = getTaskPartitionKey(command);
Callable<?> callable = createRunnableAdapter(command);
if (partitionKey != null) {
return submitToKeyOwner(callable, partitionKey);
}
return submitToRandomInternal(callable, null, false);
}
public <T> Future<T> submit(Runnable command, T result) {
final Object partitionKey = getTaskPartitionKey(command);
Callable<T> callable = createRunnableAdapter(command);
if (partitionKey != null) {
return submitToKeyOwnerInternal(callable, partitionKey, result, false);
}
return submitToRandomInternal(callable, result, false);
}
public <T> Future<T> submit(Callable<T> task) {
final Object partitionKey = getTaskPartitionKey(task);
if (partitionKey != null) {
return submitToKeyOwner(task, partitionKey);
}
return submitToRandomInternal(task, null, false);
}
public void submit(Runnable command, ExecutionCallback callback) {
final Object partitionKey = getTaskPartitionKey(command);
Callable<?> callable = createRunnableAdapter(command);
if (partitionKey != null) {
submitToKeyOwnerInternal(callable, partitionKey, callback);
} else {
submitToRandomInternal(callable, callback);
}
}
public <T> void submit(Callable<T> task, ExecutionCallback<T> callback) {
final Object partitionKey = getTaskPartitionKey(task);
if (partitionKey != null) {
submitToKeyOwnerInternal(task, partitionKey, callback);
} else {
submitToRandomInternal(task, callback);
}
}
// submit to key
public <T> Future<T> submitToKeyOwner(Callable<T> task, Object key) {
return submitToKeyOwnerInternal(task, key, null, false);
}
public void submitToKeyOwner(Runnable command, Object key, ExecutionCallback callback) {
Callable<?> callable = createRunnableAdapter(command);
submitToKeyOwner(callable, key, callback);
}
public <T> void submitToKeyOwner(Callable<T> task, Object key, ExecutionCallback<T> callback) {
submitToKeyOwnerInternal(task, key, callback);
}
// end
public LocalExecutorStats getLocalExecutorStats() {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
public void shutdown() {
destroy();
}
public List<Runnable> shutdownNow() {
shutdown();
return Collections.emptyList();
}
public boolean isShutdown() {
try {
final IsShutdownRequest request = new IsShutdownRequest(name);
Boolean result = invoke(request);
return result;
} catch (DistributedObjectDestroyedException e) {
return true;
}
}
public boolean isTerminated() {
return isShutdown();
}
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return false;
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
final List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
final List<Future<T>> result = new ArrayList<Future<T>>(tasks.size());
for (Callable<T> task : tasks) {
futures.add(submitToRandomInternal(task, null, true));
}
ExecutorService asyncExecutor = getContext().getExecutionService().getAsyncExecutor();
for (Future<T> future : futures) {
Object value;
try {
value = future.get();
} catch (ExecutionException e) {
value = e;
}
result.add(new CompletedFuture<T>(getContext().getSerializationService(), value, asyncExecutor));
}
return result;
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException {
throw new UnsupportedOperationException();
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException();
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
throw new UnsupportedOperationException();
}
protected void onDestroy() {
}
private Object getTaskPartitionKey(Object task) {
if (task instanceof PartitionAware) {
return ((PartitionAware) task).getPartitionKey();
}
return null;
}
private <T> RunnableAdapter<T> createRunnableAdapter(Runnable command) {
if (command == null) {
throw new NullPointerException();
}
return new RunnableAdapter<T>(command);
}
private <T> Future<T> submitToKeyOwnerInternal(Callable<T> task, Object key, T defaultValue, boolean preventSync) {
checkIfNotNull(task);
final String uuid = getUUID();
final int partitionId = getPartitionId(key);
final PartitionCallableRequest request = new PartitionCallableRequest(name, uuid, task, partitionId);
final ICompletableFuture<T> f = invokeFuture(request, partitionId);
return checkSync(f, uuid, null, partitionId, preventSync, defaultValue);
}
private <T> void submitToKeyOwnerInternal(Callable<T> task, Object key, ExecutionCallback<T> callback) {
checkIfNotNull(task);
final String uuid = getUUID();
final int partitionId = getPartitionId(key);
final PartitionCallableRequest request = new PartitionCallableRequest(name, uuid, task, partitionId);
final ICompletableFuture<T> f = invokeFuture(request, partitionId);
f.andThen(callback);
}
private <T> Future<T> submitToRandomInternal(Callable<T> task, T defaultValue, boolean preventSync) {
checkIfNotNull(task);
final String uuid = getUUID();
final int partitionId = randomPartitionId();
final PartitionCallableRequest request = new PartitionCallableRequest(name, uuid, task, partitionId);
final ICompletableFuture<T> f = invokeFuture(request, partitionId);
return checkSync(f, uuid, null, partitionId, preventSync, defaultValue);
}
private <T> void submitToRandomInternal(Callable<T> task, ExecutionCallback<T> callback) {
checkIfNotNull(task);
checkIfNotNull(task);
final String uuid = getUUID();
final int partitionId = randomPartitionId();
final PartitionCallableRequest request = new PartitionCallableRequest(name, uuid, task, partitionId);
final ICompletableFuture<T> f = invokeFuture(request, partitionId);
f.andThen(callback);
}
private <T> Future<T> submitToTargetInternal(Callable<T> task, final Address address, T defaultValue, boolean preventSync) {
checkIfNotNull(task);
final String uuid = getUUID();
final TargetCallableRequest request = new TargetCallableRequest(name, uuid, task, address);
ICompletableFuture<T> f = invokeFuture(request);
return checkSync(f, uuid, address, -1, preventSync, defaultValue);
}
private <T> void submitToTargetInternal(Callable<T> task, final Address address, final ExecutionCallback<T> callback) {
checkIfNotNull(task);
final TargetCallableRequest request = new TargetCallableRequest(name, null, task, address);
ICompletableFuture<T> f = invokeFuture(request);
f.andThen(callback);
}
private void checkIfNotNull(Callable task) {
if (task == null) {
throw new NullPointerException();
}
}
@Override
public String toString() {
return "IExecutorService{" + "name='" + getName() + '\'' + '}';
}
private <T> Future<T> checkSync(ICompletableFuture<T> f, String uuid,
Address address, int partitionId, boolean preventSync, T defaultValue) {
boolean sync = false;
final long last = lastSubmitTime;
final long now = Clock.currentTimeMillis();
if (last + 10 < now) {
consecutiveSubmits.set(0);
} else if (consecutiveSubmits.incrementAndGet() % 100 == 0) {
sync = true;
}
lastSubmitTime = now;
if (sync && !preventSync) {
Object response;
try {
response = f.get();
} catch (Exception e) {
response = e;
}
ExecutorService asyncExecutor = getContext().getExecutionService().getAsyncExecutor();
return new CompletedFuture<T>(getContext().getSerializationService(), response, asyncExecutor);
}
if (defaultValue != null) {
return new ClientCancellableDelegatingFuture<T>(f, getContext(), uuid, address, partitionId, defaultValue);
}
return new ClientCancellableDelegatingFuture<T>(f, getContext(), uuid, address, partitionId);
}
private List<Member> selectMembers(MemberSelector memberSelector) {
if (memberSelector == null) {
throw new IllegalArgumentException("memberSelector must not be null");
}
List<Member> selected = new ArrayList<Member>();
Collection<MemberImpl> members = getContext().getClusterService().getMemberList();
for (MemberImpl member : members) {
if (memberSelector.select(member)) {
selected.add(member);
}
}
if (selected.isEmpty()) {
throw new IllegalStateException("No member selected with memberSelector[" + memberSelector + "]");
}
return selected;
}
private static final class ExecutionCallbackWrapper<T> implements ExecutionCallback<T> {
MultiExecutionCallbackWrapper multiExecutionCallbackWrapper;
Member member;
private ExecutionCallbackWrapper(MultiExecutionCallbackWrapper multiExecutionCallback, Member member) {
this.multiExecutionCallbackWrapper = multiExecutionCallback;
this.member = member;
}
public void onResponse(T response) {
multiExecutionCallbackWrapper.onResponse(member, response);
}
public void onFailure(Throwable t) {
}
}
private static final class MultiExecutionCallbackWrapper implements MultiExecutionCallback {
private final AtomicInteger members;
private final MultiExecutionCallback multiExecutionCallback;
private final Map<Member, Object> values;
private MultiExecutionCallbackWrapper(int memberSize, MultiExecutionCallback multiExecutionCallback) {
this.multiExecutionCallback = multiExecutionCallback;
this.members = new AtomicInteger(memberSize);
values = new HashMap<Member, Object>(memberSize);
}
public void onResponse(Member member, Object value) {
multiExecutionCallback.onResponse(member, value);
values.put(member, value);
int waitingResponse = members.decrementAndGet();
if (waitingResponse == 0) {
onComplete(values);
}
}
public void onComplete(Map<Member, Object> values) {
multiExecutionCallback.onComplete(values);
}
}
private ICompletableFuture invokeFuture(PartitionCallableRequest request, int partitionId) {
try {
final Address partitionOwner = getPartitionOwner(partitionId);
return getContext().getInvocationService().invokeOnTarget(request, partitionOwner);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
private ICompletableFuture invokeFuture(TargetCallableRequest request) {
try {
return getContext().getInvocationService().invokeOnTarget(request, request.getTarget());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
private String getUUID() {
return UuidUtil.buildRandomUuidString();
}
private Address getMemberAddress(Member member) {
MemberImpl m = getContext().getClusterService().getMember(member.getUuid());
if (m == null) {
throw new HazelcastException(member + " is not available!!!");
}
return m.getAddress();
}
private int getPartitionId(Object key) {
final ClientPartitionService partitionService = getContext().getPartitionService();
return partitionService.getPartitionId(key);
}
private int randomPartitionId() {
final ClientPartitionService partitionService = getContext().getPartitionService();
return random.nextInt(partitionService.getPartitionCount());
}
private Address getPartitionOwner(int partitionId) {
final ClientPartitionService partitionService = getContext().getPartitionService();
return partitionService.getPartitionOwner(partitionId);
}
} | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientExecutorServiceProxy.java |
224 | @Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface OAccess {
public enum OAccessType {
FIELD, PROPERTY
}
public OAccessType value() default OAccessType.PROPERTY;
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_annotation_OAccess.java |
389 | public interface ORecordElement {
/**
* Available record statuses.
*/
public enum STATUS {
NOT_LOADED, LOADED, MARSHALLING, UNMARSHALLING
}
/**
* Returns the current status of the record.
*
* @return Current status as value between the defined values in the enum {@link STATUS}
*/
public STATUS getInternalStatus();
/**
* Changes the current internal status.
*
* @param iStatus
* status between the values defined in the enum {@link STATUS}
*/
public void setInternalStatus(STATUS iStatus);
/**
* Marks the instance as dirty. The dirty status could be propagated up if the implementation supports ownership concept.
*
* @return The object it self. Useful to call methods in chain.
*/
public <RET> RET setDirty();
/**
* Internal only.
*/
public void onBeforeIdentityChanged(ORID iRID);
/**
* Internal only.
*/
public void onAfterIdentityChanged(ORecord<?> iRecord);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordElement.java |
717 | public class TransportCountAction extends TransportBroadcastOperationAction<CountRequest, CountResponse, ShardCountRequest, ShardCountResponse> {
private final IndicesService indicesService;
private final ScriptService scriptService;
private final CacheRecycler cacheRecycler;
private final PageCacheRecycler pageCacheRecycler;
@Inject
public TransportCountAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService,
IndicesService indicesService, ScriptService scriptService, CacheRecycler cacheRecycler, PageCacheRecycler pageCacheRecycler) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
this.scriptService = scriptService;
this.cacheRecycler = cacheRecycler;
this.pageCacheRecycler = pageCacheRecycler;
}
@Override
protected void doExecute(CountRequest request, ActionListener<CountResponse> listener) {
request.nowInMillis = System.currentTimeMillis();
super.doExecute(request, listener);
}
@Override
protected String executor() {
return ThreadPool.Names.SEARCH;
}
@Override
protected String transportAction() {
return CountAction.NAME;
}
@Override
protected CountRequest newRequest() {
return new CountRequest();
}
@Override
protected ShardCountRequest newShardRequest() {
return new ShardCountRequest();
}
@Override
protected ShardCountRequest newShardRequest(ShardRouting shard, CountRequest request) {
String[] filteringAliases = clusterService.state().metaData().filteringAliases(shard.index(), request.indices());
return new ShardCountRequest(shard.index(), shard.id(), filteringAliases, request);
}
@Override
protected ShardCountResponse newShardResponse() {
return new ShardCountResponse();
}
@Override
protected GroupShardsIterator shards(ClusterState clusterState, CountRequest request, String[] concreteIndices) {
Map<String, Set<String>> routingMap = clusterState.metaData().resolveSearchRouting(request.routing(), request.indices());
return clusterService.operationRouting().searchShards(clusterState, request.indices(), concreteIndices, routingMap, request.preference());
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, CountRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.READ);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, CountRequest countRequest, String[] concreteIndices) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.READ, concreteIndices);
}
@Override
protected CountResponse newResponse(CountRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
long count = 0;
List<ShardOperationFailedException> shardFailures = null;
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
// simply ignore non active shards
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
if (shardFailures == null) {
shardFailures = newArrayList();
}
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
count += ((ShardCountResponse) shardResponse).getCount();
successfulShards++;
}
}
return new CountResponse(count, shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
@Override
protected ShardCountResponse shardOperation(ShardCountRequest request) throws ElasticsearchException {
IndexService indexService = indicesService.indexServiceSafe(request.index());
IndexShard indexShard = indexService.shardSafe(request.shardId());
SearchShardTarget shardTarget = new SearchShardTarget(clusterService.localNode().id(), request.index(), request.shardId());
SearchContext context = new DefaultSearchContext(0,
new ShardSearchRequest().types(request.types())
.filteringAliases(request.filteringAliases())
.nowInMillis(request.nowInMillis()),
shardTarget, indexShard.acquireSearcher("count"), indexService, indexShard,
scriptService, cacheRecycler, pageCacheRecycler);
SearchContext.setCurrent(context);
try {
// TODO: min score should move to be "null" as a value that is not initialized...
if (request.minScore() != -1) {
context.minimumScore(request.minScore());
}
BytesReference source = request.querySource();
if (source != null && source.length() > 0) {
try {
QueryParseContext.setTypes(request.types());
context.parsedQuery(indexService.queryParserService().parseQuery(source));
} finally {
QueryParseContext.removeTypes();
}
}
context.preProcess();
try {
long count = Lucene.count(context.searcher(), context.query());
return new ShardCountResponse(request.index(), request.shardId(), count);
} catch (Exception e) {
throw new QueryPhaseExecutionException(context, "failed to execute count", e);
}
} finally {
// this will also release the index searcher
context.release();
SearchContext.removeCurrent();
}
}
} | 1no label
| src_main_java_org_elasticsearch_action_count_TransportCountAction.java |
1,936 | public class MapExecuteOnAllKeysRequest extends AllPartitionsClientRequest implements Portable, SecureRequest {
private String name;
private EntryProcessor processor;
public MapExecuteOnAllKeysRequest() {
}
public MapExecuteOnAllKeysRequest(String name, EntryProcessor processor) {
this.name = name;
this.processor = processor;
}
@Override
protected OperationFactory createOperationFactory() {
return new PartitionWideEntryOperationFactory(name, processor);
}
@Override
protected Object reduce(Map<Integer, Object> map) {
MapEntrySet result = new MapEntrySet();
MapService mapService = getService();
for (Object o : map.values()) {
if (o != null) {
MapEntrySet entrySet = (MapEntrySet)mapService.toObject(o);
Set<Map.Entry<Data,Data>> entries = entrySet.getEntrySet();
for (Map.Entry<Data, Data> entry : entries) {
result.add(entry);
}
}
}
return result;
}
public String getServiceName() {
return MapService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return MapPortableHook.F_ID;
}
public int getClassId() {
return MapPortableHook.EXECUTE_ON_ALL_KEYS;
}
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
final ObjectDataOutput out = writer.getRawDataOutput();
out.writeObject(processor);
}
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
final ObjectDataInput in = reader.getRawDataInput();
processor = in.readObject();
}
public Permission getRequiredPermission() {
return new MapPermission(name, ActionConstants.ACTION_PUT, ActionConstants.ACTION_REMOVE);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_client_MapExecuteOnAllKeysRequest.java |
205 | public static final Factory<byte[]> ARRAY_FACTORY = new Factory<byte[]>() {
@Override
public byte[] get(byte[] array, int offset, int limit) {
if (offset==0 && limit==array.length) return array;
else return Arrays.copyOfRange(array,offset,limit);
}
}; | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_StaticBuffer.java |
282 | public class NullMessageCreator extends MessageCreator {
private static final Log LOG = LogFactory.getLog(NullMessageCreator.class);
public NullMessageCreator(JavaMailSender mailSender) {
super(mailSender);
}
@Override
public String buildMessageBody(EmailInfo info, HashMap<String,Object> props) {
return info.getEmailTemplate();
}
@Override
public void sendMessage(final HashMap<String,Object> props) throws MailException {
LOG.warn("NullMessageCreator is defined -- specify a real message creator to send emails");
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_email_service_message_NullMessageCreator.java |
136 | @Test
public class BooleanSerializerTest {
private static final int FIELD_SIZE = 1;
private static final Boolean OBJECT_TRUE = true;
private static final Boolean OBJECT_FALSE = false;
private OBooleanSerializer booleanSerializer;
byte[] stream = new byte[FIELD_SIZE];
@BeforeClass
public void beforeClass() {
booleanSerializer = new OBooleanSerializer();
}
public void testFieldSize() {
Assert.assertEquals(booleanSerializer.getObjectSize(null), FIELD_SIZE);
}
public void testSerialize() {
booleanSerializer.serialize(OBJECT_TRUE, stream, 0);
Assert.assertEquals(booleanSerializer.deserialize(stream, 0), OBJECT_TRUE);
booleanSerializer.serialize(OBJECT_FALSE, stream, 0);
Assert.assertEquals(booleanSerializer.deserialize(stream, 0), OBJECT_FALSE);
}
public void testSerializeNative() {
booleanSerializer.serializeNative(OBJECT_TRUE, stream, 0);
Assert.assertEquals(booleanSerializer.deserializeNative(stream, 0), OBJECT_TRUE);
booleanSerializer.serializeNative(OBJECT_FALSE, stream, 0);
Assert.assertEquals(booleanSerializer.deserializeNative(stream, 0), OBJECT_FALSE);
}
public void testNativeDirectMemoryCompatibility() {
booleanSerializer.serializeNative(OBJECT_TRUE, stream, 0);
ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream);
try {
Assert.assertEquals(booleanSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT_TRUE);
} finally {
pointer.free();
}
booleanSerializer.serializeNative(OBJECT_FALSE, stream, 0);
pointer = new ODirectMemoryPointer(stream);
try {
Assert.assertEquals(booleanSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT_FALSE);
} finally {
pointer.free();
}
}
} | 0true
| commons_src_test_java_com_orientechnologies_common_serialization_types_BooleanSerializerTest.java |
3,292 | protected static class GeoPointEnum {
private final BytesRefIterator termsEnum;
private final GeoPoint next;
private final CharsRef spare;
protected GeoPointEnum(BytesRefIterator termsEnum) {
this.termsEnum = termsEnum;
next = new GeoPoint();
spare = new CharsRef();
}
public GeoPoint next() throws IOException {
final BytesRef term = termsEnum.next();
if (term == null) {
return null;
}
UnicodeUtil.UTF8toUTF16(term, spare);
int commaIndex = -1;
for (int i = 0; i < spare.length; i++) {
if (spare.chars[spare.offset + i] == ',') { // safes a string creation
commaIndex = i;
break;
}
}
if (commaIndex == -1) {
assert false;
return next.reset(0, 0);
}
final double lat = Double.parseDouble(new String(spare.chars, spare.offset, (commaIndex - spare.offset)));
final double lon = Double.parseDouble(new String(spare.chars, (spare.offset + (commaIndex + 1)), spare.length - ((commaIndex + 1) - spare.offset)));
return next.reset(lat, lon);
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_AbstractGeoPointIndexFieldData.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.