Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
916 |
public class LockProxy extends AbstractDistributedObject<LockServiceImpl> implements ILock {
private final String name;
private final LockProxySupport lockSupport;
private final Data key;
private final int partitionId;
public LockProxy(NodeEngine nodeEngine, LockServiceImpl lockService, String name) {
super(nodeEngine, lockService);
this.name = name;
this.key = getNameAsPartitionAwareData();
this.lockSupport = new LockProxySupport(new InternalLockNamespace(name));
this.partitionId = getNodeEngine().getPartitionService().getPartitionId(key);
}
@Override
public boolean isLocked() {
return lockSupport.isLocked(getNodeEngine(), key);
}
@Override
public boolean isLockedByCurrentThread() {
return lockSupport.isLockedByCurrentThread(getNodeEngine(), key);
}
@Override
public int getLockCount() {
return lockSupport.getLockCount(getNodeEngine(), key);
}
@Override
public long getRemainingLeaseTime() {
return lockSupport.getRemainingLeaseTime(getNodeEngine(), key);
}
@Override
public void lock() {
lockSupport.lock(getNodeEngine(), key);
}
@Override
public void lock(long leaseTime, TimeUnit timeUnit) {
shouldBePositive(leaseTime, "leaseTime");
lockSupport.lock(getNodeEngine(), key, timeUnit.toMillis(leaseTime));
}
@Override
public void lockInterruptibly() throws InterruptedException {
lock();
}
@Override
public boolean tryLock() {
return lockSupport.tryLock(getNodeEngine(), key);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
if (unit == null) {
throw new NullPointerException("unit can't be null");
}
return lockSupport.tryLock(getNodeEngine(), key, time, unit);
}
@Override
public void unlock() {
lockSupport.unlock(getNodeEngine(), key);
}
@Override
public void forceUnlock() {
lockSupport.forceUnlock(getNodeEngine(), key);
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException("Use ICondition.newCondition(String name) instead!");
}
@Override
public ICondition newCondition(String name) {
if (name == null) {
throw new NullPointerException("Condition name can't be null");
}
return new ConditionImpl(this, name);
}
@Override
public String getName() {
return name;
}
@Override
public String getServiceName() {
return LockService.SERVICE_NAME;
}
@Deprecated
public Object getKey() {
return getName();
}
public Data getKeyData() {
return key;
}
public int getPartitionId() {
return partitionId;
}
ObjectNamespace getNamespace() {
return lockSupport.getNamespace();
}
// will be removed when HazelcastInstance.getLock(Object key) is removed from API
public static String convertToStringKey(Object key, SerializationService serializationService) {
if (key instanceof String) {
return String.valueOf(key);
} else {
Data data = serializationService.toData(key, PARTITIONING_STRATEGY);
// name = Integer.toString(data.hashCode());
byte[] buffer = data.getBuffer();
return Arrays.toString(buffer);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ILock{");
sb.append("name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockProxy.java
|
1,147 |
public class OSQLMethodKeys extends OAbstractSQLMethod {
public static final String NAME = "keys";
public OSQLMethodKeys() {
super(NAME);
}
@Override
public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) {
ioResult = ioResult != null && ioResult instanceof Map<?, ?> ? ((Map<?, ?>) ioResult).keySet() : null;
return ioResult;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodKeys.java
|
1,288 |
@ClusterScope(scope = Scope.TEST, numNodes = 0)
public class ClusterServiceTests extends ElasticsearchIntegrationTest {
@Test
public void testTimeoutUpdateTask() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService1 = cluster().getInstance(ClusterService.class);
final CountDownLatch block = new CountDownLatch(1);
clusterService1.submitStateUpdateTask("test1", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
try {
block.await();
} catch (InterruptedException e) {
fail();
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
fail();
}
});
final CountDownLatch timedOut = new CountDownLatch(1);
final AtomicBoolean executeCalled = new AtomicBoolean();
clusterService1.submitStateUpdateTask("test2", new TimeoutClusterStateUpdateTask() {
@Override
public TimeValue timeout() {
return TimeValue.timeValueMillis(2);
}
@Override
public void onFailure(String source, Throwable t) {
timedOut.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) {
executeCalled.set(true);
return currentState;
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
});
assertThat(timedOut.await(500, TimeUnit.MILLISECONDS), equalTo(true));
block.countDown();
Thread.sleep(100); // sleep a bit to double check that execute on the timed out update task is not called...
assertThat(executeCalled.get(), equalTo(false));
}
@Test
public void testAckedUpdateTask() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch processedLatch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
processedLatch.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(true));
assertThat(ackTimeout.get(), equalTo(false));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
assertThat(processedLatch.await(1, TimeUnit.SECONDS), equalTo(true));
}
@Test
public void testAckedUpdateTaskSameClusterState() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch processedLatch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
processedLatch.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(true));
assertThat(ackTimeout.get(), equalTo(false));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
assertThat(processedLatch.await(1, TimeUnit.SECONDS), equalTo(true));
}
@Test
public void testAckedUpdateTaskNoAckExpected() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return false;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(true));
assertThat(ackTimeout.get(), equalTo(false));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
}
@Test
public void testAckedUpdateTaskTimeoutZero() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "local")
.build();
cluster().startNode(settings);
ClusterService clusterService = cluster().getInstance(ClusterService.class);
final AtomicBoolean allNodesAcked = new AtomicBoolean(false);
final AtomicBoolean ackTimeout = new AtomicBoolean(false);
final AtomicBoolean onFailure = new AtomicBoolean(false);
final AtomicBoolean executed = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch processedLatch = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test", new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return false;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
allNodesAcked.set(true);
latch.countDown();
}
@Override
public void onAckTimeout() {
ackTimeout.set(true);
latch.countDown();
}
@Override
public TimeValue ackTimeout() {
return TimeValue.timeValueSeconds(0);
}
@Override
public TimeValue timeout() {
return TimeValue.timeValueSeconds(10);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
processedLatch.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
executed.set(true);
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("failed to execute callback in test {}", t, source);
onFailure.set(true);
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
assertThat(allNodesAcked.get(), equalTo(false));
assertThat(ackTimeout.get(), equalTo(true));
assertThat(executed.get(), equalTo(true));
assertThat(onFailure.get(), equalTo(false));
assertThat(processedLatch.await(1, TimeUnit.SECONDS), equalTo(true));
}
@Test
public void testPendingUpdateTask() throws Exception {
Settings zenSettings = settingsBuilder()
.put("discovery.type", "zen").build();
String node_0 = cluster().startNode(zenSettings);
cluster().startNodeClient(zenSettings);
ClusterService clusterService = cluster().getInstance(ClusterService.class, node_0);
final CountDownLatch block1 = new CountDownLatch(1);
final CountDownLatch invoked1 = new CountDownLatch(1);
clusterService.submitStateUpdateTask("1", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
invoked1.countDown();
try {
block1.await();
} catch (InterruptedException e) {
fail();
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
invoked1.countDown();
fail();
}
});
invoked1.await();
final CountDownLatch invoked2 = new CountDownLatch(9);
for (int i = 2; i <= 10; i++) {
clusterService.submitStateUpdateTask(Integer.toString(i), new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
invoked2.countDown();
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
fail();
}
});
}
// The tasks can be re-ordered, so we need to check out-of-order
Set<String> controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10"));
List<PendingClusterTask> pendingClusterTasks = clusterService.pendingTasks();
assertThat(pendingClusterTasks.size(), equalTo(9));
for (PendingClusterTask task : pendingClusterTasks) {
assertTrue(controlSources.remove(task.source().string()));
}
assertTrue(controlSources.isEmpty());
controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10"));
PendingClusterTasksResponse response = cluster().clientNodeClient().admin().cluster().preparePendingClusterTasks().execute().actionGet();
assertThat(response.pendingTasks().size(), equalTo(9));
for (PendingClusterTask task : response) {
assertTrue(controlSources.remove(task.source().string()));
}
assertTrue(controlSources.isEmpty());
block1.countDown();
invoked2.await();
pendingClusterTasks = clusterService.pendingTasks();
assertThat(pendingClusterTasks, empty());
response = cluster().clientNodeClient().admin().cluster().preparePendingClusterTasks().execute().actionGet();
assertThat(response.pendingTasks(), empty());
final CountDownLatch block2 = new CountDownLatch(1);
final CountDownLatch invoked3 = new CountDownLatch(1);
clusterService.submitStateUpdateTask("1", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
invoked3.countDown();
try {
block2.await();
} catch (InterruptedException e) {
fail();
}
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
invoked3.countDown();
fail();
}
});
invoked3.await();
for (int i = 2; i <= 5; i++) {
clusterService.submitStateUpdateTask(Integer.toString(i), new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return currentState;
}
@Override
public void onFailure(String source, Throwable t) {
fail();
}
});
}
Thread.sleep(100);
pendingClusterTasks = clusterService.pendingTasks();
assertThat(pendingClusterTasks.size(), equalTo(4));
controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5"));
for (PendingClusterTask task : pendingClusterTasks) {
assertTrue(controlSources.remove(task.source().string()));
}
assertTrue(controlSources.isEmpty());
response = cluster().clientNodeClient().admin().cluster().preparePendingClusterTasks().execute().actionGet();
assertThat(response.pendingTasks().size(), equalTo(4));
controlSources = new HashSet<String>(Arrays.asList("2", "3", "4", "5"));
for (PendingClusterTask task : response) {
assertTrue(controlSources.remove(task.source().string()));
assertThat(task.getTimeInQueueInMillis(), greaterThan(0l));
}
assertTrue(controlSources.isEmpty());
block2.countDown();
}
@Test
public void testListenerCallbacks() throws Exception {
Settings settings = settingsBuilder()
.put("discovery.type", "zen")
.put("discovery.zen.minimum_master_nodes", 1)
.put("discovery.zen.ping_timeout", "200ms")
.put("discovery.initial_state_timeout", "500ms")
.put("plugin.types", TestPlugin.class.getName())
.build();
cluster().startNode(settings);
ClusterService clusterService1 = cluster().getInstance(ClusterService.class);
MasterAwareService testService1 = cluster().getInstance(MasterAwareService.class);
// the first node should be a master as the minimum required is 1
assertThat(clusterService1.state().nodes().masterNode(), notNullValue());
assertThat(clusterService1.state().nodes().localNodeMaster(), is(true));
assertThat(testService1.master(), is(true));
String node_1 = cluster().startNode(settings);
ClusterService clusterService2 = cluster().getInstance(ClusterService.class, node_1);
MasterAwareService testService2 = cluster().getInstance(MasterAwareService.class, node_1);
ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes("2").execute().actionGet();
assertThat(clusterHealth.isTimedOut(), equalTo(false));
// the second node should not be the master as node1 is already the master.
assertThat(clusterService2.state().nodes().localNodeMaster(), is(false));
assertThat(testService2.master(), is(false));
cluster().stopCurrentMasterNode();
clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes("1").execute().actionGet();
assertThat(clusterHealth.isTimedOut(), equalTo(false));
// now that node1 is closed, node2 should be elected as master
assertThat(clusterService2.state().nodes().localNodeMaster(), is(true));
assertThat(testService2.master(), is(true));
Settings newSettings = settingsBuilder()
.put("discovery.zen.minimum_master_nodes", 2)
.put("discovery.type", "zen")
.build();
client().admin().cluster().prepareUpdateSettings().setTransientSettings(newSettings).execute().actionGet();
Thread.sleep(200);
// there should not be any master as the minimum number of required eligible masters is not met
assertThat(clusterService2.state().nodes().masterNode(), is(nullValue()));
assertThat(testService2.master(), is(false));
String node_2 = cluster().startNode(settings);
clusterService1 = cluster().getInstance(ClusterService.class, node_2);
testService1 = cluster().getInstance(MasterAwareService.class, node_2);
// make sure both nodes see each other otherwise the masternode below could be null if node 2 is master and node 1 did'r receive the updated cluster state...
assertThat(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setLocal(true).setWaitForNodes("2").execute().actionGet().isTimedOut(), is(false));
assertThat(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setLocal(true).setWaitForNodes("2").execute().actionGet().isTimedOut(), is(false));
// now that we started node1 again, a new master should be elected
assertThat(clusterService1.state().nodes().masterNode(), is(notNullValue()));
if (node_2.equals(clusterService1.state().nodes().masterNode().name())) {
assertThat(testService1.master(), is(true));
assertThat(testService2.master(), is(false));
} else {
assertThat(testService1.master(), is(false));
assertThat(testService2.master(), is(true));
}
}
public static class TestPlugin extends AbstractPlugin {
@Override
public String name() {
return "test plugin";
}
@Override
public String description() {
return "test plugin";
}
@Override
public Collection<Class<? extends LifecycleComponent>> services() {
List<Class<? extends LifecycleComponent>> services = new ArrayList<Class<? extends LifecycleComponent>>(1);
services.add(MasterAwareService.class);
return services;
}
}
@Singleton
public static class MasterAwareService extends AbstractLifecycleComponent<MasterAwareService> implements LocalNodeMasterListener {
private final ClusterService clusterService;
private volatile boolean master;
@Inject
public MasterAwareService(Settings settings, ClusterService clusterService) {
super(settings);
clusterService.add(this);
this.clusterService = clusterService;
logger.info("initialized test service");
}
@Override
public void onMaster() {
logger.info("on master [" + clusterService.localNode() + "]");
master = true;
}
@Override
public void offMaster() {
logger.info("off master [" + clusterService.localNode() + "]");
master = false;
}
public boolean master() {
return master;
}
@Override
protected void doStart() throws ElasticsearchException {
}
@Override
protected void doStop() throws ElasticsearchException {
}
@Override
protected void doClose() throws ElasticsearchException {
}
@Override
public String executorName() {
return ThreadPool.Names.SAME;
}
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_ClusterServiceTests.java
|
77 |
public interface AttributeSerializer<V> extends AttributeHandler<V> {
/**
* Reads an attribute from the given ReadBuffer.
* <p/>
* It is expected that this read operation adjusts the position in the ReadBuffer to after the attribute value.
*
* @param buffer ReadBuffer to read attribute from
* @return Read attribute
*/
public V read(ScanBuffer buffer);
/**
* Writes the attribute value to the given WriteBuffer.
* <p/>
* It is expected that this write operation adjusts the position in the WriteBuffer to after the attribute value.
*
* @param buffer WriteBuffer to write attribute to
* @param attribute Attribute to write to WriteBuffer
*/
public void write(WriteBuffer buffer, V attribute);
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_AttributeSerializer.java
|
109 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientMemberAttributeTest extends HazelcastTestSupport {
@After
public void cleanup() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test(timeout = 40000)
public void testChangeMemberAttributes() throws Exception {
final int count = 100;
final HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final ClientConfig config = new ClientConfig();
final ListenerConfig listenerConfig = new ListenerConfig();
final CountDownLatch countDownLatch = new CountDownLatch(count);
listenerConfig.setImplementation(new LatchMembershipListener(countDownLatch));
config.addListenerConfig(listenerConfig);
HazelcastClient.newHazelcastClient(config);
final Member localMember = instance.getCluster().getLocalMember();
for (int i = 0; i < count; i++) {
localMember.setStringAttribute("key" + i, HazelcastTestSupport.randomString());
}
assertOpenEventually(countDownLatch);
}
@Test(timeout = 120000)
public void testConfigAttributes() throws Exception {
Config c = new Config();
c.getNetworkConfig().getJoin().getTcpIpConfig().addMember("127.0.0.1").setEnabled(true);
MemberAttributeConfig memberAttributeConfig = c.getMemberAttributeConfig();
memberAttributeConfig.setIntAttribute("Test", 123);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(c);
Member m1 = h1.getCluster().getLocalMember();
assertEquals(123, (int) m1.getIntAttribute("Test"));
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(c);
Member m2 = h2.getCluster().getLocalMember();
assertEquals(123, (int) m2.getIntAttribute("Test"));
assertEquals(2, h2.getCluster().getMembers().size());
Member member = null;
for (Member m : h2.getCluster().getMembers()) {
if (m == h2.getCluster().getLocalMember())
continue;
member = m;
}
assertNotNull(member);
assertEquals(m1, member);
assertNotNull(member.getIntAttribute("Test"));
assertEquals(123, (int) member.getIntAttribute("Test"));
HazelcastInstance client = HazelcastClient.newHazelcastClient();
Collection<Member> members = client.getCluster().getMembers();
for (Member m : members) {
assertEquals(123, (int) m.getIntAttribute("Test"));
}
client.shutdown();
h1.shutdown();
h2.shutdown();
}
@Test(timeout = 120000)
public void testPresharedAttributes() throws Exception {
Config c = new Config();
c.getNetworkConfig().getJoin().getTcpIpConfig().addMember("127.0.0.1").setEnabled(true);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(c);
Member m1 = h1.getCluster().getLocalMember();
m1.setIntAttribute("Test", 123);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(c);
assertEquals(2, h2.getCluster().getMembers().size());
Member member = null;
for (Member m : h2.getCluster().getMembers()) {
if (m == h2.getCluster().getLocalMember())
continue;
member = m;
}
assertNotNull(member);
assertEquals(m1, member);
assertNotNull(member.getIntAttribute("Test"));
assertEquals(123, (int) member.getIntAttribute("Test"));
boolean found = false;
HazelcastInstance client = HazelcastClient.newHazelcastClient();
Collection<Member> members = client.getCluster().getMembers();
for (Member m : members) {
if (m.equals(m1)) {
assertEquals(123, (int) m.getIntAttribute("Test"));
found = true;
}
}
assertTrue(found);
client.shutdown();
h1.shutdown();
h2.shutdown();
}
@Test(timeout = 120000)
public void testAddAttributes() throws Exception {
Config c = new Config();
c.getNetworkConfig().getJoin().getTcpIpConfig().addMember("127.0.0.1").setEnabled(true);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(c);
Member m1 = h1.getCluster().getLocalMember();
m1.setIntAttribute("Test", 123);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(c);
assertEquals(2, h2.getCluster().getMembers().size());
Member member = null;
for (Member m : h2.getCluster().getMembers()) {
if (m == h2.getCluster().getLocalMember())
continue;
member = m;
}
assertNotNull(member);
assertEquals(m1, member);
assertNotNull(member.getIntAttribute("Test"));
assertEquals(123, (int) member.getIntAttribute("Test"));
HazelcastInstance client = HazelcastClient.newHazelcastClient();
final CountDownLatch latch = new CountDownLatch(3);
final MembershipListener listener = new LatchMembershipListener(latch);
h2.getCluster().addMembershipListener(listener);
h1.getCluster().addMembershipListener(listener);
client.getCluster().addMembershipListener(listener);
m1.setIntAttribute("Test2", 321);
// Force sleep to distribute value
assertOpenEventually(latch);
assertNotNull(member.getIntAttribute("Test2"));
assertEquals(321, (int) member.getIntAttribute("Test2"));
boolean found = false;
Collection<Member> members = client.getCluster().getMembers();
for (Member m : members) {
if (m.equals(m1)) {
assertEquals(321, (int) m.getIntAttribute("Test2"));
found = true;
}
}
assertTrue(found);
client.shutdown();
h1.shutdown();
h2.shutdown();
}
@Test(timeout = 120000)
public void testChangeAttributes() throws Exception {
Config c = new Config();
c.getNetworkConfig().getJoin().getTcpIpConfig().addMember("127.0.0.1").setEnabled(true);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(c);
Member m1 = h1.getCluster().getLocalMember();
m1.setIntAttribute("Test", 123);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(c);
assertEquals(2, h2.getCluster().getMembers().size());
Member member = null;
for (Member m : h2.getCluster().getMembers()) {
if (m == h2.getCluster().getLocalMember())
continue;
member = m;
}
assertNotNull(member);
assertEquals(m1, member);
assertNotNull(member.getIntAttribute("Test"));
assertEquals(123, (int) member.getIntAttribute("Test"));
HazelcastInstance client = HazelcastClient.newHazelcastClient();
final CountDownLatch latch = new CountDownLatch(3);
final MembershipListener listener = new LatchMembershipListener(latch);
h2.getCluster().addMembershipListener(listener);
h1.getCluster().addMembershipListener(listener);
client.getCluster().addMembershipListener(listener);
m1.setIntAttribute("Test", 321);
// Force sleep to distribute value
assertOpenEventually(latch);
assertNotNull(member.getIntAttribute("Test"));
assertEquals(321, (int) member.getIntAttribute("Test"));
boolean found = false;
Collection<Member> members = client.getCluster().getMembers();
for (Member m : members) {
if (m.equals(m1)) {
assertEquals(321, (int) m.getIntAttribute("Test"));
found = true;
}
}
assertTrue(found);
client.getLifecycleService().shutdown();
h1.shutdown();
h2.shutdown();
}
@Test(timeout = 120000)
public void testRemoveAttributes() throws Exception {
Config c = new Config();
c.getNetworkConfig().getJoin().getTcpIpConfig().addMember("127.0.0.1").setEnabled(true);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(c);
Member m1 = h1.getCluster().getLocalMember();
m1.setIntAttribute("Test", 123);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(c);
assertEquals(2, h2.getCluster().getMembers().size());
Member member = null;
for (Member m : h2.getCluster().getMembers()) {
if (m == h2.getCluster().getLocalMember())
continue;
member = m;
}
assertNotNull(member);
assertEquals(m1, member);
assertNotNull(member.getIntAttribute("Test"));
assertEquals(123, (int) member.getIntAttribute("Test"));
HazelcastInstance client = HazelcastClient.newHazelcastClient();
final CountDownLatch latch = new CountDownLatch(3);
final MembershipListener listener = new LatchMembershipListener(latch);
h2.getCluster().addMembershipListener(listener);
h1.getCluster().addMembershipListener(listener);
client.getCluster().addMembershipListener(listener);
m1.removeAttribute("Test");
// Force sleep to distribute value
assertOpenEventually(latch);
assertNull(member.getIntAttribute("Test"));
boolean found = false;
Collection<Member> members = client.getCluster().getMembers();
for (Member m : members) {
if (m.equals(m1)) {
assertNull(m.getIntAttribute("Test"));
found = true;
}
}
assertTrue(found);
client.shutdown();
h1.shutdown();
h2.shutdown();
}
private static class LatchMembershipListener implements MembershipListener {
private final CountDownLatch latch;
private LatchMembershipListener(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void memberAdded(MembershipEvent membershipEvent) {
}
@Override
public void memberRemoved(MembershipEvent membershipEvent) {
}
@Override
public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
latch.countDown();
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientMemberAttributeTest.java
|
5,291 |
public class DoubleTerms extends InternalTerms {
public static final Type TYPE = new Type("terms", "dterms");
public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public DoubleTerms readResult(StreamInput in) throws IOException {
DoubleTerms buckets = new DoubleTerms();
buckets.readFrom(in);
return buckets;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
static class Bucket extends InternalTerms.Bucket {
double term;
public Bucket(double term, long docCount, InternalAggregations aggregations) {
super(docCount, aggregations);
this.term = term;
}
@Override
public String getKey() {
return String.valueOf(term);
}
@Override
public Text getKeyAsText() {
return new StringText(String.valueOf(term));
}
@Override
public Number getKeyAsNumber() {
return term;
}
@Override
int compareTerm(Terms.Bucket other) {
return Double.compare(term, other.getKeyAsNumber().doubleValue());
}
}
private ValueFormatter valueFormatter;
DoubleTerms() {} // for serialization
public DoubleTerms(String name, InternalOrder order, int requiredSize, long minDocCount, Collection<InternalTerms.Bucket> buckets) {
this(name, order, null, requiredSize, minDocCount, buckets);
}
public DoubleTerms(String name, InternalOrder order, ValueFormatter valueFormatter, int requiredSize, long minDocCount, Collection<InternalTerms.Bucket> buckets) {
super(name, order, requiredSize, minDocCount, buckets);
this.valueFormatter = valueFormatter;
}
@Override
public Type type() {
return TYPE;
}
@Override
public InternalTerms reduce(ReduceContext reduceContext) {
List<InternalAggregation> aggregations = reduceContext.aggregations();
if (aggregations.size() == 1) {
InternalTerms terms = (InternalTerms) aggregations.get(0);
terms.trimExcessEntries(reduceContext.cacheRecycler());
return terms;
}
InternalTerms reduced = null;
Recycler.V<DoubleObjectOpenHashMap<List<Bucket>>> buckets = null;
for (InternalAggregation aggregation : aggregations) {
InternalTerms terms = (InternalTerms) aggregation;
if (terms instanceof UnmappedTerms) {
continue;
}
if (reduced == null) {
reduced = terms;
}
if (buckets == null) {
buckets = reduceContext.cacheRecycler().doubleObjectMap(terms.buckets.size());
}
for (Terms.Bucket bucket : terms.buckets) {
List<Bucket> existingBuckets = buckets.v().get(((Bucket) bucket).term);
if (existingBuckets == null) {
existingBuckets = new ArrayList<Bucket>(aggregations.size());
buckets.v().put(((Bucket) bucket).term, existingBuckets);
}
existingBuckets.add((Bucket) bucket);
}
}
if (reduced == null) {
// there are only unmapped terms, so we just return the first one (no need to reduce)
return (UnmappedTerms) aggregations.get(0);
}
// TODO: would it be better to sort the backing array buffer of hppc map directly instead of using a PQ?
final int size = Math.min(requiredSize, buckets.v().size());
BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null));
boolean[] states = buckets.v().allocated;
Object[] internalBuckets = buckets.v().values;
for (int i = 0; i < states.length; i++) {
if (states[i]) {
List<DoubleTerms.Bucket> sameTermBuckets = (List<DoubleTerms.Bucket>) internalBuckets[i];
final InternalTerms.Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext.cacheRecycler());
if (b.getDocCount() >= minDocCount) {
ordered.insertWithOverflow(b);
}
}
}
buckets.release();
InternalTerms.Bucket[] list = new InternalTerms.Bucket[ordered.size()];
for (int i = ordered.size() - 1; i >= 0; i--) {
list[i] = (Bucket) ordered.pop();
}
reduced.buckets = Arrays.asList(list);
return reduced;
}
@Override
public void readFrom(StreamInput in) throws IOException {
this.name = in.readString();
this.order = InternalOrder.Streams.readOrder(in);
this.valueFormatter = ValueFormatterStreams.readOptional(in);
this.requiredSize = readSize(in);
this.minDocCount = in.readVLong();
int size = in.readVInt();
List<InternalTerms.Bucket> buckets = new ArrayList<InternalTerms.Bucket>(size);
for (int i = 0; i < size; i++) {
buckets.add(new Bucket(in.readDouble(), in.readVLong(), InternalAggregations.readAggregations(in)));
}
this.buckets = buckets;
this.bucketMap = null;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
InternalOrder.Streams.writeOrder(order, out);
ValueFormatterStreams.writeOptional(valueFormatter, out);
writeSize(requiredSize, out);
out.writeVLong(minDocCount);
out.writeVInt(buckets.size());
for (InternalTerms.Bucket bucket : buckets) {
out.writeDouble(((Bucket) bucket).term);
out.writeVLong(bucket.getDocCount());
((InternalAggregations) bucket.getAggregations()).writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.startArray(CommonFields.BUCKETS);
for (InternalTerms.Bucket bucket : buckets) {
builder.startObject();
builder.field(CommonFields.KEY, ((Bucket) bucket).term);
if (valueFormatter != null) {
builder.field(CommonFields.KEY_AS_STRING, valueFormatter.format(((Bucket) bucket).term));
}
builder.field(CommonFields.DOC_COUNT, bucket.getDocCount());
((InternalAggregations) bucket.getAggregations()).toXContentInternal(builder, params);
builder.endObject();
}
builder.endArray();
builder.endObject();
return builder;
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_terms_DoubleTerms.java
|
3,236 |
public class ShardFieldData extends AbstractIndexShardComponent implements IndexFieldDataCache.Listener {
final CounterMetric evictionsMetric = new CounterMetric();
final CounterMetric totalMetric = new CounterMetric();
final ConcurrentMap<String, CounterMetric> perFieldTotals = ConcurrentCollections.newConcurrentMap();
private final CircuitBreakerService breakerService;
@Inject
public ShardFieldData(ShardId shardId, @IndexSettings Settings indexSettings, CircuitBreakerService breakerService) {
super(shardId, indexSettings);
this.breakerService = breakerService;
}
public FieldDataStats stats(String... fields) {
ObjectLongOpenHashMap<String> fieldTotals = null;
if (fields != null && fields.length > 0) {
fieldTotals = new ObjectLongOpenHashMap<String>();
for (Map.Entry<String, CounterMetric> entry : perFieldTotals.entrySet()) {
for (String field : fields) {
if (Regex.simpleMatch(field, entry.getKey())) {
fieldTotals.put(entry.getKey(), entry.getValue().count());
}
}
}
}
return new FieldDataStats(totalMetric.count(), evictionsMetric.count(), fieldTotals);
}
@Override
public void onLoad(FieldMapper.Names fieldNames, FieldDataType fieldDataType, AtomicFieldData fieldData) {
long sizeInBytes = fieldData.getMemorySizeInBytes();
totalMetric.inc(sizeInBytes);
String keyFieldName = fieldNames.indexName();
CounterMetric total = perFieldTotals.get(keyFieldName);
if (total != null) {
total.inc(sizeInBytes);
} else {
total = new CounterMetric();
total.inc(sizeInBytes);
CounterMetric prev = perFieldTotals.putIfAbsent(keyFieldName, total);
if (prev != null) {
prev.inc(sizeInBytes);
}
}
}
@Override
public void onUnload(FieldMapper.Names fieldNames, FieldDataType fieldDataType, boolean wasEvicted, long sizeInBytes, @Nullable AtomicFieldData fieldData) {
if (wasEvicted) {
evictionsMetric.inc();
}
if (sizeInBytes != -1) {
// Since field data is being unloaded (due to expiration or manual
// clearing), we also need to decrement the used bytes in the breaker
breakerService.getBreaker().addWithoutBreaking(-sizeInBytes);
totalMetric.dec(sizeInBytes);
String keyFieldName = fieldNames.indexName();
CounterMetric total = perFieldTotals.get(keyFieldName);
if (total != null) {
total.dec(sizeInBytes);
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_fielddata_ShardFieldData.java
|
688 |
public class BulkItemRequest implements Streamable {
private int id;
private ActionRequest request;
BulkItemRequest() {
}
public BulkItemRequest(int id, ActionRequest request) {
this.id = id;
this.request = request;
}
public int id() {
return id;
}
public ActionRequest request() {
return request;
}
public static BulkItemRequest readBulkItem(StreamInput in) throws IOException {
BulkItemRequest item = new BulkItemRequest();
item.readFrom(in);
return item;
}
@Override
public void readFrom(StreamInput in) throws IOException {
id = in.readVInt();
byte type = in.readByte();
if (type == 0) {
request = new IndexRequest();
} else if (type == 1) {
request = new DeleteRequest();
} else if (type == 2) {
request = new UpdateRequest();
}
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(id);
if (request instanceof IndexRequest) {
out.writeByte((byte) 0);
} else if (request instanceof DeleteRequest) {
out.writeByte((byte) 1);
} else if (request instanceof UpdateRequest) {
out.writeByte((byte) 2);
}
request.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_bulk_BulkItemRequest.java
|
125 |
static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
final Throwable ex;
ExceptionNode next;
final long thrower; // use id not ref to avoid weak cycles
final int hashCode; // store task hashCode before weak ref disappears
ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
super(task, exceptionTableRefQueue);
this.ex = ex;
this.next = next;
this.thrower = Thread.currentThread().getId();
this.hashCode = System.identityHashCode(task);
}
}
| 0true
|
src_main_java_jsr166e_ForkJoinTask.java
|
3,429 |
private class ProxyRegistry {
final String serviceName;
final RemoteService service;
final ConcurrentMap<String, DistributedObjectFuture> proxies = new ConcurrentHashMap<String, DistributedObjectFuture>();
private ProxyRegistry(String serviceName) {
this.serviceName = serviceName;
this.service = nodeEngine.getService(serviceName);
if (service == null) {
if (nodeEngine.isActive()) {
throw new IllegalArgumentException("Unknown service: " + serviceName);
} else {
throw new HazelcastInstanceNotActiveException();
}
}
}
/**
* Retrieves a DistributedObject proxy or creates it if it's not available
*
* @param name name of the proxy object
* @param publishEvent true if a DistributedObjectEvent should be fired
* @param initialize true if proxy object should be initialized
* @return a DistributedObject instance
*/
DistributedObject getOrCreateProxy(final String name, boolean publishEvent, boolean initialize) {
DistributedObjectFuture proxyFuture = proxies.get(name);
if (proxyFuture == null) {
if (!nodeEngine.isActive()) {
throw new HazelcastInstanceNotActiveException();
}
proxyFuture = createProxy(name, publishEvent, initialize);
if (proxyFuture == null) {
// warning; recursive call! I (@mdogan) do not think this will ever cause a stack overflow..
return getOrCreateProxy(name, publishEvent, initialize);
}
}
return proxyFuture.get();
}
/**
* Creates a DistributedObject proxy if it's not created yet
*
* @param name name of the proxy object
* @param publishEvent true if a DistributedObjectEvent should be fired
* @param initialize true if proxy object should be initialized
* @return a DistributedObject instance if it's created by this method, null otherwise
*/
DistributedObjectFuture createProxy(final String name, boolean publishEvent, boolean initialize) {
if (!proxies.containsKey(name)) {
if (!nodeEngine.isActive()) {
throw new HazelcastInstanceNotActiveException();
}
DistributedObjectFuture proxyFuture = new DistributedObjectFuture();
if (proxies.putIfAbsent(name, proxyFuture) == null) {
DistributedObject proxy = service.createDistributedObject(name);
if (initialize && proxy instanceof InitializingObject) {
try {
((InitializingObject) proxy).initialize();
} catch (Exception e) {
logger.warning("Error while initializing proxy: " + proxy, e);
}
}
nodeEngine.eventService.executeEvent(new ProxyEventProcessor(CREATED, serviceName, proxy));
if (publishEvent) {
publish(new DistributedObjectEventPacket(CREATED, serviceName, name));
}
proxyFuture.set(proxy);
return proxyFuture;
}
}
return null;
}
void destroyProxy(String name, boolean publishEvent) {
final DistributedObjectFuture proxyFuture = proxies.remove(name);
if (proxyFuture != null) {
DistributedObject proxy = proxyFuture.get();
nodeEngine.eventService.executeEvent(new ProxyEventProcessor(DESTROYED, serviceName, proxy));
if (publishEvent) {
publish(new DistributedObjectEventPacket(DESTROYED, serviceName, name));
}
}
}
private void publish(DistributedObjectEventPacket event) {
final EventService eventService = nodeEngine.getEventService();
final Collection<EventRegistration> registrations = eventService.getRegistrations(SERVICE_NAME, SERVICE_NAME);
eventService.publishEvent(SERVICE_NAME, registrations, event, event.getName().hashCode());
}
private boolean contains(String name) {
return proxies.containsKey(name);
}
void destroy() {
for (DistributedObjectFuture future : proxies.values()) {
DistributedObject distributedObject = future.get();
if (distributedObject instanceof AbstractDistributedObject) {
((AbstractDistributedObject) distributedObject).invalidate();
}
}
proxies.clear();
}
public int getProxyCount() {
return proxies.size();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_spi_impl_ProxyServiceImpl.java
|
1,351 |
public class ProjectSourceFile extends SourceFile implements IResourceAware {
public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
super(phasedUnit);
}
@Override
public ProjectPhasedUnit getPhasedUnit() {
return (ProjectPhasedUnit) super.getPhasedUnit();
}
@Override
public IProject getProjectResource() {
return getPhasedUnit().getProjectResource();
}
@Override
public IFile getFileResource() {
return getPhasedUnit().getSourceFileResource();
}
@Override
public IFolder getRootFolderResource() {
return getPhasedUnit().getSourceFolderResource();
}
public CompilationUnitDelta buildDeltaAgainstModel() {
try {
final ProjectPhasedUnit modelPhaseUnit = getPhasedUnit();
if (modelPhaseUnit != null) {
final ResourceVirtualFile virtualSrcFile = ResourceVirtualFile.createResourceVirtualFile(modelPhaseUnit.getSourceFileResource());
final ResourceVirtualFile virtualSrcDir = ResourceVirtualFile.createResourceVirtualFile(modelPhaseUnit.getSourceFolderResource());
final TypeChecker currentTypechecker = modelPhaseUnit.getTypeChecker();
final ModuleManager currentModuleManager = currentTypechecker.getPhasedUnits().getModuleManager();
Package singleSourceUnitPackage = new SingleSourceUnitPackage(getPackage(), virtualSrcFile.getPath());
PhasedUnit lastPhasedUnit = new CeylonSourceParser<PhasedUnit>() {
@Override
protected String getCharset() {
try {
return modelPhaseUnit.getProjectResource().getDefaultCharset();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
@Override
protected PhasedUnit createPhasedUnit(CompilationUnit cu, Package pkg, CommonTokenStream tokenStream) {
return new PhasedUnit(virtualSrcFile,
virtualSrcDir, cu, pkg,
currentModuleManager,
currentTypechecker.getContext(),
tokenStream.getTokens()) {
@Override
protected boolean reuseExistingDescriptorModels() {
return true;
}
};
}
}.parseFileToPhasedUnit(
currentModuleManager,
currentTypechecker,
virtualSrcFile,
virtualSrcDir,
singleSourceUnitPackage);
if (lastPhasedUnit != null) {
lastPhasedUnit.validateTree();
lastPhasedUnit.visitSrcModulePhase();
lastPhasedUnit.visitRemainingModulePhase();
lastPhasedUnit.scanDeclarations();
lastPhasedUnit.scanTypeDeclarations();
lastPhasedUnit.validateRefinement();
lastPhasedUnit.analyseFlow();
UnknownTypeCollector utc = new UnknownTypeCollector();
lastPhasedUnit.getCompilationUnit().visit(utc);
if (lastPhasedUnit.getCompilationUnit().getErrors().isEmpty()) {
return buildDeltas_.buildDeltas(modelPhaseUnit, lastPhasedUnit);
}
}
}
} catch(Exception e) {
} catch(ceylon.language.AssertionError e) {
e.printStackTrace();
}
return null;
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_ProjectSourceFile.java
|
1,637 |
public class FaunusCassandraIT extends AbstractTitanAssemblyIT {
@BeforeClass
public static void startCassandra() {
CassandraStorageSetup.startCleanEmbedded();
}
@Test
@Category({ OrderedKeyStoreTests.class })
public void testGraphOfTheGodsWithBOP() throws Exception {
unzipAndRunExpect("faunus-cassandra.expect.vm", ImmutableMap.of("cassandraPartitioner", "org.apache.cassandra.dht.ByteOrderedPartitioner"));
}
@Test
@Category({ UnorderedKeyStoreTests.class })
public void testGraphOfTheGodsWithMurmur() throws Exception {
unzipAndRunExpect("faunus-cassandra.expect.vm", ImmutableMap.of("cassandraPartitioner", "org.apache.cassandra.dht.Murmur3Partitioner"));
}
}
| 1no label
|
titan-dist_src_test_java_com_thinkaurelius_titan_pkgtest_FaunusCassandraIT.java
|
1,081 |
public static class Result {
private final Streamable action;
private final Operation operation;
private final Map<String, Object> updatedSourceAsMap;
private final XContentType updateSourceContentType;
public Result(Streamable action, Operation operation, Map<String, Object> updatedSourceAsMap, XContentType updateSourceContentType) {
this.action = action;
this.operation = operation;
this.updatedSourceAsMap = updatedSourceAsMap;
this.updateSourceContentType = updateSourceContentType;
}
@SuppressWarnings("unchecked")
public <T extends Streamable> T action() {
return (T) action;
}
public Operation operation() {
return operation;
}
public Map<String, Object> updatedSourceAsMap() {
return updatedSourceAsMap;
}
public XContentType updateSourceContentType() {
return updateSourceContentType;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_update_UpdateHelper.java
|
179 |
public class ForkJoinWorkerThread extends Thread {
/*
* ForkJoinWorkerThreads are managed by ForkJoinPools and perform
* ForkJoinTasks. For explanation, see the internal documentation
* of class ForkJoinPool.
*
* This class just maintains links to its pool and WorkQueue. The
* pool field is set immediately upon construction, but the
* workQueue field is not set until a call to registerWorker
* completes. This leads to a visibility race, that is tolerated
* by requiring that the workQueue field is only accessed by the
* owning thread.
*/
final ForkJoinPool pool; // the pool this thread works in
final ForkJoinPool.WorkQueue workQueue; // work-stealing mechanics
/**
* Creates a ForkJoinWorkerThread operating in the given pool.
*
* @param pool the pool this thread works in
* @throws NullPointerException if pool is null
*/
protected ForkJoinWorkerThread(ForkJoinPool pool) {
// Use a placeholder until a useful name can be set in registerWorker
super("aForkJoinWorkerThread");
this.pool = pool;
this.workQueue = pool.registerWorker(this);
}
/**
* Returns the pool hosting this thread.
*
* @return the pool
*/
public ForkJoinPool getPool() {
return pool;
}
/**
* Returns the index number of this thread in its pool. The
* returned value ranges from zero to the maximum number of
* threads (minus one) that have ever been created in the pool.
* This method may be useful for applications that track status or
* collect results per-worker rather than per-task.
*
* @return the index number
*/
public int getPoolIndex() {
return workQueue.poolIndex;
}
/**
* Initializes internal state after construction but before
* processing any tasks. If you override this method, you must
* invoke {@code super.onStart()} at the beginning of the method.
* Initialization requires care: Most fields must have legal
* default values, to ensure that attempted accesses from other
* threads work correctly even before this thread starts
* processing tasks.
*/
protected void onStart() {
}
/**
* Performs cleanup associated with termination of this worker
* thread. If you override this method, you must invoke
* {@code super.onTermination} at the end of the overridden method.
*
* @param exception the exception causing this thread to abort due
* to an unrecoverable error, or {@code null} if completed normally
*/
protected void onTermination(Throwable exception) {
}
/**
* This method is required to be public, but should never be
* called explicitly. It performs the main run loop to execute
* {@link ForkJoinTask}s.
*/
public void run() {
Throwable exception = null;
try {
onStart();
pool.runWorker(workQueue);
} catch (Throwable ex) {
exception = ex;
} finally {
try {
onTermination(exception);
} catch (Throwable ex) {
if (exception == null)
exception = ex;
} finally {
pool.deregisterWorker(this, exception);
}
}
}
}
| 0true
|
src_main_java_jsr166y_ForkJoinWorkerThread.java
|
570 |
public class BigDecimalRoundingAdapter extends XmlAdapter<String, BigDecimal> {
@Override
public BigDecimal unmarshal(String s) throws Exception {
return new BigDecimal(s);
}
@Override
public String marshal(BigDecimal bigDecimal) throws Exception {
return bigDecimal.setScale(2, RoundingMode.UP).toString();
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_xml_BigDecimalRoundingAdapter.java
|
1,057 |
@SuppressWarnings("unchecked")
public class OCommandExecutorSQLTraverse extends OCommandExecutorSQLResultsetAbstract {
public static final String KEYWORD_WHILE = "WHILE";
public static final String KEYWORD_TRAVERSE = "TRAVERSE";
public static final String KEYWORD_STRATEGY = "STRATEGY";
// HANDLES ITERATION IN LAZY WAY
private OTraverse traverse = new OTraverse();
/**
* Compile the filter conditions only the first time.
*/
public OCommandExecutorSQLTraverse parse(final OCommandRequest iRequest) {
super.parse(iRequest);
final int pos = parseFields();
if (pos == -1)
throw new OCommandSQLParsingException("Traverse must have the field list. Use " + getSyntax());
int endPosition = parserText.length();
int endP = parserTextUpperCase.indexOf(" " + OCommandExecutorSQLTraverse.KEYWORD_LIMIT, parserGetCurrentPosition());
if (endP > -1 && endP < endPosition)
endPosition = endP;
parsedTarget = OSQLEngine.getInstance().parseTarget(parserText.substring(pos, endPosition), getContext(), KEYWORD_WHILE);
if (!parsedTarget.parserIsEnded()) {
parserSetCurrentPosition(parsedTarget.parserGetCurrentPosition() + pos);
parserNextWord(true);
if (parserGetLastWord().equalsIgnoreCase(KEYWORD_WHERE))
// // TODO Remove the additional management of WHERE for TRAVERSE after a while
warnDeprecatedWhere();
if (parserGetLastWord().equalsIgnoreCase(KEYWORD_WHERE) || parserGetLastWord().equalsIgnoreCase(KEYWORD_WHILE)) {
compiledFilter = OSQLEngine.getInstance().parseCondition(parserText.substring(parserGetCurrentPosition(), endPosition),
getContext(), KEYWORD_WHILE);
traverse.predicate(compiledFilter);
optimize();
parserSetCurrentPosition(compiledFilter.parserIsEnded() ? endPosition : compiledFilter.parserGetCurrentPosition()
+ parserGetCurrentPosition());
} else
parserGoBack();
} else
parserSetCurrentPosition(-1);
parserSkipWhiteSpaces();
if (!parserIsEnded()) {
if (parserOptionalKeyword(KEYWORD_LIMIT, KEYWORD_SKIP, KEYWORD_TIMEOUT, KEYWORD_STRATEGY)) {
final String w = parserGetLastWord();
if (w.equals(KEYWORD_LIMIT))
parseLimit(w);
else if (w.equals(KEYWORD_SKIP))
parseSkip(w);
else if (w.equals(KEYWORD_TIMEOUT))
parseTimeout(w);
else if (w.equals(KEYWORD_STRATEGY))
parseStrategy(w);
}
}
if (limit == 0 || limit < -1)
throw new IllegalArgumentException("Limit must be > 0 or = -1 (no limit)");
else
traverse.limit(limit);
((OCommandRequestText) iRequest).getContext().setChild(traverse.getContext());
return this;
}
protected void warnDeprecatedWhere() {
OLogManager
.instance()
.warn(
this,
"Keyword WHERE in traverse has been replaced by WHILE. Please change your query to support WHILE instead of WHERE because now it's only deprecated, but in future it will be removed the back-ward compatibility.");
}
@Override
protected boolean assignTarget(Map<Object, Object> iArgs) {
if (super.assignTarget(iArgs)) {
traverse.target(target);
return true;
}
return false;
}
public Object execute(final Map<Object, Object> iArgs) {
if (!assignTarget(iArgs))
throw new OQueryParsingException("No source found in query: specify class, cluster(s) or single record(s)");
context = traverse.getContext();
context.beginExecution(timeoutMs, timeoutStrategy);
// BROWSE ALL THE RECORDS AND COLLECTS RESULT
final List<OIdentifiable> result = (List<OIdentifiable>) traverse.execute();
for (OIdentifiable r : result)
handleResult(r, true);
return getResult();
}
public boolean hasNext() {
if (target == null)
assignTarget(null);
return traverse.hasNext();
}
@Override
public OCommandContext getContext() {
return traverse.getContext();
}
public OIdentifiable next() {
if (target == null)
assignTarget(null);
return traverse.next();
}
public void remove() {
throw new UnsupportedOperationException("remove()");
}
public Iterator<OIdentifiable> iterator() {
return this;
}
public String getSyntax() {
return "TRAVERSE <field>* FROM <target> [WHILE <condition>] [STRATEGY <strategy>]";
}
protected int parseFields() {
int currentPos = 0;
final StringBuilder word = new StringBuilder();
currentPos = nextWord(parserText, parserTextUpperCase, currentPos, word, true);
if (!word.toString().equals(KEYWORD_TRAVERSE))
return -1;
int fromPosition = parserTextUpperCase.indexOf(KEYWORD_FROM_2FIND, currentPos);
if (fromPosition == -1)
throw new OQueryParsingException("Missed " + KEYWORD_FROM, parserText, currentPos);
Set<Object> fields = new HashSet<Object>();
final String fieldString = parserText.substring(currentPos, fromPosition).trim();
if (fieldString.length() > 0) {
// EXTRACT PROJECTIONS
final List<String> items = OStringSerializerHelper.smartSplit(fieldString, ',');
for (String field : items) {
final String fieldName = field.trim();
if (fieldName.contains("("))
fields.add(OSQLHelper.parseValue((OBaseParser) null, fieldName, context));
else
fields.add(fieldName);
}
} else
throw new OQueryParsingException("Missed field list to cross in TRAVERSE. Use " + getSyntax(), parserText, currentPos);
currentPos = fromPosition + KEYWORD_FROM.length() + 1;
traverse.fields(fields);
return currentPos;
}
/**
* Parses the strategy keyword if found.
*/
protected boolean parseStrategy(final String w) throws OCommandSQLParsingException {
if (!w.equals(KEYWORD_STRATEGY))
return false;
parserNextWord(true);
final String strategyWord = parserGetLastWord();
try {
traverse.setStrategy(OTraverse.STRATEGY.valueOf(strategyWord.toUpperCase()));
} catch (IllegalArgumentException e) {
throwParsingException("Invalid " + KEYWORD_STRATEGY + ". Use one between " + OTraverse.STRATEGY.values());
}
return true;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLTraverse.java
|
1,325 |
assertThat(awaitBusy(new Predicate<Object>() {
public boolean apply(Object o) {
ClusterState state = client().admin().cluster().prepareState().setLocal(true).execute().actionGet().getState();
return state.blocks().hasGlobalBlock(Discovery.NO_MASTER_BLOCK);
}
}), equalTo(true));
| 0true
|
src_test_java_org_elasticsearch_cluster_NoMasterNodeTests.java
|
725 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_SKU")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
@AdminPresentationClass(friendlyName = "baseSku")
public class SkuImpl implements Sku {
private static final Log LOG = LogFactory.getLog(SkuImpl.class);
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "SkuId")
@GenericGenerator(
name = "SkuId",
strategy = "org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name = "segment_value", value = "SkuImpl"),
@Parameter(name = "entity_name", value = "org.broadleafcommerce.core.catalog.domain.SkuImpl")
}
)
@Column(name = "SKU_ID")
@AdminPresentation(friendlyName = "SkuImpl_Sku_ID", visibility = VisibilityEnum.HIDDEN_ALL)
protected Long id;
@Column(name = "SALE_PRICE", precision = 19, scale = 5)
@AdminPresentation(friendlyName = "SkuImpl_Sku_Sale_Price", order = 2000,
group = ProductImpl.Presentation.Group.Name.Price, groupOrder = ProductImpl.Presentation.Group.Order.Price,
prominent = true, gridOrder = 6,
fieldType = SupportedFieldType.MONEY)
protected BigDecimal salePrice;
@Column(name = "RETAIL_PRICE", precision = 19, scale = 5)
@AdminPresentation(friendlyName = "SkuImpl_Sku_Retail_Price", order = 1000,
group = ProductImpl.Presentation.Group.Name.Price, groupOrder = ProductImpl.Presentation.Group.Order.Price,
prominent = true, gridOrder = 5,
fieldType = SupportedFieldType.MONEY)
protected BigDecimal retailPrice;
@Column(name = "NAME")
@Index(name = "SKU_NAME_INDEX", columnNames = {"NAME"})
@AdminPresentation(friendlyName = "SkuImpl_Sku_Name", order = ProductImpl.Presentation.FieldOrder.NAME,
group = ProductImpl.Presentation.Group.Name.General, groupOrder = ProductImpl.Presentation.Group.Order.General,
prominent = true, gridOrder = 1, columnWidth = "260px",
translatable = true)
protected String name;
@Column(name = "DESCRIPTION")
@AdminPresentation(friendlyName = "SkuImpl_Sku_Description", order = ProductImpl.Presentation.FieldOrder.SHORT_DESCRIPTION,
group = ProductImpl.Presentation.Group.Name.General, groupOrder = ProductImpl.Presentation.Group.Order.General,
largeEntry = true,
excluded = true,
translatable = true)
protected String description;
@Lob
@Type(type = "org.hibernate.type.StringClobType")
@Column(name = "LONG_DESCRIPTION", length = Integer.MAX_VALUE - 1)
@AdminPresentation(friendlyName = "SkuImpl_Sku_Large_Description", order = ProductImpl.Presentation.FieldOrder.LONG_DESCRIPTION,
group = ProductImpl.Presentation.Group.Name.General, groupOrder = ProductImpl.Presentation.Group.Order.General,
largeEntry = true,
fieldType = SupportedFieldType.HTML_BASIC,
translatable = true)
protected String longDescription;
@Column(name = "TAX_CODE")
@AdminPresentation(friendlyName = "SkuImpl_Sku_TaxCode", order = 1001, group = ProductImpl.Presentation.Group.Name.Financial)
@AdminPresentationDataDrivenEnumeration(optionFilterParams = { @OptionFilterParam(param = "type.key", value = "TAX_CODE", paramType = OptionFilterParamType.STRING) })
protected String taxCode;
@Column(name = "TAXABLE_FLAG")
@Index(name="SKU_TAXABLE_INDEX", columnNames={"TAXABLE_FLAG"})
@AdminPresentation(friendlyName = "SkuImpl_Sku_Taxable", order = 1000,
group = ProductImpl.Presentation.Group.Name.Financial)
protected Character taxable;
@Column(name = "DISCOUNTABLE_FLAG")
@Index(name="SKU_DISCOUNTABLE_INDEX", columnNames={"DISCOUNTABLE_FLAG"})
@AdminPresentation(friendlyName = "SkuImpl_Sku_Discountable", order = 2000,
tab = ProductImpl.Presentation.Tab.Name.Advanced, tabOrder = ProductImpl.Presentation.Tab.Order.Advanced,
group = ProductImpl.Presentation.Group.Name.Advanced, groupOrder = ProductImpl.Presentation.Group.Order.Advanced)
protected Character discountable = 'Y';
@Column(name = "AVAILABLE_FLAG")
@Index(name = "SKU_AVAILABLE_INDEX", columnNames = {"AVAILABLE_FLAG"})
@AdminPresentation(friendlyName = "SkuImpl_Sku_Available", order = 2000,
tab = ProductImpl.Presentation.Tab.Name.Inventory, tabOrder = ProductImpl.Presentation.Tab.Order.Inventory,
group = ProductImpl.Presentation.Group.Name.Inventory, groupOrder = ProductImpl.Presentation.Group.Order.Inventory)
protected Character available;
@Column(name = "ACTIVE_START_DATE")
@Index(name="SKU_ACTIVE_START_INDEX")
@AdminPresentation(friendlyName = "SkuImpl_Sku_Start_Date", order = 1000,
group = ProductImpl.Presentation.Group.Name.ActiveDateRange,
groupOrder = ProductImpl.Presentation.Group.Order.ActiveDateRange,
tooltip = "skuStartDateTooltip")
protected Date activeStartDate;
@Column(name = "ACTIVE_END_DATE")
@Index(name="SKU_ACTIVE_END_INDEX")
@AdminPresentation(friendlyName = "SkuImpl_Sku_End_Date", order = 2000,
group = ProductImpl.Presentation.Group.Name.ActiveDateRange,
groupOrder = ProductImpl.Presentation.Group.Order.ActiveDateRange,
tooltip = "skuEndDateTooltip")
protected Date activeEndDate;
@Embedded
protected Dimension dimension = new Dimension();
@Embedded
protected Weight weight = new Weight();
@Transient
protected DynamicSkuPrices dynamicPrices = null;
@Column(name = "IS_MACHINE_SORTABLE")
@AdminPresentation(friendlyName = "ProductImpl_Is_Product_Machine_Sortable", order = 10000,
tab = ProductImpl.Presentation.Tab.Name.Shipping, tabOrder = ProductImpl.Presentation.Tab.Order.Shipping,
group = ProductImpl.Presentation.Group.Name.Shipping, groupOrder = ProductImpl.Presentation.Group.Order.Shipping)
protected Boolean isMachineSortable = true;
@ManyToMany(targetEntity = MediaImpl.class)
@JoinTable(name = "BLC_SKU_MEDIA_MAP",
inverseJoinColumns = @JoinColumn(name = "MEDIA_ID", referencedColumnName = "MEDIA_ID"))
@MapKeyColumn(name = "MAP_KEY")
@Cascade(value = {org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
@AdminPresentationMap(friendlyName = "SkuImpl_Sku_Media",
tab = ProductImpl.Presentation.Tab.Name.Media, tabOrder = ProductImpl.Presentation.Tab.Order.Media,
keyPropertyFriendlyName = "SkuImpl_Sku_Media_Key",
deleteEntityUponRemove = true,
mediaField = "url",
forceFreeFormKeys = true
)
@AdminPresentationMapFields(
mapDisplayFields = {
@AdminPresentationMapField(
fieldName = "primary",
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.MEDIA,
group = ProductImpl.Presentation.Group.Name.General,
groupOrder = ProductImpl.Presentation.Group.Order.General,
order = ProductImpl.Presentation.FieldOrder.PRIMARY_MEDIA,
friendlyName = "SkuImpl_Primary_Media")
)
})
protected Map<String, Media> skuMedia = new HashMap<String, Media>();
/**
* This will be non-null if and only if this Sku is the default Sku for a Product
*/
@OneToOne(optional = true, targetEntity = ProductImpl.class, cascade = {CascadeType.ALL})
@Cascade(value = {org.hibernate.annotations.CascadeType.ALL})
@JoinColumn(name = "DEFAULT_PRODUCT_ID")
protected Product defaultProduct;
/**
* This relationship will be non-null if and only if this Sku is contained in the list of
* additional Skus for a Product (for Skus based on ProductOptions)
*/
@ManyToOne(optional = true, targetEntity = ProductImpl.class)
@JoinTable(name = "BLC_PRODUCT_SKU_XREF",
joinColumns = @JoinColumn(name = "SKU_ID", referencedColumnName = "SKU_ID"),
inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID"))
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
protected Product product;
@OneToMany(mappedBy = "sku", targetEntity = SkuAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blStandardElements")
@MapKey(name="name")
@BatchSize(size = 50)
@AdminPresentationMap(friendlyName = "skuAttributesTitle",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
deleteEntityUponRemove = true, forceFreeFormKeys = true)
protected Map<String, SkuAttribute> skuAttributes = new HashMap<String, SkuAttribute>();
@ManyToMany(targetEntity = ProductOptionValueImpl.class)
@JoinTable(name = "BLC_SKU_OPTION_VALUE_XREF",
joinColumns = @JoinColumn(name = "SKU_ID", referencedColumnName = "SKU_ID"),
inverseJoinColumns = @JoinColumn(name = "PRODUCT_OPTION_VALUE_ID",referencedColumnName = "PRODUCT_OPTION_VALUE_ID"))
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
@BatchSize(size = 50)
protected List<ProductOptionValue> productOptionValues = new ArrayList<ProductOptionValue>();
@ManyToMany(fetch = FetchType.LAZY, targetEntity = SkuFeeImpl.class)
@JoinTable(name = "BLC_SKU_FEE_XREF",
joinColumns = @JoinColumn(name = "SKU_ID", referencedColumnName = "SKU_ID", nullable = true),
inverseJoinColumns = @JoinColumn(name = "SKU_FEE_ID", referencedColumnName = "SKU_FEE_ID", nullable = true))
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
protected List<SkuFee> fees = new ArrayList<SkuFee>();
@ElementCollection
@CollectionTable(name = "BLC_SKU_FULFILLMENT_FLAT_RATES",
joinColumns = @JoinColumn(name = "SKU_ID", referencedColumnName = "SKU_ID", nullable = true))
@MapKeyJoinColumn(name = "FULFILLMENT_OPTION_ID", referencedColumnName = "FULFILLMENT_OPTION_ID")
@MapKeyClass(FulfillmentOptionImpl.class)
@Column(name = "RATE", precision = 19, scale = 5)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
protected Map<FulfillmentOption, BigDecimal> fulfillmentFlatRates = new HashMap<FulfillmentOption, BigDecimal>();
@ManyToMany(targetEntity = FulfillmentOptionImpl.class)
@JoinTable(name = "BLC_SKU_FULFILLMENT_EXCLUDED",
joinColumns = @JoinColumn(name = "SKU_ID", referencedColumnName = "SKU_ID"),
inverseJoinColumns = @JoinColumn(name = "FULFILLMENT_OPTION_ID",referencedColumnName = "FULFILLMENT_OPTION_ID"))
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
@BatchSize(size = 50)
protected List<FulfillmentOption> excludedFulfillmentOptions = new ArrayList<FulfillmentOption>();
@Column(name = "INVENTORY_TYPE")
@AdminPresentation(friendlyName = "SkuImpl_Sku_InventoryType", order = 1000,
tab = ProductImpl.Presentation.Tab.Name.Inventory, tabOrder = ProductImpl.Presentation.Tab.Order.Inventory,
group = ProductImpl.Presentation.Group.Name.Inventory, groupOrder = ProductImpl.Presentation.Group.Order.Inventory,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.core.inventory.service.type.InventoryType")
protected String inventoryType;
@Column(name = "FULFILLMENT_TYPE")
@AdminPresentation(friendlyName = "SkuImpl_Sku_FulfillmentType", order = 2000,
tab = ProductImpl.Presentation.Tab.Name.Inventory, tabOrder = ProductImpl.Presentation.Tab.Order.Inventory,
group = ProductImpl.Presentation.Group.Name.Inventory, groupOrder = ProductImpl.Presentation.Group.Order.Inventory,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.core.order.service.type.FulfillmentType")
protected String fulfillmentType;
/**
* Note that this field is not the target of the currencyCodeField attribute on either retailPrice or salePrice.
* This is because SKUs are special in that we want to return the currency on this SKU if there is one, falling back
* to the defaultSku's currency if possible.
*/
@ManyToOne(targetEntity = BroadleafCurrencyImpl.class)
@JoinColumn(name = "CURRENCY_CODE")
@AdminPresentation(friendlyName = "SkuImpl_Currency", order = 3000,
tab = ProductImpl.Presentation.Tab.Name.Advanced, tabOrder = ProductImpl.Presentation.Tab.Order.Advanced,
group = ProductImpl.Presentation.Group.Name.Advanced, groupOrder = ProductImpl.Presentation.Group.Order.Advanced)
@AdminPresentationToOneLookup(lookupType = LookupType.DROPDOWN, lookupDisplayProperty = "friendlyName")
protected BroadleafCurrency currency;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public boolean isOnSale() {
Money retailPrice = getRetailPrice();
Money salePrice = getSalePrice();
return (salePrice != null && !salePrice.isZero() && salePrice.lessThan(retailPrice));
}
protected boolean hasDefaultSku() {
return (product != null && product.getDefaultSku() != null && !getId().equals(product.getDefaultSku().getId()));
}
protected Sku lookupDefaultSku() {
if (product != null && product.getDefaultSku() != null) {
return product.getDefaultSku();
} else {
return null;
}
}
@Override
public Money getProductOptionValueAdjustments() {
Money optionValuePriceAdjustments = null;
if (getProductOptionValues() != null) {
for (ProductOptionValue value : getProductOptionValues()) {
if (value.getPriceAdjustment() != null) {
if (optionValuePriceAdjustments == null) {
optionValuePriceAdjustments = value.getPriceAdjustment();
} else {
optionValuePriceAdjustments = optionValuePriceAdjustments.add(value.getPriceAdjustment());
}
}
}
}
return optionValuePriceAdjustments;
}
@Override
public Money getSalePrice() {
Money returnPrice = null;
Money optionValueAdjustments = null;
if (SkuPricingConsiderationContext.hasDynamicPricing()) {
// We have dynamic pricing, so we will pull the sale price from there
if (dynamicPrices == null) {
DefaultDynamicSkuPricingInvocationHandler handler = new DefaultDynamicSkuPricingInvocationHandler(this);
Sku proxy = (Sku) Proxy.newProxyInstance(getClass().getClassLoader(), ClassUtils.getAllInterfacesForClass(getClass()), handler);
dynamicPrices = SkuPricingConsiderationContext.getSkuPricingService().getSkuPrices(proxy, SkuPricingConsiderationContext.getSkuPricingConsiderationContext());
}
returnPrice = dynamicPrices.getSalePrice();
optionValueAdjustments = dynamicPrices.getPriceAdjustment();
} else if (salePrice != null) {
// We have an explicitly set sale price directly on this entity. We will not apply any adjustments
returnPrice = new Money(salePrice, getCurrency());
}
if (returnPrice == null && hasDefaultSku()) {
returnPrice = lookupDefaultSku().getSalePrice();
optionValueAdjustments = getProductOptionValueAdjustments();
}
if (returnPrice == null) {
return null;
}
if (optionValueAdjustments != null) {
returnPrice = returnPrice.add(optionValueAdjustments);
}
return returnPrice;
}
@Override
public void setSalePrice(Money salePrice) {
this.salePrice = Money.toAmount(salePrice);
}
@Override
public Money getRetailPrice() {
Money returnPrice = null;
Money optionValueAdjustments = null;
if (SkuPricingConsiderationContext.hasDynamicPricing()) {
// We have dynamic pricing, so we will pull the retail price from there
if (dynamicPrices == null) {
DefaultDynamicSkuPricingInvocationHandler handler = new DefaultDynamicSkuPricingInvocationHandler(this);
Sku proxy = (Sku) Proxy.newProxyInstance(getClass().getClassLoader(), ClassUtils.getAllInterfacesForClass(getClass()), handler);
dynamicPrices = SkuPricingConsiderationContext.getSkuPricingService().getSkuPrices(proxy, SkuPricingConsiderationContext.getSkuPricingConsiderationContext());
}
returnPrice = dynamicPrices.getRetailPrice();
optionValueAdjustments = dynamicPrices.getPriceAdjustment();
} else if (retailPrice != null) {
returnPrice = new Money(retailPrice, getCurrency());
}
if (returnPrice == null && hasDefaultSku()) {
// Otherwise, we'll pull the retail price from the default sku
returnPrice = lookupDefaultSku().getRetailPrice();
optionValueAdjustments = getProductOptionValueAdjustments();
}
if (returnPrice == null) {
throw new IllegalStateException("Retail price on Sku with id " + getId() + " was null");
}
if (optionValueAdjustments != null) {
returnPrice = returnPrice.add(optionValueAdjustments);
}
return returnPrice;
}
@Override
public void setRetailPrice(Money retailPrice) {
this.retailPrice = Money.toAmount(retailPrice);
}
@Override
public Money getListPrice() {
return getRetailPrice();
}
@Override
public void setListPrice(Money listPrice) {
this.retailPrice = Money.toAmount(listPrice);
}
@Override
public String getName() {
if (name == null && hasDefaultSku()) {
return lookupDefaultSku().getName();
}
return DynamicTranslationProvider.getValue(this, "name", name);
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
if (description == null && hasDefaultSku()) {
return lookupDefaultSku().getDescription();
}
return DynamicTranslationProvider.getValue(this, "description", description);
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public String getLongDescription() {
if (longDescription == null && hasDefaultSku()) {
return lookupDefaultSku().getLongDescription();
}
return DynamicTranslationProvider.getValue(this, "longDescription", longDescription);
}
@Override
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
@Override
public Boolean isTaxable() {
if (taxable == null) {
if (hasDefaultSku()) {
return lookupDefaultSku().isTaxable();
}
return null;
}
return taxable == 'Y' ? Boolean.TRUE : Boolean.FALSE;
}
@Override
public Boolean getTaxable() {
return isTaxable();
}
@Override
public void setTaxable(Boolean taxable) {
if (taxable == null) {
this.taxable = null;
} else {
this.taxable = taxable ? 'Y' : 'N';
}
}
@Override
public Boolean isDiscountable() {
if (discountable == null) {
if (hasDefaultSku()) {
return lookupDefaultSku().isDiscountable();
}
return Boolean.FALSE;
}
return discountable == 'Y' ? Boolean.TRUE : Boolean.FALSE;
}
/*
* This is to facilitate serialization to non-Java clients
*/
public Boolean getDiscountable() {
return isDiscountable();
}
@Override
public void setDiscountable(Boolean discountable) {
if (discountable == null) {
this.discountable = null;
} else {
this.discountable = discountable ? 'Y' : 'N';
}
}
@Override
public Boolean isAvailable() {
if (available == null) {
if (hasDefaultSku()) {
return lookupDefaultSku().isAvailable();
}
return true;
}
return available == 'Y' ? Boolean.TRUE : Boolean.FALSE;
}
@Override
public Boolean getAvailable() {
return isAvailable();
}
@Override
public void setAvailable(Boolean available) {
if (available == null) {
this.available = null;
} else {
this.available = available ? 'Y' : 'N';
}
}
@Override
public Date getActiveStartDate() {
Date returnDate = null;
if (SkuActiveDateConsiderationContext.hasDynamicActiveDates()) {
returnDate = SkuActiveDateConsiderationContext.getSkuActiveDatesService().getDynamicSkuActiveStartDate(this);
}
if (returnDate == null) {
if (activeStartDate == null && hasDefaultSku()) {
return lookupDefaultSku().getActiveStartDate();
} else {
return activeStartDate;
}
} else {
return returnDate;
}
}
@Override
public void setActiveStartDate(Date activeStartDate) {
this.activeStartDate = activeStartDate;
}
@Override
public Date getActiveEndDate() {
Date returnDate = null;
if (SkuActiveDateConsiderationContext.hasDynamicActiveDates()) {
returnDate = SkuActiveDateConsiderationContext.getSkuActiveDatesService().getDynamicSkuActiveEndDate(this);
}
if (returnDate == null) {
if (activeEndDate == null && hasDefaultSku()) {
return lookupDefaultSku().getActiveEndDate();
} else {
return activeEndDate;
}
} else {
return returnDate;
}
}
@Override
public void setActiveEndDate(Date activeEndDate) {
this.activeEndDate = activeEndDate;
}
@Override
public Dimension getDimension() {
if (dimension == null && hasDefaultSku()) {
return lookupDefaultSku().getDimension();
} else {
return dimension;
}
}
@Override
public void setDimension(Dimension dimension) {
this.dimension = dimension;
}
@Override
public Weight getWeight() {
if (weight == null && hasDefaultSku()) {
return lookupDefaultSku().getWeight();
} else {
return weight;
}
}
@Override
public void setWeight(Weight weight) {
this.weight = weight;
}
@Override
public boolean isActive() {
if (activeStartDate == null && activeEndDate == null && hasDefaultSku()) {
return lookupDefaultSku().isActive();
}
if (LOG.isDebugEnabled()) {
if (!DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true)) {
LOG.debug("sku, " + id + ", inactive due to date");
}
}
return DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true);
}
@Override
public boolean isActive(Product product, Category category) {
if (LOG.isDebugEnabled()) {
if (!DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true)) {
LOG.debug("sku, " + id + ", inactive due to date");
} else if (!product.isActive()) {
LOG.debug("sku, " + id + ", inactive due to product being inactive");
} else if (!category.isActive()) {
LOG.debug("sku, " + id + ", inactive due to category being inactive");
}
}
return this.isActive() && (product == null || product.isActive()) && (category == null || category.isActive());
}
@Override
public Map<String, Media> getSkuMedia() {
if (skuMedia == null || skuMedia.isEmpty()) {
if (hasDefaultSku()) {
return lookupDefaultSku().getSkuMedia();
}
}
return skuMedia;
}
@Override
public void setSkuMedia(Map<String, Media> skuMedia) {
this.skuMedia = skuMedia;
}
@Override
public Product getDefaultProduct() {
return defaultProduct;
}
@Override
public void setDefaultProduct(Product defaultProduct) {
this.defaultProduct = defaultProduct;
}
@Override
public Product getProduct() {
return (getDefaultProduct() != null) ? getDefaultProduct() : this.product;
}
@Override
public void setProduct(Product product) {
this.product = product;
}
@Override
public List<ProductOptionValue> getProductOptionValues() {
return productOptionValues;
}
@Override
public void setProductOptionValues(List<ProductOptionValue> productOptionValues) {
this.productOptionValues = productOptionValues;
}
@Override
@Deprecated
public Boolean isMachineSortable() {
if (isMachineSortable == null && hasDefaultSku()) {
return lookupDefaultSku().isMachineSortable();
}
return isMachineSortable == null ? false : isMachineSortable;
}
@Override
public Boolean getIsMachineSortable() {
if (isMachineSortable == null && hasDefaultSku()) {
return lookupDefaultSku().getIsMachineSortable();
}
return isMachineSortable == null ? false : isMachineSortable;
}
@Override
@Deprecated
public void setMachineSortable(Boolean isMachineSortable) {
this.isMachineSortable = isMachineSortable;
}
@Override
public void setIsMachineSortable(Boolean isMachineSortable) {
this.isMachineSortable = isMachineSortable;
}
@Override
public List<SkuFee> getFees() {
return fees;
}
@Override
public void setFees(List<SkuFee> fees) {
this.fees = fees;
}
@Override
public Map<FulfillmentOption, BigDecimal> getFulfillmentFlatRates() {
return fulfillmentFlatRates;
}
@Override
public void setFulfillmentFlatRates(Map<FulfillmentOption, BigDecimal> fulfillmentFlatRates) {
this.fulfillmentFlatRates = fulfillmentFlatRates;
}
@Override
public List<FulfillmentOption> getExcludedFulfillmentOptions() {
return excludedFulfillmentOptions;
}
@Override
public void setExcludedFulfillmentOptions(List<FulfillmentOption> excludedFulfillmentOptions) {
this.excludedFulfillmentOptions = excludedFulfillmentOptions;
}
@Override
public InventoryType getInventoryType() {
return InventoryType.getInstance(this.inventoryType);
}
@Override
public void setInventoryType(InventoryType inventoryType) {
this.inventoryType = (inventoryType == null) ? null : inventoryType.getType();
}
@Override
public FulfillmentType getFulfillmentType() {
if (StringUtils.isEmpty(this.fulfillmentType)) {
if (hasDefaultSku() && lookupDefaultSku().getFulfillmentType() != null) {
return lookupDefaultSku().getFulfillmentType();
} else if (getProduct() != null && getProduct().getDefaultCategory() != null) {
return getProduct().getDefaultCategory().getFulfillmentType();
}
}
return FulfillmentType.getInstance(this.fulfillmentType);
}
@Override
public void setFulfillmentType(FulfillmentType fulfillmentType) {
this.fulfillmentType = fulfillmentType.getType();
}
@Override
public Map<String, SkuAttribute> getSkuAttributes() {
return skuAttributes;
}
@Override
public void setSkuAttributes(Map<String, SkuAttribute> skuAttributes) {
this.skuAttributes = skuAttributes;
}
@Override
public BroadleafCurrency getCurrency() {
if (currency == null && hasDefaultSku()) {
return lookupDefaultSku().getCurrency();
} else {
return currency;
}
}
@Override
public void setCurrency(BroadleafCurrency currency) {
this.currency = currency;
}
@Override
public void clearDynamicPrices() {
this.dynamicPrices = null;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SkuImpl other = (SkuImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (getName() == null) {
if (other.getName() != null) {
return false;
}
} else if (!getName().equals(other.getName())) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public String getTaxCode() {
if (StringUtils.isEmpty(taxCode) && hasDefaultSku()) {
return lookupDefaultSku().getTaxCode();
} else if (StringUtils.isEmpty(taxCode)) {
return getProduct().getTaxCode();
}
return taxCode;
}
@Override
public void setTaxCode(String taxCode) {
this.taxCode = taxCode;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_SkuImpl.java
|
194 |
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Audit = "Auditable_Tab";
}
public static class Order {
public static final int Audit = 99000;
}
}
public static class Group {
public static class Name {
public static final String Audit = "Auditable_Audit";
}
public static class Order {
public static final int Audit = 1000;
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_audit_Auditable.java
|
95 |
public class Geoshape {
private static final SpatialContext CTX = SpatialContext.GEO;
/**
* The Type of a shape: a point, box, circle, or polygon
*/
public enum Type {
POINT, BOX, CIRCLE, POLYGON;
}
//coordinates[0] = latitudes, coordinates[1] = longitudes
private final float[][] coordinates;
private Geoshape() {
coordinates = null;
}
private Geoshape(final float[][] coordinates) {
Preconditions.checkArgument(coordinates!=null && coordinates.length==2);
Preconditions.checkArgument(coordinates[0].length==coordinates[1].length && coordinates[0].length>0);
for (int i=0;i<coordinates[0].length;i++) {
if (Float.isNaN(coordinates[0][i])) Preconditions.checkArgument(i==1 && coordinates.length==2 && coordinates[1][i]>0);
else Preconditions.checkArgument(isValidCoordinate(coordinates[0][i],coordinates[1][i]));
}
this.coordinates=coordinates;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(coordinates[0]).append(coordinates[1]).toHashCode();
}
@Override
public boolean equals(Object other) {
if (this==other) return true;
else if (other==null) return false;
else if (!getClass().isInstance(other)) return false;
Geoshape oth = (Geoshape)other;
Preconditions.checkArgument(coordinates.length==2 && oth.coordinates.length==2);
for (int i=0;i<coordinates.length;i++) {
if (coordinates[i].length!=oth.coordinates[i].length) return false;
for (int j=0;j<coordinates[i].length;j++) {
if (Float.isNaN(coordinates[i][j]) && Float.isNaN(oth.coordinates[i][j])) continue;
if (coordinates[i][j]!=oth.coordinates[i][j]) return false;
}
}
return true;
}
@Override
public String toString() {
Type type = getType();
StringBuilder s = new StringBuilder();
s.append(type.toString().toLowerCase());
switch (type) {
case POINT:
s.append(getPoint().toString());
break;
case CIRCLE:
s.append(getPoint().toString()).append(":").append(getRadius());
break;
default:
s.append("[");
for (int i=0;i<size();i++) {
if (i>0) s.append(",");
s.append(getPoint(i));
}
s.append("]");
}
return s.toString();
}
/**
* Returns the {@link Type} of this geoshape.
*
* @return
*/
public Type getType() {
if (coordinates[0].length==1) return Type.POINT;
else if (coordinates[0].length>2) return Type.POLYGON;
else { //coordinates[0].length==2
if (Float.isNaN(coordinates[0][1])) return Type.CIRCLE;
else return Type.BOX;
}
}
/**
* Returns the number of points comprising this geoshape. A point and circle have only one point (center of cricle),
* a box has two points (the south-west and north-east corners) and a polygon has a variable number of points (>=3).
*
* @return
*/
public int size() {
switch(getType()) {
case POINT: return 1;
case CIRCLE: return 1;
case BOX: return 2;
case POLYGON: return coordinates[0].length;
default: throw new IllegalStateException("Unrecognized type: " + getType());
}
}
/**
* Returns the point at the given position. The position must be smaller than {@link #size()}.
*
* @param position
* @return
*/
public Point getPoint(int position) {
if (position<0 || position>=size()) throw new ArrayIndexOutOfBoundsException("Invalid position: " + position);
return new Point(coordinates[0][position],coordinates[1][position]);
}
/**
* Returns the singleton point of this shape. Only applicable for point and circle shapes.
*
* @return
*/
public Point getPoint() {
Preconditions.checkArgument(size()==1,"Shape does not have a single point");
return getPoint(0);
}
/**
* Returns the radius in kilometers of this circle. Only applicable to circle shapes.
* @return
*/
public float getRadius() {
Preconditions.checkArgument(getType()==Type.CIRCLE,"This shape is not a circle");
return coordinates[1][1];
}
private SpatialRelation getSpatialRelation(Geoshape other) {
Preconditions.checkNotNull(other);
return convert2Spatial4j().relate(other.convert2Spatial4j());
}
public boolean intersect(Geoshape other) {
SpatialRelation r = getSpatialRelation(other);
return r==SpatialRelation.INTERSECTS || r==SpatialRelation.CONTAINS || r==SpatialRelation.WITHIN;
}
public boolean within(Geoshape outer) {
return getSpatialRelation(outer)==SpatialRelation.WITHIN;
}
public boolean disjoint(Geoshape other) {
return getSpatialRelation(other)==SpatialRelation.DISJOINT;
}
/**
* Converts this shape into its equivalent Spatial4j {@link Shape}.
* @return
*/
public Shape convert2Spatial4j() {
switch(getType()) {
case POINT: return getPoint().getSpatial4jPoint();
case CIRCLE: return CTX.makeCircle(getPoint(0).getSpatial4jPoint(), DistanceUtils.dist2Degrees(getRadius(), DistanceUtils.EARTH_MEAN_RADIUS_KM));
case BOX: return CTX.makeRectangle(getPoint(0).getSpatial4jPoint(),getPoint(1).getSpatial4jPoint());
case POLYGON: throw new UnsupportedOperationException("Not yet supported");
default: throw new IllegalStateException("Unrecognized type: " + getType());
}
}
/**
* Constructs a point from its latitude and longitude information
* @param latitude
* @param longitude
* @return
*/
public static final Geoshape point(final float latitude, final float longitude) {
Preconditions.checkArgument(isValidCoordinate(latitude,longitude),"Invalid coordinate provided");
return new Geoshape(new float[][]{ new float[]{latitude}, new float[]{longitude}});
}
/**
* Constructs a point from its latitude and longitude information
* @param latitude
* @param longitude
* @return
*/
public static final Geoshape point(final double latitude, final double longitude) {
return point((float)latitude,(float)longitude);
}
/**
* Constructs a circle from a given center point and a radius in kilometer
* @param latitude
* @param longitude
* @param radiusInKM
* @return
*/
public static final Geoshape circle(final float latitude, final float longitude, final float radiusInKM) {
Preconditions.checkArgument(isValidCoordinate(latitude,longitude),"Invalid coordinate provided");
Preconditions.checkArgument(radiusInKM>0,"Invalid radius provided [%s]",radiusInKM);
return new Geoshape(new float[][]{ new float[]{latitude, Float.NaN}, new float[]{longitude, radiusInKM}});
}
/**
* Constructs a circle from a given center point and a radius in kilometer
* @param latitude
* @param longitude
* @param radiusInKM
* @return
*/
public static final Geoshape circle(final double latitude, final double longitude, final double radiusInKM) {
return circle((float)latitude,(float)longitude,(float)radiusInKM);
}
/**
* Constructs a new box shape which is identified by its south-west and north-east corner points
* @param southWestLatitude
* @param southWestLongitude
* @param northEastLatitude
* @param northEastLongitude
* @return
*/
public static final Geoshape box(final float southWestLatitude, final float southWestLongitude,
final float northEastLatitude, final float northEastLongitude) {
Preconditions.checkArgument(isValidCoordinate(southWestLatitude,southWestLongitude),"Invalid south-west coordinate provided");
Preconditions.checkArgument(isValidCoordinate(northEastLatitude,northEastLongitude),"Invalid north-east coordinate provided");
return new Geoshape(new float[][]{ new float[]{southWestLatitude, northEastLatitude}, new float[]{southWestLongitude, northEastLongitude}});
}
/**
* Constructs a new box shape which is identified by its south-west and north-east corner points
* @param southWestLatitude
* @param southWestLongitude
* @param northEastLatitude
* @param northEastLongitude
* @return
*/
public static final Geoshape box(final double southWestLatitude, final double southWestLongitude,
final double northEastLatitude, final double northEastLongitude) {
return box((float)southWestLatitude,(float)southWestLongitude,(float)northEastLatitude,(float)northEastLongitude);
}
/**
* Whether the given coordinates mark a point on earth.
* @param latitude
* @param longitude
* @return
*/
public static final boolean isValidCoordinate(final float latitude, final float longitude) {
return latitude>=-90.0 && latitude<=90.0 && longitude>=-180.0 && longitude<=180.0;
}
/**
* A single point representation. A point is identified by its coordinate on the earth sphere using the spherical
* system of latitudes and longitudes.
*/
public static final class Point {
private final float longitude;
private final float latitude;
/**
* Constructs a point with the given latitude and longitude
* @param latitude Between -90 and 90 degrees
* @param longitude Between -180 and 180 degrees
*/
Point(float latitude, float longitude) {
this.longitude = longitude;
this.latitude = latitude;
}
/**
* Longitude of this point
* @return
*/
public float getLongitude() {
return longitude;
}
/**
* Latitude of this point
* @return
*/
public float getLatitude() {
return latitude;
}
private com.spatial4j.core.shape.Point getSpatial4jPoint() {
return CTX.makePoint(longitude,latitude);
}
/**
* Returns the distance to another point in kilometers
*
* @param other Point
* @return
*/
public double distance(Point other) {
return DistanceUtils.degrees2Dist(CTX.getDistCalc().distance(getSpatial4jPoint(),other.getSpatial4jPoint()),DistanceUtils.EARTH_MEAN_RADIUS_KM);
}
@Override
public String toString() {
return "["+latitude+","+longitude+"]";
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(latitude).append(longitude).toHashCode();
}
@Override
public boolean equals(Object other) {
if (this==other) return true;
else if (other==null) return false;
else if (!getClass().isInstance(other)) return false;
Point oth = (Point)other;
return latitude==oth.latitude && longitude==oth.longitude;
}
}
/**
* @author Matthias Broecheler ([email protected])
*/
public static class GeoshapeSerializer implements AttributeSerializer<Geoshape> {
@Override
public void verifyAttribute(Geoshape value) {
//All values of Geoshape are valid
}
@Override
public Geoshape convert(Object value) {
if (value.getClass().isArray() && (value.getClass().getComponentType().isPrimitive() ||
Number.class.isAssignableFrom(value.getClass().getComponentType())) ) {
Geoshape shape = null;
int len= Array.getLength(value);
double[] arr = new double[len];
for (int i=0;i<len;i++) arr[i]=((Number)Array.get(value,i)).doubleValue();
if (len==2) shape= point(arr[0],arr[1]);
else if (len==3) shape= circle(arr[0],arr[1],arr[2]);
else if (len==4) shape= box(arr[0],arr[1],arr[2],arr[3]);
else throw new IllegalArgumentException("Expected 2-4 coordinates to create Geoshape, but given: " + value);
return shape;
} else if (value instanceof String) {
String[] components=null;
for (String delimiter : new String[]{",",";"}) {
components = ((String)value).split(delimiter);
if (components.length>=2 && components.length<=4) break;
else components=null;
}
Preconditions.checkArgument(components!=null,"Could not parse coordinates from string: %s",value);
double[] coords = new double[components.length];
try {
for (int i=0;i<components.length;i++) {
coords[i]=Double.parseDouble(components[i]);
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Could not parse coordinates from string: " + value, e);
}
return convert(coords);
} else return null;
}
@Override
public Geoshape read(ScanBuffer buffer) {
long l = VariableLong.readPositive(buffer);
assert l>0 && l<Integer.MAX_VALUE;
int length = (int)l;
float[][] coordinates = new float[2][];
for (int i = 0; i < 2; i++) {
coordinates[i]=buffer.getFloats(length);
}
return new Geoshape(coordinates);
}
@Override
public void write(WriteBuffer buffer, Geoshape attribute) {
float[][] coordinates = attribute.coordinates;
assert (coordinates.length==2);
assert (coordinates[0].length==coordinates[1].length && coordinates[0].length>0);
int length = coordinates[0].length;
VariableLong.writePositive(buffer,length);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < length; j++) {
buffer.putFloat(coordinates[i][j]);
}
}
}
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geoshape.java
|
572 |
public interface Searchable<T extends Serializable> extends ValueAssignable<T> {
/**
* Whether or not this class contains searchable information
*
* @return Whether or not this class contains searchable information
*/
Boolean getSearchable();
/**
* Whether or not this class contains searchable information
*
* @param searchable Whether or not this class contains searchable information
*/
void setSearchable(Boolean searchable);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_value_Searchable.java
|
290 |
public class ORubyScriptFormatter implements OScriptFormatter {
public String getFunctionDefinition(final OFunction f) {
final StringBuilder fCode = new StringBuilder();
fCode.append("def ");
fCode.append(f.getName());
fCode.append('(');
int i = 0;
if (f.getParameters() != null)
for (String p : f.getParameters()) {
if (i++ > 0)
fCode.append(',');
fCode.append(p);
}
fCode.append(")\n");
final Scanner scanner = new Scanner(f.getCode());
try {
scanner.useDelimiter("\n").skip("\r");
while (scanner.hasNext()) {
fCode.append('\t');
fCode.append(scanner.next());
}
} finally {
scanner.close();
}
fCode.append("\nend\n");
return fCode.toString();
}
@Override
public String getFunctionInvoke(final OFunction iFunction, final Object[] iArgs) {
final StringBuilder code = new StringBuilder();
code.append(iFunction.getName());
code.append('(');
if (iArgs != null) {
int i = 0;
for (Object a : iArgs) {
if (i++ > 0)
code.append(',');
code.append(a);
}
}
code.append(");");
return code.toString();
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_script_formatter_ORubyScriptFormatter.java
|
524 |
public class FlushAction extends IndicesAction<FlushRequest, FlushResponse, FlushRequestBuilder> {
public static final FlushAction INSTANCE = new FlushAction();
public static final String NAME = "indices/flush";
private FlushAction() {
super(NAME);
}
@Override
public FlushResponse newResponse() {
return new FlushResponse();
}
@Override
public FlushRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new FlushRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_flush_FlushAction.java
|
670 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="BLC_CATEGORY")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationClass(friendlyName = "CategoryImpl_baseCategory")
@SQLDelete(sql="UPDATE BLC_CATEGORY SET ARCHIVED = 'Y' WHERE CATEGORY_ID = ?")
public class CategoryImpl implements Category, Status, AdminMainEntity {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(CategoryImpl.class);
private static String buildLink(Category category, boolean ignoreTopLevel) {
Category myCategory = category;
StringBuilder linkBuffer = new StringBuilder(50);
while (myCategory != null) {
if (!ignoreTopLevel || myCategory.getDefaultParentCategory() != null) {
if (linkBuffer.length() == 0) {
linkBuffer.append(myCategory.getUrlKey());
} else if(myCategory.getUrlKey() != null && !"/".equals(myCategory.getUrlKey())){
linkBuffer.insert(0, myCategory.getUrlKey() + '/');
}
}
myCategory = myCategory.getDefaultParentCategory();
}
return linkBuffer.toString();
}
private static void fillInURLMapForCategory(Map<String, List<Long>> categoryUrlMap, Category category, String startingPath, List<Long> startingCategoryList) throws CacheFactoryException {
String urlKey = category.getUrlKey();
if (urlKey == null) {
throw new CacheFactoryException("Cannot create childCategoryURLMap - the urlKey for a category("+category.getId()+") was null");
}
String currentPath = "";
if (! "/".equals(category.getUrlKey())) {
currentPath = startingPath + "/" + category.getUrlKey();
}
List<Long> newCategoryList = new ArrayList<Long>(startingCategoryList);
newCategoryList.add(category.getId());
categoryUrlMap.put(currentPath, newCategoryList);
for (CategoryXref currentCategory : category.getChildCategoryXrefs()) {
fillInURLMapForCategory(categoryUrlMap, currentCategory.getSubCategory(), currentPath, newCategoryList);
}
}
@Id
@GeneratedValue(generator= "CategoryId")
@GenericGenerator(
name="CategoryId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="CategoryImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.CategoryImpl")
}
)
@Column(name = "CATEGORY_ID")
@AdminPresentation(friendlyName = "CategoryImpl_Category_ID", visibility = VisibilityEnum.HIDDEN_ALL)
protected Long id;
@Column(name = "NAME", nullable=false)
@Index(name="CATEGORY_NAME_INDEX", columnNames={"NAME"})
@AdminPresentation(friendlyName = "CategoryImpl_Category_Name", order = 1000,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
prominent = true, gridOrder = 1, columnWidth = "300px",
translatable = true)
protected String name;
@Column(name = "URL")
@AdminPresentation(friendlyName = "CategoryImpl_Category_Url", order = 2000,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
prominent = true, gridOrder = 2, columnWidth = "300px",
validationConfigurations = { @ValidationConfiguration(validationImplementation = "blUriPropertyValidator") })
@Index(name="CATEGORY_URL_INDEX", columnNames={"URL"})
protected String url;
@Column(name = "URL_KEY")
@Index(name="CATEGORY_URLKEY_INDEX", columnNames={"URL_KEY"})
@AdminPresentation(friendlyName = "CategoryImpl_Category_Url_Key",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced,
excluded = true)
protected String urlKey;
@Column(name = "DESCRIPTION")
@AdminPresentation(friendlyName = "CategoryImpl_Category_Description",
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
largeEntry = true,
excluded = true,
translatable = true)
protected String description;
@Column(name = "TAX_CODE")
protected String taxCode;
@Column(name = "ACTIVE_START_DATE")
@AdminPresentation(friendlyName = "CategoryImpl_Category_Active_Start_Date", order = 1000,
group = Presentation.Group.Name.ActiveDateRange, groupOrder = Presentation.Group.Order.ActiveDateRange)
protected Date activeStartDate;
@Column(name = "ACTIVE_END_DATE")
@AdminPresentation(friendlyName = "CategoryImpl_Category_Active_End_Date", order = 2000,
group = Presentation.Group.Name.ActiveDateRange, groupOrder = Presentation.Group.Order.ActiveDateRange)
protected Date activeEndDate;
@Column(name = "DISPLAY_TEMPLATE")
@AdminPresentation(friendlyName = "CategoryImpl_Category_Display_Template", order = 1000,
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected String displayTemplate;
@Lob
@Type(type = "org.hibernate.type.StringClobType")
@Column(name = "LONG_DESCRIPTION", length = Integer.MAX_VALUE - 1)
@AdminPresentation(friendlyName = "CategoryImpl_Category_Long_Description", order = 3000,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
largeEntry = true,
fieldType = SupportedFieldType.HTML_BASIC,
translatable = true)
protected String longDescription;
@ManyToOne(targetEntity = CategoryImpl.class)
@JoinColumn(name = "DEFAULT_PARENT_CATEGORY_ID")
@Index(name="CATEGORY_PARENT_INDEX", columnNames={"DEFAULT_PARENT_CATEGORY_ID"})
@AdminPresentation(friendlyName = "CategoryImpl_defaultParentCategory", order = 4000,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General)
@AdminPresentationToOneLookup()
protected Category defaultParentCategory;
@OneToMany(targetEntity = CategoryXrefImpl.class, mappedBy = "categoryXrefPK.category")
@Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST})
@OrderBy(value="displayOrder")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationAdornedTargetCollection(
targetObjectProperty = "categoryXrefPK.subCategory",
parentObjectProperty = "categoryXrefPK.category",
friendlyName = "allChildCategoriesTitle",
sortProperty = "displayOrder",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
gridVisibleFields = { "name" })
protected List<CategoryXref> allChildCategoryXrefs = new ArrayList<CategoryXref>(10);
@OneToMany(targetEntity = CategoryXrefImpl.class, mappedBy = "categoryXrefPK.subCategory")
@Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST})
@OrderBy(value="displayOrder")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationAdornedTargetCollection(
targetObjectProperty = "categoryXrefPK.category",
parentObjectProperty = "categoryXrefPK.subCategory",
friendlyName = "allParentCategoriesTitle",
sortProperty = "displayOrder",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
gridVisibleFields = { "name" })
protected List<CategoryXref> allParentCategoryXrefs = new ArrayList<CategoryXref>(10);
@OneToMany(targetEntity = CategoryProductXrefImpl.class, mappedBy = "categoryProductXref.category")
@Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST})
@OrderBy(value="displayOrder")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationAdornedTargetCollection(
targetObjectProperty = "categoryProductXref.product",
parentObjectProperty = "categoryProductXref.category",
friendlyName = "allProductsTitle",
sortProperty = "displayOrder",
tab = Presentation.Tab.Name.Products, tabOrder = Presentation.Tab.Order.Products,
gridVisibleFields = { "defaultSku.name" })
protected List<CategoryProductXref> allProductXrefs = new ArrayList<CategoryProductXref>(10);
@ElementCollection
@MapKeyColumn(name="NAME")
@Column(name="URL")
@CollectionTable(name="BLC_CATEGORY_IMAGE", joinColumns=@JoinColumn(name="CATEGORY_ID"))
@BatchSize(size = 50)
@Deprecated
protected Map<String, String> categoryImages = new HashMap<String, String>(10);
@ManyToMany(targetEntity = MediaImpl.class)
@JoinTable(name = "BLC_CATEGORY_MEDIA_MAP", inverseJoinColumns = @JoinColumn(name = "MEDIA_ID", referencedColumnName = "MEDIA_ID"))
@MapKeyColumn(name = "MAP_KEY")
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationMap(
friendlyName = "SkuImpl_Sku_Media",
tab = Presentation.Tab.Name.Media, tabOrder = Presentation.Tab.Order.Media,
keyPropertyFriendlyName = "SkuImpl_Sku_Media_Key",
deleteEntityUponRemove = true,
mediaField = "url",
keys = {
@AdminPresentationMapKey(keyName = "primary", friendlyKeyName = "mediaPrimary"),
@AdminPresentationMapKey(keyName = "alt1", friendlyKeyName = "mediaAlternate1"),
@AdminPresentationMapKey(keyName = "alt2", friendlyKeyName = "mediaAlternate2"),
@AdminPresentationMapKey(keyName = "alt3", friendlyKeyName = "mediaAlternate3"),
@AdminPresentationMapKey(keyName = "alt4", friendlyKeyName = "mediaAlternate4"),
@AdminPresentationMapKey(keyName = "alt5", friendlyKeyName = "mediaAlternate5"),
@AdminPresentationMapKey(keyName = "alt6", friendlyKeyName = "mediaAlternate6")
}
)
protected Map<String, Media> categoryMedia = new HashMap<String , Media>(10);
@OneToMany(mappedBy = "category", targetEntity = FeaturedProductImpl.class, cascade = {CascadeType.ALL})
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@OrderBy(value="sequence")
@BatchSize(size = 50)
@AdminPresentationAdornedTargetCollection(friendlyName = "featuredProductsTitle", order = 1000,
tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
targetObjectProperty = "product",
sortProperty = "sequence",
maintainedAdornedTargetFields = { "promotionMessage" },
gridVisibleFields = { "defaultSku.name", "promotionMessage" })
protected List<FeaturedProduct> featuredProducts = new ArrayList<FeaturedProduct>(10);
@OneToMany(mappedBy = "category", targetEntity = CrossSaleProductImpl.class, cascade = {CascadeType.ALL})
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@OrderBy(value="sequence")
@AdminPresentationAdornedTargetCollection(friendlyName = "crossSaleProductsTitle", order = 2000,
tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
targetObjectProperty = "relatedSaleProduct",
sortProperty = "sequence",
maintainedAdornedTargetFields = { "promotionMessage" },
gridVisibleFields = { "defaultSku.name", "promotionMessage" })
protected List<RelatedProduct> crossSaleProducts = new ArrayList<RelatedProduct>();
@OneToMany(mappedBy = "category", targetEntity = UpSaleProductImpl.class, cascade = {CascadeType.ALL})
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@OrderBy(value="sequence")
@AdminPresentationAdornedTargetCollection(friendlyName = "upsaleProductsTitle", order = 3000,
tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
targetObjectProperty = "relatedSaleProduct",
sortProperty = "sequence",
maintainedAdornedTargetFields = { "promotionMessage" },
gridVisibleFields = { "defaultSku.name", "promotionMessage" })
protected List<RelatedProduct> upSaleProducts = new ArrayList<RelatedProduct>();
@OneToMany(mappedBy = "category", targetEntity = CategorySearchFacetImpl.class, cascade = {CascadeType.ALL})
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@OrderBy(value="sequence")
@AdminPresentationAdornedTargetCollection(friendlyName = "categoryFacetsTitle", order = 1000,
tab = Presentation.Tab.Name.SearchFacets, tabOrder = Presentation.Tab.Order.SearchFacets,
targetObjectProperty = "searchFacet",
sortProperty = "sequence",
gridVisibleFields = { "field", "label", "searchDisplayPriority" })
protected List<CategorySearchFacet> searchFacets = new ArrayList<CategorySearchFacet>();
@ManyToMany(targetEntity = SearchFacetImpl.class)
@JoinTable(name = "BLC_CAT_SEARCH_FACET_EXCL_XREF", joinColumns = @JoinColumn(name = "CATEGORY_ID"),
inverseJoinColumns = @JoinColumn(name = "SEARCH_FACET_ID", nullable = true))
@Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationAdornedTargetCollection(
order = 2000,
joinEntityClass = "org.broadleafcommerce.core.search.domain.CategoryExcludedSearchFacetImpl",
targetObjectProperty = "searchFacet",
parentObjectProperty = "category",
friendlyName = "excludedFacetsTitle",
tab = Presentation.Tab.Name.SearchFacets, tabOrder = Presentation.Tab.Order.SearchFacets,
gridVisibleFields = {"field", "label", "searchDisplayPriority"})
protected List<SearchFacet> excludedSearchFacets = new ArrayList<SearchFacet>(10);
@OneToMany(mappedBy = "category", targetEntity = CategoryAttributeImpl.class, cascade = {CascadeType.ALL}, orphanRemoval = true)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@MapKey(name="name")
@BatchSize(size = 50)
@AdminPresentationMap(friendlyName = "categoryAttributesTitle",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "ProductAttributeImpl_Attribute_Name"
)
protected Map<String, CategoryAttribute> categoryAttributes = new HashMap<String, CategoryAttribute>();
@Column(name = "INVENTORY_TYPE")
@AdminPresentation(friendlyName = "CategoryImpl_Category_InventoryType", order = 2000,
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.core.inventory.service.type.InventoryType")
protected String inventoryType;
@Column(name = "FULFILLMENT_TYPE")
@AdminPresentation(friendlyName = "CategoryImpl_Category_FulfillmentType", order = 3000,
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced,
fieldType = SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration = "org.broadleafcommerce.core.order.service.type.FulfillmentType")
protected String fulfillmentType;
@Embedded
protected ArchiveStatus archiveStatus = new ArchiveStatus();
@Transient
@Hydrated(factoryMethod = "createChildCategoryURLMap")
@Deprecated
protected Map<String, List<Long>> childCategoryURLMap;
@Transient
@Hydrated(factoryMethod = "createChildCategoryIds")
protected List<Long> childCategoryIds;
@Transient
protected List<CategoryXref> childCategoryXrefs = new ArrayList<CategoryXref>(50);
@Transient
protected List<Category> legacyChildCategories = new ArrayList<Category>(50);
@Transient
protected List<Category> allLegacyChildCategories = new ArrayList<Category>(50);
@Transient
protected List<FeaturedProduct> filteredFeaturedProducts = null;
@Transient
protected List<RelatedProduct> filteredCrossSales = null;
@Transient
protected List<RelatedProduct> filteredUpSales = null;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getName() {
return DynamicTranslationProvider.getValue(this, "name", name);
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getUrl() {
// TODO: if null return
// if blank return
// if startswith "/" return
// if contains a ":" and no "?" or (contains a ":" before a "?") return
// else "add a /" at the beginning
if(url == null || url.equals("") || url.startsWith("/")) {
return url;
} else if ((url.contains(":") && !url.contains("?")) || url.indexOf('?', url.indexOf(':')) != -1) {
return url;
} else {
return "/" + url;
}
}
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public String getUrlKey() {
if ((urlKey == null || "".equals(urlKey.trim())) && name != null) {
return UrlUtil.generateUrlKey(name);
}
return urlKey;
}
@Override
public String getGeneratedUrl() {
return buildLink(this, false);
}
@Override
public void setUrlKey(String urlKey) {
this.urlKey = urlKey;
}
@Override
public String getDescription() {
return DynamicTranslationProvider.getValue(this, "description", description);
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public Date getActiveStartDate() {
if ('Y'==getArchived()) {
return null;
}
return activeStartDate;
}
@Override
public void setActiveStartDate(Date activeStartDate) {
this.activeStartDate = (activeStartDate == null) ? null : new Date(activeStartDate.getTime());
}
@Override
public Date getActiveEndDate() {
return activeEndDate;
}
@Override
public void setActiveEndDate(Date activeEndDate) {
this.activeEndDate = (activeEndDate == null) ? null : new Date(activeEndDate.getTime());
}
@Override
public boolean isActive() {
if (LOG.isDebugEnabled()) {
if (!DateUtil.isActive(activeStartDate, activeEndDate, true)) {
LOG.debug("category, " + id + ", inactive due to date");
}
if ('Y'==getArchived()) {
LOG.debug("category, " + id + ", inactive due to archived status");
}
}
return DateUtil.isActive(activeStartDate, activeEndDate, true) && 'Y'!=getArchived();
}
@Override
public String getDisplayTemplate() {
return displayTemplate;
}
@Override
public void setDisplayTemplate(String displayTemplate) {
this.displayTemplate = displayTemplate;
}
@Override
public String getLongDescription() {
return DynamicTranslationProvider.getValue(this, "longDescription", longDescription);
}
@Override
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
@Override
public Category getDefaultParentCategory() {
return defaultParentCategory;
}
@Override
public void setDefaultParentCategory(Category defaultParentCategory) {
this.defaultParentCategory = defaultParentCategory;
}
@Override
public List<CategoryXref> getAllChildCategoryXrefs(){
return allChildCategoryXrefs;
}
@Override
public List<CategoryXref> getChildCategoryXrefs() {
if (childCategoryXrefs.isEmpty()) {
for (CategoryXref category : allChildCategoryXrefs) {
if (category.getSubCategory().isActive()) {
childCategoryXrefs.add(category);
}
}
}
return Collections.unmodifiableList(childCategoryXrefs);
}
@Override
public void setChildCategoryXrefs(List<CategoryXref> childCategories) {
this.childCategoryXrefs.clear();
for(CategoryXref category : childCategories){
this.childCategoryXrefs.add(category);
}
}
@Override
public void setAllChildCategoryXrefs(List<CategoryXref> childCategories){
allChildCategoryXrefs.clear();
for(CategoryXref category : childCategories){
allChildCategoryXrefs.add(category);
}
}
@Override
@Deprecated
public List<Category> getAllChildCategories(){
if (allLegacyChildCategories.isEmpty()) {
for (CategoryXref category : allChildCategoryXrefs) {
allLegacyChildCategories.add(category.getSubCategory());
}
}
return Collections.unmodifiableList(allLegacyChildCategories);
}
@Override
public boolean hasAllChildCategories(){
return !allChildCategoryXrefs.isEmpty();
}
@Override
@Deprecated
public void setAllChildCategories(List<Category> childCategories){
throw new UnsupportedOperationException("Not Supported - Use setAllChildCategoryXrefs()");
}
@Override
@Deprecated
public List<Category> getChildCategories() {
if (legacyChildCategories.isEmpty()) {
for (CategoryXref category : allChildCategoryXrefs) {
if (category.getSubCategory().isActive()) {
legacyChildCategories.add(category.getSubCategory());
}
}
}
return Collections.unmodifiableList(legacyChildCategories);
}
@Override
public boolean hasChildCategories() {
return !getChildCategoryXrefs().isEmpty();
}
@Override
@Deprecated
public void setChildCategories(List<Category> childCategories) {
throw new UnsupportedOperationException("Not Supported - Use setChildCategoryXrefs()");
}
@Override
public List<Long> getChildCategoryIds() {
if (childCategoryIds == null) {
HydratedSetup.populateFromCache(this, "childCategoryIds");
}
return childCategoryIds;
}
@Override
public void setChildCategoryIds(List<Long> childCategoryIds) {
this.childCategoryIds = childCategoryIds;
}
public List<Long> createChildCategoryIds() {
childCategoryIds = new ArrayList<Long>();
for (CategoryXref category : allChildCategoryXrefs) {
if (category.getSubCategory().isActive()) {
childCategoryIds.add(category.getSubCategory().getId());
}
}
return childCategoryIds;
}
@Override
@Deprecated
public Map<String, String> getCategoryImages() {
return categoryImages;
}
@Override
@Deprecated
public String getCategoryImage(String imageKey) {
return categoryImages.get(imageKey);
}
@Override
@Deprecated
public void setCategoryImages(Map<String, String> categoryImages) {
this.categoryImages.clear();
for(Map.Entry<String, String> me : categoryImages.entrySet()) {
this.categoryImages.put(me.getKey(), me.getValue());
}
}
@Override
@Deprecated
public Map<String, List<Long>> getChildCategoryURLMap() {
if (childCategoryURLMap == null) {
HydratedSetup.populateFromCache(this, "childCategoryURLMap");
}
return childCategoryURLMap;
}
public Map<String, List<Long>> createChildCategoryURLMap() {
try {
Map<String, List<Long>> newMap = new HashMap<String, List<Long>>(50);
fillInURLMapForCategory(newMap, this, "", new ArrayList<Long>(10));
return newMap;
} catch (CacheFactoryException e) {
throw new RuntimeException(e);
}
}
@Override
@Deprecated
public void setChildCategoryURLMap(Map<String, List<Long>> childCategoryURLMap) {
this.childCategoryURLMap = childCategoryURLMap;
}
@Override
public List<Category> buildFullCategoryHierarchy(List<Category> currentHierarchy) {
if (currentHierarchy == null) {
currentHierarchy = new ArrayList<Category>();
currentHierarchy.add(this);
}
List<Category> myParentCategories = new ArrayList<Category>();
if (defaultParentCategory != null) {
myParentCategories.add(defaultParentCategory);
}
if (allParentCategoryXrefs != null && allParentCategoryXrefs.size() > 0) {
for (CategoryXref parent : allParentCategoryXrefs) {
myParentCategories.add(parent.getCategory());
}
}
for (Category category : myParentCategories) {
if (!currentHierarchy.contains(category)) {
currentHierarchy.add(category);
category.buildFullCategoryHierarchy(currentHierarchy);
}
}
return currentHierarchy;
}
@Override
public List<Category> buildCategoryHierarchy(List<Category> currentHierarchy) {
if (currentHierarchy == null) {
currentHierarchy = new ArrayList<Category>();
currentHierarchy.add(this);
}
if (defaultParentCategory != null && ! currentHierarchy.contains(defaultParentCategory)) {
currentHierarchy.add(defaultParentCategory);
defaultParentCategory.buildCategoryHierarchy(currentHierarchy);
}
return currentHierarchy;
}
@Override
public List<CategoryXref> getAllParentCategoryXrefs() {
return allParentCategoryXrefs;
}
@Override
public void setAllParentCategoryXrefs(List<CategoryXref> allParentCategories) {
this.allParentCategoryXrefs.clear();
allParentCategoryXrefs.addAll(allParentCategories);
}
@Override
@Deprecated
public List<Category> getAllParentCategories() {
List<Category> parents = new ArrayList<Category>(allParentCategoryXrefs.size());
for (CategoryXref xref : allParentCategoryXrefs) {
parents.add(xref.getCategory());
}
return Collections.unmodifiableList(parents);
}
@Override
@Deprecated
public void setAllParentCategories(List<Category> allParentCategories) {
throw new UnsupportedOperationException("Not Supported - Use setAllParentCategoryXrefs()");
}
@Override
public List<FeaturedProduct> getFeaturedProducts() {
if (filteredFeaturedProducts == null && featuredProducts != null) {
filteredFeaturedProducts = new ArrayList<FeaturedProduct>(featuredProducts.size());
filteredFeaturedProducts.addAll(featuredProducts);
CollectionUtils.filter(filteredFeaturedProducts, new Predicate() {
@Override
public boolean evaluate(Object arg) {
return 'Y' != ((Status) ((FeaturedProduct) arg).getProduct()).getArchived();
}
});
}
return filteredFeaturedProducts;
}
@Override
public void setFeaturedProducts(List<FeaturedProduct> featuredProducts) {
this.featuredProducts.clear();
for(FeaturedProduct featuredProduct : featuredProducts){
this.featuredProducts.add(featuredProduct);
}
}
@Override
public List<RelatedProduct> getCrossSaleProducts() {
if (filteredCrossSales == null && crossSaleProducts != null) {
filteredCrossSales = new ArrayList<RelatedProduct>(crossSaleProducts.size());
filteredCrossSales.addAll(crossSaleProducts);
CollectionUtils.filter(filteredCrossSales, new Predicate() {
@Override
public boolean evaluate(Object arg) {
return 'Y'!=((Status)((CrossSaleProductImpl) arg).getRelatedProduct()).getArchived();
}
});
}
return filteredCrossSales;
}
@Override
public void setCrossSaleProducts(List<RelatedProduct> crossSaleProducts) {
this.crossSaleProducts.clear();
for(RelatedProduct relatedProduct : crossSaleProducts){
this.crossSaleProducts.add(relatedProduct);
}
}
@Override
public List<RelatedProduct> getUpSaleProducts() {
if (filteredUpSales == null && upSaleProducts != null) {
filteredUpSales = new ArrayList<RelatedProduct>(upSaleProducts.size());
filteredUpSales.addAll(upSaleProducts);
CollectionUtils.filter(filteredUpSales, new Predicate() {
@Override
public boolean evaluate(Object arg) {
return 'Y'!=((Status)((UpSaleProductImpl) arg).getRelatedProduct()).getArchived();
}
});
}
return filteredUpSales;
}
@Override
public List<RelatedProduct> getCumulativeCrossSaleProducts() {
Set<RelatedProduct> returnProductsSet = new LinkedHashSet<RelatedProduct>();
List<Category> categoryHierarchy = buildCategoryHierarchy(null);
for (Category category : categoryHierarchy) {
returnProductsSet.addAll(category.getCrossSaleProducts());
}
return new ArrayList<RelatedProduct>(returnProductsSet);
}
@Override
public List<RelatedProduct> getCumulativeUpSaleProducts() {
Set<RelatedProduct> returnProductsSet = new LinkedHashSet<RelatedProduct>();
List<Category> categoryHierarchy = buildCategoryHierarchy(null);
for (Category category : categoryHierarchy) {
returnProductsSet.addAll(category.getUpSaleProducts());
}
return new ArrayList<RelatedProduct>(returnProductsSet);
}
@Override
public List<FeaturedProduct> getCumulativeFeaturedProducts() {
Set<FeaturedProduct> returnProductsSet = new LinkedHashSet<FeaturedProduct>();
List<Category> categoryHierarchy = buildCategoryHierarchy(null);
for (Category category : categoryHierarchy) {
returnProductsSet.addAll(category.getFeaturedProducts());
}
return new ArrayList<FeaturedProduct>(returnProductsSet);
}
@Override
public void setUpSaleProducts(List<RelatedProduct> upSaleProducts) {
this.upSaleProducts.clear();
for(RelatedProduct relatedProduct : upSaleProducts){
this.upSaleProducts.add(relatedProduct);
}
this.upSaleProducts = upSaleProducts;
}
@Override
public List<CategoryProductXref> getActiveProductXrefs() {
List<CategoryProductXref> result = new ArrayList<CategoryProductXref>();
for (CategoryProductXref product : allProductXrefs) {
if (product.getProduct().isActive()) {
result.add(product);
}
}
return Collections.unmodifiableList(result);
}
@Override
public List<CategoryProductXref> getAllProductXrefs() {
return allProductXrefs;
}
@Override
public void setAllProductXrefs(List<CategoryProductXref> allProducts) {
this.allProductXrefs.clear();
allProductXrefs.addAll(allProducts);
}
@Override
@Deprecated
public List<Product> getActiveProducts() {
List<Product> result = new ArrayList<Product>();
for (CategoryProductXref product : allProductXrefs) {
if (product.getProduct().isActive()) {
result.add(product.getProduct());
}
}
return Collections.unmodifiableList(result);
}
@Override
@Deprecated
public List<Product> getAllProducts() {
List<Product> result = new ArrayList<Product>();
for (CategoryProductXref product : allProductXrefs) {
result.add(product.getProduct());
}
return Collections.unmodifiableList(result);
}
@Override
@Deprecated
public void setAllProducts(List<Product> allProducts) {
throw new UnsupportedOperationException("Not Supported - Use setAllProductXrefs()");
}
@Override
public List<CategorySearchFacet> getSearchFacets() {
return searchFacets;
}
@Override
public void setSearchFacets(List<CategorySearchFacet> searchFacets) {
this.searchFacets = searchFacets;
}
@Override
public List<SearchFacet> getExcludedSearchFacets() {
return excludedSearchFacets;
}
@Override
public void setExcludedSearchFacets(List<SearchFacet> excludedSearchFacets) {
this.excludedSearchFacets = excludedSearchFacets;
}
@Override
public InventoryType getInventoryType() {
return InventoryType.getInstance(this.inventoryType);
}
@Override
public void setInventoryType(InventoryType inventoryType) {
this.inventoryType = inventoryType.getType();
}
@Override
public FulfillmentType getFulfillmentType() {
return FulfillmentType.getInstance(this.fulfillmentType);
}
@Override
public void setFulfillmentType(FulfillmentType fulfillmentType) {
this.fulfillmentType = fulfillmentType.getType();
}
@Override
public List<CategorySearchFacet> getCumulativeSearchFacets() {
final List<CategorySearchFacet> returnFacets = new ArrayList<CategorySearchFacet>();
returnFacets.addAll(getSearchFacets());
Collections.sort(returnFacets, facetPositionComparator);
// Add in parent facets unless they are excluded
List<CategorySearchFacet> parentFacets = null;
if (defaultParentCategory != null) {
parentFacets = defaultParentCategory.getCumulativeSearchFacets();
CollectionUtils.filter(parentFacets, new Predicate() {
@Override
public boolean evaluate(Object arg) {
CategorySearchFacet csf = (CategorySearchFacet) arg;
return !getExcludedSearchFacets().contains(csf.getSearchFacet()) && !returnFacets.contains(csf.getSearchFacet());
}
});
}
if (parentFacets != null) {
returnFacets.addAll(parentFacets);
}
return returnFacets;
}
@Override
public Map<String, Media> getCategoryMedia() {
return categoryMedia;
}
@Override
public void setCategoryMedia(Map<String, Media> categoryMedia) {
this.categoryMedia.clear();
for(Map.Entry<String, Media> me : categoryMedia.entrySet()) {
this.categoryMedia.put(me.getKey(), me.getValue());
}
}
@Override
public Map<String, CategoryAttribute> getCategoryAttributesMap() {
return categoryAttributes;
}
@Override
public void setCategoryAttributesMap(Map<String, CategoryAttribute> categoryAttributes) {
this.categoryAttributes = categoryAttributes;
}
@Override
public List<CategoryAttribute> getCategoryAttributes() {
List<CategoryAttribute> ca = new ArrayList<CategoryAttribute>(categoryAttributes.values());
return Collections.unmodifiableList(ca);
}
@Override
public void setCategoryAttributes(List<CategoryAttribute> categoryAttributes) {
this.categoryAttributes = new HashMap<String, CategoryAttribute>();
for (CategoryAttribute categoryAttribute : categoryAttributes) {
this.categoryAttributes.put(categoryAttribute.getName(), categoryAttribute);
}
}
@Override
public CategoryAttribute getCategoryAttributeByName(String name) {
for (CategoryAttribute attribute : getCategoryAttributes()) {
if (attribute.getName().equals(name)) {
return attribute;
}
}
return null;
}
@Override
public Map<String, CategoryAttribute> getMappedCategoryAttributes() {
Map<String, CategoryAttribute> map = new HashMap<String, CategoryAttribute>();
for (CategoryAttribute attr : getCategoryAttributes()) {
map.put(attr.getName(), attr);
}
return map;
}
@Override
public Character getArchived() {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
return archiveStatus.getArchived();
}
@Override
public void setArchived(Character archived) {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
archiveStatus.setArchived(archived);
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + (name == null ? 0 : name.hashCode());
result = prime * result + (url == null ? 0 : url.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;
}
CategoryImpl other = (CategoryImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (url == null) {
if (other.url != null) {
return false;
}
} else if (!url.equals(other.url)) {
return false;
}
return true;
}
protected static Comparator<CategorySearchFacet> facetPositionComparator = new Comparator<CategorySearchFacet>() {
@Override
public int compare(CategorySearchFacet o1, CategorySearchFacet o2) {
return o1.getSequence().compareTo(o2.getSequence());
}
};
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Marketing = "CategoryImpl_Marketing_Tab";
public static final String Media = "CategoryImpl_Media_Tab";
public static final String Advanced = "CategoryImpl_Advanced_Tab";
public static final String Products = "CategoryImpl_Products_Tab";
public static final String SearchFacets = "CategoryImpl_categoryFacetsTab";
}
public static class Order {
public static final int Marketing = 2000;
public static final int Media = 3000;
public static final int Advanced = 4000;
public static final int Products = 5000;
public static final int SearchFacets = 3500;
}
}
public static class Group {
public static class Name {
public static final String General = "CategoryImpl_Category_Description";
public static final String ActiveDateRange = "CategoryImpl_Active_Date_Range";
public static final String Advanced = "CategoryImpl_Advanced";
}
public static class Order {
public static final int General = 1000;
public static final int ActiveDateRange = 2000;
public static final int Advanced = 1000;
}
}
}
@Override
public String getMainEntityName() {
return getName();
}
@Override
public String getTaxCode() {
return this.taxCode;
}
@Override
public void setTaxCode(String taxCode) {
this.taxCode = taxCode;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryImpl.java
|
151 |
class ObjectClassDefinitionGenerator extends DefinitionGenerator {
private final String brokenName;
private final MemberOrTypeExpression node;
private final CompilationUnit rootNode;
private final String desc;
private final Image image;
private final ProducedType returnType;
private final LinkedHashMap<String, ProducedType> parameters;
@Override
String getBrokenName() {
return brokenName;
}
@Override
ProducedType getReturnType() {
return returnType;
}
@Override
LinkedHashMap<String, ProducedType> getParameters() {
return parameters;
}
@Override
String getDescription() {
return desc;
}
@Override
Image getImage() {
return image;
}
@Override
Tree.CompilationUnit getRootNode() {
return rootNode;
}
@Override
Node getNode() {
return node;
}
private ObjectClassDefinitionGenerator(String brokenName,
Tree.MemberOrTypeExpression node,
Tree.CompilationUnit rootNode,
String desc,
Image image,
ProducedType returnType,
LinkedHashMap<String, ProducedType> paramTypes) {
this.brokenName = brokenName;
this.node = node;
this.rootNode = rootNode;
this.desc = desc;
this.image = image;
this.returnType = returnType;
this.parameters = paramTypes;
}
String generateShared(String indent, String delim) {
return "shared " + generate(indent, delim);
}
String generate(String indent, String delim) {
StringBuffer def = new StringBuffer();
boolean isUpperCase =
Character.isUpperCase(brokenName.charAt(0));
boolean isVoid = returnType==null;
if (isUpperCase && parameters!=null) {
List<TypeParameter> typeParams = new ArrayList<TypeParameter>();
StringBuilder typeParamDef = new StringBuilder();
StringBuilder typeParamConstDef = new StringBuilder();
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, returnType);
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, parameters.values());
if (typeParamDef.length() > 0) {
typeParamDef.insert(0, "<");
typeParamDef.setLength(typeParamDef.length() - 1);
typeParamDef.append(">");
}
String defIndent = getDefaultIndent();
String supertype = isVoid ?
null : supertypeDeclaration(returnType);
def.append("class ").append(brokenName).append(typeParamDef);
appendParameters(parameters, def);
if (supertype!=null) {
def.append(delim).append(indent).append(defIndent).append(defIndent)
.append(supertype);
}
def.append(typeParamConstDef);
def.append(" {").append(delim);
if (!isVoid) {
appendMembers(indent, delim, def, defIndent);
}
def.append(indent).append("}");
}
else if (!isUpperCase && parameters==null) {
String defIndent = getDefaultIndent();
String supertype = isVoid ?
null : supertypeDeclaration(returnType);
def.append("object ").append(brokenName);
if (supertype!=null) {
def.append(delim).append(indent).append(defIndent).append(defIndent)
.append(supertype);
}
def.append(" {").append(delim);
if (!isVoid) {
appendMembers(indent, delim, def, defIndent);
}
def.append(indent).append("}");
}
else {
return null;
}
return def.toString();
}
Set<Declaration> getImports() {
Set<Declaration> imports = new HashSet<Declaration>();
importType(imports, returnType, rootNode);
if (parameters!=null) {
importTypes(imports, parameters.values(), rootNode);
}
if (returnType!=null) {
importMembers(imports);
}
return imports;
}
private void importMembers(Set<Declaration> imports) {
//TODO: this is a major copy/paste from appendMembers() below
TypeDeclaration td = getDefaultedSupertype();
Set<String> ambiguousNames = new HashSet<String>();
Collection<DeclarationWithProximity> members =
td.getMatchingMemberDeclarations(rootNode.getUnit(),
null, "", 0).values();
for (DeclarationWithProximity dwp: members) {
Declaration dec = dwp.getDeclaration();
for (Declaration d: overloads(dec)) {
if (d.isFormal() /*&& td.isInheritedFromSupertype(d)*/) {
importSignatureTypes(d, rootNode, imports);
ambiguousNames.add(d.getName());
}
}
}
for (TypeDeclaration superType: td.getSupertypeDeclarations()) {
for (Declaration m: superType.getMembers()) {
if (m.isShared()) {
Declaration r = td.getMember(m.getName(), null, false);
if (r==null ||
!r.refines(m) &&
// !r.getContainer().equals(ut) &&
!ambiguousNames.add(m.getName())) {
importSignatureTypes(m, rootNode, imports);
}
}
}
}
}
private void appendMembers(String indent, String delim, StringBuffer def,
String defIndent) {
TypeDeclaration td = getDefaultedSupertype();
Set<String> ambiguousNames = new HashSet<String>();
Collection<DeclarationWithProximity> members =
td.getMatchingMemberDeclarations(rootNode.getUnit(),
null, "", 0).values();
for (DeclarationWithProximity dwp: members) {
Declaration dec = dwp.getDeclaration();
for (Declaration d: overloads(dec)) {
if (d.isFormal() /*&& td.isInheritedFromSupertype(d)*/) {
if (ambiguousNames.add(d.getName())) {
appendRefinementText(indent, delim, def,
defIndent, d);
}
}
}
}
for (TypeDeclaration superType: td.getSupertypeDeclarations()) {
for (Declaration m: superType.getMembers()) {
if (m.isShared()) {
Declaration r = td.getMember(m.getName(), null, false);
if ((r==null ||
!r.refines(m)) &&
// !r.getContainer().equals(ut)) &&
ambiguousNames.add(m.getName())) {
appendRefinementText(indent, delim, def,
defIndent, m);
}
}
}
}
}
private TypeDeclaration getDefaultedSupertype() {
if (isNotBasic(returnType)) {
return returnType.getDeclaration();
}
else {
Unit unit = rootNode.getUnit();
return intersectionType(returnType,
unit.getBasicDeclaration().getType(),
unit).getDeclaration();
}
}
private void appendRefinementText(String indent, String delim,
StringBuffer def, String defIndent, Declaration d) {
ProducedReference pr =
getRefinedProducedReference(returnType, d);
String text = getRefinementTextFor(d, pr, node.getUnit(),
false, null, "", false);
def.append(indent).append(defIndent).append(text).append(delim);
}
static ObjectClassDefinitionGenerator create(String brokenName,
Tree.MemberOrTypeExpression node,
Tree.CompilationUnit rootNode) {
boolean isUpperCase = Character.isUpperCase(brokenName.charAt(0));
FindArgumentsVisitor fav = new FindArgumentsVisitor(node);
rootNode.visit(fav);
Unit unit = node.getUnit();
ProducedType returnType = unit.denotableType(fav.expectedType);
StringBuilder params = new StringBuilder();
LinkedHashMap<String, ProducedType> paramTypes = getParameters(fav);
if (returnType!=null) {
if(unit.isOptionalType(returnType)){
returnType = returnType.eliminateNull();
}
TypeDeclaration rtd = returnType.getDeclaration();
if ( (rtd instanceof Class) && (
rtd.equals(unit.getObjectDeclaration()) ||
rtd.equals(unit.getAnythingDeclaration()))
) {
returnType = null;
}
}
if (!isValidSupertype(returnType)) {
return null;
}
if (paramTypes!=null && isUpperCase) {
String supertype = supertypeDeclaration(returnType);
if (supertype==null) supertype = "";
String desc = "class '" + brokenName + params + supertype + "'";
return new ObjectClassDefinitionGenerator(brokenName, node, rootNode,
desc, LOCAL_CLASS, returnType, paramTypes);
}
else if (paramTypes==null && !isUpperCase) {
String desc = "object '" + brokenName + "'";
return new ObjectClassDefinitionGenerator(brokenName, node, rootNode,
desc, LOCAL_ATTRIBUTE, returnType, null);
}
else {
return null;
}
}
private static String supertypeDeclaration(ProducedType returnType) {
if (isTypeUnknown(returnType)) {
return null;
}
else {
TypeDeclaration rtd = returnType.getDeclaration();
if (rtd instanceof Class) {
return " extends " + returnType.getProducedTypeName() + "()"; //TODO: supertype arguments!
}
else if (rtd instanceof Interface) {
return " satisfies " + returnType.getProducedTypeName();
}
else if (rtd instanceof IntersectionType) {
String extendsClause = "";
StringBuilder satisfiesClause = new StringBuilder();
for (ProducedType st: rtd.getSatisfiedTypes()) {
if (st.getDeclaration() instanceof Class) {
extendsClause = " extends " + st.getProducedTypeName() + "()"; //TODO: supertype arguments!
}
else if (st.getDeclaration() instanceof Interface) {
if (satisfiesClause.length()==0) {
satisfiesClause.append(" satisfies ");
}
else {
satisfiesClause.append(" & ");
}
satisfiesClause.append(st.getProducedTypeName());
}
}
return extendsClause+satisfiesClause;
}
else {
return null;
}
}
}
private static boolean isValidSupertype(ProducedType returnType) {
if (isTypeUnknown(returnType)) {
return true;
}
else {
TypeDeclaration rtd = returnType.getDeclaration();
if (rtd.getCaseTypes()!=null) {
return false;
}
if (rtd instanceof Class) {
return !rtd.isFinal();
}
else if (rtd instanceof Interface) {
return !rtd.equals(rtd.getUnit().getCallableDeclaration());
}
else if (rtd instanceof IntersectionType) {
for (ProducedType st: rtd.getSatisfiedTypes()) {
if (!isValidSupertype(st)) return false;
}
return true;
}
else {
return false;
}
}
}
private static boolean isNotBasic(ProducedType returnType) {
if (isTypeUnknown(returnType)) {
return false;
}
else {
TypeDeclaration rtd = returnType.getDeclaration();
if (rtd instanceof Class) {
return returnType.getSupertype(rtd.getUnit().getBasicDeclaration())==null;
}
else if (rtd instanceof Interface) {
return false;
}
else if (rtd instanceof IntersectionType) {
for (ProducedType st: rtd.getSatisfiedTypes()) {
if (st.getDeclaration() instanceof Class) {
return returnType.getSupertype(rtd.getUnit().getBasicDeclaration())==null;
}
}
return false;
}
else {
return false;
}
}
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ObjectClassDefinitionGenerator.java
|
513 |
public abstract class StressTestSupport extends HazelcastTestSupport {
//todo: should be system property
public static final int RUNNING_TIME_SECONDS = 180;
//todo: should be system property
public static final int CLUSTER_SIZE = 6;
//todo: should be system property
public static final int KILL_DELAY_SECONDS = 10;
private final List<HazelcastInstance> instances = new CopyOnWriteArrayList<HazelcastInstance>();
private CountDownLatch startLatch;
private KillMemberThread killMemberThread;
private volatile boolean stopOnError = true;
private volatile boolean stopTest = false;
private boolean clusterChangeEnabled = true;
@Before
public void setUp() {
startLatch = new CountDownLatch(1);
for (int k = 0; k < CLUSTER_SIZE; k++) {
HazelcastInstance hz = newHazelcastInstance(createClusterConfig());
instances.add(hz);
}
}
public void setClusterChangeEnabled(boolean membershutdownEnabled) {
this.clusterChangeEnabled = membershutdownEnabled;
}
public Config createClusterConfig() {
return new Config();
}
@After
public void tearDown() {
for (HazelcastInstance hz : instances) {
try {
hz.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public final boolean startAndWaitForTestCompletion() {
System.out.println("Cluster change enabled:" + clusterChangeEnabled);
if (clusterChangeEnabled) {
killMemberThread = new KillMemberThread();
killMemberThread.start();
}
System.out.println("==================================================================");
System.out.println("Test started.");
System.out.println("==================================================================");
startLatch.countDown();
for (int k = 1; k <= RUNNING_TIME_SECONDS; k++) {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
float percent = (k * 100.0f) / RUNNING_TIME_SECONDS;
System.out.printf("%.1f Running for %s of %s seconds\n", percent, k, RUNNING_TIME_SECONDS);
if (stopTest) {
System.err.println("==================================================================");
System.err.println("Test ended premature!");
System.err.println("==================================================================");
return false;
}
}
System.out.println("==================================================================");
System.out.println("Test completed.");
System.out.println("==================================================================");
stopTest();
return true;
}
protected final void setStopOnError(boolean stopOnError) {
this.stopOnError = stopOnError;
}
protected final void stopTest() {
stopTest = true;
}
protected final boolean isStopped() {
return stopTest;
}
public final void assertNoErrors(TestThread... threads) {
for (TestThread thread : threads) {
thread.assertNoError();
}
}
public final void joinAll(TestThread... threads) {
for (TestThread t : threads) {
try {
t.join(60000);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while joining thread:" + t);
}
if (t.isAlive()) {
System.err.println("Could not join Thread:" + t.getName() + ", it is still alive");
for (StackTraceElement e : t.getStackTrace()) {
System.err.println("\tat " + e);
}
throw new RuntimeException("Could not join thread:" + t + ", thread is still alive");
}
}
assertNoErrors(threads);
}
public final static AtomicLong ID_GENERATOR = new AtomicLong(1);
public abstract class TestThread extends Thread {
private volatile Throwable error;
protected final Random random = new Random();
public TestThread() {
setName(getClass().getName() + "" + ID_GENERATOR.getAndIncrement());
}
@Override
public final void run() {
try {
startLatch.await();
doRun();
} catch (Throwable t) {
if (stopOnError) {
stopTest();
}
t.printStackTrace();
this.error = t;
}
}
public final void assertNoError() {
assertNull(getName() + " encountered an error", error);
}
public abstract void doRun() throws Exception;
}
public class KillMemberThread extends TestThread {
@Override
public void doRun() throws Exception {
while (!stopTest) {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(KILL_DELAY_SECONDS));
} catch (InterruptedException e) {
}
int index = random.nextInt(CLUSTER_SIZE);
HazelcastInstance instance = instances.remove(index);
instance.shutdown();
HazelcastInstance newInstance = newHazelcastInstance(createClusterConfig());
instances.add(newInstance);
}
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_stress_StressTestSupport.java
|
766 |
public class TransportShardMultiGetAction extends TransportShardSingleOperationAction<MultiGetShardRequest, MultiGetShardResponse> {
private final IndicesService indicesService;
private final boolean realtime;
@Inject
public TransportShardMultiGetAction(Settings settings, ClusterService clusterService, TransportService transportService,
IndicesService indicesService, ThreadPool threadPool) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
this.realtime = settings.getAsBoolean("action.get.realtime", true);
}
@Override
protected String executor() {
return ThreadPool.Names.GET;
}
@Override
protected String transportAction() {
return MultiGetAction.NAME + "/shard";
}
@Override
protected MultiGetShardRequest newRequest() {
return new MultiGetShardRequest();
}
@Override
protected MultiGetShardResponse newResponse() {
return new MultiGetShardResponse();
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, MultiGetShardRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.READ);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, MultiGetShardRequest request) {
return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index());
}
@Override
protected ShardIterator shards(ClusterState state, MultiGetShardRequest request) {
return clusterService.operationRouting()
.getShards(clusterService.state(), request.index(), request.shardId(), request.preference());
}
@Override
protected void resolveRequest(ClusterState state, MultiGetShardRequest request) {
if (request.realtime == null) {
request.realtime = this.realtime;
}
// no need to set concrete index and routing here, it has already been set by the multi get action on the item
//request.index(state.metaData().concreteIndex(request.index()));
}
@Override
protected MultiGetShardResponse shardOperation(MultiGetShardRequest request, int shardId) throws ElasticsearchException {
IndexService indexService = indicesService.indexServiceSafe(request.index());
IndexShard indexShard = indexService.shardSafe(shardId);
if (request.refresh() && !request.realtime()) {
indexShard.refresh(new Engine.Refresh("refresh_flag_mget").force(TransportGetAction.REFRESH_FORCE));
}
MultiGetShardResponse response = new MultiGetShardResponse();
for (int i = 0; i < request.locations.size(); i++) {
String type = request.types.get(i);
String id = request.ids.get(i);
String[] fields = request.fields.get(i);
long version = request.versions.get(i);
VersionType versionType = request.versionTypes.get(i);
if (versionType == null) {
versionType = VersionType.INTERNAL;
}
FetchSourceContext fetchSourceContext = request.fetchSourceContexts.get(i);
try {
GetResult getResult = indexShard.getService().get(type, id, fields, request.realtime(), version, versionType, fetchSourceContext);
response.add(request.locations.get(i), new GetResponse(getResult));
} catch (Throwable t) {
if (TransportActions.isShardNotAvailableException(t)) {
throw (ElasticsearchException) t;
} else {
logger.debug("[{}][{}] failed to execute multi_get for [{}]/[{}]", t, request.index(), shardId, type, id);
response.add(request.locations.get(i), new MultiGetResponse.Failure(request.index(), type, id, ExceptionsHelper.detailedMessage(t)));
}
}
}
return response;
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_get_TransportShardMultiGetAction.java
|
857 |
@SuppressWarnings("unchecked")
public class ORole extends ODocumentWrapper {
private static final long serialVersionUID = 1L;
public static final String ADMIN = "admin";
public static final String CLASS_NAME = "ORole";
public enum ALLOW_MODES {
DENY_ALL_BUT, ALLOW_ALL_BUT
}
// CRUD OPERATIONS
private static Map<Integer, String> PERMISSION_BIT_NAMES;
public final static int PERMISSION_NONE = 0;
public final static int PERMISSION_CREATE = registerPermissionBit(0, "Create");
public final static int PERMISSION_READ = registerPermissionBit(1, "Read");
public final static int PERMISSION_UPDATE = registerPermissionBit(2, "Update");
public final static int PERMISSION_DELETE = registerPermissionBit(3, "Delete");
public final static int PERMISSION_ALL = PERMISSION_CREATE + PERMISSION_READ + PERMISSION_UPDATE
+ PERMISSION_DELETE;
protected final static byte STREAM_DENY = 0;
protected final static byte STREAM_ALLOW = 1;
protected ALLOW_MODES mode = ALLOW_MODES.DENY_ALL_BUT;
protected ORole parentRole;
protected Map<String, Byte> rules = new LinkedHashMap<String, Byte>();
/**
* Constructor used in unmarshalling.
*/
public ORole() {
}
public ORole(final String iName, final ORole iParent, final ALLOW_MODES iAllowMode) {
super(CLASS_NAME);
document.field("name", iName);
parentRole = iParent;
document.field("inheritedRole", iParent != null ? iParent.getDocument() : null);
setMode(iAllowMode);
document.field("rules", new HashMap<String, Number>());
}
/**
* Create the role by reading the source document.
*/
public ORole(final ODocument iSource) {
fromStream(iSource);
}
@Override
@OBeforeDeserialization
public void fromStream(final ODocument iSource) {
if (document != null)
return;
document = iSource;
try {
mode = ((Number) document.field("mode")).byteValue() == STREAM_ALLOW ? ALLOW_MODES.ALLOW_ALL_BUT : ALLOW_MODES.DENY_ALL_BUT;
} catch (Exception ex) {
OLogManager.instance().error(this, "illegal mode " + ex.getMessage());
mode = ALLOW_MODES.DENY_ALL_BUT;
}
final OIdentifiable role = document.field("inheritedRole");
parentRole = role != null ? document.getDatabase().getMetadata().getSecurity().getRole(role) : null;
final Map<String, Number> storedRules = document.field("rules");
if (storedRules != null)
for (Entry<String, Number> a : storedRules.entrySet()) {
rules.put(a.getKey().toLowerCase(), a.getValue().byteValue());
}
if (getName().equals("admin") && !hasRule(ODatabaseSecurityResources.BYPASS_RESTRICTED))
// FIX 1.5.1 TO ASSIGN database.bypassRestricted rule to the role
addRule(ODatabaseSecurityResources.BYPASS_RESTRICTED, ORole.PERMISSION_ALL).save();
}
public boolean allow(final String iResource, final int iCRUDOperation) {
// CHECK FOR SECURITY AS DIRECT RESOURCE
final Byte access = rules.get(iResource);
if (access != null) {
final byte mask = (byte) iCRUDOperation;
return (access.byteValue() & mask) == mask;
} else if (parentRole != null)
// DELEGATE TO THE PARENT ROLE IF ANY
return parentRole.allow(iResource, iCRUDOperation);
return mode == ALLOW_MODES.ALLOW_ALL_BUT;
}
public boolean hasRule(final String iResource) {
return rules.containsKey(iResource.toLowerCase());
}
public ORole addRule(final String iResource, final int iOperation) {
rules.put(iResource.toLowerCase(), (byte) iOperation);
document.field("rules", rules);
return this;
}
/**
* Grant a permission to the resource.
*
* @param iResource
* Requested resource
* @param iOperation
* Permission to grant/add
* @return
*/
public ORole grant(final String iResource, final int iOperation) {
final Byte current = rules.get(iResource);
byte currentValue = current == null ? PERMISSION_NONE : current.byteValue();
currentValue |= (byte) iOperation;
rules.put(iResource.toLowerCase(), currentValue);
document.field("rules", rules);
return this;
}
/**
* Revoke a permission to the resource.
*
* @param iResource
* Requested resource
* @param iOperation
* Permission to grant/remove
*/
public ORole revoke(final String iResource, final int iOperation) {
if (iOperation == PERMISSION_NONE)
return this;
final Byte current = rules.get(iResource);
byte currentValue;
if (current == null)
currentValue = PERMISSION_NONE;
else {
currentValue = current.byteValue();
currentValue &= ~(byte) iOperation;
}
rules.put(iResource.toLowerCase(), currentValue);
document.field("rules", rules);
return this;
}
public String getName() {
return document.field("name");
}
public ALLOW_MODES getMode() {
return mode;
}
public ORole setMode(final ALLOW_MODES iMode) {
this.mode = iMode;
document.field("mode", mode == ALLOW_MODES.ALLOW_ALL_BUT ? STREAM_ALLOW : STREAM_DENY);
return this;
}
public ORole getParentRole() {
return parentRole;
}
public ORole setParentRole(final ORole iParent) {
this.parentRole = iParent;
document.field("inheritedRole", parentRole != null ? parentRole.getDocument() : null);
return this;
}
@Override
public ORole save() {
document.save(ORole.class.getSimpleName());
return this;
}
public Map<String, Byte> getRules() {
return Collections.unmodifiableMap(rules);
}
@Override
public String toString() {
return getName();
}
/**
* Convert the permission code to a readable string.
*
* @param iPermission
* Permission to convert
* @return String representation of the permission
*/
public static String permissionToString(final int iPermission) {
int permission = iPermission;
final StringBuilder returnValue = new StringBuilder();
for (Entry<Integer, String> p : PERMISSION_BIT_NAMES.entrySet()) {
if ((permission & p.getKey()) == p.getKey()) {
if (returnValue.length() > 0)
returnValue.append(", ");
returnValue.append(p.getValue());
permission &= ~p.getKey();
}
}
if (permission != 0) {
if (returnValue.length() > 0)
returnValue.append(", ");
returnValue.append("Unknown 0x");
returnValue.append(Integer.toHexString(permission));
}
return returnValue.toString();
}
public static int registerPermissionBit(final int iBitNo, final String iName) {
if (iBitNo < 0 || iBitNo > 31)
throw new IndexOutOfBoundsException("Permission bit number must be positive and less than 32");
final int value = 1 << iBitNo;
if (PERMISSION_BIT_NAMES == null)
PERMISSION_BIT_NAMES = new HashMap<Integer, String>();
if (PERMISSION_BIT_NAMES.containsKey(value))
throw new IndexOutOfBoundsException("Permission bit number " + String.valueOf(iBitNo) + " already in use");
PERMISSION_BIT_NAMES.put(value, iName);
return value;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_metadata_security_ORole.java
|
1,306 |
public class OClusterPage extends ODurablePage {
private static final int VERSION_SIZE = OVersionFactory.instance().getVersionSize();
private static final int NEXT_PAGE_OFFSET = NEXT_FREE_POSITION;
private static final int PREV_PAGE_OFFSET = NEXT_PAGE_OFFSET + OLongSerializer.LONG_SIZE;
private static final int FREELIST_HEADER_OFFSET = PREV_PAGE_OFFSET + OLongSerializer.LONG_SIZE;
private static final int FREE_POSITION_OFFSET = FREELIST_HEADER_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int FREE_SPACE_COUNTER_OFFSET = FREE_POSITION_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int ENTRIES_COUNT_OFFSET = FREE_SPACE_COUNTER_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int PAGE_INDEXES_LENGTH_OFFSET = ENTRIES_COUNT_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int PAGE_INDEXES_OFFSET = PAGE_INDEXES_LENGTH_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int INDEX_ITEM_SIZE = OIntegerSerializer.INT_SIZE + VERSION_SIZE;
private static final int MARKED_AS_DELETED_FLAG = 1 << 16;
private static final int POSITION_MASK = 0xFFFF;
public static final int PAGE_SIZE = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024;
public static final int MAX_ENTRY_SIZE = PAGE_SIZE - PAGE_INDEXES_OFFSET - INDEX_ITEM_SIZE;
public static final int MAX_RECORD_SIZE = MAX_ENTRY_SIZE - 3 * OIntegerSerializer.INT_SIZE;
public OClusterPage(ODirectMemoryPointer pagePointer, boolean newPage, TrackMode trackMode) throws IOException {
super(pagePointer, trackMode);
if (newPage) {
setLongValue(NEXT_PAGE_OFFSET, -1);
setLongValue(PREV_PAGE_OFFSET, -1);
setIntValue(FREE_POSITION_OFFSET, PAGE_SIZE);
setIntValue(FREE_SPACE_COUNTER_OFFSET, PAGE_SIZE - PAGE_INDEXES_OFFSET);
}
}
public int appendRecord(ORecordVersion recordVersion, byte[] record, boolean keepTombstoneVersion) throws IOException {
int freePosition = getIntValue(FREE_POSITION_OFFSET);
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
int lastEntryIndexPosition = PAGE_INDEXES_OFFSET + indexesLength * INDEX_ITEM_SIZE;
int entrySize = record.length + 3 * OIntegerSerializer.INT_SIZE;
int freeListHeader = getIntValue(FREELIST_HEADER_OFFSET);
if (!checkSpace(entrySize, freeListHeader))
return -1;
if (freeListHeader > 0) {
if (freePosition - entrySize < lastEntryIndexPosition)
doDefragmentation();
} else {
if (freePosition - entrySize < lastEntryIndexPosition + INDEX_ITEM_SIZE)
doDefragmentation();
}
freePosition = getIntValue(FREE_POSITION_OFFSET);
freePosition -= entrySize;
int entryIndex;
if (freeListHeader > 0) {
entryIndex = freeListHeader - 1;
final int tombstonePointer = getIntValue(PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * entryIndex);
int nextEntryPosition = tombstonePointer & POSITION_MASK;
if (nextEntryPosition > 0)
setIntValue(FREELIST_HEADER_OFFSET, nextEntryPosition);
else
setIntValue(FREELIST_HEADER_OFFSET, 0);
setIntValue(FREE_SPACE_COUNTER_OFFSET, getFreeSpace() - entrySize);
int entryIndexPosition = PAGE_INDEXES_OFFSET + entryIndex * INDEX_ITEM_SIZE;
setIntValue(entryIndexPosition, freePosition);
byte[] serializedVersion = getBinaryValue(entryIndexPosition + OIntegerSerializer.INT_SIZE, OVersionFactory.instance()
.getVersionSize());
ORecordVersion existingRecordVersion = OVersionFactory.instance().createVersion();
existingRecordVersion.getSerializer().fastReadFrom(serializedVersion, 0, existingRecordVersion);
if (existingRecordVersion.compareTo(recordVersion) < 0) {
recordVersion.getSerializer().fastWriteTo(serializedVersion, 0, recordVersion);
setBinaryValue(entryIndexPosition + OIntegerSerializer.INT_SIZE, serializedVersion);
} else {
if (!keepTombstoneVersion) {
existingRecordVersion.increment();
existingRecordVersion.getSerializer().fastWriteTo(serializedVersion, 0, existingRecordVersion);
setBinaryValue(entryIndexPosition + OIntegerSerializer.INT_SIZE, serializedVersion);
}
}
} else {
entryIndex = indexesLength;
setIntValue(PAGE_INDEXES_LENGTH_OFFSET, indexesLength + 1);
setIntValue(FREE_SPACE_COUNTER_OFFSET, getFreeSpace() - entrySize - INDEX_ITEM_SIZE);
int entryIndexPosition = PAGE_INDEXES_OFFSET + entryIndex * INDEX_ITEM_SIZE;
setIntValue(entryIndexPosition, freePosition);
byte[] serializedVersion = new byte[OVersionFactory.instance().getVersionSize()];
recordVersion.getSerializer().fastWriteTo(serializedVersion, 0, recordVersion);
setBinaryValue(entryIndexPosition + OIntegerSerializer.INT_SIZE, serializedVersion);
}
int entryPosition = freePosition;
setIntValue(entryPosition, entrySize);
entryPosition += OIntegerSerializer.INT_SIZE;
setIntValue(entryPosition, entryIndex);
entryPosition += OIntegerSerializer.INT_SIZE;
setIntValue(entryPosition, record.length);
entryPosition += OIntegerSerializer.INT_SIZE;
setBinaryValue(entryPosition, record);
setIntValue(FREE_POSITION_OFFSET, freePosition);
incrementEntriesCount();
return entryIndex;
}
public int replaceRecord(int entryIndex, byte[] record, ORecordVersion recordVersion) throws IOException {
int entryIndexPosition = PAGE_INDEXES_OFFSET + entryIndex * INDEX_ITEM_SIZE;
if (recordVersion != null) {
byte[] serializedVersion = getBinaryValue(entryIndexPosition + OIntegerSerializer.INT_SIZE, OVersionFactory.instance()
.getVersionSize());
ORecordVersion storedRecordVersion = OVersionFactory.instance().createVersion();
storedRecordVersion.getSerializer().fastReadFrom(serializedVersion, 0, storedRecordVersion);
if (recordVersion.compareTo(storedRecordVersion) > 0) {
recordVersion.getSerializer().fastWriteTo(serializedVersion, 0, recordVersion);
setBinaryValue(entryIndexPosition + OIntegerSerializer.INT_SIZE, serializedVersion);
}
}
int entryPointer = getIntValue(entryIndexPosition);
int entryPosition = entryPointer & POSITION_MASK;
int recordSize = getIntValue(entryPosition) - 3 * OIntegerSerializer.INT_SIZE;
int writtenBytes;
if (record.length <= recordSize) {
setIntValue(entryPointer + 2 * OIntegerSerializer.INT_SIZE, record.length);
setBinaryValue(entryPointer + 3 * OIntegerSerializer.INT_SIZE, record);
writtenBytes = record.length;
} else {
byte[] newRecord = new byte[recordSize];
System.arraycopy(record, 0, newRecord, 0, newRecord.length);
setBinaryValue(entryPointer + 3 * OIntegerSerializer.INT_SIZE, newRecord);
writtenBytes = newRecord.length;
}
return writtenBytes;
}
public ORecordVersion getRecordVersion(int position) {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
if (position >= indexesLength)
return null;
int entryIndexPosition = PAGE_INDEXES_OFFSET + position * INDEX_ITEM_SIZE;
byte[] serializedVersion = getBinaryValue(entryIndexPosition + OIntegerSerializer.INT_SIZE, OVersionFactory.instance()
.getVersionSize());
ORecordVersion recordVersion = OVersionFactory.instance().createVersion();
recordVersion.getSerializer().fastReadFrom(serializedVersion, 0, recordVersion);
return recordVersion;
}
public boolean isEmpty() {
return getFreeSpace() == PAGE_SIZE - PAGE_INDEXES_OFFSET;
}
private boolean checkSpace(int entrySize, int freeListHeader) {
if (freeListHeader > 0) {
if (getFreeSpace() - entrySize < 0)
return false;
} else {
if (getFreeSpace() - entrySize - INDEX_ITEM_SIZE < 0)
return false;
}
return true;
}
public boolean deleteRecord(int position) throws IOException {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
if (position >= indexesLength)
return false;
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * position;
int entryPointer = getIntValue(entryIndexPosition);
if ((entryPointer & MARKED_AS_DELETED_FLAG) > 0)
return false;
int entryPosition = entryPointer & POSITION_MASK;
int freeListHeader = getIntValue(FREELIST_HEADER_OFFSET);
if (freeListHeader <= 0)
setIntValue(entryIndexPosition, MARKED_AS_DELETED_FLAG);
else
setIntValue(entryIndexPosition, freeListHeader | MARKED_AS_DELETED_FLAG);
setIntValue(FREELIST_HEADER_OFFSET, position + 1);
final int entrySize = getIntValue(entryPosition);
assert entrySize > 0;
setIntValue(entryPosition, -entrySize);
setIntValue(FREE_SPACE_COUNTER_OFFSET, getFreeSpace() + entrySize);
decrementEntriesCount();
return true;
}
public boolean isDeleted(int position) {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
if (position >= indexesLength)
return true;
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * position;
int entryPointer = getIntValue(entryIndexPosition);
return (entryPointer & MARKED_AS_DELETED_FLAG) > 0;
}
public int getRecordPageOffset(int position) {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
if (position >= indexesLength)
return -1;
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * position;
int entryPointer = getIntValue(entryIndexPosition);
if ((entryPointer & MARKED_AS_DELETED_FLAG) > 0)
return -1;
int entryPosition = entryPointer & POSITION_MASK;
return entryPosition + 3 * OIntegerSerializer.INT_SIZE;
}
public int getRecordSize(int position) {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
if (position >= indexesLength)
return -1;
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * position;
int entryPointer = getIntValue(entryIndexPosition);
if ((entryPointer & MARKED_AS_DELETED_FLAG) > 0)
return -1;
int entryPosition = entryPointer & POSITION_MASK;
return getIntValue(entryPosition + 2 * OIntegerSerializer.INT_SIZE);
}
public int findFirstDeletedRecord(int position) {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
for (int i = position; i < indexesLength; i++) {
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * i;
int entryPointer = getIntValue(entryIndexPosition);
if ((entryPointer & MARKED_AS_DELETED_FLAG) > 0)
return i;
}
return -1;
}
public int findFirstRecord(int position) {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
for (int i = position; i < indexesLength; i++) {
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * i;
int entryPointer = getIntValue(entryIndexPosition);
if ((entryPointer & MARKED_AS_DELETED_FLAG) == 0)
return i;
}
return -1;
}
public int findLastRecord(int position) {
int indexesLength = getIntValue(PAGE_INDEXES_LENGTH_OFFSET);
int endIndex = Math.min(indexesLength - 1, position);
for (int i = endIndex; i >= 0; i--) {
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * i;
int entryPointer = getIntValue(entryIndexPosition);
if ((entryPointer & MARKED_AS_DELETED_FLAG) == 0)
return i;
}
return -1;
}
public int getFreeSpace() {
return getIntValue(FREE_SPACE_COUNTER_OFFSET);
}
public int getMaxRecordSize() {
int freeListHeader = getIntValue(FREELIST_HEADER_OFFSET);
int maxEntrySize;
if (freeListHeader > 0)
maxEntrySize = getFreeSpace();
else
maxEntrySize = getFreeSpace() - INDEX_ITEM_SIZE;
int result = maxEntrySize - 3 * OIntegerSerializer.INT_SIZE;
if (result < 0)
return 0;
return result;
}
public int getRecordsCount() {
return getIntValue(ENTRIES_COUNT_OFFSET);
}
public long getNextPage() {
return getLongValue(NEXT_PAGE_OFFSET);
}
public void setNextPage(long nextPage) throws IOException {
setLongValue(NEXT_PAGE_OFFSET, nextPage);
}
public long getPrevPage() {
return getLongValue(PREV_PAGE_OFFSET);
}
public void setPrevPage(long prevPage) throws IOException {
setLongValue(PREV_PAGE_OFFSET, prevPage);
}
private void incrementEntriesCount() throws IOException {
setIntValue(ENTRIES_COUNT_OFFSET, getRecordsCount() + 1);
}
private void decrementEntriesCount() throws IOException {
setIntValue(ENTRIES_COUNT_OFFSET, getRecordsCount() - 1);
}
private void doDefragmentation() throws IOException {
int freePosition = getIntValue(FREE_POSITION_OFFSET);
int currentPosition = freePosition;
List<Integer> processedPositions = new ArrayList<Integer>();
while (currentPosition < PAGE_SIZE) {
int entrySize = getIntValue(currentPosition);
if (entrySize > 0) {
int positionIndex = getIntValue(currentPosition + OIntegerSerializer.INT_SIZE);
processedPositions.add(positionIndex);
currentPosition += entrySize;
} else {
entrySize = -entrySize;
moveData(freePosition, freePosition + entrySize, currentPosition - freePosition);
currentPosition += entrySize;
freePosition += entrySize;
shiftPositions(processedPositions, entrySize);
}
}
setIntValue(FREE_POSITION_OFFSET, freePosition);
}
private void shiftPositions(List<Integer> processedPositions, int entrySize) throws IOException {
for (int positionIndex : processedPositions) {
int entryIndexPosition = PAGE_INDEXES_OFFSET + INDEX_ITEM_SIZE * positionIndex;
int entryPosition = getIntValue(entryIndexPosition);
setIntValue(entryIndexPosition, entryPosition + entrySize);
}
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OClusterPage.java
|
1,262 |
class SniffNodesSampler extends NodeSampler {
@Override
protected void doSample() {
// the nodes we are going to ping include the core listed nodes that were added
// and the last round of discovered nodes
Set<DiscoveryNode> nodesToPing = Sets.newHashSet();
for (DiscoveryNode node : listedNodes) {
nodesToPing.add(node);
}
for (DiscoveryNode node : nodes) {
nodesToPing.add(node);
}
final CountDownLatch latch = new CountDownLatch(nodesToPing.size());
final ConcurrentMap<DiscoveryNode, ClusterStateResponse> clusterStateResponses = ConcurrentCollections.newConcurrentMap();
for (final DiscoveryNode listedNode : nodesToPing) {
threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() {
@Override
public void run() {
try {
if (!transportService.nodeConnected(listedNode)) {
try {
// if its one of hte actual nodes we will talk to, not to listed nodes, fully connect
if (nodes.contains(listedNode)) {
logger.trace("connecting to cluster node [{}]", listedNode);
transportService.connectToNode(listedNode);
} else {
// its a listed node, light connect to it...
logger.trace("connecting to listed node (light) [{}]", listedNode);
transportService.connectToNodeLight(listedNode);
}
} catch (Exception e) {
logger.debug("failed to connect to node [{}], ignoring...", e, listedNode);
latch.countDown();
return;
}
}
transportService.sendRequest(listedNode, ClusterStateAction.NAME,
Requests.clusterStateRequest()
.clear().nodes(true).local(true),
TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout),
new BaseTransportResponseHandler<ClusterStateResponse>() {
@Override
public ClusterStateResponse newInstance() {
return new ClusterStateResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(ClusterStateResponse response) {
clusterStateResponses.put(listedNode, response);
latch.countDown();
}
@Override
public void handleException(TransportException e) {
logger.info("failed to get local cluster state for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
});
} catch (Throwable e) {
logger.info("failed to get local cluster state info for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
return;
}
HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(listedNodes);
HashSet<DiscoveryNode> newFilteredNodes = new HashSet<DiscoveryNode>();
for (Map.Entry<DiscoveryNode, ClusterStateResponse> entry : clusterStateResponses.entrySet()) {
if (!ignoreClusterName && !clusterName.equals(entry.getValue().getClusterName())) {
logger.warn("node {} not part of the cluster {}, ignoring...", entry.getValue().getState().nodes().localNode(), clusterName);
newFilteredNodes.add(entry.getKey());
continue;
}
for (ObjectCursor<DiscoveryNode> cursor : entry.getValue().getState().nodes().dataNodes().values()) {
newNodes.add(cursor.value);
}
}
nodes = validateNewNodes(newNodes);
filteredNodes = ImmutableList.copyOf(newFilteredNodes);
}
}
| 1no label
|
src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java
|
1,777 |
public class FieldManager {
private static final Log LOG = LogFactory.getLog(FieldManager.class);
public static final String MAPFIELDSEPARATOR = "---";
protected EntityConfiguration entityConfiguration;
protected DynamicEntityDao dynamicEntityDao;
protected List<SortableValue> middleFields = new ArrayList<SortableValue>(5);
public FieldManager(EntityConfiguration entityConfiguration, DynamicEntityDao dynamicEntityDao) {
this.entityConfiguration = entityConfiguration;
this.dynamicEntityDao = dynamicEntityDao;
}
public static Field getSingleField(Class<?> clazz, String fieldName) throws IllegalStateException {
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException nsf) {
// Try superclass
if (clazz.getSuperclass() != null) {
return getSingleField(clazz.getSuperclass(), fieldName);
}
return null;
}
}
public Field getField(Class<?> clazz, String fieldName) throws IllegalStateException {
String[] tokens = fieldName.split("\\.");
Field field = null;
for (int j=0;j<tokens.length;j++) {
String propertyName = tokens[j];
field = getSingleField(clazz, propertyName);
if (field != null && j < tokens.length - 1) {
Class<?>[] entities = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(field.getType());
if (entities.length > 0) {
String peekAheadToken = tokens[j+1];
List<Class<?>> matchedClasses = new ArrayList<Class<?>>();
for (Class<?> entity : entities) {
Field peekAheadField = null;
try {
peekAheadField = entity.getDeclaredField(peekAheadToken);
} catch (NoSuchFieldException nsf) {
//do nothing
}
if (peekAheadField != null) {
matchedClasses.add(entity);
}
}
if (matchedClasses.size() > 1) {
LOG.warn("Found the property (" + peekAheadToken + ") in more than one class of an inheritance hierarchy. This may lead to unwanted behavior, as the system does not know which class was intended. Do not use the same property name in different levels of the inheritance hierarchy. Defaulting to the first class found (" + matchedClasses.get(0).getName() + ")");
}
if (getSingleField(matchedClasses.get(0), peekAheadToken) != null) {
clazz = matchedClasses.get(0);
PersistentClass persistentClass = dynamicEntityDao.getPersistentClass(clazz.getName());
if (persistentClass != null && matchedClasses.size() == 1 && clazz.isInterface()) {
try {
clazz = entityConfiguration.lookupEntityClass(field.getType().getName());
} catch (Exception e) {
// Do nothing - we'll use the matchedClass
}
}
} else {
clazz = field.getType();
}
} else {
//may be an embedded class - try the class directly
clazz = field.getType();
}
} else {
break;
}
}
if (field != null) {
field.setAccessible(true);
}
return field;
}
public Object getFieldValue(Object bean, String fieldName) throws IllegalAccessException, FieldNotAvailableException {
StringTokenizer tokens = new StringTokenizer(fieldName, ".");
Class<?> componentClass = bean.getClass();
Field field;
Object value = bean;
while (tokens.hasMoreTokens()) {
String fieldNamePart = tokens.nextToken();
String mapKey = null;
if (fieldNamePart.contains(FieldManager.MAPFIELDSEPARATOR)) {
mapKey = fieldNamePart.substring(fieldNamePart.indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), fieldNamePart.length());
fieldNamePart = fieldNamePart.substring(0, fieldNamePart.indexOf(FieldManager.MAPFIELDSEPARATOR));
}
field = getSingleField(componentClass, fieldNamePart);
if (field != null) {
field.setAccessible(true);
value = field.get(value);
if (value != null && mapKey != null) {
value = ((Map) value).get(mapKey);
}
if (value != null) {
componentClass = value.getClass();
} else {
break;
}
} else {
throw new FieldNotAvailableException("Unable to find field (" + fieldNamePart + ") on the class (" + componentClass + ")");
}
}
return value;
}
public Object setFieldValue(Object bean, String fieldName, Object newValue) throws IllegalAccessException, InstantiationException {
StringTokenizer tokens = new StringTokenizer(fieldName, ".");
Class<?> componentClass = bean.getClass();
Field field;
Object value = bean;
int count = tokens.countTokens();
int j=0;
StringBuilder sb = new StringBuilder();
while (tokens.hasMoreTokens()) {
String fieldNamePart = tokens.nextToken();
sb.append(fieldNamePart);
String mapKey = null;
if (fieldNamePart.contains(FieldManager.MAPFIELDSEPARATOR)) {
mapKey = fieldNamePart.substring(fieldNamePart.indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), fieldNamePart.length());
fieldNamePart = fieldNamePart.substring(0, fieldNamePart.indexOf(FieldManager.MAPFIELDSEPARATOR));
}
field = getSingleField(componentClass, fieldNamePart);
field.setAccessible(true);
if (j == count - 1) {
if (mapKey != null) {
Map map = (Map) field.get(value);
if (newValue == null) {
map.remove(mapKey);
} else {
map.put(mapKey, newValue);
}
} else {
field.set(value, newValue);
}
} else {
Object myValue = field.get(value);
if (myValue != null) {
componentClass = myValue.getClass();
value = myValue;
} else {
//consult the entity configuration manager to see if there is a user
//configured entity for this class
try {
Object newEntity = entityConfiguration.createEntityInstance(field.getType().getName());
SortableValue val = new SortableValue(bean, (Serializable) newEntity, j, sb.toString());
middleFields.add(val);
field.set(value, newEntity);
componentClass = newEntity.getClass();
value = newEntity;
} catch (Exception e) {
//Use the most extended type based on the field type
Class<?>[] entities = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(field.getType());
if (!ArrayUtils.isEmpty(entities)) {
Object newEntity = entities[0].newInstance();
SortableValue val = new SortableValue(bean, (Serializable) newEntity, j, sb.toString());
middleFields.add(val);
field.set(value, newEntity);
componentClass = newEntity.getClass();
value = newEntity;
LOG.info("Unable to find a reference to ("+field.getType().getName()+") in the EntityConfigurationManager. Using the most extended form of this class identified as ("+entities[0].getName()+")");
} else {
//Just use the field type
Object newEntity = field.getType().newInstance();
field.set(value, newEntity);
componentClass = newEntity.getClass();
value = newEntity;
LOG.info("Unable to find a reference to ("+field.getType().getName()+") in the EntityConfigurationManager. Using the type of this class.");
}
}
}
}
sb.append(".");
j++;
}
return value;
}
public Map<String, Serializable> persistMiddleEntities() throws InstantiationException, IllegalAccessException {
Map<String, Serializable> persistedEntities = new HashMap<String, Serializable>();
Collections.sort(middleFields);
for (SortableValue val : middleFields) {
Serializable s = dynamicEntityDao.merge(val.entity);
persistedEntities.put(val.getContainingPropertyName(), s);
setFieldValue(val.getBean(), val.getContainingPropertyName(), s);
}
return persistedEntities;
}
public EntityConfiguration getEntityConfiguration() {
return entityConfiguration;
}
private class SortableValue implements Comparable<SortableValue> {
private Integer pos;
private Serializable entity;
private Class<?> entityClass;
private String containingPropertyName;
private Object bean;
public SortableValue(Object bean, Serializable entity, Integer pos, String containingPropertyName) {
this.bean = bean;
this.entity = entity;
this.pos = pos;
this.entityClass = entity.getClass();
this.containingPropertyName = containingPropertyName;
}
public int compareTo(SortableValue o) {
return pos.compareTo(o.pos) * -1;
}
public String getContainingPropertyName() {
return containingPropertyName;
}
private Object getBean() {
return bean;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + (entityClass == null ? 0 : entityClass.hashCode());
result = prime * result + (pos == null ? 0 : pos.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;
SortableValue other = (SortableValue) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (entityClass == null) {
if (other.entityClass != null)
return false;
} else if (!entityClass.equals(other.entityClass))
return false;
if (pos == null) {
if (other.pos != null)
return false;
} else if (!pos.equals(other.pos))
return false;
return true;
}
private FieldManager getOuterType() {
return FieldManager.this;
}
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_FieldManager.java
|
835 |
new ConstructorFunction<String, ReferenceWrapper>() {
public ReferenceWrapper createNew(String key) {
return new ReferenceWrapper();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_AtomicReferenceService.java
|
656 |
public class CategoryDaoTest extends BaseTest {
@Resource
private CategoryDao categoryDao;
@Resource
private CatalogService catalogService;
@Test(groups = {"testSetFeaturedProducts"}, dataProvider="basicCategory", dataProviderClass=CategoryDaoDataProvider.class)
@Transactional
public void testSetFeaturedProducts(Category category) {
category = catalogService.saveCategory(category);
Sku sku = new SkuImpl();
sku.setDescription("This thing will change your life");
sku.setName("Test Product");
catalogService.saveSku(sku);
Product product = new ProductImpl();
product.setModel("KGX200");
product.setDefaultSku(sku);
product = catalogService.saveProduct(product);
FeaturedProduct featuredProduct = new FeaturedProductImpl();
featuredProduct.setCategory(category);
featuredProduct.setProduct(product);
featuredProduct.setPromotionMessage("BUY ME NOW!!!!");
List<FeaturedProduct> featuredProducts = new ArrayList<FeaturedProduct>();
featuredProducts.add(featuredProduct);
category.setFeaturedProducts(featuredProducts);
category = catalogService.saveCategory(category);
Category categoryTest = categoryDao.readCategoryById(category.getId());
FeaturedProduct featuredProductTest = categoryTest.getFeaturedProducts().get(0);
assert (featuredProductTest.getPromotionMessage() == "BUY ME NOW!!!!");
assert (featuredProductTest.getProduct().getModel().equals("KGX200"));
}
}
| 0true
|
integration_src_test_java_org_broadleafcommerce_core_catalog_dao_CategoryDaoTest.java
|
63 |
public interface TitanGraphQuery<Q extends TitanGraphQuery<Q>> extends GraphQuery {
/* ---------------------------------------------------------------
* Query Specification
* ---------------------------------------------------------------
*/
/**
* The returned element must have a property for the given key that matches the condition according to the
* specified relation
*
* @param key Key that identifies the property
* @param predicate Predicate between property and condition
* @param condition
* @return This query
*/
@Override
public Q has(String key, Predicate predicate, Object condition);
/**
* The returned element must have a property for the given key that matches the condition according to the
* specified relation
*
* @param key Key that identifies the property
* @param predicate Relation between property and condition
* @param condition
* @return This query
*/
public Q has(PropertyKey key, TitanPredicate predicate, Object condition);
@Override
public Q has(String key);
@Override
public Q hasNot(String key);
@Override
public Q has(String key, Object value);
@Override
public Q hasNot(String key, Object value);
@Override
@Deprecated
public <T extends Comparable<T>> Q has(String key, T value, Compare compare);
@Override
public <T extends Comparable<?>> Q interval(String key, T startValue, T endValue);
/**
* Limits the size of the returned result set
*
* @param max The maximum number of results to return
* @return This query
*/
@Override
public Q limit(final int max);
/**
* Orders the element results of this query according
* to their property for the given key in the given order (increasing/decreasing).
*
* @param key The key of the properties on which to order
* @param order the ordering direction
* @return
*/
public Q orderBy(String key, Order order);
/**
* Orders the element results of this query according
* to their property for the given key in the given order (increasing/decreasing).
*
* @param key The key of the properties on which to order
* @param order the ordering direction
* @return
*/
public Q orderBy(PropertyKey key, Order order);
/* ---------------------------------------------------------------
* Query Execution
* ---------------------------------------------------------------
*/
/**
* Returns all vertices that match the conditions.
*
* @return
*/
public Iterable<Vertex> vertices();
/**
* Returns all edges that match the conditions.
*
* @return
*/
public Iterable<Edge> edges();
/**
* Returns all properties that match the conditions
*
* @return
*/
public Iterable<TitanProperty> properties();
/**
* Returns a description of this query for vertices as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for vertices
*/
public QueryDescription describeForVertices();
/**
* Returns a description of this query for edges as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for edges
*/
public QueryDescription describeForEdges();
/**
* Returns a description of this query for properties as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for properties
*/
public QueryDescription describeForProperties();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanGraphQuery.java
|
37 |
public class CompletionException extends RuntimeException {
private static final long serialVersionUID = 7830266012832686185L;
/**
* Constructs a {@code CompletionException} with no detail message.
* The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause(Throwable) initCause}.
*/
protected CompletionException() { }
/**
* Constructs a {@code CompletionException} with the specified detail
* message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause(Throwable) initCause}.
*
* @param message the detail message
*/
protected CompletionException(String message) {
super(message);
}
/**
* Constructs a {@code CompletionException} with the specified detail
* message and cause.
*
* @param message the detail message
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method)
*/
public CompletionException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a {@code CompletionException} with the specified cause.
* The detail message is set to {@code (cause == null ? null :
* cause.toString())} (which typically contains the class and
* detail message of {@code cause}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method)
*/
public CompletionException(Throwable cause) {
super(cause);
}
}
| 0true
|
src_main_java_jsr166e_CompletionException.java
|
287 |
public interface DataDrivenEnumerationDao {
public DataDrivenEnumeration readEnumByKey(String enumKey);
public DataDrivenEnumerationValue readEnumValueByKey(String enumKey, String enumValueKey);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_enumeration_dao_DataDrivenEnumerationDao.java
|
537 |
@Deprecated
public class TransportGatewaySnapshotAction extends TransportBroadcastOperationAction<GatewaySnapshotRequest, GatewaySnapshotResponse, ShardGatewaySnapshotRequest, ShardGatewaySnapshotResponse> {
private final IndicesService indicesService;
@Inject
public TransportGatewaySnapshotAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
TransportService transportService, IndicesService indicesService) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
}
@Override
protected String executor() {
return ThreadPool.Names.SNAPSHOT;
}
@Override
protected String transportAction() {
return GatewaySnapshotAction.NAME;
}
@Override
protected GatewaySnapshotRequest newRequest() {
return new GatewaySnapshotRequest();
}
@Override
protected GatewaySnapshotResponse newResponse(GatewaySnapshotRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = null;
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
// non active shard, ignore
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
if (shardFailures == null) {
shardFailures = Lists.newArrayList();
}
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
successfulShards++;
}
}
return new GatewaySnapshotResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
@Override
protected ShardGatewaySnapshotRequest newShardRequest() {
return new ShardGatewaySnapshotRequest();
}
@Override
protected ShardGatewaySnapshotRequest newShardRequest(ShardRouting shard, GatewaySnapshotRequest request) {
return new ShardGatewaySnapshotRequest(shard.index(), shard.id(), request);
}
@Override
protected ShardGatewaySnapshotResponse newShardResponse() {
return new ShardGatewaySnapshotResponse();
}
@Override
protected ShardGatewaySnapshotResponse shardOperation(ShardGatewaySnapshotRequest request) throws ElasticsearchException {
IndexShardGatewayService shardGatewayService = indicesService.indexServiceSafe(request.index())
.shardInjectorSafe(request.shardId()).getInstance(IndexShardGatewayService.class);
shardGatewayService.snapshot("api");
return new ShardGatewaySnapshotResponse(request.index(), request.shardId());
}
/**
* The snapshot request works against all primary shards.
*/
@Override
protected GroupShardsIterator shards(ClusterState clusterState, GatewaySnapshotRequest request, String[] concreteIndices) {
return clusterState.routingTable().activePrimaryShardsGrouped(concreteIndices, true);
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, GatewaySnapshotRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, GatewaySnapshotRequest request, String[] concreteIndices) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, concreteIndices);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_gateway_snapshot_TransportGatewaySnapshotAction.java
|
208 |
private class ClusterAuthenticator implements Authenticator {
@Override
public void auth(ClientConnection connection) throws AuthenticationException, IOException {
authenticate(connection, credentials, principal, false, false);
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
|
637 |
static final class Fields {
static final XContentBuilderString INDICES = new XContentBuilderString("indices");
static final XContentBuilderString INDEX = new XContentBuilderString("index");
static final XContentBuilderString PRIMARY_SIZE = new XContentBuilderString("primary_size");
static final XContentBuilderString PRIMARY_SIZE_IN_BYTES = new XContentBuilderString("primary_size_in_bytes");
static final XContentBuilderString SIZE = new XContentBuilderString("size");
static final XContentBuilderString SIZE_IN_BYTES = new XContentBuilderString("size_in_bytes");
static final XContentBuilderString TRANSLOG = new XContentBuilderString("translog");
static final XContentBuilderString OPERATIONS = new XContentBuilderString("operations");
static final XContentBuilderString DOCS = new XContentBuilderString("docs");
static final XContentBuilderString NUM_DOCS = new XContentBuilderString("num_docs");
static final XContentBuilderString MAX_DOC = new XContentBuilderString("max_doc");
static final XContentBuilderString DELETED_DOCS = new XContentBuilderString("deleted_docs");
static final XContentBuilderString SHARDS = new XContentBuilderString("shards");
static final XContentBuilderString ROUTING = new XContentBuilderString("routing");
static final XContentBuilderString STATE = new XContentBuilderString("state");
static final XContentBuilderString PRIMARY = new XContentBuilderString("primary");
static final XContentBuilderString NODE = new XContentBuilderString("node");
static final XContentBuilderString RELOCATING_NODE = new XContentBuilderString("relocating_node");
static final XContentBuilderString SHARD = new XContentBuilderString("shard");
static final XContentBuilderString ID = new XContentBuilderString("id");
static final XContentBuilderString PEER_RECOVERY = new XContentBuilderString("peer_recovery");
static final XContentBuilderString STAGE = new XContentBuilderString("stage");
static final XContentBuilderString START_TIME_IN_MILLIS = new XContentBuilderString("start_time_in_millis");
static final XContentBuilderString TIME = new XContentBuilderString("time");
static final XContentBuilderString TIME_IN_MILLIS = new XContentBuilderString("time_in_millis");
static final XContentBuilderString PROGRESS = new XContentBuilderString("progress");
static final XContentBuilderString REUSED_SIZE = new XContentBuilderString("reused_size");
static final XContentBuilderString REUSED_SIZE_IN_BYTES = new XContentBuilderString("reused_size_in_bytes");
static final XContentBuilderString EXPECTED_RECOVERED_SIZE = new XContentBuilderString("expected_recovered_size");
static final XContentBuilderString EXPECTED_RECOVERED_SIZE_IN_BYTES = new XContentBuilderString("expected_recovered_size_in_bytes");
static final XContentBuilderString RECOVERED_SIZE = new XContentBuilderString("recovered_size");
static final XContentBuilderString RECOVERED_SIZE_IN_BYTES = new XContentBuilderString("recovered_size_in_bytes");
static final XContentBuilderString RECOVERED = new XContentBuilderString("recovered");
static final XContentBuilderString GATEWAY_RECOVERY = new XContentBuilderString("gateway_recovery");
static final XContentBuilderString GATEWAY_SNAPSHOT = new XContentBuilderString("gateway_snapshot");
static final XContentBuilderString EXPECTED_OPERATIONS = new XContentBuilderString("expected_operations");
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_status_IndicesStatusResponse.java
|
1,419 |
public static interface RemoveListener {
void onResponse(RemoveResponse response);
void onFailure(Throwable t);
}
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexTemplateService.java
|
1,409 |
clusterService.submitStateUpdateTask("index-aliases", Priority.URGENT, new AckedClusterStateUpdateTask() {
@Override
public boolean mustAck(DiscoveryNode discoveryNode) {
return true;
}
@Override
public void onAllNodesAcked(@Nullable Throwable t) {
listener.onResponse(new ClusterStateUpdateResponse(true));
}
@Override
public void onAckTimeout() {
listener.onResponse(new ClusterStateUpdateResponse(false));
}
@Override
public TimeValue ackTimeout() {
return request.ackTimeout();
}
@Override
public TimeValue timeout() {
return request.masterNodeTimeout();
}
@Override
public void onFailure(String source, Throwable t) {
listener.onFailure(t);
}
@Override
public ClusterState execute(final ClusterState currentState) {
List<String> indicesToClose = Lists.newArrayList();
Map<String, IndexService> indices = Maps.newHashMap();
try {
for (AliasAction aliasAction : request.actions()) {
if (!Strings.hasText(aliasAction.alias()) || !Strings.hasText(aliasAction.index())) {
throw new ElasticsearchIllegalArgumentException("Index name and alias name are required");
}
if (!currentState.metaData().hasIndex(aliasAction.index())) {
throw new IndexMissingException(new Index(aliasAction.index()));
}
if (currentState.metaData().hasIndex(aliasAction.alias())) {
throw new InvalidAliasNameException(new Index(aliasAction.index()), aliasAction.alias(), "an index exists with the same name as the alias");
}
if (aliasAction.indexRouting() != null && aliasAction.indexRouting().indexOf(',') != -1) {
throw new ElasticsearchIllegalArgumentException("alias [" + aliasAction.alias() + "] has several routing values associated with it");
}
}
boolean changed = false;
MetaData.Builder builder = MetaData.builder(currentState.metaData());
for (AliasAction aliasAction : request.actions()) {
IndexMetaData indexMetaData = builder.get(aliasAction.index());
if (indexMetaData == null) {
throw new IndexMissingException(new Index(aliasAction.index()));
}
// TODO: not copy (putAll)
IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData);
if (aliasAction.actionType() == AliasAction.Type.ADD) {
String filter = aliasAction.filter();
if (Strings.hasLength(filter)) {
// parse the filter, in order to validate it
IndexService indexService = indices.get(indexMetaData.index());
if (indexService == null) {
indexService = indicesService.indexService(indexMetaData.index());
if (indexService == null) {
// temporarily create the index and add mappings so we have can parse the filter
try {
indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), clusterService.localNode().id());
if (indexMetaData.mappings().containsKey(MapperService.DEFAULT_MAPPING)) {
indexService.mapperService().merge(MapperService.DEFAULT_MAPPING, indexMetaData.mappings().get(MapperService.DEFAULT_MAPPING).source(), false);
}
for (ObjectCursor<MappingMetaData> cursor : indexMetaData.mappings().values()) {
MappingMetaData mappingMetaData = cursor.value;
indexService.mapperService().merge(mappingMetaData.type(), mappingMetaData.source(), false);
}
} catch (Exception e) {
logger.warn("[{}] failed to temporary create in order to apply alias action", e, indexMetaData.index());
continue;
}
indicesToClose.add(indexMetaData.index());
}
indices.put(indexMetaData.index(), indexService);
}
// now, parse the filter
IndexQueryParserService indexQueryParser = indexService.queryParserService();
try {
XContentParser parser = XContentFactory.xContent(filter).createParser(filter);
try {
indexQueryParser.parseInnerFilter(parser);
} finally {
parser.close();
}
} catch (Throwable e) {
throw new ElasticsearchIllegalArgumentException("failed to parse filter for [" + aliasAction.alias() + "]", e);
}
}
AliasMetaData newAliasMd = AliasMetaData.newAliasMetaDataBuilder(
aliasAction.alias())
.filter(filter)
.indexRouting(aliasAction.indexRouting())
.searchRouting(aliasAction.searchRouting())
.build();
// Check if this alias already exists
AliasMetaData aliasMd = indexMetaData.aliases().get(aliasAction.alias());
if (aliasMd != null && aliasMd.equals(newAliasMd)) {
// It's the same alias - ignore it
continue;
}
indexMetaDataBuilder.putAlias(newAliasMd);
} else if (aliasAction.actionType() == AliasAction.Type.REMOVE) {
if (!indexMetaData.aliases().containsKey(aliasAction.alias())) {
// This alias doesn't exist - ignore
continue;
}
indexMetaDataBuilder.removerAlias(aliasAction.alias());
}
changed = true;
builder.put(indexMetaDataBuilder);
}
if (changed) {
ClusterState updatedState = ClusterState.builder(currentState).metaData(builder).build();
// even though changes happened, they resulted in 0 actual changes to metadata
// i.e. remove and add the same alias to the same index
if (!updatedState.metaData().aliases().equals(currentState.metaData().aliases())) {
return updatedState;
}
}
return currentState;
} finally {
for (String index : indicesToClose) {
indicesService.removeIndex(index, "created for alias processing");
}
}
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
});
| 1no label
|
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexAliasesService.java
|
717 |
public class RelatedProductTypeEnum implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, RelatedProductTypeEnum> TYPES = new LinkedHashMap<String, RelatedProductTypeEnum>();
public static final RelatedProductTypeEnum FEATURED = new RelatedProductTypeEnum("FEATURED", "Featured");
public static final RelatedProductTypeEnum UP_SALE = new RelatedProductTypeEnum("UP_SALE", "Up sale");
public static final RelatedProductTypeEnum CROSS_SALE = new RelatedProductTypeEnum("CROSS_SALE", "Cross sale");
public static RelatedProductTypeEnum getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public RelatedProductTypeEnum() {
//do nothing
}
public RelatedProductTypeEnum(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RelatedProductTypeEnum other = (RelatedProductTypeEnum) 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_domain_RelatedProductTypeEnum.java
|
346 |
public class ODatabaseRecordThreadLocal extends ThreadLocal<ODatabaseRecord> {
public static ODatabaseRecordThreadLocal INSTANCE = new ODatabaseRecordThreadLocal();
@Override
public ODatabaseRecord get() {
ODatabaseRecord db = super.get();
if (db == null) {
if (Orient.instance().getDatabaseThreadFactory() == null) {
throw new ODatabaseException(
"Database instance is not set in current thread. Assure to set it with: ODatabaseRecordThreadLocal.INSTANCE.set(db);");
} else {
db = Orient.instance().getDatabaseThreadFactory().getThreadDatabase();
if (db == null) {
throw new ODatabaseException(
"Database instance is not set in current thread. Assure to set it with: ODatabaseRecordThreadLocal.INSTANCE.set(db);");
} else {
set(db);
}
}
}
return db;
}
@Override
public void remove() {
super.remove();
}
@Override
public void set(final ODatabaseRecord value) {
super.set(value);
}
public ODatabaseRecord getIfDefined() {
return super.get();
}
public boolean isDefined() {
return super.get() != null;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_ODatabaseRecordThreadLocal.java
|
699 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@javax.persistence.Table(name="BLC_PRODUCT")
//multi-column indexes don't appear to get exported correctly when declared at the field level, so declaring here as a workaround
@org.hibernate.annotations.Table(appliesTo = "BLC_PRODUCT", indexes = {
@Index(name = "PRODUCT_URL_INDEX",
columnNames = {"URL","URL_KEY"}
)
})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "baseProduct")
@SQLDelete(sql="UPDATE BLC_PRODUCT SET ARCHIVED = 'Y' WHERE PRODUCT_ID = ?")
public class ProductImpl implements Product, Status, AdminMainEntity {
private static final Log LOG = LogFactory.getLog(ProductImpl.class);
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The id. */
@Id
@GeneratedValue(generator= "ProductId")
@GenericGenerator(
name="ProductId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="ProductImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.ProductImpl")
}
)
@Column(name = "PRODUCT_ID")
@AdminPresentation(friendlyName = "ProductImpl_Product_ID", visibility = VisibilityEnum.HIDDEN_ALL)
protected Long id;
@Column(name = "URL")
@AdminPresentation(friendlyName = "ProductImpl_Product_Url", order = Presentation.FieldOrder.URL,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
prominent = true, gridOrder = 3, columnWidth = "200px",
requiredOverride = RequiredOverride.REQUIRED,
validationConfigurations = { @ValidationConfiguration(validationImplementation = "blUriPropertyValidator") })
protected String url;
@Column(name = "URL_KEY")
@AdminPresentation(friendlyName = "ProductImpl_Product_UrlKey",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
excluded = true)
protected String urlKey;
@Column(name = "DISPLAY_TEMPLATE")
@AdminPresentation(friendlyName = "ProductImpl_Product_Display_Template",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected String displayTemplate;
@Column(name = "MODEL")
@AdminPresentation(friendlyName = "ProductImpl_Product_Model",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected String model;
@Column(name = "MANUFACTURE")
@AdminPresentation(friendlyName = "ProductImpl_Product_Manufacturer", order = Presentation.FieldOrder.MANUFACTURER,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
prominent = true, gridOrder = 4)
protected String manufacturer;
@Column(name = "TAX_CODE")
protected String taxCode;
@Column(name = "IS_FEATURED_PRODUCT", nullable=false)
@AdminPresentation(friendlyName = "ProductImpl_Is_Featured_Product", requiredOverride = RequiredOverride.NOT_REQUIRED,
tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
group = Presentation.Group.Name.Badges, groupOrder = Presentation.Group.Order.Badges)
protected Boolean isFeaturedProduct = false;
@OneToOne(optional = false, targetEntity = SkuImpl.class, cascade={CascadeType.ALL}, mappedBy = "defaultProduct")
@Cascade(value={org.hibernate.annotations.CascadeType.ALL})
protected Sku defaultSku;
@Column(name = "CAN_SELL_WITHOUT_OPTIONS")
@AdminPresentation(friendlyName = "ProductImpl_Can_Sell_Without_Options",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced)
protected Boolean canSellWithoutOptions = false;
@Transient
protected List<Sku> skus = new ArrayList<Sku>();
@Transient
protected String promoMessage;
@OneToMany(mappedBy = "product", targetEntity = CrossSaleProductImpl.class, cascade = {CascadeType.ALL})
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@OrderBy(value="sequence")
@AdminPresentationAdornedTargetCollection(friendlyName = "crossSaleProductsTitle", order = 1000,
tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
targetObjectProperty = "relatedSaleProduct",
sortProperty = "sequence",
maintainedAdornedTargetFields = { "promotionMessage" },
gridVisibleFields = { "defaultSku.name", "promotionMessage" })
protected List<RelatedProduct> crossSaleProducts = new ArrayList<RelatedProduct>();
@OneToMany(mappedBy = "product", targetEntity = UpSaleProductImpl.class, cascade = {CascadeType.ALL})
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@OrderBy(value="sequence")
@AdminPresentationAdornedTargetCollection(friendlyName = "upsaleProductsTitle", order = 2000,
tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
targetObjectProperty = "relatedSaleProduct",
sortProperty = "sequence",
maintainedAdornedTargetFields = { "promotionMessage" },
gridVisibleFields = { "defaultSku.name", "promotionMessage" })
protected List<RelatedProduct> upSaleProducts = new ArrayList<RelatedProduct>();
@OneToMany(fetch = FetchType.LAZY, targetEntity = SkuImpl.class, mappedBy="product")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationCollection(friendlyName="ProductImpl_Additional_Skus", order = 1000,
tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions)
protected List<Sku> additionalSkus = new ArrayList<Sku>();
@ManyToOne(targetEntity = CategoryImpl.class)
@JoinColumn(name = "DEFAULT_CATEGORY_ID")
@Index(name="PRODUCT_CATEGORY_INDEX", columnNames={"DEFAULT_CATEGORY_ID"})
@AdminPresentation(friendlyName = "ProductImpl_Product_Default_Category", order = Presentation.FieldOrder.DEFAULT_CATEGORY,
group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General,
prominent = true, gridOrder = 2,
requiredOverride = RequiredOverride.REQUIRED)
@AdminPresentationToOneLookup()
protected Category defaultCategory;
@OneToMany(targetEntity = CategoryProductXrefImpl.class, mappedBy = "categoryProductXref.product")
@Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST})
@OrderBy(value="displayOrder")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationAdornedTargetCollection(friendlyName = "allParentCategoriesTitle", order = 3000,
tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing,
joinEntityClass = "org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl",
targetObjectProperty = "categoryProductXref.category",
parentObjectProperty = "categoryProductXref.product",
sortProperty = "displayOrder",
gridVisibleFields = { "name" })
protected List<CategoryProductXref> allParentCategoryXrefs = new ArrayList<CategoryProductXref>();
@OneToMany(mappedBy = "product", targetEntity = ProductAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blStandardElements")
@MapKey(name="name")
@BatchSize(size = 50)
@AdminPresentationMap(friendlyName = "productAttributesTitle",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced,
deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "ProductAttributeImpl_Attribute_Name"
)
protected Map<String, ProductAttribute> productAttributes = new HashMap<String, ProductAttribute>();
@ManyToMany(fetch = FetchType.LAZY, targetEntity = ProductOptionImpl.class)
@JoinTable(name = "BLC_PRODUCT_OPTION_XREF",
joinColumns = @JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID"),
inverseJoinColumns = @JoinColumn(name = "PRODUCT_OPTION_ID", referencedColumnName = "PRODUCT_OPTION_ID"))
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
@AdminPresentationCollection(friendlyName = "productOptionsTitle",
tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions,
addType = AddMethodType.LOOKUP,
manyToField = "products",
operationTypes = @AdminPresentationOperationTypes(removeType = OperationType.NONDESTRUCTIVEREMOVE))
protected List<ProductOption> productOptions = new ArrayList<ProductOption>();
@Embedded
protected ArchiveStatus archiveStatus = new ArchiveStatus();
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getName() {
return getDefaultSku().getName();
}
@Override
public void setName(String name) {
getDefaultSku().setName(name);
}
@Override
public String getDescription() {
return getDefaultSku().getDescription();
}
@Override
public void setDescription(String description) {
getDefaultSku().setDescription(description);
}
@Override
public String getLongDescription() {
return getDefaultSku().getLongDescription();
}
@Override
public void setLongDescription(String longDescription) {
getDefaultSku().setLongDescription(longDescription);
}
@Override
public Date getActiveStartDate() {
return getDefaultSku().getActiveStartDate();
}
@Override
public void setActiveStartDate(Date activeStartDate) {
getDefaultSku().setActiveStartDate(activeStartDate);
}
@Override
public Date getActiveEndDate() {
return getDefaultSku().getActiveEndDate();
}
@Override
public void setActiveEndDate(Date activeEndDate) {
getDefaultSku().setActiveEndDate(activeEndDate);
}
@Override
public boolean isActive() {
if (LOG.isDebugEnabled()) {
if (!DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true)) {
LOG.debug("product, " + id + ", inactive due to date");
}
if ('Y'==getArchived()) {
LOG.debug("product, " + id + ", inactive due to archived status");
}
}
return DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true) && 'Y'!=getArchived();
}
@Override
public String getModel() {
return model;
}
@Override
public void setModel(String model) {
this.model = model;
}
@Override
public String getManufacturer() {
return manufacturer;
}
@Override
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
@Override
public boolean isFeaturedProduct() {
return isFeaturedProduct;
}
@Override
public void setFeaturedProduct(boolean isFeaturedProduct) {
this.isFeaturedProduct = isFeaturedProduct;
}
@Override
public Sku getDefaultSku() {
return defaultSku;
}
@Override
public Boolean getCanSellWithoutOptions() {
return canSellWithoutOptions == null ? false : canSellWithoutOptions;
}
@Override
public void setCanSellWithoutOptions(Boolean canSellWithoutOptions) {
this.canSellWithoutOptions = canSellWithoutOptions;
}
@Override
public void setDefaultSku(Sku defaultSku) {
defaultSku.setDefaultProduct(this);
this.defaultSku = defaultSku;
}
@Override
public String getPromoMessage() {
return promoMessage;
}
@Override
public void setPromoMessage(String promoMessage) {
this.promoMessage = promoMessage;
}
@Override
public List<Sku> getAllSkus() {
List<Sku> allSkus = new ArrayList<Sku>();
allSkus.add(getDefaultSku());
for (Sku additionalSku : additionalSkus) {
if (!additionalSku.getId().equals(getDefaultSku().getId())) {
allSkus.add(additionalSku);
}
}
return allSkus;
}
@Override
public List<Sku> getSkus() {
if (skus.size() == 0) {
List<Sku> additionalSkus = getAdditionalSkus();
for (Sku sku : additionalSkus) {
if (sku.isActive()) {
skus.add(sku);
}
}
}
return skus;
}
@Override
public List<Sku> getAdditionalSkus() {
return additionalSkus;
}
@Override
public void setAdditionalSkus(List<Sku> skus) {
this.additionalSkus.clear();
for(Sku sku : skus){
this.additionalSkus.add(sku);
}
//this.skus.clear();
}
@Override
public Category getDefaultCategory() {
return defaultCategory;
}
@Override
public Map<String, Media> getMedia() {
return getDefaultSku().getSkuMedia();
}
@Override
public void setMedia(Map<String, Media> media) {
getDefaultSku().setSkuMedia(media);
}
@Override
public Map<String, Media> getAllSkuMedia() {
Map<String, Media> result = new HashMap<String, Media>();
result.putAll(getMedia());
for (Sku additionalSku : getAdditionalSkus()) {
if (!additionalSku.getId().equals(getDefaultSku().getId())) {
result.putAll(additionalSku.getSkuMedia());
}
}
return result;
}
@Override
public void setDefaultCategory(Category defaultCategory) {
this.defaultCategory = defaultCategory;
}
@Override
public List<CategoryProductXref> getAllParentCategoryXrefs() {
return allParentCategoryXrefs;
}
@Override
public void setAllParentCategoryXrefs(List<CategoryProductXref> allParentCategories) {
this.allParentCategoryXrefs.clear();
allParentCategoryXrefs.addAll(allParentCategories);
}
@Override
@Deprecated
public List<Category> getAllParentCategories() {
List<Category> parents = new ArrayList<Category>();
for (CategoryProductXref xref : allParentCategoryXrefs) {
parents.add(xref.getCategory());
}
return Collections.unmodifiableList(parents);
}
@Override
@Deprecated
public void setAllParentCategories(List<Category> allParentCategories) {
throw new UnsupportedOperationException("Not Supported - Use setAllParentCategoryXrefs()");
}
@Override
public Dimension getDimension() {
return getDefaultSku().getDimension();
}
@Override
public void setDimension(Dimension dimension) {
getDefaultSku().setDimension(dimension);
}
@Override
public BigDecimal getWidth() {
return getDefaultSku().getDimension().getWidth();
}
@Override
public void setWidth(BigDecimal width) {
getDefaultSku().getDimension().setWidth(width);
}
@Override
public BigDecimal getHeight() {
return getDefaultSku().getDimension().getHeight();
}
@Override
public void setHeight(BigDecimal height) {
getDefaultSku().getDimension().setHeight(height);
}
@Override
public BigDecimal getDepth() {
return getDefaultSku().getDimension().getDepth();
}
@Override
public void setDepth(BigDecimal depth) {
getDefaultSku().getDimension().setDepth(depth);
}
@Override
public BigDecimal getGirth() {
return getDefaultSku().getDimension().getGirth();
}
@Override
public void setGirth(BigDecimal girth) {
getDefaultSku().getDimension().setGirth(girth);
}
@Override
public ContainerSizeType getSize() {
return getDefaultSku().getDimension().getSize();
}
@Override
public void setSize(ContainerSizeType size) {
getDefaultSku().getDimension().setSize(size);
}
@Override
public ContainerShapeType getContainer() {
return getDefaultSku().getDimension().getContainer();
}
@Override
public void setContainer(ContainerShapeType container) {
getDefaultSku().getDimension().setContainer(container);
}
@Override
public String getDimensionString() {
return getDefaultSku().getDimension().getDimensionString();
}
@Override
public Weight getWeight() {
return getDefaultSku().getWeight();
}
@Override
public void setWeight(Weight weight) {
getDefaultSku().setWeight(weight);
}
@Override
public List<RelatedProduct> getCrossSaleProducts() {
List<RelatedProduct> returnProducts = new ArrayList<RelatedProduct>();
if (crossSaleProducts != null) {
returnProducts.addAll(crossSaleProducts);
CollectionUtils.filter(returnProducts, new Predicate() {
@Override
public boolean evaluate(Object arg) {
return 'Y'!=((Status)((CrossSaleProductImpl) arg).getRelatedProduct()).getArchived();
}
});
}
return returnProducts;
}
@Override
public void setCrossSaleProducts(List<RelatedProduct> crossSaleProducts) {
this.crossSaleProducts.clear();
for(RelatedProduct relatedProduct : crossSaleProducts){
this.crossSaleProducts.add(relatedProduct);
}
}
@Override
public List<RelatedProduct> getUpSaleProducts() {
List<RelatedProduct> returnProducts = new ArrayList<RelatedProduct>();
if (upSaleProducts != null) {
returnProducts.addAll(upSaleProducts);
CollectionUtils.filter(returnProducts, new Predicate() {
@Override
public boolean evaluate(Object arg) {
return 'Y'!=((Status)((UpSaleProductImpl) arg).getRelatedProduct()).getArchived();
}
});
}
return returnProducts;
}
@Override
public void setUpSaleProducts(List<RelatedProduct> upSaleProducts) {
this.upSaleProducts.clear();
for(RelatedProduct relatedProduct : upSaleProducts){
this.upSaleProducts.add(relatedProduct);
}
this.upSaleProducts = upSaleProducts;
}
@Override
public List<RelatedProduct> getCumulativeCrossSaleProducts() {
List<RelatedProduct> returnProducts = getCrossSaleProducts();
if (defaultCategory != null) {
List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeCrossSaleProducts();
if (categoryProducts != null) {
returnProducts.addAll(categoryProducts);
}
}
Iterator<RelatedProduct> itr = returnProducts.iterator();
while(itr.hasNext()) {
RelatedProduct relatedProduct = itr.next();
if (relatedProduct.getRelatedProduct().equals(this)) {
itr.remove();
}
}
return returnProducts;
}
@Override
public List<RelatedProduct> getCumulativeUpSaleProducts() {
List<RelatedProduct> returnProducts = getUpSaleProducts();
if (defaultCategory != null) {
List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeUpSaleProducts();
if (categoryProducts != null) {
returnProducts.addAll(categoryProducts);
}
}
Iterator<RelatedProduct> itr = returnProducts.iterator();
while(itr.hasNext()) {
RelatedProduct relatedProduct = itr.next();
if (relatedProduct.getRelatedProduct().equals(this)) {
itr.remove();
}
}
return returnProducts;
}
@Override
public Map<String, ProductAttribute> getProductAttributes() {
return productAttributes;
}
@Override
public void setProductAttributes(Map<String, ProductAttribute> productAttributes) {
this.productAttributes = productAttributes;
}
@Override
public List<ProductOption> getProductOptions() {
return productOptions;
}
@Override
public void setProductOptions(List<ProductOption> productOptions) {
this.productOptions = productOptions;
}
@Override
public String getUrl() {
if (url == null) {
return getGeneratedUrl();
} else {
return url;
}
}
@Override
public void setUrl(String url) {
this.url = url;
}
@Override
public String getDisplayTemplate() {
return displayTemplate;
}
@Override
public void setDisplayTemplate(String displayTemplate) {
this.displayTemplate = displayTemplate;
}
@Override
public Character getArchived() {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
return archiveStatus.getArchived();
}
@Override
public void setArchived(Character archived) {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
archiveStatus.setArchived(archived);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((skus == null) ? 0 : skus.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;
ProductImpl other = (ProductImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (skus == null) {
if (other.skus != null)
return false;
} else if (!skus.equals(other.skus))
return false;
return true;
}
@Override
public String getUrlKey() {
if (urlKey != null) {
return urlKey;
} else {
if (getName() != null) {
String returnKey = getName().toLowerCase();
returnKey = returnKey.replaceAll(" ","-");
return returnKey.replaceAll("[^A-Za-z0-9/-]", "");
}
}
return null;
}
@Override
public void setUrlKey(String urlKey) {
this.urlKey = urlKey;
}
@Override
public String getGeneratedUrl() {
if (getDefaultCategory() != null && getDefaultCategory().getGeneratedUrl() != null) {
String generatedUrl = getDefaultCategory().getGeneratedUrl();
if (generatedUrl.endsWith("//")) {
return generatedUrl + getUrlKey();
} else {
return generatedUrl + "//" + getUrlKey();
}
}
return null;
}
@Override
public void clearDynamicPrices() {
for (Sku sku : getAllSkus()) {
sku.clearDynamicPrices();
}
}
@Override
public String getMainEntityName() {
String manufacturer = getManufacturer();
return StringUtils.isBlank(manufacturer) ? getName() : manufacturer + " " + getName();
}
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Marketing = "ProductImpl_Marketing_Tab";
public static final String Media = "SkuImpl_Media_Tab";
public static final String ProductOptions = "ProductImpl_Product_Options_Tab";
public static final String Inventory = "ProductImpl_Inventory_Tab";
public static final String Shipping = "ProductImpl_Shipping_Tab";
public static final String Advanced = "ProductImpl_Advanced_Tab";
}
public static class Order {
public static final int Marketing = 2000;
public static final int Media = 3000;
public static final int ProductOptions = 4000;
public static final int Inventory = 5000;
public static final int Shipping = 6000;
public static final int Advanced = 7000;
}
}
public static class Group {
public static class Name {
public static final String General = "ProductImpl_Product_Description";
public static final String Price = "SkuImpl_Price";
public static final String ActiveDateRange = "ProductImpl_Product_Active_Date_Range";
public static final String Advanced = "ProductImpl_Advanced";
public static final String Inventory = "SkuImpl_Sku_Inventory";
public static final String Badges = "ProductImpl_Badges";
public static final String Shipping = "ProductWeight_Shipping";
public static final String Financial = "ProductImpl_Financial";
}
public static class Order {
public static final int General = 1000;
public static final int Price = 2000;
public static final int ActiveDateRange = 3000;
public static final int Advanced = 1000;
public static final int Inventory = 1000;
public static final int Badges = 1000;
public static final int Shipping = 1000;
}
}
public static class FieldOrder {
public static final int NAME = 1000;
public static final int SHORT_DESCRIPTION = 2000;
public static final int PRIMARY_MEDIA = 3000;
public static final int LONG_DESCRIPTION = 4000;
public static final int DEFAULT_CATEGORY = 5000;
public static final int MANUFACTURER = 6000;
public static final int URL = 7000;
}
}
@Override
public String getTaxCode() {
if (StringUtils.isEmpty(taxCode) && getDefaultCategory() != null) {
return getDefaultCategory().getTaxCode();
}
return taxCode;
}
@Override
public void setTaxCode(String taxCode) {
this.taxCode = taxCode;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_ProductImpl.java
|
3,126 |
static class EngineSearcher implements Searcher {
private final String source;
private final IndexSearcher searcher;
private final SearcherManager manager;
private EngineSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
this.source = source;
this.searcher = searcher;
this.manager = manager;
}
@Override
public String source() {
return this.source;
}
@Override
public IndexReader reader() {
return searcher.getIndexReader();
}
@Override
public IndexSearcher searcher() {
return searcher;
}
@Override
public boolean release() throws ElasticsearchException {
try {
manager.release(searcher);
return true;
} catch (IOException e) {
return false;
} catch (AlreadyClosedException e) {
/* this one can happen if we already closed the
* underlying store / directory and we call into the
* IndexWriter to free up pending files. */
return false;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java
|
1,287 |
@Test
public class LocalPaginatedStorageMixCrashRestore {
private ODatabaseDocumentTx baseDocumentTx;
private ODatabaseDocumentTx testDocumentTx;
private File buildDir;
private AtomicInteger idGen = new AtomicInteger();
private OLockManager<Integer, Thread> idLockManager = new OLockManager<Integer, Thread>(true, 1000);
private ExecutorService executorService = Executors.newCachedThreadPool();
private Process process;
private ConcurrentSkipListSet<Integer> addedIds = new ConcurrentSkipListSet<Integer>();
private ConcurrentSkipListSet<Integer> updatedIds = new ConcurrentSkipListSet<Integer>();
private ConcurrentHashMap<Integer, Long> deletedIds = new ConcurrentHashMap<Integer, Long>();
@BeforeClass
public void beforeClass() throws Exception {
OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL1_SIZE.setValue(0);
OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL2_SIZE.setValue(0);
String buildDirectory = System.getProperty("buildDirectory", ".");
buildDirectory += "/localPaginatedStorageMixCrashRestore";
buildDir = new File(buildDirectory);
if (buildDir.exists())
buildDir.delete();
buildDir.mkdir();
String javaExec = System.getProperty("java.home") + "/bin/java";
System.setProperty("ORIENTDB_HOME", buildDirectory);
ProcessBuilder processBuilder = new ProcessBuilder(javaExec, "-Xmx2048m", "-classpath", System.getProperty("java.class.path"),
"-DORIENTDB_HOME=" + buildDirectory, RemoteDBRunner.class.getName());
processBuilder.inheritIO();
process = processBuilder.start();
Thread.sleep(5000);
}
public static final class RemoteDBRunner {
public static void main(String[] args) throws Exception {
OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL1_SIZE.setValue(0);
OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false);
OGlobalConfiguration.CACHE_LEVEL2_SIZE.setValue(0);
OServer server = OServerMain.create();
server.startup(RemoteDBRunner.class
.getResourceAsStream("/com/orientechnologies/orient/core/storage/impl/local/paginated/db-mix-config.xml"));
server.activate();
while (true)
;
}
}
@AfterClass
public void afterClass() {
testDocumentTx.drop();
baseDocumentTx.drop();
Assert.assertTrue(buildDir.delete());
}
@BeforeMethod
public void beforeMethod() {
baseDocumentTx = new ODatabaseDocumentTx("plocal:" + buildDir.getAbsolutePath() + "/baseLocalPaginatedStorageMixCrashRestore");
if (baseDocumentTx.exists()) {
baseDocumentTx.open("admin", "admin");
baseDocumentTx.drop();
}
baseDocumentTx.create();
testDocumentTx = new ODatabaseDocumentTx("remote:localhost:3500/testLocalPaginatedStorageMixCrashRestore");
testDocumentTx.open("admin", "admin");
}
public void testDocumentChanges() throws Exception {
createSchema(baseDocumentTx);
createSchema(testDocumentTx);
System.out.println("Schema was created.");
System.out.println("Document creation was started.");
createDocuments();
System.out.println("Document creation was finished.");
System.out.println("Start data changes.");
List<Future> futures = new ArrayList<Future>();
for (int i = 0; i < 1; i++) {
futures.add(executorService.submit(new DataChangeTask(baseDocumentTx, testDocumentTx)));
}
Thread.sleep(600000);
long lastTs = System.currentTimeMillis();
process.destroy();
for (Future future : futures) {
try {
future.get();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Data changes were stopped.");
System.out.println(addedIds.size() + " records were added. " + updatedIds.size() + " were updated. " + deletedIds.size()
+ " were deleted.");
testDocumentTx = new ODatabaseDocumentTx("plocal:" + buildDir.getAbsolutePath() + "/testLocalPaginatedStorageMixCrashRestore");
testDocumentTx.open("admin", "admin");
testDocumentTx.close();
testDocumentTx.open("admin", "admin");
System.out.println("Start documents comparison.");
compareDocuments(lastTs);
}
private void createSchema(ODatabaseDocumentTx dbDocumentTx) {
ODatabaseRecordThreadLocal.INSTANCE.set(dbDocumentTx);
OSchema schema = dbDocumentTx.getMetadata().getSchema();
if (!schema.existsClass("TestClass")) {
OClass testClass = schema.createClass("TestClass");
testClass.createProperty("id", OType.INTEGER);
testClass.createProperty("timestamp", OType.LONG);
testClass.createProperty("stringValue", OType.STRING);
testClass.createIndex("idIndex", OClass.INDEX_TYPE.UNIQUE, "id");
schema.save();
}
}
private void createDocuments() {
Random random = new Random();
for (int i = 0; i < 1000000; i++) {
final ODocument document = new ODocument("TestClass");
document.field("id", idGen.getAndIncrement());
document.field("timestamp", System.currentTimeMillis());
document.field("stringValue", "sfe" + random.nextLong());
saveDoc(document, baseDocumentTx, testDocumentTx);
addedIds.add(document.<Integer> field("id"));
if (i % 10000 == 0)
System.out.println(i + " documents were created.");
}
}
private void saveDoc(ODocument document, ODatabaseDocumentTx baseDB, ODatabaseDocumentTx testDB) {
ODatabaseRecordThreadLocal.INSTANCE.set(baseDB);
ODocument testDoc = new ODocument();
document.copyTo(testDoc);
document.save();
ODatabaseRecordThreadLocal.INSTANCE.set(testDB);
testDoc.save();
ODatabaseRecordThreadLocal.INSTANCE.set(baseDB);
}
private void compareDocuments(long lastTs) {
long minTs = Long.MAX_VALUE;
int clusterId = baseDocumentTx.getClusterIdByName("TestClass");
OStorage baseStorage = baseDocumentTx.getStorage();
OPhysicalPosition[] physicalPositions = baseStorage.ceilingPhysicalPositions(clusterId, new OPhysicalPosition(
OClusterPositionFactory.INSTANCE.valueOf(0)));
int recordsRestored = 0;
int recordsTested = 0;
while (physicalPositions.length > 0) {
final ORecordId rid = new ORecordId(clusterId);
for (OPhysicalPosition physicalPosition : physicalPositions) {
rid.clusterPosition = physicalPosition.clusterPosition;
ODatabaseRecordThreadLocal.INSTANCE.set(baseDocumentTx);
ODocument baseDocument = baseDocumentTx.load(rid);
int id = baseDocument.<Integer> field("id");
if (addedIds.contains(id)) {
ODatabaseRecordThreadLocal.INSTANCE.set(testDocumentTx);
List<ODocument> testDocuments = testDocumentTx.query(new OSQLSynchQuery<ODocument>("select from TestClass where id = "
+ baseDocument.field("id")));
if (testDocuments.size() == 0) {
if (((Long) baseDocument.field("timestamp")) < minTs)
minTs = baseDocument.field("timestamp");
} else {
ODocument testDocument = testDocuments.get(0);
Assert.assertEquals(testDocument.field("id"), baseDocument.field("id"));
Assert.assertEquals(testDocument.field("timestamp"), baseDocument.field("timestamp"));
Assert.assertEquals(testDocument.field("stringValue"), baseDocument.field("stringValue"));
recordsRestored++;
}
recordsTested++;
} else if (updatedIds.contains(id)) {
ODatabaseRecordThreadLocal.INSTANCE.set(testDocumentTx);
List<ODocument> testDocuments = testDocumentTx.query(new OSQLSynchQuery<ODocument>("select from TestClass where id = "
+ baseDocument.field("id")));
if (testDocuments.size() == 0) {
if (((Long) baseDocument.field("timestamp")) < minTs)
minTs = baseDocument.field("timestamp");
} else {
ODocument testDocument = testDocuments.get(0);
if (testDocument.field("timestamp").equals(baseDocument.field("timestamp"))
&& testDocument.field("stringValue").equals(baseDocument.field("stringValue"))) {
recordsRestored++;
} else {
if (((Long) baseDocument.field("timestamp")) < minTs)
minTs = baseDocument.field("timestamp");
}
}
recordsTested++;
}
if (recordsTested % 10000 == 0)
System.out.println(recordsTested + " were tested, " + recordsRestored + " were restored ...");
}
physicalPositions = baseStorage.higherPhysicalPositions(clusterId, physicalPositions[physicalPositions.length - 1]);
}
ODatabaseRecordThreadLocal.INSTANCE.set(testDocumentTx);
System.out.println("Check deleted records");
for (Map.Entry<Integer, Long> deletedEntry : deletedIds.entrySet()) {
int deletedId = deletedEntry.getKey();
List<ODocument> testDocuments = testDocumentTx.query(new OSQLSynchQuery<ODocument>("select from TestClass where id = "
+ deletedId));
if (!testDocuments.isEmpty()) {
if (deletedEntry.getValue() < minTs)
minTs = deletedEntry.getValue();
} else
recordsRestored++;
recordsTested++;
}
System.out.println("Deleted records were checked." + deletedIds.size() + " were verified.");
System.out.println(recordsRestored + " records were restored. Total records " + recordsTested
+ ". Max interval for lost records " + (lastTs - minTs));
}
public class DataChangeTask implements Callable<Void> {
private ODatabaseDocumentTx baseDB;
private ODatabaseDocumentTx testDB;
private Random random = new Random();
public DataChangeTask(ODatabaseDocumentTx baseDB, ODatabaseDocumentTx testDocumentTx) {
this.baseDB = new ODatabaseDocumentTx(baseDB.getURL());
this.testDB = new ODatabaseDocumentTx(testDocumentTx.getURL());
}
@Override
public Void call() throws Exception {
Random random = new Random();
baseDB.open("admin", "admin");
testDB.open("admin", "admin");
try {
while (true) {
double rndOutcome = random.nextDouble();
int actionType = -1;
if (rndOutcome <= 0.2) {
if (addedIds.size() + updatedIds.size() >= 100000)
actionType = 2;
else
actionType = 0;
} else if (rndOutcome > 0.2 && rndOutcome <= 0.6)
actionType = 1;
else if (rndOutcome > 0.6) {
if (addedIds.size() + updatedIds.size() <= 2000000)
actionType = 0;
else
actionType = 2;
}
switch (actionType) {
case 0:
createRecord();
break;
case 1:
updateRecord();
break;
case 2:
deleteRecord();
break;
default:
throw new IllegalStateException("Invalid action type " + actionType);
}
}
} finally {
baseDB.close();
testDB.close();
}
}
private void createRecord() {
final int idToCreate = idGen.getAndIncrement();
idLockManager.acquireLock(Thread.currentThread(), idToCreate, OLockManager.LOCK.EXCLUSIVE);
try {
final ODocument document = new ODocument("TestClass");
document.field("id", idToCreate);
document.field("timestamp", System.currentTimeMillis());
document.field("stringValue", "sfe" + random.nextLong());
saveDoc(document, baseDB, testDB);
addedIds.add(document.<Integer> field("id"));
} finally {
idLockManager.releaseLock(Thread.currentThread(), idToCreate, OLockManager.LOCK.EXCLUSIVE);
}
}
private void deleteRecord() {
int closeId = random.nextInt(idGen.get());
Integer idToDelete = addedIds.ceiling(closeId);
if (idToDelete == null)
idToDelete = addedIds.first();
idLockManager.acquireLock(Thread.currentThread(), idToDelete, OLockManager.LOCK.EXCLUSIVE);
while (deletedIds.containsKey(idToDelete)) {
idLockManager.releaseLock(Thread.currentThread(), idToDelete, OLockManager.LOCK.EXCLUSIVE);
closeId = random.nextInt(idGen.get());
idToDelete = addedIds.ceiling(closeId);
if (idToDelete == null)
idToDelete = addedIds.first();
idLockManager.acquireLock(Thread.currentThread(), idToDelete, OLockManager.LOCK.EXCLUSIVE);
}
addedIds.remove(idToDelete);
updatedIds.remove(idToDelete);
ODatabaseRecordThreadLocal.INSTANCE.set(baseDB);
int deleted = baseDB.command(new OCommandSQL("delete from TestClass where id = " + idToDelete)).execute();
Assert.assertEquals(deleted, 1);
ODatabaseRecordThreadLocal.INSTANCE.set(testDB);
deleted = testDB.command(new OCommandSQL("delete from TestClass where id = " + idToDelete)).execute();
Assert.assertEquals(deleted, 1);
ODatabaseRecordThreadLocal.INSTANCE.set(baseDB);
long ts = System.currentTimeMillis();
deletedIds.put(idToDelete, ts);
idLockManager.releaseLock(Thread.currentThread(), idToDelete, OLockManager.LOCK.EXCLUSIVE);
}
private void updateRecord() {
int closeId = random.nextInt(idGen.get());
Integer idToUpdate = addedIds.ceiling(closeId);
if (idToUpdate == null)
idToUpdate = addedIds.first();
idLockManager.acquireLock(Thread.currentThread(), idToUpdate, OLockManager.LOCK.EXCLUSIVE);
while (deletedIds.containsKey(idToUpdate)) {
idLockManager.releaseLock(Thread.currentThread(), idToUpdate, OLockManager.LOCK.EXCLUSIVE);
closeId = random.nextInt(idGen.get());
idToUpdate = addedIds.ceiling(closeId);
if (idToUpdate == null)
idToUpdate = addedIds.first();
idLockManager.acquireLock(Thread.currentThread(), idToUpdate, OLockManager.LOCK.EXCLUSIVE);
}
addedIds.remove(idToUpdate);
List<ODocument> documentsToUpdate = baseDB.query(new OSQLSynchQuery<ODocument>("select from TestClass where id = "
+ idToUpdate));
Assert.assertTrue(!documentsToUpdate.isEmpty());
final ODocument documentToUpdate = documentsToUpdate.get(0);
documentToUpdate.field("timestamp", System.currentTimeMillis());
documentToUpdate.field("stringValue", "vde" + random.nextLong());
saveDoc(documentToUpdate, baseDB, testDB);
updatedIds.add(idToUpdate);
idLockManager.releaseLock(Thread.currentThread(), idToUpdate, OLockManager.LOCK.EXCLUSIVE);
}
}
}
| 1no label
|
server_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_LocalPaginatedStorageMixCrashRestore.java
|
279 |
public interface EmailServiceProducer {
public void send(@SuppressWarnings("rawtypes") final HashMap props);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_service_message_EmailServiceProducer.java
|
220 |
new Thread(){
public void run() {
for (int i=0; i<20; i++){
l.countDown();
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_countdownlatch_ClientCountDownLatchTest.java
|
138 |
public class MissingLogDataException extends IOException
{
public MissingLogDataException()
{
super();
}
public MissingLogDataException( String message, Throwable cause )
{
super( message, cause );
}
public MissingLogDataException( String message )
{
super( message );
}
public MissingLogDataException( Throwable cause )
{
super( cause );
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_MissingLogDataException.java
|
421 |
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AdminPresentationToOneLookup {
/**
* <p>Optional - only required if the display property is other than "name"</p>
*
* <p>Specify the property on a lookup class that should be used as the value to display to the user in
* a form in the admin tool UI</p>
*
* @return the property on the lookup class containing the displayable value
*/
String lookupDisplayProperty() default "";
/**
* <p>Optional - only required if you need to specially handle crud operations for this
* specific collection on the server</p>
*
* <p>Custom string values that will be passed to the server during Read and Inspect operations on the
* entity lookup. This allows for the creation of a custom persistence handler to handle both
* inspect and fetch phase operations. Presumably, one could use this to
* somehow filter the list of records shown when the user interacts with the lookup widget in the
* admin UI.</p>
*
* @return the custom string array to pass to the server during CRUD operations
*/
String[] customCriteria() default {};
/**
* <p>Optional - only required if you want to make the field ignore caching</p>
*
* <p>Explicitly specify whether or not this field will use server-side
* caching during inspection</p>
*
* @return whether or not this field uses caching
*/
boolean useServerSideInspectionCache() default true;
/**
* <p>Optional - only required if you want to configure the lookup
* to be driven by a prepopulated dropdown instead of the standard
* lookup type, which is modal based.</p>
*
* <p>Define whether or not the lookup type for this field should be
* handled through a modal or through a dropdown</p>
*
* @return the item is looked up via a modal or dropdown
*/
LookupType lookupType() default LookupType.STANDARD;
/**
* <p>Optional - by setting this value to true, the admin will identify
* the properties that are inside the target of this to-one field. </p>
*
* <p>Typically, this is done if you want to expose a certain field as an
* AdminPresentationToOneLookup but also allow filtering on a property that
* resides inside of the target of this lookup.</p>
*
* @return whether or not to force population of the child properties
*/
boolean forcePopulateChildProperties() default false;
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationToOneLookup.java
|
487 |
public class ClearIndicesCacheAction extends IndicesAction<ClearIndicesCacheRequest, ClearIndicesCacheResponse, ClearIndicesCacheRequestBuilder> {
public static final ClearIndicesCacheAction INSTANCE = new ClearIndicesCacheAction();
public static final String NAME = "indices/cache/clear";
private ClearIndicesCacheAction() {
super(NAME);
}
@Override
public ClearIndicesCacheResponse newResponse() {
return new ClearIndicesCacheResponse();
}
@Override
public ClearIndicesCacheRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new ClearIndicesCacheRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_cache_clear_ClearIndicesCacheAction.java
|
69 |
public interface OResourcePoolListener<K, V> {
/**
* Creates a new resource to be used and to be pooled when the client finishes with it.
*
* @return The new resource
*/
public V createNewResource(K iKey, Object... iAdditionalArgs);
/**
* Reuses the pooled resource.
*
* @return true if can be reused, otherwise false. In this case the resource will be removed from the pool
*/
public boolean reuseResource(K iKey, Object[] iAdditionalArgs, V iValue);
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_resource_OResourcePoolListener.java
|
1,839 |
@Component("blUriPropertyValidator")
public class UriPropertyValidator extends ValidationConfigurationBasedPropertyValidator {
protected static final Log LOG = LogFactory.getLog(UriPropertyValidator.class);
protected String ERROR_KEY_BEGIN_WITH_SLASH = "uriPropertyValidatorMustBeginWithSlashError";
protected String ERROR_KEY_CANNOT_END_WITH_SLASH = "uriPropertyValidatorCannotEndWithSlashError";
@Value("${uriPropertyValidator.ignoreFullUrls}")
protected boolean ignoreFullUrls = true;
@Value("${uriPropertyValidator.requireLeadingSlash}")
protected boolean requireLeadingSlash = true;
@Value("${uriPropertyValidator.allowTrailingSlash}")
protected boolean allowTrailingSlash = false;
public boolean isFullUrl(String url) {
return (url.startsWith("http") || url.startsWith("ftp"));
}
/**
* Denotes what should occur when this validator encounters a null value to validate against. Default behavior is to
* allow them, which means that this validator will always return true with null values
*/
protected boolean succeedForNullValues = true;
@Override
public PropertyValidationResult validate(Entity entity,
Serializable instance,
Map<String, FieldMetadata> entityFieldMetadata,
Map<String, String> validationConfiguration,
BasicFieldMetadata propertyMetadata,
String propertyName,
String value) {
if (value == null) {
return new PropertyValidationResult(succeedForNullValues);
}
if (isFullUrl(value) && ignoreFullUrls) {
return new PropertyValidationResult(true);
}
if (requireLeadingSlash && !value.startsWith("/")) {
return new PropertyValidationResult(false, ERROR_KEY_BEGIN_WITH_SLASH);
}
if (!allowTrailingSlash && value.endsWith("/")) {
return new PropertyValidationResult(false, ERROR_KEY_CANNOT_END_WITH_SLASH);
}
return new PropertyValidationResult(true);
}
public boolean isSucceedForNullValues() {
return succeedForNullValues;
}
public void setSucceedForNullValues(boolean succeedForNullValues) {
this.succeedForNullValues = succeedForNullValues;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_validation_UriPropertyValidator.java
|
5,821 |
public class HighlighterParseElement implements SearchParseElement {
private static final String[] DEFAULT_PRE_TAGS = new String[]{"<em>"};
private static final String[] DEFAULT_POST_TAGS = new String[]{"</em>"};
private static final String[] STYLED_PRE_TAG = {
"<em class=\"hlt1\">", "<em class=\"hlt2\">", "<em class=\"hlt3\">",
"<em class=\"hlt4\">", "<em class=\"hlt5\">", "<em class=\"hlt6\">",
"<em class=\"hlt7\">", "<em class=\"hlt8\">", "<em class=\"hlt9\">",
"<em class=\"hlt10\">"
};
private static final String[] STYLED_POST_TAGS = {"</em>"};
@Override
public void parse(XContentParser parser, SearchContext context) throws Exception {
XContentParser.Token token;
String topLevelFieldName = null;
List<SearchContextHighlight.Field> fields = newArrayList();
String[] globalPreTags = DEFAULT_PRE_TAGS;
String[] globalPostTags = DEFAULT_POST_TAGS;
boolean globalScoreOrdered = false;
boolean globalHighlightFilter = false;
boolean globalRequireFieldMatch = false;
boolean globalForceSource = false;
int globalFragmentSize = 100;
int globalNumOfFragments = 5;
String globalEncoder = "default";
int globalBoundaryMaxScan = SimpleBoundaryScanner.DEFAULT_MAX_SCAN;
Character[] globalBoundaryChars = SimpleBoundaryScanner.DEFAULT_BOUNDARY_CHARS;
String globalHighlighterType = null;
String globalFragmenter = null;
Map<String, Object> globalOptions = null;
Query globalHighlightQuery = null;
int globalNoMatchSize = 0;
int globalPhraseLimit = 256;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
topLevelFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if ("pre_tags".equals(topLevelFieldName) || "preTags".equals(topLevelFieldName)) {
List<String> preTagsList = Lists.newArrayList();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
preTagsList.add(parser.text());
}
globalPreTags = preTagsList.toArray(new String[preTagsList.size()]);
} else if ("post_tags".equals(topLevelFieldName) || "postTags".equals(topLevelFieldName)) {
List<String> postTagsList = Lists.newArrayList();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
postTagsList.add(parser.text());
}
globalPostTags = postTagsList.toArray(new String[postTagsList.size()]);
}
} else if (token.isValue()) {
if ("order".equals(topLevelFieldName)) {
globalScoreOrdered = "score".equals(parser.text());
} else if ("tags_schema".equals(topLevelFieldName) || "tagsSchema".equals(topLevelFieldName)) {
String schema = parser.text();
if ("styled".equals(schema)) {
globalPreTags = STYLED_PRE_TAG;
globalPostTags = STYLED_POST_TAGS;
}
} else if ("highlight_filter".equals(topLevelFieldName) || "highlightFilter".equals(topLevelFieldName)) {
globalHighlightFilter = parser.booleanValue();
} else if ("fragment_size".equals(topLevelFieldName) || "fragmentSize".equals(topLevelFieldName)) {
globalFragmentSize = parser.intValue();
} else if ("number_of_fragments".equals(topLevelFieldName) || "numberOfFragments".equals(topLevelFieldName)) {
globalNumOfFragments = parser.intValue();
} else if ("encoder".equals(topLevelFieldName)) {
globalEncoder = parser.text();
} else if ("require_field_match".equals(topLevelFieldName) || "requireFieldMatch".equals(topLevelFieldName)) {
globalRequireFieldMatch = parser.booleanValue();
} else if ("boundary_max_scan".equals(topLevelFieldName) || "boundaryMaxScan".equals(topLevelFieldName)) {
globalBoundaryMaxScan = parser.intValue();
} else if ("boundary_chars".equals(topLevelFieldName) || "boundaryChars".equals(topLevelFieldName)) {
char[] charsArr = parser.text().toCharArray();
globalBoundaryChars = new Character[charsArr.length];
for (int i = 0; i < charsArr.length; i++) {
globalBoundaryChars[i] = charsArr[i];
}
} else if ("type".equals(topLevelFieldName)) {
globalHighlighterType = parser.text();
} else if ("fragmenter".equals(topLevelFieldName)) {
globalFragmenter = parser.text();
} else if ("no_match_size".equals(topLevelFieldName) || "noMatchSize".equals(topLevelFieldName)) {
globalNoMatchSize = parser.intValue();
} else if ("force_source".equals(topLevelFieldName) || "forceSource".equals(topLevelFieldName)) {
globalForceSource = parser.booleanValue();
} else if ("phrase_limit".equals(topLevelFieldName) || "phraseLimit".equals(topLevelFieldName)) {
globalPhraseLimit = parser.intValue();
}
} else if (token == XContentParser.Token.START_OBJECT && "options".equals(topLevelFieldName)) {
globalOptions = parser.map();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("fields".equals(topLevelFieldName)) {
String highlightFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
highlightFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
SearchContextHighlight.Field field = new SearchContextHighlight.Field(highlightFieldName);
String fieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
fieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if ("pre_tags".equals(fieldName) || "preTags".equals(fieldName)) {
List<String> preTagsList = Lists.newArrayList();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
preTagsList.add(parser.text());
}
field.preTags(preTagsList.toArray(new String[preTagsList.size()]));
} else if ("post_tags".equals(fieldName) || "postTags".equals(fieldName)) {
List<String> postTagsList = Lists.newArrayList();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
postTagsList.add(parser.text());
}
field.postTags(postTagsList.toArray(new String[postTagsList.size()]));
} else if ("matched_fields".equals(fieldName) || "matchedFields".equals(fieldName)) {
Set<String> matchedFields = Sets.newHashSet();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
matchedFields.add(parser.text());
}
field.matchedFields(matchedFields);
}
} else if (token.isValue()) {
if ("fragment_size".equals(fieldName) || "fragmentSize".equals(fieldName)) {
field.fragmentCharSize(parser.intValue());
} else if ("number_of_fragments".equals(fieldName) || "numberOfFragments".equals(fieldName)) {
field.numberOfFragments(parser.intValue());
} else if ("fragment_offset".equals(fieldName) || "fragmentOffset".equals(fieldName)) {
field.fragmentOffset(parser.intValue());
} else if ("highlight_filter".equals(fieldName) || "highlightFilter".equals(fieldName)) {
field.highlightFilter(parser.booleanValue());
} else if ("order".equals(fieldName)) {
field.scoreOrdered("score".equals(parser.text()));
} else if ("require_field_match".equals(fieldName) || "requireFieldMatch".equals(fieldName)) {
field.requireFieldMatch(parser.booleanValue());
} else if ("boundary_max_scan".equals(topLevelFieldName) || "boundaryMaxScan".equals(topLevelFieldName)) {
field.boundaryMaxScan(parser.intValue());
} else if ("boundary_chars".equals(topLevelFieldName) || "boundaryChars".equals(topLevelFieldName)) {
char[] charsArr = parser.text().toCharArray();
Character[] boundaryChars = new Character[charsArr.length];
for (int i = 0; i < charsArr.length; i++) {
boundaryChars[i] = charsArr[i];
}
field.boundaryChars(boundaryChars);
} else if ("type".equals(fieldName)) {
field.highlighterType(parser.text());
} else if ("fragmenter".equals(fieldName)) {
field.fragmenter(parser.text());
} else if ("no_match_size".equals(fieldName) || "noMatchSize".equals(fieldName)) {
field.noMatchSize(parser.intValue());
} else if ("force_source".equals(fieldName) || "forceSource".equals(fieldName)) {
field.forceSource(parser.booleanValue());
} else if ("phrase_limit".equals(fieldName) || "phraseLimit".equals(fieldName)) {
field.phraseLimit(parser.intValue());
}
} else if (token == XContentParser.Token.START_OBJECT) {
if ("highlight_query".equals(fieldName) || "highlightQuery".equals(fieldName)) {
field.highlightQuery(context.queryParserService().parse(parser).query());
} else if (fieldName.equals("options")) {
field.options(parser.map());
}
}
}
fields.add(field);
}
}
} else if ("highlight_query".equals(topLevelFieldName) || "highlightQuery".equals(topLevelFieldName)) {
globalHighlightQuery = context.queryParserService().parse(parser).query();
}
}
}
if (globalPreTags != null && globalPostTags == null) {
throw new SearchParseException(context, "Highlighter global preTags are set, but global postTags are not set");
}
// now, go over and fill all fields with default values from the global state
for (SearchContextHighlight.Field field : fields) {
if (field.preTags() == null) {
field.preTags(globalPreTags);
}
if (field.postTags() == null) {
field.postTags(globalPostTags);
}
if (field.highlightFilter() == null) {
field.highlightFilter(globalHighlightFilter);
}
if (field.scoreOrdered() == null) {
field.scoreOrdered(globalScoreOrdered);
}
if (field.fragmentCharSize() == -1) {
field.fragmentCharSize(globalFragmentSize);
}
if (field.numberOfFragments() == -1) {
field.numberOfFragments(globalNumOfFragments);
}
if (field.encoder() == null) {
field.encoder(globalEncoder);
}
if (field.requireFieldMatch() == null) {
field.requireFieldMatch(globalRequireFieldMatch);
}
if (field.boundaryMaxScan() == -1) {
field.boundaryMaxScan(globalBoundaryMaxScan);
}
if (field.boundaryChars() == null) {
field.boundaryChars(globalBoundaryChars);
}
if (field.highlighterType() == null) {
field.highlighterType(globalHighlighterType);
}
if (field.fragmenter() == null) {
field.fragmenter(globalFragmenter);
}
if (field.options() == null || field.options().size() == 0) {
field.options(globalOptions);
}
if (field.highlightQuery() == null && globalHighlightQuery != null) {
field.highlightQuery(globalHighlightQuery);
}
if (field.noMatchSize() == -1) {
field.noMatchSize(globalNoMatchSize);
}
if (field.forceSource() == null) {
field.forceSource(globalForceSource);
}
if (field.phraseLimit() == -1) {
field.phraseLimit(globalPhraseLimit);
}
}
context.highlight(new SearchContextHighlight(fields));
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_highlight_HighlighterParseElement.java
|
159 |
private abstract class AbstractItr implements Iterator<E> {
/**
* Next node to return item for.
*/
private Node<E> nextNode;
/**
* nextItem holds on to item fields because once we claim
* that an element exists in hasNext(), we must return it in
* the following next() call even if it was in the process of
* being removed when hasNext() was called.
*/
private E nextItem;
/**
* Node returned by most recent call to next. Needed by remove.
* Reset to null if this element is deleted by a call to remove.
*/
private Node<E> lastRet;
abstract Node<E> startNode();
abstract Node<E> nextNode(Node<E> p);
AbstractItr() {
advance();
}
/**
* Sets nextNode and nextItem to next valid node, or to null
* if no such.
*/
private void advance() {
lastRet = nextNode;
Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
for (;; p = nextNode(p)) {
if (p == null) {
// p might be active end or TERMINATOR node; both are OK
nextNode = null;
nextItem = null;
break;
}
E item = p.item;
if (item != null) {
nextNode = p;
nextItem = item;
break;
}
}
}
public boolean hasNext() {
return nextItem != null;
}
public E next() {
E item = nextItem;
if (item == null) throw new NoSuchElementException();
advance();
return item;
}
public void remove() {
Node<E> l = lastRet;
if (l == null) throw new IllegalStateException();
l.item = null;
unlink(l);
lastRet = null;
}
}
| 0true
|
src_main_java_jsr166y_ConcurrentLinkedDeque.java
|
858 |
public class AlterAndGetOperation extends AbstractAlterOperation {
public AlterAndGetOperation() {
}
public AlterAndGetOperation(String name, Data function) {
super(name, function);
}
@Override
public void run() throws Exception {
NodeEngine nodeEngine = getNodeEngine();
IFunction f = nodeEngine.toObject(function);
ReferenceWrapper reference = getReference();
Object input = nodeEngine.toObject(reference.get());
//noinspection unchecked
Object output = f.apply(input);
shouldBackup = !isEquals(input, output);
if (shouldBackup) {
backup = nodeEngine.toData(output);
reference.set(backup);
}
response = output;
}
@Override
public int getId() {
return AtomicReferenceDataSerializerHook.ALTER_AND_GET;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_AlterAndGetOperation.java
|
514 |
public class IndicesExistsAction extends IndicesAction<IndicesExistsRequest, IndicesExistsResponse, IndicesExistsRequestBuilder> {
public static final IndicesExistsAction INSTANCE = new IndicesExistsAction();
public static final String NAME = "indices/exists";
private IndicesExistsAction() {
super(NAME);
}
@Override
public IndicesExistsResponse newResponse() {
return new IndicesExistsResponse();
}
@Override
public IndicesExistsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new IndicesExistsRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_exists_indices_IndicesExistsAction.java
|
2,549 |
public final class ClassLoaderUtil {
public static final String HAZELCAST_BASE_PACKAGE = "com.hazelcast.";
public static final String HAZELCAST_ARRAY = "[L" + HAZELCAST_BASE_PACKAGE;
private static final Map<String, Class> PRIMITIVE_CLASSES;
private static final int MAX_PRIM_CLASSNAME_LENGTH = 7;
private static final ConstructorCache CONSTRUCTOR_CACHE = new ConstructorCache();
static {
final Map<String, Class> primitives = new HashMap<String, Class>(10, 1.0f);
primitives.put("boolean", boolean.class);
primitives.put("byte", byte.class);
primitives.put("int", int.class);
primitives.put("long", long.class);
primitives.put("short", short.class);
primitives.put("float", float.class);
primitives.put("double", double.class);
primitives.put("char", char.class);
primitives.put("void", void.class);
PRIMITIVE_CLASSES = Collections.unmodifiableMap(primitives);
}
private ClassLoaderUtil() {
}
public static <T> T newInstance(ClassLoader classLoader, final String className)
throws Exception {
classLoader = classLoader == null ? ClassLoaderUtil.class.getClassLoader() : classLoader;
Constructor<T> constructor = CONSTRUCTOR_CACHE.get(classLoader, className);
if (constructor != null) {
return constructor.newInstance();
}
Class<T> klass = (Class<T>) loadClass(classLoader, className);
return (T) newInstance(klass, classLoader, className);
}
public static <T> T newInstance(Class<T> klass, ClassLoader classLoader, String className)
throws Exception {
final Constructor<T> constructor = klass.getDeclaredConstructor();
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
CONSTRUCTOR_CACHE.put(classLoader, className, constructor);
return constructor.newInstance();
}
public static Class<?> loadClass(final ClassLoader classLoader, final String className)
throws ClassNotFoundException {
ValidationUtil.isNotNull(className, "className");
if (className.length() <= MAX_PRIM_CLASSNAME_LENGTH && Character.isLowerCase(className.charAt(0))) {
final Class primitiveClass = PRIMITIVE_CLASSES.get(className);
if (primitiveClass != null) {
return primitiveClass;
}
}
ClassLoader theClassLoader = classLoader;
if (theClassLoader == null) {
theClassLoader = Thread.currentThread().getContextClassLoader();
}
// First try to load it through the given classloader
if (theClassLoader != null) {
try {
return tryLoadClass(className, theClassLoader);
} catch (ClassNotFoundException ignore) {
// Reset selected classloader and try with others
theClassLoader = null;
}
}
// If failed and this is a Hazelcast class try again with our classloader
if (className.startsWith(HAZELCAST_BASE_PACKAGE) || className.startsWith(HAZELCAST_ARRAY)) {
theClassLoader = ClassLoaderUtil.class.getClassLoader();
}
if (theClassLoader == null) {
theClassLoader = Thread.currentThread().getContextClassLoader();
}
if (theClassLoader != null) {
return tryLoadClass(className, theClassLoader);
}
return Class.forName(className);
}
private static Class<?> tryLoadClass(String className, ClassLoader classLoader)
throws ClassNotFoundException {
if (className.startsWith("[")) {
return Class.forName(className, false, classLoader);
} else {
return classLoader.loadClass(className);
}
}
public static boolean isInternalType(Class type) {
String name = type.getName();
ClassLoader classLoader = ClassLoaderUtil.class.getClassLoader();
return type.getClassLoader() == classLoader && name.startsWith(HAZELCAST_BASE_PACKAGE);
}
private static final class ConstructorCache {
private final ConcurrentMap<ClassLoader, ConcurrentMap<String, WeakReference<Constructor>>> cache;
private ConstructorCache() {
// Guess 16 classloaders to not waste to much memory (16 is default concurrency level)
cache = new ConcurrentReferenceHashMap<ClassLoader, ConcurrentMap<String, WeakReference<Constructor>>>(16);
}
private <T> Constructor put(ClassLoader classLoader, String className, Constructor<T> constructor) {
ClassLoader cl = classLoader == null ? ClassLoaderUtil.class.getClassLoader() : classLoader;
ConcurrentMap<String, WeakReference<Constructor>> innerCache = cache.get(cl);
if (innerCache == null) {
// Let's guess a start of 100 classes per classloader
innerCache = new ConcurrentHashMap<String, WeakReference<Constructor>>(100);
ConcurrentMap<String, WeakReference<Constructor>> old = cache.putIfAbsent(cl, innerCache);
if (old != null) {
innerCache = old;
}
}
innerCache.put(className, new WeakReference<Constructor>(constructor));
return constructor;
}
public <T> Constructor<T> get(ClassLoader classLoader, String className) {
ConcurrentMap<String, WeakReference<Constructor>> innerCache = cache.get(classLoader);
if (innerCache == null) {
return null;
}
WeakReference<Constructor> reference = innerCache.get(className);
Constructor constructor = reference == null ? null : reference.get();
if (reference != null && constructor == null) {
innerCache.remove(className);
}
return (Constructor<T>) constructor;
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_ClassLoaderUtil.java
|
505 |
public class OEngineLocal extends OEngineAbstract {
public static final String NAME = "local";
private static final AtomicBoolean memoryLocked = new AtomicBoolean(false);
public OStorage createStorage(final String iDbName, final Map<String, String> iConfiguration) {
if (memoryLocked.compareAndSet(false, true)) {
lockMemory();
}
try {
// GET THE STORAGE
return new OStorageLocal(iDbName, iDbName, getMode(iConfiguration));
} catch (Throwable t) {
OLogManager.instance().error(this,
"Error on opening database: " + iDbName + ". Current location is: " + new java.io.File(".").getAbsolutePath(), t,
ODatabaseException.class);
}
return null;
}
private void lockMemory() {
if (!OGlobalConfiguration.FILE_MMAP_USE_OLD_MANAGER.getValueAsBoolean()
&& OGlobalConfiguration.FILE_MMAP_LOCK_MEMORY.getValueAsBoolean()) {
// lock memory
try {
Class<?> MemoryLocker = ClassLoader.getSystemClassLoader().loadClass("com.orientechnologies.nio.MemoryLocker");
Method lockMemory = MemoryLocker.getMethod("lockMemory", boolean.class);
lockMemory.invoke(null, OGlobalConfiguration.JNA_DISABLE_USE_SYSTEM_LIBRARY.getValueAsBoolean());
} catch (ClassNotFoundException e) {
OLogManager
.instance()
.config(
null,
"[OEngineLocal.createStorage] Cannot lock virtual memory, the orientdb-nativeos.jar is not in classpath or there is not a native implementation for the current OS: "
+ System.getProperty("os.name") + " v." + System.getProperty("os.name"));
} catch (InvocationTargetException e) {
OLogManager
.instance()
.config(
null,
"[OEngineLocal.createStorage] Cannot lock virtual memory, the orientdb-nativeos.jar is not in classpath or there is not a native implementation for the current OS: "
+ System.getProperty("os.name") + " v." + System.getProperty("os.name"));
} catch (NoSuchMethodException e) {
throw new OMemoryLockException("Error while locking memory", e);
} catch (IllegalAccessException e) {
throw new OMemoryLockException("Error while locking memory", e);
}
}
}
public String getName() {
return NAME;
}
public boolean isShared() {
return true;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_engine_local_OEngineLocal.java
|
123 |
class FindImportNodeVisitor extends Visitor {
private final String[] packageNameComponents;
private Tree.Import result;
public FindImportNodeVisitor(String packageName) {
super();
this.packageNameComponents = packageName.split("\\.");
}
public Tree.Import getResult() {
return result;
}
public void visit(Tree.Import that) {
if (result != null) {
return;
}
List<Tree.Identifier> identifiers = that.getImportPath().getIdentifiers();
if (identifiersEqual(identifiers, packageNameComponents)) {
result = that;
}
}
private static boolean identifiersEqual(List<Tree.Identifier> identifiers,
String[] components) {
if (identifiers.size() != components.length) {
return false;
}
for (int i = 0; i < components.length; i++) {
if (!identifiers.get(i).getText().equals(components[i])) {
return false;
}
}
return true;
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_FindImportNodeVisitor.java
|
3,104 |
public final class EngineSearcherTotalHitsMatcher extends TypeSafeMatcher<Engine.Searcher> {
private final Query query;
private final int totalHits;
public EngineSearcherTotalHitsMatcher(Query query, int totalHits) {
this.query = query;
this.totalHits = totalHits;
}
@Override
public boolean matchesSafely(Engine.Searcher searcher) {
try {
long count = Lucene.count(searcher.searcher(), query);
return count == totalHits;
} catch (IOException e) {
return false;
}
}
@Override
public void describeTo(Description description) {
description.appendText("total hits of size ").appendValue(totalHits).appendText(" with query ").appendValue(query);
}
public static Matcher<Engine.Searcher> engineSearcherTotalHits(Query query, int totalHits) {
return new EngineSearcherTotalHitsMatcher(query, totalHits);
}
public static Matcher<Engine.Searcher> engineSearcherTotalHits(int totalHits) {
return new EngineSearcherTotalHitsMatcher(Queries.newMatchAllQuery(), totalHits);
}
}
| 1no label
|
src_test_java_org_elasticsearch_index_engine_EngineSearcherTotalHitsMatcher.java
|
393 |
public class ClusterSearchShardsGroup implements Streamable, ToXContent {
private String index;
private int shardId;
ShardRouting[] shards;
ClusterSearchShardsGroup() {
}
public ClusterSearchShardsGroup(String index, int shardId, ShardRouting[] shards) {
this.index = index;
this.shardId = shardId;
this.shards = shards;
}
public static ClusterSearchShardsGroup readSearchShardsGroupResponse(StreamInput in) throws IOException {
ClusterSearchShardsGroup response = new ClusterSearchShardsGroup();
response.readFrom(in);
return response;
}
public String getIndex() {
return index;
}
public int getShardId() {
return shardId;
}
public ShardRouting[] getShards() {
return shards;
}
@Override
public void readFrom(StreamInput in) throws IOException {
index = in.readString();
shardId = in.readVInt();
shards = new ShardRouting[in.readVInt()];
for (int i = 0; i < shards.length; i++) {
shards[i] = ImmutableShardRouting.readShardRoutingEntry(in, index, shardId);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(index);
out.writeVInt(shardId);
out.writeVInt(shards.length);
for (ShardRouting shardRouting : shards) {
shardRouting.writeToThin(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startArray();
for (ShardRouting shard : getShards()) {
shard.toXContent(builder, params);
}
builder.endArray();
return builder;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_shards_ClusterSearchShardsGroup.java
|
3,745 |
public class SessionAttributePredicate implements Predicate, IdentifiedDataSerializable {
private String sessionId;
// Serialization Constructor
public SessionAttributePredicate() {
}
public SessionAttributePredicate(String sessionId) {
this.sessionId = sessionId;
}
@Override
public boolean apply(Entry mapEntry) {
Object key = mapEntry.getKey();
if (key instanceof String) {
String k = (String) key;
return k.startsWith(sessionId + WebFilter.HAZELCAST_SESSION_ATTRIBUTE_SEPARATOR);
}
return false;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(sessionId);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
sessionId = in.readUTF();
}
@Override
public int getFactoryId() {
return WebDataSerializerHook.F_ID;
}
@Override
public int getId() {
return WebDataSerializerHook.SESSION_ATTRIBUTE_ID;
}
}
| 1no label
|
hazelcast-wm_src_main_java_com_hazelcast_web_SessionAttributePredicate.java
|
376 |
public class MetadataNamingStrategy extends org.springframework.jmx.export.naming.MetadataNamingStrategy {
public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException {
managedBean = AspectUtil.exposeRootBean(managedBean);
return super.getObjectName(managedBean, beanKey);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_jmx_MetadataNamingStrategy.java
|
60 |
public enum LOCK {
SHARED, EXCLUSIVE
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockManager.java
|
6,273 |
public class LessThanAssertion extends Assertion {
private static final ESLogger logger = Loggers.getLogger(LessThanAssertion.class);
public LessThanAssertion(String field, Object expectedValue) {
super(field, expectedValue);
}
@Override
@SuppressWarnings("unchecked")
protected void doAssert(Object actualValue, Object expectedValue) {
logger.trace("assert that [{}] is less than [{}]", actualValue, expectedValue);
assertThat(actualValue, instanceOf(Comparable.class));
assertThat(expectedValue, instanceOf(Comparable.class));
assertThat(errorMessage(), (Comparable)actualValue, lessThan((Comparable)expectedValue));
}
private String errorMessage() {
return "field [" + getField() + "] is not less than [" + getExpectedValue() + "]";
}
}
| 1no label
|
src_test_java_org_elasticsearch_test_rest_section_LessThanAssertion.java
|
446 |
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AdminPresentationMergeOverrides {
/**
* The new configurations for each field targeted for override
*
* @return field specific overrides
*/
AdminPresentationMergeOverride[] value();
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_presentation_override_AdminPresentationMergeOverrides.java
|
572 |
public class ODocumentFieldsHashSet extends AbstractSet<ODocument> {
private final LinkedHashSet<ODocumentWrapper> hashSet;
public ODocumentFieldsHashSet() {
hashSet = new LinkedHashSet<ODocumentWrapper>();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof ODocument))
return false;
return hashSet.contains(new ODocumentWrapper((ODocument) o));
}
@Override
public boolean remove(Object o) {
if (!(o instanceof ODocument))
return false;
return hashSet.remove(new ODocumentWrapper((ODocument) o));
}
@Override
public boolean add(ODocument document) {
return hashSet.add(new ODocumentWrapper(document));
}
@Override
public boolean isEmpty() {
return hashSet.isEmpty();
}
@Override
public void clear() {
hashSet.clear();
}
@Override
public Iterator<ODocument> iterator() {
final Iterator<ODocumentWrapper> iterator = hashSet.iterator();
return new Iterator<ODocument>() {
public boolean hasNext() {
return iterator.hasNext();
}
public ODocument next() {
return iterator.next().document;
}
public void remove() {
iterator.remove();
}
};
}
@Override
public int size() {
return hashSet.size();
}
private static final class ODocumentWrapper {
private final ODocument document;
private ODocumentWrapper(ODocument document) {
this.document = document;
}
@Override
public int hashCode() {
int hashCode = document.getIdentity().hashCode();
for (Object field : document.fieldValues())
hashCode = 31 * hashCode + field.hashCode();
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == document)
return true;
if (obj.getClass() != document.getClass())
return false;
final ODocument anotherDocument = (ODocument) obj;
if (!document.getIdentity().equals(anotherDocument.getIdentity()))
return false;
final String[] filedNames = document.fieldNames();
final String[] anotherFieldNames = anotherDocument.fieldNames();
if (filedNames.length != anotherFieldNames.length)
return false;
for (final String fieldName : filedNames) {
final Object fieldValue = document.field(fieldName);
final Object anotherFieldValue = anotherDocument.field(fieldName);
if (fieldValue == null && anotherFieldValue != null)
return false;
if (fieldValue != null && !fieldValue.equals(anotherFieldValue))
return false;
}
return true;
}
@Override
public String toString() {
return document.toString();
}
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_ODocumentFieldsHashSet.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
|
322 |
@SuppressWarnings("serial")
public class OStorageFileConfiguration implements Serializable {
public transient OStorageSegmentConfiguration parent;
public String path;
public String type = "mmap";
public String maxSize = null;
public String incrementSize = "50%";
public OStorageFileConfiguration() {
}
public OStorageFileConfiguration(final OStorageSegmentConfiguration iParent, final String iPath, final String iType,
final String iMaxSize, String iIncrementSize) {
parent = iParent;
path = iPath;
type = iType;
maxSize = iMaxSize;
incrementSize = iIncrementSize;
}
@Override
public String toString() {
return path;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_config_OStorageFileConfiguration.java
|
1,388 |
public static class Timestamp {
public static String parseStringTimestamp(String timestampAsString, FormatDateTimeFormatter dateTimeFormatter) throws TimestampParsingException {
long ts;
try {
// if we manage to parse it, its a millisecond timestamp, just return the string as is
ts = Long.parseLong(timestampAsString);
return timestampAsString;
} catch (NumberFormatException e) {
try {
ts = dateTimeFormatter.parser().parseMillis(timestampAsString);
} catch (RuntimeException e1) {
throw new TimestampParsingException(timestampAsString);
}
}
return Long.toString(ts);
}
public static final Timestamp EMPTY = new Timestamp(false, null, TimestampFieldMapper.DEFAULT_DATE_TIME_FORMAT);
private final boolean enabled;
private final String path;
private final String format;
private final String[] pathElements;
private final FormatDateTimeFormatter dateTimeFormatter;
public Timestamp(boolean enabled, String path, String format) {
this.enabled = enabled;
this.path = path;
if (path == null) {
pathElements = Strings.EMPTY_ARRAY;
} else {
pathElements = Strings.delimitedListToStringArray(path, ".");
}
this.format = format;
this.dateTimeFormatter = Joda.forPattern(format);
}
public boolean enabled() {
return enabled;
}
public boolean hasPath() {
return path != null;
}
public String path() {
return this.path;
}
public String[] pathElements() {
return this.pathElements;
}
public String format() {
return this.format;
}
public FormatDateTimeFormatter dateTimeFormatter() {
return this.dateTimeFormatter;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Timestamp timestamp = (Timestamp) o;
if (enabled != timestamp.enabled) return false;
if (dateTimeFormatter != null ? !dateTimeFormatter.equals(timestamp.dateTimeFormatter) : timestamp.dateTimeFormatter != null)
return false;
if (format != null ? !format.equals(timestamp.format) : timestamp.format != null) return false;
if (path != null ? !path.equals(timestamp.path) : timestamp.path != null) return false;
if (!Arrays.equals(pathElements, timestamp.pathElements)) return false;
return true;
}
@Override
public int hashCode() {
int result = (enabled ? 1 : 0);
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (format != null ? format.hashCode() : 0);
result = 31 * result + (pathElements != null ? Arrays.hashCode(pathElements) : 0);
result = 31 * result + (dateTimeFormatter != null ? dateTimeFormatter.hashCode() : 0);
return result;
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_metadata_MappingMetaData.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
|
1,057 |
public class TaxType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, TaxType> TYPES = new LinkedHashMap<String, TaxType>();
public static final TaxType CITY = new TaxType("CITY", "City");
public static final TaxType STATE = new TaxType("STATE", "State");
public static final TaxType DISTRICT = new TaxType("DISTRICT", "District");
public static final TaxType COUNTY = new TaxType("COUNTY", "County");
public static final TaxType COUNTRY = new TaxType("COUNTRY", "Country");
public static final TaxType SHIPPING = new TaxType("SHIPPING", "Shipping");
// Used by SimpleTaxModule to represent total taxes owed.
public static final TaxType COMBINED = new TaxType("COMBINED", "Combined");
public static TaxType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public TaxType() {
//do nothing
}
public TaxType(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;
TaxType other = (TaxType) 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_order_domain_TaxType.java
|
1,448 |
public static class Factory implements MetaData.Custom.Factory<SnapshotMetaData> {
@Override
public String type() {
return TYPE; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public SnapshotMetaData readFrom(StreamInput in) throws IOException {
Entry[] entries = new Entry[in.readVInt()];
for (int i = 0; i < entries.length; i++) {
SnapshotId snapshotId = SnapshotId.readSnapshotId(in);
boolean includeGlobalState = in.readBoolean();
State state = State.fromValue(in.readByte());
int indices = in.readVInt();
ImmutableList.Builder<String> indexBuilder = ImmutableList.builder();
for (int j = 0; j < indices; j++) {
indexBuilder.add(in.readString());
}
ImmutableMap.Builder<ShardId, ShardSnapshotStatus> builder = ImmutableMap.<ShardId, ShardSnapshotStatus>builder();
int shards = in.readVInt();
for (int j = 0; j < shards; j++) {
ShardId shardId = ShardId.readShardId(in);
String nodeId = in.readOptionalString();
State shardState = State.fromValue(in.readByte());
builder.put(shardId, new ShardSnapshotStatus(nodeId, shardState));
}
entries[i] = new Entry(snapshotId, includeGlobalState, state, indexBuilder.build(), builder.build());
}
return new SnapshotMetaData(entries);
}
@Override
public void writeTo(SnapshotMetaData repositories, StreamOutput out) throws IOException {
out.writeVInt(repositories.entries().size());
for (Entry entry : repositories.entries()) {
entry.snapshotId().writeTo(out);
out.writeBoolean(entry.includeGlobalState());
out.writeByte(entry.state().value());
out.writeVInt(entry.indices().size());
for (String index : entry.indices()) {
out.writeString(index);
}
out.writeVInt(entry.shards().size());
for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards().entrySet()) {
shardEntry.getKey().writeTo(out);
out.writeOptionalString(shardEntry.getValue().nodeId());
out.writeByte(shardEntry.getValue().state().value());
}
}
}
@Override
public SnapshotMetaData fromXContent(XContentParser parser) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void toXContent(SnapshotMetaData customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startArray("snapshots");
for (Entry entry : customIndexMetaData.entries()) {
toXContent(entry, builder, params);
}
builder.endArray();
}
public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject();
builder.field("repository", entry.snapshotId().getRepository());
builder.field("snapshot", entry.snapshotId().getSnapshot());
builder.field("include_global_state", entry.includeGlobalState());
builder.field("state", entry.state());
builder.startArray("indices");
{
for (String index : entry.indices()) {
builder.value(index);
}
}
builder.endArray();
builder.startArray("shards");
{
for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards.entrySet()) {
ShardId shardId = shardEntry.getKey();
ShardSnapshotStatus status = shardEntry.getValue();
builder.startObject();
{
builder.field("index", shardId.getIndex());
builder.field("shard", shardId.getId());
builder.field("state", status.state());
builder.field("node", status.nodeId());
}
builder.endObject();
}
}
builder.endArray();
builder.endObject();
}
public boolean isPersistent() {
return false;
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_SnapshotMetaData.java
|
599 |
ex.execute(new Runnable() {
public void run() {
try {
Thread.sleep(random.nextInt(10) * 1000);
final Config config = new Config();
config.setProperty("hazelcast.wait.seconds.before.join", "5");
String name = "group" + random.nextInt(groupCount);
groups.get(name).incrementAndGet();
config.getGroupConfig().setName(name);
final NetworkConfig networkConfig = config.getNetworkConfig();
networkConfig.getJoin().getMulticastConfig().setEnabled(false);
TcpIpConfig tcpIpConfig = networkConfig.getJoin().getTcpIpConfig();
tcpIpConfig.setEnabled(true);
int port = 12301;
networkConfig.setPortAutoIncrement(false);
networkConfig.setPort(port + seed);
for (int i = 0; i < count; i++) {
tcpIpConfig.addMember("127.0.0.1:" + (port + i));
}
HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
mapOfInstances.put(seed, h);
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
| 0true
|
hazelcast_src_test_java_com_hazelcast_cluster_JoinStressTest.java
|
407 |
@Test
public class TrackedListTest {
public void testAddNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 0);
Assert.assertEquals(event.getValue(), "value1");
changed.value = true;
}
});
trackedList.add("value1");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testAddNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 2);
Assert.assertEquals(event.getValue(), "value3");
changed.value = true;
}
});
trackedList.add("value3");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testAddNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
Assert.assertTrue(doc.isDirty());
}
public void testAddNotificationFour() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.add("value3");
Assert.assertEquals(changed.value, Boolean.FALSE);
Assert.assertFalse(doc.isDirty());
}
public void testAddAllNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final List<String> valuesToAdd = new ArrayList<String>();
valuesToAdd.add("value1");
valuesToAdd.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.ADD, 0, "value1"));
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.ADD, 1, "value3"));
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
if (firedEvents.get(0).equals(event))
firedEvents.remove(0);
else
Assert.fail();
}
});
trackedList.addAll(valuesToAdd);
Assert.assertEquals(firedEvents.size(), 0);
Assert.assertTrue(doc.isDirty());
}
public void testAddAllNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final List<String> valuesToAdd = new ArrayList<String>();
valuesToAdd.add("value1");
valuesToAdd.add("value3");
trackedList.addAll(valuesToAdd);
Assert.assertTrue(doc.isDirty());
}
public void testAddAllNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
final List<String> valuesToAdd = new ArrayList<String>();
valuesToAdd.add("value1");
valuesToAdd.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.addAll(valuesToAdd);
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testAddIndexNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertEquals(event.getValue(), "value3");
changed.value = true;
}
});
trackedList.add(1, "value3");
Assert.assertEquals(changed.value, Boolean.TRUE);
Assert.assertTrue(doc.isDirty());
}
public void testAddIndexNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.add(1, "value3");
Assert.assertTrue(doc.isDirty());
}
public void testAddIndexNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.add(1, "value3");
Assert.assertEquals(changed.value, Boolean.FALSE);
Assert.assertFalse(doc.isDirty());
}
public void testSetNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.UPDATE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertEquals(event.getValue(), "value4");
changed.value = true;
}
});
trackedList.set(1, "value4");
Assert.assertEquals(changed.value, Boolean.TRUE);
Assert.assertTrue(doc.isDirty());
}
public void testSetNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.set(1, "value4");
Assert.assertTrue(doc.isDirty());
}
public void testSetNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.set(1, "value4");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveNotificationOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertNull(event.getValue());
changed.value = true;
}
});
trackedList.remove("value2");
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testRemoveNotificationTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.remove("value2");
Assert.assertTrue(doc.isDirty());
}
public void testRemoveNotificationThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.remove("value2");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveNotificationFour() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.remove("value4");
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testRemoveIndexOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE);
Assert.assertEquals(event.getOldValue(), "value2");
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertNull(event.getValue());
changed.value = true;
}
});
trackedList.remove(1);
Assert.assertTrue(changed.value);
Assert.assertTrue(doc.isDirty());
}
public void testRemoveIndexTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.remove(1);
Assert.assertTrue(doc.isDirty());
}
public void testRemoveIndexThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.remove(1);
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testClearOne() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 2, null, "value3"));
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 1, null, "value2"));
firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 0, null, "value1"));
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
if (firedEvents.get(0).equals(event))
firedEvents.remove(0);
else
Assert.fail();
}
});
trackedList.clear();
Assert.assertEquals(0, firedEvents.size());
Assert.assertTrue(doc.isDirty());
}
public void testClearTwo() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
trackedList.clear();
Assert.assertTrue(doc.isDirty());
}
public void testClearThree() {
final ODocument doc = new ODocument();
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
doc.unsetDirty();
Assert.assertFalse(doc.isDirty());
final ORef<Boolean> changed = new ORef<Boolean>(false);
trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
changed.value = true;
}
});
trackedList.clear();
Assert.assertFalse(changed.value);
Assert.assertFalse(doc.isDirty());
}
public void testReturnOriginalStateOne() {
final ODocument doc = new ODocument();
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
trackedList.add("value4");
trackedList.add("value5");
final List<String> original = new ArrayList<String>(trackedList);
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
firedEvents.add(event);
}
});
trackedList.add("value6");
trackedList.add("value7");
trackedList.set(2, "value10");
trackedList.add(1, "value8");
trackedList.add(1, "value8");
trackedList.remove(3);
trackedList.remove("value7");
trackedList.add(0, "value9");
trackedList.add(0, "value9");
trackedList.add(0, "value9");
trackedList.add(0, "value9");
trackedList.remove("value9");
trackedList.remove("value9");
trackedList.add(4, "value11");
Assert.assertEquals(original, trackedList.returnOriginalState(firedEvents));
}
public void testReturnOriginalStateTwo() {
final ODocument doc = new ODocument();
final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
trackedList.add("value1");
trackedList.add("value2");
trackedList.add("value3");
trackedList.add("value4");
trackedList.add("value5");
final List<String> original = new ArrayList<String>(trackedList);
final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
firedEvents.add(event);
}
});
trackedList.add("value6");
trackedList.add("value7");
trackedList.set(2, "value10");
trackedList.add(1, "value8");
trackedList.remove(3);
trackedList.clear();
trackedList.remove("value7");
trackedList.add(0, "value9");
trackedList.add("value11");
trackedList.add(0, "value12");
trackedList.add("value12");
Assert.assertEquals(original, trackedList.returnOriginalState(firedEvents));
}
/**
* Test that {@link OTrackedList} is serialised correctly.
*/
@Test
public void testSerialization() throws Exception {
class NotSerializableDocument extends ODocument {
private static final long serialVersionUID = 1L;
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
}
final OTrackedList<String> beforeSerialization = new OTrackedList<String>(new NotSerializableDocument());
beforeSerialization.add("firstVal");
beforeSerialization.add("secondVal");
final OMemoryStream memoryStream = new OMemoryStream();
ObjectOutputStream out = new ObjectOutputStream(memoryStream);
out.writeObject(beforeSerialization);
out.close();
final ObjectInputStream input = new ObjectInputStream(new OMemoryInputStream(memoryStream.copy()));
@SuppressWarnings("unchecked")
final List<String> afterSerialization = (List<String>) input.readObject();
Assert.assertEquals(afterSerialization.size(), beforeSerialization.size(), "List size");
for (int i = 0; i < afterSerialization.size(); i++) {
Assert.assertEquals(afterSerialization.get(i), beforeSerialization.get(i));
}
}
}
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
|
1,112 |
public class SimpleGetActionBenchmark {
public static void main(String[] args) {
long OPERATIONS = SizeValue.parseSizeValue("300k").singles();
Node node = NodeBuilder.nodeBuilder().node();
Client client;
if (false) {
client = NodeBuilder.nodeBuilder().client(true).node().client();
} else {
client = node.client();
}
client.prepareIndex("test", "type1", "1").setSource("field1", "value1").execute().actionGet();
StopWatch stopWatch = new StopWatch().start();
for (long i = 0; i < OPERATIONS; i++) {
client.prepareGet("test", "type1", "1").execute().actionGet();
}
stopWatch.stop();
System.out.println("Ran in " + stopWatch.totalTime() + ", per second: " + (((double) OPERATIONS) / stopWatch.totalTime().secondsFrac()));
node.close();
}
}
| 0true
|
src_test_java_org_elasticsearch_benchmark_get_SimpleGetActionBenchmark.java
|
269 |
public class MapPutPartitionAwareCallable implements Callable, DataSerializable, PartitionAware, HazelcastInstanceAware {
private HazelcastInstance instance;
public String mapName;
public Object partitionKey;
public MapPutPartitionAwareCallable(){}
public MapPutPartitionAwareCallable(String mapName, Object partitionKey) {
this.mapName = mapName;
this.partitionKey = partitionKey;
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(mapName);
}
public void readData(ObjectDataInput in) throws IOException {
mapName = in.readUTF();
}
@Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
instance = hazelcastInstance;
}
public String getMapName() {
return mapName;
}
public void setMapName(String mapName) {
this.mapName = mapName;
}
@Override
public Object getPartitionKey() {
return partitionKey;
}
@Override
public Object call() throws Exception {
Member member = instance.getCluster().getLocalMember();
IMap map = instance.getMap(mapName);
map.put(member.getUuid(), member.getUuid()+"value");
return member.getUuid();
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_tasks_MapPutPartitionAwareCallable.java
|
137 |
public interface TitanManagement extends TitanConfiguration, SchemaManager {
/*
##################### RELATION TYPE INDEX ##########################
*/
/**
* Identical to {@link #buildEdgeIndex(com.thinkaurelius.titan.core.EdgeLabel, String, com.tinkerpop.blueprints.Direction, com.thinkaurelius.titan.core.Order, com.thinkaurelius.titan.core.RelationType...)}
* with default sort order {@link Order#ASC}.
*
* @param label
* @param name
* @param direction
* @param sortKeys
* @return the created {@link RelationTypeIndex}
*/
public RelationTypeIndex buildEdgeIndex(EdgeLabel label, String name, Direction direction, RelationType... sortKeys);
/**
* Creates a {@link RelationTypeIndex} for the provided edge label. That means, that all edges of that label will be
* indexed according to this index definition which will speed up certain vertex-centric queries.
* <p/>
* An indexed is defined by its name, the direction in which the index should be created (can be restricted to one
* direction or both), the sort order and - most importantly - the sort keys which define the index key.
*
* @param label
* @param name
* @param direction
* @param sortOrder
* @param sortKeys
* @return the created {@link RelationTypeIndex}
*/
public RelationTypeIndex buildEdgeIndex(EdgeLabel label, String name, Direction direction, Order sortOrder, RelationType... sortKeys);
/**
* Identical to {@link #buildPropertyIndex(com.thinkaurelius.titan.core.PropertyKey, String, com.thinkaurelius.titan.core.Order, com.thinkaurelius.titan.core.RelationType...)}
* with default sort order {@link Order#ASC}.
*
* @param key
* @param name
* @param sortKeys
* @return the created {@link RelationTypeIndex}
*/
public RelationTypeIndex buildPropertyIndex(PropertyKey key, String name, RelationType... sortKeys);
/**
* Creates a {@link RelationTypeIndex} for the provided property key. That means, that all properties of that key will be
* indexed according to this index definition which will speed up certain vertex-centric queries.
* <p/>
* An indexed is defined by its name, the sort order and - most importantly - the sort keys which define the index key.
*
* @param key
* @param name
* @param sortOrder
* @param sortKeys
* @return the created {@link RelationTypeIndex}
*/
public RelationTypeIndex buildPropertyIndex(PropertyKey key, String name, Order sortOrder, RelationType... sortKeys);
/**
* Whether a {@link RelationTypeIndex} with the given name has been defined for the provided {@link RelationType}
* @param type
* @param name
* @return
*/
public boolean containsRelationIndex(RelationType type, String name);
/**
* Returns the {@link RelationTypeIndex} with the given name for the provided {@link RelationType} or null
* if it does not exist
*
* @param type
* @param name
* @return
*/
public RelationTypeIndex getRelationIndex(RelationType type, String name);
/**
* Returns an {@link Iterable} over all {@link RelationTypeIndex}es defined for the provided {@link RelationType}
* @param type
* @return
*/
public Iterable<RelationTypeIndex> getRelationIndexes(RelationType type);
/*
##################### GRAPH INDEX ##########################
*/
/**
* Whether the graph has a graph index defined with the given name.
*
* @param name
* @return
*/
public boolean containsGraphIndex(String name);
/**
* Returns the graph index with the given name or null if it does not exist
*
* @param name
* @return
*/
public TitanGraphIndex getGraphIndex(String name);
/**
* Returns all graph indexes that index the given element type.
*
* @param elementType
* @return
*/
public Iterable<TitanGraphIndex> getGraphIndexes(final Class<? extends Element> elementType);
/**
* Returns an {@link IndexBuilder} to add a graph index to this Titan graph. The index to-be-created
* has the provided name and indexes elements of the given type.
*
* @param indexName
* @param elementType
* @return
*/
public IndexBuilder buildIndex(String indexName, Class<? extends Element> elementType);
public void addIndexKey(final TitanGraphIndex index, final PropertyKey key, Parameter... parameters);
/**
* Builder for {@link TitanGraphIndex}. Allows for the configuration of a graph index prior to its construction.
*/
public interface IndexBuilder {
/**
* Adds the given key to the composite key of this index
*
* @param key
* @return this IndexBuilder
*/
public IndexBuilder addKey(PropertyKey key);
/**
* Adds the given key and associated parameters to the composite key of this index
* @param key
* @param parameters
* @return this IndexBuilder
*/
public IndexBuilder addKey(PropertyKey key, Parameter... parameters);
/**
* Restricts this index to only those elements that have the provided schemaType. If this graph index indexes
* vertices, then the argument is expected to be a vertex label and only vertices with that label will be indexed.
* Likewise, for edges and properties only those with the matching relation type will be indexed.
*
* @param schemaType
* @return this IndexBuilder
*/
public IndexBuilder indexOnly(TitanSchemaType schemaType);
/**
* Makes this a unique index for the configured element type,
* i.e. an index key can be associated with at most one element in the graph.
*
* @return this IndexBuilder
*/
public IndexBuilder unique();
/**
* Builds a composite index according to the specification
*
* @return the created composite {@link TitanGraphIndex}
*/
public TitanGraphIndex buildCompositeIndex();
/**
* Builds a mixed index according to the specification against the backend index with the given name (i.e.
* the name under which that index is configured in the graph configuration)
*
* @param backingIndex the name of the mixed index
* @return the created mixed {@link TitanGraphIndex}
*/
public TitanGraphIndex buildMixedIndex(String backingIndex);
}
/*
##################### CONSISTENCY SETTING ##########################
*/
/**
* Retrieves the consistency modifier for the given {@link TitanSchemaElement}. If none has been explicitly
* defined, {@link ConsistencyModifier#DEFAULT} is returned.
*
* @param element
* @return
*/
public ConsistencyModifier getConsistency(TitanSchemaElement element);
/**
* Sets the consistency modifier for the given {@link TitanSchemaElement}. Note, that only {@link RelationType}s
* and composite graph indexes allow changing of the consistency level.
*
* @param element
* @param consistency
*/
public void setConsistency(TitanSchemaElement element, ConsistencyModifier consistency);
/**
* Retrieves the time-to-live for the given {@link TitanSchemaType} as a {@link Duration}.
* If none has been explicitly defined, a zero-length {@link Duration} is returned.
*
* @param type
* @return
*/
public Duration getTTL(TitanSchemaType type);
/**
* Sets the time-to-live for the given {@link TitanSchemaType}. The most granular time unit used for TTL values
* is seconds. Any argument will be rounded to seconds if it is more granular than that.
*
* @param type the affected type
* @param ttl time-to-live
* @param unit time unit of the specified ttl
*/
public void setTTL(TitanSchemaType type, int ttl, TimeUnit unit);
/*
##################### SCHEMA UPDATE ##########################
*/
/**
* Changes the name of a {@link TitanSchemaElement} to the provided new name.
* The new name must be valid and not already in use, otherwise an {@link IllegalArgumentException} is thrown.
*
* @param element
* @param newName
*/
public void changeName(TitanSchemaElement element, String newName);
/**
* Updates the provided index according to the given {@link SchemaAction}
*
* @param index
* @param updateAction
*/
public void updateIndex(TitanIndex index, SchemaAction updateAction);
/*
##################### CLUSTER MANAGEMENT ##########################
*/
/**
* Returns a set of unique instance ids for all Titan instances that are currently
* part of this graph cluster.
*
* @return
*/
public Set<String> getOpenInstances();
/**
* Forcefully removes a Titan instance from this graph cluster as identified by its name.
* <p/>
* This method should be used with great care and only in cases where a Titan instance
* has been abnormally terminated (i.e. killed instead of properly shut-down). If this happens, the instance
* will continue to be listed as an open instance which means that 1) a new instance with the same id cannot
* be started and 2) schema updates will fail because the killed instance cannot acknowledge the schema update.
*
* <p/>
* Throws an exception if the instance is not part of this cluster or if the instance has
* been started after the start of this management transaction which is indicative of the instance
* having been restarted successfully.
*
* @param instanceId
*/
public void forceCloseInstance(String instanceId);
/**
* Returns an iterable over all defined types that have the given clazz (either {@link EdgeLabel} which returns all labels,
* {@link PropertyKey} which returns all keys, or {@link RelationType} which returns all types).
*
* @param clazz {@link RelationType} or sub-interface
* @param <T>
* @return Iterable over all types for the given category (label, key, or both)
*/
public <T extends RelationType> Iterable<T> getRelationTypes(Class<T> clazz);
/**
* Returns an {@link Iterable} over all defined {@link VertexLabel}s.
*
* @return
*/
public Iterable<VertexLabel> getVertexLabels();
/**
* Whether this management transaction is open or has been closed (i.e. committed or rolled-back)
* @return
*/
public boolean isOpen();
/**
* Commits this management transaction and persists all schema changes. Closes this transaction.
* @see com.thinkaurelius.titan.core.TitanTransaction#commit()
*/
public void commit();
/**
* Closes this management transaction and discards all changes.
* @see com.thinkaurelius.titan.core.TitanTransaction#rollback()
*/
public void rollback();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_TitanManagement.java
|
1,356 |
ShardStartedTransportHandler.ACTION, new ShardRoutingEntry(shardRouting, indexUUID, reason), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send shard started to [{}]", exp, clusterService.state().nodes().masterNode());
}
});
| 0true
|
src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java
|
79 |
public static class Presentation {
public static class Tab {
public static class Name {
public static final String File_Details = "StaticAssetImpl_FileDetails_Tab";
public static final String Advanced = "StaticAssetImpl_Advanced_Tab";
}
public static class Order {
public static final int File_Details = 2000;
public static final int Advanced = 3000;
}
}
public static class FieldOrder {
// General Fields
public static final int NAME = 1000;
public static final int URL = 2000;
public static final int TITLE = 3000;
public static final int ALT_TEXT = 4000;
public static final int MIME_TYPE = 5000;
public static final int FILE_EXTENSION = 6000;
public static final int FILE_SIZE = 7000;
// Used by subclasses to know where the last field is.
public static final int LAST = 7000;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java
|
379 |
public class ODatabaseRecordTx extends ODatabaseRecordAbstract {
public static final String TYPE = "record";
private OTransaction currentTx;
public ODatabaseRecordTx(final String iURL, final byte iRecordType) {
super(iURL, iRecordType);
init();
}
public ODatabaseRecord begin() {
return begin(TXTYPE.OPTIMISTIC);
}
public ODatabaseRecord begin(final TXTYPE iType) {
setCurrentDatabaseinThreadLocal();
if (currentTx.isActive())
currentTx.rollback();
// WAKE UP LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onBeforeTxBegin(underlying);
} catch (Throwable t) {
OLogManager.instance().error(this, "Error before tx begin", t);
}
switch (iType) {
case NOTX:
setDefaultTransactionMode();
break;
case OPTIMISTIC:
currentTx = new OTransactionOptimistic(this);
break;
case PESSIMISTIC:
throw new UnsupportedOperationException("Pessimistic transaction");
}
currentTx.begin();
return this;
}
public ODatabaseRecord begin(final OTransaction iTx) {
currentTx.rollback();
// WAKE UP LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onBeforeTxBegin(underlying);
} catch (Throwable t) {
OLogManager.instance().error(this, "Error before the transaction begin", t, OTransactionBlockedException.class);
}
currentTx = iTx;
currentTx.begin();
return this;
}
public ODatabaseRecord commit() {
setCurrentDatabaseinThreadLocal();
// WAKE UP LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onBeforeTxCommit(this);
} catch (Throwable t) {
try {
rollback();
} catch (Exception e) {
}
OLogManager.instance().debug(this, "Cannot commit the transaction: caught exception on execution of %s.onBeforeTxCommit()",
t, OTransactionBlockedException.class, listener.getClass());
}
try {
currentTx.commit();
} catch (RuntimeException e) {
// WAKE UP ROLLBACK LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onBeforeTxRollback(underlying);
} catch (Throwable t) {
OLogManager.instance().error(this, "Error before tx rollback", t);
}
// ROLLBACK TX AT DB LEVEL
currentTx.rollback();
// WAKE UP ROLLBACK LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onAfterTxRollback(underlying);
} catch (Throwable t) {
OLogManager.instance().error(this, "Error after tx rollback", t);
}
throw e;
}
// WAKE UP LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onAfterTxCommit(underlying);
} catch (Throwable t) {
OLogManager
.instance()
.debug(
this,
"Error after the transaction has been committed. The transaction remains valid. The exception caught was on execution of %s.onAfterTxCommit()",
t, OTransactionBlockedException.class, listener.getClass());
}
return this;
}
public ODatabaseRecord rollback() {
if (currentTx.isActive()) {
// WAKE UP LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onBeforeTxRollback(underlying);
} catch (Throwable t) {
OLogManager.instance().error(this, "Error before tx rollback", t);
}
currentTx.rollback();
// WAKE UP LISTENERS
for (ODatabaseListener listener : underlying.browseListeners())
try {
listener.onAfterTxRollback(underlying);
} catch (Throwable t) {
OLogManager.instance().error(this, "Error after tx rollback", t);
}
}
return this;
}
public OTransaction getTransaction() {
return currentTx;
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET load(final ORecordInternal<?> iRecord, final String iFetchPlan) {
return (RET) currentTx.loadRecord(iRecord.getIdentity(), iRecord, iFetchPlan, false, false);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET load(ORecordInternal<?> iRecord, String iFetchPlan, boolean iIgnoreCache,
boolean loadTombstone) {
return (RET) currentTx.loadRecord(iRecord.getIdentity(), iRecord, iFetchPlan, iIgnoreCache, loadTombstone);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET load(final ORecordInternal<?> iRecord) {
return (RET) currentTx.loadRecord(iRecord.getIdentity(), iRecord, null, false, false);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET load(final ORID iRecordId) {
return (RET) currentTx.loadRecord(iRecordId, null, null, false, false);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET load(final ORID iRecordId, final String iFetchPlan) {
return (RET) currentTx.loadRecord(iRecordId, null, iFetchPlan, false, false);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET load(ORID iRecordId, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) {
return (RET) currentTx.loadRecord(iRecordId, null, iFetchPlan, iIgnoreCache, loadTombstone);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET reload(ORecordInternal<?> iRecord) {
return reload(iRecord, null, false);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET reload(ORecordInternal<?> iRecord, String iFetchPlan) {
return reload(iRecord, iFetchPlan, false);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET reload(ORecordInternal<?> iRecord, String iFetchPlan, boolean iIgnoreCache) {
ORecordInternal<?> record = currentTx.loadRecord(iRecord.getIdentity(), iRecord, iFetchPlan, iIgnoreCache, false);
if (record != null && iRecord != record) {
iRecord.fromStream(record.toStream());
iRecord.getRecordVersion().copyFrom(record.getRecordVersion());
}
return (RET) record;
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent, final OPERATION_MODE iMode,
boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback,
ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
return (RET) save(iContent, (String) null, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent) {
return (RET) save(iContent, (String) null, OPERATION_MODE.SYNCHRONOUS, false, null, null);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent, final String iClusterName) {
return (RET) save(iContent, iClusterName, OPERATION_MODE.SYNCHRONOUS, false, null, null);
}
@Override
public boolean updatedReplica(ORecordInternal<?> iContent) {
return currentTx.updateReplica(iContent);
}
@SuppressWarnings("unchecked")
@Override
public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iContent, final String iClusterName,
final OPERATION_MODE iMode, boolean iForceCreate, ORecordCallback<? extends Number> iRecordCreatedCallback,
ORecordCallback<ORecordVersion> iRecordUpdatedCallback) {
currentTx.saveRecord(iContent, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback);
return (RET) iContent;
}
/**
* Deletes the record without checking the version.
*/
public ODatabaseRecord delete(final ORID iRecord) {
final ORecord<?> rec = iRecord.getRecord();
if (rec != null)
rec.delete();
return this;
}
@Override
public ODatabaseRecord delete(final ORecordInternal<?> iRecord) {
currentTx.deleteRecord(iRecord, OPERATION_MODE.SYNCHRONOUS);
return this;
}
@Override
public ODatabaseRecord delete(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode) {
currentTx.deleteRecord(iRecord, iMode);
return this;
}
public void executeRollback(final OTransaction iTransaction) {
}
protected void checkTransaction() {
if (currentTx == null || currentTx.getStatus() == TXSTATUS.INVALID)
throw new OTransactionException("Transaction not started");
}
private void init() {
currentTx = new OTransactionNoTx(this);
}
public ORecordInternal<?> getRecordByUserObject(final Object iUserObject, final boolean iCreateIfNotAvailable) {
return (ORecordInternal<?>) iUserObject;
}
public void registerUserObject(final Object iObject, final ORecordInternal<?> iRecord) {
}
public void registerUserObjectAfterLinkSave(ORecordInternal<?> iRecord) {
}
public Object getUserObjectByRecord(final OIdentifiable record, final String iFetchPlan) {
return record;
}
public boolean existsUserObjectByRID(final ORID iRID) {
return true;
}
public String getType() {
return TYPE;
}
public void setDefaultTransactionMode() {
if (!(currentTx instanceof OTransactionNoTx))
currentTx = new OTransactionNoTx(this);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_db_record_ODatabaseRecordTx.java
|
5,100 |
class SearchFreeContextRequest extends TransportRequest {
private long id;
SearchFreeContextRequest() {
}
SearchFreeContextRequest(TransportRequest request, long id) {
super(request);
this.id = id;
}
public long id() {
return this.id;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
id = in.readLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeLong(id);
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_action_SearchServiceTransportAction.java
|
1,055 |
private final class TermVectorsDocsAndPosEnum extends DocsAndPositionsEnum {
private boolean hasPositions;
private boolean hasOffsets;
private boolean hasPayloads;
int curPos = -1;
int doc = -1;
private int freq;
private int[] startOffsets;
private int[] positions;
private BytesRef[] payloads;
private int[] endOffsets;
private DocsAndPositionsEnum reset(int[] positions, int[] startOffsets, int[] endOffsets, BytesRef[] payloads, int freq) {
curPos = -1;
doc = -1;
this.hasPositions = positions != null;
this.hasOffsets = startOffsets != null;
this.hasPayloads = payloads != null;
this.freq = freq;
this.startOffsets = startOffsets;
this.endOffsets = endOffsets;
this.payloads = payloads;
this.positions = positions;
return this;
}
@Override
public int nextDoc() throws IOException {
return doc = (doc == -1 ? 0 : NO_MORE_DOCS);
}
@Override
public int docID() {
return doc;
}
@Override
public int advance(int target) throws IOException {
while (nextDoc() < target && doc != NO_MORE_DOCS) {
}
return doc;
}
@Override
public int freq() throws IOException {
return freq;
}
// call nextPosition once before calling this one
// because else counter is not advanced
@Override
public int startOffset() throws IOException {
assert curPos < freq && curPos >= 0;
return hasOffsets ? startOffsets[curPos] : -1;
}
@Override
// can return -1 if posistions were not requested or
// stored but offsets were stored and requested
public int nextPosition() throws IOException {
assert curPos + 1 < freq;
++curPos;
// this is kind of cheating but if you don't need positions
// we safe lots fo space on the wire
return hasPositions ? positions[curPos] : -1;
}
@Override
public BytesRef getPayload() throws IOException {
assert curPos < freq && curPos >= 0;
return hasPayloads ? payloads[curPos] : null;
}
@Override
public int endOffset() throws IOException {
assert curPos < freq && curPos >= 0;
return hasOffsets ? endOffsets[curPos] : -1;
}
@Override
public long cost() {
return 1;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_termvector_TermVectorFields.java
|
7 |
public class AbbreviationsManagerTest {
private Properties defaultProperties;
@BeforeMethod
public void init() {
defaultProperties = new Properties();
defaultProperties.setProperty("fiber optic", "F/O");
defaultProperties.setProperty("system", "Sys");
}
@Test
public void testGetAlternatives() {
AbbreviationsManager manager;
Properties props;
List<String> alternatives;
props = new Properties();
manager = new AbbreviationsManager(props);
alternatives = manager.getAlternatives("volts");
assertEquals(alternatives.size(), 1);
assertEquals(alternatives.get(0), "volts");
props = new Properties();
props.setProperty("Volts", "V"); // Note that lookup should be case insensitive.
manager = new AbbreviationsManager(props);
alternatives = manager.getAlternatives("volts");
assertEquals(alternatives.size(), 2);
assertEquals(alternatives.get(0), "volts"); // Matches the case of getAbbreviations() argument.
assertEquals(alternatives.get(1), "V");
props = new Properties();
props.setProperty("Amperes", "Amps | A | aa | bbbb | a | aaaa ");
manager = new AbbreviationsManager(props);
alternatives = manager.getAlternatives("amperes");
assertEquals(alternatives.size(), 7);
assertEquals(alternatives.get(0), "amperes"); // Must match in case to getAbbreviations() argument.
assertEquals(alternatives.get(1), "A");
assertEquals(alternatives.get(2), "a");
assertEquals(alternatives.get(3), "aa");
assertEquals(alternatives.get(4), "Amps"); // same length items are in left to right specified order
assertEquals(alternatives.get(5), "bbbb");
assertEquals(alternatives.get(6), "aaaa");
}
@Test(dataProvider="getAbbreviationsTests")
public void testGetAbbreviations(String s, String[] expectedPhrases) {
AbbreviationsManager manager = new AbbreviationsManager(defaultProperties);
Abbreviations abbrev = manager.getAbbreviations(s);
assertEquals(abbrev.getValue(), s);
assertEquals(abbrev.getPhrases().size(), expectedPhrases.length);
for (int i=0; i<abbrev.getPhrases().size(); ++i) {
String phrase = abbrev.getPhrases().get(i);
assertEquals(phrase, expectedPhrases[i]);
List<String> alternatives = abbrev.getAbbreviations(phrase);
List<String> expectedAlternatives = manager.getAlternatives(abbrev.getPhrases().get(i));
assertTrue(alternatives.size() >= 1);
assertEquals(alternatives.size(), expectedAlternatives.size());
assertEquals(alternatives.get(0), abbrev.getPhrases().get(i));
}
}
@DataProvider(name="getAbbreviationsTests")
private Object[][] getGetAbbreviationsTests() {
return new Object[][] {
{ "System", new String[] { "System" } }, // One word in abbreviations map
{ "MDM", new String[] { "MDM" } }, // One word not in abbreviations map
{ "Fiber Optic", new String[] { "Fiber Optic" } }, // Exact phrase in abbreviations map
// Some longer tests.
{ "Junk1 Junk2 Junk3", new String[] { "Junk1", "Junk2", "Junk3" } }, // No matches
{ "Fiber Optic MDM System", new String[] { "Fiber Optic", "MDM", "System" } },
};
}
}
| 0true
|
tableViews_src_test_java_gov_nasa_arc_mct_abbreviation_impl_AbbreviationsManagerTest.java
|
84 |
GREATER_THAN_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp>=0:false;
}
@Override
public String toString() {
return ">=";
}
@Override
public TitanPredicate negate() {
return LESS_THAN;
}
};
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java
|
513 |
deleteIndexService.deleteIndex(new MetaDataDeleteIndexService.Request(index).timeout(request.timeout()).masterTimeout(request.masterNodeTimeout()), new MetaDataDeleteIndexService.Listener() {
private volatile Throwable lastFailure;
private volatile boolean ack = true;
@Override
public void onResponse(MetaDataDeleteIndexService.Response response) {
if (!response.acknowledged()) {
ack = false;
}
if (count.countDown()) {
if (lastFailure != null) {
listener.onFailure(lastFailure);
} else {
listener.onResponse(new DeleteIndexResponse(ack));
}
}
}
@Override
public void onFailure(Throwable t) {
logger.debug("[{}] failed to delete index", t, index);
lastFailure = t;
if (count.countDown()) {
listener.onFailure(t);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_delete_TransportDeleteIndexAction.java
|
210 |
public class OStorageRemoteThreadLocal extends ThreadLocal<OStorageRemoteSession> {
public static OStorageRemoteThreadLocal INSTANCE = new OStorageRemoteThreadLocal();
public class OStorageRemoteSession {
public boolean commandExecuting = false;
public Integer sessionId = -1;
public String serverURL = null;
}
@Override
protected OStorageRemoteSession initialValue() {
return new OStorageRemoteSession();
}
}
| 0true
|
client_src_main_java_com_orientechnologies_orient_client_remote_OStorageRemoteThreadLocal.java
|
3,401 |
public final class ExecutionServiceImpl implements ExecutionService {
private final NodeEngineImpl nodeEngine;
private final ExecutorService cachedExecutorService;
private final ScheduledExecutorService scheduledExecutorService;
private final ScheduledExecutorService defaultScheduledExecutorServiceDelegate;
private final ILogger logger;
private final CompletableFutureTask completableFutureTask;
private final ConcurrentMap<String, ManagedExecutorService> executors
= new ConcurrentHashMap<String, ManagedExecutorService>();
public ExecutionServiceImpl(NodeEngineImpl nodeEngine) {
this.nodeEngine = nodeEngine;
final Node node = nodeEngine.getNode();
logger = node.getLogger(ExecutionService.class.getName());
final ClassLoader classLoader = node.getConfigClassLoader();
final ThreadFactory threadFactory = new PoolExecutorThreadFactory(node.threadGroup,
node.getThreadPoolNamePrefix("cached"), classLoader);
cachedExecutorService = new ThreadPoolExecutor(
3, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), threadFactory, new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (logger.isFinestEnabled()) {
logger.finest("Node is shutting down; discarding the task: " + r);
}
}
}
);
final String scheduledThreadName = node.getThreadNamePrefix("scheduled");
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new SingleExecutorThreadFactory(node.threadGroup, classLoader, scheduledThreadName));
enableRemoveOnCancelIfAvailable();
final int coreSize = Runtime.getRuntime().availableProcessors();
// default executors
register(SYSTEM_EXECUTOR, coreSize, Integer.MAX_VALUE, ExecutorType.CACHED);
register(SCHEDULED_EXECUTOR, coreSize * 5, coreSize * 100000, ExecutorType.CACHED);
defaultScheduledExecutorServiceDelegate = getScheduledExecutor(SCHEDULED_EXECUTOR);
// Register CompletableFuture task
completableFutureTask = new CompletableFutureTask();
scheduleWithFixedDelay(completableFutureTask, 1000, 100, TimeUnit.MILLISECONDS);
}
private void enableRemoveOnCancelIfAvailable() {
try {
final Method m = scheduledExecutorService.getClass().getMethod("setRemoveOnCancelPolicy", boolean.class);
m.invoke(scheduledExecutorService, true);
} catch (NoSuchMethodException ignored) {
} catch (InvocationTargetException ignored) {
} catch (IllegalAccessException ignored) {
}
}
@Override
public ManagedExecutorService register(String name, int poolSize, int queueCapacity, ExecutorType type) {
ExecutorConfig cfg = nodeEngine.getConfig().getExecutorConfigs().get(name);
if (cfg != null) {
poolSize = cfg.getPoolSize();
queueCapacity = cfg.getQueueCapacity() <= 0 ? Integer.MAX_VALUE : cfg.getQueueCapacity();
}
ManagedExecutorService executor = createExecutor(name, poolSize, queueCapacity, type);
if (executors.putIfAbsent(name, executor) != null) {
throw new IllegalArgumentException("ExecutorService['" + name + "'] already exists!");
}
return executor;
}
private final ConstructorFunction<String, ManagedExecutorService> constructor =
new ConstructorFunction<String, ManagedExecutorService>() {
public ManagedExecutorService createNew(String name) {
final ExecutorConfig cfg = nodeEngine.getConfig().findExecutorConfig(name);
final int queueCapacity = cfg.getQueueCapacity() <= 0 ? Integer.MAX_VALUE : cfg.getQueueCapacity();
return createExecutor(name, cfg.getPoolSize(), queueCapacity, ExecutorType.CACHED);
}
};
private ManagedExecutorService createExecutor(String name, int poolSize, int queueCapacity, ExecutorType type) {
ManagedExecutorService executor;
if (type == ExecutorType.CACHED) {
executor = new CachedExecutorServiceDelegate(nodeEngine, name, cachedExecutorService, poolSize, queueCapacity);
} else if (type == ExecutorType.CONCRETE) {
Node node = nodeEngine.getNode();
String internalName = name.startsWith("hz:") ? name.substring(3) : name;
NamedThreadPoolExecutor pool = new NamedThreadPoolExecutor(name, poolSize, poolSize,
60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(queueCapacity),
new PoolExecutorThreadFactory(node.threadGroup,
node.getThreadPoolNamePrefix(internalName), node.getConfigClassLoader())
);
pool.allowCoreThreadTimeOut(true);
executor = pool;
} else {
throw new IllegalArgumentException("Unknown executor type: " + type);
}
return executor;
}
@Override
public ManagedExecutorService getExecutor(String name) {
return ConcurrencyUtil.getOrPutIfAbsent(executors, name, constructor);
}
@Override
public <V> ICompletableFuture<V> asCompletableFuture(Future<V> future) {
if (future == null) {
throw new IllegalArgumentException("future must not be null");
}
if (future instanceof ICompletableFuture) {
return (ICompletableFuture<V>) future;
}
return registerCompletableFuture(future);
}
@Override
public void execute(String name, Runnable command) {
getExecutor(name).execute(command);
}
@Override
public Future<?> submit(String name, Runnable task) {
return getExecutor(name).submit(task);
}
@Override
public <T> Future<T> submit(String name, Callable<T> task) {
return getExecutor(name).submit(task);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return defaultScheduledExecutorServiceDelegate.schedule(command, delay, unit);
}
@Override
public ScheduledFuture<?> schedule(String name, Runnable command, long delay, TimeUnit unit) {
return getScheduledExecutor(name).schedule(command, delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return defaultScheduledExecutorServiceDelegate.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(String name, Runnable command, long initialDelay,
long period, TimeUnit unit) {
return getScheduledExecutor(name).scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit) {
return defaultScheduledExecutorServiceDelegate.scheduleWithFixedDelay(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(String name, Runnable command, long initialDelay,
long period, TimeUnit unit) {
return getScheduledExecutor(name).scheduleWithFixedDelay(command, initialDelay, period, unit);
}
@Override
public ScheduledExecutorService getDefaultScheduledExecutor() {
return defaultScheduledExecutorServiceDelegate;
}
@Override
public ScheduledExecutorService getScheduledExecutor(String name) {
return new ScheduledExecutorServiceDelegate(scheduledExecutorService, getExecutor(name));
}
@PrivateApi
void shutdown() {
logger.finest("Stopping executors...");
cachedExecutorService.shutdown();
scheduledExecutorService.shutdownNow();
try {
cachedExecutorService.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.finest(e);
}
for (ExecutorService executorService : executors.values()) {
executorService.shutdown();
}
executors.clear();
}
@Override
public void shutdownExecutor(String name) {
final ExecutorService ex = executors.remove(name);
if (ex != null) {
ex.shutdown();
}
}
private <V> ICompletableFuture<V> registerCompletableFuture(Future<V> future) {
CompletableFutureEntry<V> entry = new CompletableFutureEntry<V>(future, nodeEngine, completableFutureTask);
completableFutureTask.registerCompletableFutureEntry(entry);
return entry.completableFuture;
}
private static class CompletableFutureTask implements Runnable {
private final List<CompletableFutureEntry> entries = new ArrayList<CompletableFutureEntry>();
private final Lock entriesLock = new ReentrantLock();
private <V> void registerCompletableFutureEntry(CompletableFutureEntry<V> entry) {
entriesLock.lock();
try {
entries.add(entry);
} finally {
entriesLock.unlock();
}
}
@Override
public void run() {
if (entries.isEmpty()) {
return;
}
CompletableFutureEntry[] copy;
entriesLock.lock();
try {
copy = new CompletableFutureEntry[entries.size()];
copy = this.entries.toArray(copy);
} finally {
entriesLock.unlock();
}
List<CompletableFutureEntry> removes = null;
for (CompletableFutureEntry entry : copy) {
if (entry.processState()) {
if (removes == null) {
removes = new ArrayList<CompletableFutureEntry>(copy.length / 2);
}
removes.add(entry);
}
}
// Remove processed elements
if (removes != null && !removes.isEmpty()) {
entriesLock.lock();
try {
for (int i = 0; i < removes.size(); i++) {
entries.remove(removes.get(i));
}
} finally {
entriesLock.unlock();
}
}
}
}
static class CompletableFutureEntry<V> {
private final BasicCompletableFuture<V> completableFuture;
private final CompletableFutureTask completableFutureTask;
private CompletableFutureEntry(Future<V> future, NodeEngine nodeEngine,
CompletableFutureTask completableFutureTask) {
this.completableFutureTask = completableFutureTask;
this.completableFuture = new BasicCompletableFuture<V>(future, nodeEngine);
}
private boolean processState() {
if (completableFuture.isDone()) {
Object result;
try {
result = completableFuture.future.get();
} catch (Throwable t) {
result = t;
}
completableFuture.setResult(result);
return true;
}
return false;
}
}
private static class ScheduledExecutorServiceDelegate implements ScheduledExecutorService {
private final ScheduledExecutorService scheduledExecutorService;
private final ExecutorService executor;
private ScheduledExecutorServiceDelegate(ScheduledExecutorService scheduledExecutorService, ExecutorService executor) {
this.scheduledExecutorService = scheduledExecutorService;
this.executor = executor;
}
@Override
public void execute(Runnable command) {
executor.execute(command);
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return executor.submit(task);
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return executor.submit(task, result);
}
@Override
public Future<?> submit(Runnable task) {
return executor.submit(task);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(new ScheduledTaskRunner(command, executor), delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return scheduledExecutorService.scheduleAtFixedRate(new ScheduledTaskRunner(command, executor), initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return scheduledExecutorService.scheduleWithFixedDelay(new ScheduledTaskRunner(command, executor), initialDelay, delay, unit);
}
@Override
public void shutdown() {
throw new UnsupportedOperationException();
}
@Override
public List<Runnable> shutdownNow() {
throw new UnsupportedOperationException();
}
@Override
public boolean isShutdown() {
return false;
}
@Override
public boolean isTerminated() {
return false;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
throw new UnsupportedOperationException();
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
throw new UnsupportedOperationException();
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
throw new UnsupportedOperationException();
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException();
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
throw new UnsupportedOperationException();
}
@Override
public <V> ScheduledFuture<V> schedule(final Callable<V> callable, long delay, TimeUnit unit) {
throw new UnsupportedOperationException();
}
}
static class BasicCompletableFuture<V> extends AbstractCompletableFuture<V> {
private final Future<V> future;
BasicCompletableFuture(Future<V> future, NodeEngine nodeEngine) {
super(nodeEngine, nodeEngine.getLogger(BasicCompletableFuture.class));
this.future = future;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return future.isCancelled();
}
@Override
public boolean isDone() {
boolean done = future.isDone();
if (done && !super.isDone()) {
forceSetResult();
return true;
}
return done || super.isDone();
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
V result = future.get(timeout, unit);
// If not yet set by CompletableFuture task runner, we can go for it!
if (!super.isDone()) {
setResult(result);
}
return result;
}
private void forceSetResult() {
Object result;
try {
result = future.get();
} catch (Throwable t) {
result = t;
}
setResult(result);
}
}
private static class ScheduledTaskRunner implements Runnable {
private final Executor executor;
private final Runnable runnable;
public ScheduledTaskRunner(Runnable runnable, Executor executor) {
this.executor = executor;
this.runnable = runnable;
}
@Override
public void run() {
try {
executor.execute(runnable);
} catch (Throwable t) {
ExceptionUtil.sneakyThrow(t);
}
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_spi_impl_ExecutionServiceImpl.java
|
1,507 |
@Component("blAuthenticationSuccessHandler")
public class BroadleafAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
String targetUrl = request.getParameter(getTargetUrlParameter());
if (StringUtils.isNotBlank(targetUrl) && targetUrl.contains(":")) {
getRedirectStrategy().sendRedirect(request, response, getDefaultTargetUrl());
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
| 1no label
|
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_security_BroadleafAuthenticationSuccessHandler.java
|
1,489 |
public class Nodes {
private static final String[] NO_STRINGS = new String[0];
private static final Pattern IDPATTERN =
Pattern.compile("(^|[A-Z])([A-Z]*)([_a-z]+)");
public static Tree.Declaration findDeclaration(Tree.CompilationUnit cu, Node node) {
FindDeclarationVisitor fcv = new FindDeclarationVisitor(node);
fcv.visit(cu);
return fcv.getDeclarationNode();
}
public static Tree.Declaration findDeclarationWithBody(Tree.CompilationUnit cu, Node node) {
FindBodyContainerVisitor fcv = new FindBodyContainerVisitor(node);
fcv.visit(cu);
return fcv.getDeclarationNode();
}
public static Tree.NamedArgument findArgument(Tree.CompilationUnit cu, Node node) {
FindArgumentVisitor fcv = new FindArgumentVisitor(node);
fcv.visit(cu);
return fcv.getArgumentNode();
}
public static Statement findStatement(Tree.CompilationUnit cu, Node node) {
FindStatementVisitor visitor = new FindStatementVisitor(node, false);
cu.visit(visitor);
return visitor.getStatement();
}
public static Statement findToplevelStatement(Tree.CompilationUnit cu, Node node) {
FindStatementVisitor visitor = new FindStatementVisitor(node, true);
cu.visit(visitor);
return visitor.getStatement();
}
public static Declaration getAbstraction(Declaration d) {
if (isOverloadedVersion(d)) {
return d.getContainer().getDirectMember(d.getName(), null, false);
}
else {
return d;
}
}
public static Tree.Declaration getContainer(Tree.CompilationUnit cu,
final Declaration dec) {
class FindContainer extends Visitor {
final Scope container = dec.getContainer();
Tree.Declaration result;
@Override
public void visit(Tree.Declaration that) {
super.visit(that);
if (that.getDeclarationModel().equals(container)) {
result = that;
}
}
}
FindContainer fc = new FindContainer();
cu.visit(fc);
if (fc.result instanceof Tree.Declaration) {
return (Tree.Declaration) fc.result;
}
else {
return null;
}
}
public static Tree.ImportMemberOrType findImport(Tree.CompilationUnit cu, Node node) {
if (node instanceof Tree.ImportMemberOrType) {
return (Tree.ImportMemberOrType) node;
}
final Declaration declaration;
if (node instanceof Tree.MemberOrTypeExpression) {
declaration = ((Tree.MemberOrTypeExpression) node).getDeclaration();
}
else if (node instanceof Tree.SimpleType) {
declaration = ((Tree.SimpleType) node).getDeclarationModel();
}
else if (node instanceof Tree.MemberLiteral) {
declaration = ((Tree.MemberLiteral) node).getDeclaration();
}
else {
return null;
}
class FindImportVisitor extends Visitor {
Tree.ImportMemberOrType result;
@Override
public void visit(Tree.Declaration that) {}
@Override
public void visit(Tree.ImportMemberOrType that) {
super.visit(that);
if (that.getDeclarationModel()!=null &&
that.getDeclarationModel().equals(declaration)) {
result = that;
}
}
}
if (declaration!=null) {
FindImportVisitor visitor = new FindImportVisitor();
visitor.visit(cu);
return visitor.result;
}
else {
return null;
}
}
public static Node findNode(Tree.CompilationUnit cu, int offset) {
return findNode(cu, offset, offset+1);
}
public static Node findNode(Node cu, int startOffset, int endOffset) {
FindNodeVisitor visitor = new FindNodeVisitor(startOffset, endOffset);
cu.visit(visitor);
return visitor.getNode();
}
private static Node findScope(Tree.CompilationUnit cu, int startOffset, int endOffset) {
FindScopeVisitor visitor = new FindScopeVisitor(startOffset, endOffset);
cu.visit(visitor);
return visitor.getNode();
}
public static Node findNode(Tree.CompilationUnit cu, ITextSelection s) {
return findNode(cu, s.getOffset(), s.getOffset()+s.getLength());
}
public static Node findScope(Tree.CompilationUnit cu, ITextSelection s) {
return findScope(cu, s.getOffset(), s.getOffset()+s.getLength());
}
private static Node toNode(Node node) {
if (node instanceof Node) {
return Nodes.getIdentifyingNode((Node) node);
}
else {
return null;
}
}
public static int getStartOffset(Node node) {
return Nodes.getNodeStartOffset(toNode(node));
}
public static int getEndOffset(Node node) {
return Nodes.getNodeEndOffset(toNode(node));
}
public static int getLength(Node node) {
return getEndOffset(node) - getStartOffset(node);
}
public static int getNodeLength(Node node) {
return Nodes.getNodeEndOffset(node) - Nodes.getNodeStartOffset(node);
}
public static Node getIdentifyingNode(Node node) {
if (node instanceof Tree.Declaration) {
return ((Tree.Declaration) node).getIdentifier();
}
else if (node instanceof Tree.ModuleDescriptor) {
return ((Tree.ModuleDescriptor) node).getImportPath();
}
else if (node instanceof Tree.PackageDescriptor) {
return ((Tree.PackageDescriptor) node).getImportPath();
}
else if (node instanceof Tree.Import) {
return ((Tree.Import) node).getImportPath();
}
else if (node instanceof Tree.ImportModule) {
return ((Tree.ImportModule) node).getImportPath();
}
else if (node instanceof Tree.NamedArgument) {
Identifier id = ((Tree.NamedArgument) node).getIdentifier();
if (id==null || id.getToken()==null) {
return node;
}
else {
return id;
}
}
else if (node instanceof Tree.StaticMemberOrTypeExpression) {
return ((Tree.StaticMemberOrTypeExpression) node).getIdentifier();
}
else if (node instanceof Tree.ExtendedTypeExpression) {
//TODO: whoah! this is really ugly!
return ((CustomTree.ExtendedTypeExpression) node).getType()
.getIdentifier();
}
else if (node instanceof Tree.SimpleType) {
return ((Tree.SimpleType) node).getIdentifier();
}
else if (node instanceof Tree.ImportMemberOrType) {
return ((Tree.ImportMemberOrType) node).getIdentifier();
}
else if (node instanceof Tree.InitializerParameter) {
return ((Tree.InitializerParameter) node).getIdentifier();
}
else if (node instanceof Tree.MemberLiteral) {
return ((Tree.MemberLiteral) node).getIdentifier();
}
else if (node instanceof Tree.TypeLiteral) {
return getIdentifyingNode(((Tree.TypeLiteral) node).getType());
}
else {
return node;
}
}
public static Iterator<CommonToken> getTokenIterator(List<CommonToken> tokens,
IRegion region) {
int regionOffset = region.getOffset();
int regionLength = region.getLength();
if (regionLength<=0) {
return Collections.<CommonToken>emptyList().iterator();
}
int regionEnd = regionOffset + regionLength - 1;
if (tokens==null) {
return null;
}
else {
int firstTokIdx =
getTokenIndexAtCharacter(tokens, regionOffset);
// getTokenIndexAtCharacter() answers the negative of the index of the
// preceding token if the given offset is not actually within a token.
if (firstTokIdx < 0) {
firstTokIdx= -firstTokIdx + 1;
}
int lastTokIdx =
getTokenIndexAtCharacter(tokens, regionEnd);
if (lastTokIdx < 0) {
lastTokIdx= -lastTokIdx;
}
return tokens.subList(firstTokIdx, lastTokIdx+1).iterator();
}
}
//
// This function returns the index of the token element
// containing the offset specified. If such a token does
// not exist, it returns the negation of the index of the
// element immediately preceding the offset.
//
public static int getTokenIndexAtCharacter(List<CommonToken> tokens, int offset) {
//search using bisection
int low = 0,
high = tokens.size();
while (high > low)
{
int mid = (high + low) / 2;
CommonToken midElement = (CommonToken) tokens.get(mid);
if (offset >= midElement.getStartIndex() &&
offset <= midElement.getStopIndex())
return mid;
else if (offset < midElement.getStartIndex())
high = mid;
else low = mid + 1;
}
return -(low - 1);
}
public static int getNodeStartOffset(Node node) {
if (node==null) {
return 0;
}
else {
Integer index = node.getStartIndex();
return index==null?0:index;
}
}
public static int getNodeEndOffset(Node node) {
if (node==null) {
return 0;
}
else {
Integer index = node.getStopIndex();
return index==null?0:index+1;
}
}
public static Node getReferencedNode(Node node,
CeylonParseController controller) {
return getReferencedNode(getReferencedModel(node),
controller);
}
public static Node getReferencedNode(Referenceable dec,
CeylonParseController controller) {
return getReferencedNode(dec,
getCompilationUnit(dec, controller));
}
public static Referenceable getReferencedModel(Node node) {
if (node instanceof Tree.ImportPath) {
return ((Tree.ImportPath) node).getModel();
}
else if (node instanceof Tree.DocLink) {
Tree.DocLink docLink = (Tree.DocLink) node;
if (docLink.getBase()==null) {
if (docLink.getModule()!=null) {
return docLink.getModule();
}
if (docLink.getPkg()!=null) {
return docLink.getPkg();
}
}
}
Referenceable dec = getReferencedDeclaration((Node) node);
if (dec instanceof MethodOrValue) {
MethodOrValue mv = (MethodOrValue) dec;
if (mv.isShortcutRefinement()) {
dec = mv.getRefinedDeclaration();
}
}
return dec;
}
public static Referenceable getReferencedExplicitDeclaration(Node node,
Tree.CompilationUnit rn) {
Referenceable dec = getReferencedDeclaration(node);
if (dec!=null && dec.getUnit()!=null &&
dec.getUnit().equals(node.getUnit())) {
FindDeclarationNodeVisitor fdv =
new FindDeclarationNodeVisitor(dec);
fdv.visit(rn);
Node decNode = fdv.getDeclarationNode();
if (decNode instanceof Tree.Variable) {
Tree.Variable var = (Tree.Variable) decNode;
if (var.getType() instanceof Tree.SyntheticVariable) {
Tree.Term term = var.getSpecifierExpression()
.getExpression().getTerm();
return getReferencedExplicitDeclaration(term, rn);
}
}
}
return dec;
}
public static Referenceable getReferencedDeclaration(Node node) {
//NOTE: this must accept a null node, returning null!
if (node instanceof Tree.MemberOrTypeExpression) {
return ((Tree.MemberOrTypeExpression) node).getDeclaration();
}
else if (node instanceof Tree.SimpleType) {
return ((Tree.SimpleType) node).getDeclarationModel();
}
else if (node instanceof Tree.ImportMemberOrType) {
return ((Tree.ImportMemberOrType) node).getDeclarationModel();
}
else if (node instanceof Tree.Declaration) {
return ((Tree.Declaration) node).getDeclarationModel();
}
else if (node instanceof Tree.NamedArgument) {
Parameter p = ((Tree.NamedArgument) node).getParameter();
return p==null ? null : p.getModel();
}
else if (node instanceof Tree.InitializerParameter) {
Parameter p = ((Tree.InitializerParameter) node).getParameterModel();
return p==null ? null : p.getModel();
}
else if (node instanceof Tree.MetaLiteral) {
return ((Tree.MetaLiteral) node).getDeclaration();
}
else if (node instanceof Tree.DocLink) {
DocLink docLink = (Tree.DocLink) node;
List<Declaration> qualified = docLink.getQualified();
if (qualified!=null && !qualified.isEmpty()) {
return qualified.get(qualified.size()-1);
}
else {
return docLink.getBase();
}
}
else if (node instanceof Tree.ImportPath) {
return ((Tree.ImportPath) node).getModel();
}
else {
return null;
}
}
public static Node getReferencedNode(Referenceable dec,
Tree.CompilationUnit compilationUnit) {
if (compilationUnit==null || dec==null) {
return null;
}
else {
FindReferencedNodeVisitor visitor =
new FindReferencedNodeVisitor(dec);
compilationUnit.visit(visitor);
//System.out.println("referenced node: " + visitor.getDeclarationNode());
return visitor.getDeclarationNode();
}
}
public static Tree.CompilationUnit getCompilationUnit(Referenceable model,
CeylonParseController cpc) {
if (model==null) {
return null;
}
else {
Tree.CompilationUnit root = cpc==null ?
null : cpc.getRootNode();
if (root!=null && root.getUnit()!=null &&
root.getUnit().equals(model.getUnit())) {
return root;
}
else {
Unit unit = model.getUnit();
PhasedUnit pu = null;
if (unit instanceof ProjectSourceFile) {
pu = ((ProjectSourceFile) unit).getPhasedUnit();
// Here pu should never be null !
}
if (unit instanceof EditedSourceFile) {
pu = ((EditedSourceFile) unit).getPhasedUnit();
// Here pu should never be null !
}
if (unit instanceof ICrossProjectReference) {
ProjectPhasedUnit requiredProjectPhasedUnit =
((ICrossProjectReference) unit).getOriginalPhasedUnit();
if (requiredProjectPhasedUnit != null
&& requiredProjectPhasedUnit.isFullyTyped()) {
pu = requiredProjectPhasedUnit;
}
else {
System.err.println("ABNORMAL : cross reference with a null original PhasedUnit !");
pu = ((ICrossProjectReference) unit).getPhasedUnit();
}
}
if (pu == null && (unit instanceof ExternalSourceFile ||
unit instanceof CeylonBinaryUnit)) {
pu = ((CeylonUnit)unit).getPhasedUnit();
}
// TODO : When using binary ceylon archives, add a case here with
// unit instanceof CeylonBinaryUnit
// And perform the same sort of thing as for ExternalSourceFile :
// -> return the associated source PhasedUnit if any
if (pu!=null) {
return pu.getCompilationUnit();
}
return null;
}
}
}
public static String toString(Node term, List<CommonToken> tokens) {
Integer start = term.getStartIndex();
int length = term.getStopIndex()-start+1;
Region region = new Region(start, length);
StringBuilder exp = new StringBuilder();
for (Iterator<CommonToken> ti =
getTokenIterator(tokens, region);
ti.hasNext();) {
CommonToken token = ti.next();
int type = token.getType();
String text = token.getText();
if (type==LIDENTIFIER &&
getTokenLength(token)>text.length()) {
exp.append("\\i");
}
else if (type==UIDENTIFIER &&
getTokenLength(token)>text.length()) {
exp.append("\\I");
}
exp.append(text);
}
return exp.toString();
}
public static int getTokenLength(CommonToken token) {
return token.getStopIndex()-token.getStartIndex()+1;
}
public static String[] nameProposals(Node node) {
return nameProposals(node, false);
}
public static String[] nameProposals(Node node, boolean unplural) {
if (node instanceof Tree.FunctionArgument) {
Tree.FunctionArgument fa = (Tree.FunctionArgument) node;
if (fa.getExpression()!=null) {
node = fa.getExpression();
}
}
Set<String> names = new LinkedHashSet<String>();
Node identifyingNode = node;
if (identifyingNode instanceof Tree.Expression) {
identifyingNode =
((Tree.Expression) identifyingNode).getTerm();
}
if (identifyingNode instanceof Tree.InvocationExpression) {
identifyingNode =
((Tree.InvocationExpression) identifyingNode)
.getPrimary();
}
if (identifyingNode instanceof Tree.QualifiedMemberOrTypeExpression) {
Tree.QualifiedMemberOrTypeExpression qmte =
(Tree.QualifiedMemberOrTypeExpression) identifyingNode;
Declaration declaration = qmte.getDeclaration();
if (declaration!=null) {
addNameProposals(names, false, declaration.getName());
//TODO: propose a compound name like personName for person.name
}
}
if (identifyingNode instanceof Tree.FunctionType) {
Tree.StaticType type = ((Tree.FunctionType) identifyingNode).getReturnType();
if (type instanceof Tree.SimpleType) {
String name = ((Tree.SimpleType) type).getDeclarationModel().getName();
addNameProposals(names, false, name);
}
}
if (identifyingNode instanceof Tree.BaseMemberOrTypeExpression) {
BaseMemberOrTypeExpression bmte =
(Tree.BaseMemberOrTypeExpression) identifyingNode;
Declaration declaration = bmte.getDeclaration();
if (unplural) {
String name = declaration.getName();
if (name.endsWith("s")) {
addNameProposals(names, false, name.substring(0, name.length()-1));
}
}
}
if (identifyingNode instanceof Tree.SumOp) {
names.add("sum");
}
else if (identifyingNode instanceof Tree.DifferenceOp) {
names.add("difference");
}
else if (identifyingNode instanceof Tree.ProductOp) {
names.add("product");
}
else if (identifyingNode instanceof Tree.QuotientOp) {
names.add("ratio");
}
else if (identifyingNode instanceof Tree.RemainderOp) {
names.add("remainder");
}
else if (identifyingNode instanceof Tree.UnionOp) {
names.add("union");
}
else if (identifyingNode instanceof Tree.IntersectionOp) {
names.add("intersection");
}
else if (identifyingNode instanceof Tree.ComplementOp) {
names.add("complement");
}
else if (identifyingNode instanceof Tree.RangeOp) {
names.add("range");
}
else if (identifyingNode instanceof Tree.EntryOp) {
names.add("entry");
}
if (identifyingNode instanceof Tree.Term) {
ProducedType type = ((Tree.Term) node).getTypeModel();
if (!Util.isTypeUnknown(type)) {
if (!unplural) {
TypeDeclaration d = type.getDeclaration();
if (d instanceof ClassOrInterface ||
d instanceof TypeParameter) {
addNameProposals(names, false, d.getName());
}
}
if (node.getUnit().isIterableType(type)) {
ProducedType iteratedType =
node.getUnit().getIteratedType(type);
TypeDeclaration itd =
iteratedType.getDeclaration();
if (itd instanceof ClassOrInterface ||
itd instanceof TypeParameter) {
addNameProposals(names, true&&!unplural,
itd.getName());
}
}
}
}
if (names.isEmpty()) {
names.add("it");
}
return names.toArray(NO_STRINGS);
}
public static void addNameProposals(Set<String> names,
boolean plural, String tn) {
String name = Character.toLowerCase(tn.charAt(0)) + tn.substring(1);
Matcher matcher = IDPATTERN.matcher(name);
while (matcher.find()) {
int loc = matcher.start(2);
String initial = name.substring(matcher.start(1), loc);
if (Character.isLowerCase(name.charAt(0))) {
initial = initial.toLowerCase();
}
String subname = initial + name.substring(loc);
if (plural) subname += "s";
if (Escaping.KEYWORDS.contains(subname)) {
names.add("\\i" + subname);
}
else {
names.add(subname);
}
}
}
public static Tree.SpecifierOrInitializerExpression getDefaultArgSpecifier(
Tree.Parameter p) {
if (p instanceof Tree.ValueParameterDeclaration) {
Tree.AttributeDeclaration pd = (Tree.AttributeDeclaration)
((Tree.ValueParameterDeclaration) p).getTypedDeclaration();
return pd.getSpecifierOrInitializerExpression();
}
else if (p instanceof Tree.FunctionalParameterDeclaration) {
Tree.MethodDeclaration pd = (Tree.MethodDeclaration)
((Tree.FunctionalParameterDeclaration) p).getTypedDeclaration();
return pd.getSpecifierExpression();
}
else if (p instanceof Tree.InitializerParameter) {
return ((Tree.InitializerParameter) p).getSpecifierExpression();
}
else {
return null;
}
}
public static CommonToken getTokenStrictlyContainingOffset(int offset,
List<CommonToken> tokens) {
if (tokens!=null) {
if (tokens.size()>1) {
if (tokens.get(tokens.size()-1).getStartIndex()==offset) { //at very end of file
//check to see if last token is an
//unterminated string or comment
//Note: ANTLR sometimes sends me 2 EOFs,
// so do this:
CommonToken token = null;
for (int i=1;
tokens.size()>=i &&
(token==null || token.getType()==EOF);
i++) {
token = tokens.get(tokens.size()-i);
}
int type = token==null ? -1 : token.getType();
if ((type==STRING_LITERAL ||
type==STRING_END ||
type==ASTRING_LITERAL) &&
(!token.getText().endsWith("\"") ||
token.getText().length()==1) ||
(type==VERBATIM_STRING || type==AVERBATIM_STRING) &&
(!token.getText().endsWith("\"\"\"")||
token.getText().length()==3) ||
(type==MULTI_COMMENT) &&
(!token.getText().endsWith("*/")||
token.getText().length()==2) ||
type==LINE_COMMENT) {
return token;
}
}
else {
int tokenIndex = getTokenIndexAtCharacter(tokens, offset);
if (tokenIndex>=0) {
CommonToken token = tokens.get(tokenIndex);
if (token.getStartIndex()<offset) {
return token;
}
}
}
}
}
return null;
}
public static void appendParameters(StringBuilder result,
Tree.FunctionArgument fa, Unit unit, List<CommonToken> tokens) {
for (Tree.ParameterList pl: fa.getParameterLists()) {
result.append('(');
boolean first=true;
for (Tree.Parameter p: pl.getParameters()) {
if (first) {
first=false;
}
else {
result.append(", ");
}
if (p instanceof Tree.InitializerParameter) {
ProducedType type =
p.getParameterModel().getType();
if (!isTypeUnknown(type)) {
result.append(type.getProducedTypeName(unit))
.append(" ");
}
}
result.append(toString(p, tokens));
}
result.append(')');
}
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_util_Nodes.java
|
130 |
{
@Override
public boolean isValid( TransactionInfo txInfo )
{
return true;
}
};
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_RecoveryVerifier.java
|
3,723 |
private final class EntryProcessorExecutor implements Runnable {
private final Integer second;
private EntryProcessorExecutor(Integer second) {
this.second = second;
}
@Override
public void run() {
scheduledTaskMap.remove(second);
final Map<Object, ScheduledEntry<K, V>> entries = scheduledEntries.remove(second);
if (entries == null || entries.isEmpty()) {
return;
}
Set<ScheduledEntry<K, V>> values = new HashSet<ScheduledEntry<K, V>>(entries.size());
for (Map.Entry<Object, ScheduledEntry<K, V>> entry : entries.entrySet()) {
Integer removed = secondsOfKeys.remove(entry.getKey());
if (removed != null) {
values.add(entry.getValue());
}
}
//sort entries asc by schedule times and send to processor.
entryProcessor.process(SecondsBasedEntryTaskScheduler.this, sortForEntryProcessing(values));
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_util_scheduler_SecondsBasedEntryTaskScheduler.java
|
34 |
@Service("blRequestFieldService")
public class RequestFieldServiceImpl extends AbstractRuleBuilderFieldService {
@Override
public void init() {
fields.add(new FieldData.Builder()
.label("rule_requestFullUrl")
.name("fullUrlWithQueryString")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_requestUri")
.name("requestURI")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_requestIsSecure")
.name("secure")
.operators("blcOperators_Boolean")
.options("[]")
.type(SupportedFieldType.BOOLEAN)
.build());
}
@Override
public String getName() {
return RuleIdentifier.REQUEST;
}
@Override
public String getDtoClassName() {
return "org.broadleafcommerce.common.RequestDTOImpl";
}
}
| 0true
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_RequestFieldServiceImpl.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
|
558 |
typeIntersection = Collections2.filter(indexService.mapperService().types(), new Predicate<String>() {
@Override
public boolean apply(String type) {
return Regex.simpleMatch(types, type);
}
});
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_TransportGetFieldMappingsAction.java
|
498 |
private static class MapRewriter implements FieldRewriter<Map<String, Object>> {
@Override
public Map<String, Object> rewriteValue(Map<String, Object> mapValue) {
boolean wasRewritten = false;
Map<String, Object> result = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : mapValue.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
FieldRewriter<Object> fieldRewriter = RewritersFactory.INSTANCE.findRewriter(null, null, value);
Object newValue = fieldRewriter.rewriteValue(value);
if (newValue != null) {
result.put(key, newValue);
wasRewritten = true;
} else
result.put(key, value);
}
if (wasRewritten)
return result;
return null;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseImport.java
|
5,425 |
public static class WithScript extends Bytes {
private final BytesValues bytesValues;
public WithScript(FieldDataSource delegate, SearchScript script) {
this.bytesValues = new BytesValues(delegate, script);
}
@Override
public MetaData metaData() {
return MetaData.UNKNOWN;
}
@Override
public BytesValues bytesValues() {
return bytesValues;
}
static class BytesValues extends org.elasticsearch.index.fielddata.BytesValues {
private final FieldDataSource source;
private final SearchScript script;
private final BytesRef scratch;
public BytesValues(FieldDataSource source, SearchScript script) {
super(true);
this.source = source;
this.script = script;
scratch = new BytesRef();
}
@Override
public int setDocument(int docId) {
return source.bytesValues().setDocument(docId);
}
@Override
public BytesRef nextValue() {
BytesRef value = source.bytesValues().nextValue();
script.setNextVar("_value", value.utf8ToString());
scratch.copyChars(script.run().toString());
return scratch;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_support_FieldDataSource.java
|
5,196 |
public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalGeoHashGrid readResult(StreamInput in) throws IOException {
InternalGeoHashGrid buckets = new InternalGeoHashGrid();
buckets.readFrom(in);
return buckets;
}
};
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_bucket_geogrid_InternalGeoHashGrid.java
|
634 |
public class IndicesStatusRequest extends BroadcastOperationRequest<IndicesStatusRequest> {
private boolean recovery = false;
private boolean snapshot = false;
public IndicesStatusRequest() {
this(Strings.EMPTY_ARRAY);
}
public IndicesStatusRequest(String... indices) {
super(indices);
}
/**
* Should the status include recovery information. Defaults to <tt>false</tt>.
*/
public IndicesStatusRequest recovery(boolean recovery) {
this.recovery = recovery;
return this;
}
public boolean recovery() {
return this.recovery;
}
/**
* Should the status include recovery information. Defaults to <tt>false</tt>.
*/
public IndicesStatusRequest snapshot(boolean snapshot) {
this.snapshot = snapshot;
return this;
}
public boolean snapshot() {
return this.snapshot;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(recovery);
out.writeBoolean(snapshot);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
recovery = in.readBoolean();
snapshot = in.readBoolean();
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_status_IndicesStatusRequest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.